@blockdia/scratch-blocks 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (243) hide show
  1. package/.nvmrc +1 -0
  2. package/LICENSE +674 -0
  3. package/README.md +57 -0
  4. package/TRADEMARK +1 -0
  5. package/blockly_compressed_horizontal.js +2268 -0
  6. package/blockly_compressed_vertical.js +2296 -0
  7. package/blockly_uncompressed_horizontal.js +1212 -0
  8. package/blockly_uncompressed_vertical.js +1212 -0
  9. package/blocks_common/colour.js +61 -0
  10. package/blocks_common/math.js +159 -0
  11. package/blocks_common/matrix.js +54 -0
  12. package/blocks_common/note.js +58 -0
  13. package/blocks_common/text.js +57 -0
  14. package/blocks_compressed.js +37 -0
  15. package/blocks_compressed_horizontal.js +68 -0
  16. package/blocks_compressed_vertical.js +216 -0
  17. package/blocks_horizontal/control.js +212 -0
  18. package/blocks_horizontal/default_toolbox.js +139 -0
  19. package/blocks_horizontal/event.js +190 -0
  20. package/blocks_horizontal/wedo.js +325 -0
  21. package/blocks_vertical/control.js +532 -0
  22. package/blocks_vertical/data.js +666 -0
  23. package/blocks_vertical/default_toolbox.js +571 -0
  24. package/blocks_vertical/event.js +329 -0
  25. package/blocks_vertical/extensions.js +294 -0
  26. package/blocks_vertical/looks.js +591 -0
  27. package/blocks_vertical/motion.js +587 -0
  28. package/blocks_vertical/operators.js +470 -0
  29. package/blocks_vertical/procedures.js +1051 -0
  30. package/blocks_vertical/sensing.js +555 -0
  31. package/blocks_vertical/sound.js +246 -0
  32. package/blocks_vertical/vertical_extensions.js +289 -0
  33. package/build/gen_blocks.js +1 -0
  34. package/build/test_expect.js +1 -0
  35. package/build/test_input.js +1 -0
  36. package/build.py +647 -0
  37. package/cleanup.sh +101 -0
  38. package/core/block.js +1837 -0
  39. package/core/block_animations.js +107 -0
  40. package/core/block_drag_surface.js +299 -0
  41. package/core/block_dragger.js +424 -0
  42. package/core/block_events.js +531 -0
  43. package/core/block_render_svg_horizontal.js +892 -0
  44. package/core/block_render_svg_vertical.js +1734 -0
  45. package/core/block_svg.js +1355 -0
  46. package/core/blockly.js +620 -0
  47. package/core/blocks.js +37 -0
  48. package/core/bubble.js +664 -0
  49. package/core/bubble_dragger.js +285 -0
  50. package/core/colours.js +177 -0
  51. package/core/comment.js +293 -0
  52. package/core/comment_events.js +539 -0
  53. package/core/connection.js +776 -0
  54. package/core/connection_db.js +300 -0
  55. package/core/constants.js +408 -0
  56. package/core/contextmenu.js +534 -0
  57. package/core/css.js +1354 -0
  58. package/core/data_category.js +490 -0
  59. package/core/dragged_connection_manager.js +260 -0
  60. package/core/dropdowndiv.js +408 -0
  61. package/core/events.js +429 -0
  62. package/core/events_abstract.js +113 -0
  63. package/core/extensions.js +450 -0
  64. package/core/field.js +810 -0
  65. package/core/field_angle.js +410 -0
  66. package/core/field_checkbox.js +133 -0
  67. package/core/field_colour.js +253 -0
  68. package/core/field_colour_slider.js +387 -0
  69. package/core/field_date.js +353 -0
  70. package/core/field_dropdown.js +447 -0
  71. package/core/field_iconmenu.js +309 -0
  72. package/core/field_image.js +200 -0
  73. package/core/field_label.js +136 -0
  74. package/core/field_label_serializable.js +125 -0
  75. package/core/field_matrix.js +566 -0
  76. package/core/field_note.js +850 -0
  77. package/core/field_number.js +366 -0
  78. package/core/field_numberdropdown.js +77 -0
  79. package/core/field_textdropdown.js +164 -0
  80. package/core/field_textinput.js +675 -0
  81. package/core/field_textinput_removable.js +105 -0
  82. package/core/field_variable.js +385 -0
  83. package/core/field_variable_getter.js +185 -0
  84. package/core/field_vertical_separator.js +161 -0
  85. package/core/flyout_base.js +935 -0
  86. package/core/flyout_button.js +324 -0
  87. package/core/flyout_dragger.js +83 -0
  88. package/core/flyout_extension_category_header.js +159 -0
  89. package/core/flyout_horizontal.js +475 -0
  90. package/core/flyout_vertical.js +770 -0
  91. package/core/generator.js +426 -0
  92. package/core/gesture.js +1010 -0
  93. package/core/grid.js +227 -0
  94. package/core/icon.js +205 -0
  95. package/core/inject.js +496 -0
  96. package/core/input.js +285 -0
  97. package/core/insertion_marker_manager.js +678 -0
  98. package/core/intersection_observer.js +102 -0
  99. package/core/msg.js +62 -0
  100. package/core/mutator.js +426 -0
  101. package/core/names.js +198 -0
  102. package/core/options.js +244 -0
  103. package/core/procedures.js +739 -0
  104. package/core/rendered_connection.js +417 -0
  105. package/core/scratch_block_comment.js +646 -0
  106. package/core/scratch_blocks_utils.js +246 -0
  107. package/core/scratch_bubble.js +699 -0
  108. package/core/scratch_events.js +131 -0
  109. package/core/scratch_msgs.js +85 -0
  110. package/core/scrollbar.js +875 -0
  111. package/core/toolbox.js +803 -0
  112. package/core/tooltip.js +337 -0
  113. package/core/touch.js +226 -0
  114. package/core/trashcan.js +343 -0
  115. package/core/ui_events.js +91 -0
  116. package/core/ui_menu_utils.js +68 -0
  117. package/core/utils.js +825 -0
  118. package/core/variable_events.js +259 -0
  119. package/core/variable_map.js +415 -0
  120. package/core/variable_model.js +116 -0
  121. package/core/variables.js +674 -0
  122. package/core/warning.js +199 -0
  123. package/core/widgetdiv.js +344 -0
  124. package/core/workspace.js +673 -0
  125. package/core/workspace_audio.js +170 -0
  126. package/core/workspace_comment.js +426 -0
  127. package/core/workspace_comment_render_svg.js +706 -0
  128. package/core/workspace_comment_svg.js +609 -0
  129. package/core/workspace_drag_surface_svg.js +195 -0
  130. package/core/workspace_dragger.js +132 -0
  131. package/core/workspace_svg.js +2382 -0
  132. package/core/xml.js +930 -0
  133. package/core/zoom_controls.js +301 -0
  134. package/dist/horizontal.js +222 -0
  135. package/dist/vertical.js +222 -0
  136. package/dist/web/horizontal.js +232 -0
  137. package/dist/web/vertical.js +232 -0
  138. package/i18n/common.py +234 -0
  139. package/i18n/create_messages.py +162 -0
  140. package/i18n/create_scratch_msgs.js +69 -0
  141. package/i18n/dedup_json.py +73 -0
  142. package/i18n/js_to_json.js +46 -0
  143. package/i18n/js_to_json.py +136 -0
  144. package/i18n/json_to_js.js +52 -0
  145. package/i18n/json_to_js.py +185 -0
  146. package/i18n/sync_tx_translations.js +111 -0
  147. package/i18n/test_scratch_msgs.js +87 -0
  148. package/i18n/tests.py +47 -0
  149. package/i18n/xliff_to_json.py +232 -0
  150. package/local_build.sh +70 -0
  151. package/media/click.mp3 +0 -0
  152. package/media/click.ogg +0 -0
  153. package/media/click.wav +0 -0
  154. package/media/comment-arrow-down.svg +10 -0
  155. package/media/comment-arrow-up.svg +10 -0
  156. package/media/delete-x.svg +10 -0
  157. package/media/delete.mp3 +0 -0
  158. package/media/delete.ogg +0 -0
  159. package/media/delete.wav +0 -0
  160. package/media/dropdown-arrow-dark.svg +1 -0
  161. package/media/dropdown-arrow.svg +1 -0
  162. package/media/extensions/microbit-block-icon.svg +130 -0
  163. package/media/extensions/music-block-icon.svg +17 -0
  164. package/media/extensions/pen-block-icon.svg +19 -0
  165. package/media/extensions/wedo2-block-icon.svg +36 -0
  166. package/media/eyedropper.svg +22 -0
  167. package/media/green-flag.svg +17 -0
  168. package/media/handclosed.cur +0 -0
  169. package/media/handdelete.cur +0 -0
  170. package/media/handopen.cur +0 -0
  171. package/media/icons/arrow.svg +12 -0
  172. package/media/icons/arrow_button.svg +1 -0
  173. package/media/icons/control_forever.svg +1 -0
  174. package/media/icons/control_repeat.svg +1 -0
  175. package/media/icons/control_stop.svg +1 -0
  176. package/media/icons/control_wait.svg +1 -0
  177. package/media/icons/event_broadcast_blue.svg +1 -0
  178. package/media/icons/event_broadcast_coral.svg +1 -0
  179. package/media/icons/event_broadcast_green.svg +1 -0
  180. package/media/icons/event_broadcast_magenta.svg +1 -0
  181. package/media/icons/event_broadcast_orange.svg +1 -0
  182. package/media/icons/event_broadcast_purple.svg +1 -0
  183. package/media/icons/event_when-broadcast-received_blue.svg +1 -0
  184. package/media/icons/event_when-broadcast-received_coral.svg +1 -0
  185. package/media/icons/event_when-broadcast-received_green.svg +1 -0
  186. package/media/icons/event_when-broadcast-received_magenta.svg +1 -0
  187. package/media/icons/event_when-broadcast-received_orange.svg +1 -0
  188. package/media/icons/event_when-broadcast-received_purple.svg +1 -0
  189. package/media/icons/event_whenflagclicked.svg +1 -0
  190. package/media/icons/remove.svg +19 -0
  191. package/media/icons/set-led_blue.svg +1 -0
  192. package/media/icons/set-led_coral.svg +1 -0
  193. package/media/icons/set-led_green.svg +1 -0
  194. package/media/icons/set-led_magenta.svg +1 -0
  195. package/media/icons/set-led_mystery.svg +1 -0
  196. package/media/icons/set-led_orange.svg +1 -0
  197. package/media/icons/set-led_purple.svg +1 -0
  198. package/media/icons/set-led_white.svg +1 -0
  199. package/media/icons/set-led_yellow.svg +1 -0
  200. package/media/icons/wedo_motor-clockwise.svg +1 -0
  201. package/media/icons/wedo_motor-counterclockwise.svg +1 -0
  202. package/media/icons/wedo_motor-speed_fast.svg +1 -0
  203. package/media/icons/wedo_motor-speed_med.svg +1 -0
  204. package/media/icons/wedo_motor-speed_slow.svg +1 -0
  205. package/media/icons/wedo_when-distance_close.svg +1 -0
  206. package/media/icons/wedo_when-tilt-backward.svg +1 -0
  207. package/media/icons/wedo_when-tilt-forward.svg +1 -0
  208. package/media/icons/wedo_when-tilt-left.svg +1 -0
  209. package/media/icons/wedo_when-tilt-right.svg +1 -0
  210. package/media/icons/wedo_when-tilt.svg +1 -0
  211. package/media/repeat.svg +18 -0
  212. package/media/rotate-left.svg +1 -0
  213. package/media/rotate-right.svg +1 -0
  214. package/media/sprites.png +0 -0
  215. package/media/status-not-ready.svg +13 -0
  216. package/media/status-ready.svg +13 -0
  217. package/media/zoom-in.svg +1 -0
  218. package/media/zoom-out.svg +1 -0
  219. package/media/zoom-reset.svg +1 -0
  220. package/msg/js/en.js +290 -0
  221. package/msg/json/en.json +285 -0
  222. package/msg/messages.js +359 -0
  223. package/msg/scratch_msgs.js +22969 -0
  224. package/package.json +60 -0
  225. package/pull_from_blockly.sh +151 -0
  226. package/renovate.json5 +15 -0
  227. package/shim/blockly_compressed_horizontal-blocks_compressed.js +1 -0
  228. package/shim/blockly_compressed_horizontal.Blockly.js +1 -0
  229. package/shim/blockly_compressed_horizontal.goog.js +1 -0
  230. package/shim/blockly_compressed_horizontal.js +1 -0
  231. package/shim/blockly_compressed_vertical-blocks_compressed.js +1 -0
  232. package/shim/blockly_compressed_vertical.Blockly.js +1 -0
  233. package/shim/blockly_compressed_vertical.goog.js +1 -0
  234. package/shim/blockly_compressed_vertical.js +1 -0
  235. package/shim/blocks_compressed_horizontal-blockly_compressed_horizontal-messages.js +1 -0
  236. package/shim/blocks_compressed_horizontal.js +1 -0
  237. package/shim/blocks_compressed_vertical-blockly_compressed_vertical-messages.js +1 -0
  238. package/shim/blocks_compressed_vertical.js +1 -0
  239. package/shim/gh-pages.js +1 -0
  240. package/shim/horizontal.js +1 -0
  241. package/shim/index.js +17 -0
  242. package/shim/vertical.js +1 -0
  243. package/universal-python.js +82 -0
package/build.py ADDED
@@ -0,0 +1,647 @@
1
+ #!/usr/bin/python2.7
2
+ # Compresses the core Blockly files into a single JavaScript file.
3
+ #
4
+ # Copyright 2012 Google Inc.
5
+ # https://developers.google.com/blockly/
6
+ #
7
+ # Licensed under the Apache License, Version 2.0 (the "License");
8
+ # you may not use this file except in compliance with the License.
9
+ # You may obtain a copy of the License at
10
+ #
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+ #
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+
19
+ # This script generates two versions of Blockly's core files:
20
+ # blockly_compressed.js
21
+ # blockly_uncompressed.js
22
+ # The compressed file is a concatenation of all of Blockly's core files which
23
+ # have been run through Google's Closure Compiler. This is done using the
24
+ # online API (which takes a few seconds and requires an Internet connection).
25
+ # The uncompressed file is a script that loads in each of Blockly's core files
26
+ # one by one. This takes much longer for a browser to load, but is useful
27
+ # when debugging code since line numbers are meaningful and variables haven't
28
+ # been renamed. The uncompressed file also allows for a faster developement
29
+ # cycle since there is no need to rebuild or recompile, just reload.
30
+ #
31
+ # This script also generates:
32
+ # blocks_compressed.js: The compressed common blocks.
33
+ # blocks_horizontal_compressed.js: The compressed Scratch horizontal blocks.
34
+ # blocks_vertical_compressed.js: The compressed Scratch vertical blocks.
35
+ # msg/js/<LANG>.js for every language <LANG> defined in msg/js/<LANG>.json.
36
+
37
+ import sys
38
+
39
+ import errno, glob, json, os, re, subprocess, threading, codecs, functools, platform
40
+
41
+ if sys.version_info[0] == 2:
42
+ import httplib
43
+ from urllib import urlencode
44
+ else:
45
+ import http.client as httplib
46
+ from urllib.parse import urlencode
47
+ from importlib import reload
48
+
49
+ REMOTE_COMPILER = "remote"
50
+
51
+ CLOSURE_DIR = os.path.pardir
52
+ CLOSURE_ROOT = os.path.pardir
53
+ CLOSURE_LIBRARY = "closure-library"
54
+ CLOSURE_COMPILER = REMOTE_COMPILER
55
+
56
+ CLOSURE_DIR_NPM = "node_modules"
57
+ CLOSURE_ROOT_NPM = os.path.join("node_modules")
58
+ CLOSURE_LIBRARY_NPM = "google-closure-library"
59
+ CLOSURE_COMPILER_NPM = ("google-closure-compiler.cmd" if os.name == "nt" else "google-closure-compiler")
60
+
61
+ def import_path(fullpath):
62
+ """Import a file with full path specification.
63
+ Allows one to import from any directory, something __import__ does not do.
64
+
65
+ Args:
66
+ fullpath: Path and filename of import.
67
+
68
+ Returns:
69
+ An imported module.
70
+ """
71
+ path, filename = os.path.split(fullpath)
72
+ filename, ext = os.path.splitext(filename)
73
+ sys.path.append(path)
74
+ module = __import__(filename)
75
+ reload(module) # Might be out of date.
76
+ del sys.path[-1]
77
+ return module
78
+
79
+ def read(filename):
80
+ f = open(filename)
81
+ content = "".join(f.readlines())
82
+ f.close()
83
+ return content
84
+
85
+ HEADER = ("// Do not edit this file; automatically generated by build.py.\n"
86
+ "'use strict';\n")
87
+
88
+
89
+ class Gen_uncompressed(threading.Thread):
90
+ """Generate a JavaScript file that loads Blockly's raw files.
91
+ Runs in a separate thread.
92
+ """
93
+ def __init__(self, search_paths, vertical, closure_env):
94
+ threading.Thread.__init__(self)
95
+ self.search_paths = search_paths
96
+ self.vertical = vertical
97
+ self.closure_env = closure_env
98
+
99
+ def run(self):
100
+ if self.vertical:
101
+ target_filename = 'blockly_uncompressed_vertical.js'
102
+ else:
103
+ target_filename = 'blockly_uncompressed_horizontal.js'
104
+ f = open(target_filename, 'w')
105
+ f.write(HEADER)
106
+ f.write(self.format_js("""
107
+ var isNodeJS = !!(typeof module !== 'undefined' && module.exports &&
108
+ typeof window === 'undefined');
109
+
110
+ if (isNodeJS) {
111
+ var window = {};
112
+ require('{closure_library}');
113
+ }
114
+
115
+ window.BLOCKLY_DIR = (function() {
116
+ if (!isNodeJS) {
117
+ // Find name of current directory.
118
+ var scripts = document.getElementsByTagName('script');
119
+ var re = new RegExp('(.+)[\\/]blockly_uncompressed(_vertical|_horizontal|)\\.js$');
120
+ for (var i = 0, script; script = scripts[i]; i++) {
121
+ var match = re.exec(script.src);
122
+ if (match) {
123
+ return match[1];
124
+ }
125
+ }
126
+ alert('Could not detect Blockly\\'s directory name.');
127
+ }
128
+ return '';
129
+ })();
130
+
131
+ window.BLOCKLY_BOOT = function() {
132
+ var dir = '';
133
+ if (isNodeJS) {
134
+ require('{closure_library}');
135
+ dir = 'blockly';
136
+ } else {
137
+ // Execute after Closure has loaded.
138
+ if (!window.goog) {
139
+ alert('Error: Closure not found. Read this:\\n' +
140
+ 'developers.google.com/blockly/guides/modify/web/closure');
141
+ }
142
+ if (window.BLOCKLY_DIR.search(/node_modules/)) {
143
+ dir = '..';
144
+ } else {
145
+ dir = window.BLOCKLY_DIR.match(/[^\\/]+$/)[0];
146
+ }
147
+ }
148
+ """))
149
+ add_dependency = []
150
+ base_path = calcdeps.FindClosureBasePath(self.search_paths)
151
+ for dep in calcdeps.BuildDependenciesFromFiles(self.search_paths):
152
+ add_dependency.append(calcdeps.GetDepsLine(dep, base_path))
153
+ add_dependency.sort() # Deterministic build.
154
+ add_dependency = '\n'.join(add_dependency)
155
+ # Find the Blockly directory name and replace it with a JS variable.
156
+ # This allows blockly_uncompressed.js to be compiled on one computer and be
157
+ # used on another, even if the directory name differs.
158
+ m = re.search('[\\/]([^\\/]+)[\\/]core[\\/]blockly.js', add_dependency)
159
+ add_dependency = re.sub('([\\/])' + re.escape(m.group(1)) +
160
+ '([\\/]core[\\/])', '\\1" + dir + "\\2', add_dependency)
161
+ f.write(add_dependency + '\n')
162
+
163
+ provides = []
164
+ for dep in calcdeps.BuildDependenciesFromFiles(self.search_paths):
165
+ # starts with '../' or 'node_modules/'
166
+ if not dep.filename.startswith(self.closure_env["closure_root"] + os.sep):
167
+ provides.extend(dep.provides)
168
+ provides.sort() # Deterministic build.
169
+ f.write('\n')
170
+ f.write('// Load Blockly.\n')
171
+ for provide in provides:
172
+ f.write("goog.require('%s');\n" % provide)
173
+
174
+ f.write(self.format_js("""
175
+ delete this.BLOCKLY_DIR;
176
+ delete this.BLOCKLY_BOOT;
177
+ };
178
+
179
+ if (isNodeJS) {
180
+ window.BLOCKLY_BOOT();
181
+ module.exports = Blockly;
182
+ } else {
183
+ // Delete any existing Closure (e.g. Soy's nogoog_shim).
184
+ document.write('<script>var goog = undefined;</script>');
185
+ // Load fresh Closure Library.
186
+ document.write('<script src="' + window.BLOCKLY_DIR +
187
+ '/{closure_dir}/{closure_library}/closure/goog/base.js"></script>');
188
+ document.write('<script>window.BLOCKLY_BOOT();</script>');
189
+ }
190
+ """))
191
+ f.close()
192
+ print("SUCCESS: " + target_filename)
193
+
194
+ def format_js(self, code):
195
+ """Format JS in a way that python's format method can work with to not
196
+ consider brace-wrapped sections to be format replacements while still
197
+ replacing known keys.
198
+ """
199
+
200
+ key_whitelist = self.closure_env.keys()
201
+
202
+ keys_pipe_separated = functools.reduce(lambda accum, key: accum + "|" + key, key_whitelist)
203
+ begin_brace = re.compile(r"\{(?!%s)" % (keys_pipe_separated,))
204
+
205
+ end_brace = re.compile(r"\}")
206
+ def end_replacement(match):
207
+ try:
208
+ maybe_key = match.string[match.string[:match.start()].rindex("{") + 1:match.start()]
209
+ except ValueError:
210
+ return "}}"
211
+
212
+ if maybe_key and maybe_key in key_whitelist:
213
+ return "}"
214
+ else:
215
+ return "}}"
216
+
217
+ return begin_brace.sub("{{", end_brace.sub(end_replacement, code)).format(**self.closure_env)
218
+
219
+ class Gen_compressed(threading.Thread):
220
+ """Generate a JavaScript file that contains all of Blockly's core and all
221
+ required parts of Closure, compiled together.
222
+ Uses the Closure Compiler's online API.
223
+ Runs in a separate thread.
224
+ """
225
+ def __init__(self, search_paths_vertical, search_paths_horizontal, closure_env):
226
+ threading.Thread.__init__(self)
227
+ self.search_paths_vertical = search_paths_vertical
228
+ self.search_paths_horizontal = search_paths_horizontal
229
+ self.closure_env = closure_env
230
+
231
+ def run(self):
232
+ self.gen_core(True)
233
+ self.gen_core(False)
234
+ self.gen_blocks("horizontal")
235
+ self.gen_blocks("vertical")
236
+ self.gen_blocks("common")
237
+
238
+ def gen_core(self, vertical):
239
+ if vertical:
240
+ target_filename = 'blockly_compressed_vertical.js'
241
+ search_paths = self.search_paths_vertical
242
+ else:
243
+ target_filename = 'blockly_compressed_horizontal.js'
244
+ search_paths = self.search_paths_horizontal
245
+ # Define the parameters for the POST request.
246
+ params = [
247
+ ("compilation_level", "SIMPLE"),
248
+
249
+ # remote will filter this out
250
+ ("language_in", "ECMASCRIPT_2017"),
251
+ ("language_out", "ECMASCRIPT5"),
252
+ ("rewrite_polyfills", "false"),
253
+ ("define", "goog.DEBUG=false"),
254
+
255
+ # local will filter this out
256
+ ("use_closure_library", "true"),
257
+ ]
258
+
259
+ # Read in all the source files.
260
+ filenames = calcdeps.CalculateDependencies(search_paths,
261
+ [os.path.join("core", "blockly.js")])
262
+ filenames.sort() # Deterministic build.
263
+ for filename in filenames:
264
+ # Append filenames as false arguments the step before compiling will
265
+ # either transform them into arguments for local or remote compilation
266
+ params.append(("js_file", filename))
267
+
268
+ self.do_compile(params, target_filename, filenames, "")
269
+
270
+ def gen_blocks(self, block_type):
271
+ if block_type == "horizontal":
272
+ target_filename = "blocks_compressed_horizontal.js"
273
+ filenames = glob.glob(os.path.join("blocks_horizontal", "*.js"))
274
+ elif block_type == "vertical":
275
+ target_filename = "blocks_compressed_vertical.js"
276
+ filenames = glob.glob(os.path.join("blocks_vertical", "*.js"))
277
+ elif block_type == "common":
278
+ target_filename = "blocks_compressed.js"
279
+ filenames = glob.glob(os.path.join("blocks_common", "*.js"))
280
+
281
+ # glob.glob ordering is platform-dependent and not necessary deterministic
282
+ filenames.sort() # Deterministic build.
283
+
284
+ # Define the parameters for the POST request.
285
+ params = [
286
+ ("compilation_level", "SIMPLE"),
287
+ ]
288
+
289
+ # Read in all the source files.
290
+ # Add Blockly.Blocks to be compatible with the compiler.
291
+ params.append(("js_file", os.path.join("build", "gen_blocks.js")))
292
+ # Add Blockly.Colours for use of centralized colour bank
293
+ filenames.append(os.path.join("core", "colours.js"))
294
+ filenames.append(os.path.join("core", "constants.js"))
295
+
296
+ for filename in filenames:
297
+ # Append filenames as false arguments the step before compiling will
298
+ # either transform them into arguments for local or remote compilation
299
+ params.append(("js_file", filename))
300
+
301
+ # Remove Blockly.Blocks to be compatible with Blockly.
302
+ remove = "var Blockly={Blocks:{}};"
303
+ self.do_compile(params, target_filename, filenames, remove)
304
+
305
+ def do_compile(self, params, target_filename, filenames, remove):
306
+ if self.closure_env["closure_compiler"] == REMOTE_COMPILER:
307
+ do_compile = self.do_compile_remote
308
+ else:
309
+ do_compile = self.do_compile_local
310
+ json_data = do_compile(params, target_filename)
311
+
312
+ if self.report_errors(target_filename, filenames, json_data):
313
+ self.write_output(target_filename, remove, json_data)
314
+ self.report_stats(target_filename, json_data)
315
+
316
+ def do_compile_local(self, params, target_filename):
317
+ filter_keys = ["use_closure_library"]
318
+
319
+ # Drop arg if arg is js_file else add dashes
320
+ dash_params = []
321
+ for (arg, value) in params:
322
+ dash_params.append((value,) if arg == "js_file" else ("--" + arg, value))
323
+
324
+ # Flatten dash_params into dash_args if their keys are not in filter_keys
325
+ dash_args = []
326
+ for pair in dash_params:
327
+ if pair[0][2:] not in filter_keys:
328
+ dash_args.extend(pair)
329
+
330
+ # Build the final args array by prepending CLOSURE_COMPILER_NPM to
331
+ # dash_args and dropping any falsy members
332
+ args = []
333
+ for group in [[CLOSURE_COMPILER_NPM], dash_args]:
334
+ args.extend(filter(lambda item: item, group))
335
+
336
+ # On Windows, the command line is too long, so we save the arguments to a file instead
337
+ use_flagfile = platform.system() == "Windows"
338
+ if platform.system() == "Windows":
339
+ flagfile_name = target_filename + ".config"
340
+ with open(flagfile_name, "w") as f:
341
+ # \ needs to be escaped still
342
+ f.write(" ".join(args[1:]).replace("\\", "\\\\"))
343
+ args = [CLOSURE_COMPILER_NPM, "--flagfile", flagfile_name]
344
+
345
+ proc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
346
+ (stdout, stderr) = proc.communicate()
347
+
348
+ if use_flagfile:
349
+ os.remove(flagfile_name)
350
+
351
+ # Build the JSON response.
352
+ filesizes = [os.path.getsize(value) for (arg, value) in params if arg == "js_file"]
353
+ return dict(
354
+ compiledCode=stdout,
355
+ statistics=dict(
356
+ originalSize=functools.reduce(lambda v, size: v + size, filesizes, 0),
357
+ compressedSize=len(stdout),
358
+ )
359
+ )
360
+
361
+ def do_compile_remote(self, params, target_filename):
362
+ filter_keys = [
363
+ "language_in",
364
+ "language_out",
365
+ "rewrite_polyfills",
366
+ "define",
367
+ ]
368
+
369
+ params.extend([
370
+ ("output_format", "json"),
371
+ ("output_info", "compiled_code"),
372
+ ("output_info", "warnings"),
373
+ ("output_info", "errors"),
374
+ ("output_info", "statistics"),
375
+ ])
376
+
377
+ # Send the request to Google.
378
+ remoteParams = []
379
+ for (arg, value) in params:
380
+ if not arg in filter_keys:
381
+ if arg == "js_file":
382
+ if not value.startswith(self.closure_env["closure_root"] + os.sep):
383
+ remoteParams.append(("js_code", read(value)))
384
+ # Change the normal compilation_level value SIMPLE to the remove
385
+ # service's SIMPLE_OPTIMIZATIONS
386
+ elif arg == "compilation_level" and value == "SIMPLE":
387
+ remoteParams.append((arg, "SIMPLE_OPTIMIZATIONS"))
388
+ else:
389
+ remoteParams.append((arg, value))
390
+
391
+ headers = {"Content-type": "application/x-www-form-urlencoded"}
392
+ conn = httplib.HTTPSConnection("closure-compiler.appspot.com")
393
+ conn.request("POST", "/compile", urlencode(remoteParams), headers)
394
+ response = conn.getresponse()
395
+ # Decode is necessary for Python 3.4 compatibility
396
+ json_str = response.read().decode("utf-8")
397
+ conn.close()
398
+
399
+ # Parse the JSON response.
400
+ return json.loads(json_str)
401
+
402
+ def report_errors(self, target_filename, filenames, json_data):
403
+ def file_lookup(name):
404
+ if not name.startswith("Input_"):
405
+ return "???"
406
+ n = int(name[6:]) - 1
407
+ return filenames[n]
408
+
409
+ if "serverErrors" in json_data:
410
+ errors = json_data["serverErrors"]
411
+ for error in errors:
412
+ print("SERVER ERROR: %s" % target_filename)
413
+ print(error["error"])
414
+ elif "errors" in json_data:
415
+ errors = json_data["errors"]
416
+ for error in errors:
417
+ print("FATAL ERROR")
418
+ print(error["error"])
419
+ if error["file"]:
420
+ print("%s at line %d:" % (
421
+ file_lookup(error["file"]), error["lineno"]))
422
+ print(error["line"])
423
+ print((" " * error["charno"]) + "^")
424
+ sys.exit(1)
425
+ else:
426
+ if "warnings" in json_data:
427
+ warnings = json_data["warnings"]
428
+ for warning in warnings:
429
+ print("WARNING")
430
+ print(warning["warning"])
431
+ if warning["file"]:
432
+ print("%s at line %d:" % (
433
+ file_lookup(warning["file"]), warning["lineno"]))
434
+ print(warning["line"])
435
+ print((" " * warning["charno"]) + "^")
436
+ print()
437
+
438
+ return True
439
+
440
+ return False
441
+
442
+ def write_output(self, target_filename, remove, json_data):
443
+ if "compiledCode" not in json_data:
444
+ print("FATAL ERROR: Compiler did not return compiledCode.")
445
+ sys.exit(1)
446
+
447
+ code = HEADER + "\n" + json_data["compiledCode"].decode("utf-8")
448
+ code = code.replace(remove, "")
449
+
450
+ # Trim down Google's (and only Google's) Apache licences.
451
+ # The Closure Compiler preserves these.
452
+ LICENSE = re.compile("""/\\*
453
+
454
+ [\\w ]+
455
+
456
+ Copyright \\d+ Google Inc.
457
+ https://developers.google.com/blockly/
458
+
459
+ Licensed under the Apache License, Version 2.0 \\(the "License"\\);
460
+ you may not use this file except in compliance with the License.
461
+ You may obtain a copy of the License at
462
+
463
+ http://www.apache.org/licenses/LICENSE-2.0
464
+
465
+ Unless required by applicable law or agreed to in writing, software
466
+ distributed under the License is distributed on an "AS IS" BASIS,
467
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
468
+ See the License for the specific language governing permissions and
469
+ limitations under the License.
470
+ \\*/""")
471
+ code = re.sub(LICENSE, "", code)
472
+
473
+ stats = json_data["statistics"]
474
+ original_b = stats["originalSize"]
475
+ compressed_b = stats["compressedSize"]
476
+ if original_b > 0 and compressed_b > 0:
477
+ f = open(target_filename, "w")
478
+ f.write(code)
479
+ f.close()
480
+
481
+ def report_stats(self, target_filename, json_data):
482
+ stats = json_data["statistics"]
483
+ original_b = stats["originalSize"]
484
+ compressed_b = stats["compressedSize"]
485
+ if original_b > 0 and compressed_b > 0:
486
+ original_kb = int(original_b / 1024 + 0.5)
487
+ compressed_kb = int(compressed_b / 1024 + 0.5)
488
+ ratio = int(float(compressed_b) / float(original_b) * 100 + 0.5)
489
+ print("SUCCESS: " + target_filename)
490
+ print("Size changed from %d KB to %d KB (%d%%)." % (
491
+ original_kb, compressed_kb, ratio))
492
+ else:
493
+ print("UNKNOWN ERROR")
494
+
495
+
496
+ class Gen_langfiles(threading.Thread):
497
+ """Generate JavaScript file for each natural language supported.
498
+
499
+ Runs in a separate thread.
500
+ """
501
+
502
+ def __init__(self):
503
+ threading.Thread.__init__(self)
504
+
505
+ def _rebuild(self, srcs, dests):
506
+ # Determine whether any of the files in srcs is newer than any in dests.
507
+ try:
508
+ return (max(os.path.getmtime(src) for src in srcs) >
509
+ min(os.path.getmtime(dest) for dest in dests))
510
+ except OSError as e:
511
+ # Was a file not found?
512
+ if e.errno == errno.ENOENT:
513
+ # If it was a source file, we can't proceed.
514
+ if e.filename in srcs:
515
+ print("Source file missing: " + e.filename)
516
+ sys.exit(1)
517
+ else:
518
+ # If a destination file was missing, rebuild.
519
+ return True
520
+ else:
521
+ print("Error checking file creation times: " + str(e))
522
+
523
+ def run(self):
524
+ # The files msg/json/{en,qqq,synonyms}.json depend on msg/messages.js.
525
+ if self._rebuild([os.path.join("msg", "messages.js")],
526
+ [os.path.join("msg", "json", f) for f in
527
+ ["en.json", "qqq.json", "synonyms.json"]]):
528
+ try:
529
+ subprocess.check_call([
530
+ "python",
531
+ os.path.join("i18n", "js_to_json.py"),
532
+ "--input_file", "msg/messages.js",
533
+ "--output_dir", "msg/json/",
534
+ "--quiet"])
535
+ except (subprocess.CalledProcessError, OSError) as e:
536
+ # Documentation for subprocess.check_call says that CalledProcessError
537
+ # will be raised on failure, but I found that OSError is also possible.
538
+ print("Error running i18n/js_to_json.py: ", e)
539
+ sys.exit(1)
540
+
541
+ # Checking whether it is necessary to rebuild the js files would be a lot of
542
+ # work since we would have to compare each <lang>.json file with each
543
+ # <lang>.js file. Rebuilding is easy and cheap, so just go ahead and do it.
544
+ try:
545
+ # Use create_messages.py to create .js files from .json files.
546
+ cmd = [
547
+ "python",
548
+ os.path.join("i18n", "create_messages.py"),
549
+ "--source_lang_file", os.path.join("msg", "json", "en.json"),
550
+ "--source_synonym_file", os.path.join("msg", "json", "synonyms.json"),
551
+ "--source_constants_file", os.path.join("msg", "json", "constants.json"),
552
+ "--key_file", os.path.join("msg", "json", "keys.json"),
553
+ "--output_dir", os.path.join("msg", "js"),
554
+ "--quiet"]
555
+ json_files = glob.glob(os.path.join("msg", "json", "*.json"))
556
+ json_files = [file for file in json_files if not
557
+ (file.endswith(("keys.json", "synonyms.json", "qqq.json", "constants.json")))]
558
+ cmd.extend(json_files)
559
+ subprocess.check_call(cmd)
560
+ except (subprocess.CalledProcessError, OSError) as e:
561
+ print("Error running i18n/create_messages.py: ", e)
562
+ sys.exit(1)
563
+
564
+ # Output list of .js files created.
565
+ for f in json_files:
566
+ # This assumes the path to the current directory does not contain "json".
567
+ f = f.replace("json", "js")
568
+ if os.path.isfile(f):
569
+ print("SUCCESS: " + f)
570
+ else:
571
+ print("FAILED to create " + f)
572
+
573
+ def exclude_vertical(item):
574
+ return not item.endswith("block_render_svg_vertical.js")
575
+
576
+ def exclude_horizontal(item):
577
+ return not item.endswith("block_render_svg_horizontal.js")
578
+
579
+ if __name__ == "__main__":
580
+ try:
581
+ closure_dir = CLOSURE_DIR_NPM
582
+ closure_root = CLOSURE_ROOT_NPM
583
+ closure_library = CLOSURE_LIBRARY_NPM
584
+ closure_compiler = CLOSURE_COMPILER_NPM
585
+
586
+ # Load calcdeps from the local library
587
+ calcdeps = import_path(os.path.join(
588
+ closure_root, closure_library, "closure", "bin", "calcdeps.py"))
589
+
590
+ # Sanity check the local compiler
591
+ test_args = [closure_compiler, os.path.join("build", "test_input.js")]
592
+ test_proc = subprocess.Popen(test_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
593
+ (stdout, _) = test_proc.communicate()
594
+ assert stdout.decode("utf-8") == read(os.path.join("build", "test_expect.js"))
595
+
596
+ print("Using local compiler: %s ...\n" % CLOSURE_COMPILER_NPM)
597
+ except (ImportError, AssertionError):
598
+ if os.path.isdir(os.path.join(os.path.pardir, "closure-library-read-only")):
599
+ # Dir got renamed when Closure moved from Google Code to GitHub in 2014.
600
+ print("Error: Closure directory needs to be renamed from"
601
+ "'closure-library-read-only' to 'closure-library'.\n"
602
+ "Please rename this directory.")
603
+ elif os.path.isdir(os.path.join(os.path.pardir, "google-closure-library")):
604
+ print("Error: Closure directory needs to be renamed from"
605
+ "'google-closure-library' to 'closure-library'.\n"
606
+ "Please rename this directory.")
607
+ else:
608
+ print("""Error: Closure not found. Usually this means 'npm ci' failed. Try running it again? More resources:
609
+ developers.google.com/blockly/guides/modify/web/closure""")
610
+ sys.exit(1)
611
+
612
+ search_paths = list(calcdeps.ExpandDirectories(
613
+ ["core", os.path.join(closure_root, closure_library)]))
614
+
615
+ search_paths_horizontal = list(filter(exclude_vertical, search_paths))
616
+ search_paths_vertical = list(filter(exclude_horizontal, search_paths))
617
+
618
+ closure_env = {
619
+ "closure_dir": closure_dir,
620
+ "closure_root": closure_root,
621
+ "closure_library": closure_library,
622
+ "closure_compiler": closure_compiler,
623
+ }
624
+
625
+ # Run all tasks in parallel threads.
626
+ # Uncompressed is limited by processor speed.
627
+ # Compressed is limited by network and server speed.
628
+ threads = [
629
+ # Vertical:
630
+ Gen_uncompressed(search_paths_vertical, True, closure_env),
631
+ # Horizontal:
632
+ Gen_uncompressed(search_paths_horizontal, False, closure_env),
633
+ # Compressed forms of vertical and horizontal.
634
+ Gen_compressed(search_paths_vertical, search_paths_horizontal, closure_env),
635
+
636
+ # This is run locally in a separate thread.
637
+ # Gen_langfiles()
638
+ ]
639
+
640
+ for thread in threads:
641
+ thread.start()
642
+
643
+ # Need to wait for all threads to finish before the main process ends as in Python 3.12,
644
+ # once the main interpreter is being shutdown, trying to spawn more child threads will
645
+ # raise "RuntimeError: can't create new thread at interpreter shutdown"
646
+ for thread in threads:
647
+ thread.join()