2018-01-17 11:31:44 -05:00
|
|
|
const TextEncoder = require('text-encoding').TextEncoder;
|
2017-04-17 15:10:04 -04:00
|
|
|
const EventEmitter = require('events');
|
2018-03-05 17:20:36 -05:00
|
|
|
const JSZip = require('jszip');
|
2017-01-13 16:34:26 -05:00
|
|
|
|
2018-04-30 16:35:24 -04:00
|
|
|
const Buffer = require('buffer').Buffer;
|
2017-08-04 14:25:17 -04:00
|
|
|
const centralDispatch = require('./dispatch/central-dispatch');
|
2017-08-29 14:43:09 -04:00
|
|
|
const ExtensionManager = require('./extension-support/extension-manager');
|
2017-04-17 15:10:04 -04:00
|
|
|
const log = require('./util/log');
|
2018-06-13 09:20:22 -04:00
|
|
|
const MathUtil = require('./util/math-util');
|
2017-04-17 15:10:04 -04:00
|
|
|
const Runtime = require('./engine/runtime');
|
2017-04-26 11:44:53 -04:00
|
|
|
const sb2 = require('./serialization/sb2');
|
|
|
|
const sb3 = require('./serialization/sb3');
|
2017-04-17 15:10:04 -04:00
|
|
|
const StringUtil = require('./util/string-util');
|
2017-12-11 15:41:45 -05:00
|
|
|
const formatMessage = require('format-message');
|
2018-02-26 22:43:55 -05:00
|
|
|
const validate = require('scratch-parser');
|
|
|
|
|
2017-12-21 18:34:19 -05:00
|
|
|
const Variable = require('./engine/variable');
|
2017-03-20 12:52:57 -04:00
|
|
|
|
2017-09-11 09:42:16 -04:00
|
|
|
const {loadCostume} = require('./import/load-costume.js');
|
|
|
|
const {loadSound} = require('./import/load-sound.js');
|
2018-02-13 10:48:33 -05:00
|
|
|
const {serializeSounds, serializeCostumes} = require('./serialization/serialize-assets');
|
2018-04-30 16:35:24 -04:00
|
|
|
require('canvas-toBlob');
|
2017-03-27 15:04:44 -04:00
|
|
|
|
2017-04-17 15:10:04 -04:00
|
|
|
const RESERVED_NAMES = ['_mouse_', '_stage_', '_edge_', '_myself_', '_random_'];
|
2017-01-13 16:34:26 -05:00
|
|
|
|
2018-03-29 19:29:23 -04:00
|
|
|
const CORE_EXTENSIONS = [
|
|
|
|
// 'motion',
|
|
|
|
// 'looks',
|
|
|
|
// 'sound',
|
|
|
|
// 'events',
|
|
|
|
// 'control',
|
|
|
|
// 'sensing',
|
|
|
|
// 'operators',
|
|
|
|
// 'variables',
|
|
|
|
// 'myBlocks'
|
|
|
|
];
|
|
|
|
|
2017-01-13 16:34:26 -05:00
|
|
|
/**
|
|
|
|
* Handles connections between blocks, stage, and extensions.
|
|
|
|
* @constructor
|
|
|
|
*/
|
2017-04-17 19:42:48 -04:00
|
|
|
class VirtualMachine extends EventEmitter {
|
|
|
|
constructor () {
|
|
|
|
super();
|
|
|
|
|
|
|
|
/**
|
|
|
|
* VM runtime, to store blocks, I/O devices, sprites/targets, etc.
|
|
|
|
* @type {!Runtime}
|
|
|
|
*/
|
2017-05-12 11:42:22 -04:00
|
|
|
this.runtime = new Runtime();
|
2017-08-04 14:25:17 -04:00
|
|
|
centralDispatch.setService('runtime', this.runtime).catch(e => {
|
|
|
|
log.error(`Failed to register runtime service: ${JSON.stringify(e)}`);
|
|
|
|
});
|
|
|
|
|
2017-04-17 19:42:48 -04:00
|
|
|
/**
|
|
|
|
* The "currently editing"/selected target ID for the VM.
|
|
|
|
* Block events from any Blockly workspace are routed to this target.
|
2017-11-03 14:17:16 -04:00
|
|
|
* @type {Target}
|
2017-04-17 19:42:48 -04:00
|
|
|
*/
|
2017-05-12 11:42:22 -04:00
|
|
|
this.editingTarget = null;
|
2017-11-21 11:45:11 -05:00
|
|
|
|
|
|
|
/**
|
|
|
|
* The currently dragging target, for redirecting IO data.
|
|
|
|
* @type {Target}
|
|
|
|
*/
|
|
|
|
this._dragTarget = null;
|
|
|
|
|
2017-04-17 19:42:48 -04:00
|
|
|
// Runtime emits are passed along as VM emits.
|
2017-05-12 11:42:22 -04:00
|
|
|
this.runtime.on(Runtime.SCRIPT_GLOW_ON, glowData => {
|
|
|
|
this.emit(Runtime.SCRIPT_GLOW_ON, glowData);
|
2017-04-17 19:42:48 -04:00
|
|
|
});
|
2017-05-12 11:42:22 -04:00
|
|
|
this.runtime.on(Runtime.SCRIPT_GLOW_OFF, glowData => {
|
|
|
|
this.emit(Runtime.SCRIPT_GLOW_OFF, glowData);
|
2017-04-17 19:42:48 -04:00
|
|
|
});
|
2017-05-12 11:42:22 -04:00
|
|
|
this.runtime.on(Runtime.BLOCK_GLOW_ON, glowData => {
|
|
|
|
this.emit(Runtime.BLOCK_GLOW_ON, glowData);
|
2017-04-17 19:42:48 -04:00
|
|
|
});
|
2017-05-12 11:42:22 -04:00
|
|
|
this.runtime.on(Runtime.BLOCK_GLOW_OFF, glowData => {
|
|
|
|
this.emit(Runtime.BLOCK_GLOW_OFF, glowData);
|
2017-04-17 19:42:48 -04:00
|
|
|
});
|
2018-12-06 11:47:09 -05:00
|
|
|
this.runtime.on(Runtime.PROJECT_START, () => {
|
|
|
|
this.emit(Runtime.PROJECT_START);
|
|
|
|
});
|
2017-05-12 11:42:22 -04:00
|
|
|
this.runtime.on(Runtime.PROJECT_RUN_START, () => {
|
|
|
|
this.emit(Runtime.PROJECT_RUN_START);
|
2017-04-17 19:42:48 -04:00
|
|
|
});
|
2017-05-12 11:42:22 -04:00
|
|
|
this.runtime.on(Runtime.PROJECT_RUN_STOP, () => {
|
|
|
|
this.emit(Runtime.PROJECT_RUN_STOP);
|
2017-04-17 19:42:48 -04:00
|
|
|
});
|
2018-11-26 17:03:41 -05:00
|
|
|
this.runtime.on(Runtime.PROJECT_CHANGED, () => {
|
|
|
|
this.emit(Runtime.PROJECT_CHANGED);
|
|
|
|
});
|
2017-05-12 11:42:22 -04:00
|
|
|
this.runtime.on(Runtime.VISUAL_REPORT, visualReport => {
|
|
|
|
this.emit(Runtime.VISUAL_REPORT, visualReport);
|
2017-04-17 19:42:48 -04:00
|
|
|
});
|
2017-05-12 11:42:22 -04:00
|
|
|
this.runtime.on(Runtime.TARGETS_UPDATE, () => {
|
|
|
|
this.emitTargetsUpdate();
|
2017-04-17 19:42:48 -04:00
|
|
|
});
|
2017-05-15 10:45:20 -04:00
|
|
|
this.runtime.on(Runtime.MONITORS_UPDATE, monitorList => {
|
|
|
|
this.emit(Runtime.MONITORS_UPDATE, monitorList);
|
2017-05-10 15:47:06 -04:00
|
|
|
});
|
2018-02-12 10:25:42 -05:00
|
|
|
this.runtime.on(Runtime.BLOCK_DRAG_UPDATE, areBlocksOverGui => {
|
|
|
|
this.emit(Runtime.BLOCK_DRAG_UPDATE, areBlocksOverGui);
|
|
|
|
});
|
2018-11-01 14:13:07 -04:00
|
|
|
this.runtime.on(Runtime.BLOCK_DRAG_END, (blocks, topBlockId) => {
|
|
|
|
this.emit(Runtime.BLOCK_DRAG_END, blocks, topBlockId);
|
2018-02-23 11:57:19 -05:00
|
|
|
});
|
2017-09-04 14:06:31 -04:00
|
|
|
this.runtime.on(Runtime.EXTENSION_ADDED, blocksInfo => {
|
|
|
|
this.emit(Runtime.EXTENSION_ADDED, blocksInfo);
|
2017-08-29 14:43:09 -04:00
|
|
|
});
|
2017-12-11 15:41:45 -05:00
|
|
|
this.runtime.on(Runtime.BLOCKSINFO_UPDATE, blocksInfo => {
|
|
|
|
this.emit(Runtime.BLOCKSINFO_UPDATE, blocksInfo);
|
|
|
|
});
|
2018-11-20 16:32:08 -05:00
|
|
|
this.runtime.on(Runtime.BLOCKS_NEED_UPDATE, () => {
|
|
|
|
this.emitWorkspaceUpdate();
|
|
|
|
});
|
2018-06-19 17:59:03 -04:00
|
|
|
this.runtime.on(Runtime.PERIPHERAL_LIST_UPDATE, info => {
|
|
|
|
this.emit(Runtime.PERIPHERAL_LIST_UPDATE, info);
|
|
|
|
});
|
|
|
|
this.runtime.on(Runtime.PERIPHERAL_CONNECTED, () =>
|
|
|
|
this.emit(Runtime.PERIPHERAL_CONNECTED)
|
|
|
|
);
|
2018-10-17 15:48:07 -04:00
|
|
|
this.runtime.on(Runtime.PERIPHERAL_REQUEST_ERROR, () =>
|
|
|
|
this.emit(Runtime.PERIPHERAL_REQUEST_ERROR)
|
|
|
|
);
|
|
|
|
this.runtime.on(Runtime.PERIPHERAL_DISCONNECT_ERROR, data =>
|
|
|
|
this.emit(Runtime.PERIPHERAL_DISCONNECT_ERROR, data)
|
2018-06-21 15:18:56 -04:00
|
|
|
);
|
2018-07-17 16:03:06 -04:00
|
|
|
this.runtime.on(Runtime.PERIPHERAL_SCAN_TIMEOUT, () =>
|
|
|
|
this.emit(Runtime.PERIPHERAL_SCAN_TIMEOUT)
|
|
|
|
);
|
2018-09-20 17:13:51 -04:00
|
|
|
this.runtime.on(Runtime.MIC_LISTENING, listening => {
|
|
|
|
this.emit(Runtime.MIC_LISTENING, listening);
|
|
|
|
});
|
2018-11-27 11:37:01 -05:00
|
|
|
this.runtime.on(Runtime.RUNTIME_STARTED, () => {
|
|
|
|
this.emit(Runtime.RUNTIME_STARTED);
|
|
|
|
});
|
2018-11-26 11:16:05 -05:00
|
|
|
this.runtime.on(Runtime.HAS_CLOUD_DATA_UPDATE, hasCloudData => {
|
|
|
|
this.emit(Runtime.HAS_CLOUD_DATA_UPDATE, hasCloudData);
|
|
|
|
});
|
2018-06-19 17:59:03 -04:00
|
|
|
|
2017-10-04 15:16:27 -04:00
|
|
|
this.extensionManager = new ExtensionManager(this.runtime);
|
2017-04-17 19:42:48 -04:00
|
|
|
|
|
|
|
this.blockListener = this.blockListener.bind(this);
|
|
|
|
this.flyoutBlockListener = this.flyoutBlockListener.bind(this);
|
2017-05-08 09:53:16 -04:00
|
|
|
this.monitorBlockListener = this.monitorBlockListener.bind(this);
|
2017-06-15 17:29:15 -04:00
|
|
|
this.variableListener = this.variableListener.bind(this);
|
2017-04-17 19:42:48 -04:00
|
|
|
}
|
|
|
|
|
2017-01-13 16:34:26 -05:00
|
|
|
/**
|
2017-04-17 19:42:48 -04:00
|
|
|
* Start running the VM - do this before anything else.
|
2017-01-13 16:34:26 -05:00
|
|
|
*/
|
2017-04-17 19:42:48 -04:00
|
|
|
start () {
|
|
|
|
this.runtime.start();
|
|
|
|
}
|
|
|
|
|
2017-01-13 16:34:26 -05:00
|
|
|
/**
|
2017-04-17 19:42:48 -04:00
|
|
|
* "Green flag" handler - start all threads starting with a green flag.
|
2017-01-13 16:34:26 -05:00
|
|
|
*/
|
2017-04-17 19:42:48 -04:00
|
|
|
greenFlag () {
|
|
|
|
this.runtime.greenFlag();
|
|
|
|
}
|
2017-01-13 16:34:26 -05:00
|
|
|
|
2017-04-17 19:42:48 -04:00
|
|
|
/**
|
|
|
|
* Set whether the VM is in "turbo mode."
|
|
|
|
* When true, loops don't yield to redraw.
|
|
|
|
* @param {boolean} turboModeOn Whether turbo mode should be set.
|
|
|
|
*/
|
|
|
|
setTurboMode (turboModeOn) {
|
|
|
|
this.runtime.turboMode = !!turboModeOn;
|
2018-08-02 10:00:21 -04:00
|
|
|
if (this.runtime.turboMode) {
|
|
|
|
this.emit(Runtime.TURBO_MODE_ON);
|
|
|
|
} else {
|
|
|
|
this.emit(Runtime.TURBO_MODE_OFF);
|
|
|
|
}
|
2017-04-17 19:42:48 -04:00
|
|
|
}
|
2017-01-13 16:34:26 -05:00
|
|
|
|
2017-04-17 19:42:48 -04:00
|
|
|
/**
|
|
|
|
* Set whether the VM is in 2.0 "compatibility mode."
|
|
|
|
* When true, ticks go at 2.0 speed (30 TPS).
|
|
|
|
* @param {boolean} compatibilityModeOn Whether compatibility mode is set.
|
|
|
|
*/
|
|
|
|
setCompatibilityMode (compatibilityModeOn) {
|
|
|
|
this.runtime.setCompatibilityMode(!!compatibilityModeOn);
|
|
|
|
}
|
2017-01-13 16:34:26 -05:00
|
|
|
|
2017-04-17 19:42:48 -04:00
|
|
|
/**
|
|
|
|
* Stop all threads and running activities.
|
|
|
|
*/
|
|
|
|
stopAll () {
|
|
|
|
this.runtime.stopAll();
|
|
|
|
}
|
2017-01-13 16:34:26 -05:00
|
|
|
|
2017-04-17 19:42:48 -04:00
|
|
|
/**
|
|
|
|
* Clear out current running project data.
|
|
|
|
*/
|
|
|
|
clear () {
|
|
|
|
this.runtime.dispose();
|
|
|
|
this.editingTarget = null;
|
|
|
|
this.emitTargetsUpdate();
|
|
|
|
}
|
2017-01-13 16:34:26 -05:00
|
|
|
|
2017-04-17 19:42:48 -04:00
|
|
|
/**
|
|
|
|
* Get data for playground. Data comes back in an emitted event.
|
|
|
|
*/
|
|
|
|
getPlaygroundData () {
|
|
|
|
const instance = this;
|
|
|
|
// Only send back thread data for the current editingTarget.
|
|
|
|
const threadData = this.runtime.threads.filter(thread => thread.target === instance.editingTarget);
|
|
|
|
// Remove the target key, since it's a circular reference.
|
|
|
|
const filteredThreadData = JSON.stringify(threadData, (key, value) => {
|
|
|
|
if (key === 'target') return;
|
|
|
|
return value;
|
|
|
|
}, 2);
|
|
|
|
this.emit('playgroundData', {
|
|
|
|
blocks: this.editingTarget.blocks,
|
|
|
|
threads: filteredThreadData
|
|
|
|
});
|
|
|
|
}
|
2017-01-13 16:34:26 -05:00
|
|
|
|
2017-04-17 19:42:48 -04:00
|
|
|
/**
|
|
|
|
* Post I/O data to the virtual devices.
|
|
|
|
* @param {?string} device Name of virtual I/O device.
|
|
|
|
* @param {object} data Any data object to post to the I/O device.
|
|
|
|
*/
|
|
|
|
postIOData (device, data) {
|
|
|
|
if (this.runtime.ioDevices[device]) {
|
|
|
|
this.runtime.ioDevices[device].postData(data);
|
|
|
|
}
|
2017-01-13 16:34:26 -05:00
|
|
|
}
|
|
|
|
|
2018-04-26 13:24:31 -04:00
|
|
|
setVideoProvider (videoProvider) {
|
|
|
|
this.runtime.ioDevices.video.setProvider(videoProvider);
|
|
|
|
}
|
|
|
|
|
2018-10-29 00:59:06 -04:00
|
|
|
setCloudProvider (cloudProvider) {
|
|
|
|
this.runtime.ioDevices.cloud.setProvider(cloudProvider);
|
|
|
|
}
|
|
|
|
|
Refactor for hardware extensions (#1555)
* Beginning refactor: renaming 'device' to 'peripheral', shortening function names, reordering functions, etc.
* Continuing refactoring: renaming some functions to be more verbose in the runtime, adding JSDocs, etc.
* Changing 'device' to 'peripheral', etc.
* Changing 'session' to 'socket'.
* Fixing EV3 menus and menu arg validation, reordering functions, etc.
* Add _send, add some references to documentation, etc.
* Factored out _outputCommand and _inputCommand, renamed some enums, etc.
* Fixed _outputCommand, some other minor cleanup.
* Make _outputCommand and _inputCommand public.
* Added TODO.
* Renamed BLE UUID enums to be clearer.
* Change WeDo2 in comments to WeDo 2.0, etc.
* Changed some WeDo2Motor command names, cleaned up some JSDocs.
* Beginning a major EV3 refactor.
* WeDo2 formatting and comment changes.
* Motor refactoring in EV3: motorTurnClockwise and motorTurnCounterClockwise initial working state.
* Add reminders to possibly cast motor menu args in WeDo2.
* Continue to move motor commands in EV3 to EV3Motor class, don't create new EV3Motor on every poll cycle, etc.
* Factoring EV3 polling value commands, etc.
* Fixing EV3 motor power, position and button pressed, and some commenting, etc.
* Move EV3 motor position parsing to EV3Motor class, move directCommand and directCompoundCommand functions, some commenting, etc.
* Changed WeDo2 motor label enum name.
* Removed some EV3 motor functions that aren't needed, changed menu label enum names, moved some opcodes up to enums.
* Fixing comments and documentation.
* Some commenting.
* Adding further documentation and references to PDFs, changed reply check to be safer, etc.
* Some comment changes.
* Moving some functions around in EV3 and WeDo2 to match.
* Commenting, etc.
* Some renaming of session, etc.
* Fix stopAllMotors in EV3.
* Fixing clearing of motors in EV3.
* Some comment changes.
* Change runtime .extensions/registerExtension to .peripheralExtensions/registerPeripheralExtension.
* Renaming outputCommand/inputCommand to generateOutputCommand/generateInputCommand, etc.
* Moved motorCommandIDs to EV3Motor class, renamed directCommand to generateCommand, etc.
* Adding a reminder to rename something.
* JSDoc fix in EV3Motor class.
* Fixing microbit function name.
* Adding a todo item.
* Changing Ev3 menu formats to be backwards compatible, moving a BLE function up.
* Fixing EV3 ports again, and button pressed returning a boolean.
* Fixing menu value to be a string in EV3.
2018-09-07 17:01:23 -04:00
|
|
|
/**
|
|
|
|
* Tell the specified extension to scan for a peripheral.
|
|
|
|
* @param {string} extensionId - the id of the extension.
|
|
|
|
*/
|
|
|
|
scanForPeripheral (extensionId) {
|
|
|
|
this.runtime.scanForPeripheral(extensionId);
|
2018-06-19 17:59:03 -04:00
|
|
|
}
|
|
|
|
|
Refactor for hardware extensions (#1555)
* Beginning refactor: renaming 'device' to 'peripheral', shortening function names, reordering functions, etc.
* Continuing refactoring: renaming some functions to be more verbose in the runtime, adding JSDocs, etc.
* Changing 'device' to 'peripheral', etc.
* Changing 'session' to 'socket'.
* Fixing EV3 menus and menu arg validation, reordering functions, etc.
* Add _send, add some references to documentation, etc.
* Factored out _outputCommand and _inputCommand, renamed some enums, etc.
* Fixed _outputCommand, some other minor cleanup.
* Make _outputCommand and _inputCommand public.
* Added TODO.
* Renamed BLE UUID enums to be clearer.
* Change WeDo2 in comments to WeDo 2.0, etc.
* Changed some WeDo2Motor command names, cleaned up some JSDocs.
* Beginning a major EV3 refactor.
* WeDo2 formatting and comment changes.
* Motor refactoring in EV3: motorTurnClockwise and motorTurnCounterClockwise initial working state.
* Add reminders to possibly cast motor menu args in WeDo2.
* Continue to move motor commands in EV3 to EV3Motor class, don't create new EV3Motor on every poll cycle, etc.
* Factoring EV3 polling value commands, etc.
* Fixing EV3 motor power, position and button pressed, and some commenting, etc.
* Move EV3 motor position parsing to EV3Motor class, move directCommand and directCompoundCommand functions, some commenting, etc.
* Changed WeDo2 motor label enum name.
* Removed some EV3 motor functions that aren't needed, changed menu label enum names, moved some opcodes up to enums.
* Fixing comments and documentation.
* Some commenting.
* Adding further documentation and references to PDFs, changed reply check to be safer, etc.
* Some comment changes.
* Moving some functions around in EV3 and WeDo2 to match.
* Commenting, etc.
* Some renaming of session, etc.
* Fix stopAllMotors in EV3.
* Fixing clearing of motors in EV3.
* Some comment changes.
* Change runtime .extensions/registerExtension to .peripheralExtensions/registerPeripheralExtension.
* Renaming outputCommand/inputCommand to generateOutputCommand/generateInputCommand, etc.
* Moved motorCommandIDs to EV3Motor class, renamed directCommand to generateCommand, etc.
* Adding a reminder to rename something.
* JSDoc fix in EV3Motor class.
* Fixing microbit function name.
* Adding a todo item.
* Changing Ev3 menu formats to be backwards compatible, moving a BLE function up.
* Fixing EV3 ports again, and button pressed returning a boolean.
* Fixing menu value to be a string in EV3.
2018-09-07 17:01:23 -04:00
|
|
|
/**
|
|
|
|
* Connect to the extension's specified peripheral.
|
|
|
|
* @param {string} extensionId - the id of the extension.
|
|
|
|
* @param {number} peripheralId - the id of the peripheral.
|
|
|
|
*/
|
|
|
|
connectPeripheral (extensionId, peripheralId) {
|
|
|
|
this.runtime.connectPeripheral(extensionId, peripheralId);
|
2018-06-19 17:59:03 -04:00
|
|
|
}
|
|
|
|
|
Refactor for hardware extensions (#1555)
* Beginning refactor: renaming 'device' to 'peripheral', shortening function names, reordering functions, etc.
* Continuing refactoring: renaming some functions to be more verbose in the runtime, adding JSDocs, etc.
* Changing 'device' to 'peripheral', etc.
* Changing 'session' to 'socket'.
* Fixing EV3 menus and menu arg validation, reordering functions, etc.
* Add _send, add some references to documentation, etc.
* Factored out _outputCommand and _inputCommand, renamed some enums, etc.
* Fixed _outputCommand, some other minor cleanup.
* Make _outputCommand and _inputCommand public.
* Added TODO.
* Renamed BLE UUID enums to be clearer.
* Change WeDo2 in comments to WeDo 2.0, etc.
* Changed some WeDo2Motor command names, cleaned up some JSDocs.
* Beginning a major EV3 refactor.
* WeDo2 formatting and comment changes.
* Motor refactoring in EV3: motorTurnClockwise and motorTurnCounterClockwise initial working state.
* Add reminders to possibly cast motor menu args in WeDo2.
* Continue to move motor commands in EV3 to EV3Motor class, don't create new EV3Motor on every poll cycle, etc.
* Factoring EV3 polling value commands, etc.
* Fixing EV3 motor power, position and button pressed, and some commenting, etc.
* Move EV3 motor position parsing to EV3Motor class, move directCommand and directCompoundCommand functions, some commenting, etc.
* Changed WeDo2 motor label enum name.
* Removed some EV3 motor functions that aren't needed, changed menu label enum names, moved some opcodes up to enums.
* Fixing comments and documentation.
* Some commenting.
* Adding further documentation and references to PDFs, changed reply check to be safer, etc.
* Some comment changes.
* Moving some functions around in EV3 and WeDo2 to match.
* Commenting, etc.
* Some renaming of session, etc.
* Fix stopAllMotors in EV3.
* Fixing clearing of motors in EV3.
* Some comment changes.
* Change runtime .extensions/registerExtension to .peripheralExtensions/registerPeripheralExtension.
* Renaming outputCommand/inputCommand to generateOutputCommand/generateInputCommand, etc.
* Moved motorCommandIDs to EV3Motor class, renamed directCommand to generateCommand, etc.
* Adding a reminder to rename something.
* JSDoc fix in EV3Motor class.
* Fixing microbit function name.
* Adding a todo item.
* Changing Ev3 menu formats to be backwards compatible, moving a BLE function up.
* Fixing EV3 ports again, and button pressed returning a boolean.
* Fixing menu value to be a string in EV3.
2018-09-07 17:01:23 -04:00
|
|
|
/**
|
|
|
|
* Disconnect from the extension's connected peripheral.
|
|
|
|
* @param {string} extensionId - the id of the extension.
|
|
|
|
*/
|
|
|
|
disconnectPeripheral (extensionId) {
|
|
|
|
this.runtime.disconnectPeripheral(extensionId);
|
2018-06-27 14:21:11 -04:00
|
|
|
}
|
|
|
|
|
Refactor for hardware extensions (#1555)
* Beginning refactor: renaming 'device' to 'peripheral', shortening function names, reordering functions, etc.
* Continuing refactoring: renaming some functions to be more verbose in the runtime, adding JSDocs, etc.
* Changing 'device' to 'peripheral', etc.
* Changing 'session' to 'socket'.
* Fixing EV3 menus and menu arg validation, reordering functions, etc.
* Add _send, add some references to documentation, etc.
* Factored out _outputCommand and _inputCommand, renamed some enums, etc.
* Fixed _outputCommand, some other minor cleanup.
* Make _outputCommand and _inputCommand public.
* Added TODO.
* Renamed BLE UUID enums to be clearer.
* Change WeDo2 in comments to WeDo 2.0, etc.
* Changed some WeDo2Motor command names, cleaned up some JSDocs.
* Beginning a major EV3 refactor.
* WeDo2 formatting and comment changes.
* Motor refactoring in EV3: motorTurnClockwise and motorTurnCounterClockwise initial working state.
* Add reminders to possibly cast motor menu args in WeDo2.
* Continue to move motor commands in EV3 to EV3Motor class, don't create new EV3Motor on every poll cycle, etc.
* Factoring EV3 polling value commands, etc.
* Fixing EV3 motor power, position and button pressed, and some commenting, etc.
* Move EV3 motor position parsing to EV3Motor class, move directCommand and directCompoundCommand functions, some commenting, etc.
* Changed WeDo2 motor label enum name.
* Removed some EV3 motor functions that aren't needed, changed menu label enum names, moved some opcodes up to enums.
* Fixing comments and documentation.
* Some commenting.
* Adding further documentation and references to PDFs, changed reply check to be safer, etc.
* Some comment changes.
* Moving some functions around in EV3 and WeDo2 to match.
* Commenting, etc.
* Some renaming of session, etc.
* Fix stopAllMotors in EV3.
* Fixing clearing of motors in EV3.
* Some comment changes.
* Change runtime .extensions/registerExtension to .peripheralExtensions/registerPeripheralExtension.
* Renaming outputCommand/inputCommand to generateOutputCommand/generateInputCommand, etc.
* Moved motorCommandIDs to EV3Motor class, renamed directCommand to generateCommand, etc.
* Adding a reminder to rename something.
* JSDoc fix in EV3Motor class.
* Fixing microbit function name.
* Adding a todo item.
* Changing Ev3 menu formats to be backwards compatible, moving a BLE function up.
* Fixing EV3 ports again, and button pressed returning a boolean.
* Fixing menu value to be a string in EV3.
2018-09-07 17:01:23 -04:00
|
|
|
/**
|
|
|
|
* Returns whether the extension has a currently connected peripheral.
|
|
|
|
* @param {string} extensionId - the id of the extension.
|
|
|
|
* @return {boolean} - whether the extension has a connected peripheral.
|
|
|
|
*/
|
2018-06-27 14:21:11 -04:00
|
|
|
getPeripheralIsConnected (extensionId) {
|
|
|
|
return this.runtime.getPeripheralIsConnected(extensionId);
|
|
|
|
}
|
|
|
|
|
2017-04-17 19:42:48 -04:00
|
|
|
/**
|
2018-03-14 14:18:24 -04:00
|
|
|
* Load a Scratch project from a .sb, .sb2, .sb3 or json string.
|
2018-03-14 15:09:45 -04:00
|
|
|
* @param {string | object} input A json string, object, or ArrayBuffer representing the project to load.
|
2017-04-19 17:54:52 -04:00
|
|
|
* @return {!Promise} Promise that resolves after targets are installed.
|
2017-04-17 19:42:48 -04:00
|
|
|
*/
|
2018-03-14 14:18:24 -04:00
|
|
|
loadProject (input) {
|
2018-03-22 16:19:36 -04:00
|
|
|
if (typeof input === 'object' && !(input instanceof ArrayBuffer) &&
|
|
|
|
!ArrayBuffer.isView(input)) {
|
|
|
|
// If the input is an object and not any ArrayBuffer
|
|
|
|
// or an ArrayBuffer view (this includes all typed arrays and DataViews)
|
2018-03-22 14:04:58 -04:00
|
|
|
// turn the object into a JSON string, because we suspect
|
|
|
|
// this is a project.json as an object
|
2018-03-14 15:09:45 -04:00
|
|
|
// validate expects a string or buffer as input
|
2018-03-22 14:04:58 -04:00
|
|
|
// TODO not sure if we need to check that it also isn't a data view
|
2018-03-14 15:09:45 -04:00
|
|
|
input = JSON.stringify(input);
|
|
|
|
}
|
2017-01-13 16:34:26 -05:00
|
|
|
|
2018-03-15 22:40:40 -04:00
|
|
|
const validationPromise = new Promise((resolve, reject) => {
|
2018-05-04 09:19:41 -04:00
|
|
|
// The second argument of false below indicates to the validator that the
|
|
|
|
// input should be parsed/validated as an entire project (and not a single sprite)
|
|
|
|
validate(input, false, (error, res) => {
|
2018-05-04 14:48:29 -04:00
|
|
|
if (error) return reject(error);
|
|
|
|
resolve(res);
|
2018-03-15 22:40:40 -04:00
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
return validationPromise
|
2018-03-14 14:18:24 -04:00
|
|
|
.then(validatedInput => this.deserializeProject(validatedInput[0], validatedInput[1]))
|
2018-10-30 15:26:22 -04:00
|
|
|
.then(() => this.runtime.emitProjectLoaded())
|
2018-03-14 14:18:24 -04:00
|
|
|
.catch(error => {
|
|
|
|
// Intentionally rejecting here (want errors to be handled by caller)
|
|
|
|
if (error.hasOwnProperty('validationError')) {
|
|
|
|
return Promise.reject(JSON.stringify(error));
|
|
|
|
}
|
|
|
|
return Promise.reject(error);
|
2018-02-16 00:44:23 -05:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2017-04-17 19:42:48 -04:00
|
|
|
/**
|
|
|
|
* Load a project from the Scratch web site, by ID.
|
|
|
|
* @param {string} id - the ID of the project to download, as a string.
|
|
|
|
*/
|
|
|
|
downloadProjectId (id) {
|
2017-04-20 18:30:38 -04:00
|
|
|
const storage = this.runtime.storage;
|
|
|
|
if (!storage) {
|
2017-04-17 19:42:48 -04:00
|
|
|
log.error('No storage module present; cannot load project: ', id);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
const vm = this;
|
2017-04-20 18:30:38 -04:00
|
|
|
const promise = storage.load(storage.AssetType.Project, id);
|
2017-04-17 19:42:48 -04:00
|
|
|
promise.then(projectAsset => {
|
2018-05-01 08:56:22 -04:00
|
|
|
vm.loadProject(projectAsset.data);
|
2017-04-17 19:42:48 -04:00
|
|
|
});
|
2017-03-13 18:06:28 -04:00
|
|
|
}
|
2017-01-27 13:44:48 -05:00
|
|
|
|
2017-04-26 11:44:53 -04:00
|
|
|
/**
|
2017-04-26 16:50:53 -04:00
|
|
|
* @returns {string} Project in a Scratch 3.0 JSON representation.
|
2017-04-26 11:44:53 -04:00
|
|
|
*/
|
|
|
|
saveProjectSb3 () {
|
2018-02-13 10:48:33 -05:00
|
|
|
const soundDescs = serializeSounds(this.runtime);
|
|
|
|
const costumeDescs = serializeCostumes(this.runtime);
|
2018-03-05 17:20:36 -05:00
|
|
|
const projectJson = this.toJSON();
|
2018-02-13 10:48:33 -05:00
|
|
|
|
2018-03-14 14:18:24 -04:00
|
|
|
// TODO want to eventually move zip creation out of here, and perhaps
|
|
|
|
// into scratch-storage
|
2018-03-05 17:20:36 -05:00
|
|
|
const zip = new JSZip();
|
|
|
|
|
|
|
|
// Put everything in a zip file
|
|
|
|
zip.file('project.json', projectJson);
|
2018-06-19 08:51:16 -04:00
|
|
|
this._addFileDescsToZip(soundDescs.concat(costumeDescs), zip);
|
2018-03-05 17:20:36 -05:00
|
|
|
|
2018-03-27 13:00:58 -04:00
|
|
|
return zip.generateAsync({
|
|
|
|
type: 'blob',
|
|
|
|
compression: 'DEFLATE',
|
|
|
|
compressionOptions: {
|
2018-04-06 15:47:24 -04:00
|
|
|
level: 6 // Tradeoff between best speed (1) and best compression (9)
|
2018-03-27 13:00:58 -04:00
|
|
|
}
|
|
|
|
});
|
2017-01-13 16:34:26 -05:00
|
|
|
}
|
|
|
|
|
2018-11-05 15:38:04 -05:00
|
|
|
/*
|
|
|
|
* @type {Array<object>} Array of all costumes and sounds currently in the runtime
|
|
|
|
*/
|
|
|
|
get assets () {
|
2018-11-15 05:26:05 -05:00
|
|
|
return this.runtime.targets.reduce((acc, target) => (
|
|
|
|
acc
|
|
|
|
.concat(target.sprite.sounds.map(sound => sound.asset))
|
|
|
|
.concat(target.sprite.costumes.map(costume => costume.asset))
|
|
|
|
), []);
|
2018-11-05 15:38:04 -05:00
|
|
|
}
|
|
|
|
|
2018-06-19 08:51:16 -04:00
|
|
|
_addFileDescsToZip (fileDescs, zip) {
|
|
|
|
for (let i = 0; i < fileDescs.length; i++) {
|
|
|
|
const currFileDesc = fileDescs[i];
|
|
|
|
zip.file(currFileDesc.fileName, currFileDesc.fileContent);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-06-25 09:23:04 -04:00
|
|
|
/**
|
|
|
|
* Exports a sprite in the sprite3 format.
|
|
|
|
* @param {string} targetId ID of the target to export
|
|
|
|
* @param {string=} optZipType Optional type that the resulting
|
|
|
|
* zip should be outputted in. Options are: base64, binarystring,
|
|
|
|
* array, uint8array, arraybuffer, blob, or nodebuffer. Defaults to
|
|
|
|
* blob if argument not provided.
|
|
|
|
* See https://stuk.github.io/jszip/documentation/api_jszip/generate_async.html#type-option
|
|
|
|
* for more information about these options.
|
|
|
|
* @return {object} A generated zip of the sprite and its assets in the format
|
|
|
|
* specified by optZipType or blob by default.
|
|
|
|
*/
|
|
|
|
exportSprite (targetId, optZipType) {
|
2018-06-19 08:51:16 -04:00
|
|
|
const soundDescs = serializeSounds(this.runtime, targetId);
|
|
|
|
const costumeDescs = serializeCostumes(this.runtime, targetId);
|
2018-12-04 10:52:49 -05:00
|
|
|
const spriteJson = StringUtil.stringify(sb3.serialize(this.runtime, targetId));
|
2018-06-19 08:51:16 -04:00
|
|
|
|
|
|
|
const zip = new JSZip();
|
|
|
|
zip.file('sprite.json', spriteJson);
|
|
|
|
this._addFileDescsToZip(soundDescs.concat(costumeDescs), zip);
|
|
|
|
|
|
|
|
return zip.generateAsync({
|
2018-06-25 09:23:04 -04:00
|
|
|
type: typeof optZipType === 'string' ? optZipType : 'blob',
|
2018-06-19 08:51:16 -04:00
|
|
|
compression: 'DEFLATE',
|
|
|
|
compressionOptions: {
|
|
|
|
level: 6
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2017-04-26 11:44:53 -04:00
|
|
|
/**
|
|
|
|
* Export project as a Scratch 3.0 JSON representation.
|
|
|
|
* @return {string} Serialized state of the runtime.
|
|
|
|
*/
|
|
|
|
toJSON () {
|
2018-12-04 10:52:49 -05:00
|
|
|
return StringUtil.stringify(sb3.serialize(this.runtime));
|
2017-04-26 11:44:53 -04:00
|
|
|
}
|
2017-01-13 16:34:26 -05:00
|
|
|
|
2018-03-14 15:09:45 -04:00
|
|
|
// TODO do we still need this function? Keeping it here so as not to introduce
|
|
|
|
// a breaking change.
|
2017-04-26 11:44:53 -04:00
|
|
|
/**
|
|
|
|
* Load a project from a Scratch JSON representation.
|
|
|
|
* @param {string} json JSON string representing a project.
|
2017-04-26 16:50:53 -04:00
|
|
|
* @returns {Promise} Promise that resolves after the project has loaded
|
2017-04-26 11:44:53 -04:00
|
|
|
*/
|
|
|
|
fromJSON (json) {
|
2018-03-21 17:55:02 -04:00
|
|
|
log.warning('fromJSON is now just a wrapper around loadProject, please use that function instead.');
|
2018-03-14 15:09:45 -04:00
|
|
|
return this.loadProject(json);
|
|
|
|
}
|
2017-01-13 16:34:26 -05:00
|
|
|
|
2017-04-26 11:44:53 -04:00
|
|
|
/**
|
|
|
|
* Load a project from a Scratch JSON representation.
|
2018-03-14 14:18:24 -04:00
|
|
|
* @param {string} projectJSON JSON string representing a project.
|
|
|
|
* @param {?JSZip} zip Optional zipped project containing assets to be loaded.
|
2017-04-26 16:50:53 -04:00
|
|
|
* @returns {Promise} Promise that resolves after the project has loaded
|
2017-04-26 11:44:53 -04:00
|
|
|
*/
|
2018-03-14 14:18:24 -04:00
|
|
|
deserializeProject (projectJSON, zip) {
|
2017-04-26 11:44:53 -04:00
|
|
|
// Clear the current runtime
|
|
|
|
this.clear();
|
|
|
|
|
2018-03-14 14:18:24 -04:00
|
|
|
const runtime = this.runtime;
|
|
|
|
const deserializePromise = function () {
|
|
|
|
const projectVersion = projectJSON.projectVersion;
|
|
|
|
if (projectVersion === 2) {
|
2018-03-25 18:14:30 -04:00
|
|
|
return sb2.deserialize(projectJSON, runtime, false, zip);
|
2018-03-14 14:18:24 -04:00
|
|
|
}
|
|
|
|
if (projectVersion === 3) {
|
|
|
|
return sb3.deserialize(projectJSON, runtime, zip);
|
|
|
|
}
|
|
|
|
return Promise.reject('Unable to verify Scratch Project version.');
|
|
|
|
};
|
|
|
|
return deserializePromise()
|
2017-11-03 14:17:16 -04:00
|
|
|
.then(({targets, extensions}) =>
|
|
|
|
this.installTargets(targets, extensions, true));
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Install `deserialize` results: zero or more targets after the extensions (if any) used by those targets.
|
|
|
|
* @param {Array.<Target>} targets - the targets to be installed
|
|
|
|
* @param {ImportedExtensionsInfo} extensions - metadata about extensions used by these targets
|
|
|
|
* @param {boolean} wholeProject - set to true if installing a whole project, as opposed to a single sprite.
|
2017-11-03 15:50:37 -04:00
|
|
|
* @returns {Promise} resolved once targets have been installed
|
2017-11-03 14:17:16 -04:00
|
|
|
*/
|
|
|
|
installTargets (targets, extensions, wholeProject) {
|
|
|
|
const extensionPromises = [];
|
2018-03-29 19:29:23 -04:00
|
|
|
|
|
|
|
if (wholeProject) {
|
|
|
|
CORE_EXTENSIONS.forEach(extensionID => {
|
|
|
|
if (!this.extensionManager.isExtensionLoaded(extensionID)) {
|
|
|
|
extensionPromises.push(this.extensionManager.loadExtensionURL(extensionID));
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2017-11-03 14:17:16 -04:00
|
|
|
extensions.extensionIDs.forEach(extensionID => {
|
|
|
|
if (!this.extensionManager.isExtensionLoaded(extensionID)) {
|
|
|
|
const extensionURL = extensions.extensionURLs.get(extensionID) || extensionID;
|
|
|
|
extensionPromises.push(this.extensionManager.loadExtensionURL(extensionURL));
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
targets = targets.filter(target => !!target);
|
|
|
|
|
2017-11-03 15:50:37 -04:00
|
|
|
return Promise.all(extensionPromises).then(() => {
|
2017-11-03 14:17:16 -04:00
|
|
|
targets.forEach(target => {
|
|
|
|
this.runtime.targets.push(target);
|
|
|
|
(/** @type RenderedTarget */ target).updateAllDrawableProperties();
|
2018-01-11 11:28:21 -05:00
|
|
|
// Ensure unique sprite name
|
|
|
|
if (target.isSprite()) this.renameSprite(target.id, target.getName());
|
2017-11-03 14:17:16 -04:00
|
|
|
});
|
2017-04-26 16:50:53 -04:00
|
|
|
// Select the first target for editing, e.g., the first sprite.
|
2017-11-03 14:17:16 -04:00
|
|
|
if (wholeProject && (targets.length > 1)) {
|
|
|
|
this.editingTarget = targets[1];
|
2017-05-11 02:24:10 -04:00
|
|
|
} else {
|
2017-11-03 14:17:16 -04:00
|
|
|
this.editingTarget = targets[0];
|
2017-05-11 02:24:10 -04:00
|
|
|
}
|
2017-01-27 20:05:54 -05:00
|
|
|
|
2018-06-20 12:12:33 -04:00
|
|
|
if (!wholeProject) {
|
|
|
|
this.editingTarget.fixUpVariableReferences();
|
|
|
|
}
|
|
|
|
|
2017-04-26 16:50:53 -04:00
|
|
|
// Update the VM user's knowledge of targets and blocks on the workspace.
|
2018-11-26 17:03:41 -05:00
|
|
|
this.emitTargetsUpdate(false /* Don't emit project change */);
|
2017-04-26 16:50:53 -04:00
|
|
|
this.emitWorkspaceUpdate();
|
|
|
|
this.runtime.setEditingTarget(this.editingTarget);
|
2018-10-29 00:59:06 -04:00
|
|
|
this.runtime.ioDevices.cloud.setStage(this.runtime.getTargetForStage());
|
2017-04-26 16:50:53 -04:00
|
|
|
});
|
2017-04-26 11:44:53 -04:00
|
|
|
}
|
2017-01-27 20:05:54 -05:00
|
|
|
|
2018-05-03 09:47:47 -04:00
|
|
|
/**
|
|
|
|
* Add a sprite, this could be .sprite2 or .sprite3. Unpack and validate
|
|
|
|
* such a file first.
|
|
|
|
* @param {string | object} input A json string, object, or ArrayBuffer representing the project to load.
|
|
|
|
* @return {!Promise} Promise that resolves after targets are installed.
|
|
|
|
*/
|
|
|
|
addSprite (input) {
|
2018-05-03 16:19:29 -04:00
|
|
|
const errorPrefix = 'Sprite Upload Error:';
|
2018-05-03 09:47:47 -04:00
|
|
|
if (typeof input === 'object' && !(input instanceof ArrayBuffer) &&
|
|
|
|
!ArrayBuffer.isView(input)) {
|
|
|
|
// If the input is an object and not any ArrayBuffer
|
|
|
|
// or an ArrayBuffer view (this includes all typed arrays and DataViews)
|
|
|
|
// turn the object into a JSON string, because we suspect
|
|
|
|
// this is a project.json as an object
|
|
|
|
// validate expects a string or buffer as input
|
|
|
|
// TODO not sure if we need to check that it also isn't a data view
|
|
|
|
input = JSON.stringify(input);
|
|
|
|
}
|
|
|
|
|
|
|
|
const validationPromise = new Promise((resolve, reject) => {
|
2018-05-04 09:19:41 -04:00
|
|
|
// The second argument of true below indicates to the parser/validator
|
|
|
|
// that the given input should be treated as a single sprite and not
|
|
|
|
// an entire project
|
|
|
|
validate(input, true, (error, res) => {
|
2018-05-04 14:48:29 -04:00
|
|
|
if (error) return reject(error);
|
|
|
|
resolve(res);
|
2018-05-03 09:47:47 -04:00
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
return validationPromise
|
|
|
|
.then(validatedInput => {
|
|
|
|
const projectVersion = validatedInput[0].projectVersion;
|
|
|
|
if (projectVersion === 2) {
|
2018-05-03 16:19:29 -04:00
|
|
|
return this._addSprite2(validatedInput[0], validatedInput[1]);
|
2018-05-03 09:47:47 -04:00
|
|
|
}
|
|
|
|
if (projectVersion === 3) {
|
2018-05-03 16:19:29 -04:00
|
|
|
return this._addSprite3(validatedInput[0], validatedInput[1]);
|
2018-05-03 09:47:47 -04:00
|
|
|
}
|
2018-05-03 16:19:29 -04:00
|
|
|
return Promise.reject(`${errorPrefix} Unable to verify sprite version.`);
|
2018-05-03 09:47:47 -04:00
|
|
|
})
|
|
|
|
.catch(error => {
|
|
|
|
// Intentionally rejecting here (want errors to be handled by caller)
|
|
|
|
if (error.hasOwnProperty('validationError')) {
|
|
|
|
return Promise.reject(JSON.stringify(error));
|
|
|
|
}
|
2018-05-03 16:19:29 -04:00
|
|
|
return Promise.reject(`${errorPrefix} ${error}`);
|
2018-05-03 09:47:47 -04:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2017-04-17 19:42:48 -04:00
|
|
|
/**
|
|
|
|
* Add a single sprite from the "Sprite2" (i.e., SB2 sprite) format.
|
2018-05-03 16:19:29 -04:00
|
|
|
* @param {object} sprite Object representing 2.0 sprite to be added.
|
2018-05-03 09:47:47 -04:00
|
|
|
* @param {?ArrayBuffer} zip Optional zip of assets being referenced by json
|
2017-04-26 16:50:53 -04:00
|
|
|
* @returns {Promise} Promise that resolves after the sprite is added
|
2017-04-17 19:42:48 -04:00
|
|
|
*/
|
2018-05-03 16:19:29 -04:00
|
|
|
_addSprite2 (sprite, zip) {
|
2017-04-27 17:49:57 -04:00
|
|
|
// Validate & parse
|
|
|
|
|
2018-05-03 16:19:29 -04:00
|
|
|
return sb2.deserialize(sprite, this.runtime, true, zip)
|
2017-11-03 14:17:16 -04:00
|
|
|
.then(({targets, extensions}) =>
|
|
|
|
this.installTargets(targets, extensions, false));
|
2017-04-17 19:42:48 -04:00
|
|
|
}
|
2017-01-13 16:34:26 -05:00
|
|
|
|
2018-04-26 04:59:53 -04:00
|
|
|
/**
|
|
|
|
* Add a single sb3 sprite.
|
2018-05-03 16:19:29 -04:00
|
|
|
* @param {object} sprite Object rperesenting 3.0 sprite to be added.
|
2018-05-03 09:47:47 -04:00
|
|
|
* @param {?ArrayBuffer} zip Optional zip of assets being referenced by target json
|
2018-04-26 04:59:53 -04:00
|
|
|
* @returns {Promise} Promise that resolves after the sprite is added
|
|
|
|
*/
|
2018-05-03 16:19:29 -04:00
|
|
|
_addSprite3 (sprite, zip) {
|
2018-04-26 04:59:53 -04:00
|
|
|
// Validate & parse
|
|
|
|
|
|
|
|
return sb3
|
2018-05-03 16:19:29 -04:00
|
|
|
.deserialize(sprite, this.runtime, zip, true)
|
2018-05-01 07:23:21 -04:00
|
|
|
.then(({targets, extensions}) => this.installTargets(targets, extensions, false));
|
2018-04-26 04:59:53 -04:00
|
|
|
}
|
|
|
|
|
2017-04-17 19:42:48 -04:00
|
|
|
/**
|
|
|
|
* Add a costume to the current editing target.
|
|
|
|
* @param {string} md5ext - the MD5 and extension of the costume to be loaded.
|
|
|
|
* @param {!object} costumeObject Object representing the costume.
|
|
|
|
* @property {int} skinId - the ID of the costume's render skin, once installed.
|
|
|
|
* @property {number} rotationCenterX - the X component of the costume's origin.
|
|
|
|
* @property {number} rotationCenterY - the Y component of the costume's origin.
|
|
|
|
* @property {number} [bitmapResolution] - the resolution scale for a bitmap costume.
|
2018-07-31 09:47:48 -04:00
|
|
|
* @param {string} optTargetId - the id of the target to add to, if not the editing target.
|
2018-12-14 14:20:42 -05:00
|
|
|
* @param {string} optVersion - if this is 2, load costume as sb2, otherwise load costume as sb3.
|
2017-12-14 16:46:31 -05:00
|
|
|
* @returns {?Promise} - a promise that resolves when the costume has been added
|
2017-04-17 19:42:48 -04:00
|
|
|
*/
|
2018-12-14 14:20:42 -05:00
|
|
|
addCostume (md5ext, costumeObject, optTargetId, optVersion) {
|
2018-07-31 09:47:48 -04:00
|
|
|
const target = optTargetId ? this.runtime.getTargetById(optTargetId) :
|
|
|
|
this.editingTarget;
|
|
|
|
if (target) {
|
2018-12-14 14:20:42 -05:00
|
|
|
return loadCostume(md5ext, costumeObject, this.runtime, optVersion).then(() => {
|
2018-07-31 09:47:48 -04:00
|
|
|
target.addCostume(costumeObject);
|
|
|
|
target.setCostume(
|
|
|
|
target.getCostumes().length - 1
|
|
|
|
);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
// If the target cannot be found by id, return a rejected promise
|
2018-12-14 14:20:42 -05:00
|
|
|
return Promise.reject();
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Add a costume loaded from the library to the current editing target.
|
|
|
|
* @param {string} md5ext - the MD5 and extension of the costume to be loaded.
|
|
|
|
* @param {!object} costumeObject Object representing the costume.
|
|
|
|
* @property {int} skinId - the ID of the costume's render skin, once installed.
|
|
|
|
* @property {number} rotationCenterX - the X component of the costume's origin.
|
|
|
|
* @property {number} rotationCenterY - the Y component of the costume's origin.
|
|
|
|
* @property {number} [bitmapResolution] - the resolution scale for a bitmap costume.
|
|
|
|
* @returns {?Promise} - a promise that resolves when the costume has been added
|
|
|
|
*/
|
|
|
|
addCostumeFromLibrary (md5ext, costumeObject) {
|
|
|
|
if (!this.editingTarget) return Promise.reject();
|
|
|
|
return this.addCostume(md5ext, costumeObject, this.editingTarget.id, 2 /* optVersion */);
|
2017-04-17 19:42:48 -04:00
|
|
|
}
|
2017-01-13 16:34:26 -05:00
|
|
|
|
2018-02-23 10:42:29 -05:00
|
|
|
/**
|
|
|
|
* Duplicate the costume at the given index. Add it at that index + 1.
|
|
|
|
* @param {!int} costumeIndex Index of costume to duplicate
|
2018-02-23 11:09:19 -05:00
|
|
|
* @returns {?Promise} - a promise that resolves when the costume has been decoded and added
|
2018-02-23 10:42:29 -05:00
|
|
|
*/
|
|
|
|
duplicateCostume (costumeIndex) {
|
|
|
|
const originalCostume = this.editingTarget.getCostumes()[costumeIndex];
|
|
|
|
const clone = Object.assign({}, originalCostume);
|
|
|
|
const md5ext = `${clone.assetId}.${clone.dataFormat}`;
|
2018-02-23 11:09:19 -05:00
|
|
|
return loadCostume(md5ext, clone, this.runtime).then(() => {
|
2018-02-23 16:24:18 -05:00
|
|
|
this.editingTarget.addCostume(clone, costumeIndex + 1);
|
2018-02-23 10:42:29 -05:00
|
|
|
this.editingTarget.setCostume(costumeIndex + 1);
|
|
|
|
this.emitTargetsUpdate();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Duplicate the sound at the given index. Add it at that index + 1.
|
|
|
|
* @param {!int} soundIndex Index of sound to duplicate
|
2018-02-23 11:09:19 -05:00
|
|
|
* @returns {?Promise} - a promise that resolves when the sound has been decoded and added
|
2018-02-23 10:42:29 -05:00
|
|
|
*/
|
|
|
|
duplicateSound (soundIndex) {
|
|
|
|
const originalSound = this.editingTarget.getSounds()[soundIndex];
|
|
|
|
const clone = Object.assign({}, originalSound);
|
2018-06-22 09:45:23 -04:00
|
|
|
return loadSound(clone, this.runtime, this.editingTarget.sprite).then(() => {
|
2018-02-23 16:24:18 -05:00
|
|
|
this.editingTarget.addSound(clone, soundIndex + 1);
|
2018-02-23 10:42:29 -05:00
|
|
|
this.emitTargetsUpdate();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2017-07-07 08:19:32 -04:00
|
|
|
/**
|
|
|
|
* Rename a costume on the current editing target.
|
|
|
|
* @param {int} costumeIndex - the index of the costume to be renamed.
|
|
|
|
* @param {string} newName - the desired new name of the costume (will be modified if already in use).
|
|
|
|
*/
|
|
|
|
renameCostume (costumeIndex, newName) {
|
2017-07-25 10:32:25 -04:00
|
|
|
this.editingTarget.renameCostume(costumeIndex, newName);
|
2017-07-07 08:19:32 -04:00
|
|
|
this.emitTargetsUpdate();
|
|
|
|
}
|
|
|
|
|
2017-05-15 08:30:02 -04:00
|
|
|
/**
|
|
|
|
* Delete a costume from the current editing target.
|
|
|
|
* @param {int} costumeIndex - the index of the costume to be removed.
|
2018-08-21 15:12:42 -04:00
|
|
|
* @return {?function} A function to restore the deleted costume, or null,
|
|
|
|
* if no costume was deleted.
|
2017-05-15 08:30:02 -04:00
|
|
|
*/
|
|
|
|
deleteCostume (costumeIndex) {
|
2018-08-21 15:12:42 -04:00
|
|
|
const deletedCostume = this.editingTarget.deleteCostume(costumeIndex);
|
|
|
|
if (deletedCostume) {
|
|
|
|
const target = this.editingTarget;
|
|
|
|
return () => {
|
|
|
|
target.addCostume(deletedCostume);
|
|
|
|
this.emitTargetsUpdate();
|
|
|
|
};
|
|
|
|
}
|
|
|
|
return null;
|
2017-05-15 08:30:02 -04:00
|
|
|
}
|
|
|
|
|
2017-04-17 19:42:48 -04:00
|
|
|
/**
|
|
|
|
* Add a sound to the current editing target.
|
|
|
|
* @param {!object} soundObject Object representing the costume.
|
2018-07-31 09:47:48 -04:00
|
|
|
* @param {string} optTargetId - the id of the target to add to, if not the editing target.
|
2017-04-17 19:42:48 -04:00
|
|
|
* @returns {?Promise} - a promise that resolves when the sound has been decoded and added
|
|
|
|
*/
|
2018-07-31 09:47:48 -04:00
|
|
|
addSound (soundObject, optTargetId) {
|
|
|
|
const target = optTargetId ? this.runtime.getTargetById(optTargetId) :
|
|
|
|
this.editingTarget;
|
|
|
|
if (target) {
|
|
|
|
return loadSound(soundObject, this.runtime, target.sprite).then(() => {
|
|
|
|
target.addSound(soundObject);
|
|
|
|
this.emitTargetsUpdate();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
// If the target cannot be found by id, return a rejected promise
|
|
|
|
return new Promise.reject();
|
2017-04-17 19:42:48 -04:00
|
|
|
}
|
2017-04-03 09:33:23 -04:00
|
|
|
|
2017-07-07 08:19:32 -04:00
|
|
|
/**
|
|
|
|
* Rename a sound on the current editing target.
|
|
|
|
* @param {int} soundIndex - the index of the sound to be renamed.
|
|
|
|
* @param {string} newName - the desired new name of the sound (will be modified if already in use).
|
|
|
|
*/
|
|
|
|
renameSound (soundIndex, newName) {
|
2017-07-25 10:32:25 -04:00
|
|
|
this.editingTarget.renameSound(soundIndex, newName);
|
2017-07-07 08:19:32 -04:00
|
|
|
this.emitTargetsUpdate();
|
|
|
|
}
|
|
|
|
|
2017-07-25 12:39:30 -04:00
|
|
|
/**
|
|
|
|
* Get a sound buffer from the audio engine.
|
|
|
|
* @param {int} soundIndex - the index of the sound to be got.
|
|
|
|
* @return {AudioBuffer} the sound's audio buffer.
|
|
|
|
*/
|
|
|
|
getSoundBuffer (soundIndex) {
|
|
|
|
const id = this.editingTarget.sprite.sounds[soundIndex].soundId;
|
|
|
|
if (id && this.runtime && this.runtime.audioEngine) {
|
2018-06-21 17:23:33 -04:00
|
|
|
return this.editingTarget.sprite.soundBank.getSoundPlayer(id).buffer;
|
2017-07-25 12:39:30 -04:00
|
|
|
}
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Update a sound buffer.
|
|
|
|
* @param {int} soundIndex - the index of the sound to be updated.
|
|
|
|
* @param {AudioBuffer} newBuffer - new audio buffer for the audio engine.
|
2018-02-23 16:21:07 -05:00
|
|
|
* @param {ArrayBuffer} soundEncoding - the new (wav) encoded sound to be stored
|
2017-07-25 12:39:30 -04:00
|
|
|
*/
|
2018-02-23 16:21:07 -05:00
|
|
|
updateSoundBuffer (soundIndex, newBuffer, soundEncoding) {
|
|
|
|
const sound = this.editingTarget.sprite.sounds[soundIndex];
|
|
|
|
const id = sound ? sound.soundId : null;
|
2017-07-25 12:39:30 -04:00
|
|
|
if (id && this.runtime && this.runtime.audioEngine) {
|
2018-06-21 17:23:33 -04:00
|
|
|
this.editingTarget.sprite.soundBank.getSoundPlayer(id).buffer = newBuffer;
|
2017-07-25 12:39:30 -04:00
|
|
|
}
|
2018-02-23 16:21:07 -05:00
|
|
|
// Update sound in runtime
|
|
|
|
if (soundEncoding) {
|
|
|
|
// Now that we updated the sound, the format should also be updated
|
|
|
|
// so that the sound can eventually be decoded the right way.
|
|
|
|
// Sounds that were formerly 'adpcm', but were updated in sound editor
|
|
|
|
// will not get decoded by the audio engine correctly unless the format
|
|
|
|
// is updated as below.
|
|
|
|
sound.format = '';
|
|
|
|
const storage = this.runtime.storage;
|
2018-10-18 07:39:28 -04:00
|
|
|
sound.asset = storage.createAsset(
|
2018-02-23 16:21:07 -05:00
|
|
|
storage.AssetType.Sound,
|
|
|
|
storage.DataFormat.WAV,
|
2018-10-18 07:39:28 -04:00
|
|
|
soundEncoding,
|
|
|
|
null,
|
|
|
|
true // generate md5
|
2018-02-23 16:21:07 -05:00
|
|
|
);
|
2018-10-18 07:39:28 -04:00
|
|
|
sound.assetId = sound.asset.assetId;
|
2018-04-20 14:13:57 -04:00
|
|
|
sound.dataFormat = storage.DataFormat.WAV;
|
2018-02-23 16:21:07 -05:00
|
|
|
sound.md5 = `${sound.assetId}.${sound.dataFormat}`;
|
|
|
|
}
|
|
|
|
// If soundEncoding is null, it's because gui had a problem
|
|
|
|
// encoding the updated sound. We don't want to store anything in this
|
|
|
|
// case, and gui should have logged an error.
|
|
|
|
|
2017-07-25 12:39:30 -04:00
|
|
|
this.emitTargetsUpdate();
|
|
|
|
}
|
|
|
|
|
2017-05-15 08:30:02 -04:00
|
|
|
/**
|
|
|
|
* Delete a sound from the current editing target.
|
|
|
|
* @param {int} soundIndex - the index of the sound to be removed.
|
2018-08-17 14:01:24 -04:00
|
|
|
* @return {?Function} A function to restore the sound that was deleted,
|
|
|
|
* or null, if no sound was deleted.
|
2017-05-15 08:30:02 -04:00
|
|
|
*/
|
|
|
|
deleteSound (soundIndex) {
|
2018-08-17 14:01:24 -04:00
|
|
|
const target = this.editingTarget;
|
|
|
|
const deletedSound = this.editingTarget.deleteSound(soundIndex);
|
|
|
|
if (deletedSound) {
|
|
|
|
const restoreFun = () => {
|
|
|
|
target.addSound(deletedSound);
|
|
|
|
this.emitTargetsUpdate();
|
|
|
|
};
|
|
|
|
return restoreFun;
|
|
|
|
}
|
|
|
|
return null;
|
2017-05-15 08:30:02 -04:00
|
|
|
}
|
|
|
|
|
2017-08-30 18:42:44 -04:00
|
|
|
/**
|
2018-04-27 17:23:30 -04:00
|
|
|
* Get a string representation of the image from storage.
|
2017-08-31 13:41:47 -04:00
|
|
|
* @param {int} costumeIndex - the index of the costume to be got.
|
2018-04-27 17:23:30 -04:00
|
|
|
* @return {string} the costume's SVG string if it's SVG,
|
|
|
|
* a dataURI if it's a PNG or JPG, or null if it couldn't be found or decoded.
|
2017-08-30 18:42:44 -04:00
|
|
|
*/
|
2018-04-26 13:36:51 -04:00
|
|
|
getCostume (costumeIndex) {
|
2018-10-18 07:39:28 -04:00
|
|
|
const asset = this.editingTarget.getCostumes()[costumeIndex].asset;
|
|
|
|
if (!asset || !this.runtime || !this.runtime.storage) return null;
|
|
|
|
const format = asset.dataFormat;
|
2018-04-24 17:34:59 -04:00
|
|
|
if (format === this.runtime.storage.DataFormat.SVG) {
|
2018-10-18 07:39:28 -04:00
|
|
|
return asset.decodeText();
|
2018-04-26 18:34:35 -04:00
|
|
|
} else if (format === this.runtime.storage.DataFormat.PNG ||
|
|
|
|
format === this.runtime.storage.DataFormat.JPG) {
|
2018-10-18 07:39:28 -04:00
|
|
|
return asset.encodeDataURI();
|
2017-08-30 18:42:44 -04:00
|
|
|
}
|
2018-10-18 07:39:28 -04:00
|
|
|
log.error(`Unhandled format: ${asset.dataFormat}`);
|
2017-08-30 18:42:44 -04:00
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
2018-04-24 17:34:59 -04:00
|
|
|
/**
|
|
|
|
* Update a costume with the given bitmap
|
2018-04-30 16:35:24 -04:00
|
|
|
* @param {!int} costumeIndex - the index of the costume to be updated.
|
|
|
|
* @param {!ImageData} bitmap - new bitmap for the renderer.
|
|
|
|
* @param {!number} rotationCenterX x of point about which the costume rotates, relative to its upper left corner
|
|
|
|
* @param {!number} rotationCenterY y of point about which the costume rotates, relative to its upper left corner
|
|
|
|
* @param {!number} bitmapResolution 1 for bitmaps that have 1 pixel per unit of stage,
|
2018-04-26 18:43:49 -04:00
|
|
|
* 2 for double-resolution bitmaps
|
2018-04-24 17:34:59 -04:00
|
|
|
*/
|
2018-04-26 18:34:35 -04:00
|
|
|
updateBitmap (costumeIndex, bitmap, rotationCenterX, rotationCenterY, bitmapResolution) {
|
2018-04-24 17:34:59 -04:00
|
|
|
const costume = this.editingTarget.getCostumes()[costumeIndex];
|
2018-04-30 16:35:24 -04:00
|
|
|
if (!(costume && this.runtime && this.runtime.renderer)) return;
|
|
|
|
|
|
|
|
costume.rotationCenterX = rotationCenterX;
|
|
|
|
costume.rotationCenterY = rotationCenterY;
|
|
|
|
|
|
|
|
// @todo: updateBitmapSkin does not take ImageData
|
|
|
|
const canvas = document.createElement('canvas');
|
|
|
|
canvas.width = bitmap.width;
|
|
|
|
canvas.height = bitmap.height;
|
|
|
|
const context = canvas.getContext('2d');
|
|
|
|
context.putImageData(bitmap, 0, 0);
|
2018-05-04 13:37:07 -04:00
|
|
|
|
2018-04-30 16:35:24 -04:00
|
|
|
// Divide by resolution because the renderer's definition of the rotation center
|
|
|
|
// is the rotation center divided by the bitmap resolution
|
|
|
|
this.runtime.renderer.updateBitmapSkin(
|
|
|
|
costume.skinId,
|
|
|
|
canvas,
|
|
|
|
bitmapResolution,
|
|
|
|
[rotationCenterX / bitmapResolution, rotationCenterY / bitmapResolution]
|
2018-04-26 18:34:35 -04:00
|
|
|
);
|
2018-04-30 16:35:24 -04:00
|
|
|
|
|
|
|
// @todo there should be a better way to get from ImageData to a decodable storage format
|
|
|
|
canvas.toBlob(blob => {
|
|
|
|
const reader = new FileReader();
|
|
|
|
reader.addEventListener('loadend', () => {
|
|
|
|
const storage = this.runtime.storage;
|
|
|
|
costume.dataFormat = storage.DataFormat.PNG;
|
|
|
|
costume.bitmapResolution = bitmapResolution;
|
|
|
|
costume.size = [bitmap.width, bitmap.height];
|
2018-10-18 07:39:28 -04:00
|
|
|
costume.asset = storage.createAsset(
|
|
|
|
storage.AssetType.ImageBitmap,
|
|
|
|
costume.dataFormat,
|
|
|
|
Buffer.from(reader.result),
|
|
|
|
null, // id
|
|
|
|
true // generate md5
|
|
|
|
);
|
|
|
|
costume.assetId = costume.asset.assetId;
|
2018-04-30 16:35:24 -04:00
|
|
|
costume.md5 = `${costume.assetId}.${costume.dataFormat}`;
|
|
|
|
this.emitTargetsUpdate();
|
|
|
|
});
|
|
|
|
reader.readAsArrayBuffer(blob);
|
|
|
|
});
|
2018-04-24 17:34:59 -04:00
|
|
|
}
|
|
|
|
|
2017-08-30 18:42:44 -04:00
|
|
|
/**
|
|
|
|
* Update a costume with the given SVG
|
|
|
|
* @param {int} costumeIndex - the index of the costume to be updated.
|
|
|
|
* @param {string} svg - new SVG for the renderer.
|
2017-09-05 17:49:30 -04:00
|
|
|
* @param {number} rotationCenterX x of point about which the costume rotates, relative to its upper left corner
|
|
|
|
* @param {number} rotationCenterY y of point about which the costume rotates, relative to its upper left corner
|
2017-08-30 18:42:44 -04:00
|
|
|
*/
|
2017-09-05 16:51:03 -04:00
|
|
|
updateSvg (costumeIndex, svg, rotationCenterX, rotationCenterY) {
|
2018-02-21 19:59:35 -05:00
|
|
|
const costume = this.editingTarget.getCostumes()[costumeIndex];
|
2017-08-30 18:42:44 -04:00
|
|
|
if (costume && this.runtime && this.runtime.renderer) {
|
2017-09-05 17:53:27 -04:00
|
|
|
costume.rotationCenterX = rotationCenterX;
|
|
|
|
costume.rotationCenterY = rotationCenterY;
|
2017-09-05 16:51:03 -04:00
|
|
|
this.runtime.renderer.updateSVGSkin(costume.skinId, svg, [rotationCenterX, rotationCenterY]);
|
2018-04-10 09:51:29 -04:00
|
|
|
costume.size = this.runtime.renderer.getSkinSize(costume.skinId);
|
2017-08-30 18:42:44 -04:00
|
|
|
}
|
2017-10-13 17:35:56 -04:00
|
|
|
const storage = this.runtime.storage;
|
2018-02-14 16:52:41 -05:00
|
|
|
// If we're in here, we've edited an svg in the vector editor,
|
|
|
|
// so the dataFormat should be 'svg'
|
|
|
|
costume.dataFormat = storage.DataFormat.SVG;
|
2018-05-04 14:39:20 -04:00
|
|
|
costume.bitmapResolution = 1;
|
2018-10-18 07:39:28 -04:00
|
|
|
costume.asset = storage.createAsset(
|
|
|
|
storage.AssetType.ImageVector,
|
|
|
|
costume.dataFormat,
|
|
|
|
(new TextEncoder()).encode(svg),
|
|
|
|
null,
|
|
|
|
true // generate md5
|
|
|
|
);
|
|
|
|
costume.assetId = costume.asset.assetId;
|
|
|
|
costume.md5 = `${costume.assetId}.${costume.dataFormat}`;
|
2017-10-13 17:35:56 -04:00
|
|
|
this.emitTargetsUpdate();
|
2017-08-30 18:42:44 -04:00
|
|
|
}
|
|
|
|
|
2017-04-17 19:42:48 -04:00
|
|
|
/**
|
|
|
|
* Add a backdrop to the stage.
|
|
|
|
* @param {string} md5ext - the MD5 and extension of the backdrop to be loaded.
|
|
|
|
* @param {!object} backdropObject Object representing the backdrop.
|
|
|
|
* @property {int} skinId - the ID of the backdrop's render skin, once installed.
|
|
|
|
* @property {number} rotationCenterX - the X component of the backdrop's origin.
|
|
|
|
* @property {number} rotationCenterY - the Y component of the backdrop's origin.
|
|
|
|
* @property {number} [bitmapResolution] - the resolution scale for a bitmap backdrop.
|
2017-12-19 11:11:38 -05:00
|
|
|
* @returns {?Promise} - a promise that resolves when the backdrop has been added
|
2017-04-17 19:42:48 -04:00
|
|
|
*/
|
|
|
|
addBackdrop (md5ext, backdropObject) {
|
2017-12-19 11:11:38 -05:00
|
|
|
return loadCostume(md5ext, backdropObject, this.runtime).then(() => {
|
2017-04-17 19:42:48 -04:00
|
|
|
const stage = this.runtime.getTargetForStage();
|
2018-01-11 11:28:21 -05:00
|
|
|
stage.addCostume(backdropObject);
|
2018-02-21 19:59:35 -05:00
|
|
|
stage.setCostume(stage.getCostumes().length - 1);
|
2017-04-17 19:42:48 -04:00
|
|
|
});
|
|
|
|
}
|
2017-01-13 16:34:26 -05:00
|
|
|
|
2017-04-17 19:42:48 -04:00
|
|
|
/**
|
|
|
|
* Rename a sprite.
|
|
|
|
* @param {string} targetId ID of a target whose sprite to rename.
|
|
|
|
* @param {string} newName New name of the sprite.
|
|
|
|
*/
|
|
|
|
renameSprite (targetId, newName) {
|
|
|
|
const target = this.runtime.getTargetById(targetId);
|
|
|
|
if (target) {
|
|
|
|
if (!target.isSprite()) {
|
|
|
|
throw new Error('Cannot rename non-sprite targets.');
|
|
|
|
}
|
|
|
|
const sprite = target.sprite;
|
|
|
|
if (!sprite) {
|
|
|
|
throw new Error('No sprite associated with this target.');
|
|
|
|
}
|
|
|
|
if (newName && RESERVED_NAMES.indexOf(newName) === -1) {
|
|
|
|
const names = this.runtime.targets
|
2017-05-18 09:12:12 -04:00
|
|
|
.filter(runtimeTarget => runtimeTarget.isSprite() && runtimeTarget.id !== target.id)
|
2017-04-17 19:42:48 -04:00
|
|
|
.map(runtimeTarget => runtimeTarget.sprite.name);
|
2018-02-05 16:54:58 -05:00
|
|
|
const oldName = sprite.name;
|
|
|
|
const newUnusedName = StringUtil.unusedName(newName, names);
|
|
|
|
sprite.name = newUnusedName;
|
|
|
|
const allTargets = this.runtime.targets;
|
|
|
|
for (let i = 0; i < allTargets.length; i++) {
|
|
|
|
const currTarget = allTargets[i];
|
|
|
|
currTarget.blocks.updateAssetName(oldName, newName, 'sprite');
|
|
|
|
}
|
2017-04-17 19:42:48 -04:00
|
|
|
}
|
|
|
|
this.emitTargetsUpdate();
|
|
|
|
} else {
|
|
|
|
throw new Error('No target with the provided id.');
|
2017-03-20 11:14:25 -04:00
|
|
|
}
|
2017-01-13 16:34:26 -05:00
|
|
|
}
|
|
|
|
|
2017-04-17 19:42:48 -04:00
|
|
|
/**
|
|
|
|
* Delete a sprite and all its clones.
|
|
|
|
* @param {string} targetId ID of a target whose sprite to delete.
|
2018-08-08 18:29:54 -04:00
|
|
|
* @return {Function} Returns a function to restore the sprite that was deleted
|
2017-04-17 19:42:48 -04:00
|
|
|
*/
|
|
|
|
deleteSprite (targetId) {
|
|
|
|
const target = this.runtime.getTargetById(targetId);
|
2017-06-12 08:35:27 -04:00
|
|
|
|
2017-04-17 19:42:48 -04:00
|
|
|
if (target) {
|
2017-11-06 17:41:57 -05:00
|
|
|
const targetIndexBeforeDelete = this.runtime.targets.map(t => t.id).indexOf(target.id);
|
2017-04-17 19:42:48 -04:00
|
|
|
if (!target.isSprite()) {
|
|
|
|
throw new Error('Cannot delete non-sprite targets.');
|
|
|
|
}
|
|
|
|
const sprite = target.sprite;
|
|
|
|
if (!sprite) {
|
|
|
|
throw new Error('No sprite associated with this target.');
|
|
|
|
}
|
2018-08-08 18:29:54 -04:00
|
|
|
const spritePromise = this.exportSprite(targetId, 'uint8array');
|
2018-08-09 11:53:37 -04:00
|
|
|
const restoreSprite = () => spritePromise.then(spriteBuffer => this.addSprite(spriteBuffer));
|
2018-08-15 14:31:40 -04:00
|
|
|
// Remove monitors from the runtime state and remove the
|
|
|
|
// target-specific monitored blocks (e.g. local variables)
|
2018-12-06 18:59:58 -05:00
|
|
|
target.deleteMonitors();
|
2017-04-17 19:42:48 -04:00
|
|
|
const currentEditingTarget = this.editingTarget;
|
|
|
|
for (let i = 0; i < sprite.clones.length; i++) {
|
|
|
|
const clone = sprite.clones[i];
|
|
|
|
this.runtime.stopForTarget(sprite.clones[i]);
|
|
|
|
this.runtime.disposeTarget(sprite.clones[i]);
|
|
|
|
// Ensure editing target is switched if we are deleting it.
|
|
|
|
if (clone === currentEditingTarget) {
|
2017-06-12 08:35:27 -04:00
|
|
|
const nextTargetIndex = Math.min(this.runtime.targets.length - 1, targetIndexBeforeDelete);
|
2017-11-08 15:49:51 -05:00
|
|
|
if (this.runtime.targets.length > 0){
|
|
|
|
this.setEditingTarget(this.runtime.targets[nextTargetIndex].id);
|
|
|
|
} else {
|
|
|
|
this.editingTarget = null;
|
|
|
|
}
|
2017-04-17 19:42:48 -04:00
|
|
|
}
|
2017-01-13 16:34:26 -05:00
|
|
|
}
|
2017-04-17 19:42:48 -04:00
|
|
|
// Sprite object should be deleted by GC.
|
|
|
|
this.emitTargetsUpdate();
|
2018-08-08 18:29:54 -04:00
|
|
|
return restoreSprite;
|
2017-01-13 16:34:26 -05:00
|
|
|
}
|
2018-08-08 18:29:54 -04:00
|
|
|
|
|
|
|
throw new Error('No target with the provided id.');
|
2017-01-13 16:34:26 -05:00
|
|
|
}
|
|
|
|
|
2017-09-07 11:51:21 -04:00
|
|
|
/**
|
|
|
|
* Duplicate a sprite.
|
|
|
|
* @param {string} targetId ID of a target whose sprite to duplicate.
|
2017-11-09 09:18:44 -05:00
|
|
|
* @returns {Promise} Promise that resolves when duplicated target has
|
|
|
|
* been added to the runtime.
|
2017-09-07 11:51:21 -04:00
|
|
|
*/
|
|
|
|
duplicateSprite (targetId) {
|
|
|
|
const target = this.runtime.getTargetById(targetId);
|
2017-09-12 10:16:26 -04:00
|
|
|
if (!target) {
|
2017-09-07 11:51:21 -04:00
|
|
|
throw new Error('No target with the provided id.');
|
2017-09-12 10:16:26 -04:00
|
|
|
} else if (!target.isSprite()) {
|
|
|
|
throw new Error('Cannot duplicate non-sprite targets.');
|
|
|
|
} else if (!target.sprite) {
|
|
|
|
throw new Error('No sprite associated with this target.');
|
2017-09-07 11:51:21 -04:00
|
|
|
}
|
2017-11-08 15:49:51 -05:00
|
|
|
return target.duplicate().then(newTarget => {
|
2017-09-12 10:16:26 -04:00
|
|
|
this.runtime.targets.push(newTarget);
|
|
|
|
this.setEditingTarget(newTarget.id);
|
|
|
|
});
|
2017-09-07 11:51:21 -04:00
|
|
|
}
|
|
|
|
|
2017-04-17 19:42:48 -04:00
|
|
|
/**
|
|
|
|
* Set the audio engine for the VM/runtime
|
|
|
|
* @param {!AudioEngine} audioEngine The audio engine to attach
|
|
|
|
*/
|
|
|
|
attachAudioEngine (audioEngine) {
|
|
|
|
this.runtime.attachAudioEngine(audioEngine);
|
|
|
|
}
|
2017-01-13 16:34:26 -05:00
|
|
|
|
2017-04-17 19:42:48 -04:00
|
|
|
/**
|
|
|
|
* Set the renderer for the VM/runtime
|
|
|
|
* @param {!RenderWebGL} renderer The renderer to attach
|
|
|
|
*/
|
|
|
|
attachRenderer (renderer) {
|
|
|
|
this.runtime.attachRenderer(renderer);
|
|
|
|
}
|
2017-01-13 16:34:26 -05:00
|
|
|
|
2018-09-18 15:47:28 -04:00
|
|
|
/**
|
|
|
|
* @returns {RenderWebGL} The renderer attached to the vm
|
|
|
|
*/
|
|
|
|
get renderer () {
|
|
|
|
return this.runtime && this.runtime.renderer;
|
|
|
|
}
|
|
|
|
|
2018-05-10 11:00:51 -04:00
|
|
|
/**
|
|
|
|
* Set the svg adapter for the VM/runtime, which converts scratch 2 svgs to scratch 3 svgs
|
|
|
|
* @param {!SvgRenderer} svgAdapter The adapter to attach
|
|
|
|
*/
|
|
|
|
attachV2SVGAdapter (svgAdapter) {
|
|
|
|
this.runtime.attachV2SVGAdapter(svgAdapter);
|
|
|
|
}
|
|
|
|
|
2018-07-10 10:21:21 -04:00
|
|
|
/**
|
2018-07-10 10:39:47 -04:00
|
|
|
* Set the bitmap adapter for the VM/runtime, which converts scratch 2
|
|
|
|
* bitmaps to scratch 3 bitmaps. (Scratch 3 bitmaps are all bitmap resolution 2)
|
2018-07-10 10:21:21 -04:00
|
|
|
* @param {!function} bitmapAdapter The adapter to attach
|
|
|
|
*/
|
|
|
|
attachV2BitmapAdapter (bitmapAdapter) {
|
|
|
|
this.runtime.attachV2BitmapAdapter(bitmapAdapter);
|
|
|
|
}
|
|
|
|
|
2017-04-17 19:42:48 -04:00
|
|
|
/**
|
|
|
|
* Set the storage module for the VM/runtime
|
|
|
|
* @param {!ScratchStorage} storage The storage module to attach
|
|
|
|
*/
|
|
|
|
attachStorage (storage) {
|
|
|
|
this.runtime.attachStorage(storage);
|
2017-01-13 16:34:26 -05:00
|
|
|
}
|
|
|
|
|
2017-12-11 15:41:45 -05:00
|
|
|
/**
|
|
|
|
* set the current locale and builtin messages for the VM
|
2018-07-31 09:01:37 -04:00
|
|
|
* @param {!string} locale current locale
|
|
|
|
* @param {!object} messages builtin messages map for current locale
|
2018-07-11 08:35:22 -04:00
|
|
|
* @returns {Promise} Promise that resolves when all the blocks have been
|
|
|
|
* updated for a new locale (or empty if locale hasn't changed.)
|
2017-12-11 15:41:45 -05:00
|
|
|
*/
|
|
|
|
setLocale (locale, messages) {
|
2018-11-27 13:25:55 -05:00
|
|
|
if (locale !== formatMessage.setup().locale) {
|
|
|
|
formatMessage.setup({locale: locale, translations: {[locale]: messages}});
|
2017-12-11 15:41:45 -05:00
|
|
|
}
|
2018-07-11 08:35:22 -04:00
|
|
|
return this.extensionManager.refreshBlocks();
|
2017-12-11 15:41:45 -05:00
|
|
|
}
|
|
|
|
|
2018-07-18 09:52:55 -04:00
|
|
|
/**
|
|
|
|
* get the current locale for the VM
|
|
|
|
* @returns {string} the current locale in the VM
|
|
|
|
*/
|
|
|
|
getLocale () {
|
|
|
|
return formatMessage.setup().locale;
|
|
|
|
}
|
|
|
|
|
2017-04-17 19:42:48 -04:00
|
|
|
/**
|
|
|
|
* Handle a Blockly event for the current editing target.
|
|
|
|
* @param {!Blockly.Event} e Any Blockly event.
|
|
|
|
*/
|
|
|
|
blockListener (e) {
|
|
|
|
if (this.editingTarget) {
|
|
|
|
this.editingTarget.blocks.blocklyListen(e, this.runtime);
|
|
|
|
}
|
|
|
|
}
|
2017-01-13 16:34:26 -05:00
|
|
|
|
2017-04-17 19:42:48 -04:00
|
|
|
/**
|
|
|
|
* Handle a Blockly event for the flyout.
|
|
|
|
* @param {!Blockly.Event} e Any Blockly event.
|
|
|
|
*/
|
|
|
|
flyoutBlockListener (e) {
|
|
|
|
this.runtime.flyoutBlocks.blocklyListen(e, this.runtime);
|
2017-01-13 16:34:26 -05:00
|
|
|
}
|
2017-04-17 19:42:48 -04:00
|
|
|
|
2017-05-08 09:53:16 -04:00
|
|
|
/**
|
|
|
|
* Handle a Blockly event for the flyout to be passed to the monitor container.
|
|
|
|
* @param {!Blockly.Event} e Any Blockly event.
|
|
|
|
*/
|
|
|
|
monitorBlockListener (e) {
|
2017-05-10 11:22:03 -04:00
|
|
|
// Filter events by type, since monitor blocks only need to listen to these events.
|
|
|
|
// Monitor blocks shouldn't be destroyed when flyout blocks are deleted.
|
2017-05-08 09:53:16 -04:00
|
|
|
if (['create', 'change'].indexOf(e.type) !== -1) {
|
|
|
|
this.runtime.monitorBlocks.blocklyListen(e, this.runtime);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-06-15 17:29:15 -04:00
|
|
|
/**
|
|
|
|
* Handle a Blockly event for the variable map.
|
|
|
|
* @param {!Blockly.Event} e Any Blockly event.
|
|
|
|
*/
|
|
|
|
variableListener (e) {
|
|
|
|
// Filter events by type, since blocks only needs to listen to these
|
|
|
|
// var events.
|
|
|
|
if (['var_create', 'var_rename', 'var_delete'].indexOf(e.type) !== -1) {
|
|
|
|
this.runtime.getTargetForStage().blocks.blocklyListen(e,
|
|
|
|
this.runtime);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-04-17 19:42:48 -04:00
|
|
|
/**
|
|
|
|
* Set an editing target. An editor UI can use this function to switch
|
|
|
|
* between editing different targets, sprites, etc.
|
|
|
|
* After switching the editing target, the VM may emit updates
|
|
|
|
* to the list of targets and any attached workspace blocks
|
|
|
|
* (see `emitTargetsUpdate` and `emitWorkspaceUpdate`).
|
|
|
|
* @param {string} targetId Id of target to set as editing.
|
|
|
|
*/
|
|
|
|
setEditingTarget (targetId) {
|
|
|
|
// Has the target id changed? If not, exit.
|
2018-01-11 16:43:18 -05:00
|
|
|
if (this.editingTarget && targetId === this.editingTarget.id) {
|
2017-04-17 19:42:48 -04:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
const target = this.runtime.getTargetById(targetId);
|
|
|
|
if (target) {
|
|
|
|
this.editingTarget = target;
|
|
|
|
// Emit appropriate UI updates.
|
2018-11-26 17:03:41 -05:00
|
|
|
this.emitTargetsUpdate(false /* Don't emit project change */);
|
2017-04-17 19:42:48 -04:00
|
|
|
this.emitWorkspaceUpdate();
|
|
|
|
this.runtime.setEditingTarget(target);
|
|
|
|
}
|
2017-01-13 16:34:26 -05:00
|
|
|
}
|
|
|
|
|
2018-02-23 11:57:19 -05:00
|
|
|
/**
|
|
|
|
* Called when blocks are dragged from one sprite to another. Adds the blocks to the
|
|
|
|
* workspace of the given target.
|
2018-02-23 16:09:38 -05:00
|
|
|
* @param {!Array<object>} blocks Blocks to add.
|
|
|
|
* @param {!string} targetId Id of target to add blocks to.
|
2018-07-13 12:58:45 -04:00
|
|
|
* @param {?string} optFromTargetId Optional target id indicating that blocks are being
|
|
|
|
* shared from that target. This is needed for resolving any potential variable conflicts.
|
2018-11-05 13:00:35 -05:00
|
|
|
* @return {!Promise} Promise that resolves when the extensions and blocks have been added.
|
2018-02-23 11:57:19 -05:00
|
|
|
*/
|
2018-07-13 12:58:45 -04:00
|
|
|
shareBlocksToTarget (blocks, targetId, optFromTargetId) {
|
2018-07-11 12:27:20 -04:00
|
|
|
const copiedBlocks = JSON.parse(JSON.stringify(blocks));
|
2018-02-23 11:57:19 -05:00
|
|
|
const target = this.runtime.getTargetById(targetId);
|
2018-07-13 12:58:45 -04:00
|
|
|
|
|
|
|
if (optFromTargetId) {
|
|
|
|
// If the blocks are being shared from another target,
|
|
|
|
// resolve any possible variable conflicts that may arise.
|
|
|
|
const fromTarget = this.runtime.getTargetById(optFromTargetId);
|
|
|
|
fromTarget.resolveVariableSharingConflictsWithTarget(copiedBlocks, target);
|
2018-07-09 10:44:45 -04:00
|
|
|
}
|
|
|
|
|
2018-11-05 13:00:35 -05:00
|
|
|
// Create a unique set of extensionIds that are not yet loaded
|
|
|
|
const extensionIDs = new Set(copiedBlocks
|
|
|
|
.map(b => sb3.getExtensionIdForOpcode(b.opcode))
|
|
|
|
.filter(id => !!id) // Remove ids that do not exist
|
|
|
|
.filter(id => !this.extensionManager.isExtensionLoaded(id)) // and remove loaded extensions
|
|
|
|
);
|
|
|
|
|
|
|
|
// Create an array promises for extensions to load
|
|
|
|
const extensionPromises = Array.from(extensionIDs,
|
|
|
|
id => this.extensionManager.loadExtensionURL(id)
|
|
|
|
);
|
|
|
|
|
|
|
|
return Promise.all(extensionPromises).then(() => {
|
|
|
|
copiedBlocks.forEach(block => {
|
|
|
|
target.blocks.createBlock(block);
|
|
|
|
});
|
|
|
|
target.blocks.updateTargetSpecificBlocks(target.isStage);
|
|
|
|
});
|
2018-02-23 11:57:19 -05:00
|
|
|
}
|
|
|
|
|
2018-06-18 10:37:23 -04:00
|
|
|
/**
|
|
|
|
* Called when costumes are dragged from editing target to another target.
|
|
|
|
* Sets the newly added costume as the current costume.
|
|
|
|
* @param {!number} costumeIndex Index of the costume of the editing target to share.
|
|
|
|
* @param {!string} targetId Id of target to add the costume.
|
|
|
|
* @return {Promise} Promise that resolves when the new costume has been loaded.
|
|
|
|
*/
|
|
|
|
shareCostumeToTarget (costumeIndex, targetId) {
|
|
|
|
const originalCostume = this.editingTarget.getCostumes()[costumeIndex];
|
|
|
|
const clone = Object.assign({}, originalCostume);
|
|
|
|
const md5ext = `${clone.assetId}.${clone.dataFormat}`;
|
|
|
|
return loadCostume(md5ext, clone, this.runtime).then(() => {
|
|
|
|
const target = this.runtime.getTargetById(targetId);
|
|
|
|
if (target) {
|
|
|
|
target.addCostume(clone);
|
|
|
|
target.setCostume(
|
|
|
|
target.getCostumes().length - 1
|
|
|
|
);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Called when sounds are dragged from editing target to another target.
|
|
|
|
* @param {!number} soundIndex Index of the sound of the editing target to share.
|
|
|
|
* @param {!string} targetId Id of target to add the sound.
|
|
|
|
* @return {Promise} Promise that resolves when the new sound has been loaded.
|
|
|
|
*/
|
|
|
|
shareSoundToTarget (soundIndex, targetId) {
|
|
|
|
const originalSound = this.editingTarget.getSounds()[soundIndex];
|
|
|
|
const clone = Object.assign({}, originalSound);
|
2018-06-22 09:45:23 -04:00
|
|
|
const target = this.runtime.getTargetById(targetId);
|
|
|
|
return loadSound(clone, this.runtime, target.sprite).then(() => {
|
2018-06-18 10:37:23 -04:00
|
|
|
if (target) {
|
|
|
|
target.addSound(clone);
|
|
|
|
this.emitTargetsUpdate();
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2017-06-15 11:53:30 -04:00
|
|
|
/**
|
|
|
|
* Repopulate the workspace with the blocks of the current editingTarget. This
|
|
|
|
* allows us to get around bugs like gui#413.
|
|
|
|
*/
|
|
|
|
refreshWorkspace () {
|
|
|
|
if (this.editingTarget) {
|
|
|
|
this.emitWorkspaceUpdate();
|
|
|
|
this.runtime.setEditingTarget(this.editingTarget);
|
2018-11-26 17:03:41 -05:00
|
|
|
this.emitTargetsUpdate(false /* Don't emit project change */);
|
2017-06-15 11:53:30 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-04-17 19:42:48 -04:00
|
|
|
/**
|
|
|
|
* Emit metadata about available targets.
|
|
|
|
* An editor UI could use this to display a list of targets and show
|
|
|
|
* the currently editing one.
|
2018-11-26 17:03:41 -05:00
|
|
|
* @param {bool} triggerProjectChange If true, also emit a project changed event.
|
|
|
|
* Disabled selectively by updates that don't affect project serialization.
|
|
|
|
* Defaults to true.
|
2017-04-17 19:42:48 -04:00
|
|
|
*/
|
2018-11-26 17:03:41 -05:00
|
|
|
emitTargetsUpdate (triggerProjectChange) {
|
|
|
|
if (typeof triggerProjectChange === 'undefined') triggerProjectChange = true;
|
2017-04-17 19:42:48 -04:00
|
|
|
this.emit('targetsUpdate', {
|
|
|
|
// [[target id, human readable target name], ...].
|
2017-04-19 17:36:33 -04:00
|
|
|
targetList: this.runtime.targets
|
|
|
|
.filter(
|
|
|
|
// Don't report clones.
|
|
|
|
target => !target.hasOwnProperty('isOriginal') || target.isOriginal
|
|
|
|
).map(
|
|
|
|
target => target.toJSON()
|
|
|
|
),
|
2017-04-17 19:42:48 -04:00
|
|
|
// Currently editing target id.
|
|
|
|
editingTarget: this.editingTarget ? this.editingTarget.id : null
|
|
|
|
});
|
2018-11-26 17:03:41 -05:00
|
|
|
if (triggerProjectChange) this.runtime.emitProjectChanged();
|
2017-04-17 19:42:48 -04:00
|
|
|
}
|
2017-01-13 16:34:26 -05:00
|
|
|
|
2017-04-17 19:42:48 -04:00
|
|
|
/**
|
|
|
|
* Emit an Blockly/scratch-blocks compatible XML representation
|
|
|
|
* of the current editing target's blocks.
|
|
|
|
*/
|
|
|
|
emitWorkspaceUpdate () {
|
2017-12-21 18:34:19 -05:00
|
|
|
// Create a list of broadcast message Ids according to the stage variables
|
|
|
|
const stageVariables = this.runtime.getTargetForStage().variables;
|
|
|
|
let messageIds = [];
|
|
|
|
for (const varId in stageVariables) {
|
|
|
|
if (stageVariables[varId].type === Variable.BROADCAST_MESSAGE_TYPE) {
|
|
|
|
messageIds.push(varId);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// Go through all blocks on all targets, removing referenced
|
|
|
|
// broadcast ids from the list.
|
|
|
|
for (let i = 0; i < this.runtime.targets.length; i++) {
|
|
|
|
const currTarget = this.runtime.targets[i];
|
|
|
|
const currBlocks = currTarget.blocks._blocks;
|
|
|
|
for (const blockId in currBlocks) {
|
|
|
|
if (currBlocks[blockId].fields.BROADCAST_OPTION) {
|
|
|
|
const id = currBlocks[blockId].fields.BROADCAST_OPTION.id;
|
|
|
|
const index = messageIds.indexOf(id);
|
|
|
|
if (index !== -1) {
|
|
|
|
messageIds = messageIds.slice(0, index)
|
|
|
|
.concat(messageIds.slice(index + 1));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// Anything left in messageIds is not referenced by a block, so delete it.
|
|
|
|
for (let i = 0; i < messageIds.length; i++) {
|
|
|
|
const id = messageIds[i];
|
|
|
|
delete this.runtime.getTargetForStage().variables[id];
|
|
|
|
}
|
2018-07-06 13:02:23 -04:00
|
|
|
const globalVarMap = Object.assign({}, this.runtime.getTargetForStage().variables);
|
|
|
|
const localVarMap = this.editingTarget.isStage ?
|
|
|
|
Object.create(null) :
|
|
|
|
Object.assign({}, this.editingTarget.variables);
|
2017-07-17 12:02:48 -04:00
|
|
|
|
2018-07-06 13:02:23 -04:00
|
|
|
const globalVariables = Object.keys(globalVarMap).map(k => globalVarMap[k]);
|
|
|
|
const localVariables = Object.keys(localVarMap).map(k => localVarMap[k]);
|
2018-05-31 16:33:42 -04:00
|
|
|
const workspaceComments = Object.keys(this.editingTarget.comments)
|
2018-05-21 11:30:22 -04:00
|
|
|
.map(k => this.editingTarget.comments[k])
|
|
|
|
.filter(c => c.blockId === null);
|
2017-05-25 11:44:49 -04:00
|
|
|
|
|
|
|
const xmlString = `<xml xmlns="http://www.w3.org/1999/xhtml">
|
|
|
|
<variables>
|
2018-07-06 13:02:23 -04:00
|
|
|
${globalVariables.map(v => v.toXML()).join()}
|
|
|
|
${localVariables.map(v => v.toXML(true)).join()}
|
2017-05-25 11:44:49 -04:00
|
|
|
</variables>
|
2018-05-31 16:33:42 -04:00
|
|
|
${workspaceComments.map(c => c.toXML()).join()}
|
2018-05-21 11:30:22 -04:00
|
|
|
${this.editingTarget.blocks.toXML(this.editingTarget.comments)}
|
2017-05-25 11:44:49 -04:00
|
|
|
</xml>`;
|
|
|
|
|
|
|
|
this.emit('workspaceUpdate', {xml: xmlString});
|
2017-04-17 19:42:48 -04:00
|
|
|
}
|
2017-01-13 16:34:26 -05:00
|
|
|
|
2017-04-17 19:42:48 -04:00
|
|
|
/**
|
|
|
|
* Get a target id for a drawable id. Useful for interacting with the renderer
|
|
|
|
* @param {int} drawableId The drawable id to request the target id for
|
|
|
|
* @returns {?string} The target id, if found. Will also be null if the target found is the stage.
|
|
|
|
*/
|
|
|
|
getTargetIdForDrawableId (drawableId) {
|
|
|
|
const target = this.runtime.getTargetByDrawableId(drawableId);
|
|
|
|
if (target && target.hasOwnProperty('id') && target.hasOwnProperty('isStage') && !target.isStage) {
|
|
|
|
return target.id;
|
|
|
|
}
|
|
|
|
return null;
|
2017-03-03 09:35:57 -05:00
|
|
|
}
|
|
|
|
|
2018-06-13 09:20:22 -04:00
|
|
|
/**
|
|
|
|
* Reorder target by index. Return whether a change was made.
|
|
|
|
* @param {!string} targetIndex Index of the target.
|
|
|
|
* @param {!number} newIndex index that the target should be moved to.
|
|
|
|
* @returns {boolean} Whether a target was reordered.
|
|
|
|
*/
|
|
|
|
reorderTarget (targetIndex, newIndex) {
|
|
|
|
let targets = this.runtime.targets;
|
2018-06-13 10:09:22 -04:00
|
|
|
targetIndex = MathUtil.clamp(targetIndex, 0, targets.length - 1);
|
|
|
|
newIndex = MathUtil.clamp(newIndex, 0, targets.length - 1);
|
|
|
|
if (targetIndex === newIndex) return false;
|
|
|
|
const target = targets[targetIndex];
|
2018-06-13 09:20:22 -04:00
|
|
|
targets = targets.slice(0, targetIndex).concat(targets.slice(targetIndex + 1));
|
|
|
|
targets.splice(newIndex, 0, target);
|
|
|
|
this.runtime.targets = targets;
|
|
|
|
this.emitTargetsUpdate();
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2018-06-05 12:01:24 -04:00
|
|
|
/**
|
|
|
|
* Reorder the costumes of a target if it exists. Return whether it succeeded.
|
|
|
|
* @param {!string} targetId ID of the target which owns the costumes.
|
|
|
|
* @param {!number} costumeIndex index of the costume to move.
|
|
|
|
* @param {!number} newIndex index that the costume should be moved to.
|
2018-06-06 09:35:19 -04:00
|
|
|
* @returns {boolean} Whether a costume was reordered.
|
2018-06-05 12:01:24 -04:00
|
|
|
*/
|
|
|
|
reorderCostume (targetId, costumeIndex, newIndex) {
|
|
|
|
const target = this.runtime.getTargetById(targetId);
|
|
|
|
if (target) {
|
2018-06-06 09:35:19 -04:00
|
|
|
return target.reorderCostume(costumeIndex, newIndex);
|
2018-06-05 12:01:24 -04:00
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2018-06-06 09:35:19 -04:00
|
|
|
* Reorder the sounds of a target if it exists. Return whether it occured.
|
2018-06-05 12:01:24 -04:00
|
|
|
* @param {!string} targetId ID of the target which owns the sounds.
|
|
|
|
* @param {!number} soundIndex index of the sound to move.
|
|
|
|
* @param {!number} newIndex index that the sound should be moved to.
|
2018-06-06 09:35:19 -04:00
|
|
|
* @returns {boolean} Whether a sound was reordered.
|
2018-06-05 12:01:24 -04:00
|
|
|
*/
|
|
|
|
reorderSound (targetId, soundIndex, newIndex) {
|
|
|
|
const target = this.runtime.getTargetById(targetId);
|
|
|
|
if (target) {
|
2018-06-06 09:35:19 -04:00
|
|
|
return target.reorderSound(soundIndex, newIndex);
|
2018-06-05 12:01:24 -04:00
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2017-04-17 19:42:48 -04:00
|
|
|
/**
|
|
|
|
* Put a target into a "drag" state, during which its X/Y positions will be unaffected
|
|
|
|
* by blocks.
|
|
|
|
* @param {string} targetId The id for the target to put into a drag state
|
|
|
|
*/
|
|
|
|
startDrag (targetId) {
|
|
|
|
const target = this.runtime.getTargetById(targetId);
|
|
|
|
if (target) {
|
2017-11-21 11:45:11 -05:00
|
|
|
this._dragTarget = target;
|
2017-04-17 19:42:48 -04:00
|
|
|
target.startDrag();
|
|
|
|
}
|
2017-03-03 09:35:57 -05:00
|
|
|
}
|
|
|
|
|
2017-04-17 19:42:48 -04:00
|
|
|
/**
|
|
|
|
* Remove a target from a drag state, so blocks may begin affecting X/Y position again
|
|
|
|
* @param {string} targetId The id for the target to remove from the drag state
|
|
|
|
*/
|
|
|
|
stopDrag (targetId) {
|
|
|
|
const target = this.runtime.getTargetById(targetId);
|
2017-11-21 11:45:11 -05:00
|
|
|
if (target) {
|
|
|
|
this._dragTarget = null;
|
|
|
|
target.stopDrag();
|
2018-04-11 09:12:43 -04:00
|
|
|
this.setEditingTarget(target.sprite && target.sprite.clones[0] ?
|
|
|
|
target.sprite.clones[0].id : target.id);
|
2017-11-21 11:45:11 -05:00
|
|
|
}
|
2017-04-17 19:42:48 -04:00
|
|
|
}
|
2017-03-03 09:35:57 -05:00
|
|
|
|
2017-04-17 19:42:48 -04:00
|
|
|
/**
|
2017-11-21 11:45:11 -05:00
|
|
|
* Post/edit sprite info for the current editing target or the drag target.
|
2017-04-17 19:42:48 -04:00
|
|
|
* @param {object} data An object with sprite info data to set.
|
|
|
|
*/
|
|
|
|
postSpriteInfo (data) {
|
2017-11-21 11:45:11 -05:00
|
|
|
if (this._dragTarget) {
|
|
|
|
this._dragTarget.postSpriteInfo(data);
|
|
|
|
} else {
|
|
|
|
this.editingTarget.postSpriteInfo(data);
|
|
|
|
}
|
2017-04-17 19:42:48 -04:00
|
|
|
}
|
2018-06-05 10:46:06 -04:00
|
|
|
|
|
|
|
/**
|
2018-06-05 16:08:14 -04:00
|
|
|
* Set a target's variable's value. Return whether it succeeded.
|
2018-06-05 10:46:06 -04:00
|
|
|
* @param {!string} targetId ID of the target which owns the variable.
|
|
|
|
* @param {!string} variableId ID of the variable to set.
|
|
|
|
* @param {!*} value The new value of that variable.
|
|
|
|
* @returns {boolean} whether the target and variable were found and updated.
|
|
|
|
*/
|
|
|
|
setVariableValue (targetId, variableId, value) {
|
|
|
|
const target = this.runtime.getTargetById(targetId);
|
|
|
|
if (target) {
|
|
|
|
const variable = target.lookupVariableById(variableId);
|
|
|
|
if (variable) {
|
|
|
|
variable.value = value;
|
2018-12-05 22:38:06 -05:00
|
|
|
|
|
|
|
if (variable.isCloud) {
|
|
|
|
this.runtime.ioDevices.cloud.requestUpdateVariable(variable.name, variable.value);
|
|
|
|
}
|
|
|
|
|
2018-06-05 10:46:06 -04:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2018-06-05 16:08:14 -04:00
|
|
|
* Get a target's variable's value. Return null if the target or variable does not exist.
|
2018-06-05 10:46:06 -04:00
|
|
|
* @param {!string} targetId ID of the target which owns the variable.
|
|
|
|
* @param {!string} variableId ID of the variable to set.
|
|
|
|
* @returns {?*} The value of the variable, or null if it could not be looked up.
|
|
|
|
*/
|
|
|
|
getVariableValue (targetId, variableId) {
|
|
|
|
const target = this.runtime.getTargetById(targetId);
|
|
|
|
if (target) {
|
|
|
|
const variable = target.lookupVariableById(variableId);
|
|
|
|
if (variable) {
|
|
|
|
return variable.value;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return null;
|
|
|
|
}
|
2017-04-17 19:42:48 -04:00
|
|
|
}
|
2017-01-13 16:34:26 -05:00
|
|
|
|
|
|
|
module.exports = VirtualMachine;
|