forked from cjayb/thinkpython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Lumpy.py
1576 lines (1223 loc) · 47.2 KB
/
Lumpy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
"""This module is part of Swampy, a suite of programs available from
allendowney.com/swampy.
Copyright 2010 Allen B. Downey
Distributed under the GNU General Public License at gnu.org/licenses/gpl.html.
UML diagrams for Python
Lumpy generates UML diagrams (currently object and class diagrams)
from a running Python program. It is similar to a graphical debugger
in the sense that it generates a visualization of the state of a
running program, but it is different from a debugger in the sense that
it tries to generate high-level visualizations that are compliant (at
least in spirit) with standard UML.
There are three target audiences for this module: teachers, students
and software engineers. Teachers can use Lumpy to generate figures
that demonstrate a model of the execution of a Python
program. Students can use Lumpy to explore the behavior of the Python
interpreter. Software engineers can use Lumpy to extract the structure
of existing programs by diagramming the relationships among the
classes, including classes defined in libraries and the Python
interpreter.
"""
import inspect
import sys
import Tkinter
from Tkinter import N, S, E, W, SW, HORIZONTAL, ALL, LAST
from Gui import Gui, GuiCanvas, Point, BBox, underride, ScaleTransform
# get the version of Python
VERSION = sys.version.split()[0].split('.')
MAJOR = int(VERSION[0])
if MAJOR < 2:
print 'You must have at least Python version 2.0 to run Lumpy.'
sys.exit()
MINOR = int(VERSION[1])
if MAJOR == 2 and MINOR < 4:
# TODO: provide a substitute implementation of set
pass
if MAJOR == 2:
TKINTER_MODULE = Tkinter
else:
TKINTER_MODULE = tkinter
# most text uses the font specified below; some labels
# in object diagrams use smallfont. Lumpy uses the size
# of the fonts to define a length unit, so
# changing the font sizes will cause the whole diagram to
# scale up or down.
FONT = ("Helvetica", 10)
SMALLFONT = ("Helvetica", 9)
class DiagCanvas(GuiCanvas):
"""Canvas for displaying Diagrams."""
def box(self, box, padx=0.4, pady=0.2, **options):
"""Draws a rectangle with the given bounding box.
Args:
box: BBox object or list of coordinate pairs.
padx, pady: padding
"""
# underride sets default values only if the called hasn't
underride(options, outline='black')
box.left -= padx
box.top -= pady
box.right += padx
box.bottom += pady
item = self.rectangle(box, **options)
return item
def arrow(self, start, end, **options):
"""Draws an arrow.
Args:
start: Point or coordinate pair.
end: Point or coordinate pair.
"""
return self.line([start, end], **options)
def offset_text(self, pos, text, dx=0, dy=0, **options):
"""Draws the given text at the given position.
Args:
pos: Point or coordinate pair
text: string
dx, dy: offset
"""
underride(options, fill='black', font=FONT, anchor=W)
x, y = pos
x += dx
y += dy
return self.text([x, y], text, **options)
def dot(self, pos, r=0.2, **options):
"""Draws a dot at the given position with radius r."""
underride(options, fill='white', outline='orange')
return self.circle(pos, r, **options)
def measure(self, t, **options):
"""Finds the bounding box of the list of words.
Draws the text, measures them, and then deletes them.
"""
pos = Point([0, 0])
tags = 'temp'
for s in t:
self.offset_text(pos, s, tags=tags, **options)
pos.y += 1
bbox = self.bbox(tags)
self.delete(tags)
return bbox
class MakeTag(object):
"""Encapsulates a unique Tag generator."""
nextid = 0
@classmethod
def make_tag(cls, prefix='Tag'):
"""Return a tuple with a single element: a tag string.
Uses the given prefix and a unique id as a suffix.
prefix: string
returns: string
"""
cls.nextid += 1
tag = '%s%d' % (prefix, cls.nextid)
return tag,
class Thing(object):
"""Parent class for objects that have a graphical representation.
Each Thing object corresponds to an item
or set of items in a diagram. A Thing can only be drawn in
one Diagram at a time.
"""
things_created = 0
things_drawn = 0
def __new__(cls, *args, **kwds):
"""Override __new__ so we can count the number of Things."""
Thing.things_created += 1
return object.__new__(cls)
def get_bbox(self):
"""Returns the bounding box of this object if it is drawn."""
return self.canvas.bbox(self.tags)
def set_offset(self, pos):
"""Sets the offset attribute.
The offset attribute keeps track of the offset between
the bounding box of the Thing and its nominal position, so
that if the Thing is moved later, we can compute its new
nominal position.
"""
self.offset = self.get_bbox().offset(pos)
def pos(self):
"""Computes the nominal position of a Thing.
Gets the current bounding box and adds the offset.
"""
return self.get_bbox().pos(self.offset)
def isdrawn(self):
"""Return True if the object has been drawn."""
return hasattr(self, 'drawn')
def draw(self, diag, pos, flip, tags=tuple()):
"""Draws this Thing at the given position.
Most child classes use this method as a template and
override drawme() to provide type-specific behavior.
draw() and drawme() are not allowed to modify pos.
Args:
diag: which diagram to draw on
pos: Point or coordinate pair
flip: int (1 means draw left to right; flip=-1 means right to left)
tags: additional tags to apply
Returns:
list of Thing objects
"""
if self.isdrawn():
return []
self.drawn = True
self.diag = diag
self.canvas = diag.canvas
# keep track of how many things have been drawn.
# Simple values can get drawn more than once, so the
# total number of things drawn can be greater than
# the number of things.
Thing.things_drawn += 1
if Thing.things_drawn % 100 == 0:
print Thing.things_drawn
# uncomment this to see things as they are drawn
#self.diag.lumpy.update()
# each thing has a list of tags: its own tag plus
# the tag of each thing it belongs to. This convention
# makes it possible to move entire structures with one
# move command.
self.tags = MakeTag.make_tag(self.__class__.__name__)
tags += self.tags
# invoke drawme in the child class
drawn = self.drawme(diag, pos, flip, tags)
if drawn == None:
drawn = [self]
self.set_offset(pos)
return drawn
def drawme(self, diag, pos, flip, tags):
raise ValueError('Unimplemented method.')
def bind(self, tags=None):
"""Create bindings for the items with the given tags."""
tags = tags or self.tags
items = self.canvas.find_withtag(tags)
for item in items:
self.canvas.tag_bind(item, "<Button-1>", self.down)
def down(self, event):
"""Save state for the beginning of a drag and drop.
Callback invoked when the user clicks on an item.
"""
self.dragx = event.x
self.dragy = event.y
self.canvas.bind("<B1-Motion>", self.motion)
self.canvas.bind("<ButtonRelease-1>", self.up)
return True
def motion(self, event):
"""Move the Thing during a drag.
Callback invoked when the user drags an item"""
dx = event.x - self.dragx
dy = event.y - self.dragy
self.dragx = event.x
self.dragy = event.y
self.canvas.move(self.tags, dx, dy)
self.diag.update_arrows()
def up(self, event):
"""Release the object being dragged.
Callback invoked when the user releases the button.
"""
event.widget.unbind ("<B1-Motion>")
event.widget.unbind ("<ButtonRelease-1>")
self.diag.update_arrows()
class Dot(Thing):
"""Represents a dot in a diagram."""
def drawme(self, diag, pos, flip, tags=tuple()):
"""Draws the Thing."""
self.canvas.dot(pos, tags=tags)
class Simple(Thing):
"""Represents a simple value like a number or a string."""
def __init__(self, lumpy, val):
lumpy.register(self, val)
self.val = val
def drawme(self, diag, pos, flip, tags=tuple()):
"""Draws the Thing."""
p = pos.copy()
p.x += 0.1 * flip
anchor = {1:W, -1:E}
# put quotes around strings; for everything else, use
# the standard str representation
val = self.val
maxlen = 30
if isinstance(val, str):
val = val.strip('\n')
label = "'%s'" % val[0:maxlen]
else:
label = str(val)
self.canvas.offset_text(p, label, tags=tags, anchor=anchor[flip])
self.bind()
class Index(Simple):
"""Represents an index in a Sequence.
An Index object does not register with lumpy, so that even
in pedantic mode, it is always drawn, and it is never the
target of a reference (since it is not really a value at
run-time).
"""
def __init__(self, _, val):
self.val = val
def drawme(self, diag, pos, flip, tags=tuple()):
"""Draws the Thing."""
p = pos.copy()
p.x += 0.1 * flip
anchor = {1:W, -1:E}
label = str(self.val)
self.canvas.offset_text(p, label, tags=tags, anchor=anchor[flip])
self.bind()
class Mapping(Thing):
"""Represents a mapping type (usually a dictionary).
Sequence and Instance inherit from Mapping.
"""
def __init__(self, lumpy, val):
lumpy.register(self, val)
self.bindings = make_kvps(lumpy, val.items())
self.boxoptions = dict(outline='purple')
self.label = type(val).__name__
def get_bbox(self):
"""Gets the bounding box for this Mapping.
The bbox of a Mapping is the bbox of its box item.
This is different from other Things.
"""
return self.canvas.bbox(self.boxitem)
def drawme(self, diag, pos, flip, tags=tuple()):
"""Draws the Thing."""
p = pos.copy()
# intag is attached to items that should be considered
# inside the box
intag = self.tags[0] + 'inside'
# draw the bindings
for binding in self.bindings:
# check whether the key was already drawn
drawn = binding.key.isdrawn()
# draw the binding
binding.draw(diag, p, flip, tags=tags)
# apply intag to the dots
self.canvas.addtag_withtag(intag, binding.dot.tags)
if drawn:
# if the key was already drawn, then the binding
# contains two dots, so we should add intag to the
# second one.
if binding.dot2:
self.canvas.addtag_withtag(intag, binding.dot2.tags)
else:
# if the key wasn't drawn yet, it should be
# considered inside this mapping
self.canvas.addtag_withtag(intag, binding.key.tags)
# move down to the position for the next binding
p.y = binding.get_bbox().bottom + 1.8
if len(self.bindings):
# if there are any bindings, draw a box around them
bbox = self.canvas.bbox(intag)
item = self.canvas.box(bbox, tags=tags, **self.boxoptions)
else:
# otherwise just draw a box
bbox = BBox([p.copy(), p.copy()])
item = self.canvas.box(bbox, padx=0.4, pady=0.4, tags=tags,
**self.boxoptions)
# make the box clickable
self.bind(item)
self.boxitem = item
# put the label above the box
if self.label:
p = bbox.upperleft()
item = self.canvas.offset_text(p, self.label, anchor=SW,
font=SMALLFONT, tags=tags)
# make the label clickable
self.bind(item)
# if the whole mapping is not in the right position, shift it.
if flip == 1:
dx = pos.x - self.get_bbox().left
else:
dx = pos.x - self.get_bbox().right
self.canvas.move(self.tags, dx, 0, transform=True)
def scan_bindings(self, cls):
"""Looks for references to other types.
Invokes add_hasa on cls.
Args:
cls: is the Class of the object that contains this mapping.
"""
for binding in self.bindings:
for val in binding.vals:
self.scan_val(cls, val)
def scan_val(self, cls, val):
"""Looks for references to other types.
If we find a reference to an object type, make a note
of the HAS-A relationship. If we find a reference to a
container type, scan it for references.
Args:
cls: is the Class of the object that contains this mapping.
"""
if isinstance(val, Instance) and val.cls is not None:
cls.add_hasa(val.cls)
elif isinstance(val, Sequence):
val.scan_bindings(cls)
elif isinstance(val, Mapping):
val.scan_bindings(cls)
class Sequence(Mapping):
"""Represents a sequence type (mostly lists and tuples)."""
def __init__(self, lumpy, val):
lumpy.register(self, val)
self.bindings = make_bindings(lumpy, enumerate(val))
self.label = type(val).__name__
# color code lists, tuples, and other sequences
if isinstance(val, list):
self.boxoptions = dict(outline='green1')
elif isinstance(val, tuple):
self.boxoptions = dict(outline='green4')
else:
self.boxoptions = dict(outline='green2')
class Instance(Mapping):
"""Represents an object (usually).
Anything with a __dict__ is treated as an Instance.
"""
def __init__(self, lumpy, val):
lumpy.register(self, val)
# if this object has a class, make a Thing to
# represent the class, too
if hasclass(val):
class_or_type = val.__class__
self.cls = make_thing(lumpy, class_or_type)
else:
class_or_type = type(val)
self.cls = None
self.label = class_or_type.__name__
if class_or_type in lumpy.instance_vars:
# if the class is in the list, only display only the
# unrestricted instance variables
ks = lumpy.instance_vars[class_or_type]
it = [(k, getattr(val, k)) for k in ks]
seq = make_bindings(lumpy, it)
else:
# otherwise, display all of the instance variables
if hasdict(val):
it = val.__dict__.items()
elif hasslots(val):
it = [(k, getattr(val, k)) for k in val.__slots__]
else:
t = [k for k, v in type(val).__dict__.iteritems()
if str(v).find('attribute') == 1]
it = [(k, getattr(val, k)) for k in t]
seq = make_bindings(lumpy, it)
# and if the object extends list, tuple or dict,
# append the items
if isinstance(val, (list, tuple)):
seq += make_bindings(lumpy, enumerate(val))
if isinstance(val, dict):
seq += make_bindings(lumpy, val.items())
# if this instance has a name attribute, show it
attr = '__name__'
if hasname(val):
seq += make_bindings(lumpy, [[attr, val.__name__]])
self.bindings = seq
self.boxoptions = dict(outline='red')
def scan_bindings(self, cls):
"""Look for references to other types.
Invokes add_ivar and add_hasa on cls.
Records the names of the instance variables.
Args:
cls: is the Class of the object that contains this mapping.
"""
for binding in self.bindings:
cls.add_ivar(binding.key.val)
for val in binding.vals:
self.scan_val(cls, val)
class Frame(Mapping):
"""Represents a frame."""
def __init__(self, lumpy, frame):
it = frame.locals.items()
self.bindings = make_bindings(lumpy, it)
self.label = frame.func
self.boxoptions = dict(outline='blue')
class Class(Instance):
"""Represents a Class.
Inherits from Instance, which controls how a Class appears in an
object diagram, and contains a ClassDiagramClass, which
controls how the Class appears in a class diagram.
"""
def __init__(self, lumpy, classobj):
Instance.__init__(self, lumpy, classobj)
self.cdc = ClassDiagramClass(lumpy, classobj)
self.cdc.cls = self
lumpy.classes.append(self)
self.classobj = classobj
self.module = classobj.__module__
self.bases = classobj.__bases__
# childs is the list of classes that inherit directly
# from this one; parents is the list of base classes
# for this one
self.childs = []
# refers is a dictionary that records, for each other
# class, the total number of references we have found from
# this class to that
self.refers = {}
# make a list of Things to represent the
# parent classes
if lumpy.is_opaque(classobj):
self.parents = []
else:
self.parents = [make_thing(lumpy, base) for base in self.bases]
# add self to the parents' lists of children
for parent in self.parents:
parent.add_child(self)
# height and depth are used to lay out the tree
self.height = None
self.depth = None
def add_child(self, child):
"""Adds a child.
When a subclass is created, it notifies its parent
classes, who update their list of children."""
self.childs.append(child)
def add_hasa(self, child, n=1):
"""Increment the reference count from this class to a child."""
self.refers[child] = self.refers.get(child, 0) + n
def add_ivar(self, var):
"""Adds to the set of instance variables for this class."""
self.cdc.ivars.add(var)
def set_height(self):
"""Computes the maximum height between this class and a leaf class.
(A leaf class has no children)
Sets the height attribute.
"""
if self.height != None:
return
if not self.childs:
self.height = 0
return
for child in self.childs:
child.set_height()
heights = [child.height for child in self.childs]
self.height = max(heights) + 1
def set_depth(self):
"""Compute the maximum depth between this class and a root class.
(A root class has no parent)
Sets the depth attribute.
"""
if self.depth != None:
return
if not self.parents:
self.depth = 0
return
for parent in self.parents:
parent.set_depth()
depths = [parent.depth for parent in self.parents]
self.depth = max(depths) + 1
class ClassDiagramClass(Thing):
"""Represents a class as it appears in a class diagram."""
def __init__(self, lumpy, classobj):
self.lumpy = lumpy
self.classobj = classobj
# self.methods is the list of methods defined in this class.
# self.cvars is the list of class variables.
# self.ivars is a set of instance variables.
self.methods = []
self.cvars = []
self.ivars = set()
# if this is a restricted (or opaque) class, then
# vars contains the list of instance variables that
# will be shown; otherwise it is None.
try:
variables = lumpy.instance_vars[classobj]
except KeyError:
variables = None
# we can get methods and class variables now, but we
# have to wait until the Lumpy representation of the stack
# is complete before we can go looking for instance vars.
for key, val in classobj.__dict__.items():
if variables is not None and key not in variables:
continue
if iscallable(val):
self.methods.append(val)
else:
self.cvars.append(key)
key = lambda x: x.__class__.__name__ + "." + x.__name__
self.methods.sort(key=key)
self.cvars.sort()
self.boxoptions = dict(outline='blue')
self.lineoptions = dict(fill='blue')
def drawme(self, diag, pos, flip, tags=tuple()):
"""Draws the Thing."""
p = pos.copy()
# draw the name of the class
name = self.classobj.__name__
item = self.canvas.offset_text(p, name, tags=tags)
p.y += 0.8
# in order to draw lines between segments, we have
# to store the locations and draw the lines, later,
# when we know the location of the box
lines = []
# draw a line between the name and the methods
if self.methods:
lines.append(p.y)
p.y += 1
# draw the methods
for f in self.methods:
item = self.canvas.offset_text(p, f.__name__, tags=tags)
p.y += 1
# draw the class variables
cvars = [var for var in self.cvars if not var.startswith('__')]
if cvars:
lines.append(p.y)
p.y += 1
for varname in cvars:
item = self.canvas.offset_text(p, varname, tags=tags)
p.y += 1
# if this is a restricted (or opaque) class, remove
# unwanted instance vars from self.ivars
try:
variables = self.lumpy.instance_vars[self.classobj]
self.ivars.intersection_update(variables)
except KeyError:
pass
# draw the instance variables
ivars = list(self.ivars)
ivars.sort()
if ivars:
lines.append(p.y)
p.y += 1
for varname in ivars:
item = self.canvas.offset_text(p, varname, tags=tags)
p.y += 1
# draw the box
bbox = self.get_bbox()
item = self.canvas.box(bbox, tags=tags, **self.boxoptions)
self.boxitem = item
# draw the lines
for y in lines:
coords = [[bbox.left, y], [bbox.right, y]]
item = self.canvas.line(coords, tags=tags, **self.lineoptions)
# only the things we have drawn so far should be bound
self.bind()
# make a list of all classes drawn
alldrawn = [self]
# draw the descendents of this class
childs = self.cls.childs
if childs:
q = pos.copy()
q.x = bbox.right + 8
drawn = self.diag.draw_classes(childs, q, tags)
alldrawn.extend(drawn)
self.head = self.arrow_head(diag, bbox, tags)
# connect this class to its children
for child in childs:
a = ParentArrow(self.lumpy, self, child.cdc)
self.diag.add_arrow(a)
# if the class is not in the right position, shift it.
dx = pos.x - self.get_bbox().left
self.canvas.move(self.tags, dx, 0)
return alldrawn
def arrow_head(self, diag, bbox, tags, size=0.5):
"""Draws the hollow arrow head.
Connects this class to classes that inherit from it.
"""
x, y = bbox.midright()
x += 0.1
coords = [[x, y], [x+size, y+size], [x+size, y-size], [x, y]]
item = self.canvas.line(coords, tags=tags, **self.lineoptions)
return item
class Binding(Thing):
"""Represents the binding between a key or variable and a value."""
def __init__(self, lumpy, key, val):
lumpy.register(self, (key, val))
self.key = key
self.vals = [val]
def rebind(self, val):
"""Add to the list of values.
I don't remember what this is for and it is not in current use.
"""
self.vals.append(val)
def draw_key(self, diag, pos, flip, tags):
"""Draws a reference to a previously-drawn key.
(Rather than drawing the key inside the mapping.)
"""
pos.x -= 0.5 * flip
self.dot2 = Dot()
self.dot2.draw(diag, pos, -flip, tags=tags)
# only the things we have drawn so far should
# be handles for this binding
self.bind()
if not self.key.isdrawn():
pos.x -= 2.0 * flip
self.key.draw(diag, pos, -flip, tags=tags)
a = ReferenceArrow(self.lumpy, self.dot2, self.key, fill='orange')
diag.add_arrow(a)
def drawme(self, diag, pos, flip, tags=tuple()):
"""Draws the Thing."""
self.dot = Dot()
self.dot.draw(diag, pos, flip, tags=tags)
p = pos.copy()
p.x -= 0.5 * flip
# if the key is a Simple, try to draw it inside the mapping;
# otherwise, draw a reference to it
if isinstance(self.key, Simple):
drawn = self.key.draw(diag, p, -flip, tags=tags)
# if a Simple thing doesn't get drawn, we must be in
# pedantic mode.
if drawn:
self.bind()
self.dot2 = None
else:
self.draw_key(diag, p, flip, tags)
else:
self.draw_key(diag, p, flip, tags)
p = pos.copy()
p.x += 2.0 * flip
for val in self.vals:
val.draw(diag, p, flip, tags=tags)
a = ReferenceArrow(self.lumpy, self.dot, val, fill='orange')
diag.add_arrow(a)
p.y += 1
class Arrow(Thing):
"""Parent class for arrows."""
def update(self):
"""Redraws this arrow after something moves."""
if not hasdiag(self):
return
self.diag.canvas.delete(self.item)
self.draw(self.diag)
class ReferenceArrow(Arrow):
"""Represents a reference in an object diagram."""
def __init__(self, lumpy, key, val, **options):
self.lumpy = lumpy
self.key = key
self.val = val
self.options = options
def draw(self, diag):
"""Draw the Thing.
Overrides draw() rather than drawme() because arrows can't
be dragged and dropped.
"""
self.diag = diag
canvas = diag.canvas
self.item = canvas.arrow(self.key.pos(),
self.val.pos(),
**self.options)
self.item.lower()
def update(self):
"""Redraws this arrow after something moves."""
if not hasdiag(self):
return
self.item.coords([self.key.pos(), self.val.pos()])
class ParentArrow(Arrow):
"""Represents an inheritance arrow.
Shows an is-a relationship between classes in a class diagram.
"""
def __init__(self, lumpy, parent, child, **options):
self.lumpy = lumpy
self.parent = parent
self.child = child
underride(options, fill='blue')
self.options = options
def draw(self, diag):
"""Draw the Thing.
Overrides draw() rather than drawme() because arrows can't
be dragged and dropped.
"""
self.diag = diag
parent, child = self.parent, self.child
# the line connects the midleft point of the child
# to the arrowhead of the parent; it always contains
# two horizontal segments and one vertical.
canvas = diag.canvas
bbox = canvas.bbox(parent.head)
p = bbox.midright()
q = canvas.bbox(child.boxitem).midleft()
midx = (p.x + q.x) / 2.0
m1 = [midx, p.y]
m2 = [midx, q.y]
coords = [p, m1, m2, q]
self.item = canvas.line(coords, **self.options)
canvas.lower(self.item)
class ContainsArrow(Arrow):
"""Represents a contains arrow.
Shows a has-a relationship between classes in a class diagram.
"""
def __init__(self, lumpy, parent, child, **options):
self.lumpy = lumpy
self.parent = parent
self.child = child
underride(options, fill='orange', arrow=LAST)
self.options = options
def draw(self, diag):
"""Draw the Thing.
Overrides draw() rather than drawme() because arrows can't
be dragged and dropped.
"""
self.diag = diag
parent, child = self.parent, self.child
if not child.isdrawn():
self.item = None
return
canvas = diag.canvas
p = canvas.bbox(parent.boxitem).midleft()
q = canvas.bbox(child.boxitem).midright()
coords = [p, q]
self.item = canvas.line(coords, **self.options)
canvas.lower(self.item)
class Stack(Thing):
"""Represents the call stack."""
def __init__(self, lumpy, snapshot):
self.lumpy = lumpy
self.frames = [Frame(lumpy, frame) for frame in snapshot.frames]
def drawme(self, diag, pos, flip, tags=tuple()):
"""Draws the Thing."""
p = pos.copy()
for frame in self.frames:
frame.draw(diag, p, flip, tags=tags)
bbox = self.get_bbox()
#p.y = bbox.bottom + 3
p.x = bbox.right + 3
def make_bindings(lumpy, iterator):
"""Make bindings for each key-value pair in iterator.
The keys are made into Index objects.
"""
seq = [Binding(lumpy, Index(lumpy, k), make_thing(lumpy, v))
for k, v in iterator]
return seq
def make_kvps(lumpy, iterator):
"""Make bindings for each key-value pair in iterator.
The keys are made into Thing objects.
"""
seq = [Binding(lumpy, make_thing(lumpy, k), make_thing(lumpy, v))
for k, v in iterator]
return seq
def make_thing(lumpy, val):
"""Make a Thing to represents this value.