@scratch/scratch-vm 11.0.0-beta.1

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 (175) hide show
  1. package/.jsdoc.json +20 -0
  2. package/.nvmrc +1 -0
  3. package/CHANGELOG.md +7004 -0
  4. package/LICENSE +12 -0
  5. package/README.md +120 -0
  6. package/TRADEMARK +1 -0
  7. package/commitlint.config.js +4 -0
  8. package/docs/extensions.md +527 -0
  9. package/package.json +103 -0
  10. package/release.config.js +13 -0
  11. package/src/blocks/scratch3_control.js +206 -0
  12. package/src/blocks/scratch3_core_example.js +69 -0
  13. package/src/blocks/scratch3_data.js +257 -0
  14. package/src/blocks/scratch3_event.js +137 -0
  15. package/src/blocks/scratch3_looks.js +612 -0
  16. package/src/blocks/scratch3_motion.js +288 -0
  17. package/src/blocks/scratch3_operators.js +154 -0
  18. package/src/blocks/scratch3_procedures.js +79 -0
  19. package/src/blocks/scratch3_sensing.js +336 -0
  20. package/src/blocks/scratch3_sound.js +350 -0
  21. package/src/dispatch/central-dispatch.js +143 -0
  22. package/src/dispatch/shared-dispatch.js +235 -0
  23. package/src/dispatch/worker-dispatch.js +110 -0
  24. package/src/engine/adapter.js +176 -0
  25. package/src/engine/block-utility.js +242 -0
  26. package/src/engine/blocks-execute-cache.js +19 -0
  27. package/src/engine/blocks-runtime-cache.js +78 -0
  28. package/src/engine/blocks.js +1299 -0
  29. package/src/engine/comment.js +56 -0
  30. package/src/engine/execute.js +580 -0
  31. package/src/engine/monitor-record.js +23 -0
  32. package/src/engine/mutation-adapter.js +48 -0
  33. package/src/engine/profiler.js +390 -0
  34. package/src/engine/runtime.js +2686 -0
  35. package/src/engine/scratch-blocks-constants.js +27 -0
  36. package/src/engine/sequencer.js +361 -0
  37. package/src/engine/stage-layering.js +29 -0
  38. package/src/engine/target.js +799 -0
  39. package/src/engine/thread.js +404 -0
  40. package/src/engine/variable.js +70 -0
  41. package/src/extension-support/argument-type.js +47 -0
  42. package/src/extension-support/block-type.js +50 -0
  43. package/src/extension-support/define-messages.js +18 -0
  44. package/src/extension-support/extension-manager.js +440 -0
  45. package/src/extension-support/extension-metadata.js +64 -0
  46. package/src/extension-support/extension-worker.js +59 -0
  47. package/src/extension-support/reporter-scope.js +18 -0
  48. package/src/extension-support/target-type.js +17 -0
  49. package/src/extensions/scratch3_boost/index.js +2113 -0
  50. package/src/extensions/scratch3_ev3/index.js +1355 -0
  51. package/src/extensions/scratch3_gdx_for/index.js +981 -0
  52. package/src/extensions/scratch3_gdx_for/scratch-link-device-adapter.js +44 -0
  53. package/src/extensions/scratch3_makeymakey/index.js +396 -0
  54. package/src/extensions/scratch3_microbit/index.js +984 -0
  55. package/src/extensions/scratch3_music/assets/drums/1-snare.mp3 +0 -0
  56. package/src/extensions/scratch3_music/assets/drums/10-wood-block.mp3 +0 -0
  57. package/src/extensions/scratch3_music/assets/drums/11-cowbell.mp3 +0 -0
  58. package/src/extensions/scratch3_music/assets/drums/12-triangle.mp3 +0 -0
  59. package/src/extensions/scratch3_music/assets/drums/13-bongo.mp3 +0 -0
  60. package/src/extensions/scratch3_music/assets/drums/14-conga.mp3 +0 -0
  61. package/src/extensions/scratch3_music/assets/drums/15-cabasa.mp3 +0 -0
  62. package/src/extensions/scratch3_music/assets/drums/16-guiro.mp3 +0 -0
  63. package/src/extensions/scratch3_music/assets/drums/17-vibraslap.mp3 +0 -0
  64. package/src/extensions/scratch3_music/assets/drums/18-cuica.mp3 +0 -0
  65. package/src/extensions/scratch3_music/assets/drums/2-bass-drum.mp3 +0 -0
  66. package/src/extensions/scratch3_music/assets/drums/3-side-stick.mp3 +0 -0
  67. package/src/extensions/scratch3_music/assets/drums/4-crash-cymbal.mp3 +0 -0
  68. package/src/extensions/scratch3_music/assets/drums/5-open-hi-hat.mp3 +0 -0
  69. package/src/extensions/scratch3_music/assets/drums/6-closed-hi-hat.mp3 +0 -0
  70. package/src/extensions/scratch3_music/assets/drums/7-tambourine.mp3 +0 -0
  71. package/src/extensions/scratch3_music/assets/drums/8-hand-clap.mp3 +0 -0
  72. package/src/extensions/scratch3_music/assets/drums/9-claves.mp3 +0 -0
  73. package/src/extensions/scratch3_music/assets/instruments/1-piano/108.mp3 +0 -0
  74. package/src/extensions/scratch3_music/assets/instruments/1-piano/24.mp3 +0 -0
  75. package/src/extensions/scratch3_music/assets/instruments/1-piano/36.mp3 +0 -0
  76. package/src/extensions/scratch3_music/assets/instruments/1-piano/48.mp3 +0 -0
  77. package/src/extensions/scratch3_music/assets/instruments/1-piano/60.mp3 +0 -0
  78. package/src/extensions/scratch3_music/assets/instruments/1-piano/72.mp3 +0 -0
  79. package/src/extensions/scratch3_music/assets/instruments/1-piano/84.mp3 +0 -0
  80. package/src/extensions/scratch3_music/assets/instruments/1-piano/96.mp3 +0 -0
  81. package/src/extensions/scratch3_music/assets/instruments/10-clarinet/48.mp3 +0 -0
  82. package/src/extensions/scratch3_music/assets/instruments/10-clarinet/60.mp3 +0 -0
  83. package/src/extensions/scratch3_music/assets/instruments/11-saxophone/36.mp3 +0 -0
  84. package/src/extensions/scratch3_music/assets/instruments/11-saxophone/60.mp3 +0 -0
  85. package/src/extensions/scratch3_music/assets/instruments/11-saxophone/84.mp3 +0 -0
  86. package/src/extensions/scratch3_music/assets/instruments/12-flute/60.mp3 +0 -0
  87. package/src/extensions/scratch3_music/assets/instruments/12-flute/72.mp3 +0 -0
  88. package/src/extensions/scratch3_music/assets/instruments/13-wooden-flute/60.mp3 +0 -0
  89. package/src/extensions/scratch3_music/assets/instruments/13-wooden-flute/72.mp3 +0 -0
  90. package/src/extensions/scratch3_music/assets/instruments/14-bassoon/36.mp3 +0 -0
  91. package/src/extensions/scratch3_music/assets/instruments/14-bassoon/48.mp3 +0 -0
  92. package/src/extensions/scratch3_music/assets/instruments/14-bassoon/60.mp3 +0 -0
  93. package/src/extensions/scratch3_music/assets/instruments/15-choir/48.mp3 +0 -0
  94. package/src/extensions/scratch3_music/assets/instruments/15-choir/60.mp3 +0 -0
  95. package/src/extensions/scratch3_music/assets/instruments/15-choir/72.mp3 +0 -0
  96. package/src/extensions/scratch3_music/assets/instruments/16-vibraphone/60.mp3 +0 -0
  97. package/src/extensions/scratch3_music/assets/instruments/16-vibraphone/72.mp3 +0 -0
  98. package/src/extensions/scratch3_music/assets/instruments/17-music-box/60.mp3 +0 -0
  99. package/src/extensions/scratch3_music/assets/instruments/18-steel-drum/60.mp3 +0 -0
  100. package/src/extensions/scratch3_music/assets/instruments/19-marimba/60.mp3 +0 -0
  101. package/src/extensions/scratch3_music/assets/instruments/2-electric-piano/60.mp3 +0 -0
  102. package/src/extensions/scratch3_music/assets/instruments/20-synth-lead/60.mp3 +0 -0
  103. package/src/extensions/scratch3_music/assets/instruments/21-synth-pad/60.mp3 +0 -0
  104. package/src/extensions/scratch3_music/assets/instruments/3-organ/60.mp3 +0 -0
  105. package/src/extensions/scratch3_music/assets/instruments/4-guitar/60.mp3 +0 -0
  106. package/src/extensions/scratch3_music/assets/instruments/5-electric-guitar/60.mp3 +0 -0
  107. package/src/extensions/scratch3_music/assets/instruments/6-bass/36.mp3 +0 -0
  108. package/src/extensions/scratch3_music/assets/instruments/6-bass/48.mp3 +0 -0
  109. package/src/extensions/scratch3_music/assets/instruments/7-pizzicato/60.mp3 +0 -0
  110. package/src/extensions/scratch3_music/assets/instruments/8-cello/36.mp3 +0 -0
  111. package/src/extensions/scratch3_music/assets/instruments/8-cello/48.mp3 +0 -0
  112. package/src/extensions/scratch3_music/assets/instruments/8-cello/60.mp3 +0 -0
  113. package/src/extensions/scratch3_music/assets/instruments/9-trombone/36.mp3 +0 -0
  114. package/src/extensions/scratch3_music/assets/instruments/9-trombone/48.mp3 +0 -0
  115. package/src/extensions/scratch3_music/assets/instruments/9-trombone/60.mp3 +0 -0
  116. package/src/extensions/scratch3_music/index.js +1333 -0
  117. package/src/extensions/scratch3_music/manifest.js +63 -0
  118. package/src/extensions/scratch3_pen/index.js +770 -0
  119. package/src/extensions/scratch3_speech2text/index.js +700 -0
  120. package/src/extensions/scratch3_text2speech/index.js +766 -0
  121. package/src/extensions/scratch3_translate/index.js +286 -0
  122. package/src/extensions/scratch3_video_sensing/debug.js +13 -0
  123. package/src/extensions/scratch3_video_sensing/index.js +594 -0
  124. package/src/extensions/scratch3_video_sensing/library.js +384 -0
  125. package/src/extensions/scratch3_video_sensing/math.js +76 -0
  126. package/src/extensions/scratch3_video_sensing/view.js +509 -0
  127. package/src/extensions/scratch3_wedo2/index.js +1616 -0
  128. package/src/import/load-costume.js +416 -0
  129. package/src/import/load-sound.js +116 -0
  130. package/src/index.js +10 -0
  131. package/src/io/ble.js +256 -0
  132. package/src/io/bt.js +202 -0
  133. package/src/io/clock.js +39 -0
  134. package/src/io/cloud.js +169 -0
  135. package/src/io/keyboard.js +146 -0
  136. package/src/io/mouse.js +145 -0
  137. package/src/io/mouseWheel.js +28 -0
  138. package/src/io/userData.js +24 -0
  139. package/src/io/video.js +210 -0
  140. package/src/playground/benchmark.css +83 -0
  141. package/src/playground/benchmark.js +753 -0
  142. package/src/playground/index.html +111 -0
  143. package/src/playground/suite.css +78 -0
  144. package/src/playground/suite.html +25 -0
  145. package/src/playground/suite.js +544 -0
  146. package/src/playground/video-sensing.html +18 -0
  147. package/src/playground/video-sensing.js +133 -0
  148. package/src/serialization/deserialize-assets.js +178 -0
  149. package/src/serialization/sb2.js +1295 -0
  150. package/src/serialization/sb2_specmap.js +1818 -0
  151. package/src/serialization/sb3.js +1320 -0
  152. package/src/serialization/serialize-assets.js +60 -0
  153. package/src/sprites/rendered-target.js +1115 -0
  154. package/src/sprites/sprite.js +177 -0
  155. package/src/util/base64-util.js +48 -0
  156. package/src/util/cast.js +218 -0
  157. package/src/util/clone.js +17 -0
  158. package/src/util/color.js +204 -0
  159. package/src/util/fetch-with-timeout.js +53 -0
  160. package/src/util/get-monitor-id.js +33 -0
  161. package/src/util/jsonrpc.js +114 -0
  162. package/src/util/log.js +4 -0
  163. package/src/util/math-util.js +122 -0
  164. package/src/util/maybe-format-message.js +18 -0
  165. package/src/util/new-block-ids.js +33 -0
  166. package/src/util/rateLimiter.js +73 -0
  167. package/src/util/scratch-link-websocket.js +133 -0
  168. package/src/util/string-util.js +94 -0
  169. package/src/util/task-queue.js +203 -0
  170. package/src/util/timer.js +103 -0
  171. package/src/util/uid.js +29 -0
  172. package/src/util/variable-util.js +48 -0
  173. package/src/util/xml-escape.js +33 -0
  174. package/src/virtual-machine.js +1586 -0
  175. package/webpack.config.js +134 -0
