-
Notifications
You must be signed in to change notification settings - Fork 1
/
s2g.py
3265 lines (2779 loc) · 133 KB
/
s2g.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
#!/bin/env python3
# Copyright (C) 2016 - 2019 Victor T. Norman, Calvin College, Grand Rapids, MI, USA
#
# ScratchFoot: a Scratch emulation layer for Greenfoot, along with a program
# to convert a Scratch project to a Greenfoot scenario.
# 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/>
import glob
import json
import os, os.path
import platform
import argparse
import re
from pprint import pprint
import shutil
from subprocess import call, getstatusoutput
import sys
import tkinter
import tkinter.messagebox
# Global Variables that can be set via command-line arguments.
debug = False
inference = False
name_resolution = False
useGui = False
# Indentation level in outputted Java code.
NUM_SPACES_PER_LEVEL = 4
# This variable tracks how many cloud variables have been generated, and
# serves as each cloud var's id
cloudVars = 0
worldClassName = ""
# A list of all variables, some local, some global
allVars = []
# Set up arguments
parser = argparse.ArgumentParser()
parser.add_argument("-v", "--verbose", action="store_true", help="Enable verbose output")
parser.add_argument("-d", "--dotypeinference", action="store_true", help="Automatically infer variable types")
parser.add_argument("-r", "--resolvevariablenames", action="store_true", help="Automatically convert to java ids")
parser.add_argument("-g", "--gui", action="store_true", help="Use GUI converter (Experimental)")
parser.add_argument('-o', "--onlydecode", action="store_true",
help="Only decode the project.json, don't move files, etc.")
parser.add_argument("--scratch_file", help="Location of scratch sb2/sb3 file", default=os.getcwd(), required=False)
parser.add_argument("--greenfoot_dir", help="Location of greenfoot project directory", default=os.getcwd(),
required=False)
args = parser.parse_args()
# Apply arguments
if args.verbose:
debug = True
if args.dotypeinference:
inference = True
if args.resolvevariablenames:
name_resolution = True
if args.gui:
useGui = True
onlyDecode = args.onlydecode
SCRATCH_FILE = args.scratch_file.strip()
# Take off spaces and a possible trailing "/"
PROJECT_DIR = args.greenfoot_dir.strip().rstrip("/")
SCRATCH_PROJ_DIR = "scratch_code"
if SCRATCH_FILE.endswith('.sb2'):
print('Scratch conversion only works with Scratch 3.0')
sys.exit(-1)
# Initialize stage globally
stage = None
JAVA_KEYWORDS = ('abstract', 'continue', 'for', 'new', 'switch', 'assert', 'default', 'goto', \
'package', 'synchronized', 'boolean', 'do', 'if', 'private', 'this', 'break', \
'double', 'implements', 'protected', 'throw', 'byte', 'else', 'import', 'public', \
'throws', 'case', 'enum', 'instanceof', 'return', 'transient', 'catch', 'extends', \
'int', 'short', 'try', 'char', 'final', 'interface', 'static', 'void', 'class', 'finally', \
'long', 'strictfp', 'volatile', 'const', 'float', 'native', 'super', 'while')
class CodeAndCb:
"""This class binds together code, and possibly code that that code
will call that belongs in a callback."""
# class variable
cbScriptId = 0
def __init__(self):
self.code = ""
self.cbCode = ""
# self.varInitCode = ""
def addToCbCode(self, code):
self.cbCode += code
def getNextScriptId(self):
ret = CodeAndCb.cbScriptId
CodeAndCb.cbScriptId += 1
return ret
def addToCode(self, code):
self.code += code
def execOrDie(cmd, descr):
try:
print("Executing shell command: " + cmd)
retcode = call(cmd, shell=True)
if retcode < 0:
print("Command to " + descr + " was terminated by signal", -retcode, \
file=sys.stderr)
sys.exit(1)
else:
print("Command to " + descr + " succeeded")
except OSError as e:
print("Command to " + descr + ": Execution failed:", e, \
file=sys.stderr)
sys.exit(1)
def genIndent(level):
return (" " * (level * NUM_SPACES_PER_LEVEL))
def convertKeyPressName(keyname):
# Single letter/number keynames in Scratch and Greenfoot are identical.
# Keyname "space" is the same in each.
# Scratch does not have keynames for F1, F2, ..., Control, Backspace, etc.
# 4 arrow keys in Scratch are called "left arrow", "right arrow", etc.
# In Greenfoot, they are just "left", "right", etc.
if "arrow" in keyname:
keyname = keyname.rstrip(" arrow")
return keyname
def convertToNumber(tok):
if isinstance(tok, (float, int)):
return tok
# Try to convert the string/bool, etc., to an integer.
try:
val = int(tok)
except ValueError:
try:
val = float(tok)
except ValueError:
raise
return val
def convertToJavaId(id, noLeadingNumber=True, capitalizeFirst=False):
"""Convert the given string id to a legal java identifier,
by removing all non-alphanumeric characters (spaces,
pound signs, etc.). If noLeadingNumber is true, then
convert a leading digit to its corresponding name.
"""
res = ""
# Drop everything except letters and numbers.
# Upper case letters in the middle that follow a space,
# so that we get CamelCase-like results.
lastWasSpace = False
for ch in id:
if ch.isspace():
lastWasSpace = True
elif ch.isalpha() or ch.isdigit():
if lastWasSpace:
ch = ch.upper() # does nothing if isdigit.
lastWasSpace = False
res += ch
# Look to see if res starts with a digit.
if noLeadingNumber and res[0].isdigit():
digit2name = ("zero", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine")
res = digit2name[int(res[0])] + res[1:]
if capitalizeFirst and not res[0].isdigit():
res = res[0].upper() + res[1:]
# Ensure that the resulting name is not a java keyword
if res in JAVA_KEYWORDS:
res += '_'
return res
class Variable:
"""Represents a single variable defined in Scratch, and
includes properties of it: its name, type, what sprite
it belongs to, whether it is a cloud variable or not, its
uniqueId defined in Scratch, etc."""
# NOTE NOTE NOTE: there does not seem to be any information in the project.json
# file now about persistence, whether it is shown or not, slider, etc...
def __init__(self, uniqId, json):
"""json is of this format
[
"vic", <-- unsanitized scratch name
"44" <-- initial value
]
or for a list
[
"alist",
[ "firstitem", "seconditem" ]
]
"""
self._json = json
self._uniqId = uniqId
self._type = None
self._scratchName = json[0]
self._initValue = json[1]
self._isCloud = False
self._owner = None
self._local_or_global = None
self._gfName = None
# Stuff used for GUI when converting types, resolving
# names, etc.
self._nameEntry = None
self._typeStringVar = None
self._initValueEntry = None
# print(str(self))
allVars.append(self)
def setGfName(self, name):
self._gfName = name
def setType(self, type):
self._type = type
def setOwner(self, owner):
self._owner = owner
def setGlobal(self):
self._local_or_global = 'global'
def setLocal(self):
self._local_or_global = 'local'
def getName(self): return self._scratchName
def getInitValue(self): return self._initValue
def getOwner(self): return self._owner
def getType(self): return self._type
def getGfName(self): return self._gfName
def getUniqueId(self): return self._uniqId
def isLocal(self):
assert self._local_or_global is not None
return self._local_or_global == 'local'
def isGlobal(self):
assert self._local_or_global is not None
return self._local_or_global == 'global'
def setNameEntry(self, ent):
self._ent = ent
def setTypeStringVar(self, svar):
self._svar = svar
def setInitialValueEntry(self, ive):
self._initValueEntry = ive
def __str__(self):
return 'Variable with name %s, gfname %s, uniqId %s initValue %s owner %s' % (self._scratchName, self._gfName, self._uniqId, self._initValue, self._owner)
def getVariableBySpriteAndName(sprite, name):
for v in allVars:
if v.getOwner() == sprite and v.getName() == name:
return v
return None
def getVariableByUniqueId(id):
for v in allVars:
if v.getUniqueId() == id:
return v
return None
class Block:
"""
This represents a Scratch Block, with its opcode, parent,
children, inputs, etc.
"""
def __init__(self, id, opcode):
self._id = id
self._opcode = opcode
self._inputs = {}
self._fields = {}
self._topLevel = False
self._next = None
# dictionary mapping key -> child block.
self._children = {}
# Used for calling a user-defined procedure.
self._procCode = None
self._procArgIds = []
self._procDefnParamNames = []
def setInputs(self, inputs):
"""inputs are a json object (for now)"""
self._inputs = inputs
def setFields(self, fields):
"""fields are a json object (for now)"""
self._fields = fields
def setTopLevel(self, val):
self._topLevel = val
def setNext(self, blockObj):
self._next = blockObj
def setChild(self, key, childBlock):
if key in self._children:
raise ValueError('block has child with key %s already' % key)
self._children[key] = childBlock
def setProcCode(self, proccode):
self._procCode = proccode
def setProcCallArgIds(self, j):
self._procArgIds = json.loads(j)
def setProcDefnParamNames(self, j):
self._procDefnParamNames = json.loads(j)
def isTopLevel(self):
return self._topLevel
def hasChild(self, key):
return key in self._children
def getId(self):
return self._id
def getOpcode(self):
return self._opcode
def getNext(self):
return self._next
def getInputs(self):
return self._inputs
def getInput(self, key):
return self._inputs[key]
def getFields(self):
return self._fields
def getField(self, key, index=0):
return self.getFields()[key][index]
def hasField(self, key):
return key in self._fields
def getChild(self, key):
return self._children[key]
def getProcCode(self):
return self._procCode
def getProcCallArgIds(self):
return self._procArgIds
def getProcDefnParamNames(self):
return self._procDefnParamNames
def strWithIndent(self, indentLevel=0):
res = (" " * indentLevel) + str(self)
n = self._next
while n:
res += "\n" + str(n)
n = n._next
return res
def __str__(self):
return "BLOCK: " + self._opcode
class SpriteOrStage:
"""This is an abstract class that represents either a Stage class or
Sprite class to be generated in Java. The two are the same for
most/all script code generation. They differ primarily in the set up
code, constructor code, etc.
"""
def __init__(self, name, sprData):
"""Construct an object holding information about the sprite,
including code we are generating for it, its name, world
constructor code for it, etc.
"""
# The parsed json structure.
self._sprData = sprData
self._name = name
self._fileHeaderCode = ""
self._worldCtorCode = ""
self._ctorCode = ""
# The next 3 code strings are written into the constructor.
self._regCallbacksCode = ""
self._costumeCode = ""
self._initSettingsCode = ""
self._varDefnCode = ""
self._cbCode = []
self._addedToWorldCode = ""
# Remember if we've generated code for a copy constructor
# so that we don't do it multiple times.
self._copyConstructorMade = False
# A dictionary mapping variableName --> (sanitizedName, variableType).
# We need this so we can generate code that calls the correct
# functions to generate the correct type of results.
# E.g., if a variable is boolean, we'll call boolExpr()
# from setVariables(), not mathExpr().
# The name is the sanitized name.
self.varInfo = {}
self.listInfo = {}
print("\n----------- Sprite: %s ----------------" % self._name)
def copySounds(self, soundsDir):
# Move all of this sprites sounds to project/sounds/[spritename]
if 'sounds' in self._sprData:
if not os.path.exists(os.path.join(soundsDir, self.getName())):
os.makedirs(os.path.join(soundsDir, self.getName()))
for sound in self._sprData['sounds']:
soundName = sound['name']
id = sound['assetId']
if sound['format'] == 'adpcm':
print("Warning: Sound is in adpcm format and will not work:", soundName)
shutil.copyfile(os.path.join(PROJECT_DIR, SCRATCH_PROJ_DIR, str(id) + '.wav'),
os.path.join(soundsDir, self.getName(), soundName + '.wav'))
def getName(self):
return self._name
def getVarInfo(self, name):
"""Might return None if name not found in the mapping.
Otherwise, returns a tuple: (clean name, varType)"""
return self.varInfo.get(name)
def getListInfo(self, name):
"""Might return None if name not found in the mapping.
Otherwise, returns a tuple: (clean name, varType)"""
return self.listInfo.get(name)
def whenClicked(self, codeObj, block):
raise NotImplementedError('Implemented in subclass')
def genAddSpriteCall(self):
self._worldCtorCode += '%saddSprite("%s", %d, %d);\n' % \
(genIndent(2), self._name, self._sprData['x'], self._sprData['y'])
def getWorldCtorCode(self):
return self._worldCtorCode
def getCostumesCode(self):
return self._costumeCode
def genHeaderCode(self):
"""Generate code at the top of the output file -- imports, public class ..., etc."""
self._fileHeaderCode = "import greenfoot.*;\n\n"
self._fileHeaderCode += "/**\n * Write a description of class " + self._name + " here.\n"
self._fileHeaderCode += " * \n * @author (your name)\n * @version (a version number or a date)\n"
self._fileHeaderCode += " */\n"
self._fileHeaderCode += "public class " + self._name + " extends Scratch\n{\n"
def genConstructorCode(self):
"""Generate code for the constructor.
This code will include calls to initialize data, etc., followed by code
to register callbacks for whenFlagClicked,
whenKeyPressed, etc.
"""
self._ctorCode = genIndent(1) + "public " + self._name + "()\n"
self._ctorCode += genIndent(1) + "{\n"
self._ctorCode += self._costumeCode
self._ctorCode += self._initSettingsCode
self._ctorCode += self._regCallbacksCode
self._ctorCode += genIndent(1) + "}\n"
def genVariablesDefnCode(self, varsObjects, listsObjects, allChildren, cloudVars):
"""Generate code to define instance variables for this sprite.
The varsObjects is a list of dictionaries, one per variable (see below).
The allChildren is the list of dictionaries defined for this
project. It is necessary because sprites and their scripts (in a
dictionary with an "objName" key) are in children, also a dictionary
exists for each variable, with a "cmd" --> "getVar:" entry. We
need info from both the varsObjects and each of those other
variable-specific dictionaries.
"""
# TODO: fix all this documentation.
# The varsObjects has this format:
# [{ "name": "xloc",
# "value": false,
# "isPersistent": false
# }]
# We get the name and default value from this easily, but we have to derive
# A variable-specific dictionary (in 'children' list) has this format:
# {
# "target": "Sprite1",
# "cmd": "getVar:",
# "param": "xloc",
# "color": 15629590,
# "label": "Sprite1: xloc",
# "mode": 1,
# "sliderMin": 0,
# "sliderMax": 100,
# "isDiscrete": true,
# "x": 5,
# "y": 8,
# "visible": true
# },
#
# Algorithm:
# for each variable in the varsObjects list:
# o get the *name* and *value* out.
# o derive the *type* from the *value*.
# o find the variable's dictionary in allChildren, where
# the dictionary has 'cmd' -> 'getVar:' and 'param' -> *name* and
# 'target' -> *spriteName*. From that entry,
# o get *label*
# o get *x* and *y* location
# o get *visible*
# o generate the variable's definition.
# o generate the code in the constructor to create the variable with
# the initial value.
# o generate code to possibly hide() the variable.
# o NOTE: api does not support putting the variable at a x,y
# location. TODO
def genVariablesDefnCodeGui(listOfVars, listOfLists, allChildren, cloudVars):
"""Generate code to define instance variables for this sprite.
Uses a tkinter GUI to simplify the process
"""
nameList = []
typeList = []
valueList = []
self.ready = False
# Whenever the user presses a key, check validity of all fields
def keypress():
# Turns the text green if it's a valid name, red otherwise
self.ready = True
# track what names are in use
names = {}
for e in nameList:
# if this name is already in use turn both red
if e.get() in names.keys():
names[e.get()]['fg'] = 'red'
e['fg'] = 'red'
self.ready = False
# update the reference, this loses the old reference,
names[e.get()] = e
continue
# otherwise store the current name-entry pair
else:
names[e.get()] = e
# Check if the name is a valid java id
if re.match(r"[A-Za-z][A-Za-z0-9_]*$", e.get()):
e['fg'] = 'green'
else:
e['fg'] = 'red'
self.ready = False
# Check if the name is a java keyword
if e.get() in JAVA_KEYWORDS:
e['fg'] = 'red'
self.ready = False
for e in typeList:
# Ensure the type is valid
if not e.get().lower() in ('int', 'string', 'double'):
self.ready = False
for i in range(0, len(valueList)):
# Check if the current value is valid for the type specified
if typeList[i].get().lower() == 'string':
try:
str(valueList[i].get())
valueList[i]['fg'] = 'green'
except:
valueList[i]['fg'] = 'red'
self.ready = False
elif typeList[i].get().lower() == 'int':
try:
int(valueList[i].get())
valueList[i]['fg'] = 'green'
except:
valueList[i]['fg'] = 'red'
self.ready = False
elif typeList[i].get().lower() == 'double':
try:
float(valueList[i].get())
valueList[i]['fg'] = 'green'
except:
valueList[i]['fg'] = 'red'
self.ready = False
else:
valueList[i]['fg'] = 'blue'
self.ready = False
gui.after(25, keypress)
# Automatically convert names and determine types for all variables
def autoCB():
for e in nameList:
s = e.get()
e.delete(0, tkinter.END)
e.insert(tkinter.END, convertToJavaId(s))
for i in range(0, len(typeList)):
try:
typeList[i].set(deriveType("", valueList[i].get())[1])
except ValueError:
typeList[i].set("String")
keypress()
# Display a help message informing the user how to use the namer
def helpCB():
tkinter.messagebox.showinfo("Help",
"If a name is red, that means it is not valid in Java. Java variable names must " +
"start with a letter, and contain only letters, numbers and _. (No spaces!) There are also " +
"some words that can't be variable names because they mean something special in java: \n" +
str(JAVA_KEYWORDS) + ". \n\nIf a type " +
"is red, that means it is not a valid type. The types that work with this " +
"converter are:\n\tInt: a number that will never be a decimal\n\tDouble: a number " +
"that can be a decimal\n\tString: symbols, letters, and text\n\nIf a value is red, " +
"that means that the variable cannot store that value. For example, an Int " +
"cannot store the value 1.5, since it has to store whole numbers.")
# Write out the results to the file
def confirmCB():
global cloudVars
if not self.ready:
tkinter.messagebox.showerror("Error", "Some of the inputs are still invalid. Click help for more " + \
"details on how to fix them.")
gui.focus_set()
return
for i in range(len(listOfVars)): # var is a dictionary.
var = listOfVars[i]
name = var['name'] # unsanitized Scratch name
value = var['value']
cloud = var['isPersistent']
print(("Processing var: " + name).encode('utf-8'))
# return the varType and the value converted to a java equivalent
# for that type. (e.g., False --> false)
# varType is one of 'Boolean', 'Double', 'Int', 'String'
varType = typeList[i].get().title()
if cloud:
value = cloudVars
cloudVars += 1
varType = 'Cloud'
# The first character is a weird Unicode cloud glyph and the
# second is a space. Get rid of them.
name = name[2:]
# Sanitize the name: make it a legal Java identifier.
sanname = nameList[i].get()
# We need this so we can generate code that calls the correct
# functions to generate the correct type of results.
# E.g., if a variable is boolean, we'll call boolExpr()
# from setVariables(), not mathExpr().
# Record a mapping from unsanitized name --> (sanitized name, type)
self.varInfo[name] = (sanname, varType)
if True:
print("Adding varInfo entry for", self._name, ":", name,
"--> (" + sanname + ", " + varType + ")")
for aDict in allChildren:
if aDict.get('cmd') == 'getVar:' and \
aDict.get('param') == name and \
aDict.get('target') == self._name:
varInfo = aDict
# If variable definition dictionary found, use it
label = varInfo['label']
x = varInfo['x'] # Not used at this time.
y = varInfo['y'] # Not used at this time.
visible = varInfo['visible']
break
else:
if cloud:
# Cloud variables do not have a definition dictionary, so use default
# values.
label = name
x = 0
y = 0
visible = True
else:
# If no variable dict could be found, this variable is never shown
# so these values don't matter
label = "unknown: " + name
x = 0
y = 0
visible = False
print("No variable definition dictionary found in script json:", name)
# TODO: FIX THIS: move code into subclass!!!
# Something like "Scratch.IntVar score; or ScratchWorld.IntVar score;"
if self.getNameTypeAndLocalGlobal(name)[2]:
self._varDefnCode += genIndent(1) + 'static %sVar %s;\n' % (varType, sanname)
else:
self._varDefnCode += genIndent(1) + "%sVar %s;\n" % (varType, sanname)
# Escape any quotes in the label
label = re.sub('"', '\\"', label)
if varType.lower() == "string":
# Escape any quotes, and add make it a string literal
value = '"' + re.sub('"', '\\"', value) + '"'
# Something like "score = createIntVariable((MyWorld) world, "score", 0);
self._addedToWorldCode += '%s%s = create%sVariable((%s) world, "%s", %s);\n' % \
(genIndent(2), sanname, varType, worldClassName, label, str(value))
if not visible:
self._addedToWorldCode += genIndent(2) + sanname + ".hide();\n"
# Add blank line after variable definitions.
self._varDefnCode += "\n"
self._addedToWorldCode += genIndent(2) + "// List initializations.\n"
for l in listOfLists:
name = l['listName']
contents = l['contents']
visible = l['visible']
try:
sanname = convertToJavaId(name)
except:
print("Error converting list to java id")
sys.exit(0)
self.listInfo[name] = sanname
# I know this is bad style, but at the moment it's necessary
# Later down the line we can move all this code to subclasses instead
if type(self) == Stage:
self._varDefnCode += genIndent(1) + 'static ScratchList %s;\n' % (sanname)
else:
self._varDefnCode += genIndent(1) + "ScratchList %s;\n" % (sanname)
self._addedToWorldCode += '%s%s = createList(world, "%s"' % (genIndent(2), sanname, name)
for obj in contents:
disp = deriveType(name, obj)
self._addedToWorldCode += ', %s' % (str(disp[0]))
self._addedToWorldCode += ');\n'
if not visible:
self._addedToWorldCode += '%s%s.hide();\n' % (genIndent(2), sanname)
# Close the addedToWorld() method definition.
self._addedToWorldCode += genIndent(1) + "}\n"
# Return focus and execution back to the main window
root.focus_set()
gui.quit()
gui.destroy()
# --------------- genVariablesDefnCodeGui main ------------------------------------
gui = tkinter.Toplevel(root)
# gui.bind("<Any-KeyPress>", keypress)
gui.title("Variable Namer")
gui.grab_set()
table = tkinter.Frame(gui)
table.pack()
buttons = tkinter.Frame(gui)
buttons.pack(side=tkinter.BOTTOM)
auto = tkinter.Button(buttons, text="Auto-Convert", command=autoCB)
auto.pack(side=tkinter.LEFT)
confirm = tkinter.Button(buttons, text="Confirm", command=confirmCB)
confirm.pack(side=tkinter.LEFT)
help = tkinter.Button(buttons, text="Help", command=helpCB)
help.pack(side=tkinter.LEFT)
tkinter.Label(table, text=" Scratch Name ").grid(row=0, column=0)
tkinter.Label(table, text="Java Name").grid(row=0, column=1)
tkinter.Label(table, text="Java Type").grid(row=0, column=2)
tkinter.Label(table, text="Starting Value").grid(row=0, column=3)
# Populate lists
row = 1
for var in listOfVars:
name = var['name'] # unsanitized Scratch name
value = var['value']
cloud = var['isPersistent']
lbl = tkinter.Entry(table)
lbl.insert(tkinter.END, name)
lbl.configure(state="readonly")
lbl.grid(row=row, column=0, sticky=tkinter.W + tkinter.E)
ent = tkinter.Entry(table)
ent.insert(tkinter.END, name)
ent.grid(row=row, column=1, sticky=tkinter.W + tkinter.E)
nameList.append(ent)
svar = tkinter.StringVar(gui)
ent2 = tkinter.OptionMenu(table, svar, "Int", "Double", "String")
ent2.grid(row=row, column=2, sticky=tkinter.W + tkinter.E)
# ent2.bind("<Button-1>", keypress)
typeList.append(svar)
ent3 = tkinter.Entry(table)
ent3.insert(tkinter.END, value)
ent3.grid(row=row, column=3, sticky=tkinter.W + tkinter.E)
valueList.append(ent3)
row += 1
# Update the text color
keypress()
gui.mainloop()
def chooseType(name, val):
i, typechosen = deriveType(name, val)
while not inference:
try:
print("\n\nWhat type of variable should \"" + name + "\": " + str(val) + " be?")
theType = input("\tInt: A number that won't have decimals\n\tDouble:" +
" A number that can have decimals\n\tString: Text or letters\n" +
"This variable looks like: " + typechosen +
"\nPress enter without typing anything to use suggested type\n> ").capitalize()
# Try to convert the value to the chosen type, only the first character needs to be entered
if theType[0] == 'I':
return int(val), 'Int'
elif theType[0] == 'D':
return float(val), 'Double'
elif theType[0] == 'S':
return '"' + str(val) + '"', "String"
# If ? is chosen, continue with automatic derivation
elif theType == "?":
break
print(theType, "not recognized, please choose one of these (Int,Double,String)")
except IndexError:
# Nothing was entered
break
except:
# If val is not able to be converted to type, it will be set to default, or the user may choose
# a different type.
if input("Could not convert " + str(val) + " to " + theType +
" Set to default value? (y/n)\n> ") == "y":
if theType[0] == 'I':
return (0, 'Int')
elif theType[0] == 'F':
return 0.0, 'Double'
elif theType[0] == 'S':
return '""', "String"
return deriveType(name, val)
def deriveType(name, val):
if isinstance(val, str):
#
# See if the string value is a legal integer or floating point number.
# If it is, assume it should be that. This seems to be what Scratch
# does -- represents things as strings, but if legal, treats them
# as numbers.
#
try:
i = int(val)
return i, 'Int'
except:
pass
try:
f = float(val)
return f, 'Double'
except:
pass
return '"' + val + '"', 'String'
elif isinstance(val, bool):
if val:
return "true", 'Boolean'
else:
return "false", 'Boolean'
elif isinstance(val, int):
return val, 'Int'
elif isinstance(val, float):
return val, 'Double'
else:
raise ValueError("deriveType cannot figure out type of -->" +
str(val) + "<--")
# -------------------------- genVariablesDefnCode main starts here -----------------------------
# create an object for each variable and store in a list.
# Each variable definition block looks like this:
# "jd59I%YWo]3`[L`d?tD[": [ <-- unique id
# "vic", <-- name
# "44" <-- initial value
# ]
theseVars = [Variable(varId, varsObjects[varId]) for varId in varsObjects]
#
# Initialization goes into the method addedToWorld() for Sprites, but
# into the ctor for World.
#
self._addedToWorldCode += "\n" + genIndent(1) + "private " + worldClassName + " world;"
self._addedToWorldCode += "\n" + genIndent(1) + "public void addedToWorld(World w)\n"
self._addedToWorldCode += genIndent(1) + "{\n"
self._addedToWorldCode += genIndent(2) + "world = (" + worldClassName + ") w;\n"
self._addedToWorldCode += genIndent(2) + "super.addedToWorld(w);\n"
self._addedToWorldCode += genIndent(2) + "// Variable initializations.\n"
# If running in gui mode, call the gui method instead
if useGui:
genVariablesDefnCodeGui(varsObjects, listsObjects, allChildren, cloudVars)
return
for var in theseVars:
name = var.getName() # unsanitized Scratch name
value = var.getInitValue()
cloud = False # TODO var['isPersistent']
# return the varType and the value converted to a java equivalent
# for that type. (e.g., False --> false)
# varType is one of 'Boolean', 'Double', 'Int', 'String'
if cloud: # TODO: this is always False for now.
value = cloudVars
cloudVars += 1
varType = 'Cloud'
# The first character is a weird Unicode cloud glyph and the
# second is a space. Get rid of them.
name = name[2:]
else:
value, varType = chooseType(name, value)
var.setType(varType)
# Sanitize the name: make it a legal Java identifier.
try:
if name_resolution:
sanname = convertToJavaId(name)
elif not convertToJavaId(name) == name:
sanname = self.resolveName(name)
else:
sanname = convertToJavaId(name)
except:
print("Error converting variable to java id")
sys.exit(0)
var.setGfName(sanname)
self.setVariableIsLocalOrGlobal(var)
var.setOwner(self)
'''
for aDict in allChildren:
if aDict.get('cmd') == 'getVar:' and \
aDict.get('param') == name and \
aDict.get('target') == self._name:
varInfo = aDict
# If variable definition dictionary found, use it
label = varInfo['label']
x = varInfo['x'] # Not used at this time.
y = varInfo['y'] # Not used at this time.
visible = varInfo['visible']
break
else:
if cloud:
# Cloud variables do not have a definition dictionary, so use default
# values.
label = name
x = 0
y = 0
visible = True
else:
# If no variable dict could be found, this variable is never shown
# so these values don't matter
label = "unknown: " + name
x = 0
y = 0
visible = False
print("No variable definition dictionary found in script json:", name)
'''
# Something like "Scratch.IntVar score; or ScratchWorld.IntVar score;"
self._varDefnCode += self.genVarDefnCode(1, var)
# Something like "score = createIntVariable((MyWorld) world, "score", 0);
self._addedToWorldCode += '%s%s = create%sVariable((%s) world, "%s", %s);\n' % \
(genIndent(2), sanname, varType, worldClassName, name, str(value))
# if not visible:
# self._addedToWorldCode += genIndent(2) + sanname + ".hide();\n"
# Add blank line after variable definitions.
self._varDefnCode += "\n"
self._addedToWorldCode += genIndent(2) + "// List initializations.\n"