@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.
- package/.jsdoc.json +20 -0
- package/.nvmrc +1 -0
- package/CHANGELOG.md +7004 -0
- package/LICENSE +12 -0
- package/README.md +120 -0
- package/TRADEMARK +1 -0
- package/commitlint.config.js +4 -0
- package/docs/extensions.md +527 -0
- package/package.json +103 -0
- package/release.config.js +13 -0
- package/src/blocks/scratch3_control.js +206 -0
- package/src/blocks/scratch3_core_example.js +69 -0
- package/src/blocks/scratch3_data.js +257 -0
- package/src/blocks/scratch3_event.js +137 -0
- package/src/blocks/scratch3_looks.js +612 -0
- package/src/blocks/scratch3_motion.js +288 -0
- package/src/blocks/scratch3_operators.js +154 -0
- package/src/blocks/scratch3_procedures.js +79 -0
- package/src/blocks/scratch3_sensing.js +336 -0
- package/src/blocks/scratch3_sound.js +350 -0
- package/src/dispatch/central-dispatch.js +143 -0
- package/src/dispatch/shared-dispatch.js +235 -0
- package/src/dispatch/worker-dispatch.js +110 -0
- package/src/engine/adapter.js +176 -0
- package/src/engine/block-utility.js +242 -0
- package/src/engine/blocks-execute-cache.js +19 -0
- package/src/engine/blocks-runtime-cache.js +78 -0
- package/src/engine/blocks.js +1299 -0
- package/src/engine/comment.js +56 -0
- package/src/engine/execute.js +580 -0
- package/src/engine/monitor-record.js +23 -0
- package/src/engine/mutation-adapter.js +48 -0
- package/src/engine/profiler.js +390 -0
- package/src/engine/runtime.js +2686 -0
- package/src/engine/scratch-blocks-constants.js +27 -0
- package/src/engine/sequencer.js +361 -0
- package/src/engine/stage-layering.js +29 -0
- package/src/engine/target.js +799 -0
- package/src/engine/thread.js +404 -0
- package/src/engine/variable.js +70 -0
- package/src/extension-support/argument-type.js +47 -0
- package/src/extension-support/block-type.js +50 -0
- package/src/extension-support/define-messages.js +18 -0
- package/src/extension-support/extension-manager.js +440 -0
- package/src/extension-support/extension-metadata.js +64 -0
- package/src/extension-support/extension-worker.js +59 -0
- package/src/extension-support/reporter-scope.js +18 -0
- package/src/extension-support/target-type.js +17 -0
- package/src/extensions/scratch3_boost/index.js +2113 -0
- package/src/extensions/scratch3_ev3/index.js +1355 -0
- package/src/extensions/scratch3_gdx_for/index.js +981 -0
- package/src/extensions/scratch3_gdx_for/scratch-link-device-adapter.js +44 -0
- package/src/extensions/scratch3_makeymakey/index.js +396 -0
- package/src/extensions/scratch3_microbit/index.js +984 -0
- package/src/extensions/scratch3_music/assets/drums/1-snare.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/drums/10-wood-block.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/drums/11-cowbell.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/drums/12-triangle.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/drums/13-bongo.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/drums/14-conga.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/drums/15-cabasa.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/drums/16-guiro.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/drums/17-vibraslap.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/drums/18-cuica.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/drums/2-bass-drum.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/drums/3-side-stick.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/drums/4-crash-cymbal.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/drums/5-open-hi-hat.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/drums/6-closed-hi-hat.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/drums/7-tambourine.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/drums/8-hand-clap.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/drums/9-claves.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/1-piano/108.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/1-piano/24.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/1-piano/36.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/1-piano/48.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/1-piano/60.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/1-piano/72.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/1-piano/84.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/1-piano/96.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/10-clarinet/48.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/10-clarinet/60.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/11-saxophone/36.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/11-saxophone/60.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/11-saxophone/84.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/12-flute/60.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/12-flute/72.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/13-wooden-flute/60.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/13-wooden-flute/72.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/14-bassoon/36.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/14-bassoon/48.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/14-bassoon/60.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/15-choir/48.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/15-choir/60.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/15-choir/72.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/16-vibraphone/60.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/16-vibraphone/72.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/17-music-box/60.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/18-steel-drum/60.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/19-marimba/60.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/2-electric-piano/60.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/20-synth-lead/60.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/21-synth-pad/60.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/3-organ/60.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/4-guitar/60.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/5-electric-guitar/60.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/6-bass/36.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/6-bass/48.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/7-pizzicato/60.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/8-cello/36.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/8-cello/48.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/8-cello/60.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/9-trombone/36.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/9-trombone/48.mp3 +0 -0
- package/src/extensions/scratch3_music/assets/instruments/9-trombone/60.mp3 +0 -0
- package/src/extensions/scratch3_music/index.js +1333 -0
- package/src/extensions/scratch3_music/manifest.js +63 -0
- package/src/extensions/scratch3_pen/index.js +770 -0
- package/src/extensions/scratch3_speech2text/index.js +700 -0
- package/src/extensions/scratch3_text2speech/index.js +766 -0
- package/src/extensions/scratch3_translate/index.js +286 -0
- package/src/extensions/scratch3_video_sensing/debug.js +13 -0
- package/src/extensions/scratch3_video_sensing/index.js +594 -0
- package/src/extensions/scratch3_video_sensing/library.js +384 -0
- package/src/extensions/scratch3_video_sensing/math.js +76 -0
- package/src/extensions/scratch3_video_sensing/view.js +509 -0
- package/src/extensions/scratch3_wedo2/index.js +1616 -0
- package/src/import/load-costume.js +416 -0
- package/src/import/load-sound.js +116 -0
- package/src/index.js +10 -0
- package/src/io/ble.js +256 -0
- package/src/io/bt.js +202 -0
- package/src/io/clock.js +39 -0
- package/src/io/cloud.js +169 -0
- package/src/io/keyboard.js +146 -0
- package/src/io/mouse.js +145 -0
- package/src/io/mouseWheel.js +28 -0
- package/src/io/userData.js +24 -0
- package/src/io/video.js +210 -0
- package/src/playground/benchmark.css +83 -0
- package/src/playground/benchmark.js +753 -0
- package/src/playground/index.html +111 -0
- package/src/playground/suite.css +78 -0
- package/src/playground/suite.html +25 -0
- package/src/playground/suite.js +544 -0
- package/src/playground/video-sensing.html +18 -0
- package/src/playground/video-sensing.js +133 -0
- package/src/serialization/deserialize-assets.js +178 -0
- package/src/serialization/sb2.js +1295 -0
- package/src/serialization/sb2_specmap.js +1818 -0
- package/src/serialization/sb3.js +1320 -0
- package/src/serialization/serialize-assets.js +60 -0
- package/src/sprites/rendered-target.js +1115 -0
- package/src/sprites/sprite.js +177 -0
- package/src/util/base64-util.js +48 -0
- package/src/util/cast.js +218 -0
- package/src/util/clone.js +17 -0
- package/src/util/color.js +204 -0
- package/src/util/fetch-with-timeout.js +53 -0
- package/src/util/get-monitor-id.js +33 -0
- package/src/util/jsonrpc.js +114 -0
- package/src/util/log.js +4 -0
- package/src/util/math-util.js +122 -0
- package/src/util/maybe-format-message.js +18 -0
- package/src/util/new-block-ids.js +33 -0
- package/src/util/rateLimiter.js +73 -0
- package/src/util/scratch-link-websocket.js +133 -0
- package/src/util/string-util.js +94 -0
- package/src/util/task-queue.js +203 -0
- package/src/util/timer.js +103 -0
- package/src/util/uid.js +29 -0
- package/src/util/variable-util.js +48 -0
- package/src/util/xml-escape.js +33 -0
- package/src/virtual-machine.js +1586 -0
- package/webpack.config.js +134 -0
|
@@ -0,0 +1,1295 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview
|
|
3
|
+
* Partial implementation of an SB2 JSON importer.
|
|
4
|
+
* Parses provided JSON and then generates all needed
|
|
5
|
+
* scratch-vm runtime structures.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
const Blocks = require('../engine/blocks');
|
|
9
|
+
const RenderedTarget = require('../sprites/rendered-target');
|
|
10
|
+
const Sprite = require('../sprites/sprite');
|
|
11
|
+
const Color = require('../util/color');
|
|
12
|
+
const log = require('../util/log');
|
|
13
|
+
const uid = require('../util/uid');
|
|
14
|
+
const StringUtil = require('../util/string-util');
|
|
15
|
+
const MathUtil = require('../util/math-util');
|
|
16
|
+
const specMap = require('./sb2_specmap');
|
|
17
|
+
const Comment = require('../engine/comment');
|
|
18
|
+
const Variable = require('../engine/variable');
|
|
19
|
+
const MonitorRecord = require('../engine/monitor-record');
|
|
20
|
+
const StageLayering = require('../engine/stage-layering');
|
|
21
|
+
|
|
22
|
+
const {loadCostume} = require('../import/load-costume.js');
|
|
23
|
+
const {loadSound} = require('../import/load-sound.js');
|
|
24
|
+
const {deserializeCostume, deserializeSound} = require('./deserialize-assets.js');
|
|
25
|
+
|
|
26
|
+
// Constants used during deserialization of an SB2 file
|
|
27
|
+
const CORE_EXTENSIONS = [
|
|
28
|
+
'argument',
|
|
29
|
+
'control',
|
|
30
|
+
'data',
|
|
31
|
+
'event',
|
|
32
|
+
'looks',
|
|
33
|
+
'math',
|
|
34
|
+
'motion',
|
|
35
|
+
'operator',
|
|
36
|
+
'procedures',
|
|
37
|
+
'sensing',
|
|
38
|
+
'sound'
|
|
39
|
+
];
|
|
40
|
+
|
|
41
|
+
// Adjust script coordinates to account for
|
|
42
|
+
// larger block size in scratch-blocks.
|
|
43
|
+
// @todo: Determine more precisely the right formulas here.
|
|
44
|
+
const WORKSPACE_X_SCALE = 1.5;
|
|
45
|
+
const WORKSPACE_Y_SCALE = 2.2;
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Convert a Scratch 2.0 procedure string (e.g., "my_procedure %s %b %n")
|
|
49
|
+
* into an argument map. This allows us to provide the expected inputs
|
|
50
|
+
* to a mutated procedure call.
|
|
51
|
+
* @param {string} procCode Scratch 2.0 procedure string.
|
|
52
|
+
* @return {object} Argument map compatible with those in sb2specmap.
|
|
53
|
+
*/
|
|
54
|
+
const parseProcedureArgMap = function (procCode) {
|
|
55
|
+
const argMap = [
|
|
56
|
+
{} // First item in list is op string.
|
|
57
|
+
];
|
|
58
|
+
const INPUT_PREFIX = 'input';
|
|
59
|
+
let inputCount = 0;
|
|
60
|
+
// Split by %n, %b, %s.
|
|
61
|
+
const parts = procCode.split(/(?=[^\\]%[nbs])/);
|
|
62
|
+
for (let i = 0; i < parts.length; i++) {
|
|
63
|
+
const part = parts[i].trim();
|
|
64
|
+
if (part.substring(0, 1) === '%') {
|
|
65
|
+
const argType = part.substring(1, 2);
|
|
66
|
+
const arg = {
|
|
67
|
+
type: 'input',
|
|
68
|
+
inputName: INPUT_PREFIX + (inputCount++)
|
|
69
|
+
};
|
|
70
|
+
if (argType === 'n') {
|
|
71
|
+
arg.inputOp = 'math_number';
|
|
72
|
+
} else if (argType === 's') {
|
|
73
|
+
arg.inputOp = 'text';
|
|
74
|
+
} else if (argType === 'b') {
|
|
75
|
+
arg.inputOp = 'boolean';
|
|
76
|
+
}
|
|
77
|
+
argMap.push(arg);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return argMap;
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Generate a list of "argument IDs" for procdefs and caller mutations.
|
|
85
|
+
* IDs just end up being `input0`, `input1`, ... which is good enough.
|
|
86
|
+
* @param {string} procCode Scratch 2.0 procedure string.
|
|
87
|
+
* @return {Array.<string>} Array of argument id strings.
|
|
88
|
+
*/
|
|
89
|
+
const parseProcedureArgIds = function (procCode) {
|
|
90
|
+
return parseProcedureArgMap(procCode)
|
|
91
|
+
.map(arg => arg.inputName)
|
|
92
|
+
.filter(name => name); // Filter out unnamed inputs which are labels
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Flatten a block tree into a block list.
|
|
97
|
+
* Children are temporarily stored on the `block.children` property.
|
|
98
|
+
* @param {Array.<object>} blocks list generated by `parseBlockList`.
|
|
99
|
+
* @return {Array.<object>} Flattened list to be passed to `blocks.createBlock`.
|
|
100
|
+
*/
|
|
101
|
+
const flatten = function (blocks) {
|
|
102
|
+
let finalBlocks = [];
|
|
103
|
+
for (let i = 0; i < blocks.length; i++) {
|
|
104
|
+
const block = blocks[i];
|
|
105
|
+
finalBlocks.push(block);
|
|
106
|
+
if (block.children) {
|
|
107
|
+
finalBlocks = finalBlocks.concat(flatten(block.children));
|
|
108
|
+
}
|
|
109
|
+
delete block.children;
|
|
110
|
+
}
|
|
111
|
+
return finalBlocks;
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Parse any list of blocks from SB2 JSON into a list of VM-format blocks.
|
|
116
|
+
* Could be used to parse a top-level script,
|
|
117
|
+
* a list of blocks in a branch (e.g., in forever),
|
|
118
|
+
* or a list of blocks in an argument (e.g., move [pick random...]).
|
|
119
|
+
* @param {Array.<object>} blockList SB2 JSON-format block list.
|
|
120
|
+
* @param {Function} addBroadcastMsg function to update broadcast message name map
|
|
121
|
+
* @param {Function} getVariableId function to retreive a variable's ID based on name
|
|
122
|
+
* @param {ImportedExtensionsInfo} extensions - (in/out) parsed extension information will be stored here.
|
|
123
|
+
* @param {ParseState} parseState - info on the state of parsing beyond the current block.
|
|
124
|
+
* @param {object<int, Comment>} comments - Comments from sb2 project that need to be attached to blocks.
|
|
125
|
+
* They are indexed in this object by the sb2 flattened block list index indicating
|
|
126
|
+
* which block they should attach to.
|
|
127
|
+
* @param {int} commentIndex The current index of the top block in this list if it were in a flattened
|
|
128
|
+
* list of all blocks for the target
|
|
129
|
+
* @return {Array<Array.<object>|int>} Tuple where first item is the Scratch VM-format block list, and
|
|
130
|
+
* second item is the updated comment index
|
|
131
|
+
*/
|
|
132
|
+
const parseBlockList = function (blockList, addBroadcastMsg, getVariableId, extensions, parseState, comments,
|
|
133
|
+
commentIndex) {
|
|
134
|
+
const resultingList = [];
|
|
135
|
+
let previousBlock = null; // For setting next.
|
|
136
|
+
for (let i = 0; i < blockList.length; i++) {
|
|
137
|
+
const block = blockList[i];
|
|
138
|
+
// eslint-disable-next-line no-use-before-define
|
|
139
|
+
const parsedBlockAndComments = parseBlock(block, addBroadcastMsg, getVariableId,
|
|
140
|
+
extensions, parseState, comments, commentIndex);
|
|
141
|
+
const parsedBlock = parsedBlockAndComments[0];
|
|
142
|
+
// Update commentIndex
|
|
143
|
+
commentIndex = parsedBlockAndComments[1];
|
|
144
|
+
|
|
145
|
+
if (!parsedBlock) continue;
|
|
146
|
+
if (previousBlock) {
|
|
147
|
+
parsedBlock.parent = previousBlock.id;
|
|
148
|
+
previousBlock.next = parsedBlock.id;
|
|
149
|
+
}
|
|
150
|
+
previousBlock = parsedBlock;
|
|
151
|
+
resultingList.push(parsedBlock);
|
|
152
|
+
}
|
|
153
|
+
return [resultingList, commentIndex];
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Parse a Scratch object's scripts into VM blocks.
|
|
158
|
+
* This should only handle top-level scripts that include X, Y coordinates.
|
|
159
|
+
* @param {!object} scripts Scripts object from SB2 JSON.
|
|
160
|
+
* @param {!Blocks} blocks Blocks object to load parsed blocks into.
|
|
161
|
+
* @param {Function} addBroadcastMsg function to update broadcast message name map
|
|
162
|
+
* @param {Function} getVariableId function to retreive a variable's ID based on name
|
|
163
|
+
* @param {ImportedExtensionsInfo} extensions - (in/out) parsed extension information will be stored here.
|
|
164
|
+
* @param {object} comments Comments that need to be attached to the blocks that need to be parsed
|
|
165
|
+
*/
|
|
166
|
+
const parseScripts = function (scripts, blocks, addBroadcastMsg, getVariableId, extensions, comments) {
|
|
167
|
+
// Keep track of the index of the current script being
|
|
168
|
+
// parsed in order to attach block comments correctly
|
|
169
|
+
let scriptIndexForComment = 0;
|
|
170
|
+
|
|
171
|
+
for (let i = 0; i < scripts.length; i++) {
|
|
172
|
+
const script = scripts[i];
|
|
173
|
+
const scriptX = script[0];
|
|
174
|
+
const scriptY = script[1];
|
|
175
|
+
const blockList = script[2];
|
|
176
|
+
const parseState = {};
|
|
177
|
+
const [parsedBlockList, newCommentIndex] = parseBlockList(blockList, addBroadcastMsg, getVariableId, extensions,
|
|
178
|
+
parseState, comments, scriptIndexForComment);
|
|
179
|
+
scriptIndexForComment = newCommentIndex;
|
|
180
|
+
if (parsedBlockList[0]) {
|
|
181
|
+
parsedBlockList[0].x = scriptX * WORKSPACE_X_SCALE;
|
|
182
|
+
parsedBlockList[0].y = scriptY * WORKSPACE_Y_SCALE;
|
|
183
|
+
parsedBlockList[0].topLevel = true;
|
|
184
|
+
parsedBlockList[0].parent = null;
|
|
185
|
+
}
|
|
186
|
+
// Flatten children and create add the blocks.
|
|
187
|
+
const convertedBlocks = flatten(parsedBlockList);
|
|
188
|
+
for (let j = 0; j < convertedBlocks.length; j++) {
|
|
189
|
+
blocks.createBlock(convertedBlocks[j]);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Create a callback for assigning fixed IDs to imported variables
|
|
196
|
+
* Generator stores the global variable mapping in a closure
|
|
197
|
+
* @param {!string} targetId the id of the target to scope the variable to
|
|
198
|
+
* @return {string} variable ID
|
|
199
|
+
*/
|
|
200
|
+
const generateVariableIdGetter = (function () {
|
|
201
|
+
let globalVariableNameMap = {};
|
|
202
|
+
const namer = (targetId, name, type) => `${targetId}-${StringUtil.replaceUnsafeChars(name)}-${type}`;
|
|
203
|
+
return function (targetId, topLevel) {
|
|
204
|
+
// Reset the global variable map if topLevel
|
|
205
|
+
if (topLevel) globalVariableNameMap = {};
|
|
206
|
+
return function (name, type) {
|
|
207
|
+
if (topLevel) { // Store the name/id pair in the globalVariableNameMap
|
|
208
|
+
globalVariableNameMap[`${name}-${type}`] = namer(targetId, name, type);
|
|
209
|
+
return globalVariableNameMap[`${name}-${type}`];
|
|
210
|
+
}
|
|
211
|
+
// Not top-level, so first check the global name map
|
|
212
|
+
if (globalVariableNameMap[`${name}-${type}`]) return globalVariableNameMap[`${name}-${type}`];
|
|
213
|
+
return namer(targetId, name, type);
|
|
214
|
+
};
|
|
215
|
+
};
|
|
216
|
+
}());
|
|
217
|
+
|
|
218
|
+
const globalBroadcastMsgStateGenerator = (function () {
|
|
219
|
+
let broadcastMsgNameMap = {};
|
|
220
|
+
const allBroadcastFields = [];
|
|
221
|
+
const emptyStringName = uid();
|
|
222
|
+
return function (topLevel) {
|
|
223
|
+
if (topLevel) broadcastMsgNameMap = {};
|
|
224
|
+
return {
|
|
225
|
+
broadcastMsgMapUpdater: function (name, field) {
|
|
226
|
+
name = name.toLowerCase();
|
|
227
|
+
if (name === '') {
|
|
228
|
+
name = emptyStringName;
|
|
229
|
+
}
|
|
230
|
+
broadcastMsgNameMap[name] = `broadcastMsgId-${StringUtil.replaceUnsafeChars(name)}`;
|
|
231
|
+
allBroadcastFields.push(field);
|
|
232
|
+
return broadcastMsgNameMap[name];
|
|
233
|
+
},
|
|
234
|
+
globalBroadcastMsgs: broadcastMsgNameMap,
|
|
235
|
+
allBroadcastFields: allBroadcastFields,
|
|
236
|
+
emptyMsgName: emptyStringName
|
|
237
|
+
};
|
|
238
|
+
};
|
|
239
|
+
}());
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Parse a single monitor object and create all its in-memory VM objects.
|
|
243
|
+
*
|
|
244
|
+
* It is important that monitors are parsed last,
|
|
245
|
+
* - after all sprite targets have finished parsing, and
|
|
246
|
+
* - after the rest of the stage has finished parsing.
|
|
247
|
+
*
|
|
248
|
+
* It is specifically important that all the scripts in the project
|
|
249
|
+
* have been parsed and all the relevant targets exist, have uids,
|
|
250
|
+
* and have their variables initialized.
|
|
251
|
+
* Calling this function before these things are true, will result in
|
|
252
|
+
* undefined behavior.
|
|
253
|
+
* @param {!object} object - From-JSON "Monitor object"
|
|
254
|
+
* @param {!Runtime} runtime - (in/out) Runtime object to load monitor info into.
|
|
255
|
+
* @param {!Array.<Target>} targets - Targets have already been parsed.
|
|
256
|
+
* @param {ImportedExtensionsInfo} extensions - (in/out) parsed extension information will be stored here.
|
|
257
|
+
*/
|
|
258
|
+
|
|
259
|
+
const parseMonitorObject = (object, runtime, targets, extensions) => {
|
|
260
|
+
// If we can't find the block in the spec map, ignore it.
|
|
261
|
+
// This happens for things like Lego Wedo 1.0 monitors.
|
|
262
|
+
const mapped = specMap[object.cmd];
|
|
263
|
+
if (!mapped) {
|
|
264
|
+
log.warn(`Could not find monitor block with opcode: ${object.cmd}`);
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
// In scratch 2.0, there are two monitors that now correspond to extension
|
|
268
|
+
// blocks (tempo and video motion/direction). In the case of the
|
|
269
|
+
// video motion/direction block, this reporter is not monitorable in Scratch 3.0.
|
|
270
|
+
// In the case of the tempo block, we should import it and load the music extension
|
|
271
|
+
// only when the monitor is actually visible.
|
|
272
|
+
|
|
273
|
+
const opcode = specMap[object.cmd].opcode;
|
|
274
|
+
const extIndex = opcode.indexOf('_');
|
|
275
|
+
const extID = opcode.substring(0, extIndex);
|
|
276
|
+
|
|
277
|
+
if (extID === 'videoSensing') {
|
|
278
|
+
return;
|
|
279
|
+
} else if (CORE_EXTENSIONS.indexOf(extID) === -1 && extID !== '' &&
|
|
280
|
+
!extensions.extensionIDs.has(extID) && !object.visible) {
|
|
281
|
+
// Don't import this monitor if it refers to a non-core extension that
|
|
282
|
+
// doesn't exist anywhere else in the project and it isn't visible.
|
|
283
|
+
// This should only apply to the tempo block at this point since
|
|
284
|
+
// there are no other sb2 blocks that are now extension monitors.
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
let target = null;
|
|
289
|
+
// List blocks don't come in with their target name set.
|
|
290
|
+
// Find the target by searching for a target with matching variable name/type.
|
|
291
|
+
if (!Object.prototype.hasOwnProperty.call(object, 'target')) {
|
|
292
|
+
for (let i = 0; i < targets.length; i++) {
|
|
293
|
+
const currTarget = targets[i];
|
|
294
|
+
const listVariables = Object.keys(currTarget.variables).filter(key => {
|
|
295
|
+
const variable = currTarget.variables[key];
|
|
296
|
+
return variable.type === Variable.LIST_TYPE && variable.name === object.listName;
|
|
297
|
+
});
|
|
298
|
+
if (listVariables.length > 0) {
|
|
299
|
+
target = currTarget; // Keep this target for later use
|
|
300
|
+
object.target = currTarget.getName(); // Set target name to normalize with other monitors
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// Get the target for this monitor, if not gotten above.
|
|
306
|
+
target = target || targets.filter(t => t.getName() === object.target)[0];
|
|
307
|
+
if (!target) throw new Error('Cannot create monitor for target that cannot be found by name');
|
|
308
|
+
|
|
309
|
+
// Create var id getter to make block naming/parsing easier, variables already created.
|
|
310
|
+
const getVariableId = generateVariableIdGetter(target.id, false);
|
|
311
|
+
// eslint-disable-next-line no-use-before-define
|
|
312
|
+
const [block, _] = parseBlock(
|
|
313
|
+
[object.cmd, object.param], // Scratch 2 monitor blocks only have one param.
|
|
314
|
+
null, // `addBroadcastMsg`, not needed for monitor blocks.
|
|
315
|
+
getVariableId,
|
|
316
|
+
extensions,
|
|
317
|
+
{},
|
|
318
|
+
null, // `comments`, not needed for monitor blocks
|
|
319
|
+
null // `commentIndex`, not needed for monitor blocks
|
|
320
|
+
);
|
|
321
|
+
|
|
322
|
+
// Monitor blocks have special IDs to match the toolbox obtained from the getId
|
|
323
|
+
// function in the runtime.monitorBlocksInfo. Variable monitors, however,
|
|
324
|
+
// get their IDs from the variable id they reference.
|
|
325
|
+
if (object.cmd === 'getVar:') {
|
|
326
|
+
block.id = getVariableId(object.param, Variable.SCALAR_TYPE);
|
|
327
|
+
} else if (object.cmd === 'contentsOfList:') {
|
|
328
|
+
block.id = getVariableId(object.param, Variable.LIST_TYPE);
|
|
329
|
+
} else if (Object.prototype.hasOwnProperty.call(runtime.monitorBlockInfo, block.opcode)) {
|
|
330
|
+
block.id = runtime.monitorBlockInfo[block.opcode].getId(target.id, block.fields);
|
|
331
|
+
} else {
|
|
332
|
+
// If the opcode can't be found in the runtime monitorBlockInfo,
|
|
333
|
+
// then default to using the block opcode as the id instead.
|
|
334
|
+
// This is for extension monitors, and assumes that extension monitors
|
|
335
|
+
// cannot be sprite specific.
|
|
336
|
+
block.id = block.opcode;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// Block needs a targetId if it is targetting something other than the stage
|
|
340
|
+
block.targetId = target.isStage ? null : target.id;
|
|
341
|
+
|
|
342
|
+
// Property required for running monitored blocks.
|
|
343
|
+
block.isMonitored = object.visible;
|
|
344
|
+
|
|
345
|
+
const existingMonitorBlock = runtime.monitorBlocks._blocks[block.id];
|
|
346
|
+
if (existingMonitorBlock) {
|
|
347
|
+
// A monitor block already exists if the toolbox has been loaded and
|
|
348
|
+
// the monitor block is not target specific (because the block gets recycled).
|
|
349
|
+
// Update the existing block with the relevant monitor information.
|
|
350
|
+
existingMonitorBlock.isMonitored = object.visible;
|
|
351
|
+
existingMonitorBlock.targetId = block.targetId;
|
|
352
|
+
} else {
|
|
353
|
+
// Blocks can be created with children, flatten and add to monitorBlocks.
|
|
354
|
+
const newBlocks = flatten([block]);
|
|
355
|
+
for (let i = 0; i < newBlocks.length; i++) {
|
|
356
|
+
runtime.monitorBlocks.createBlock(newBlocks[i]);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
// Convert numbered mode into strings for better understandability.
|
|
361
|
+
switch (object.mode) {
|
|
362
|
+
case 1:
|
|
363
|
+
object.mode = 'default';
|
|
364
|
+
break;
|
|
365
|
+
case 2:
|
|
366
|
+
object.mode = 'large';
|
|
367
|
+
break;
|
|
368
|
+
case 3:
|
|
369
|
+
object.mode = 'slider';
|
|
370
|
+
break;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
// Create a monitor record for the runtime's monitorState
|
|
374
|
+
runtime.requestAddMonitor(MonitorRecord({
|
|
375
|
+
id: block.id,
|
|
376
|
+
targetId: block.targetId,
|
|
377
|
+
spriteName: block.targetId ? object.target : null,
|
|
378
|
+
opcode: block.opcode,
|
|
379
|
+
params: runtime.monitorBlocks._getBlockParams(block),
|
|
380
|
+
value: '',
|
|
381
|
+
mode: object.mode,
|
|
382
|
+
sliderMin: object.sliderMin,
|
|
383
|
+
sliderMax: object.sliderMax,
|
|
384
|
+
isDiscrete: object.isDiscrete,
|
|
385
|
+
x: object.x,
|
|
386
|
+
y: object.y,
|
|
387
|
+
width: object.width,
|
|
388
|
+
height: object.height,
|
|
389
|
+
visible: object.visible
|
|
390
|
+
}));
|
|
391
|
+
};
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* Parse the assets of a single "Scratch object" and load them. This
|
|
395
|
+
* preprocesses objects to support loading the data for those assets over a
|
|
396
|
+
* network while the objects are further processed into Blocks, Sprites, and a
|
|
397
|
+
* list of needed Extensions.
|
|
398
|
+
* @param {!object} object - From-JSON "Scratch object:" sprite, stage, watcher.
|
|
399
|
+
* @param {!Runtime} runtime - Runtime object to load all structures into.
|
|
400
|
+
* @param {boolean} topLevel - Whether this is the top-level object (stage).
|
|
401
|
+
* @param {?object} zip - Optional zipped assets for local file import
|
|
402
|
+
* @return {?{costumePromises:Array.<Promise>,soundPromises:Array.<Promise>,soundBank:SoundBank,children:object}}
|
|
403
|
+
* Object of arrays of promises and child objects for asset objects used in
|
|
404
|
+
* Sprites. As well as a SoundBank for the sound assets. null for unsupported
|
|
405
|
+
* objects.
|
|
406
|
+
*/
|
|
407
|
+
const parseScratchAssets = function (object, runtime, topLevel, zip) {
|
|
408
|
+
if (!Object.prototype.hasOwnProperty.call(object, 'objName')) {
|
|
409
|
+
// Skip parsing monitors. Or any other objects missing objName.
|
|
410
|
+
return null;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
const assets = {
|
|
414
|
+
costumePromises: [],
|
|
415
|
+
soundPromises: [],
|
|
416
|
+
soundBank: runtime.audioEngine && runtime.audioEngine.createBank(),
|
|
417
|
+
children: []
|
|
418
|
+
};
|
|
419
|
+
|
|
420
|
+
// Costumes from JSON.
|
|
421
|
+
const costumePromises = assets.costumePromises;
|
|
422
|
+
if (Object.prototype.hasOwnProperty.call(object, 'costumes')) {
|
|
423
|
+
for (let i = 0; i < object.costumes.length; i++) {
|
|
424
|
+
const costumeSource = object.costumes[i];
|
|
425
|
+
const bitmapResolution = costumeSource.bitmapResolution || 1;
|
|
426
|
+
const costume = {
|
|
427
|
+
name: costumeSource.costumeName,
|
|
428
|
+
bitmapResolution: bitmapResolution,
|
|
429
|
+
rotationCenterX: topLevel ? 240 * bitmapResolution : costumeSource.rotationCenterX,
|
|
430
|
+
rotationCenterY: topLevel ? 180 * bitmapResolution : costumeSource.rotationCenterY,
|
|
431
|
+
// TODO we eventually want this next property to be called
|
|
432
|
+
// md5ext to reflect what it actually contains, however this
|
|
433
|
+
// will be a very extensive change across many repositories
|
|
434
|
+
// and should be done carefully and altogether
|
|
435
|
+
md5: costumeSource.baseLayerMD5,
|
|
436
|
+
skinId: null
|
|
437
|
+
};
|
|
438
|
+
const md5ext = costumeSource.baseLayerMD5;
|
|
439
|
+
const idParts = StringUtil.splitFirst(md5ext, '.');
|
|
440
|
+
const md5 = idParts[0];
|
|
441
|
+
let ext;
|
|
442
|
+
if (idParts.length === 2 && idParts[1]) {
|
|
443
|
+
ext = idParts[1];
|
|
444
|
+
} else {
|
|
445
|
+
// Default to 'png' if baseLayerMD5 is not formatted correctly
|
|
446
|
+
ext = 'png';
|
|
447
|
+
// Fix costume md5 for later
|
|
448
|
+
costume.md5 = `${costume.md5}.${ext}`;
|
|
449
|
+
}
|
|
450
|
+
costume.dataFormat = ext;
|
|
451
|
+
costume.assetId = md5;
|
|
452
|
+
if (costumeSource.textLayerMD5) {
|
|
453
|
+
costume.textLayerMD5 = StringUtil.splitFirst(costumeSource.textLayerMD5, '.')[0];
|
|
454
|
+
}
|
|
455
|
+
// If there is no internet connection, or if the asset is not in storage
|
|
456
|
+
// for some reason, and we are doing a local .sb2 import, (e.g. zip is provided)
|
|
457
|
+
// the file name of the costume should be the baseLayerID followed by the file ext
|
|
458
|
+
const assetFileName = `${costumeSource.baseLayerID}.${ext}`;
|
|
459
|
+
const textLayerFileName = costumeSource.textLayerID ? `${costumeSource.textLayerID}.png` : null;
|
|
460
|
+
costumePromises.push(deserializeCostume(costume, runtime, zip, assetFileName, textLayerFileName)
|
|
461
|
+
.then(() => loadCostume(costume.md5, costume, runtime, 2 /* optVersion */))
|
|
462
|
+
);
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
// Sounds from JSON
|
|
466
|
+
const {soundBank, soundPromises} = assets;
|
|
467
|
+
if (Object.prototype.hasOwnProperty.call(object, 'sounds')) {
|
|
468
|
+
for (let s = 0; s < object.sounds.length; s++) {
|
|
469
|
+
const soundSource = object.sounds[s];
|
|
470
|
+
const sound = {
|
|
471
|
+
name: soundSource.soundName,
|
|
472
|
+
format: soundSource.format,
|
|
473
|
+
rate: soundSource.rate,
|
|
474
|
+
sampleCount: soundSource.sampleCount,
|
|
475
|
+
// TODO we eventually want this next property to be called
|
|
476
|
+
// md5ext to reflect what it actually contains, however this
|
|
477
|
+
// will be a very extensive change across many repositories
|
|
478
|
+
// and should be done carefully and altogether
|
|
479
|
+
// (for example, the audio engine currently relies on this
|
|
480
|
+
// property to be named 'md5')
|
|
481
|
+
md5: soundSource.md5,
|
|
482
|
+
data: null
|
|
483
|
+
};
|
|
484
|
+
const md5ext = soundSource.md5;
|
|
485
|
+
const idParts = StringUtil.splitFirst(md5ext, '.');
|
|
486
|
+
const md5 = idParts[0];
|
|
487
|
+
const ext = idParts[1].toLowerCase();
|
|
488
|
+
sound.dataFormat = ext;
|
|
489
|
+
sound.assetId = md5;
|
|
490
|
+
// If there is no internet connection, or if the asset is not in storage
|
|
491
|
+
// for some reason, and we are doing a local .sb2 import, (e.g. zip is provided)
|
|
492
|
+
// the file name of the sound should be the soundID (provided from the project.json)
|
|
493
|
+
// followed by the file ext
|
|
494
|
+
const assetFileName = `${soundSource.soundID}.${ext}`;
|
|
495
|
+
soundPromises.push(
|
|
496
|
+
deserializeSound(sound, runtime, zip, assetFileName)
|
|
497
|
+
.then(() => loadSound(sound, runtime, soundBank))
|
|
498
|
+
);
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
// The stage will have child objects; recursively process them.
|
|
503
|
+
const childrenAssets = assets.children;
|
|
504
|
+
if (object.children) {
|
|
505
|
+
for (let m = 0; m < object.children.length; m++) {
|
|
506
|
+
childrenAssets.push(parseScratchAssets(object.children[m], runtime, false, zip));
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
return assets;
|
|
511
|
+
};
|
|
512
|
+
|
|
513
|
+
/**
|
|
514
|
+
* Parse a single "Scratch object" and create all its in-memory VM objects.
|
|
515
|
+
* TODO: parse the "info" section, especially "savedExtensions"
|
|
516
|
+
* @param {!object} object - From-JSON "Scratch object:" sprite, stage, watcher.
|
|
517
|
+
* @param {!Runtime} runtime - Runtime object to load all structures into.
|
|
518
|
+
* @param {ImportedExtensionsInfo} extensions - (in/out) parsed extension information will be stored here.
|
|
519
|
+
* @param {boolean} topLevel - Whether this is the top-level object (stage).
|
|
520
|
+
* @param {?object} zip - Optional zipped assets for local file import
|
|
521
|
+
* @param {object} assets - Promises for assets of this scratch object grouped
|
|
522
|
+
* into costumes and sounds
|
|
523
|
+
* @return {!Promise.<Array.<Target>>} Promise for the loaded targets when ready, or null for unsupported objects.
|
|
524
|
+
*/
|
|
525
|
+
const parseScratchObject = function (object, runtime, extensions, topLevel, zip, assets) {
|
|
526
|
+
if (!Object.prototype.hasOwnProperty.call(object, 'objName')) {
|
|
527
|
+
if (Object.prototype.hasOwnProperty.call(object, 'listName')) {
|
|
528
|
+
// Shim these objects so they can be processed as monitors
|
|
529
|
+
object.cmd = 'contentsOfList:';
|
|
530
|
+
object.param = object.listName;
|
|
531
|
+
object.mode = 'list';
|
|
532
|
+
}
|
|
533
|
+
// Defer parsing monitors until targets are all parsed
|
|
534
|
+
object.deferredMonitor = true;
|
|
535
|
+
return Promise.resolve(object);
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
// Blocks container for this object.
|
|
539
|
+
const blocks = new Blocks(runtime);
|
|
540
|
+
// @todo: For now, load all Scratch objects (stage/sprites) as a Sprite.
|
|
541
|
+
const sprite = new Sprite(blocks, runtime);
|
|
542
|
+
// Sprite/stage name from JSON.
|
|
543
|
+
if (Object.prototype.hasOwnProperty.call(object, 'objName')) {
|
|
544
|
+
if (topLevel && object.objName !== 'Stage') {
|
|
545
|
+
for (const child of object.children) {
|
|
546
|
+
if (!Object.prototype.hasOwnProperty.call(child, 'objName') && child.target === object.objName) {
|
|
547
|
+
child.target = 'Stage';
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
object.objName = 'Stage';
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
sprite.name = object.objName;
|
|
554
|
+
}
|
|
555
|
+
// Costumes from JSON.
|
|
556
|
+
const costumePromises = assets.costumePromises;
|
|
557
|
+
// Sounds from JSON
|
|
558
|
+
const {soundBank, soundPromises} = assets;
|
|
559
|
+
|
|
560
|
+
// Create the first clone, and load its run-state from JSON.
|
|
561
|
+
const target = sprite.createClone(topLevel ? StageLayering.BACKGROUND_LAYER : StageLayering.SPRITE_LAYER);
|
|
562
|
+
|
|
563
|
+
const getVariableId = generateVariableIdGetter(target.id, topLevel);
|
|
564
|
+
|
|
565
|
+
const globalBroadcastMsgObj = globalBroadcastMsgStateGenerator(topLevel);
|
|
566
|
+
const addBroadcastMsg = globalBroadcastMsgObj.broadcastMsgMapUpdater;
|
|
567
|
+
|
|
568
|
+
// Load target properties from JSON.
|
|
569
|
+
if (Object.prototype.hasOwnProperty.call(object, 'variables')) {
|
|
570
|
+
for (let j = 0; j < object.variables.length; j++) {
|
|
571
|
+
const variable = object.variables[j];
|
|
572
|
+
// A variable is a cloud variable if:
|
|
573
|
+
// - the project says it's a cloud variable, and
|
|
574
|
+
// - it's a stage variable, and
|
|
575
|
+
// - the runtime can support another cloud variable
|
|
576
|
+
const isCloud = variable.isPersistent && topLevel && runtime.canAddCloudVariable();
|
|
577
|
+
const newVariable = new Variable(
|
|
578
|
+
getVariableId(variable.name, Variable.SCALAR_TYPE),
|
|
579
|
+
variable.name,
|
|
580
|
+
Variable.SCALAR_TYPE,
|
|
581
|
+
isCloud
|
|
582
|
+
);
|
|
583
|
+
if (isCloud) runtime.addCloudVariable();
|
|
584
|
+
newVariable.value = variable.value;
|
|
585
|
+
target.variables[newVariable.id] = newVariable;
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
// If included, parse any and all comments on the object (this includes top-level
|
|
590
|
+
// workspace comments as well as comments attached to specific blocks)
|
|
591
|
+
const blockComments = {};
|
|
592
|
+
if (Object.prototype.hasOwnProperty.call(object, 'scriptComments')) {
|
|
593
|
+
const comments = object.scriptComments.map(commentDesc => {
|
|
594
|
+
const [
|
|
595
|
+
commentX,
|
|
596
|
+
commentY,
|
|
597
|
+
commentWidth,
|
|
598
|
+
commentHeight,
|
|
599
|
+
commentFullSize,
|
|
600
|
+
flattenedBlockIndex,
|
|
601
|
+
commentText
|
|
602
|
+
] = commentDesc;
|
|
603
|
+
const isBlockComment = commentDesc[5] >= 0;
|
|
604
|
+
const newComment = new Comment(
|
|
605
|
+
null, // generate a new id for this comment
|
|
606
|
+
commentText, // text content of sb2 comment
|
|
607
|
+
// Only serialize x & y position of comment if it's a workspace comment
|
|
608
|
+
// If it's a block comment, we'll let scratch-blocks handle positioning
|
|
609
|
+
isBlockComment ? null : commentX * WORKSPACE_X_SCALE,
|
|
610
|
+
isBlockComment ? null : commentY * WORKSPACE_Y_SCALE,
|
|
611
|
+
commentWidth * WORKSPACE_X_SCALE,
|
|
612
|
+
commentHeight * WORKSPACE_Y_SCALE,
|
|
613
|
+
!commentFullSize
|
|
614
|
+
);
|
|
615
|
+
if (isBlockComment) {
|
|
616
|
+
// commentDesc[5] refers to the index of the block that this
|
|
617
|
+
// comment is attached to -- in a flattened version of the
|
|
618
|
+
// scripts array.
|
|
619
|
+
// If commentDesc[5] is -1, this is a workspace comment (we don't need to do anything
|
|
620
|
+
// extra at this point), otherwise temporarily save the flattened script array
|
|
621
|
+
// index as the blockId property of the new comment. We will
|
|
622
|
+
// change this to refer to the actual block id of the corresponding
|
|
623
|
+
// block when that block gets created
|
|
624
|
+
newComment.blockId = flattenedBlockIndex;
|
|
625
|
+
// Add this comment to the block comments object with its script index
|
|
626
|
+
// as the key
|
|
627
|
+
if (Object.prototype.hasOwnProperty.call(blockComments, flattenedBlockIndex)) {
|
|
628
|
+
blockComments[flattenedBlockIndex].push(newComment);
|
|
629
|
+
} else {
|
|
630
|
+
blockComments[flattenedBlockIndex] = [newComment];
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
return newComment;
|
|
634
|
+
});
|
|
635
|
+
|
|
636
|
+
// Add all the comments that were just created to the target.comments,
|
|
637
|
+
// referenced by id
|
|
638
|
+
comments.forEach(comment => {
|
|
639
|
+
target.comments[comment.id] = comment;
|
|
640
|
+
});
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
// If included, parse any and all scripts/blocks on the object.
|
|
644
|
+
if (Object.prototype.hasOwnProperty.call(object, 'scripts')) {
|
|
645
|
+
parseScripts(object.scripts, blocks, addBroadcastMsg, getVariableId, extensions, blockComments);
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
// If there are any comments referring to a numerical block ID, make them
|
|
649
|
+
// workspace comments. These are comments that were originally created as
|
|
650
|
+
// block comments, detached from the block, and then had the associated
|
|
651
|
+
// block deleted.
|
|
652
|
+
// These comments should be imported as workspace comments
|
|
653
|
+
// by making their blockIDs (which currently refer to non-existing blocks)
|
|
654
|
+
// null (See #1452).
|
|
655
|
+
for (const commentIndex in blockComments) {
|
|
656
|
+
const currBlockComments = blockComments[commentIndex];
|
|
657
|
+
currBlockComments.forEach(c => {
|
|
658
|
+
if (typeof c.blockId === 'number') {
|
|
659
|
+
c.blockId = null;
|
|
660
|
+
}
|
|
661
|
+
});
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
// Update stage specific blocks (e.g. sprite clicked <=> stage clicked)
|
|
665
|
+
blocks.updateTargetSpecificBlocks(topLevel); // topLevel = isStage
|
|
666
|
+
|
|
667
|
+
if (Object.prototype.hasOwnProperty.call(object, 'lists')) {
|
|
668
|
+
for (let k = 0; k < object.lists.length; k++) {
|
|
669
|
+
const list = object.lists[k];
|
|
670
|
+
const newVariable = new Variable(
|
|
671
|
+
getVariableId(list.listName, Variable.LIST_TYPE),
|
|
672
|
+
list.listName,
|
|
673
|
+
Variable.LIST_TYPE,
|
|
674
|
+
false
|
|
675
|
+
);
|
|
676
|
+
newVariable.value = list.contents;
|
|
677
|
+
target.variables[newVariable.id] = newVariable;
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
if (Object.prototype.hasOwnProperty.call(object, 'scratchX')) {
|
|
681
|
+
target.x = object.scratchX;
|
|
682
|
+
}
|
|
683
|
+
if (Object.prototype.hasOwnProperty.call(object, 'scratchY')) {
|
|
684
|
+
target.y = object.scratchY;
|
|
685
|
+
}
|
|
686
|
+
if (Object.prototype.hasOwnProperty.call(object, 'direction')) {
|
|
687
|
+
// Sometimes the direction can be outside of the range: LLK/scratch-gui#5806
|
|
688
|
+
// wrapClamp it (like we do on RenderedTarget.setDirection)
|
|
689
|
+
target.direction = MathUtil.wrapClamp(object.direction, -179, 180);
|
|
690
|
+
}
|
|
691
|
+
if (Object.prototype.hasOwnProperty.call(object, 'isDraggable')) {
|
|
692
|
+
target.draggable = object.isDraggable;
|
|
693
|
+
}
|
|
694
|
+
if (Object.prototype.hasOwnProperty.call(object, 'scale')) {
|
|
695
|
+
// SB2 stores as 1.0 = 100%; we use % in the VM.
|
|
696
|
+
target.size = object.scale * 100;
|
|
697
|
+
}
|
|
698
|
+
if (Object.prototype.hasOwnProperty.call(object, 'visible')) {
|
|
699
|
+
target.visible = object.visible;
|
|
700
|
+
}
|
|
701
|
+
if (Object.prototype.hasOwnProperty.call(object, 'currentCostumeIndex')) {
|
|
702
|
+
// Current costume index can sometimes be a floating
|
|
703
|
+
// point number, use Math.floor to come up with an appropriate index
|
|
704
|
+
// and clamp it to the actual number of costumes the object has for good measure.
|
|
705
|
+
target.currentCostume = MathUtil.clamp(Math.floor(object.currentCostumeIndex), 0, object.costumes.length - 1);
|
|
706
|
+
}
|
|
707
|
+
if (Object.prototype.hasOwnProperty.call(object, 'rotationStyle')) {
|
|
708
|
+
if (object.rotationStyle === 'none') {
|
|
709
|
+
target.rotationStyle = RenderedTarget.ROTATION_STYLE_NONE;
|
|
710
|
+
} else if (object.rotationStyle === 'leftRight') {
|
|
711
|
+
target.rotationStyle = RenderedTarget.ROTATION_STYLE_LEFT_RIGHT;
|
|
712
|
+
} else if (object.rotationStyle === 'normal') {
|
|
713
|
+
target.rotationStyle = RenderedTarget.ROTATION_STYLE_ALL_AROUND;
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
if (Object.prototype.hasOwnProperty.call(object, 'tempoBPM')) {
|
|
717
|
+
target.tempo = object.tempoBPM;
|
|
718
|
+
}
|
|
719
|
+
if (Object.prototype.hasOwnProperty.call(object, 'videoAlpha')) {
|
|
720
|
+
// SB2 stores alpha as opacity, where 1.0 is opaque.
|
|
721
|
+
// We convert to a percentage, and invert it so 100% is full transparency.
|
|
722
|
+
target.videoTransparency = 100 - (100 * object.videoAlpha);
|
|
723
|
+
}
|
|
724
|
+
if (Object.prototype.hasOwnProperty.call(object, 'info')) {
|
|
725
|
+
if (Object.prototype.hasOwnProperty.call(object.info, 'videoOn')) {
|
|
726
|
+
if (object.info.videoOn) {
|
|
727
|
+
target.videoState = RenderedTarget.VIDEO_STATE.ON;
|
|
728
|
+
} else {
|
|
729
|
+
target.videoState = RenderedTarget.VIDEO_STATE.OFF;
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
if (Object.prototype.hasOwnProperty.call(object, 'indexInLibrary')) {
|
|
734
|
+
// Temporarily store the 'indexInLibrary' property from the sb2 file
|
|
735
|
+
// so that we can correctly order sprites in the target pane.
|
|
736
|
+
// This will be deleted after we are done parsing and ordering the targets list.
|
|
737
|
+
target.targetPaneOrder = object.indexInLibrary;
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
target.isStage = topLevel;
|
|
741
|
+
|
|
742
|
+
Promise.all(costumePromises).then(costumes => {
|
|
743
|
+
sprite.costumes = costumes;
|
|
744
|
+
});
|
|
745
|
+
|
|
746
|
+
Promise.all(soundPromises).then(sounds => {
|
|
747
|
+
sprite.sounds = sounds;
|
|
748
|
+
// Make sure if soundBank is undefined, sprite.soundBank is then null.
|
|
749
|
+
sprite.soundBank = soundBank || null;
|
|
750
|
+
});
|
|
751
|
+
|
|
752
|
+
// The stage will have child objects; recursively process them.
|
|
753
|
+
const childrenPromises = [];
|
|
754
|
+
if (object.children) {
|
|
755
|
+
for (let m = 0; m < object.children.length; m++) {
|
|
756
|
+
childrenPromises.push(
|
|
757
|
+
parseScratchObject(object.children[m], runtime, extensions, false, zip, assets.children[m])
|
|
758
|
+
);
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
return Promise.all(
|
|
763
|
+
costumePromises.concat(soundPromises)
|
|
764
|
+
).then(() =>
|
|
765
|
+
Promise.all(
|
|
766
|
+
childrenPromises
|
|
767
|
+
).then(children => {
|
|
768
|
+
// Need create broadcast msgs as variables after
|
|
769
|
+
// all other targets have finished processing.
|
|
770
|
+
if (target.isStage) {
|
|
771
|
+
const allBroadcastMsgs = globalBroadcastMsgObj.globalBroadcastMsgs;
|
|
772
|
+
const allBroadcastMsgFields = globalBroadcastMsgObj.allBroadcastFields;
|
|
773
|
+
const oldEmptyMsgName = globalBroadcastMsgObj.emptyMsgName;
|
|
774
|
+
if (allBroadcastMsgs[oldEmptyMsgName]) {
|
|
775
|
+
// Find a fresh 'messageN'
|
|
776
|
+
let currIndex = 1;
|
|
777
|
+
while (allBroadcastMsgs[`message${currIndex}`]) {
|
|
778
|
+
currIndex += 1;
|
|
779
|
+
}
|
|
780
|
+
const newEmptyMsgName = `message${currIndex}`;
|
|
781
|
+
// Add the new empty message name to the broadcast message
|
|
782
|
+
// name map, and assign it the old id.
|
|
783
|
+
// Then, delete the old entry in map.
|
|
784
|
+
allBroadcastMsgs[newEmptyMsgName] = allBroadcastMsgs[oldEmptyMsgName];
|
|
785
|
+
delete allBroadcastMsgs[oldEmptyMsgName];
|
|
786
|
+
// Now update all the broadcast message fields with
|
|
787
|
+
// the new empty message name.
|
|
788
|
+
for (let i = 0; i < allBroadcastMsgFields.length; i++) {
|
|
789
|
+
if (allBroadcastMsgFields[i].value === '') {
|
|
790
|
+
allBroadcastMsgFields[i].value = newEmptyMsgName;
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
// Traverse the broadcast message name map and create
|
|
795
|
+
// broadcast messages as variables on the stage (which is this
|
|
796
|
+
// target).
|
|
797
|
+
for (const msgName in allBroadcastMsgs) {
|
|
798
|
+
const msgId = allBroadcastMsgs[msgName];
|
|
799
|
+
const newMsg = new Variable(
|
|
800
|
+
msgId,
|
|
801
|
+
msgName,
|
|
802
|
+
Variable.BROADCAST_MESSAGE_TYPE,
|
|
803
|
+
false
|
|
804
|
+
);
|
|
805
|
+
target.variables[newMsg.id] = newMsg;
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
let targets = [target];
|
|
809
|
+
const deferredMonitors = [];
|
|
810
|
+
for (let n = 0; n < children.length; n++) {
|
|
811
|
+
if (children[n]) {
|
|
812
|
+
if (children[n].deferredMonitor) {
|
|
813
|
+
deferredMonitors.push(children[n]);
|
|
814
|
+
} else {
|
|
815
|
+
targets = targets.concat(children[n]);
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
// It is important that monitors are parsed last
|
|
820
|
+
// - after all sprite targets have finished parsing
|
|
821
|
+
// - and this is the last thing that happens in the stage parsing
|
|
822
|
+
// It is specifically important that all the scripts in the project
|
|
823
|
+
// have been parsed and all the relevant targets exist, have uids,
|
|
824
|
+
// and have their variables initialized.
|
|
825
|
+
for (let n = 0; n < deferredMonitors.length; n++) {
|
|
826
|
+
parseMonitorObject(deferredMonitors[n], runtime, targets, extensions);
|
|
827
|
+
}
|
|
828
|
+
return targets;
|
|
829
|
+
})
|
|
830
|
+
);
|
|
831
|
+
};
|
|
832
|
+
|
|
833
|
+
const reorderParsedTargets = function (targets) {
|
|
834
|
+
// Reorder parsed targets based on the temporary targetPaneOrder property
|
|
835
|
+
// and then delete it.
|
|
836
|
+
|
|
837
|
+
const reordered = targets.map((t, index) => {
|
|
838
|
+
t.layerOrder = index;
|
|
839
|
+
return t;
|
|
840
|
+
}).sort((a, b) => a.targetPaneOrder - b.targetPaneOrder);
|
|
841
|
+
|
|
842
|
+
// Delete the temporary target pane ordering since we shouldn't need it anymore.
|
|
843
|
+
reordered.forEach(t => {
|
|
844
|
+
delete t.targetPaneOrder;
|
|
845
|
+
});
|
|
846
|
+
|
|
847
|
+
return reordered;
|
|
848
|
+
};
|
|
849
|
+
|
|
850
|
+
|
|
851
|
+
/**
|
|
852
|
+
* Top-level handler. Parse provided JSON,
|
|
853
|
+
* and process the top-level object (the stage object).
|
|
854
|
+
* @param {!object} json SB2-format JSON to load.
|
|
855
|
+
* @param {!Runtime} runtime Runtime object to load all structures into.
|
|
856
|
+
* @param {boolean=} optForceSprite If set, treat as sprite (Sprite2).
|
|
857
|
+
* @param {?object} zip Optional zipped assets for local file import
|
|
858
|
+
* @return {Promise.<ImportedProject>} Promise that resolves to the loaded targets when ready.
|
|
859
|
+
*/
|
|
860
|
+
const sb2import = function (json, runtime, optForceSprite, zip) {
|
|
861
|
+
const extensions = {
|
|
862
|
+
extensionIDs: new Set(),
|
|
863
|
+
extensionURLs: new Map()
|
|
864
|
+
};
|
|
865
|
+
return Promise.resolve(parseScratchAssets(json, runtime, !optForceSprite, zip))
|
|
866
|
+
// Force this promise to wait for the next loop in the js tick. Let
|
|
867
|
+
// storage have some time to send off asset requests.
|
|
868
|
+
.then(assets => Promise.resolve(assets))
|
|
869
|
+
.then(assets => (
|
|
870
|
+
parseScratchObject(json, runtime, extensions, !optForceSprite, zip, assets)
|
|
871
|
+
))
|
|
872
|
+
.then(reorderParsedTargets)
|
|
873
|
+
.then(targets => ({
|
|
874
|
+
targets,
|
|
875
|
+
extensions
|
|
876
|
+
}));
|
|
877
|
+
};
|
|
878
|
+
|
|
879
|
+
/**
|
|
880
|
+
* Given the sb2 block, inspect the specmap for a translation method or object.
|
|
881
|
+
* @param {!object} block a sb2 formatted block
|
|
882
|
+
* @return {object} specmap block to parse this opcode
|
|
883
|
+
*/
|
|
884
|
+
const specMapBlock = function (block) {
|
|
885
|
+
const opcode = block[0];
|
|
886
|
+
const mapped = opcode && specMap[opcode];
|
|
887
|
+
if (!mapped) {
|
|
888
|
+
log.warn(`Couldn't find SB2 block: ${opcode}`);
|
|
889
|
+
return null;
|
|
890
|
+
}
|
|
891
|
+
if (typeof mapped === 'function') {
|
|
892
|
+
return mapped(block);
|
|
893
|
+
}
|
|
894
|
+
return mapped;
|
|
895
|
+
};
|
|
896
|
+
|
|
897
|
+
/**
|
|
898
|
+
* Parse a single SB2 JSON-formatted block and its children.
|
|
899
|
+
* @param {!object} sb2block SB2 JSON-formatted block.
|
|
900
|
+
* @param {Function} addBroadcastMsg function to update broadcast message name map
|
|
901
|
+
* @param {Function} getVariableId function to retrieve a variable's ID based on name
|
|
902
|
+
* @param {ImportedExtensionsInfo} extensions - (in/out) parsed extension information will be stored here.
|
|
903
|
+
* @param {ParseState} parseState - info on the state of parsing beyond the current block.
|
|
904
|
+
* @param {object<int, Comment>} comments - Comments from sb2 project that need to be attached to blocks.
|
|
905
|
+
* They are indexed in this object by the sb2 flattened block list index indicating
|
|
906
|
+
* which block they should attach to.
|
|
907
|
+
* @param {int} commentIndex The comment index for the block to be parsed if it were in a flattened
|
|
908
|
+
* list of all blocks for the target
|
|
909
|
+
* @return {Array.<object|int>} Tuple where first item is the Scratch VM-format block (or null if unsupported object),
|
|
910
|
+
* and second item is the updated comment index (after this block and its children are parsed)
|
|
911
|
+
*/
|
|
912
|
+
const parseBlock = function (sb2block, addBroadcastMsg, getVariableId, extensions, parseState, comments, commentIndex) {
|
|
913
|
+
const commentsForParsedBlock = (comments && typeof commentIndex === 'number' && !isNaN(commentIndex)) ?
|
|
914
|
+
comments[commentIndex] : null;
|
|
915
|
+
const blockMetadata = specMapBlock(sb2block);
|
|
916
|
+
if (!blockMetadata) {
|
|
917
|
+
// No block opcode found, exclude this block, increment the commentIndex,
|
|
918
|
+
// make all block comments into workspace comments and send them to zero/zero
|
|
919
|
+
// to prevent serialization issues.
|
|
920
|
+
if (commentsForParsedBlock) {
|
|
921
|
+
commentsForParsedBlock.forEach(comment => {
|
|
922
|
+
comment.blockId = null;
|
|
923
|
+
comment.x = comment.y = 0;
|
|
924
|
+
});
|
|
925
|
+
}
|
|
926
|
+
return [null, commentIndex + 1];
|
|
927
|
+
}
|
|
928
|
+
const oldOpcode = sb2block[0];
|
|
929
|
+
|
|
930
|
+
// If the block is from an extension, record it.
|
|
931
|
+
const index = blockMetadata.opcode.indexOf('_');
|
|
932
|
+
const prefix = blockMetadata.opcode.substring(0, index);
|
|
933
|
+
if (CORE_EXTENSIONS.indexOf(prefix) === -1) {
|
|
934
|
+
if (prefix !== '') extensions.extensionIDs.add(prefix);
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
// Block skeleton.
|
|
938
|
+
const activeBlock = {
|
|
939
|
+
id: uid(), // Generate a new block unique ID.
|
|
940
|
+
opcode: blockMetadata.opcode, // Converted, e.g. "motion_movesteps".
|
|
941
|
+
inputs: {}, // Inputs to this block and the blocks they point to.
|
|
942
|
+
fields: {}, // Fields on this block and their values.
|
|
943
|
+
next: null, // Next block.
|
|
944
|
+
shadow: false, // No shadow blocks in an SB2 by default.
|
|
945
|
+
children: [] // Store any generated children, flattened in `flatten`.
|
|
946
|
+
};
|
|
947
|
+
|
|
948
|
+
// Attach any comments to this block..
|
|
949
|
+
if (commentsForParsedBlock) {
|
|
950
|
+
// Attach only the last comment to the block, make all others workspace comments
|
|
951
|
+
activeBlock.comment = commentsForParsedBlock[commentsForParsedBlock.length - 1].id;
|
|
952
|
+
commentsForParsedBlock.forEach(comment => {
|
|
953
|
+
if (comment.id === activeBlock.comment) {
|
|
954
|
+
comment.blockId = activeBlock.id;
|
|
955
|
+
} else {
|
|
956
|
+
// All other comments don't get a block ID and are sent back to zero.
|
|
957
|
+
// This is important, because if they have `null` x/y, serialization breaks.
|
|
958
|
+
comment.blockId = null;
|
|
959
|
+
comment.x = comment.y = 0;
|
|
960
|
+
}
|
|
961
|
+
});
|
|
962
|
+
}
|
|
963
|
+
commentIndex++;
|
|
964
|
+
|
|
965
|
+
const parentExpectedArg = parseState.expectedArg;
|
|
966
|
+
|
|
967
|
+
// For a procedure call, generate argument map from proc string.
|
|
968
|
+
if (oldOpcode === 'call') {
|
|
969
|
+
blockMetadata.argMap = parseProcedureArgMap(sb2block[1]);
|
|
970
|
+
}
|
|
971
|
+
// Look at the expected arguments in `blockMetadata.argMap.`
|
|
972
|
+
// The basic problem here is to turn positional SB2 arguments into
|
|
973
|
+
// non-positional named Scratch VM arguments.
|
|
974
|
+
for (let i = 0; i < blockMetadata.argMap.length; i++) {
|
|
975
|
+
const expectedArg = blockMetadata.argMap[i];
|
|
976
|
+
const providedArg = sb2block[i + 1]; // (i = 0 is opcode)
|
|
977
|
+
// Whether the input is obscuring a shadow.
|
|
978
|
+
let shadowObscured = false;
|
|
979
|
+
// Positional argument is an input.
|
|
980
|
+
if (expectedArg.type === 'input') {
|
|
981
|
+
// Create a new block and input metadata.
|
|
982
|
+
const inputUid = uid();
|
|
983
|
+
activeBlock.inputs[expectedArg.inputName] = {
|
|
984
|
+
name: expectedArg.inputName,
|
|
985
|
+
block: null,
|
|
986
|
+
shadow: null
|
|
987
|
+
};
|
|
988
|
+
if (typeof providedArg === 'object' && providedArg) {
|
|
989
|
+
// Block or block list occupies the input.
|
|
990
|
+
let innerBlocks;
|
|
991
|
+
parseState.expectedArg = expectedArg;
|
|
992
|
+
if (typeof providedArg[0] === 'object' && providedArg[0]) {
|
|
993
|
+
// Block list occupies the input.
|
|
994
|
+
[innerBlocks, commentIndex] = parseBlockList(providedArg, addBroadcastMsg, getVariableId,
|
|
995
|
+
extensions, parseState, comments, commentIndex);
|
|
996
|
+
} else {
|
|
997
|
+
// Single block occupies the input.
|
|
998
|
+
const parsedBlockDesc = parseBlock(providedArg, addBroadcastMsg, getVariableId, extensions,
|
|
999
|
+
parseState, comments, commentIndex);
|
|
1000
|
+
innerBlocks = parsedBlockDesc[0] ? [parsedBlockDesc[0]] : [];
|
|
1001
|
+
// Update commentIndex
|
|
1002
|
+
commentIndex = parsedBlockDesc[1];
|
|
1003
|
+
}
|
|
1004
|
+
parseState.expectedArg = parentExpectedArg;
|
|
1005
|
+
|
|
1006
|
+
// Check if innerBlocks is not an empty list.
|
|
1007
|
+
// An empty list indicates that all the inner blocks from the sb2 have
|
|
1008
|
+
// unknown opcodes and have been skipped.
|
|
1009
|
+
if (innerBlocks.length > 0) {
|
|
1010
|
+
let previousBlock = null;
|
|
1011
|
+
for (let j = 0; j < innerBlocks.length; j++) {
|
|
1012
|
+
if (j === 0) {
|
|
1013
|
+
innerBlocks[j].parent = activeBlock.id;
|
|
1014
|
+
} else {
|
|
1015
|
+
innerBlocks[j].parent = previousBlock;
|
|
1016
|
+
}
|
|
1017
|
+
previousBlock = innerBlocks[j].id;
|
|
1018
|
+
}
|
|
1019
|
+
activeBlock.inputs[expectedArg.inputName].block = (
|
|
1020
|
+
innerBlocks[0].id
|
|
1021
|
+
);
|
|
1022
|
+
activeBlock.children = (
|
|
1023
|
+
activeBlock.children.concat(innerBlocks)
|
|
1024
|
+
);
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
// Obscures any shadow.
|
|
1028
|
+
shadowObscured = true;
|
|
1029
|
+
}
|
|
1030
|
+
// Generate a shadow block to occupy the input.
|
|
1031
|
+
if (!expectedArg.inputOp) {
|
|
1032
|
+
// Undefined inputOp. inputOp should always be defined for inputs.
|
|
1033
|
+
log.warn(`Unknown input operation for input ${expectedArg.inputName} of opcode ${activeBlock.opcode}.`);
|
|
1034
|
+
continue;
|
|
1035
|
+
}
|
|
1036
|
+
if (expectedArg.inputOp === 'boolean' || expectedArg.inputOp === 'substack') {
|
|
1037
|
+
// No editable shadow input; e.g., for a boolean.
|
|
1038
|
+
continue;
|
|
1039
|
+
}
|
|
1040
|
+
// Each shadow has a field generated for it automatically.
|
|
1041
|
+
// Value to be filled in the field.
|
|
1042
|
+
let fieldValue = providedArg;
|
|
1043
|
+
// Shadows' field names match the input name, except for these:
|
|
1044
|
+
let fieldName = expectedArg.inputName;
|
|
1045
|
+
if (expectedArg.inputOp === 'math_number' ||
|
|
1046
|
+
expectedArg.inputOp === 'math_whole_number' ||
|
|
1047
|
+
expectedArg.inputOp === 'math_positive_number' ||
|
|
1048
|
+
expectedArg.inputOp === 'math_integer' ||
|
|
1049
|
+
expectedArg.inputOp === 'math_angle') {
|
|
1050
|
+
fieldName = 'NUM';
|
|
1051
|
+
// Fields are given Scratch 2.0 default values if obscured.
|
|
1052
|
+
if (shadowObscured) {
|
|
1053
|
+
fieldValue = 10;
|
|
1054
|
+
}
|
|
1055
|
+
} else if (expectedArg.inputOp === 'text') {
|
|
1056
|
+
fieldName = 'TEXT';
|
|
1057
|
+
if (shadowObscured) {
|
|
1058
|
+
fieldValue = '';
|
|
1059
|
+
}
|
|
1060
|
+
} else if (expectedArg.inputOp === 'colour_picker') {
|
|
1061
|
+
// Convert SB2 color to hex.
|
|
1062
|
+
fieldValue = Color.decimalToHex(providedArg);
|
|
1063
|
+
fieldName = 'COLOUR';
|
|
1064
|
+
if (shadowObscured) {
|
|
1065
|
+
fieldValue = '#990000';
|
|
1066
|
+
}
|
|
1067
|
+
} else if (expectedArg.inputOp === 'event_broadcast_menu') {
|
|
1068
|
+
fieldName = 'BROADCAST_OPTION';
|
|
1069
|
+
if (shadowObscured) {
|
|
1070
|
+
fieldValue = '';
|
|
1071
|
+
}
|
|
1072
|
+
} else if (expectedArg.inputOp === 'sensing_of_object_menu') {
|
|
1073
|
+
if (shadowObscured) {
|
|
1074
|
+
fieldValue = '_stage_';
|
|
1075
|
+
} else if (fieldValue === 'Stage') {
|
|
1076
|
+
fieldValue = '_stage_';
|
|
1077
|
+
}
|
|
1078
|
+
} else if (expectedArg.inputOp === 'note') {
|
|
1079
|
+
if (shadowObscured) {
|
|
1080
|
+
fieldValue = 60;
|
|
1081
|
+
}
|
|
1082
|
+
} else if (expectedArg.inputOp === 'music.menu.DRUM') {
|
|
1083
|
+
if (shadowObscured) {
|
|
1084
|
+
fieldValue = 1;
|
|
1085
|
+
}
|
|
1086
|
+
} else if (expectedArg.inputOp === 'music.menu.INSTRUMENT') {
|
|
1087
|
+
if (shadowObscured) {
|
|
1088
|
+
fieldValue = 1;
|
|
1089
|
+
}
|
|
1090
|
+
} else if (expectedArg.inputOp === 'videoSensing.menu.ATTRIBUTE') {
|
|
1091
|
+
if (shadowObscured) {
|
|
1092
|
+
fieldValue = 'motion';
|
|
1093
|
+
}
|
|
1094
|
+
} else if (expectedArg.inputOp === 'videoSensing.menu.SUBJECT') {
|
|
1095
|
+
if (shadowObscured) {
|
|
1096
|
+
fieldValue = 'this sprite';
|
|
1097
|
+
}
|
|
1098
|
+
} else if (expectedArg.inputOp === 'videoSensing.menu.VIDEO_STATE') {
|
|
1099
|
+
if (shadowObscured) {
|
|
1100
|
+
fieldValue = 'on';
|
|
1101
|
+
}
|
|
1102
|
+
} else if (shadowObscured) {
|
|
1103
|
+
// Filled drop-down menu.
|
|
1104
|
+
fieldValue = '';
|
|
1105
|
+
}
|
|
1106
|
+
const fields = {};
|
|
1107
|
+
fields[fieldName] = {
|
|
1108
|
+
name: fieldName,
|
|
1109
|
+
value: fieldValue
|
|
1110
|
+
};
|
|
1111
|
+
// event_broadcast_menus have some extra properties to add to the
|
|
1112
|
+
// field and a different value than the rest
|
|
1113
|
+
if (expectedArg.inputOp === 'event_broadcast_menu') {
|
|
1114
|
+
// Need to update the broadcast message name map with
|
|
1115
|
+
// the value of this field.
|
|
1116
|
+
// Also need to provide the fields[fieldName] object,
|
|
1117
|
+
// so that we can later update its value property, e.g.
|
|
1118
|
+
// if sb2 message name is empty string, we will later
|
|
1119
|
+
// replace this field's value with messageN
|
|
1120
|
+
// once we can traverse through all the existing message names
|
|
1121
|
+
// and come up with a fresh messageN.
|
|
1122
|
+
const broadcastId = addBroadcastMsg(fieldValue, fields[fieldName]);
|
|
1123
|
+
fields[fieldName].id = broadcastId;
|
|
1124
|
+
fields[fieldName].variableType = expectedArg.variableType;
|
|
1125
|
+
}
|
|
1126
|
+
activeBlock.children.push({
|
|
1127
|
+
id: inputUid,
|
|
1128
|
+
opcode: expectedArg.inputOp,
|
|
1129
|
+
inputs: {},
|
|
1130
|
+
fields: fields,
|
|
1131
|
+
next: null,
|
|
1132
|
+
topLevel: false,
|
|
1133
|
+
parent: activeBlock.id,
|
|
1134
|
+
shadow: true
|
|
1135
|
+
});
|
|
1136
|
+
activeBlock.inputs[expectedArg.inputName].shadow = inputUid;
|
|
1137
|
+
// If no block occupying the input, alias to the shadow.
|
|
1138
|
+
if (!activeBlock.inputs[expectedArg.inputName].block) {
|
|
1139
|
+
activeBlock.inputs[expectedArg.inputName].block = inputUid;
|
|
1140
|
+
}
|
|
1141
|
+
} else if (expectedArg.type === 'field') {
|
|
1142
|
+
// Add as a field on this block.
|
|
1143
|
+
activeBlock.fields[expectedArg.fieldName] = {
|
|
1144
|
+
name: expectedArg.fieldName,
|
|
1145
|
+
value: providedArg
|
|
1146
|
+
};
|
|
1147
|
+
|
|
1148
|
+
if (expectedArg.fieldName === 'CURRENTMENU') {
|
|
1149
|
+
// In 3.0, the field value of the `sensing_current` block
|
|
1150
|
+
// is in all caps.
|
|
1151
|
+
activeBlock.fields[expectedArg.fieldName].value = providedArg.toUpperCase();
|
|
1152
|
+
if (providedArg === 'day of week') {
|
|
1153
|
+
activeBlock.fields[expectedArg.fieldName].value = 'DAYOFWEEK';
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
if (expectedArg.fieldName === 'VARIABLE') {
|
|
1158
|
+
// Add `id` property to variable fields
|
|
1159
|
+
activeBlock.fields[expectedArg.fieldName].id = getVariableId(providedArg, Variable.SCALAR_TYPE);
|
|
1160
|
+
} else if (expectedArg.fieldName === 'LIST') {
|
|
1161
|
+
// Add `id` property to variable fields
|
|
1162
|
+
activeBlock.fields[expectedArg.fieldName].id = getVariableId(providedArg, Variable.LIST_TYPE);
|
|
1163
|
+
} else if (expectedArg.fieldName === 'BROADCAST_OPTION') {
|
|
1164
|
+
// Add the name in this field to the broadcast msg name map.
|
|
1165
|
+
// Also need to provide the fields[fieldName] object,
|
|
1166
|
+
// so that we can later update its value property, e.g.
|
|
1167
|
+
// if sb2 message name is empty string, we will later
|
|
1168
|
+
// replace this field's value with messageN
|
|
1169
|
+
// once we can traverse through all the existing message names
|
|
1170
|
+
// and come up with a fresh messageN.
|
|
1171
|
+
const broadcastId = addBroadcastMsg(providedArg, activeBlock.fields[expectedArg.fieldName]);
|
|
1172
|
+
activeBlock.fields[expectedArg.fieldName].id = broadcastId;
|
|
1173
|
+
}
|
|
1174
|
+
const varType = expectedArg.variableType;
|
|
1175
|
+
if (typeof varType === 'string') {
|
|
1176
|
+
activeBlock.fields[expectedArg.fieldName].variableType = varType;
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
// Updates for blocks that have new menus (e.g. in Looks)
|
|
1182
|
+
switch (oldOpcode) {
|
|
1183
|
+
case 'comeToFront':
|
|
1184
|
+
activeBlock.fields.FRONT_BACK = {
|
|
1185
|
+
name: 'FRONT_BACK',
|
|
1186
|
+
value: 'front'
|
|
1187
|
+
};
|
|
1188
|
+
break;
|
|
1189
|
+
case 'goBackByLayers:':
|
|
1190
|
+
activeBlock.fields.FORWARD_BACKWARD = {
|
|
1191
|
+
name: 'FORWARD_BACKWARD',
|
|
1192
|
+
value: 'backward'
|
|
1193
|
+
};
|
|
1194
|
+
break;
|
|
1195
|
+
case 'backgroundIndex':
|
|
1196
|
+
activeBlock.fields.NUMBER_NAME = {
|
|
1197
|
+
name: 'NUMBER_NAME',
|
|
1198
|
+
value: 'number'
|
|
1199
|
+
};
|
|
1200
|
+
break;
|
|
1201
|
+
case 'sceneName':
|
|
1202
|
+
activeBlock.fields.NUMBER_NAME = {
|
|
1203
|
+
name: 'NUMBER_NAME',
|
|
1204
|
+
value: 'name'
|
|
1205
|
+
};
|
|
1206
|
+
break;
|
|
1207
|
+
case 'costumeIndex':
|
|
1208
|
+
activeBlock.fields.NUMBER_NAME = {
|
|
1209
|
+
name: 'NUMBER_NAME',
|
|
1210
|
+
value: 'number'
|
|
1211
|
+
};
|
|
1212
|
+
break;
|
|
1213
|
+
case 'costumeName':
|
|
1214
|
+
activeBlock.fields.NUMBER_NAME = {
|
|
1215
|
+
name: 'NUMBER_NAME',
|
|
1216
|
+
value: 'name'
|
|
1217
|
+
};
|
|
1218
|
+
break;
|
|
1219
|
+
}
|
|
1220
|
+
|
|
1221
|
+
// Special cases to generate mutations.
|
|
1222
|
+
if (oldOpcode === 'stopScripts') {
|
|
1223
|
+
// Mutation for stop block: if the argument is 'other scripts',
|
|
1224
|
+
// the block needs a next connection.
|
|
1225
|
+
if (sb2block[1] === 'other scripts in sprite' ||
|
|
1226
|
+
sb2block[1] === 'other scripts in stage') {
|
|
1227
|
+
activeBlock.mutation = {
|
|
1228
|
+
tagName: 'mutation',
|
|
1229
|
+
hasnext: 'true',
|
|
1230
|
+
children: []
|
|
1231
|
+
};
|
|
1232
|
+
}
|
|
1233
|
+
} else if (oldOpcode === 'procDef') {
|
|
1234
|
+
// Mutation for procedure definition:
|
|
1235
|
+
// store all 2.0 proc data.
|
|
1236
|
+
const procData = sb2block.slice(1);
|
|
1237
|
+
// Create a new block and input metadata.
|
|
1238
|
+
const inputUid = uid();
|
|
1239
|
+
const inputName = 'custom_block';
|
|
1240
|
+
activeBlock.inputs[inputName] = {
|
|
1241
|
+
name: inputName,
|
|
1242
|
+
block: inputUid,
|
|
1243
|
+
shadow: inputUid
|
|
1244
|
+
};
|
|
1245
|
+
activeBlock.children = [{
|
|
1246
|
+
id: inputUid,
|
|
1247
|
+
opcode: 'procedures_prototype',
|
|
1248
|
+
inputs: {},
|
|
1249
|
+
fields: {},
|
|
1250
|
+
next: null,
|
|
1251
|
+
shadow: true,
|
|
1252
|
+
children: [],
|
|
1253
|
+
mutation: {
|
|
1254
|
+
tagName: 'mutation',
|
|
1255
|
+
proccode: procData[0], // e.g., "abc %n %b %s"
|
|
1256
|
+
argumentnames: JSON.stringify(procData[1]), // e.g. ['arg1', 'arg2']
|
|
1257
|
+
argumentids: JSON.stringify(parseProcedureArgIds(procData[0])),
|
|
1258
|
+
argumentdefaults: JSON.stringify(procData[2]), // e.g., [1, 'abc']
|
|
1259
|
+
warp: procData[3], // Warp mode, e.g., true/false.
|
|
1260
|
+
children: []
|
|
1261
|
+
}
|
|
1262
|
+
}];
|
|
1263
|
+
} else if (oldOpcode === 'call') {
|
|
1264
|
+
// Mutation for procedure call:
|
|
1265
|
+
// string for proc code (e.g., "abc %n %b %s").
|
|
1266
|
+
activeBlock.mutation = {
|
|
1267
|
+
tagName: 'mutation',
|
|
1268
|
+
children: [],
|
|
1269
|
+
proccode: sb2block[1],
|
|
1270
|
+
argumentids: JSON.stringify(parseProcedureArgIds(sb2block[1]))
|
|
1271
|
+
};
|
|
1272
|
+
} else if (oldOpcode === 'getParam') {
|
|
1273
|
+
let returnCode = sb2block[2];
|
|
1274
|
+
|
|
1275
|
+
// Ensure the returnCode is "b" if used in a boolean input.
|
|
1276
|
+
if (parentExpectedArg && parentExpectedArg.inputOp === 'boolean' && returnCode !== 'b') {
|
|
1277
|
+
returnCode = 'b';
|
|
1278
|
+
}
|
|
1279
|
+
|
|
1280
|
+
// Assign correct opcode based on the block shape.
|
|
1281
|
+
switch (returnCode) {
|
|
1282
|
+
case 'r':
|
|
1283
|
+
activeBlock.opcode = 'argument_reporter_string_number';
|
|
1284
|
+
break;
|
|
1285
|
+
case 'b':
|
|
1286
|
+
activeBlock.opcode = 'argument_reporter_boolean';
|
|
1287
|
+
break;
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
1290
|
+
return [activeBlock, commentIndex];
|
|
1291
|
+
};
|
|
1292
|
+
|
|
1293
|
+
module.exports = {
|
|
1294
|
+
deserialize: sb2import
|
|
1295
|
+
};
|