@@ -0,0 +1,799 @@
1
+ const EventEmitter = require('events');
2
+
3
+ const Blocks = require('./blocks');
4
+ const Variable = require('../engine/variable');
5
+ const Comment = require('../engine/comment');
6
+ const uid = require('../util/uid');
7
+ const {Map} = require('immutable');
8
+ const log = require('../util/log');
9
+ const StringUtil = require('../util/string-util');
10
+ const VariableUtil = require('../util/variable-util');
11
+
12
+ /**
13
+ * @fileoverview
14
+ * A Target is an abstract "code-running" object for the Scratch VM.
15
+ * Examples include sprites/clones or potentially physical-world devices.
16
+ */
17
+
18
+ class Target extends EventEmitter {
19
+
20
+ /**
21
+ * @param {Runtime} runtime Reference to the runtime.
22
+ * @param {?Blocks} blocks Blocks instance for the blocks owned by this target.
23
+ * @constructor
24
+ */
25
+ constructor (runtime, blocks) {
26
+ super();
27
+
28
+ if (!blocks) {
29
+ blocks = new Blocks(runtime);
30
+ }
31
+
32
+ /**
33
+ * Reference to the runtime.
34
+ * @type {Runtime}
35
+ */
36
+ this.runtime = runtime;
37
+ /**
38
+ * A unique ID for this target.
39
+ * @type {string}
40
+ */
41
+ this.id = uid();
42
+ /**
43
+ * Blocks run as code for this target.
44
+ * @type {!Blocks}
45
+ */
46
+ this.blocks = blocks;
47
+ /**
48
+ * Dictionary of variables and their values for this target.
49
+ * Key is the variable id.
50
+ * @type {Object.<string,*>}
51
+ */
52
+ this.variables = {};
53
+ /**
54
+ * Dictionary of comments for this target.
55
+ * Key is the comment id.
56
+ * @type {Object.<string,*>}
57
+ */
58
+ this.comments = {};
59
+ /**
60
+ * Dictionary of custom state for this target.
61
+ * This can be used to store target-specific custom state for blocks which need it.
62
+ * TODO: do we want to persist this in SB3 files?
63
+ * @type {Object.<string,*>}
64
+ */
65
+ this._customState = {};
66
+
67
+ /**
68
+ * Currently known values for edge-activated hats.
69
+ * Keys are block ID for the hat; values are the currently known values.
70
+ * @type {Object.<string, *>}
71
+ */
72
+ this._edgeActivatedHatValues = {};
73
+ }
74
+
75
+ /**
76
+ * Called when the project receives a "green flag."
77
+ * @abstract
78
+ */
79
+ onGreenFlag () {}
80
+
81
+ /**
82
+ * Return a human-readable name for this target.
83
+ * Target implementations should override this.
84
+ * @abstract
85
+ * @returns {string} Human-readable name for the target.
86
+ */
87
+ getName () {
88
+ return this.id;
89
+ }
90
+
91
+ /**
92
+ * Update an edge-activated hat block value.
93
+ * @param {!string} blockId ID of hat to store value for.
94
+ * @param {*} newValue Value to store for edge-activated hat.
95
+ * @return {*} The old value for the edge-activated hat.
96
+ */
97
+ updateEdgeActivatedValue (blockId, newValue) {
98
+ const oldValue = this._edgeActivatedHatValues[blockId];
99
+ this._edgeActivatedHatValues[blockId] = newValue;
100
+ return oldValue;
101
+ }
102
+
103
+ hasEdgeActivatedValue (blockId) {
104
+ return Object.prototype.hasOwnProperty.call(this._edgeActivatedHatValues, blockId);
105
+ }
106
+
107
+ /**
108
+ * Clear all edge-activaed hat values.
109
+ */
110
+ clearEdgeActivatedValues () {
111
+ this._edgeActivatedHatValues = {};
112
+ }
113
+
114
+ /**
115
+ * Look up a variable object, first by id, and then by name if the id is not found.
116
+ * Create a new variable if both lookups fail.
117
+ * @param {string} id Id of the variable.
118
+ * @param {string} name Name of the variable.
119
+ * @return {!Variable} Variable object.
120
+ */
121
+ lookupOrCreateVariable (id, name) {
122
+ let variable = this.lookupVariableById(id);
123
+ if (variable) return variable;
124
+
125
+ variable = this.lookupVariableByNameAndType(name, Variable.SCALAR_TYPE);
126
+ if (variable) return variable;
127
+
128
+ // No variable with this name exists - create it locally.
129
+ const newVariable = new Variable(id, name, Variable.SCALAR_TYPE, false);
130
+ this.variables[id] = newVariable;
131
+ return newVariable;
132
+ }
133
+
134
+ /**
135
+ * Look up a broadcast message object with the given id and return it
136
+ * if it exists.
137
+ * @param {string} id Id of the variable.
138
+ * @param {string} name Name of the variable.
139
+ * @return {?Variable} Variable object.
140
+ */
141
+ lookupBroadcastMsg (id, name) {
142
+ let broadcastMsg;
143
+ if (id) {
144
+ broadcastMsg = this.lookupVariableById(id);
145
+ } else if (name) {
146
+ broadcastMsg = this.lookupBroadcastByInputValue(name);
147
+ } else {
148
+ log.error('Cannot find broadcast message if neither id nor name are provided.');
149
+ }
150
+ if (broadcastMsg) {
151
+ if (name && (broadcastMsg.name.toLowerCase() !== name.toLowerCase())) {
152
+ log.error(`Found broadcast message with id: ${id}, but` +
153
+ `its name, ${broadcastMsg.name} did not match expected name ${name}.`);
154
+ }
155
+ if (broadcastMsg.type !== Variable.BROADCAST_MESSAGE_TYPE) {
156
+ log.error(`Found variable with id: ${id}, but its type ${broadcastMsg.type}` +
157
+ `did not match expected type ${Variable.BROADCAST_MESSAGE_TYPE}`);
158
+ }
159
+ return broadcastMsg;
160
+ }
161
+ }
162
+
163
+ /**
164
+ * Look up a broadcast message with the given name and return the variable
165
+ * if it exists. Does not create a new broadcast message variable if
166
+ * it doesn't exist.
167
+ * @param {string} name Name of the variable.
168
+ * @return {?Variable} Variable object.
169
+ */
170
+ lookupBroadcastByInputValue (name) {
171
+ const vars = this.variables;
172
+ for (const propName in vars) {
173
+ if ((vars[propName].type === Variable.BROADCAST_MESSAGE_TYPE) &&
174
+ (vars[propName].name.toLowerCase() === name.toLowerCase())) {
175
+ return vars[propName];
176
+ }
177
+ }
178
+ }
179
+
180
+ /**
181
+ * Look up a variable object.
182
+ * Search begins for local variables; then look for globals.
183
+ * @param {string} id Id of the variable.
184
+ * @param {string} name Name of the variable.
185
+ * @return {!Variable} Variable object.
186
+ */
187
+ lookupVariableById (id) {
188
+ // If we have a local copy, return it.
189
+ if (Object.prototype.hasOwnProperty.call(this.variables, id)) {
190
+ return this.variables[id];
191
+ }
192
+ // If the stage has a global copy, return it.
193
+ if (this.runtime && !this.isStage) {
194
+ const stage = this.runtime.getTargetForStage();
195
+ if (stage && Object.prototype.hasOwnProperty.call(stage.variables, id)) {
196
+ return stage.variables[id];
197
+ }
198
+ }
199
+ }
200
+
201
+ /**
202
+ * Look up a variable object by its name and variable type.
203
+ * Search begins with local variables; then global variables if a local one
204
+ * was not found.
205
+ * @param {string} name Name of the variable.
206
+ * @param {string} type Type of the variable. Defaults to Variable.SCALAR_TYPE.
207
+ * @param {?bool} skipStage Optional flag to skip checking the stage
208
+ * @return {?Variable} Variable object if found, or null if not.
209
+ */
210
+ lookupVariableByNameAndType (name, type, skipStage) {
211
+ if (typeof name !== 'string') return;
212
+ if (typeof type !== 'string') type = Variable.SCALAR_TYPE;
213
+ skipStage = skipStage || false;
214
+
215
+ for (const varId in this.variables) {
216
+ const currVar = this.variables[varId];
217
+ if (currVar.name === name && currVar.type === type) {
218
+ return currVar;
219
+ }
220
+ }
221
+
222
+ if (!skipStage && this.runtime && !this.isStage) {
223
+ const stage = this.runtime.getTargetForStage();
224
+ if (stage) {
225
+ for (const varId in stage.variables) {
226
+ const currVar = stage.variables[varId];
227
+ if (currVar.name === name && currVar.type === type) {
228
+ return currVar;
229
+ }
230
+ }
231
+ }
232
+ }
233
+
234
+ return null;
235
+ }
236
+
237
+ /**
238
+ * Look up a list object for this target, and create it if one doesn't exist.
239
+ * Search begins for local lists; then look for globals.
240
+ * @param {!string} id Id of the list.
241
+ * @param {!string} name Name of the list.
242
+ * @return {!Varible} Variable object representing the found/created list.
243
+ */
244
+ lookupOrCreateList (id, name) {
245
+ let list = this.lookupVariableById(id);
246
+ if (list) return list;
247
+
248
+ list = this.lookupVariableByNameAndType(name, Variable.LIST_TYPE);
249
+ if (list) return list;
250
+
251
+ // No variable with this name exists - create it locally.
252
+ const newList = new Variable(id, name, Variable.LIST_TYPE, false);
253
+ this.variables[id] = newList;
254
+ return newList;
255
+ }
256
+
257
+ /**
258
+ * Creates a variable with the given id and name and adds it to the
259
+ * dictionary of variables.
260
+ * @param {string} id Id of variable
261
+ * @param {string} name Name of variable.
262
+ * @param {string} type Type of variable, '', 'broadcast_msg', or 'list'
263
+ * @param {boolean} isCloud Whether the variable to create has the isCloud flag set.
264
+ * Additional checks are made that the variable can be created as a cloud variable.
265
+ */
266
+ createVariable (id, name, type, isCloud) {
267
+ if (!Object.prototype.hasOwnProperty.call(this.variables, id)) {
268
+ const newVariable = new Variable(id, name, type, false);
269
+ if (isCloud && this.isStage && this.runtime.canAddCloudVariable()) {
270
+ newVariable.isCloud = true;
271
+ this.runtime.addCloudVariable();
272
+ this.runtime.ioDevices.cloud.requestCreateVariable(newVariable);
273
+ }
274
+ this.variables[id] = newVariable;
275
+ }
276
+ }
277
+
278
+ /**
279
+ * Creates a comment with the given properties.
280
+ * @param {string} id Id of the comment.
281
+ * @param {string} blockId Optional id of the block the comment is attached
282
+ * to if it is a block comment.
283
+ * @param {string} text The text the comment contains.
284
+ * @param {number} x The x coordinate of the comment on the workspace.
285
+ * @param {number} y The y coordinate of the comment on the workspace.
286
+ * @param {number} width The width of the comment when it is full size
287
+ * @param {number} height The height of the comment when it is full size
288
+ * @param {boolean} minimized Whether the comment is minimized.
289
+ */
290
+ createComment (id, blockId, text, x, y, width, height, minimized) {
291
+ if (!Object.prototype.hasOwnProperty.call(this.comments, id)) {
292
+ const newComment = new Comment(id, text, x, y,
293
+ width, height, minimized);
294
+ if (blockId) {
295
+ newComment.blockId = blockId;
296
+ const blockWithComment = this.blocks.getBlock(blockId);
297
+ if (blockWithComment) {
298
+ blockWithComment.comment = id;
299
+ } else {
300
+ log.warn(`Could not find block with id ${blockId
301
+ } associated with commentId: ${id}`);
302
+ }
303
+ }
304
+ this.comments[id] = newComment;
305
+ }
306
+ }
307
+
308
+ /**
309
+ * Renames the variable with the given id to newName.
310
+ * @param {string} id Id of variable to rename.
311
+ * @param {string} newName New name for the variable.
312
+ */
313
+ renameVariable (id, newName) {
314
+ if (Object.prototype.hasOwnProperty.call(this.variables, id)) {
315
+ const variable = this.variables[id];
316
+ if (variable.id === id) {
317
+ const oldName = variable.name;
318
+ variable.name = newName;
319
+
320
+ if (this.runtime) {
321
+ if (variable.isCloud && this.isStage) {
322
+ this.runtime.ioDevices.cloud.requestRenameVariable(oldName, newName);
323
+ }
324
+
325
+ if (variable.type === Variable.SCALAR_TYPE) {
326
+ // sensing__of may be referencing to this variable.
327
+ // Change the reference.
328
+ let blockUpdated = false;
329
+ this.runtime.targets.forEach(t => {
330
+ blockUpdated = t.blocks.updateSensingOfReference(
331
+ oldName,
332
+ newName,
333
+ this.isStage ? '_stage_' : this.getName()
334
+ ) || blockUpdated;
335
+ });
336
+ // Request workspace change only if sensing_of blocks were actually updated.
337
+ if (blockUpdated) this.runtime.requestBlocksUpdate();
338
+ }
339
+
340
+ const blocks = this.runtime.monitorBlocks;
341
+ blocks.changeBlock({
342
+ id: id,
343
+ element: 'field',
344
+ name: variable.type === Variable.LIST_TYPE ? 'LIST' : 'VARIABLE',
345
+ value: id
346
+ }, this.runtime);
347
+ const monitorBlock = blocks.getBlock(variable.id);
348
+ if (monitorBlock) {
349
+ this.runtime.requestUpdateMonitor(Map({
350
+ id: id,
351
+ params: blocks._getBlockParams(monitorBlock)
352
+ }));
353
+ }
354
+ }
355
+
356
+ }
357
+ }
358
+ }
359
+
360
+ /**
361
+ * Removes the variable with the given id from the dictionary of variables.
362
+ * @param {string} id Id of variable to delete.
363
+ */
364
+ deleteVariable (id) {
365
+ if (Object.prototype.hasOwnProperty.call(this.variables, id)) {
366
+ // Get info about the variable before deleting it
367
+ const deletedVariableName = this.variables[id].name;
368
+ const deletedVariableWasCloud = this.variables[id].isCloud;
369
+ delete this.variables[id];
370
+ if (this.runtime) {
371
+ if (deletedVariableWasCloud && this.isStage) {
372
+ this.runtime.ioDevices.cloud.requestDeleteVariable(deletedVariableName);
373
+ this.runtime.removeCloudVariable();
374
+ }
375
+ this.runtime.monitorBlocks.deleteBlock(id);
376
+ this.runtime.requestRemoveMonitor(id);
377
+ }
378
+ }
379
+ }
380
+
381
+ /**
382
+ * Remove this target's monitors from the runtime state and remove the
383
+ * target-specific monitored blocks (e.g. local variables, global variables for the stage, x-position).
384
+ * NOTE: This does not delete any of the stage monitors like backdrop name.
385
+ */
386
+ deleteMonitors () {
387
+ this.runtime.requestRemoveMonitorByTargetId(this.id);
388
+ let targetSpecificMonitorBlockIds;
389
+ if (this.isStage) {
390
+ // This only deletes global variables and not other stage monitors like backdrop number.
391
+ targetSpecificMonitorBlockIds = Object.keys(this.variables);
392
+ } else {
393
+ targetSpecificMonitorBlockIds = Object.keys(this.runtime.monitorBlocks._blocks)
394
+ .filter(key => this.runtime.monitorBlocks._blocks[key].targetId === this.id);
395
+ }
396
+ for (const blockId of targetSpecificMonitorBlockIds) {
397
+ this.runtime.monitorBlocks.deleteBlock(blockId);
398
+ }
399
+ }
400
+
401
+ /**
402
+ * Create a clone of the variable with the given id from the dictionary of
403
+ * this target's variables.
404
+ * @param {string} id Id of variable to duplicate.
405
+ * @param {boolean=} optKeepOriginalId Optional flag to keep the original variable ID
406
+ * for the duplicate variable. This is necessary when cloning a sprite, for example.
407
+ * @return {?Variable} The duplicated variable, or null if
408
+ * the original variable was not found.
409
+ */
410
+ duplicateVariable (id, optKeepOriginalId) {
411
+ if (Object.prototype.hasOwnProperty.call(this.variables, id)) {
412
+ const originalVariable = this.variables[id];
413
+ const newVariable = new Variable(
414
+ optKeepOriginalId ? id : null, // conditionally keep original id or generate a new one
415
+ originalVariable.name,
416
+ originalVariable.type,
417
+ originalVariable.isCloud
418
+ );
419
+ if (newVariable.type === Variable.LIST_TYPE) {
420
+ newVariable.value = originalVariable.value.slice(0);
421
+ } else {
422
+ newVariable.value = originalVariable.value;
423
+ }
424
+ return newVariable;
425
+ }
426
+ return null;
427
+ }
428
+
429
+ /**
430
+ * Duplicate the dictionary of this target's variables as part of duplicating.
431
+ * this target or making a clone.
432
+ * @param {object=} optBlocks Optional block container for the target being duplicated.
433
+ * If provided, new variables will be generated with new UIDs and any variable references
434
+ * in this blocks container will be updated to refer to the corresponding new IDs.
435
+ * @return {object} The duplicated dictionary of variables
436
+ */
437
+ duplicateVariables (optBlocks) {
438
+ let allVarRefs;
439
+ if (optBlocks) {
440
+ allVarRefs = optBlocks.getAllVariableAndListReferences();
441
+ }
442
+ return Object.keys(this.variables).reduce((accum, varId) => {
443
+ const newVariable = this.duplicateVariable(varId, !optBlocks);
444
+ accum[newVariable.id] = newVariable;
445
+ if (optBlocks && allVarRefs) {
446
+ const currVarRefs = allVarRefs[varId];
447
+ if (currVarRefs) {
448
+ this.mergeVariables(varId, newVariable.id, currVarRefs);
449
+ }
450
+ }
451
+ return accum;
452
+ }, {});
453
+ }
454
+
455
+ /**
456
+ * Post/edit sprite info.
457
+ * @param {object} data An object with sprite info data to set.
458
+ * @abstract
459
+ */
460
+ postSpriteInfo () {}
461
+
462
+ /**
463
+ * Retrieve custom state associated with this target and the provided state ID.
464
+ * @param {string} stateId - specify which piece of state to retrieve.
465
+ * @returns {*} the associated state, if any was found.
466
+ */
467
+ getCustomState (stateId) {
468
+ return this._customState[stateId];
469
+ }
470
+
471
+ /**
472
+ * Store custom state associated with this target and the provided state ID.
473
+ * @param {string} stateId - specify which piece of state to store on this target.
474
+ * @param {*} newValue - the state value to store.
475
+ */
476
+ setCustomState (stateId, newValue) {
477
+ this._customState[stateId] = newValue;
478
+ }
479
+
480
+ /**
481
+ * Call to destroy a target.
482
+ * @abstract
483
+ */
484
+ dispose () {
485
+ this._customState = {};
486
+
487
+ if (this.runtime) {
488
+ this.runtime.removeExecutable(this);
489
+ }
490
+ }
491
+
492
+ // Variable Conflict Resolution Helpers
493
+
494
+ /**
495
+ * Get the names of all the variables of the given type that are in scope for this target.
496
+ * For targets that are not the stage, this includes any target-specific
497
+ * variables as well as any stage variables unless the skipStage flag is true.
498
+ * For the stage, this is all stage variables.
499
+ * @param {string} type The variable type to search for; defaults to Variable.SCALAR_TYPE
500
+ * @param {?bool} skipStage Optional flag to skip the stage.
501
+ * @return {Array<string>} A list of variable names
502
+ */
503
+ getAllVariableNamesInScopeByType (type, skipStage) {
504
+ if (typeof type !== 'string') type = Variable.SCALAR_TYPE;
505
+ skipStage = skipStage || false;
506
+ const targetVariables = Object.values(this.variables)
507
+ .filter(v => v.type === type)
508
+ .map(variable => variable.name);
509
+ if (skipStage || this.isStage || !this.runtime) {
510
+ return targetVariables;
511
+ }
512
+ const stage = this.runtime.getTargetForStage();
513
+ const stageVariables = stage.getAllVariableNamesInScopeByType(type);
514
+ return targetVariables.concat(stageVariables);
515
+ }
516
+
517
+ /**
518
+ * Merge variable references with another variable.
519
+ * @param {string} idToBeMerged ID of the variable whose references need to be updated
520
+ * @param {string} idToMergeWith ID of the variable that the old references should be replaced with
521
+ * @param {?Array<Object>} optReferencesToUpdate Optional context of the change.
522
+ * Defaults to all the blocks in this target.
523
+ * @param {?string} optNewName New variable name to merge with. The old
524
+ * variable name in the references being updated should be replaced with this new name.
525
+ * If this parameter is not provided or is '', no name change occurs.
526
+ */
527
+ mergeVariables (idToBeMerged, idToMergeWith, optReferencesToUpdate, optNewName) {
528
+ const referencesToChange = optReferencesToUpdate ||
529
+ // TODO should there be a separate helper function that traverses the blocks
530
+ // for all references for a given ID instead of doing the below..?
531
+ this.blocks.getAllVariableAndListReferences()[idToBeMerged];
532
+
533
+ VariableUtil.updateVariableIdentifiers(referencesToChange, idToMergeWith, optNewName);
534
+ }
535
+
536
+ /**
537
+ * Share a local variable (and given references for that variable) to the stage.
538
+ * @param {string} varId The ID of the variable to share.
539
+ * @param {Array<object>} varRefs The list of variable references being shared,
540
+ * that reference the given variable ID. The names and IDs of these variable
541
+ * references will be updated to refer to the new (or pre-existing) global variable.
542
+ */
543
+ shareLocalVariableToStage (varId, varRefs) {
544
+ if (!this.runtime) return;
545
+ const variable = this.variables[varId];
546
+ if (!variable) {
547
+ log.warn(`Cannot share a local variable to the stage if it's not local.`);
548
+ return;
549
+ }
550
+ const stage = this.runtime.getTargetForStage();
551
+ // If a local var is being shared with the stage,
552
+ // sharing will make the variable global, resulting in a conflict
553
+ // with the existing local variable. Preemptively Resolve this conflict
554
+ // by renaming the new global variable.
555
+
556
+ // First check if we've already done the local to global transition for this
557
+ // variable. If we have, merge it with the global variable we've already created.
558
+ const varIdForStage = `StageVarFromLocal_${varId}`;
559
+ let stageVar = stage.lookupVariableById(varIdForStage);
560
+ // If a global var doesn't already exist, create a new one with a fresh name.
561
+ // Use the ID we created above so that we can lookup this new variable in the
562
+ // future if we decide to share this same variable again.
563
+ if (!stageVar) {
564
+ const varName = variable.name;
565
+ const varType = variable.type;
566
+
567
+ const newStageName = `Stage: ${varName}`;
568
+ stageVar = this.runtime.createNewGlobalVariable(newStageName, varIdForStage, varType);
569
+ }
570
+ // Update all variable references to use the new name and ID
571
+ this.mergeVariables(varId, stageVar.id, varRefs, stageVar.name);
572
+ }
573
+
574
+ /**
575
+ * Share a local variable with a sprite, merging with one of the same name and
576
+ * type if it already exists on the sprite, or create a new one.
577
+ * @param {string} varId Id of the variable to share
578
+ * @param {Target} sprite The sprite to share the variable with
579
+ * @param {Array<object>} varRefs A list of all the variable references currently being shared.
580
+ */
581
+ shareLocalVariableToSprite (varId, sprite, varRefs) {
582
+ if (!this.runtime) return;
583
+ if (this.isStage) return;
584
+ const variable = this.variables[varId];
585
+ if (!variable) {
586
+ log.warn(`Tried to call 'shareLocalVariableToSprite' with a non-local variable.`);
587
+ return;
588
+ }
589
+ const varName = variable.name;
590
+ const varType = variable.type;
591
+ // Check if the receiving sprite already has a variable of the same name and type
592
+ // and use the existing variable, otherwise create a new one.
593
+ const existingLocalVar = sprite.lookupVariableByNameAndType(varName, varType);
594
+ let newVarId;
595
+ if (existingLocalVar) {
596
+ newVarId = existingLocalVar.id;
597
+ } else {
598
+ const newVar = new Variable(null, varName, varType);
599
+ newVarId = newVar.id;
600
+ sprite.variables[newVarId] = newVar;
601
+ }
602
+
603
+ // Merge with the local variable on the new sprite.
604
+ this.mergeVariables(varId, newVarId, varRefs);
605
+ }
606
+
607
+ /**
608
+ * Given a list of variable referencing fields, shares those variables with
609
+ * the target with the provided id, resolving any variable conflicts that arise
610
+ * using the following rules:
611
+ *
612
+ * If this target is the stage, exit. There are no conflicts that arise
613
+ * from sharing variables from the stage to another sprite. The variables
614
+ * already exist globally, so no further action is needed.
615
+ *
616
+ * If a variable being referenced is a global variable, do nothing. The
617
+ * global variable already exists so no further action is needed.
618
+ *
619
+ * If a variable being referenced is local, and
620
+ * 1) The receiving target is a sprite:
621
+ * create a new local variable or merge with an existing local variable
622
+ * of the same name and type. Update all the referencing fields
623
+ * for the original variable to reference the new variable.
624
+ * 2) The receiving target is the stage:
625
+ * Create a new global variable with a fresh name and update all the referencing
626
+ * fields to reference the new variable.
627
+ *
628
+ * @param {Array<object>} blocks The blocks containing
629
+ * potential conflicting references to variables.
630
+ * @param {Target} receivingTarget The target receiving the variables
631
+ */
632
+ resolveVariableSharingConflictsWithTarget (blocks, receivingTarget) {
633
+ if (this.isStage) return;
634
+
635
+ // Get all the variable references in the given list of blocks
636
+ const allVarListRefs = this.blocks.getAllVariableAndListReferences(blocks);
637
+
638
+ // For all the variables being referenced, check for which ones are local
639
+ // to this target, and resolve conflicts based on whether the receiving target
640
+ // is a sprite (with a conflicting local variable) or whether it is
641
+ // the stage (which cannot have local variables)
642
+ for (const varId in allVarListRefs) {
643
+ const currVar = this.variables[varId];
644
+ if (!currVar) continue; // The current variable is global, there shouldn't be any conflicts here, skip it.
645
+
646
+ // Get the list of references for the current variable id
647
+ const currVarListRefs = allVarListRefs[varId];
648
+
649
+ if (receivingTarget.isStage) {
650
+ this.shareLocalVariableToStage(varId, currVarListRefs);
651
+ } else {
652
+ this.shareLocalVariableToSprite(varId, receivingTarget, currVarListRefs);
653
+ }
654
+ }
655
+ }
656
+
657
+ /**
658
+ * Fixes up variable references in this target avoiding conflicts with
659
+ * pre-existing variables in the same scope.
660
+ * This is used when uploading this target as a new sprite into an existing
661
+ * project, where the new sprite may contain references
662
+ * to variable names that already exist as global variables in the project
663
+ * (and thus are in scope for variable references in the given sprite).
664
+ *
665
+ * If this target has a block that references an existing global variable and that
666
+ * variable *does not* exist in this target (e.g. it was a global variable in the
667
+ * project the sprite was originally exported from), merge the variables. This entails
668
+ * fixing the variable references in this sprite to reference the id of the pre-existing global variable.
669
+ *
670
+ * If this target has a block that references an existing global variable and that
671
+ * variable does exist in the target itself (e.g. it's a local variable in the sprite being uploaded),
672
+ * then the local variable is renamed to distinguish itself from the pre-existing variable.
673
+ * All blocks that reference the local variable will be updated to use the new name.
674
+ */
675
+ // TODO (#1360) This function is too long, add some helpers for the different chunks and cases...
676
+ fixUpVariableReferences () {
677
+ if (!this.runtime) return; // There's no runtime context to conflict with
678
+ if (this.isStage) return; // Stage can't have variable conflicts with itself (and also can't be uploaded)
679
+ const stage = this.runtime.getTargetForStage();
680
+ if (!stage || !stage.variables) return;
681
+
682
+ const renameConflictingLocalVar = (id, name, type) => {
683
+ const conflict = stage.lookupVariableByNameAndType(name, type);
684
+ if (conflict) {
685
+ const newName = StringUtil.unusedName(
686
+ `${this.getName()}: ${name}`,
687
+ this.getAllVariableNamesInScopeByType(type));
688
+ this.renameVariable(id, newName);
689
+ return newName;
690
+ }
691
+ return null;
692
+ };
693
+
694
+ const allReferences = this.blocks.getAllVariableAndListReferences();
695
+ const unreferencedLocalVarIds = [];
696
+ if (Object.keys(this.variables).length > 0) {
697
+ for (const localVarId in this.variables) {
698
+ if (!Object.prototype.hasOwnProperty.call(this.variables, localVarId)) continue;
699
+ if (!allReferences[localVarId]) unreferencedLocalVarIds.push(localVarId);
700
+ }
701
+ }
702
+ const conflictIdsToReplace = Object.create(null);
703
+ const conflictNamesToReplace = Object.create(null);
704
+
705
+ // Cache the list of all variable names by type so that we don't need to
706
+ // re-calculate this in every iteration of the following loop.
707
+ const varNamesByType = {};
708
+ const allVarNames = type => {
709
+ const namesOfType = varNamesByType[type];
710
+ if (namesOfType) return namesOfType;
711
+ varNamesByType[type] = this.runtime.getAllVarNamesOfType(type);
712
+ return varNamesByType[type];
713
+ };
714
+
715
+ for (const varId in allReferences) {
716
+ // We don't care about which var ref we get, they should all have the same var info
717
+ const varRef = allReferences[varId][0];
718
+ const varName = varRef.referencingField.value;
719
+ const varType = varRef.type;
720
+ if (this.lookupVariableById(varId)) {
721
+ // Found a variable with the id in either the target or the stage,
722
+ // figure out which one.
723
+ if (Object.prototype.hasOwnProperty.call(this.variables, varId)) {
724
+ // If the target has the variable, then check whether the stage
725
+ // has one with the same name and type. If it does, then rename
726
+ // this target specific variable so that there is a distinction.
727
+ const newVarName = renameConflictingLocalVar(varId, varName, varType);
728
+
729
+ if (newVarName) {
730
+ // We are not calling this.blocks.updateBlocksAfterVarRename
731
+ // here because it will search through all the blocks. We already
732
+ // have access to all the references for this var id.
733
+ allReferences[varId].map(ref => {
734
+ ref.referencingField.value = newVarName;
735
+ return ref;
736
+ });
737
+ }
738
+ }
739
+ } else {
740
+ // We didn't find the referenced variable id anywhere,
741
+ // Treat it as a reference to a global variable (from the original
742
+ // project this sprite was exported from).
743
+ // Check for whether a global variable of the same name and type exists,
744
+ // and if so, track it to merge with the existing global in a second pass of the blocks.
745
+ const existingVar = stage.lookupVariableByNameAndType(varName, varType);
746
+ if (existingVar) {
747
+ if (!conflictIdsToReplace[varId]) {
748
+ conflictIdsToReplace[varId] = existingVar.id;
749
+ }
750
+ } else {
751
+ // A global variable with the same name did not already exist,
752
+ // create a new one such that it does not conflict with any
753
+ // names of local variables of the same type.
754
+ const allNames = allVarNames(varType);
755
+ const freshName = StringUtil.unusedName(varName, allNames);
756
+ stage.createVariable(varId, freshName, varType);
757
+ if (!conflictNamesToReplace[varId]) {
758
+ conflictNamesToReplace[varId] = freshName;
759
+ }
760
+ }
761
+ }
762
+ }
763
+ // Rename any local variables that were missed above because they aren't
764
+ // referenced by any blocks
765
+ for (const id in unreferencedLocalVarIds) {
766
+ const varId = unreferencedLocalVarIds[id];
767
+ const name = this.variables[varId].name;
768
+ const type = this.variables[varId].type;
769
+ renameConflictingLocalVar(varId, name, type);
770
+ }
771
+ // Handle global var conflicts with existing global vars (e.g. a sprite is uploaded, and has
772
+ // blocks referencing some variable that the sprite does not own, and this
773
+ // variable conflicts with a global var)
774
+ // In this case, we want to merge the new variable referenes with the
775
+ // existing global variable
776
+ for (const conflictId in conflictIdsToReplace) {
777
+ const existingId = conflictIdsToReplace[conflictId];
778
+ const referencesToUpdate = allReferences[conflictId];
779
+ this.mergeVariables(conflictId, existingId, referencesToUpdate);
780
+ }
781
+
782
+ // Handle global var conflicts existing local vars (e.g a sprite is uploaded,
783
+ // and has blocks referencing some variable that the sprite does not own, and this
784
+ // variable conflcits with another sprite's local var).
785
+ // In this case, we want to go through the variable references and update
786
+ // the name of the variable in that reference.
787
+ for (const conflictId in conflictNamesToReplace) {
788
+ const newName = conflictNamesToReplace[conflictId];
789
+ const referencesToUpdate = allReferences[conflictId];
790
+ referencesToUpdate.map(ref => {
791
+ ref.referencingField.value = newName;
792
+ return ref;
793
+ });
794
+ }
795
+ }
796
+
797
+ }
798
+
799
+ module.exports = Target;