-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathturtleps.py
More file actions
2559 lines (1959 loc) · 78.9 KB
/
Copy pathturtleps.py
File metadata and controls
2559 lines (1959 loc) · 78.9 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
# ************ WARNING! ********************
# ************ DO _NOT_ WRITE INTO THIS FILE !! ********************
#
# ************ ATTENZIONE! ********************
# ************ _NON_ SCRIVERE IN QUESTO FILE !! ********************
#
print("TPS: Loading turtleps.py")
import sys
print(f"SYSTEM: {sys.implementation.name} {'.'.join(map(str, sys.implementation.version[:3]))} (python {'.'.join(map(str, sys.version_info[:3]))})" )
print('system', sys.version)
# in pyodide: SYSTEM: cpython 3.12.7 (python 3.12.7)
# in micropython: SYSTEM: micropython 1.24.1 (python 3.4.0)
if "pyodide" in sys.modules:
SYSTEM = "pyodide"
elif sys.implementation.name == "micropython":
SYSTEM = "micropython"
else:
raise Exception("Unknown python platform!")
print("Detected system:", SYSTEM)
import re
import math
import asyncio
import os
import js
from js import console
import pyscript
from pyscript import document, window
from pyscript.js_modules import turtleps as tpsjs
_debugging = False
#_debugging = True
#_tracing = True
_tracing = False
def _debug(*args, c=False):
if _debugging:
if c:
console.log("TPS DEBUG:", *args)
else:
print("TPS DEBUG:", *args)
def _trace(*args, c=False):
if _tracing:
if c:
console.log("TPS TRACE:",*args)
else:
print("TRACE:", *args)
def _info(*args, c=False):
if c:
console.log("TPS INFO:", *args)
else:
print("TPS INFO", *args)
def _warn(*args, c=False):
if c:
console.warn("TPS WARN:", *args)
else:
print("TPS WARN", *args, file=sys.stderr)
def _error(*args, c=False):
"""
@since 0.9.0
"""
if c:
console.error("ERROR:", *args)
else:
print("ERROR:", *args, file=sys.stderr)
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
class CDTNException(Exception):
def __init__ ( self, *args ):
super().__init__(*args)
def __str__(self):
words = []
for arg in self.args:
#todo handle js elements
words.append(str(arg))
return f"{self.__class__.__name__} {' '.join(words)}"
def __repr__(self):
words = []
for arg in self.args:
#todo handle js elements
words.append(repr(arg))
return f"{self.__class__.__name__} ' '.join(words)"
class CDTNValueError(CDTNException):
"""
@since 0.9.0
"""
class CDTNRuntimeError(CDTNException):
"""
@since 0.9.0
"""
pass
# note: not Enum as it's not supported in micropython
class Resource:
"""
Simple class to model a resource status
!! CDTN NEW
@since 0.9.0
"""
TO_LOAD = 0
LOADED = 1
FAILED = 2
# note: not Enum as it's not supported in micropython
class GameStatus:
"""
PLAY is normal status, simply means turtleps module is loaded
STOP is intended as 'panic mode':
- asyncio tasks are shut down
- what about main.py?
- Sounds are interrupted
- Sprites still show for inspection
- mouse and keys are unregistered
PAUSED is not yet implemented apparently pausing pyodide is complicated
"""
PLAY = 0,
STOP = 1
IMG_WARNING = "img/warning.svg"
"""
@since 0.9.0
"""
def exception_handler(loop, context):
"""
To prevent stop related errors
@since 0.10.0
"""
exception = context['exception']
message = context['message']
_info(f'TPS EXCEPTION HANDLER: Task failed, msg={message}, exception={exception}')
if SYSTEM == "micropython":
_loop = asyncio.get_event_loop() # deprecated but micropython only supports this
else:
_loop = asyncio.get_running_loop()
# set the exception handler
_loop.set_exception_handler(exception_handler)
if SYSTEM != 'micropython':
from typing import Awaitable
from uuid import uuid4
from importlib import reload as importlib_reload
from urllib.parse import urlparse
from pprint import pprint
from traceback import print_exception
else:
_info("DETECTED MICROPYTHON, PUTTING SHIMS...")
_info("- replacing traceback print_exception")
def print_exception(e, file=sys.stderr):
sys.print_exception(e, file)
_info("- replacing uuid for micropython shim")
import ubinascii
from random import randint
def urandom(n):
return bytes(randint(0, 255) for _ in range(n))
class UUID:
def __init__(self, bytes):
if len(bytes) != 16:
raise ValueError('bytes arg must be 16 bytes long')
self._bytes = bytes
@property
def hex(self):
return ubinascii.hexlify(self._bytes).decode()
def __str__(self):
h = self.hex
return '-'.join((h[0:8], h[8:12], h[12:16], h[16:20], h[20:32]))
def __repr__(self):
return "<UUID: %s>" % str(self)
def uuid4():
"""Generates a random UUID compliant to RFC 4122 pg.14"""
random = bytearray(urandom(16))
random[6] = (random[6] & 0x0F) | 0x40
random[8] = (random[8] & 0x3F) | 0x80
return UUID(bytes=random)
_info("- replacing typing.Awaitable with a shim")
# would like from typing import Awaitable
# but can't use typing https://micropython-stubs.readthedocs.io/en/main/typing_mpy.html
class Awaitable:
pass
_info("- replacing asyncio.core._task_queue with ours (will just forward calls) ...")
_orig_asyncio_core_task_queue = asyncio.core._task_queue
class TurtlepsTaskQueue:
"""@since 0.12.2
"""
def __init__(self):
pass
def peek(self):
_debug("TurtlepsTaskQueue.peek shim was called")
return _orig_asyncio_core_task_queue.peek()
def push(self, v, key=None):
_debug("TurtlepsTaskQueue.push shim was called with:", v, "type(v)", type(v))
_running_tasks.add(v)
_orig_asyncio_core_task_queue.push(v, key)
def pop(self):
_debug("TurtlepsTaskQueue.pop shim was called")
v = _orig_asyncio_core_task_queue.pop()
if v in _running_tasks:
_running_tasks.remove(v)
return v
def remove(self, v):
_debug("TurtlepsTaskQueue.remove shim was called")
if v in _running_tasks:
_running_tasks.remove(v)
_orig_asyncio_core_task_queue.remove(v)
asyncio.core._task_queue = TurtlepsTaskQueue()
_info("- replacing asyncio.gather with a shim")
_orig_gather = asyncio.gather
def _turtleps_gather(*awaitables, return_exceptions=False):
""" Cpython can kinda work even without await, micropython doesn't
unless you wrap the thing with a create_task
"""
_info("turtleps_gather shim was called")
return asyncio.create_task(_orig_gather(*awaitables, return_exceptions=return_exceptions))
asyncio.gather = _turtleps_gather
_info("- creating asyncio.all_tasks shim")
def turtleps_all_tasks():
_debug("turtleps_all_tasks shim was called, returning _running_tasks")
#loop = asyncio.get_event_loop()
#tasks = loop.runq + loop.waitq #runq attribute doesn't exist in newer micropython versions :-/
return _running_tasks
asyncio.all_tasks = turtleps_all_tasks
_info("- replacing importlib_reload with a totally dummy non-working shim")
def importlib_reload(module):
n = module.__name__
#print("dir(module): ", dir(module))
#print("module.__name__: ", module.__name__)
#print("str(module): ", n)
#sys.modules[str(module)].myfunc()
print("sys.modules", sys.modules)
del sys.modules[n]
exec('import ' + n, {} )
_info("- replacing urlparse with JS shim")
class ParseResult:
def _replace(self, **args):
# TODO quick & dirty implementation
ret = ParseResult()
ret.scheme = self.scheme
ret.netloc = self.netloc
ret.path = self.path
ret.query = self.query
ret.fragment = self.fragment
for k,v in args.items():
if k == 'scheme': # there is no __setattr__ in micropython
self.scheme = v
elif k == 'netloc':
self.netloc = v
elif k == 'path':
self.path = v
elif k == 'query':
self.query = v
elif k == 'fragment':
self.fragment = v
else:
raise ValueError(f"Unsupported param: {k}")
return ret
def geturl(self):
sc = self.scheme + '://' if self.scheme else ''
q = '?' + self.query if self.query else ''
f = '#' + self.fragment if self.fragment else ''
return sc + self.netloc + self.path + q + f
def urlparse(url):
js.console.log('urlparse url:',url);
# see https://dmitripavlutin.com/parse-url-javascript/
# and https://developer.mozilla.org/en-US/docs/Web/API/URL
#urlparse("scheme://netloc/path;parameters?query#fragment")
#ParseResult(scheme='scheme', netloc='netloc', path='/path;parameters', params='',
#query='query', fragment='fragment')
mock = 'http://MOCK/'
mocked = False
pr = ParseResult()
pr.scheme = ''
pr.netloc = ''
pr.path = ''
pr.query = ''
pr.fragment = ''
if not url.startswith('http'):
mocked = True
# adding mock http so javascript doesn't complain
nurl = mock + url
try:
#python parse seems a lot more lenient
jpr = js.URL.new(nurl)
except:
return pr
pr.scheme = jpr.protocol[:-1] # js includes :
pr.netloc = jpr.hostname
if mocked:
pr.path = jpr.pathname[1:] # no leading /
else:
pr.path = jpr.pathname
pr.query = jpr.search
pr.fragment = jpr.hash
if mocked:
pr.scheme = ''
pr.netloc = ''
return pr
_info("- replacing pprint with a shabby shim")
def pprint(obj):
print(repr(obj))
# see https://github.com/CoderDojoTrento/turtle-pyscript/issues/8
_running_tasks = set()
_running_tasks.add(asyncio.current_task())
def _schedule_task(awaitable):
"""
@since 0.8
"""
t = asyncio.create_task(awaitable)
# this is only a CPython problem, see https://github.com/micropython/micropython/issues/12299
def clean_task(t):
if t in _running_tasks:
_running_tasks.remove(t)
if SYSTEM != "micropython":
_running_tasks.add(t)
t.add_done_callback(clean_task) # consider stop
return t
_info('Received pyscript.config:', pprint(pyscript.config))
_info("- all tasks:")
for t in asyncio.all_tasks():
if SYSTEM == "micropython":
c = t.coro
else:
c = t.get_coro()
_info(" Coroutine:", c.__name__ if c else 'None')
_info("dir(t)", dir(t))
_info("dir(c)", dir(c))
#__pragma__ ('skip')
#document = Math = setInterval = clearInterval = 0
#__pragma__ ('noskip')
"""
Aug 2024:
TURTLE MODULE TAKEN FROM transcrypt (apache licence)
https://github.com/TranscryptOrg/Transcrypt/blob/master/transcrypt/modules/turtle/__init__.py
NOTE: YOU DON'T NEED TRANSCRIPT, WE EXECUTE IT IN PYSCRIPT
"""
# not importing anything from turtle as it's disabled in pyodide
class TurtleGraphicsError(Exception):
"""Some TurtleGraphics Error
"""
pass
class Vec2D(tuple):
"""A 2 dimensional vector class, used as a helper class
for implementing turtle graphics.
May be useful for turtle graphics programs also.
Derived from tuple, so a vector is a tuple!
Provides (for a, b vectors, k number):
a+b vector addition
a-b vector subtraction
a*b inner product
k*a and a*k multiplication with scalar
|a| absolute value of a
a.rotate(angle) rotation
"""
# micropython lacks __new__, see https://docs.micropython.org/en/latest/genrst/core_language.html#when-inheriting-native-types-calling-a-method-in-init-self-before-super-init-raises-an-attributeerror-or-segfaults-if-micropy-builtin-method-check-self-arg-is-not-enabled
# TODO I bet there is a simpler way to handle it
if SYSTEM == 'micropython':
def __init__(self, x, y):
super().__init__((x, y))
else:
def __new__(cls, x, y):
return tuple.__new__(cls, (x, y))
def __add__(self, other):
return Vec2D(self[0]+other[0], self[1]+other[1])
def __mul__(self, other):
if isinstance(other, Vec2D):
return self[0]*other[0]+self[1]*other[1]
return Vec2D(self[0]*other, self[1]*other)
def __rmul__(self, other):
if isinstance(other, int) or isinstance(other, float):
return Vec2D(self[0]*other, self[1]*other)
return NotImplemented
def __sub__(self, other):
return Vec2D(self[0]-other[0], self[1]-other[1])
def __neg__(self):
return Vec2D(-self[0], -self[1])
def __abs__(self):
return math.hypot(*self)
def rotate(self, angle):
"""rotate self counterclockwise by angle
"""
perp = Vec2D(-self[1], self[0])
angle = math.radians(angle)
c, s = math.cos(angle), math.sin(angle)
return Vec2D(self[0]*c+perp[0]*s, self[1]*c+perp[1]*s)
def __getnewargs__(self):
return (self[0], self[1])
def __repr__(self):
return "(%.2f,%.2f)" % self
def _parse_color_args(*args):
if len(args) == 1:
if isinstance(args[0], tuple):
svg_color = f"rgb({','.join([str(a) for a in args[0]])})"
elif isinstance(args[0], str):
svg_color = args[0]
else:
raise TurtleGraphicsError(f"Unrecognized color format: {args[0]}")
elif len(args) == 3:
svg_color = f"rgb({','.join([str(a) for a in args])})"
else:
raise TurtleGraphicsError(f"Unrecognized color format: {args}")
return svg_color
def _sanitize_id(name):
""" Valid stuff: any unicode international character, digit, -
Invalid characters will be converted to -
@since 0.7.3
"""
ret = re.sub(r"[^\w0-9\-_]", '-', name)
return ret
#def abs (vec2D):
# return Math.sqrt (vec2D [0] * vec2D [0] + vec2D [1] * vec2D [1])
_CFG = {"width" : 400, # 0.5, # Screen
"height" : 400, # 0.75,
"canvwidth" : 400,
"canvheight": 300,
"leftright": None,
"topbottom": None,
"mode": "standard", # TurtleScreen
"colormode": 1.0,
"delay": 20, # CDTN: original default is 10 which is quite small, leads to high frames per second
# I think it's besto to use only internally, not in the examples.
# delay (ms) delay (s) framerate
# 10 0.01 s 100 fps
# 16 0.016 s ~60 fps
# 20 0.02 s 50 fps
# 32 ms 0.032 s ~30 fps
"undobuffersize": 1000, # RawTurtle
"shape": "classic",
"pencolor" : "black",
"fillcolor" : "black",
"resizemode" : "noresize", # CDTN: why? I would expect "user"
"visible" : True,
"language": "english", # docstrings
"exampleturtle": "turtle",
"examplescreen": "screen",
"title": "Python Turtle Graphics",
"using_IDLE": False
}
_ns = 'http://www.w3.org/2000/svg'
# this is a better version BUT in MicroPython using len() gives # object of type 'JsProxy' has no len()
"""
_all_svgs = document.querySelectorAll('.tps-screen');
if len(_all_svgs) == 1:
_svg = _all_svgs[0]
elif len(_all_svgs) > 1:
_error("FOUND MULTIPLE ELEMENTS WITH .tps-screen CLASS, THERE SHOULD BE ONLY ONE: PICKING THE FIRST...")
_svg = _all_svgs[0]
else:
_svg = None
"""
# so let's keep it simple for now:
_svg = document.querySelector('.tps-screen');
if _svg:
_info("Found existing svg, cleaning content..", _svg, c=True)
_svg.replaceChildren()
else:
_svg = document.createElementNS (_ns, 'svg')
_info("Adding new svg", _svg, "to body", c=True)
_svg.classList.add("tps-screen")
document.body.appendChild (_svg)
_silhouettes = document.createElementNS(_ns, 'g')
_silhouettes.setAttribute('class', 'tps-silhouettes')
_defs = document.createElementNS (_ns, 'defs')
_defs.setAttributeNS(None, 'class', 'tps-defs')
_defs.appendChild(_silhouettes)
_svg.appendChild(_defs)
# so we can at least define z-order of turtles
_svg_sprites = document.createElementNS (_ns, 'g')
_svg_sprites.setAttribute('class', 'tps-sprites')
_svg.appendChild(_svg_sprites)
_svg_comics = document.createElementNS (_ns, 'g')
"""@since 0.11.0"""
_svg_comics.setAttribute('class', 'tps-comics')
_svg.appendChild(_svg_comics)
def _onload_image(shape, event):
"""
Note onload event seems fired even when file image is in cache (tried in chrome)
@since 0.9.0
"""
img = event.target
_debug("image loaded with event:", event, c=True)
_debug("- event timeStamp:", event.timeStamp)
url = img.getAttribute("href")
img_id = img.getAttribute("id")
_debug("- image:", img, c=True)
_debug(" - image id:", img_id)
_debug(" - image href:", url)
shape_size = shape.get_svg_image_size()
_debug(" - registered shape:", shape)
_debug(" - shape size:", shape_size )
shape.status = Resource.LOADED
create_clip(img)
def _version_url(url, v):
"""
@since 0.10.0
"""
#urlparse("scheme://netloc/path;parameters?query#fragment")
#ParseResult(scheme='scheme', netloc='netloc', path='/path;parameters', params='',
#query='query', fragment='fragment')
pr = urlparse(url)
if pr.scheme:
return url
# url is relative, we can manage it
prefix = ''
if pr.query:
q += pr.query + '&'
return pr._replace(query=pr.query + prefix + 'v=' + str(v)).geturl()
def create_clip(img):
"""
@since 0.9.0
"""
img_id = img.getAttribute("id")
clip_id = f"tps-clip-{img_id}"
clip_path = document.createElementNS(_ns, 'clipPath')
clip_path.setAttribute('clip-rule', "evenodd") # TODO don't know what this is
clip_path.setAttribute('id', clip_id)
Screen()._clip_paths.appendChild(clip_path)
img.setAttribute('clip-path', f"url(#{clip_id})")
def img_loaded(e):
work_canvas = tpsjs.vectorize(e.target, clip_path)
_debug(" - vectorized shape:", shape)
_debug("Vectorized canvas:", work_canvas, c=True)
work_img = js.Image.new()
work_img.src = img.getAttribute('href')
work_img.onload = img_loaded
def _onerror_image(shape, event):
"""
@since 0.9.0
"""
_debug("image loading FAILED with event:", event)
_debug("- event timeStamp:", event.timeStamp)
_debug("- image:", event.target)
_debug(" - image id:", event.target.getAttribute("id"))
_debug(" - image href:", event.target.getAttribute("href"))
_debug(f" - registered shape: {shape}")
_debug(f" - shape size: {shape.get_svg_image_size()}")
shape.status = Resource.FAILED
shape.svg.onload = None
shape.svg.onerror = None
orig_href = shape.svg.getAttribute('href')
shape.svg.setAttribute('href', IMG_WARNING)
shape.svg.setAttribute('data-cdtn-orig-href', orig_href)
tooltip = document.createElementNS (_ns, 'title')
tooltip.textContent = f"Error loading image:\n{orig_href}"
shape.svg.appendChild(tooltip)
create_clip(shape.svg)
class Shape(object):
"""Data structure modeling shapes.
attribute _type is one of "polygon", "image", "compound"
attribute _data is - depending on _type a poygon-tuple,
an image or a list constructed using the addcomponent method.
CDTN: doesn't seem really useful, in the original CPython implementation doesn't
have public attributes nor methods to retrieve stuff.
original _data che be in many forms, from concrete bitmap images to tuples
Decision: will store in ._data nothing
will store in .svg an unlinked svg element
"""
def __init__(self, type_, data=None):
self._type = type_
if type_ == "polygon":
if isinstance(data, list):
data = tuple(data)
"""
<polygon points="100,100 150,25 150,75 200,0" fill="none" stroke="black" />
"""
poly = document.createElementNS(_ns, 'polygon')
points_str = ' '.join([','.join([str(el) for el in t]) for t in data])
poly.setAttributeNS(None, 'points', points_str)
self.svg = poly
self.status = Resource.LOADED
# leaving default fill...
elif type_ == "image":
if not data:
raise ValueError("CDTN: Missing image data!")
img = document.createElementNS(_ns, 'image')
#img.setAttributeNS(None, 'x', 0)
#img.setAttributeNS(None, 'y', 0)
#img.setAttributeNS(None, 'width', 20)
#img.setAttributeNS(None, 'height', 20)
#img.setAttributeNS(None, 'xlink:href', name) # doesn't like it
# using our mirrored global config as unfortunately Pyscript doesn't support changing config between runs
if hasattr(tpsjs, "tps_config") and hasattr(tpsjs.tps_config, "tps") and hasattr(tpsjs.tps_config.tps, "v"):
v = tpsjs.tps_config.tps.v
_debug("!!!!!! updating v", v)
new_data = _version_url(data, v)
else:
new_data = data
img.setAttributeNS(None, 'href', new_data)
self.svg = img
self.status = Resource.TO_LOAD
#CDTN commented, expect svg node
#if isinstance(data, str):
#if data.lower().endswith(".gif") and os.path.isfile(data):
# data = TurtleScreen._image(data)
# else data assumed to be PhotoImage # CDTN ??
elif type_ == "compound":
#data = [] CDTN
self.svg = document.createElementNS(_ns, 'g') # group
self.status = Resource.LOADED
else:
raise TurtleGraphicsError("There is no shape type %s" % type_)
def get_svg_image_size(self):
"""
"""
if self._type != "image":
raise CDTNException("Other types are currently not supported")
return (self.svg.getBBox().width, self.svg.getBBox().height )
def addcomponent(self, poly, fill, outline=None):
"""Add component to a shape of type compound.
Arguments: poly is a polygon, i. e. a tuple of number pairs.
fill is the fillcolor of the component,
outline is the outline color of the component.
call (for a Shapeobject namend s):
-- s.addcomponent(((0,0), (10,10), (-10,10)), "red", "blue")
Example:
>>> poly = ((0,0),(10,-5),(0,10),(-10,-5))
>>> s = Shape("compound")
>>> s.addcomponent(poly, "red", "blue")
>>> # .. add more components and then use register_shape()
"""
if self._type != "compound":
raise TurtleGraphicsError("Cannot add component to %s Shape"
% self._type)
if outline is None:
outline = fill
poly = document.createElementNS(_ns, 'polygon')
points_str = ' '.join([','.join(t) for t in data])
poly.setAttributeNS(None, 'points', points_str)
if fill:
poly.setAttributeNS(None, 'fill', fill)
if outline:
poly.setAttributeNS(None, 'outline', outline)
self._data.appendChild(poly)
def get_tag_name(element):
"""
CDTN new
TODO TEST THIS..
@since 0.11.0
"""
if element == None:
return "None"
ret = element.tagName
if element.id:
ret += ' ' + element.id
elif element.classList:
ret += ' ' + element.classList.toString()
return ret
def Screen():
"""Return the singleton screen object.
If none exists at the moment, create a new one and return it,
else return the existing one."""
if Sprite._screen is None:
_debug("No default screen found, creating one..")
Sprite._screen = _Screen()
return Sprite._screen
class _Screen:
def __init__(self):
_debug("CDTN: Initializing screen...")
self.svg = _svg
self._clip_paths = _silhouettes
self.svg_sprites = _svg_sprites
self._svg_comics = _svg_comics
self.background = None # init later
self._defaultSprite = None
self._timer = None
self._delay = _CFG["delay"]
self._turtles = []
self._shapes = {}
self._width = _CFG["width"]
self._height = _CFG["height"]
self._offset = [_CFG["width"]//2, _CFG["height"]//2]
translate = f"{self._offset[0]},{self._offset[1] }"
self._svg_comics.setAttribute('transform',f"translate({translate})")
self._pressedKeys = set()
#self.canvwidth = w
#self.canvheight = h
#self.xscale = self.yscale = 1.0
shapes = {
"arrow" : Shape("polygon", ((-10,0), (10,0), (0,10))),
"turtle" : Shape("polygon", ((0,16), (-2,14), (-1,10), (-4,7),
(-7,9), (-9,8), (-6,5), (-7,1), (-5,-3), (-8,-6),
(-6,-8), (-4,-5), (0,-7), (4,-5), (6,-8), (8,-6),
(5,-3), (7,1), (6,5), (9,8), (7,9), (4,7), (1,10),
(2,14))),
"circle" : Shape("polygon", ((10,0), (9.51,3.09), (8.09,5.88),
(5.88,8.09), (3.09,9.51), (0,10), (-3.09,9.51),
(-5.88,8.09), (-8.09,5.88), (-9.51,3.09), (-10,0),
(-9.51,-3.09), (-8.09,-5.88), (-5.88,-8.09),
(-3.09,-9.51), (-0.00,-10.00), (3.09,-9.51),
(5.88,-8.09), (8.09,-5.88), (9.51,-3.09))),
"square" : Shape("polygon", ((10,-10), (10,10), (-10,10),
(-10,-10))),
"triangle" : Shape("polygon", ((10,-5.77), (0,11.55),
(-10,-5.77))),
"classic": Shape("polygon", ((0,0),(-5,-9),(0,-7),(5,-9))),
"blank" : Shape("polygon", tuple()),
"bgpanel" : Shape("polygon", (
(-1 - self._width // 2, 1 + self._height // 2),
( 1 + self._width // 2, 1 + self._height // 2),
( 1 + self._width // 2,-1 - self._height // 2),
(-1 - self._width // 2,-1 - self._height // 2)))
}
for name, shape in shapes.items():
self.register_shape(name, shape)
#self._mode = mode
#self._delayvalue = delay
#self._colormode = _CFG["colormode"]
#self._keys = []
self.clear()
#if sys.platform == 'darwin':
# Force Turtle window to the front on OS X. This is needed because
# the Turtle window will show behind the Terminal window when you
# start the demo from the command line.
# rootwindow = cv.winfo_toplevel()
# rootwindow.call('wm', 'attributes', '.', '-topmost', '1')
# rootwindow.call('wm', 'attributes', '.', '-topmost', '0')
def _right_size(myself=None):
self.update()
self.setup()
window.onresize = _right_size
_right_size()
def delay(self, delay=None):
""" Return or set the drawing delay in integer milliseconds.
Optional argument:
delay -- positive integer
Example:
>>> screen.delay(15)
>>> screen.delay()
15
@since 0.8.0
"""
if delay is None:
return self._delay
self._delay = int(delay)
def framerate(self):
""" !!!! CDTN NEW
@since 0.9.0
"""
return int(1000 / self._delay)
def getshapes(self):
"""Return a list of names of all currently available turtle shapes.
No argument.
Example (for a TurtleScreen instance named screen):
>>> screen.getshapes()
['arrow', 'blank', 'circle', ... , 'turtle']
"""
return sorted(self._shapes.keys())
def _clear_background(self):
"""
@since 0.11.0
"""
if self.background:
sp = self.background.svg_shape
self.background.svg.replaceChildren(sp)
self.background.shape('bgpanel')
else:
self.background = Sprite(screen = self,
shape = "bgpanel",
id_prefix ="turtle-background",
draw_target = "itself") # dummy element
_debug("!!!!!!!!!!! Setting bgcolor white")
self.background.fillcolor("white")
self.background.pencolor("red")
self.background.shapesize(1.0)
self.background.pensize(1)
self.background.goto(0,0)
def clear(self):
"""Delete all drawings and all turtles from the TurtleScreen.
No argument.
Reset empty TurtleScreen to its initial state: white background,
no backgroundimage, no eventbindings and tracing on.
Example (for a TurtleScreen instance named screen):