forked from scratchfoundation/scratch-vm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathruntime.js
More file actions
1630 lines (1470 loc) · 55.1 KB
/
Copy pathruntime.js
File metadata and controls
1630 lines (1470 loc) · 55.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const EventEmitter = require('events');
const {OrderedMap} = require('immutable');
const escapeHtml = require('escape-html');
const ArgumentType = require('../extension-support/argument-type');
const Blocks = require('./blocks');
const BlockType = require('../extension-support/block-type');
const Sequencer = require('./sequencer');
const Thread = require('./thread');
const Profiler = require('./profiler');
// Virtual I/O devices.
const Clock = require('../io/clock');
const DeviceManager = require('../io/deviceManager');
const Keyboard = require('../io/keyboard');
const Mouse = require('../io/mouse');
const MouseWheel = require('../io/mouseWheel');
const defaultBlockPackages = {
scratch3_control: require('../blocks/scratch3_control'),
scratch3_event: require('../blocks/scratch3_event'),
scratch3_looks: require('../blocks/scratch3_looks'),
scratch3_motion: require('../blocks/scratch3_motion'),
scratch3_operators: require('../blocks/scratch3_operators'),
scratch3_sound: require('../blocks/scratch3_sound'),
scratch3_sensing: require('../blocks/scratch3_sensing'),
scratch3_data: require('../blocks/scratch3_data'),
scratch3_procedures: require('../blocks/scratch3_procedures')
};
/**
* Information used for converting Scratch argument types into scratch-blocks data.
* @type {object.<ArgumentType, {shadowType: string, fieldType: string}>}}
*/
const ArgumentTypeMap = (() => {
const map = {};
map[ArgumentType.ANGLE] = {
shadowType: 'math_angle',
fieldType: 'NUM'
};
map[ArgumentType.COLOR] = {
shadowType: 'colour_picker'
};
map[ArgumentType.NUMBER] = {
shadowType: 'math_number',
fieldType: 'NUM'
};
map[ArgumentType.STRING] = {
shadowType: 'text',
fieldType: 'TEXT'
};
map[ArgumentType.BOOLEAN] = {
check: 'Boolean'
};
return map;
})();
/**
* These constants are copied from scratch-blocks/core/constants.js
* @TODO find a way to require() these... maybe make a scratch-blocks/dist/constants.js or something like that?
* @readonly
* @enum {int}
*/
const ScratchBlocksConstants = {
/**
* ENUM for output shape: hexagonal (booleans/predicates).
* @const
*/
OUTPUT_SHAPE_HEXAGONAL: 1,
/**
* ENUM for output shape: rounded (numbers).
* @const
*/
OUTPUT_SHAPE_ROUND: 2,
/**
* ENUM for output shape: squared (any/all values; strings).
* @const
*/
OUTPUT_SHAPE_SQUARE: 3
};
/**
* Numeric ID for Runtime._step in Profiler instances.
* @type {number}
*/
let stepProfilerId = -1;
/**
* Numeric ID for Sequencer.stepThreads in Profiler instances.
* @type {number}
*/
let stepThreadsProfilerId = -1;
/**
* Numeric ID for RenderWebGL.draw in Profiler instances.
* @type {number}
*/
let rendererDrawProfilerId = -1;
/**
* Manages targets, scripts, and the sequencer.
* @constructor
*/
class Runtime extends EventEmitter {
constructor () {
super();
/**
* Target management and storage.
* @type {Array.<!Target>}
*/
this.targets = [];
/**
* A list of threads that are currently running in the VM.
* Threads are added when execution starts and pruned when execution ends.
* @type {Array.<Thread>}
*/
this.threads = [];
/** @type {!Sequencer} */
this.sequencer = new Sequencer(this);
/**
* Storage container for flyout blocks.
* These will execute on `_editingTarget.`
* @type {!Blocks}
*/
this.flyoutBlocks = new Blocks();
/**
* Storage container for monitor blocks.
* These will execute on a target maybe
* @type {!Blocks}
*/
this.monitorBlocks = new Blocks();
/**
* Currently known editing target for the VM.
* @type {?Target}
*/
this._editingTarget = null;
/**
* Map to look up a block primitive's implementation function by its opcode.
* This is a two-step lookup: package name first, then primitive name.
* @type {Object.<string, Function>}
*/
this._primitives = {};
/**
* Map to look up all block information by extended opcode.
* @type {Array.<CategoryInfo>}
* @private
*/
this._blockInfo = [];
/**
* Map to look up hat blocks' metadata.
* Keys are opcode for hat, values are metadata objects.
* @type {Object.<string, Object>}
*/
this._hats = {};
/**
* Currently known values for edge-activated hats.
* Keys are block ID for the hat; values are the currently known values.
* @type {Object.<string, *>}
*/
this._edgeActivatedHatValues = {};
/**
* A list of script block IDs that were glowing during the previous frame.
* @type {!Array.<!string>}
*/
this._scriptGlowsPreviousFrame = [];
/**
* Number of non-monitor threads running during the previous frame.
* @type {number}
*/
this._nonMonitorThreadCount = 0;
/**
* Currently known number of clones, used to enforce clone limit.
* @type {number}
*/
this._cloneCounter = 0;
/**
* Flag to emit a targets update at the end of a step. When target data
* changes, this flag is set to true.
* @type {boolean}
*/
this._refreshTargets = false;
/**
* Map to look up all monitor block information by opcode.
* @type {object}
* @private
*/
this.monitorBlockInfo = {};
/**
* Ordered map of all monitors, which are MonitorReporter objects.
*/
this._monitorState = OrderedMap({});
/**
* Monitor state from last tick
*/
this._prevMonitorState = OrderedMap({});
/**
* Whether the project is in "turbo mode."
* @type {Boolean}
*/
this.turboMode = false;
/**
* Whether the project is in "compatibility mode" (30 TPS).
* @type {Boolean}
*/
this.compatibilityMode = false;
/**
* A reference to the current runtime stepping interval, set
* by a `setInterval`.
* @type {!number}
*/
this._steppingInterval = null;
/**
* Current length of a step.
* Changes as mode switches, and used by the sequencer to calculate
* WORK_TIME.
* @type {!number}
*/
this.currentStepTime = null;
/**
* Whether any primitive has requested a redraw.
* Affects whether `Sequencer.stepThreads` will yield
* after stepping each thread.
* Reset on every frame.
* @type {boolean}
*/
this.redrawRequested = false;
// Register all given block packages.
this._registerBlockPackages();
// Register and initialize "IO devices", containers for processing
// I/O related data.
/** @type {Object.<string, Object>} */
this.ioDevices = {
clock: new Clock(),
deviceManager: new DeviceManager(),
keyboard: new Keyboard(this),
mouse: new Mouse(this),
mouseWheel: new MouseWheel(this)
};
/**
* A runtime profiler that records timed events for later playback to
* diagnose Scratch performance.
* @type {Profiler}
*/
this.profiler = null;
}
/**
* Width of the stage, in pixels.
* @const {number}
*/
static get STAGE_WIDTH () {
return 480;
}
/**
* Height of the stage, in pixels.
* @const {number}
*/
static get STAGE_HEIGHT () {
return 360;
}
/**
* Event name for glowing a script.
* @const {string}
*/
static get SCRIPT_GLOW_ON () {
return 'SCRIPT_GLOW_ON';
}
/**
* Event name for unglowing a script.
* @const {string}
*/
static get SCRIPT_GLOW_OFF () {
return 'SCRIPT_GLOW_OFF';
}
/**
* Event name for glowing a block.
* @const {string}
*/
static get BLOCK_GLOW_ON () {
return 'BLOCK_GLOW_ON';
}
/**
* Event name for unglowing a block.
* @const {string}
*/
static get BLOCK_GLOW_OFF () {
return 'BLOCK_GLOW_OFF';
}
/**
* Event name when the project is started (threads may not necessarily be
* running).
* @const {string}
*/
static get PROJECT_START () {
return 'PROJECT_START';
}
/**
* Event name when threads start running.
* Used by the UI to indicate running status.
* @const {string}
*/
static get PROJECT_RUN_START () {
return 'PROJECT_RUN_START';
}
/**
* Event name when threads stop running
* Used by the UI to indicate not-running status.
* @const {string}
*/
static get PROJECT_RUN_STOP () {
return 'PROJECT_RUN_STOP';
}
/**
* Event name for project being stopped or restarted by the user.
* Used by blocks that need to reset state.
* @const {string}
*/
static get PROJECT_STOP_ALL () {
return 'PROJECT_STOP_ALL';
}
/**
* Event name for visual value report.
* @const {string}
*/
static get VISUAL_REPORT () {
return 'VISUAL_REPORT';
}
/**
* Event name for targets update report.
* @const {string}
*/
static get TARGETS_UPDATE () {
return 'TARGETS_UPDATE';
}
/**
* Event name for monitors update.
* @const {string}
*/
static get MONITORS_UPDATE () {
return 'MONITORS_UPDATE';
}
/**
* Event name for block drag update.
* @const {string}
*/
static get BLOCK_DRAG_UPDATE () {
return 'BLOCK_DRAG_UPDATE';
}
/**
* Event name for block drag end.
* @const {string}
*/
static get BLOCK_DRAG_END () {
return 'BLOCK_DRAG_END';
}
/**
* Event name for reporting that an extension was added.
* @const {string}
*/
static get EXTENSION_ADDED () {
return 'EXTENSION_ADDED';
}
/**
* Event name for reporting that blocksInfo was updated.
* @const {string}
*/
static get BLOCKSINFO_UPDATE () {
return 'BLOCKSINFO_UPDATE';
}
/**
* How rapidly we try to step threads by default, in ms.
*/
static get THREAD_STEP_INTERVAL () {
return 1000 / 60;
}
/**
* In compatibility mode, how rapidly we try to step threads, in ms.
*/
static get THREAD_STEP_INTERVAL_COMPATIBILITY () {
return 1000 / 30;
}
/**
* How many clones can be created at a time.
* @const {number}
*/
static get MAX_CLONES () {
return 300;
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
/**
* Register default block packages with this runtime.
* @todo Prefix opcodes with package name.
* @private
*/
_registerBlockPackages () {
for (const packageName in defaultBlockPackages) {
if (defaultBlockPackages.hasOwnProperty(packageName)) {
// @todo pass a different runtime depending on package privilege?
const packageObject = new (defaultBlockPackages[packageName])(this);
// Collect primitives from package.
if (packageObject.getPrimitives) {
const packagePrimitives = packageObject.getPrimitives();
for (const op in packagePrimitives) {
if (packagePrimitives.hasOwnProperty(op)) {
this._primitives[op] =
packagePrimitives[op].bind(packageObject);
}
}
}
// Collect hat metadata from package.
if (packageObject.getHats) {
const packageHats = packageObject.getHats();
for (const hatName in packageHats) {
if (packageHats.hasOwnProperty(hatName)) {
this._hats[hatName] = packageHats[hatName];
}
}
}
// Collect monitored from package.
if (packageObject.getMonitored) {
this.monitorBlockInfo = Object.assign({}, this.monitorBlockInfo, packageObject.getMonitored());
}
}
}
}
/**
* Generate an extension-specific menu ID.
* @param {string} menuName - the name of the menu.
* @param {string} extensionId - the ID of the extension hosting the menu.
* @returns {string} - the constructed ID.
* @private
*/
_makeExtensionMenuId (menuName, extensionId) {
return `${extensionId}.menu.${escapeHtml(menuName)}`;
}
/**
* Register the primitives provided by an extension.
* @param {ExtensionInfo} extensionInfo - information about the extension (id, blocks, etc.)
* @private
*/
_registerExtensionPrimitives (extensionInfo) {
const categoryInfo = {
id: extensionInfo.id,
name: extensionInfo.name,
blockIconURI: extensionInfo.blockIconURI,
menuIconURI: extensionInfo.menuIconURI,
color1: '#FF6680',
color2: '#FF4D6A',
color3: '#FF3355',
blocks: [],
menus: []
};
this._blockInfo.push(categoryInfo);
for (const menuName in extensionInfo.menus) {
if (extensionInfo.menus.hasOwnProperty(menuName)) {
const menuItems = extensionInfo.menus[menuName];
const convertedMenu = this._buildMenuForScratchBlocks(menuName, menuItems, categoryInfo);
categoryInfo.menus.push(convertedMenu);
}
}
for (const blockInfo of extensionInfo.blocks) {
const convertedBlock = this._convertForScratchBlocks(blockInfo, categoryInfo);
const opcode = convertedBlock.json.type;
categoryInfo.blocks.push(convertedBlock);
this._primitives[opcode] = convertedBlock.info.func;
if (blockInfo.blockType === BlockType.HAT) {
this._hats[opcode] = {edgeActivated: true}; /** @TODO let extension specify this */
}
}
this.emit(Runtime.EXTENSION_ADDED, categoryInfo.blocks.concat(categoryInfo.menus));
}
/**
* Reregister the primitives for an extension
* @param {ExtensionInfo} extensionInfo - new info (results of running getInfo)
* for an extension
* @private
*/
_refreshExtensionPrimitives (extensionInfo) {
let extensionBlocks = [];
for (const categoryInfo of this._blockInfo) {
if (extensionInfo.id === categoryInfo.id) {
categoryInfo.blocks = [];
categoryInfo.menus = [];
for (const menuName in extensionInfo.menus) {
if (extensionInfo.menus.hasOwnProperty(menuName)) {
const menuItems = extensionInfo.menus[menuName];
const convertedMenu = this._buildMenuForScratchBlocks(menuName, menuItems, categoryInfo);
categoryInfo.menus.push(convertedMenu);
}
}
for (const blockInfo of extensionInfo.blocks) {
const convertedBlock = this._convertForScratchBlocks(blockInfo, categoryInfo);
const opcode = convertedBlock.json.type;
categoryInfo.blocks.push(convertedBlock);
this._primitives[opcode] = convertedBlock.info.func;
if (blockInfo.blockType === BlockType.HAT) {
this._hats[opcode] = {edgeActivated: true}; /** @TODO let extension specify this */
}
}
extensionBlocks = extensionBlocks.concat(categoryInfo.blocks, categoryInfo.menus);
}
}
this.emit(Runtime.BLOCKSINFO_UPDATE, extensionBlocks);
}
/**
* Build the scratch-blocks JSON for a menu. Note that scratch-blocks treats menus as a special kind of block.
* @param {string} menuName - the name of the menu
* @param {array} menuItems - the list of items for this menu
* @param {CategoryInfo} categoryInfo - the category for this block
* @returns {object} - a JSON-esque object ready for scratch-blocks' consumption
* @private
*/
_buildMenuForScratchBlocks (menuName, menuItems, categoryInfo) {
const menuId = this._makeExtensionMenuId(menuName, categoryInfo.id);
let options = null;
if (typeof menuItems === 'function') {
options = menuItems;
} else {
options = menuItems.map(item => {
switch (typeof item) {
case 'string':
return [item, item];
case 'object':
return [item.text, item.value];
default:
throw new Error(`Can't interpret menu item: ${item}`);
}
});
}
return {
json: {
message0: '%1',
type: menuId,
inputsInline: true,
output: 'String',
colour: categoryInfo.color1,
colourSecondary: categoryInfo.color2,
colourTertiary: categoryInfo.color3,
outputShape: ScratchBlocksConstants.OUTPUT_SHAPE_ROUND,
args0: [
{
type: 'field_dropdown',
name: menuName,
options: options
}
]
}
};
}
/**
* Convert BlockInfo into scratch-blocks JSON & XML, and generate a proxy function.
* @param {BlockInfo} blockInfo - the block to convert
* @param {CategoryInfo} categoryInfo - the category for this block
* @returns {{info: BlockInfo, json: object, xml: string}} - the converted & original block information
* @private
*/
_convertForScratchBlocks (blockInfo, categoryInfo) {
const extendedOpcode = `${categoryInfo.id}.${blockInfo.opcode}`;
const blockJSON = {
type: extendedOpcode,
inputsInline: true,
category: categoryInfo.name,
colour: categoryInfo.color1,
colourSecondary: categoryInfo.color2,
colourTertiary: categoryInfo.color3,
args0: [],
extensions: ['scratch_extension']
};
const inputList = [];
// TODO: store this somewhere so that we can map args appropriately after translation.
// This maps an arg name to its relative position in the original (usually English) block text.
// When displaying a block in another language we'll need to run a `replace` action similar to the one below,
// but each `[ARG]` will need to be replaced with the number in this map instead of `args0.length`.
const argsMap = {};
blockJSON.message0 = '';
// If an icon for the extension exists, prepend it to each block, with a vertical separator.
if (categoryInfo.blockIconURI) {
blockJSON.message0 = '%1 %2';
const iconJSON = {
type: 'field_image',
src: categoryInfo.blockIconURI,
width: 40,
height: 40
};
const separatorJSON = {
type: 'field_vertical_separator'
};
blockJSON.args0.push(iconJSON);
blockJSON.args0.push(separatorJSON);
}
blockJSON.message0 += blockInfo.text.replace(/\[(.+?)]/g, (match, placeholder) => {
// Sanitize the placeholder to ensure valid XML
placeholder = placeholder.replace(/[<"&]/, '_');
const argJSON = {
type: 'input_value',
name: placeholder
};
const argInfo = blockInfo.arguments[placeholder] || {};
const argTypeInfo = ArgumentTypeMap[argInfo.type] || {};
const defaultValue = (typeof argInfo.defaultValue === 'undefined' ?
'' :
escapeHtml(argInfo.defaultValue.toString()));
if (argTypeInfo.check) {
argJSON.check = argTypeInfo.check;
}
const shadowType = (argInfo.menu ?
this._makeExtensionMenuId(argInfo.menu, categoryInfo.id) :
argTypeInfo.shadowType);
const fieldType = argInfo.menu || argTypeInfo.fieldType;
// <value> is the ScratchBlocks name for a block input.
inputList.push(`<value name="${placeholder}">`);
// The <shadow> is a placeholder for a reporter and is visible when there's no reporter in this input.
// Boolean inputs don't need to specify a shadow in the XML.
if (shadowType) {
inputList.push(`<shadow type="${shadowType}">`);
// <field> is a text field that the user can type into. Some shadows, like the color picker, don't allow
// text input and therefore don't need a field element.
if (fieldType) {
inputList.push(`<field name="${fieldType}">${defaultValue}</field>`);
}
inputList.push('</shadow>');
}
inputList.push('</value>');
// scratch-blocks uses 1-based argument indexing
blockJSON.args0.push(argJSON);
const argNum = blockJSON.args0.length;
argsMap[placeholder] = argNum;
return `%${argNum}`;
});
switch (blockInfo.blockType) {
case BlockType.COMMAND:
blockJSON.outputShape = ScratchBlocksConstants.OUTPUT_SHAPE_SQUARE;
blockJSON.previousStatement = null; // null = available connection; undefined = hat
if (!blockInfo.isTerminal) {
blockJSON.nextStatement = null; // null = available connection; undefined = terminal
}
break;
case BlockType.REPORTER:
blockJSON.output = 'String'; // TODO: distinguish number & string here?
blockJSON.outputShape = ScratchBlocksConstants.OUTPUT_SHAPE_ROUND;
break;
case BlockType.BOOLEAN:
blockJSON.output = 'Boolean';
blockJSON.outputShape = ScratchBlocksConstants.OUTPUT_SHAPE_HEXAGONAL;
break;
case BlockType.HAT:
blockJSON.outputShape = ScratchBlocksConstants.OUTPUT_SHAPE_SQUARE;
blockJSON.nextStatement = null; // null = available connection; undefined = terminal
break;
case BlockType.CONDITIONAL:
// Statement inputs get names like 'SUBSTACK', 'SUBSTACK2', 'SUBSTACK3', ...
for (let branchNum = 1; branchNum <= blockInfo.branchCount; ++branchNum) {
blockJSON[`message${branchNum}`] = '%1';
blockJSON[`args${branchNum}`] = [{
type: 'input_statement',
name: `SUBSTACK${branchNum > 1 ? branchNum : ''}`
}];
}
blockJSON.outputShape = ScratchBlocksConstants.OUTPUT_SHAPE_SQUARE;
blockJSON.previousStatement = null; // null = available connection; undefined = hat
blockJSON.nextStatement = null; // null = available connection; undefined = terminal
break;
}
if (blockInfo.isTerminal) {
delete blockJSON.nextStatement;
}
const blockXML = `<block type="${extendedOpcode}">${inputList.join('')}</block>`;
return {
info: blockInfo,
json: blockJSON,
xml: blockXML
};
}
/**
* @returns {string} scratch-blocks XML description for all dynamic blocks, wrapped in <category> elements.
*/
getBlocksXML () {
const xmlParts = [];
for (const categoryInfo of this._blockInfo) {
const {name, color1, color2} = categoryInfo;
const paletteBlocks = categoryInfo.blocks.filter(block => !block.info.hideFromPalette);
const colorXML = `colour="${color1}" secondaryColour="${color2}"`;
// Use a menu icon if there is one. Otherwise, use the block icon. If there's no icon,
// the category menu will show its default colored circle.
let menuIconURI = '';
if (categoryInfo.menuIconURI) {
menuIconURI = categoryInfo.menuIconURI;
} else if (categoryInfo.blockIconURI) {
menuIconURI = categoryInfo.blockIconURI;
}
const menuIconXML = menuIconURI ?
`iconURI="${menuIconURI}"` : '';
xmlParts.push(`<category name="${name}" ${colorXML} ${menuIconXML}>`);
xmlParts.push.apply(xmlParts, paletteBlocks.map(block => block.xml));
xmlParts.push('</category>');
}
return xmlParts.join('\n');
}
/**
* @returns {Array.<string>} - an array containing the scratch-blocks JSON information for each dynamic block.
*/
getBlocksJSON () {
return this._blockInfo.reduce(
(result, categoryInfo) => result.concat(categoryInfo.blocks.map(blockInfo => blockInfo.json)), []);
}
/**
* Retrieve the function associated with the given opcode.
* @param {!string} opcode The opcode to look up.
* @return {Function} The function which implements the opcode.
*/
getOpcodeFunction (opcode) {
return this._primitives[opcode];
}
/**
* Return whether an opcode represents a hat block.
* @param {!string} opcode The opcode to look up.
* @return {boolean} True if the op is known to be a hat.
*/
getIsHat (opcode) {
return this._hats.hasOwnProperty(opcode);
}
/**
* Return whether an opcode represents an edge-activated hat block.
* @param {!string} opcode The opcode to look up.
* @return {boolean} True if the op is known to be a edge-activated hat.
*/
getIsEdgeActivatedHat (opcode) {
return this._hats.hasOwnProperty(opcode) &&
this._hats[opcode].edgeActivated;
}
/**
* Update an edge-activated hat block value.
* @param {!string} blockId ID of hat to store value for.
* @param {*} newValue Value to store for edge-activated hat.
* @return {*} The old value for the edge-activated hat.
*/
updateEdgeActivatedValue (blockId, newValue) {
const oldValue = this._edgeActivatedHatValues[blockId];
this._edgeActivatedHatValues[blockId] = newValue;
return oldValue;
}
/**
* Clear all edge-activaed hat values.
*/
clearEdgeActivatedValues () {
this._edgeActivatedHatValues = {};
}
/**
* Attach the audio engine
* @param {!AudioEngine} audioEngine The audio engine to attach
*/
attachAudioEngine (audioEngine) {
this.audioEngine = audioEngine;
}
/**
* Attach the renderer
* @param {!RenderWebGL} renderer The renderer to attach
*/
attachRenderer (renderer) {
this.renderer = renderer;
}
/**
* Attach the storage module
* @param {!ScratchStorage} storage The storage module to attach
*/
attachStorage (storage) {
this.storage = storage;
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
/**
* Create a thread and push it to the list of threads.
* @param {!string} id ID of block that starts the stack.
* @param {!Target} target Target to run thread on.
* @param {?object} opts optional arguments
* @param {?boolean} opts.stackClick true if the script was activated by clicking on the stack
* @param {?boolean} opts.updateMonitor true if the script should update a monitor value
* @return {!Thread} The newly created thread.
*/
_pushThread (id, target, opts) {
opts = Object.assign({
stackClick: false,
updateMonitor: false
}, opts);
const thread = new Thread(id);
thread.target = target;
thread.stackClick = opts.stackClick;
thread.updateMonitor = opts.updateMonitor;
thread.pushStack(id);
this.threads.push(thread);
return thread;
}
/**
* Stop a thread: stop running it immediately, and remove it from the thread list later.
* @param {!Thread} thread Thread object to remove from actives
*/
_stopThread (thread) {
// Mark the thread for later removal
thread.isKilled = true;
// Inform sequencer to stop executing that thread.
this.sequencer.retireThread(thread);
}
/**
* Restart a thread in place, maintaining its position in the list of threads.
* This is used by `startHats` to and is necessary to ensure 2.0-like execution order.
* Test project: https://scratch.mit.edu/projects/130183108/
* @param {!Thread} thread Thread object to restart.
* @return {Thread} The restarted thread.
*/
_restartThread (thread) {
const newThread = new Thread(thread.topBlock);
newThread.target = thread.target;
newThread.stackClick = thread.stackClick;
newThread.updateMonitor = thread.updateMonitor;
newThread.pushStack(thread.topBlock);
const i = this.threads.indexOf(thread);
if (i > -1) {
this.threads[i] = newThread;
return newThread;
}
this.threads.push(thread);
return thread;
}
/**
* Return whether a thread is currently active/running.
* @param {?Thread} thread Thread object to check.
* @return {boolean} True if the thread is active/running.
*/
isActiveThread (thread) {
return (
(
thread.stack.length > 0 &&
thread.status !== Thread.STATUS_DONE) &&
this.threads.indexOf(thread) > -1);
}
/**
* Toggle a script.
* @param {!string} topBlockId ID of block that starts the script.
* @param {?object} opts optional arguments to toggle script
* @param {?string} opts.target target ID for target to run script on. If not supplied, uses editing target.
* @param {?boolean} opts.stackClick true if the user activated the stack by clicking, false if not. This
* determines whether we show a visual report when turning on the script.
*/
toggleScript (topBlockId, opts) {
opts = Object.assign({
target: this._editingTarget,
stackClick: false
}, opts);
// Remove any existing thread.
for (let i = 0; i < this.threads.length; i++) {
// Toggling a script that's already running turns it off
if (this.threads[i].topBlock === topBlockId && this.threads[i].status !== Thread.STATUS_DONE) {
const blockContainer = opts.target.blocks;
const opcode = blockContainer.getOpcode(blockContainer.getBlock(topBlockId));
if (this.getIsEdgeActivatedHat(opcode) && this.threads[i].stackClick !== opts.stackClick) {
// Allow edge activated hat thread stack click to coexist with
// edge activated hat thread that runs every frame
continue;
}
this._stopThread(this.threads[i]);
return;
}
}
// Otherwise add it.
this._pushThread(topBlockId, opts.target, opts);
}
/**
* Enqueue a script that when finished will update the monitor for the block.
* @param {!string} topBlockId ID of block that starts the script.
* @param {?Target} optTarget target Target to run script on. If not supplied, uses editing target.
*/
addMonitorScript (topBlockId, optTarget) {
if (!optTarget) optTarget = this._editingTarget;
for (let i = 0; i < this.threads.length; i++) {
// Don't re-add the script if it's already running
if (this.threads[i].topBlock === topBlockId && this.threads[i].status !== Thread.STATUS_DONE &&
this.threads[i].updateMonitor) {
return;
}
}
// Otherwise add it.
this._pushThread(topBlockId, optTarget, {updateMonitor: true});
}
/**
* Run a function `f` for all scripts in a workspace.
* `f` will be called with two parameters:
* - the top block ID of the script.
* - the target that owns the script.
* @param {!Function} f Function to call for each script.
* @param {Target=} optTarget Optionally, a target to restrict to.
*/
allScriptsDo (f, optTarget) {
let targets = this.targets;
if (optTarget) {
targets = [optTarget];
}
for (let t = targets.length - 1; t >= 0; t--) {
const target = targets[t];
const scripts = target.blocks.getScripts();
for (let j = 0; j < scripts.length; j++) {