scratch-blocks 0.1.0-prerelease.20211005172512

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