diff --git a/src/engine/runtime-events.js b/src/engine/runtime-events.js index 65d4c47dca..5ed4e5417b 100644 --- a/src/engine/runtime-events.js +++ b/src/engine/runtime-events.js @@ -88,10 +88,6 @@ const RuntimeEvents = { */ AFTER_EXECUTE: 'AFTER_EXECUTE', - /** - * Event name for reporting asset download progress. Fired with finished, total - * @const {string} - */ ASSET_PROGRESS: 'ASSET_PROGRESS', /** diff --git a/src/engine/runtime.js b/src/engine/runtime.js index 619cb30811..2c3760db77 100644 --- a/src/engine/runtime.js +++ b/src/engine/runtime.js @@ -280,6 +280,8 @@ class Runtime extends EventEmitter { */ this.turboMode = false; + this.projectName = ''; + /** * tw: Responsible for managing the VM's many timers. */ @@ -1049,7 +1051,7 @@ class Runtime extends EventEmitter { handleExtensionButtonPress (buttonData) { const callback = this.extensionButtons.get(buttonData); - callback(); + if (callback) callback(); } /** @@ -1085,9 +1087,6 @@ class Runtime extends EventEmitter { return ScratchBlocksToolbox.getBlocksXML(this._blockInfo, target); } - /** - * @returns {Array.} - an array containing the scratch-blocks JSON information for each dynamic block. - */ getBlocksJSON () { return ScratchBlocksToolbox.getBlocksJSON(this._blockInfo); } @@ -1533,9 +1532,13 @@ class Runtime extends EventEmitter { // Look up metadata for the relevant hat. const hatMeta = instance._hats[requestedHatOpcode]; - for (const opts in optMatchFields) { - if (!Object.prototype.hasOwnProperty.call(optMatchFields, opts)) continue; - optMatchFields[opts] = optMatchFields[opts].toUpperCase(); + let matchFields = null; + if (optMatchFields) { + matchFields = {}; + for (const field in optMatchFields) { + if (!Object.prototype.hasOwnProperty.call(optMatchFields, field)) continue; + matchFields[field] = String(optMatchFields[field]).toUpperCase(); + } } // Consider all scripts, looking for hats with opcode `requestedHatOpcode`. @@ -1550,8 +1553,8 @@ class Runtime extends EventEmitter { // This needs to happen before the block is evaluated // (i.e., before the predicate can be run) because "broadcast and wait" // needs to have a precise collection of started threads. - for (const matchField in optMatchFields) { - if (hatFields[matchField].value !== optMatchFields[matchField]) { + for (const matchField in matchFields) { + if (hatFields[matchField].value !== matchFields[matchField]) { // Field mismatch. return; } @@ -2039,6 +2042,15 @@ class Runtime extends EventEmitter { } } + setProjectName (name) { + this.projectName = typeof name === 'string' ? name : ''; + } + + setTurboMode (turboModeOn) { + this.turboMode = !!turboModeOn; + this.emit(this.turboMode ? Runtime.TURBO_MODE_ON : Runtime.TURBO_MODE_OFF); + } + /** * Set whether we are in 30 TPS compatibility mode. * @param {boolean} compatibilityModeOn True iff in compatibility mode. @@ -2117,10 +2129,13 @@ class Runtime extends EventEmitter { const offsetX = deltaX / 2; const offsetY = deltaY / 2; for (const monitor of this._monitorState.valueSeq()) { + const x = monitor.get('x'); + const y = monitor.get('y'); + if (typeof x !== 'number' || typeof y !== 'number') continue; this.requestUpdateMonitor({ id: monitor.id, - x: monitor.get('x') + offsetX, - y: monitor.get('y') + offsetY + x: x + offsetX, + y: y + offsetY }); } this.emit(Runtime.MONITORS_UPDATE, this._monitorState.shallowClone()); @@ -2374,8 +2389,7 @@ class Runtime extends EventEmitter { this.setFramerate(parsed.framerate); } if (parsed.turbo) { - this.turboMode = true; - this.emit(Runtime.TURBO_MODE_ON); + this.setTurboMode(true); } if (parsed.interpolation) { this.setInterpolation(true); diff --git a/src/extension-support/scratch-blocks-toolbox.js b/src/extension-support/scratch-blocks-toolbox.js index b176423af6..5c744bb947 100644 --- a/src/extension-support/scratch-blocks-toolbox.js +++ b/src/extension-support/scratch-blocks-toolbox.js @@ -676,8 +676,13 @@ const getBlocksXML = function (categories, target) { }; const getBlocksJSON = function (categories) { - return categories.reduce( - (result, categoryInfo) => result.concat(categoryInfo.blocks.map(blockInfo => blockInfo.json)), []); + const result = []; + for (const categoryInfo of categories) { + for (const blockInfo of categoryInfo.blocks) { + if (blockInfo.json) result.push(blockInfo.json); + } + } + return result; }; module.exports = { diff --git a/src/virtual-machine.js b/src/virtual-machine.js index c79ec9e1fa..23345659f5 100644 --- a/src/virtual-machine.js +++ b/src/virtual-machine.js @@ -167,8 +167,8 @@ class VirtualMachine extends EventEmitter { this.runtime.on(Runtime.EXTENSIONS_REORDERED, info => { this.emit(Runtime.EXTENSIONS_REORDERED, info); }); - this.runtime.on(Runtime.EXTENSION_FIELD_ADDED, (fieldName, fieldImplementation) => { - this.emit(Runtime.EXTENSION_FIELD_ADDED, fieldName, fieldImplementation); + this.runtime.on(Runtime.EXTENSION_FIELD_ADDED, fieldInfo => { + this.emit(Runtime.EXTENSION_FIELD_ADDED, fieldInfo); }); this.runtime.on(Runtime.BLOCKSINFO_UPDATE, categoryInfo => { this.emit(Runtime.BLOCKSINFO_UPDATE, categoryInfo); @@ -189,8 +189,8 @@ class VirtualMachine extends EventEmitter { this.runtime.on(Runtime.PERIPHERAL_CONNECTED, () => this.emit(Runtime.PERIPHERAL_CONNECTED) ); - this.runtime.on(Runtime.PERIPHERAL_REQUEST_ERROR, () => - this.emit(Runtime.PERIPHERAL_REQUEST_ERROR) + this.runtime.on(Runtime.PERIPHERAL_REQUEST_ERROR, data => + this.emit(Runtime.PERIPHERAL_REQUEST_ERROR, data) ); this.runtime.on(Runtime.PERIPHERAL_DISCONNECTED, () => this.emit(Runtime.PERIPHERAL_DISCONNECTED) @@ -231,8 +231,8 @@ class VirtualMachine extends EventEmitter { this.runtime.on(Runtime.COMPILE_ERROR, (target, error) => { this.emit(Runtime.COMPILE_ERROR, target, error); }); - this.runtime.on(Runtime.ASSET_PROGRESS, (finished, total) => { - this.emit(Runtime.ASSET_PROGRESS, finished, total); + this.runtime.on(Runtime.ASSET_PROGRESS, (finished, total, detail) => { + this.emit(Runtime.ASSET_PROGRESS, finished, total, detail); }); this.runtime.on(Runtime.TURBO_MODE_OFF, () => { this.emit(Runtime.TURBO_MODE_OFF); @@ -353,12 +353,7 @@ class VirtualMachine extends EventEmitter { * @param {boolean} turboModeOn Whether turbo mode should be set. */ setTurboMode (turboModeOn) { - this.runtime.turboMode = !!turboModeOn; - if (this.runtime.turboMode) { - this.emit(Runtime.TURBO_MODE_ON); - } else { - this.emit(Runtime.TURBO_MODE_OFF); - } + this.runtime.setTurboMode(turboModeOn); } /** @@ -394,6 +389,10 @@ class VirtualMachine extends EventEmitter { this.runtime.setStageSize(width, height); } + setProjectName (name) { + this.runtime.setProjectName(name); + } + setInEditor (inEditor) { this.runtime.setInEditor(inEditor); } @@ -1695,7 +1694,7 @@ class VirtualMachine extends EventEmitter { const allTargets = this.runtime.targets; for (let i = 0; i < allTargets.length; i++) { const currTarget = allTargets[i]; - currTarget.blocks.updateAssetName(oldName, newName, 'sprite'); + currTarget.blocks.updateAssetName(oldName, newUnusedName, 'sprite'); } if (newUnusedName !== oldName) this.emitTargetsUpdate(); @@ -2070,12 +2069,11 @@ class VirtualMachine extends EventEmitter { const originalSound = this.editingTarget.getSounds()[soundIndex]; const clone = Object.assign({}, originalSound); const target = this.runtime.getTargetById(targetId); + if (!target) return Promise.resolve(); return loadSound(clone, this.runtime, target.sprite.soundBank).then(() => { if (this._editCommandActive && !this._editCommandActive()) throw new Error('Editing session ended'); - if (target) { - target.addSound(clone); - this.emitTargetsUpdate(); - } + target.addSound(clone); + this.emitTargetsUpdate(); }); } @@ -2489,6 +2487,7 @@ class VirtualMachine extends EventEmitter { */ postSpriteInfo (data) { const target = this._dragTarget || this.editingTarget; + if (!target) return; target.postSpriteInfo(data); // Post sprite info means the gui has changed something about a sprite, // either through the sprite info pane fields (e.g. direction, size) or @@ -2504,7 +2503,7 @@ class VirtualMachine extends EventEmitter { } // Emit immediate event for collaboration sync if properties changed - if (Object.keys(changedProps).length > 0 && target) { + if (Object.keys(changedProps).length > 0) { this.runtime.emit(Runtime.SPRITE_INFO_CHANGED, target, changedProps); } diff --git a/test/fixtures/toolbox/scratch-blocks-toolbox.json b/test/fixtures/toolbox/scratch-blocks-toolbox.json index 870e0dc0d6..631e43fd80 100644 --- a/test/fixtures/toolbox/scratch-blocks-toolbox.json +++ b/test/fixtures/toolbox/scratch-blocks-toolbox.json @@ -30,7 +30,6 @@ } ], "json": [ - null, { "type": "toolboxtest_command", "inputsInline": true, @@ -81,7 +80,6 @@ "previousStatement": null, "nextStatement": null }, - null, { "type": "toolboxtest_reporter", "inputsInline": true, @@ -478,10 +476,6 @@ "outputShape": 3, "previousStatement": null }, - null, - null, - null, - null, { "type": "plaincolors_say", "inputsInline": true, diff --git a/test/unit/engine_runtime.js b/test/unit/engine_runtime.js index d99ecbe593..166bced86a 100644 --- a/test/unit/engine_runtime.js +++ b/test/unit/engine_runtime.js @@ -274,3 +274,67 @@ test('Clock is reset on runtime dispose', t => { t.ok(c.projectTimer() === 0); t.end(); }); + +test('handleExtensionButtonPress ignores unknown buttons', t => { + const rt = new Runtime(); + t.doesNotThrow(() => rt.handleExtensionButtonPress('test_missing')); + let pressed = 0; + rt.extensionButtons.set('test_button', () => { + pressed++; + }); + rt.handleExtensionButtonPress('test_button'); + t.equal(pressed, 1); + t.end(); +}); + +const makeHatRuntime = fieldValue => { + const rt = new Runtime(); + rt._hats.test_whenNamed = {restartExistingThreads: false}; + const target = {id: 'target'}; + rt.allScriptsByOpcodeDo = (opcode, f) => { + f({blockId: 'hat', fieldsOfInputs: {NAME: {value: fieldValue}}}, target); + }; + rt._pushThread = () => ({isCompiled: true, executableHat: false}); + return rt; +}; + +test('startHats matches without changing the caller match fields', t => { + const rt = makeHatRuntime('HELLO'); + const fields = {NAME: 'hello'}; + t.equal(rt.startHats('test_whenNamed', fields).length, 1); + t.same(fields, {NAME: 'hello'}); + t.end(); +}); + +test('startHats accepts match values that are not strings', t => { + const rt = makeHatRuntime('12'); + t.equal(rt.startHats('test_whenNamed', {NAME: 12}).length, 1); + t.equal(rt.startHats('test_whenNamed', {NAME: 13}).length, 0); + t.end(); +}); + +test('setStageSize keeps auto-positioned monitors auto-positioned', t => { + const rt = new Runtime(); + rt.requestAddMonitor(new MonitorRecord({id: 'auto'})); + rt.requestAddMonitor(new MonitorRecord({id: 'placed', x: 10, y: 20})); + rt.setStageSize(560, 420); + t.equal(rt._monitorState.get('auto').get('x'), null); + t.equal(rt._monitorState.get('auto').get('y'), null); + t.equal(rt._monitorState.get('placed').get('x'), 50); + t.equal(rt._monitorState.get('placed').get('y'), 50); + t.end(); +}); + +test('getBlocksJSON leaves out entries without JSON', t => { + const rt = new Runtime(); + rt._blockInfo = [{ + blocks: [ + {json: {type: 'test_a'}}, + {xml: ''}, + {json: null, xml: ''}, + {json: {type: 'test_b'}} + ] + }]; + t.same(rt.getBlocksJSON(), [{type: 'test_a'}, {type: 'test_b'}]); + t.end(); +}); diff --git a/test/unit/virtual-machine.js b/test/unit/virtual-machine.js index 94dbe8c5dc..f867ecdfc4 100644 --- a/test/unit/virtual-machine.js +++ b/test/unit/virtual-machine.js @@ -1112,3 +1112,102 @@ test('clearFlyoutBlocks removes all of the flyout blocks', t => { t.end(); }); + +test('shareSoundToTarget resolves without a target', async t => { + const vm = new VirtualMachine(); + const spr = new Sprite(null, vm.runtime); + const target = spr.createClone(); + target.addSound({name: 'sound1'}); + vm.runtime.targets = [target]; + vm.editingTarget = target; + + await vm.shareSoundToTarget(0, 'missing'); + t.equal(target.getSounds().length, 1); + t.end(); +}); + +test('postSpriteInfo does nothing without an editing or drag target', t => { + const vm = new VirtualMachine(); + let changed = 0; + vm.runtime.emitProjectChanged = () => { + changed++; + }; + t.doesNotThrow(() => vm.postSpriteInfo({x: 10})); + t.equal(changed, 0); + t.end(); +}); + +test('Forwarded runtime events keep all of their arguments', t => { + const vm = new VirtualMachine(); + + const progress = []; + vm.on('ASSET_PROGRESS', (...args) => progress.push(args)); + vm.runtime.emit('ASSET_PROGRESS', 1, 2, {name: 'a'}); + t.same(progress, [[1, 2, {name: 'a'}]]); + + const fields = []; + vm.on('EXTENSION_FIELD_ADDED', (...args) => fields.push(args)); + const field = {name: 'field_test_thing', implementation: {}}; + vm.runtime.emit('EXTENSION_FIELD_ADDED', field); + t.equal(fields.length, 1); + t.equal(fields[0].length, 1); + t.equal(fields[0][0], field); + + const errors = []; + vm.on('PERIPHERAL_REQUEST_ERROR', (...args) => errors.push(args)); + vm.runtime.emit('PERIPHERAL_REQUEST_ERROR', {message: 'x', extensionId: 'ev3'}); + t.same(errors, [[{message: 'x', extensionId: 'ev3'}]]); + + t.end(); +}); + +test('Setting turbo mode emits events on the runtime once each', t => { + const vm = new VirtualMachine(); + const runtimeEvents = []; + const vmEvents = []; + vm.runtime.on('TURBO_MODE_ON', () => runtimeEvents.push('on')); + vm.runtime.on('TURBO_MODE_OFF', () => runtimeEvents.push('off')); + vm.on('TURBO_MODE_ON', () => vmEvents.push('on')); + vm.on('TURBO_MODE_OFF', () => vmEvents.push('off')); + + vm.setTurboMode(true); + t.equal(vm.runtime.turboMode, true); + vm.setTurboMode(0); + t.equal(vm.runtime.turboMode, false); + + t.same(runtimeEvents, ['on', 'off']); + t.same(vmEvents, ['on', 'off']); + t.end(); +}); + +test('setProjectName sets the name extensions read from the runtime', t => { + const vm = new VirtualMachine(); + t.equal(vm.runtime.projectName, ''); + vm.setProjectName('My game'); + t.equal(vm.runtime.projectName, 'My game'); + vm.setProjectName(null); + t.equal(vm.runtime.projectName, ''); + t.end(); +}); + +test('renameSprite updates block references to the deduplicated name', t => { + const vm = new VirtualMachine(); + vm.emitTargetsUpdate = () => {}; + + const spr1 = new Sprite(null, vm.runtime); + spr1.name = 'foo'; + const target1 = spr1.createClone(); + const spr2 = new Sprite(null, vm.runtime); + spr2.name = 'bar'; + const target2 = spr2.createClone(); + vm.runtime.targets = [target1, target2]; + + const renames = []; + target1.blocks.updateAssetName = (oldName, newName, type) => renames.push([oldName, newName, type]); + target2.blocks.updateAssetName = () => {}; + + vm.renameSprite(target2.id, 'foo'); + t.equal(target2.sprite.name, 'foo2'); + t.same(renames, [['bar', 'foo2', 'sprite']]); + t.end(); +});