-
Notifications
You must be signed in to change notification settings - Fork 1
/
runtime.js
2734 lines (2460 loc) · 96.4 KB
/
runtime.js
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 ArgumentType = require('../extension-support/argument-type');
const Blocks = require('./blocks');
const BlocksRuntimeCache = require('./blocks-runtime-cache');
const BlockType = require('../extension-support/block-type');
const Profiler = require('./profiler');
const Sequencer = require('./sequencer');
const execute = require('./execute.js');
const ScratchBlocksConstants = require('./scratch-blocks-constants');
const TargetType = require('../extension-support/target-type');
const Thread = require('./thread');
const log = require('../util/log');
const maybeFormatMessage = require('../util/maybe-format-message');
const StageLayering = require('./stage-layering');
const Variable = require('./variable');
const xmlEscape = require('../util/xml-escape');
const ScratchLinkWebSocket = require('../util/scratch-link-websocket');
// Virtual I/O devices.
const Clock = require('../io/clock');
const Cloud = require('../io/cloud');
const Keyboard = require('../io/keyboard');
const Mouse = require('../io/mouse');
const MouseWheel = require('../io/mouseWheel');
const UserData = require('../io/userData');
const Video = require('../io/video');
const StringUtil = require('../util/string-util');
const uid = require('../util/uid');
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')
};
const defaultExtensionColors = ['#0FBD8C', '#0DA57A', '#0B8E69'];
/**
* 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] = {
shadow: {
type: 'math_angle',
// We specify fieldNames here so that we can pick
// create and populate a field with the defaultValue
// specified in the extension.
// When the `fieldName` property is not specified,
// the <field></field> will be left out of the XML and
// the scratch-blocks defaults for that field will be
// used instead (e.g. default of 0 for number fields)
fieldName: 'NUM'
}
};
map[ArgumentType.COLOR] = {
shadow: {
type: 'colour_picker',
fieldName: 'COLOUR'
}
};
map[ArgumentType.NUMBER] = {
shadow: {
type: 'math_number',
fieldName: 'NUM'
}
};
map[ArgumentType.STRING] = {
shadow: {
type: 'text',
fieldName: 'TEXT'
}
};
map[ArgumentType.BOOLEAN] = {
check: 'Boolean'
};
map[ArgumentType.MATRIX] = {
shadow: {
type: 'matrix',
fieldName: 'MATRIX'
}
};
map[ArgumentType.NOTE] = {
shadow: {
type: 'note',
fieldName: 'NOTE'
}
};
map[ArgumentType.IMAGE] = {
// Inline images are weird because they're not actually "arguments".
// They are more analagous to the label on a block.
fieldType: 'field_image'
};
return map;
})();
/**
* A pair of functions used to manage the cloud variable limit,
* to be used when adding (or attempting to add) or removing a cloud variable.
* @typedef {object} CloudDataManager
* @property {function} canAddCloudVariable A function to call to check that
* a cloud variable can be added.
* @property {function} addCloudVariable A function to call to track a new
* cloud variable on the runtime.
* @property {function} removeCloudVariable A function to call when
* removing an existing cloud variable.
* @property {function} hasCloudVariables A function to call to check that
* the runtime has any cloud variables.
*/
/**
* Creates and manages cloud variable limit in a project,
* and returns two functions to be used to add a new
* cloud variable (while checking that it can be added)
* and remove an existing cloud variable.
* These are to be called whenever attempting to create or delete
* a cloud variable.
* @return {CloudDataManager} The functions to be used when adding or removing a
* cloud variable.
*/
const cloudDataManager = () => {
const limit = 10;
let count = 0;
const canAddCloudVariable = () => count < limit;
const addCloudVariable = () => {
count++;
};
const removeCloudVariable = () => {
count--;
};
const hasCloudVariables = () => count > 0;
return {
canAddCloudVariable,
addCloudVariable,
removeCloudVariable,
hasCloudVariables
};
};
/**
* 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 = [];
/**
* Targets in reverse order of execution. Shares its order with drawables.
* @type {Array.<!Target>}
*/
this.executableTargets = [];
/**
* 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(this, true /* force no glow */);
/**
* Storage container for monitor blocks.
* These will execute on a target maybe
* @type {!Blocks}
*/
this.monitorBlocks = new Blocks(this, true /* force no glow */);
/**
* 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 = {};
/**
* 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;
/**
* All threads that finished running and were removed from this.threads
* by behaviour in Sequencer.stepThreads.
* @type {Array<Thread>}
*/
this._lastStepDoneThreads = null;
/**
* 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;
// Set an intial value for this.currentMSecs
this.updateCurrentMSecs();
/**
* 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(this),
cloud: new Cloud(this),
keyboard: new Keyboard(this),
mouse: new Mouse(this),
mouseWheel: new MouseWheel(this),
userData: new UserData(),
video: new Video(this)
};
/**
* A list of extensions, used to manage hardware connection.
*/
this.peripheralExtensions = {};
/**
* A runtime profiler that records timed events for later playback to
* diagnose Scratch performance.
* @type {Profiler}
*/
this.profiler = null;
const newCloudDataManager = cloudDataManager();
/**
* Check wether the runtime has any cloud data.
* @type {function}
* @return {boolean} Whether or not the runtime currently has any
* cloud variables.
*/
this.hasCloudData = newCloudDataManager.hasCloudVariables;
/**
* A function which checks whether a new cloud variable can be added
* to the runtime.
* @type {function}
* @return {boolean} Whether or not a new cloud variable can be added
* to the runtime.
*/
this.canAddCloudVariable = newCloudDataManager.canAddCloudVariable;
/**
* A function that tracks a new cloud variable in the runtime,
* updating the cloud variable limit. Calling this function will
* emit a cloud data update event if this is the first cloud variable
* being added.
* @type {function}
*/
this.addCloudVariable = this._initializeAddCloudVariable(newCloudDataManager);
/**
* A function which updates the runtime's cloud variable limit
* when removing a cloud variable and emits a cloud update event
* if the last of the cloud variables is being removed.
* @type {function}
*/
this.removeCloudVariable = this._initializeRemoveCloudVariable(newCloudDataManager);
/**
* A string representing the origin of the current project from outside of the
* Scratch community, such as CSFirst.
* @type {?string}
*/
this.origin = null;
// 记录坐标网格的 skinId 和 drawableId
this._coordinateSkinId = null;
this._coordinateDrawableId = null;
}
/**
* 保存当前舞台区域的渲染宽高
* 通过下面的 getter / setter 进行获取以及修改
* PS:
* 这里这套 stageNativeSize 的逻辑跟 scratch-svg-renderer 库的 src/bitmap-adapter.js 的 BitmapAdapter 中的是一样的
* 暂时没有想到其它方法,只能在两个地方维护同一套逻辑,只是给不同的 class 使用
* scratch-svg-renderer 的 stageNativeSize 是处理上传背景图以及更换背景尺寸时做适配
* 这里的 stageNativeSize 是为了给保存工程文件以及加载工程文件是,可以顺利根据工程文件的 stageNativeSize 进行舞台的初始化使用
*/
static stageNativeSize = [480, 360];
/**
* Width of the stage, in pixels.
* @const {number}
*/
static get STAGE_WIDTH () {
// return 480; 原本是固定数值
return Runtime.stageNativeSize[0];
}
/**
* Height of the stage, in pixels.
* @const {number}
*/
static get STAGE_HEIGHT () {
// return 360; 原本是固定数值
return Runtime.stageNativeSize[1];
}
/**
* 设置舞台区域的渲染宽度
* @const {number}
*/
static set STAGE_WIDTH (value) {
Runtime.stageNativeSize[0] = value;
}
/**
* 设置舞台区域的渲染高度
* @const {number}
*/
static set STAGE_HEIGHT (value) {
Runtime.stageNativeSize[1] = value;
}
/**
* 官网 scratch 舞台区域宽度像素大小
* @const {number}
*/
static get OFFICIAL_STAGE_WIDTH () {
return 480;
}
/**
* 官网 scratch 舞台区域高度像素大小
* @const {number}
*/
static get OFFICIAL_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 for a cloud data update
* to this project.
* @const {string}
*/
static get HAS_CLOUD_DATA_UPDATE () {
return 'HAS_CLOUD_DATA_UPDATE';
}
/**
* Event name for turning on turbo mode.
* @const {string}
*/
static get TURBO_MODE_ON () {
return 'TURBO_MODE_ON';
}
/**
* Event name for turning off turbo mode.
* @const {string}
*/
static get TURBO_MODE_OFF () {
return 'TURBO_MODE_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 target being stopped by a stop for target call.
* Used by blocks that need to stop individual targets.
* @const {string}
*/
static get STOP_FOR_TARGET () {
return 'STOP_FOR_TARGET';
}
/**
* Event name for visual value report.
* @const {string}
*/
static get VISUAL_REPORT () {
return 'VISUAL_REPORT';
}
/**
* Event name for project loaded report.
* @const {string}
*/
static get PROJECT_LOADED () {
return 'PROJECT_LOADED';
}
/**
* Event name for report that a change was made that can be saved
* @const {string}
*/
static get PROJECT_CHANGED () {
return 'PROJECT_CHANGED';
}
/**
* Event name for report that a change was made to an extension in the toolbox.
* @const {string}
*/
static get TOOLBOX_EXTENSIONS_NEED_UPDATE () {
return 'TOOLBOX_EXTENSIONS_NEED_UPDATE';
}
/**
* 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 an extension as asked for a custom field to be added
* @const {string}
*/
static get EXTENSION_FIELD_ADDED () {
return 'EXTENSION_FIELD_ADDED';
}
/**
* Event name for updating the available set of peripheral devices.
* This causes the peripheral connection modal to update a list of
* available peripherals.
* @const {string}
*/
static get PERIPHERAL_LIST_UPDATE () {
return 'PERIPHERAL_LIST_UPDATE';
}
/**
* Event name for when the user picks a bluetooth device to connect to
* via Companion Device Manager (CDM)
* @const {string}
*/
static get USER_PICKED_PERIPHERAL () {
return 'USER_PICKED_PERIPHERAL';
}
/**
* Event name for reporting that a peripheral has connected.
* This causes the status button in the blocks menu to indicate 'connected'.
* @const {string}
*/
static get PERIPHERAL_CONNECTED () {
return 'PERIPHERAL_CONNECTED';
}
/**
* Event name for reporting that a peripheral has been intentionally disconnected.
* This causes the status button in the blocks menu to indicate 'disconnected'.
* @const {string}
*/
static get PERIPHERAL_DISCONNECTED () {
return 'PERIPHERAL_DISCONNECTED';
}
/**
* Event name for reporting that a peripheral has encountered a request error.
* This causes the peripheral connection modal to switch to an error state.
* @const {string}
*/
static get PERIPHERAL_REQUEST_ERROR () {
return 'PERIPHERAL_REQUEST_ERROR';
}
/**
* Event name for reporting that a peripheral connection has been lost.
* This causes a 'peripheral connection lost' error alert to display.
* @const {string}
*/
static get PERIPHERAL_CONNECTION_LOST_ERROR () {
return 'PERIPHERAL_CONNECTION_LOST_ERROR';
}
/**
* Event name for reporting that a peripheral has not been discovered.
* This causes the peripheral connection modal to show a timeout state.
* @const {string}
*/
static get PERIPHERAL_SCAN_TIMEOUT () {
return 'PERIPHERAL_SCAN_TIMEOUT';
}
/**
* Event name to indicate that the microphone is being used to stream audio.
* @const {string}
*/
static get MIC_LISTENING () {
return 'MIC_LISTENING';
}
/**
* Event name for reporting that blocksInfo was updated.
* @const {string}
*/
static get BLOCKSINFO_UPDATE () {
return 'BLOCKSINFO_UPDATE';
}
/**
* Event name when the runtime tick loop has been started.
* @const {string}
*/
static get RUNTIME_STARTED () {
return 'RUNTIME_STARTED';
}
/**
* Event name when the runtime dispose has been called.
* @const {string}
*/
static get RUNTIME_DISPOSED () {
return 'RUNTIME_DISPOSED';
}
/**
* Event name for reporting that a block was updated and needs to be rerendered.
* @const {string}
*/
static get BLOCKS_NEED_UPDATE () {
return 'BLOCKS_NEED_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;
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Helper function for initializing the addCloudVariable function
_initializeAddCloudVariable (newCloudDataManager) {
// The addCloudVariable function
return (() => {
const hadCloudVarsBefore = this.hasCloudData();
newCloudDataManager.addCloudVariable();
if (!hadCloudVarsBefore && this.hasCloudData()) {
this.emit(Runtime.HAS_CLOUD_DATA_UPDATE, true);
}
});
}
// Helper function for initializing the removeCloudVariable function
_initializeRemoveCloudVariable (newCloudDataManager) {
return (() => {
const hadCloudVarsBefore = this.hasCloudData();
newCloudDataManager.removeCloudVariable();
if (hadCloudVarsBefore && !this.hasCloudData()) {
this.emit(Runtime.HAS_CLOUD_DATA_UPDATE, false);
}
});
}
/**
* 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());
}
}
}
}
getMonitorState () {
return this._monitorState;
}
/**
* 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_${xmlEscape(menuName)}`;
}
/**
* Create a context ("args") object for use with `formatMessage` on messages which might be target-specific.
* @param {Target} [target] - the target to use as context. If a target is not provided, default to the current
* editing target or the stage.
*/
makeMessageContextForTarget (target) {
const context = {};
target = target || this.getEditingTarget() || this.getTargetForStage();
if (target) {
context.targetType = (target.isStage ? TargetType.STAGE : TargetType.SPRITE);
}
}
/**
* Register the primitives provided by an extension.
* @param {ExtensionMetadata} extensionInfo - information about the extension (id, blocks, etc.)
* @private
*/
_registerExtensionPrimitives (extensionInfo) {
const categoryInfo = {
id: extensionInfo.id,
name: maybeFormatMessage(extensionInfo.name),
showStatusButton: extensionInfo.showStatusButton,
blockIconURI: extensionInfo.blockIconURI,
menuIconURI: extensionInfo.menuIconURI
};
if (extensionInfo.color1) {
categoryInfo.color1 = extensionInfo.color1;
categoryInfo.color2 = extensionInfo.color2;
categoryInfo.color3 = extensionInfo.color3;
} else {
categoryInfo.color1 = defaultExtensionColors[0];
categoryInfo.color2 = defaultExtensionColors[1];
categoryInfo.color3 = defaultExtensionColors[2];
}
this._blockInfo.push(categoryInfo);
this._fillExtensionCategory(categoryInfo, extensionInfo);
for (const fieldTypeName in categoryInfo.customFieldTypes) {
if (extensionInfo.customFieldTypes.hasOwnProperty(fieldTypeName)) {
const fieldTypeInfo = categoryInfo.customFieldTypes[fieldTypeName];
// Emit events for custom field types from extension
this.emit(Runtime.EXTENSION_FIELD_ADDED, {
name: `field_${fieldTypeInfo.extendedName}`,
implementation: fieldTypeInfo.fieldImplementation
});
}
}
this.emit(Runtime.EXTENSION_ADDED, categoryInfo);
}
/**
* Reregister the primitives for an extension
* @param {ExtensionMetadata} extensionInfo - new info (results of running getInfo) for an extension
* @private
*/
_refreshExtensionPrimitives (extensionInfo) {
const categoryInfo = this._blockInfo.find(info => info.id === extensionInfo.id);
if (categoryInfo) {
categoryInfo.name = maybeFormatMessage(extensionInfo.name);
this._fillExtensionCategory(categoryInfo, extensionInfo);
this.emit(Runtime.BLOCKSINFO_UPDATE, categoryInfo);
}
}
/**
* Read extension information, convert menus, blocks and custom field types
* and store the results in the provided category object.
* @param {CategoryInfo} categoryInfo - the category to be filled
* @param {ExtensionMetadata} extensionInfo - the extension metadata to read
* @private
*/
_fillExtensionCategory (categoryInfo, extensionInfo) {
categoryInfo.blocks = [];
categoryInfo.customFieldTypes = {};
categoryInfo.menus = [];
categoryInfo.menuInfo = {};
for (const menuName in extensionInfo.menus) {
if (extensionInfo.menus.hasOwnProperty(menuName)) {
const menuInfo = extensionInfo.menus[menuName];
const convertedMenu = this._buildMenuForScratchBlocks(menuName, menuInfo, categoryInfo);
categoryInfo.menus.push(convertedMenu);
categoryInfo.menuInfo[menuName] = menuInfo;
}
}
for (const fieldTypeName in extensionInfo.customFieldTypes) {
if (extensionInfo.customFieldTypes.hasOwnProperty(fieldTypeName)) {
const fieldType = extensionInfo.customFieldTypes[fieldTypeName];
const fieldTypeInfo = this._buildCustomFieldInfo(
fieldTypeName,
fieldType,
extensionInfo.id,
categoryInfo
);
categoryInfo.customFieldTypes[fieldTypeName] = fieldTypeInfo;
}
}
for (const blockInfo of extensionInfo.blocks) {
try {
const convertedBlock = this._convertForScratchBlocks(blockInfo, categoryInfo);
categoryInfo.blocks.push(convertedBlock);
if (convertedBlock.json) {
const opcode = convertedBlock.json.type;
if (blockInfo.blockType !== BlockType.EVENT) {
this._primitives[opcode] = convertedBlock.info.func;
}
if (blockInfo.blockType === BlockType.EVENT || blockInfo.blockType === BlockType.HAT) {
this._hats[opcode] = {
edgeActivated: blockInfo.isEdgeActivated,
restartExistingThreads: blockInfo.shouldRestartExistingThreads
};
}
}
} catch (e) {
log.error('Error parsing block: ', {block: blockInfo, error: e});
}
}
}
/**
* Convert the given extension menu items into the scratch-blocks style of list of pairs.
* If the menu is dynamic (e.g. the passed in argument is a function), return the input unmodified.
* @param {object} menuItems - an array of menu items or a function to retrieve such an array
* @returns {object} - an array of 2 element arrays or the original input function
* @private
*/
_convertMenuItems (menuItems) {
if (typeof menuItems !== 'function') {
const extensionMessageContext = this.makeMessageContextForTarget();
return menuItems.map(item => {
const formattedItem = maybeFormatMessage(item, extensionMessageContext);
switch (typeof formattedItem) {
case 'string':
return [formattedItem, formattedItem];
case 'object':
return [maybeFormatMessage(item.text, extensionMessageContext), item.value];
default: