-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcs1graphics.py
More file actions
5436 lines (4451 loc) ยท 215 KB
/
Copy pathcs1graphics.py
File metadata and controls
5436 lines (4451 loc) ยท 215 KB
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
"""cs1graphics.py
Copyright 2008-2014, David Letscher, Michael H. Goldwasser, Christopher Porter
Go to www.cs1graphics.org for more information.
This is Version 1.2 multithreaded release (23 July 2014)
Modified by Jungkook Park for KAIST CS101. (24 Nov 2015)
- Use Pillow instead of PIL.
- Allow base64 image extension.
- FIx ImportError for _tempfile.
- Add function saveToIO.
- Make periodic function call.
"""
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# If you are interested in doing further development of cs1graphics,
# please contact the authors to receive the Developer's Guide.
# Configuration Options:
# ----------------------
# By default, cs1graphics uses true multi-threading. However, the
# default Python/Tk implementation shipped on many versions of Apple's
# OSX operating system does not allow for such support. The following
# flag should be changed to False to switch to a slightly more limited
# model of threading. This behavior can also be triggered
# programmatically by calling configureNativeThreading(False) prior to
# issuing any graphics commands.
_nativeThreading = False
# By default, cs1graphics uses the common "computer science"
# coordinate system, with the origin in the top-left corner of a
# window, and with the y-axis oriented so that positive values are
# below the origin. To get a traditional "mathematics" coordinate
# system, with the origin in the bottom-left and the positive y-axis
# oriented above the origin, the following flag can be changed to
# True. This behavior can also be triggered programmatically by
# calling configureMathMode(True) prior to issuing any graphics
# commands.
_mathMode = False
# cs1graphics allows for a layer to be recursively nested within
# itself, for some cool effects. The rendering of such recursion is
# artificially capped with the following recursive limit. This limit
# may also be changed programmatically with the
# configureSetRecursionLimit function.
_RECURSIVE_LIMIT = 10
# The following dictionary of flags should only be used by developers
# to adjust the level of verbosity when debugging various aspects of
# the system.
_DEBUG = {
'wait': 0,
'mainLoop': 0,
'processEvents': 0,
'Events': 0,
'Tkinter': 0,
'Front': 0,
'Middle': 0,
'RenderedH': 0,
'UpdateManager': 0,
'processCommands': 0,
}
_dashMultiplier = 2 # oddity about whether pattern should be (a,b) or (a,b,a,b)
_elice_use = False
import copy as _copy
import math as _math
import random as _random
import time as _time
import threading as _threading
import atexit as _atexit
import os as _os
import sys as _sys
import traceback as _traceback
from array import array as _array
# change in module names for Python 2 vs 3
try:
import Queue as _Queue
except ImportError:
import queue as _Queue # Python 3
try:
import thread as _thread
except ImportError:
import _thread as _thread # Python 3
try:
import Tkinter as _Tkinter
except ImportError:
try:
import tkinter as _Tkinter # Python 3
except ImportError:
raise ImportError('cs1graphics requires that Tkinter be installed')
try:
from PIL import Image as _Image
from PIL import ImageTk as _ImageTk
_pilAvailable = True
except ImportError:
_pilAvailable = False
import base64 as _base64
try:
from cStringIO import StringIO as _Base64IO
except ImportError:
from io import BytesIO as _Base64IO
import io as _io
import tempfile as _tempfile
# Library
_tkroot = None
_ourRandom = _random.Random()
_ourRandom.seed(1234) # initialize the random seed so that behaviors are reproducible
# support for Python 2.x/3.x.
# We want to use isinstance(foo, basestring) in either case
try:
unicode
except NameError:
basestring = unicode = str
# Global Configuration Controls
def configureNativeThreading(flag=False):
"""Configures cs1graphics to run in native multi-threaded mode when flag is True.
By default, the library uses a multi-threaded model in which case
all rendering is managed by a secondary thread, and EventHandlers
are immediately activated once registered without blocking the
primary thread.
However, on systems that do not support accessing Tkinter from a
secondary thread, the model can be changed to be single-threaded,
with all rendering in the primary thread and EventHandlers
activated only when the end of the main thread is reached, or an
explicit (blocking) call to startEventHandling() is made.
Note: This command must be executed prior to the use of any core
library functionality.
Note: As an alternative, your cs1graphics installation can be
configured with the default mode set using the variable
_nativeThread in the preamble of file cs1graphics.py.
"""
if _graphicsManager._state != 'Initial':
raise GraphicsError('configuration must occur prior to other use of the library')
global _nativeThreading
_nativeThreading = True
def configureMathMode(flag=True):
"""Forces cs1graphics to use standard math coordinate system when flag is True.
By default, cs1graphics uses a standard computer graphics
coordinate system with the origin at the top-left and the positive
y-axis oriented downward.
If this function is invoked, it causes canvases to use a standard
mathematics coordinate system with the origin at bottom-left and
the positive y-axis oriented upward. In math mode, a positive
rotation is conventionally counterclockwise rather than clockwise.
NOTE: This command must be executed prior to the use of any core
library functionality.
Note: As an alternative, your cs1graphics installation can be
configured with the default coordinate system set using the
variable _mathMode in the preamble of file cs1graphics.py.
"""
if _graphicsManager._state != 'Initial':
raise GraphicsError('configuration must occur prior to other use of the library')
global _mathMode
_mathMode = flag
def configureSetRecursionLimit(limit):
"""Changes the limit on recursion for drawable inclusion.
In cases such as when adding a layer to itself, the drawing
process is intentionally capped with some maximum recursive depth
to avoid an infinite recursion. By default, that limit is 10.
This function allows that to be changed.
"""
if _graphicsManager._state != 'Initial':
raise GraphicsError('configuration must occur prior to other use of the library')
if not isinstance(limit, int):
raise TypeError('limit should be an integer')
if limit < 1:
raise ValueError('limit must be positive')
global _RECURSIVE_LIMIT
_RECURSIVE_LIMIT = limit
class GraphicsError(Exception):
def __init__(self, message, recoverable=False):
super(GraphicsError, self).__init__()
self._recoverable = recoverable
# Data structures
# special purpose comparator for chains, since Python3 no longer allows
# for us to use default < for chain tuples that include a class instance.
def _chainCompare(a, b):
return _chainCompareRecurse(a, b, 0)
def _chainCompareRecurse(a, b, k):
"""Compare implicit slices a[k:] and b[k:]"""
if len(a) == k:
return len(b) > k
elif len(b) == k:
return False
elif a[k][0] < b[k][0]:
return True
elif b[k][0] < a[k][0]:
return False
elif a[k][1] == b[k][1]:
return _chainCompareRecurse(a, b, k + 1)
else:
# arbitrary tie-breaker for our model of chains with multiple inheritance
return str(a[k][1]) < str(b[k][1])
class _OrderedMap:
"""Implements an ordered map.
Although we do not formally require the keys to be hashable, the
expectation is that they should not be mutated.
By default, ordering is based on < operator, but the user
can provide a non-standard boolean function for comparing keys.
This implementation is based upon an underlying treap.
"""
def _less(a, b):
"""Generic version of comparison function."""
return a < b
_less = staticmethod(_less)
def __init__(self, less=None):
"""Create an empty map.
less is a boolean function with callingsignature less(keyA, keyB)
that returns True if keyA is strictly less than keyB.
If not sent, the default < operator is used.
"""
self._root = None
self._size = 0
if less is not None:
self._less = less
def __len__(self):
"""Return the size of the map."""
return self._size
def _trace(self, key):
"""Walk path looking for given key.
Return the node that has the key, if any.
Otherwise return the last true node visited.
In case of an empty map, None is returned.
"""
if len(self) > 0:
walk = self._root
while walk is not None and \
(self._less(key, walk.key) or self._less(walk.key, key)):
# no match thus far
trail = walk
if self._less(key, walk.key):
walk = walk.left
else:
walk = walk.right
if walk is not None:
result = walk
else:
result = trail
else:
result = None
return result
def __delitem__(self, key):
"""Remove the entry assoicated with the key.
KeyError results if key does not exist.
"""
temp = self.find(key)
if temp is None:
raise KeyError(repr(key))
self.remove(temp)
def __getitem__(self, key):
"""Return the value associated with the key.
KeyError results if key does not exist.
"""
temp = self.find(key)
if temp is None:
raise KeyError(repr(key))
else:
return temp.value()
def __setitem__(self, key, value):
"""Associate key to value.
If key exists, old value is overwritten with new.
If key does not exist, it is added to the map.
"""
self.insert(key, value) # ignore return value
def find(self, key):
"""Return an iterator to the key's position, if found.
None is returned if key not found.
"""
walk = self._trace(key)
if walk is not None and not \
(self._less(key, walk.key) or self._less(walk.key, key)):
return _OrderedMap.iterator(walk)
else:
return None
def __contains__(self, key):
"""Return True if key in the map."""
return self.find(key) is not None
def first(self):
"""Return iterator to the first element of the map.
None is returned if map is empty.
"""
if len(self) > 0:
return _OrderedMap.iterator(self._root.subtreeMin())
else:
return None
def last(self):
"""Return iterator to the last element of the map.
None is returned if map is empty.
"""
if len(self) > 0:
return _OrderedMap.iterator(self._root.subtreeMax())
else:
return None
def __iter__(self):
"""Return generator for (key,value) pairs."""
walk = self.first()
while walk is not None:
yield (walk.key(), walk.value())
walk = walk.next()
def closestBefore(self, key, strict=True):
"""Return iterator to position at or before the key.
With strict=True (the default), the search looks for an item
that has a key strictly smaller than the given one.
With strict=False, it will return an exact match if possible, and
otherwise the closest before.
Will return None in the case that no earlier key is found.
"""
walk = self._trace(key)
if walk is None:
return None
if self._less(walk.key, key):
# this is strictly smaller than key, so it must be it
return _OrderedMap.iterator(walk)
elif not (strict or self._less(key, walk.key)):
# use the exact match
return _OrderedMap.iterator(walk)
elif walk.left is not None:
# found an exact match, and it has lesser children
return _OrderedMap.iterator(walk.left.subtreeMax())
else:
# start walking upward
while walk is not None and not self._less(walk.key, key):
walk = walk.parent
if walk is not None:
return _OrderedMap.iterator(walk)
else:
return None
def closestAfter(self, key, strict=True):
"""Return iterator to position at or after the key.
With strict=True (the default), the search looks for an item
that has a key strictly larger than the given one.
With strict=False, it will return an exact match if possible, and
otherwise the closest after.
Will return None in the case that no later key is found.
"""
walk = self._trace(key)
if self._less(key, walk.key):
# this is strictly larger than key, so it must be it
return _OrderedMap.iterator(walk)
elif not (strict or self._less(walk.key, key)):
# use the exact match
return _OrderedMap.iterator(walk)
elif walk.right is not None:
# found an exact match, and it has greater children
return _OrderedMap.iterator(walk.right.subtreeMin())
else:
# start walking upward
while walk is not None and not self._less(key, walk.key):
walk = walk.parent
if walk is not None:
return _OrderedMap.iterator(walk)
else:
return None
def insert(self, key, value=None):
"""Associate key to value.
If key exists, old value is overwritten with new.
If key does not exist, it is added to the map.
Return an iterator to the key's position.
"""
walk = self._trace(key)
if walk is None:
self._size += 1
self._root = _OrderedMap._node(key, value)
return _OrderedMap.iterator(self._root)
else:
if self._less(key, walk.key):
walk.left = _OrderedMap._node(key, value, walk)
walk = walk.left
self._insertRebalance(walk)
self._size += 1
elif self._less(walk.key, key):
walk.right = _OrderedMap._node(key, value, walk)
walk = walk.right
self._insertRebalance(walk)
self._size += 1
else:
# key exists; overwrite old value
walk.val = value
return _OrderedMap.iterator(walk)
def _insertRebalance(self, walk):
while walk.parent is not None and walk.priority < walk.parent.priority:
self._rotateUp(walk)
def remove(self, posn):
"""Remove the item at the given iterator."""
if not isinstance(posn, self.iterator):
raise TypeError("Must provide valid iterator for remove")
self._size -= 1
walk = posn._nd
if walk.left is None or walk.right is None:
self._easyDelete(walk)
else:
# use predecessor as sub for the current node
sub = walk.left.subtreeMax()
# fix pointer from above
if self._root is walk:
self._root = sub
elif walk is walk.parent.left:
walk.parent.left = sub
else:
walk.parent.right = sub
# relocate sub and remove walk
if sub is not walk.left:
# clean up below
sub.parent.right = sub.left
if sub.left is not None:
sub.left.parent = sub.parent
# sub takes over left child of walk
sub.left = walk.left
walk.left.parent = sub
# sub takes over right child of walk
sub.right = walk.right
walk.right.parent = sub
# sub gets new parent
sub.parent = walk.parent
# restore heap property from sub downward
downward = True
while downward:
child = sub.left
if sub.right is not None and (child is None or sub.right.priority < child.priority):
child = sub.right
if child is not None and child.priority < sub.priority:
self._rotateUp(child)
else:
downward = False
def _rotateUp(self, walk):
"""Rotate node walk up one level.
Assumes that walk is not the root (but parent may be)
"""
parent = walk.parent
grand = parent.parent
walk.parent = grand
parent.parent = walk
if parent.left is walk:
parent.left = walk.right
if walk.right is not None:
walk.right.parent = parent
walk.right = parent
else:
parent.right = walk.left
if walk.left is not None:
walk.left.parent = parent
walk.left = parent
if grand is None:
self._root = walk
else:
if grand.left is parent:
grand.left = walk
else:
grand.right = walk
def _easyDelete(self, walk):
"""Assumes that walk is a node that has at most one child."""
if walk.left is None:
child = walk.right
else:
child = walk.left
if child is not None:
child.parent = walk.parent
if walk.parent is None:
self._root = child
else:
if walk is walk.parent.left:
walk.parent.left = child
else:
walk.parent.right = child
walk.parent = walk.left = walk.right = None # disconnect, to be safe
###################################################
######### nested class _OrderedMap._node ##########
class _node:
__slots__ = ('key', 'val', 'parent', 'left', 'right', 'priority') # optimization
"""Simple struct to represent node of the treap"""
def __init__(self, key, value=None, parent=None, leftChild=None, rightChild=None):
self.key = key
self.val = value
self.parent = parent
self.left = leftChild
self.right = rightChild
self.priority = _ourRandom.random()
def subtreeMin(self):
"""Return leftmost node of subtree."""
walk = self
while walk.left is not None:
walk = walk.left
return walk
def subtreeMax(self):
"""Return rightmost node of subtree."""
walk = self
while walk.right is not None:
walk = walk.right
return walk
def predecessor(self):
"""Returns node of predecessor. Returns None if this is minimum."""
if self.left is not None:
return self.left.subtreeMax()
else:
walk = self
while walk.parent is not None and walk.parent.left is walk:
walk = walk.parent
return walk.parent
def successor(self):
"""Returns node of successor. Returns None if this is maximum."""
if self.right is not None:
return self.right.subtreeMin()
else:
walk = self
while walk.parent is not None and walk.parent.right is walk:
walk = walk.parent
return walk.parent
######### end of class _OrderedMap._node ##########
######################################################
######### nested class _OrderedMap.iterator ##########
class iterator:
"""Encapsulation of a position in the map"""
def __init__(self, node):
self._nd = node
def __repr__(self):
return "Iterator[key=" + repr(self.key()) + ' value=' + repr(self.value()) + "]"
def __eq__(self, other):
"""Return True if iterators represent the same position."""
return self._nd == other._nd
def __ne__(self, other):
"""Return True if iterators do not represent the same position."""
return not self._nd == other._nd
def key(self):
"""Return key of element at this position."""
return self._nd.key
def value(self):
"""Return value of element at this position."""
return self._nd.val
def prev(self):
"""Return iterator to the previous element of the map.
Return None if there is no predecessor."""
other = self._nd.predecessor()
if other is not None:
return _OrderedMap.iterator(other)
else:
return None
def next(self):
"""Return iterator to the next element of the map.
Return None if there is no successor."""
other = self._nd.successor()
if other is not None:
return _OrderedMap.iterator(other)
else:
return None
######### end of class _OrderedMap.iterator ##########
class _Hierarchy:
"""Used to maintain minimal information to track which objects are
currently contained (directly or indirectly) on a Canvas, and to
track the parent/child relationships between those objects.
Technically, each object is noted as an (object,cls) pair where
cls is the class whose _draw was called. Typically, this will be
the object's class, but could be a parent class for some.
Furthermore, each object typically has only one such entry in the
hierarchy, but with multiple inheritence (e.g. Button), there
might be three or more different entries, one due to the original
Button._draw call, but two subsequent due to the underlying
Rectangle._draw and Text._draw calls.
"""
def __init__(self):
self._objects = {} # map from obj to set of all (obj,cls) pairs
self._relationships = {} # map from (obj.cls) pair to [parentSet, childrenDict, maxSerial]
# where parentSet is set of (obj,cls) tuples,
# childrenDict is dictionary mapping from (child,cls) -> serialFloat,
# and maxSerial is an upper bound on the serials currently in use
def __contains__(self, drawable):
"""Determines whether the drawable is contained in the current hierarchy."""
return drawable in self._objects
def newCanvas(self, canvas):
"""Adds canvas as new top-level container in the hierarchy."""
self._objects[canvas] = set()
self._objects[canvas].add((canvas, Canvas))
self._relationships[(canvas, Canvas)] = [set(), {}, 0]
def addLink(self, parentTuple, childTuple):
"""Connect child to parent.
parentTuple and childTuple should both be of form (object,cls)
and that parentTuple is already in this hierarchy.
"""
self._objects.setdefault(childTuple[0], set()).add(childTuple)
relate = self._relationships[parentTuple]
relate[2] += 1 # update serial
relate[1][childTuple] = relate[2] # new child with updated serial
self._relationships.setdefault(childTuple, [set(), {}, 0])[0].add(parentTuple)
def removeLink(self, parentTuple, childTuple):
"""Removes the child from the parent (including the cleansing of any descendents)."""
# remove child from parent's list of children
parentsChildren = self._relationships[parentTuple][1]
del self._relationships[parentTuple][1][childTuple]
# remove parent from child's list of parents
childsParents = self._relationships[childTuple][0]
childsParents.remove(parentTuple)
if not childsParents: # empty set
self._recursiveRemove(childTuple)
def findChildTuple(self, parentTuple, child):
"""For when we know the child, but not the child's appropriate "class" tag
(because _draw was not necessarily from that class)
"""
for k in self._relationships[parentTuple][1].keys():
if k[0] == child:
return k
def getSerial(self, parentTuple, childTuple):
return self._relationships[parentTuple][1][childTuple]
def _recursiveRemove(self, objTuple):
# remove association from self._objects
objSet = self._objects[objTuple[0]]
objSet.remove(objTuple)
if not objSet: # empty set
del self._objects[objTuple[0]]
# remove association from self._relationships
entry = self._relationships.pop(objTuple)
children = entry[1]
for c in children.keys():
childsParents = self._relationships[c][0]
childsParents.remove(objTuple)
if not childsParents: # no more parents
self._recursiveRemove(c)
def reviseChildren(self, drawTuple, childSequence):
"""Compares the newSequence of drawable's children to sequence currently on record.
Returns list of (child,serial) pairs for those children that require updated serial numbers.
"""
raise NotImplementedError('reviseChildren not yet written') # TODO
def computeUpwardChains(self, drawable, counts=None):
if counts is None:
counts = {}
if isinstance(drawable, tuple):
tuples = [drawable]
else:
tuples = self._objects[drawable]
results = []
for t in tuples:
self._computeUpwardChainsRecurse(results, t, counts)
if _DEBUG['Middle'] >= 2:
print('ComputeUpwardChains(' + str(drawable) + ',' + str(counts) + ') returning:')
for c in results:
print(' ' + str(tuple(c)))
return results
def _computeUpwardChainsRecurse(self, results, drawTuple, count):
prevCount = count.get(drawTuple, 0)
if prevCount < _RECURSIVE_LIMIT:
parents = self._relationships[drawTuple][0]
if parents:
count[drawTuple] = 1 + prevCount
for p in parents:
oldSize = len(results)
self._computeUpwardChainsRecurse(results, p, count)
for k in range(oldSize, len(results)):
results[k].append(drawTuple)
count[drawTuple] -= 1 # decrement count, to avoid side effects
if count[drawTuple] == 0:
del count[drawTuple]
else:
results.append([drawTuple]) # "drawTuple" must represent a canvas
def computeDownwardChains(self, drawTuple):
"""Computes all downward chians from the given starting point.
Returns pre-order list of (chain, countDict) pairs
Allows for cycles in chain, up to the globally determined recursive limit.
"""
results = []
self._computeDownwardChainsRecurse(results, drawTuple, {})
if _DEBUG['Middle'] >= 2:
print('ComputeDownwardChains(' + str(drawTuple) + ') returning:')
for c in results:
print(' ' + str(tuple(c)))
return results
def _computeDownwardChainsRecurse(self, results, drawTuple, count):
"""
Returns a pre-order list of all downward chains (including all prefixes).
Furthermore this version is given a dictionary of counts, mapping from
drawTuple -> frequency that is presumed to have occurred
outside the context of this call (zero if not present).
Semantic is that there is a total cap on the number of
occurrences of any given element, including the previous
counts.
Note: this function must guarantee that count is restored to
its previous state by the end of a given call so that there
are no lasting side effect (except perhaps by having non-keys
end up as keys with a count of zero).
"""
prevCount = count.get(drawTuple, 0)
count[drawTuple] = 1 + prevCount
results.append(([drawTuple], dict(count)))
for child in self._relationships[drawTuple][1].keys():
if count.get(child, 0) < _RECURSIVE_LIMIT:
oldSize = len(results)
self._computeDownwardChainsRecurse(results, child, count)
for k in range(oldSize, len(results)):
results[k][0].insert(0, drawTuple)
count[drawTuple] -= 1 # decrement count to avoid lasting effect
if count[drawTuple] == 0:
del count[drawTuple]
class _RenderedHierarchy:
class Node:
__slots__ = ('_chain', '_children', '_sortedChildren', '_prev', '_next', '_parent', # optimization
'_depth', '_transformation', '_cumulativeTransformation', '_renderedDrawable')
def __init__(self):
self._chain = None
self._children = dict()
self._sortedChildren = _OrderedMap()
self._prev = None
self._next = None
self._parent = None
self._depth = None
self._transformation = _Transformation()
self._cumulativeTransformation = _Transformation()
self._renderedDrawable = None
def __init__(self):
self._root = self.Node()
self._first = None
self._last = None
self._nodeLookup = dict()
self._nodeLookup[tuple()] = self._root
def add(self, chain, depth, transformation, renderedDrawable):
"""Add a new chain to the hierarchy and return the new node.
The parent chain must be present.
"""
parentChain = chain[:-1]
parentNode = self._nodeLookup[parentChain]
# Create the new node
newNode = self.Node()
newNode._chain = chain
newNode._depth = depth
newNode._transformation = transformation
if parentChain and parentChain[-1][0] is chain[-1][0] and parentChain[-1][1] is not chain[-1][1]:
# do not reapply local transform if parent call to _draw is reflected in the chain
# (recognized by same object ID, but with different class; this allows recursive layer)
newNode._cumulativeTransformation = parentNode._cumulativeTransformation * _Transformation()
else:
# standard case
newNode._cumulativeTransformation = parentNode._cumulativeTransformation * transformation
newNode._renderedDrawable = renderedDrawable
newNode._parent = parentNode
# Link new node into structure
self._nodeLookup[chain] = newNode
parentNode._children[chain[-1]] = newNode
parentNode._sortedChildren[depth] = newNode
self._addThreads(newNode, parentNode)
return newNode
def remove(self, chain):
"""Remove a node and all of its children.
A list of RenderedDrawables to be deleted is returned.
"""
node = self._nodeLookup[chain]
parentChain = chain[:-1]
parentNode = self._nodeLookup[parentChain]
# Remove parent references and threads
parentNode._children.pop(chain[-1])
del parentNode._sortedChildren[node._depth]
self._removeThreads(node, parentNode)
# Find all of the RenderedDrawables to delete
deleted = list()
queue = [node]
while len(queue) > 0:
n = queue.pop()
self._nodeLookup.pop(n._chain)
if n._renderedDrawable is not None:
deleted.append(n._renderedDrawable)
queue.extend(n._children.values())
return deleted
def prev(self, node):
"""Find the previous leaf node.
Precondition: node is a leaf node
If there is no previous node it returns None
"""
return node._prev
def next(self, node):
"""Find the next leaf node.
Precondition: node is a leaf node
If there is no next node it returns None
"""
return node._next
def first(self, node):
while len(node._sortedChildren) > 0:
node = node._sortedChildren.first().value()
return node
def last(self, node):
while len(node._sortedChildren) > 0:
node = node._sortedChildren.last().value()
return node
def getNode(self, chain):
return self._nodeLookup[chain]
def hasChain(self, chain):
return chain in self._nodeLookup
def getDepth(self, chain):
return self._nodeLookup[chain]._depth
def changeDepth(self, chain, newDepth):
node = self._nodeLookup[chain]
oldDepth = node._depth
if _DEBUG['RenderedH'] >= 1.5:
print('change depth of ' + str(chain) + ' from ' + str(oldDepth) + ' to ' + str(newDepth))
node._depth = newDepth
parent = node._parent
handle = parent._sortedChildren.find(oldDepth)
prevSib = handle.prev()
nextSib = handle.next()
del parent._sortedChildren[oldDepth]
parent._sortedChildren[newDepth] = node
if (prevSib is not None and newDepth < prevSib.key()) or \
(nextSib is not None and newDepth > nextSib.key()):
# must re-thread relative to siblings
if _DEBUG['RenderedH'] >= 2.5:
for (k, v) in iter(parent._sortedChildren):
print(' child: ' + str(k) + ' ' + str(v))
self._removeThreads(node, parent) # detach from old location
self._addThreads(node, parent) # reattach in new location