|
let _TextEncoder; |
|
if (typeof TextEncoder === 'undefined') { |
|
_TextEncoder = require('text-encoding').TextEncoder; |
|
} else { |
|
|
|
_TextEncoder = TextEncoder; |
|
} |
|
const EventEmitter = require('events'); |
|
const JSZip = require('jszip'); |
|
|
|
const Buffer = require('buffer').Buffer; |
|
const centralDispatch = require('./dispatch/central-dispatch'); |
|
const ExtensionManager = require('./extension-support/extension-manager'); |
|
const log = require('./util/log'); |
|
const MathUtil = require('./util/math-util'); |
|
const Runtime = require('./engine/runtime'); |
|
const StringUtil = require('./util/string-util'); |
|
const RenderedTarget = require('./sprites/rendered-target'); |
|
const StageLayering = require('./engine/stage-layering'); |
|
const Sprite = require('./sprites/sprite'); |
|
const Blocks = require('./engine/blocks'); |
|
const Comment = require('./engine/comment.js'); |
|
const formatMessage = require('format-message'); |
|
const ExtensionStorage = require('./util/deprecated-extension-storage.js'); |
|
|
|
const Variable = require('./engine/variable'); |
|
const newBlockIds = require('./util/new-block-ids'); |
|
|
|
const {loadCostume} = require('./import/load-costume.js'); |
|
const {loadSound} = require('./import/load-sound.js'); |
|
const {serializeSounds, serializeCostumes} = require('./serialization/serialize-assets'); |
|
require('canvas-toBlob'); |
|
const {exportCostume} = require('./serialization/tw-costume-import-export'); |
|
const Base64Util = require('./util/base64-util'); |
|
|
|
const RESERVED_NAMES = ['_mouse_', '_stage_', '_edge_', '_myself_', '_random_']; |
|
const PM_LIBRARY_API = "https://library.penguinmod.com/"; |
|
|
|
const IRGenerator = require('./compiler/irgen'); |
|
const JSGenerator = require('./compiler/jsgen'); |
|
const jsexecute = require('./compiler/jsexecute'); |
|
const { SyntheticModule } = require('vm'); |
|
|
|
const CORE_EXTENSIONS = [ |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
]; |
|
|
|
|
|
formatMessage.setup({ |
|
missingTranslation: 'ignore' |
|
}); |
|
|
|
const createRuntimeService = runtime => { |
|
const service = {}; |
|
service._refreshExtensionPrimitives = runtime._refreshExtensionPrimitives.bind(runtime); |
|
service._registerExtensionPrimitives = runtime._registerExtensionPrimitives.bind(runtime); |
|
service._removeExtensionPrimitive = runtime._removeExtensionPrimitive.bind(runtime); |
|
return service; |
|
}; |
|
|
|
|
|
|
|
|
|
|
|
class VirtualMachine extends EventEmitter { |
|
constructor () { |
|
super(); |
|
|
|
|
|
|
|
|
|
|
|
this.runtime = new Runtime(); |
|
centralDispatch.setService('runtime', createRuntimeService(this.runtime)).catch(e => { |
|
log.error(`Failed to register runtime service: ${JSON.stringify(e)}`); |
|
}); |
|
|
|
|
|
|
|
|
|
|
|
|
|
this.editingTarget = null; |
|
|
|
|
|
|
|
|
|
|
|
this._dragTarget = null; |
|
|
|
|
|
this.runtime.on(Runtime.SCRIPT_GLOW_ON, glowData => { |
|
this.emit(Runtime.SCRIPT_GLOW_ON, glowData); |
|
}); |
|
this.runtime.on(Runtime.SCRIPT_GLOW_OFF, glowData => { |
|
this.emit(Runtime.SCRIPT_GLOW_OFF, glowData); |
|
}); |
|
this.runtime.on(Runtime.BLOCK_GLOW_ON, glowData => { |
|
this.emit(Runtime.BLOCK_GLOW_ON, glowData); |
|
}); |
|
this.runtime.on(Runtime.BLOCK_GLOW_OFF, glowData => { |
|
this.emit(Runtime.BLOCK_GLOW_OFF, glowData); |
|
}); |
|
this.runtime.on(Runtime.PROJECT_START, () => { |
|
this.emit(Runtime.PROJECT_START); |
|
}); |
|
this.runtime.on(Runtime.PROJECT_RUN_START, () => { |
|
this.emit(Runtime.PROJECT_RUN_START); |
|
}); |
|
this.runtime.on(Runtime.PROJECT_RUN_STOP, () => { |
|
this.emit(Runtime.PROJECT_RUN_STOP); |
|
}); |
|
this.runtime.on(Runtime.PROJECT_CHANGED, () => { |
|
this.emit(Runtime.PROJECT_CHANGED); |
|
}); |
|
this.runtime.on(Runtime.VISUAL_REPORT, visualReport => { |
|
this.emit(Runtime.VISUAL_REPORT, visualReport); |
|
}); |
|
this.runtime.on(Runtime.BLOCK_STACK_ERROR, visualReport => { |
|
this.emit(Runtime.BLOCK_STACK_ERROR, visualReport); |
|
}); |
|
this.runtime.on(Runtime.TARGETS_UPDATE, emitProjectChanged => { |
|
this.emitTargetsUpdate(emitProjectChanged); |
|
}); |
|
this.runtime.on(Runtime.MONITORS_UPDATE, monitorList => { |
|
this.emit(Runtime.MONITORS_UPDATE, monitorList); |
|
}); |
|
this.runtime.on(Runtime.BLOCK_DRAG_UPDATE, areBlocksOverGui => { |
|
this.emit(Runtime.BLOCK_DRAG_UPDATE, areBlocksOverGui); |
|
}); |
|
this.runtime.on(Runtime.BLOCK_DRAG_END, (blocks, topBlockId) => { |
|
this.emit(Runtime.BLOCK_DRAG_END, blocks, topBlockId); |
|
}); |
|
this.runtime.on(Runtime.EXTENSION_ADDED, categoryInfo => { |
|
this.emit(Runtime.EXTENSION_ADDED, categoryInfo); |
|
}); |
|
this.runtime.on(Runtime.EXTENSION_REMOVED, () => { |
|
this.emit(Runtime.EXTENSION_REMOVED); |
|
}); |
|
this.runtime.on(Runtime.EXTENSION_FIELD_ADDED, (fieldName, fieldImplementation) => { |
|
this.emit(Runtime.EXTENSION_FIELD_ADDED, fieldName, fieldImplementation); |
|
}); |
|
this.runtime.on(Runtime.BLOCKSINFO_UPDATE, categoryInfo => { |
|
this.emit(Runtime.BLOCKSINFO_UPDATE, categoryInfo); |
|
}); |
|
this.runtime.on(Runtime.BLOCKS_NEED_UPDATE, () => { |
|
this.emitWorkspaceUpdate(); |
|
}); |
|
this.runtime.on(Runtime.TOOLBOX_EXTENSIONS_NEED_UPDATE, () => { |
|
this.extensionManager.refreshBlocks(); |
|
}); |
|
this.runtime.on(Runtime.PERIPHERAL_LIST_UPDATE, info => { |
|
this.emit(Runtime.PERIPHERAL_LIST_UPDATE, info); |
|
}); |
|
this.runtime.on(Runtime.USER_PICKED_PERIPHERAL, info => { |
|
this.emit(Runtime.USER_PICKED_PERIPHERAL, info); |
|
}); |
|
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_DISCONNECTED, () => |
|
this.emit(Runtime.PERIPHERAL_DISCONNECTED) |
|
); |
|
this.runtime.on(Runtime.PERIPHERAL_CONNECTION_LOST_ERROR, data => |
|
this.emit(Runtime.PERIPHERAL_CONNECTION_LOST_ERROR, data) |
|
); |
|
this.runtime.on(Runtime.PERIPHERAL_SCAN_TIMEOUT, () => |
|
this.emit(Runtime.PERIPHERAL_SCAN_TIMEOUT) |
|
); |
|
this.runtime.on(Runtime.MIC_LISTENING, listening => { |
|
this.emit(Runtime.MIC_LISTENING, listening); |
|
}); |
|
this.runtime.on(Runtime.RUNTIME_STARTED, () => { |
|
this.emit(Runtime.RUNTIME_STARTED); |
|
}); |
|
this.runtime.on(Runtime.RUNTIME_PAUSED, () => { |
|
this.emit(Runtime.RUNTIME_PAUSED); |
|
}); |
|
this.runtime.on(Runtime.RUNTIME_UNPAUSED, () => { |
|
this.emit(Runtime.RUNTIME_UNPAUSED); |
|
}); |
|
this.runtime.on(Runtime.RUNTIME_STOPPED, () => { |
|
this.emit(Runtime.RUNTIME_STOPPED); |
|
}); |
|
this.runtime.on(Runtime.HAS_CLOUD_DATA_UPDATE, hasCloudData => { |
|
this.emit(Runtime.HAS_CLOUD_DATA_UPDATE, hasCloudData); |
|
}); |
|
this.runtime.on(Runtime.RUNTIME_OPTIONS_CHANGED, runtimeOptions => { |
|
this.emit(Runtime.RUNTIME_OPTIONS_CHANGED, runtimeOptions); |
|
}); |
|
this.runtime.on(Runtime.COMPILER_OPTIONS_CHANGED, compilerOptions => { |
|
this.emit(Runtime.COMPILER_OPTIONS_CHANGED, compilerOptions); |
|
}); |
|
this.runtime.on(Runtime.FRAMERATE_CHANGED, framerate => { |
|
this.emit(Runtime.FRAMERATE_CHANGED, framerate); |
|
}); |
|
this.runtime.on(Runtime.INTERPOLATION_CHANGED, framerate => { |
|
this.emit(Runtime.INTERPOLATION_CHANGED, framerate); |
|
}); |
|
this.runtime.on(Runtime.BEFORE_INTERPOLATE, target => { |
|
this.emit(Runtime.BEFORE_INTERPOLATE, target); |
|
}); |
|
this.runtime.on(Runtime.AFTER_INTERPOLATE, target => { |
|
this.emit(Runtime.AFTER_INTERPOLATE, target); |
|
}); |
|
this.runtime.on(Runtime.STAGE_SIZE_CHANGED, (width, height) => { |
|
this.emit(Runtime.STAGE_SIZE_CHANGED, width, height); |
|
}); |
|
this.runtime.on(Runtime.COMPILE_ERROR, (target, error) => { |
|
this.emit(Runtime.COMPILE_ERROR, target, error); |
|
}); |
|
this.runtime.on(Runtime.TURBO_MODE_OFF, () => { |
|
this.emit(Runtime.TURBO_MODE_OFF); |
|
}); |
|
this.runtime.on(Runtime.TURBO_MODE_ON, () => { |
|
this.emit(Runtime.TURBO_MODE_ON); |
|
}); |
|
|
|
this.extensionManager = new ExtensionManager(this); |
|
this.securityManager = this.extensionManager.securityManager; |
|
this.runtime.extensionManager = this.extensionManager; |
|
this.runtime.vm = this; |
|
|
|
|
|
for (const id of CORE_EXTENSIONS) { |
|
this.extensionManager.loadExtensionIdSync(id); |
|
} |
|
|
|
this.blockListener = this.blockListener.bind(this); |
|
this.flyoutBlockListener = this.flyoutBlockListener.bind(this); |
|
this.monitorBlockListener = this.monitorBlockListener.bind(this); |
|
this.variableListener = this.variableListener.bind(this); |
|
this.addListener('workspaceUpdate', () => { |
|
this.extensionManager.refreshDynamicCategorys(); |
|
}); |
|
|
|
|
|
|
|
|
|
this.exports = { |
|
Sprite, |
|
RenderedTarget, |
|
JSZip, |
|
JSGenerator, |
|
IRGenerator, |
|
jsexecute, |
|
loadCostume, |
|
loadSound, |
|
Blocks, |
|
Comment, |
|
StageLayering, |
|
Variable, |
|
Thread: require('./engine/thread.js'), |
|
execute: require('./engine/execute.js'), |
|
centralDispatch |
|
}; |
|
|
|
|
|
|
|
|
|
|
|
this.exports.i_will_not_ask_for_help_when_these_break = () => { |
|
console.info( |
|
'Note on i_will_not_ask_for_help_when_these_break: this function is ' + |
|
'only included for compatibility with TurboWarp, and you should avoid ' + |
|
'using it when possible.\n' + |
|
'All indexes are able to be accessed from the regular vm.exports ' + |
|
'property. Below is a map of all elements here to their vm.exports ' + |
|
'counterpart:\n' + |
|
'IRGenerator -> IRGenerator\nJSGenerator -> JSGenerator\nThread -> Thread\n' + |
|
'execute -> execute\n' + |
|
'ScriptTreeGenerator -> IRGenerator.exports.ScriptTreeGenerator' |
|
); |
|
return { |
|
IRGenerator, |
|
JSGenerator, |
|
ScriptTreeGenerator: IRGenerator.exports.ScriptTreeGenerator, |
|
Thread: this.exports.Thread, |
|
execute: this.exports.execute |
|
} |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
start () { |
|
this.runtime.start(); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
stop () { |
|
this.runtime.stop(); |
|
} |
|
|
|
|
|
|
|
|
|
greenFlag () { |
|
this.runtime.greenFlag(); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
setTurboMode (turboModeOn) { |
|
this.runtime.turboMode = !!turboModeOn; |
|
if (this.runtime.turboMode) { |
|
this.emit(Runtime.TURBO_MODE_ON); |
|
} else { |
|
this.emit(Runtime.TURBO_MODE_OFF); |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
setCompatibilityMode (compatibilityModeOn) { |
|
this.runtime.setCompatibilityMode(!!compatibilityModeOn); |
|
} |
|
|
|
setFramerate (framerate) { |
|
this.runtime.setFramerate(framerate); |
|
} |
|
|
|
setInterpolation (interpolationEnabled) { |
|
this.runtime.setInterpolation(interpolationEnabled); |
|
} |
|
|
|
setRuntimeOptions (runtimeOptions) { |
|
this.runtime.setRuntimeOptions(runtimeOptions); |
|
} |
|
|
|
setCompilerOptions (compilerOptions) { |
|
this.runtime.setCompilerOptions(compilerOptions); |
|
} |
|
|
|
setStageSize (width, height) { |
|
this.runtime.setStageSize(width, height); |
|
} |
|
|
|
setInEditor (inEditor) { |
|
this.runtime.setInEditor(inEditor); |
|
} |
|
|
|
convertToPackagedRuntime () { |
|
this.runtime.convertToPackagedRuntime(); |
|
} |
|
|
|
addAddonBlock (options) { |
|
this.runtime.addAddonBlock(options); |
|
} |
|
|
|
getAddonBlock (procedureCode) { |
|
return this.runtime.getAddonBlock(procedureCode); |
|
} |
|
|
|
storeProjectOptions () { |
|
this.runtime.storeProjectOptions(); |
|
if (this.editingTarget.isStage) { |
|
this.emitWorkspaceUpdate(); |
|
} |
|
} |
|
|
|
enableDebug () { |
|
this.runtime.enableDebug(); |
|
return 'enabled debug mode'; |
|
} |
|
|
|
|
|
|
|
|
|
stopAll () { |
|
this.runtime.stopAll(); |
|
} |
|
|
|
|
|
|
|
|
|
clear () { |
|
this.runtime.dispose(); |
|
this.editingTarget = null; |
|
this.emitTargetsUpdate(false ); |
|
} |
|
|
|
|
|
|
|
|
|
getPlaygroundData () { |
|
const instance = this; |
|
|
|
const threadData = this.runtime.threads.filter(thread => thread.target === instance.editingTarget); |
|
|
|
const filteredThreadData = JSON.stringify(threadData, (key, value) => { |
|
if (key === 'target' || key === 'blockContainer') return; |
|
return value; |
|
}, 2); |
|
this.emit('playgroundData', { |
|
blocks: this.editingTarget.blocks, |
|
threads: filteredThreadData |
|
}); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
postIOData (device, data) { |
|
if (this.runtime.ioDevices[device]) { |
|
this.runtime.ioDevices[device].postData(data); |
|
} |
|
} |
|
|
|
setVideoProvider (videoProvider) { |
|
this.runtime.ioDevices.video.setProvider(videoProvider); |
|
} |
|
|
|
setCloudProvider (cloudProvider) { |
|
this.runtime.ioDevices.cloud.setProvider(cloudProvider); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
scanForPeripheral (extensionId) { |
|
this.runtime.scanForPeripheral(extensionId); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
connectPeripheral (extensionId, peripheralId) { |
|
this.runtime.connectPeripheral(extensionId, peripheralId); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
disconnectPeripheral (extensionId) { |
|
this.runtime.disconnectPeripheral(extensionId); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
getPeripheralIsConnected (extensionId) { |
|
return this.runtime.getPeripheralIsConnected(extensionId); |
|
} |
|
|
|
isSB2(json) { |
|
return Array.isArray(json.children) && !Array.isArray(json.targets); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
loadProject (input) { |
|
return new Promise(async (resolve, reject) => { |
|
try { |
|
const arr = new Uint8Array(input); |
|
const tag = [...arr.slice(0, 7)] |
|
.map(char => String.fromCharCode(char)) |
|
.join(''); |
|
if (tag === 'Scratch') { |
|
const { SB1File } = require('scratch-sb1-converter'); |
|
const sb1 = new SB1File(input); |
|
const json = sb1.json; |
|
json.projectVersion = 2; |
|
return resolve([json, sb1.zip]); |
|
} |
|
|
|
if (typeof input === 'string') input = JSON.parse(input); |
|
|
|
if (input.toString() === '[object Object]') { |
|
input.projectVersion = this.isSB2(input) ? 2 : 3; |
|
return resolve([input, null]); |
|
} |
|
if (tag.slice(0, 2) !== 'PK') { |
|
|
|
const decoder = new TextDecoder('UTF-8'); |
|
input = decoder.decode(input); |
|
|
|
if (typeof input === 'string') input = JSON.parse(input); |
|
|
|
if (input.toString() === '[object Object]') { |
|
input.projectVersion = this.isSB2(input) ? 2 : 3; |
|
return resolve([input, null]); |
|
} |
|
} |
|
|
|
const zip = await JSZip.loadAsync(input); |
|
const proj = zip.file('project.json'); |
|
if (!proj) return reject('No project.json file inside the given project'); |
|
const json = JSON.parse(await proj.async('string')); |
|
json.projectVersion = this.isSB2(json) ? 2 : 3; |
|
|
|
this._projectZip = zip |
|
return resolve([json, zip]); |
|
} catch (err) { |
|
reject(err.toString()); |
|
} |
|
}) |
|
.then(validatedInput => this.deserializeProject(validatedInput[0], validatedInput[1])) |
|
.then(() => this.runtime.emitProjectLoaded()) |
|
.catch(error => { |
|
console.error(error); |
|
|
|
if (error.hasOwnProperty('validationError')) { |
|
return Promise.reject(JSON.stringify(error, null, 4)); |
|
} |
|
return Promise.reject(error); |
|
}); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
downloadProjectId (id) { |
|
const storage = this.runtime.storage; |
|
if (!storage) { |
|
log.error('No storage module present; cannot load project: ', id); |
|
return; |
|
} |
|
const vm = this; |
|
const promise = storage.load(storage.AssetType.Project, id); |
|
promise.then(projectAsset => { |
|
if (!projectAsset) { |
|
log.error(`Failed to fetch project with id: ${id}`); |
|
return null; |
|
} |
|
return vm.loadProject(projectAsset.data); |
|
}); |
|
} |
|
|
|
_projectZip = new JSZip(); |
|
|
|
|
|
|
|
|
|
_saveProjectZip () { |
|
const projectJson = this.toJSON(); |
|
|
|
|
|
|
|
const zip = new JSZip(); |
|
|
|
|
|
zip.file('project.json', projectJson); |
|
this._addFileDescsToZip(this.serializeAssets(), zip); |
|
|
|
|
|
if (this._projectZip) { |
|
try { |
|
zip.files = {...zip.files, ...Object.fromEntries(Object.entries(this._projectZip.files).filter(v => v[0].startsWith("extraAssets/")))} |
|
} catch (e) { |
|
console.warn("unable to get extra assets", e) |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
const date = new Date(1591657163000); |
|
for (const file of Object.values(zip.files)) { |
|
file.date = date; |
|
} |
|
|
|
|
|
const COMPRESSABLE_FORMATS = [ |
|
'.json', |
|
'.svg', |
|
'.wav', |
|
'.ttf', |
|
'.otf' |
|
]; |
|
for (const file of Object.values(zip.files)) { |
|
if (COMPRESSABLE_FORMATS.some(ext => file.name.endsWith(ext))) { |
|
file.options.compression = 'DEFLATE'; |
|
} else { |
|
file.options.compression = 'STORE'; |
|
} |
|
} |
|
return zip; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
saveProjectSb3 (type) { |
|
return this._saveProjectZip().generateAsync({ |
|
type: type || 'blob', |
|
mimeType: 'application/x.scratch.sb3', |
|
compression: 'DEFLATE' |
|
}); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
saveProjectSb3Stream (type) { |
|
return this._saveProjectZip().generateInternalStream({ |
|
type: type || 'arraybuffer', |
|
mimeType: 'application/x.scratch.sb3', |
|
compression: 'DEFLATE' |
|
}); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
saveProjectSb3DontZip () { |
|
const projectJson = this.toJSON(); |
|
|
|
const files = { |
|
'project.json': new _TextEncoder().encode(projectJson) |
|
}; |
|
for (const fileDesc of this.serializeAssets()) { |
|
files[fileDesc.fileName] = fileDesc.fileContent; |
|
} |
|
|
|
return files; |
|
} |
|
|
|
|
|
|
|
|
|
get assets () { |
|
const costumesAndSounds = this.runtime.targets.reduce((acc, target) => ( |
|
acc |
|
.concat(target.sprite.sounds.map(sound => sound.asset)) |
|
.concat(target.sprite.costumes.map(costume => costume.asset)) |
|
), []); |
|
const fonts = this.runtime.fontManager.serializeAssets(); |
|
return [ |
|
...costumesAndSounds, |
|
...fonts |
|
]; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
serializeAssets(targetId) { |
|
const costumeDescs = serializeCostumes(this.runtime, targetId); |
|
const soundDescs = serializeSounds(this.runtime, targetId); |
|
const fontDescs = this.runtime.fontManager.serializeAssets().map(asset => ({ |
|
fileName: `${asset.assetId}.${asset.dataFormat}`, |
|
fileContent: asset.data |
|
})); |
|
return [ |
|
...costumeDescs, |
|
...soundDescs, |
|
...fontDescs |
|
]; |
|
} |
|
|
|
_addFileDescsToZip (fileDescs, zip) { |
|
for (let i = 0; i < fileDescs.length; i++) { |
|
const currFileDesc = fileDescs[i]; |
|
zip.file(currFileDesc.fileName, currFileDesc.fileContent); |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
exportSprite (targetId, optZipType) { |
|
const spriteJson = this.toJSON(targetId); |
|
|
|
const zip = new JSZip(); |
|
zip.file('sprite.json', spriteJson); |
|
this._addFileDescsToZip(this.serializeAssets(targetId), zip); |
|
|
|
return zip.generateAsync({ |
|
type: typeof optZipType === 'string' ? optZipType : 'blob', |
|
mimeType: 'application/x.scratch.sprite3', |
|
compression: 'DEFLATE', |
|
compressionOptions: { |
|
level: 6 |
|
} |
|
}); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
toJSON (optTargetId, serializationOptions) { |
|
const sb3 = require('./serialization/sb3'); |
|
return StringUtil.stringify(sb3.serialize(this.runtime, optTargetId, serializationOptions)); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
fromJSON (json) { |
|
log.warning('fromJSON is now just a wrapper around loadProject, please use that function instead.'); |
|
return this.loadProject(json); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
deserializeProject (projectJSON, zip) { |
|
|
|
this.clear(); |
|
|
|
if (typeof performance !== 'undefined') { |
|
performance.mark('scratch-vm-deserialize-start'); |
|
} |
|
const runtime = this.runtime; |
|
const deserializePromise = function () { |
|
const projectVersion = projectJSON.projectVersion; |
|
if (projectVersion === 2) { |
|
const sb2 = require('./serialization/sb2'); |
|
return sb2.deserialize(projectJSON, runtime, false, zip); |
|
} |
|
if (projectVersion === 3) { |
|
const sb3 = require('./serialization/sb3'); |
|
|
|
return sb3.deserialize(projectJSON, runtime, zip, false, this); |
|
} |
|
return Promise.reject('Unable to verify Scratch Project version.'); |
|
}; |
|
return deserializePromise() |
|
.then(({targets, extensions}) => { |
|
if (typeof performance !== 'undefined') { |
|
performance.mark('scratch-vm-deserialize-end'); |
|
try { |
|
performance.measure('scratch-vm-deserialize', |
|
'scratch-vm-deserialize-start', 'scratch-vm-deserialize-end'); |
|
} catch (e) { |
|
|
|
|
|
|
|
|
|
log.error(e); |
|
} |
|
} |
|
return this.installTargets(targets, extensions, true); |
|
}); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
async _loadExtensions (extensionIDs, extensionURLs = new Map()) { |
|
const extensionPromises = []; |
|
for (const extensionID of extensionIDs) { |
|
const url = extensionURLs.get(extensionID); |
|
if (this.extensionManager.isExtensionLoaded(extensionID)) { |
|
|
|
} else if (url) { |
|
|
|
if (await this.securityManager.canLoadExtensionFromProject(url)) { |
|
extensionPromises.push(this.extensionManager.loadExtensionURL(url)); |
|
} else { |
|
throw new Error(`Permission to load extension denied: ${extensionID}`); |
|
} |
|
} else if (this.extensionManager.isBuiltinExtension(extensionID)) { |
|
|
|
this.extensionManager.loadExtensionIdSync(extensionID); |
|
} else { |
|
throw new Error(`Unknown extension: ${extensionID}`); |
|
} |
|
} |
|
return Promise.all(extensionPromises); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async installTargets (targets, extensions, wholeProject) { |
|
await this.extensionManager.allAsyncExtensionsLoaded(); |
|
|
|
targets = targets.filter(target => !!target); |
|
|
|
return this._loadExtensions(extensions.extensionIDs, extensions.extensionURLs).then(() => { |
|
const deprecated_extensionStorage = {}; |
|
for (const extension of extensions.extensionIDs) { |
|
if (!extensions.extensionData[extension]) continue; |
|
if ( |
|
`ext_${extension}` in this.runtime && |
|
typeof this.runtime[`ext_${extension}`].deserialize === 'function' |
|
) { |
|
this.runtime[`ext_${extension}`].deserialize(extensions.extensionData[extension]); |
|
continue; |
|
} |
|
deprecated_extensionStorage[extension] = extensions.extensionData[extension]; |
|
} |
|
if (deprecated_extensionStorage) |
|
this.runtime.extensionStorage = ExtensionStorage(deprecated_extensionStorage); |
|
|
|
targets.forEach(target => { |
|
this.runtime.addTarget(target); |
|
( target).updateAllDrawableProperties(); |
|
|
|
if (target.isSprite()) this.renameSprite(target.id, target.getName()); |
|
|
|
if (!("extensionData" in target)) return; |
|
|
|
const deprecated_extensionStorage_pertarget = {}; |
|
|
|
for (const extension of extensions.extensionIDs) { |
|
if (!(extension in target.extensionData)) continue; |
|
|
|
if ( |
|
`ext_${extension}` in this.runtime && |
|
typeof this.runtime[`ext_${extension}`].deserializeForTarget === 'function' |
|
) { |
|
this.runtime[`ext_${extension}`].deserializeForTarget( |
|
target.extensionData[extension], |
|
target, |
|
); |
|
continue; |
|
} |
|
deprecated_extensionStorage_pertarget[extension] = target.extensionData[extension]; |
|
} |
|
|
|
if (deprecated_extensionStorage) |
|
target.extensionStorage = ExtensionStorage(deprecated_extensionStorage_pertarget); |
|
|
|
delete target["extensionData"] |
|
}); |
|
|
|
|
|
this.runtime.executableTargets.sort((a, b) => a.layerOrder - b.layerOrder); |
|
targets.forEach(target => { |
|
delete target.layerOrder; |
|
}); |
|
|
|
|
|
if (wholeProject && (targets.length > 1)) { |
|
this.editingTarget = targets[1]; |
|
} else { |
|
this.editingTarget = targets[0]; |
|
} |
|
|
|
if (!wholeProject) { |
|
this.editingTarget.fixUpVariableReferences(); |
|
} |
|
|
|
if (wholeProject) { |
|
this.runtime.parseProjectOptions(); |
|
} |
|
|
|
|
|
this.emitTargetsUpdate(false ); |
|
this.emitWorkspaceUpdate(); |
|
this.runtime.setEditingTarget(this.editingTarget); |
|
this.runtime.ioDevices.cloud.setStage(this.runtime.getTargetForStage()); |
|
}); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
addSprite (input) { |
|
const errorPrefix = 'Sprite Upload Error:'; |
|
if (typeof input === 'object' && !(input instanceof ArrayBuffer) && |
|
!ArrayBuffer.isView(input)) { |
|
|
|
|
|
|
|
|
|
|
|
|
|
input = JSON.stringify(input); |
|
} |
|
|
|
const validationPromise = new Promise((resolve, reject) => { |
|
const validate = require('scratch-parser'); |
|
|
|
|
|
|
|
validate(input, true, (error, res) => { |
|
if (error) return reject(error); |
|
resolve(res); |
|
}); |
|
}); |
|
|
|
return validationPromise |
|
.then(validatedInput => { |
|
const projectVersion = validatedInput[0].projectVersion; |
|
if (projectVersion === 2) { |
|
return this._addSprite2(validatedInput[0], validatedInput[1]); |
|
} |
|
if (projectVersion === 3) { |
|
return this._addSprite3(validatedInput[0], validatedInput[1]); |
|
} |
|
return Promise.reject(`${errorPrefix} Unable to verify sprite version.`); |
|
}) |
|
.then(() => this.runtime.emitProjectChanged()) |
|
.catch(error => { |
|
|
|
if (error.hasOwnProperty('validationError')) { |
|
return Promise.reject(JSON.stringify(error)); |
|
} |
|
return Promise.reject(`${errorPrefix} ${error}`); |
|
}); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
_addSprite2 (sprite, zip) { |
|
|
|
|
|
const sb2 = require('./serialization/sb2'); |
|
return sb2.deserialize(sprite, this.runtime, true, zip) |
|
.then(({targets, extensions}) => |
|
this.installTargets(targets, extensions, false)); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
_addSprite3 (sprite, zip) { |
|
|
|
const sb3 = require('./serialization/sb3'); |
|
return sb3 |
|
.deserialize(sprite, this.runtime, zip, true) |
|
.then(({targets, extensions}) => this.installTargets(targets, extensions, false)); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
addCostume (md5ext, costumeObject, optTargetId, optVersion) { |
|
const target = optTargetId ? this.runtime.getTargetById(optTargetId) : |
|
this.editingTarget; |
|
if (target) { |
|
if (costumeObject.fromPenguinModLibrary === true) { |
|
return new Promise((resolve, reject) => { |
|
fetch(`${PM_LIBRARY_API}files/${costumeObject.libraryId}`) |
|
.then((r) => r.arrayBuffer()) |
|
.then((arrayBuffer) => { |
|
const dataFormat = costumeObject.dataFormat; |
|
const storage = this.runtime.storage; |
|
const asset = new storage.Asset( |
|
storage.AssetType[dataFormat === 'svg' ? "ImageVector" : "ImageBitmap"], |
|
null, |
|
storage.DataFormat[dataFormat.toUpperCase()], |
|
new Uint8Array(arrayBuffer), |
|
true |
|
); |
|
const newCostumeObject = { |
|
md5: asset.assetId + '.' + asset.dataFormat, |
|
asset: asset, |
|
name: costumeObject.name |
|
} |
|
loadCostume(newCostumeObject.md5, newCostumeObject, this.runtime, optVersion).then(costumeAsset => { |
|
target.addCostume(newCostumeObject); |
|
target.setCostume( |
|
target.getCostumes().length - 1 |
|
); |
|
this.runtime.emitProjectChanged(); |
|
resolve(costumeAsset, newCostumeObject); |
|
}) |
|
}).catch(reject); |
|
}); |
|
} |
|
return loadCostume(md5ext, costumeObject, this.runtime, optVersion).then(costumeObject => { |
|
target.addCostume(costumeObject); |
|
target.setCostume( |
|
target.getCostumes().length - 1 |
|
); |
|
this.runtime.emitProjectChanged(); |
|
}); |
|
} |
|
|
|
return Promise.reject(); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
addCostumeFromLibrary (md5ext, costumeObject) { |
|
if (!this.editingTarget) return Promise.reject(); |
|
return this.addCostume(md5ext, costumeObject, this.editingTarget.id, 2 ); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
duplicateCostume (costumeIndex) { |
|
const originalCostume = this.editingTarget.getCostumes()[costumeIndex]; |
|
const clone = Object.assign({}, originalCostume); |
|
const md5ext = `${clone.assetId}.${clone.dataFormat}`; |
|
return loadCostume(md5ext, clone, this.runtime).then(() => { |
|
this.editingTarget.addCostume(clone, costumeIndex + 1); |
|
this.editingTarget.setCostume(costumeIndex + 1); |
|
this.emitTargetsUpdate(); |
|
}); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
duplicateSound (soundIndex) { |
|
const originalSound = this.editingTarget.getSounds()[soundIndex]; |
|
const clone = Object.assign({}, originalSound); |
|
return loadSound(clone, this.runtime, this.editingTarget.sprite.soundBank).then(() => { |
|
this.editingTarget.addSound(clone, soundIndex + 1); |
|
this.emitTargetsUpdate(); |
|
}); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
renameCostume (costumeIndex, newName) { |
|
this.editingTarget.renameCostume(costumeIndex, newName); |
|
this.emitTargetsUpdate(); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
deleteCostume (costumeIndex) { |
|
const deletedCostume = this.editingTarget.deleteCostume(costumeIndex); |
|
if (deletedCostume) { |
|
const target = this.editingTarget; |
|
this.runtime.emitProjectChanged(); |
|
return () => { |
|
target.addCostume(deletedCostume); |
|
this.emitTargetsUpdate(); |
|
}; |
|
} |
|
return null; |
|
} |
|
|
|
|
|
|
|
|
|
pause() { |
|
this.runtime.pause(); |
|
} |
|
|
|
|
|
|
|
|
|
play() { |
|
this.runtime.play(); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
addSound (soundObject, optTargetId) { |
|
const target = optTargetId ? this.runtime.getTargetById(optTargetId) : |
|
this.editingTarget; |
|
if (target) { |
|
if (soundObject.fromPenguinModLibrary === true) { |
|
return new Promise((resolve, reject) => { |
|
fetch(`${PM_LIBRARY_API}files/${soundObject.libraryId}`) |
|
.then((r) => r.arrayBuffer()) |
|
.then((arrayBuffer) => { |
|
const storage = this.runtime.storage; |
|
const asset = new storage.Asset( |
|
storage.AssetType.Sound, |
|
null, |
|
storage.DataFormat.MP3, |
|
new Uint8Array(arrayBuffer), |
|
true |
|
); |
|
const newSoundObject = { |
|
md5: asset.assetId + '.' + asset.dataFormat, |
|
asset: asset, |
|
name: soundObject.name |
|
} |
|
loadSound(newSoundObject, this.runtime, target.sprite.soundBank).then(soundAsset => { |
|
target.addSound(newSoundObject); |
|
this.emitTargetsUpdate(); |
|
resolve(soundAsset, newSoundObject); |
|
}); |
|
}).catch(reject); |
|
}); |
|
} |
|
return loadSound(soundObject, this.runtime, target.sprite.soundBank).then(() => { |
|
target.addSound(soundObject); |
|
this.emitTargetsUpdate(); |
|
}); |
|
} |
|
|
|
return Promise.reject(new Error(`No target with ID: ${optTargetId}`)); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
renameSound (soundIndex, newName) { |
|
this.editingTarget.renameSound(soundIndex, newName); |
|
this.emitTargetsUpdate(); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
getSoundBuffer (soundIndex) { |
|
const id = this.editingTarget.sprite.sounds[soundIndex]?.soundId; |
|
if (id && this.runtime && this.runtime.audioEngine) { |
|
return this.editingTarget.sprite.soundBank.getSoundPlayer(id).buffer; |
|
} |
|
return null; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
updateSoundBuffer (soundIndex, newBuffer, soundEncoding) { |
|
const sound = this.editingTarget.sprite.sounds[soundIndex]; |
|
if (sound && sound.broken) delete sound.broken; |
|
const id = sound ? sound.soundId : null; |
|
if (id && this.runtime && this.runtime.audioEngine) { |
|
this.editingTarget.sprite.soundBank.getSoundPlayer(id).buffer = newBuffer; |
|
} |
|
|
|
if (soundEncoding) { |
|
|
|
|
|
|
|
|
|
|
|
sound.format = ''; |
|
const storage = this.runtime.storage; |
|
sound.asset = storage.createAsset( |
|
storage.AssetType.Sound, |
|
storage.DataFormat.WAV, |
|
soundEncoding, |
|
null, |
|
true |
|
); |
|
sound.assetId = sound.asset.assetId; |
|
sound.dataFormat = storage.DataFormat.WAV; |
|
sound.md5 = `${sound.assetId}.${sound.dataFormat}`; |
|
sound.sampleCount = newBuffer.length; |
|
sound.rate = newBuffer.sampleRate; |
|
} |
|
|
|
|
|
|
|
|
|
this.emitTargetsUpdate(); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
deleteSound (soundIndex) { |
|
const target = this.editingTarget; |
|
const deletedSound = this.editingTarget.deleteSound(soundIndex); |
|
if (deletedSound) { |
|
this.runtime.emitProjectChanged(); |
|
const restoreFun = () => { |
|
target.addSound(deletedSound); |
|
this.emitTargetsUpdate(); |
|
}; |
|
return restoreFun; |
|
} |
|
return null; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
getCostume (costumeIndex) { |
|
const asset = this.editingTarget.getCostumes()[costumeIndex].asset; |
|
if (!asset || !this.runtime || !this.runtime.storage) return null; |
|
const format = asset.dataFormat; |
|
if (format === this.runtime.storage.DataFormat.SVG) { |
|
return asset.decodeText(); |
|
} else if (format === this.runtime.storage.DataFormat.PNG || |
|
format === this.runtime.storage.DataFormat.JPG) { |
|
return asset.encodeDataURI(); |
|
} |
|
log.error(`Unhandled format: ${asset.dataFormat}`); |
|
return null; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
getExportedCostume (costumeObject, optIncludeExtras) { |
|
return exportCostume(costumeObject, optIncludeExtras); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
getExportedCostumeBase64 (costumeObject, optIncludeExtras) { |
|
const binaryData = this.getExportedCostume(costumeObject, optIncludeExtras); |
|
return Base64Util.uint8ArrayToBase64(binaryData); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
updateBitmap (costumeIndex, bitmap, rotationCenterX, rotationCenterY, bitmapResolution) { |
|
return this._updateBitmap( |
|
this.editingTarget.getCostumes()[costumeIndex], |
|
bitmap, |
|
rotationCenterX, |
|
rotationCenterY, |
|
bitmapResolution |
|
); |
|
} |
|
|
|
_updateBitmap (costume, bitmap, rotationCenterX, rotationCenterY, bitmapResolution) { |
|
if (!(costume && this.runtime && this.runtime.renderer)) return; |
|
if (costume && costume.broken) delete costume.broken; |
|
|
|
costume.rotationCenterX = rotationCenterX; |
|
costume.rotationCenterY = rotationCenterY; |
|
|
|
|
|
const bitmapWidth = bitmap.sourceWidth === 0 ? 0 : bitmap.width; |
|
const bitmapHeight = bitmap.sourceHeight === 0 ? 0 : bitmap.height; |
|
|
|
const canvas = document.createElement('canvas'); |
|
canvas.width = bitmapWidth; |
|
canvas.height = bitmapHeight; |
|
const context = canvas.getContext('2d'); |
|
context.putImageData(bitmap, 0, 0); |
|
|
|
|
|
|
|
this.runtime.renderer.updateBitmapSkin( |
|
costume.skinId, |
|
canvas, |
|
bitmapResolution, |
|
[rotationCenterX / bitmapResolution, rotationCenterY / bitmapResolution] |
|
); |
|
|
|
|
|
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 = [bitmapWidth, bitmapHeight]; |
|
costume.asset = storage.createAsset( |
|
storage.AssetType.ImageBitmap, |
|
costume.dataFormat, |
|
Buffer.from(reader.result), |
|
null, |
|
true |
|
); |
|
costume.assetId = costume.asset.assetId; |
|
costume.md5 = `${costume.assetId}.${costume.dataFormat}`; |
|
this.emitTargetsUpdate(); |
|
}); |
|
|
|
if (blob){ |
|
reader.readAsArrayBuffer(blob); |
|
} |
|
}); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
updateSvg (costumeIndex, svg, rotationCenterX, rotationCenterY) { |
|
return this._updateSvg( |
|
this.editingTarget.getCostumes()[costumeIndex], |
|
svg, |
|
rotationCenterX, |
|
rotationCenterY |
|
); |
|
} |
|
|
|
_updateSvg (costume, svg, rotationCenterX, rotationCenterY) { |
|
if (costume && costume.broken) delete costume.broken; |
|
if (costume && this.runtime && this.runtime.renderer) { |
|
costume.rotationCenterX = rotationCenterX; |
|
costume.rotationCenterY = rotationCenterY; |
|
this.runtime.renderer.updateSVGSkin(costume.skinId, svg, [rotationCenterX, rotationCenterY]); |
|
costume.size = this.runtime.renderer.getSkinSize(costume.skinId); |
|
} |
|
const storage = this.runtime.storage; |
|
|
|
|
|
costume.dataFormat = storage.DataFormat.SVG; |
|
costume.bitmapResolution = 1; |
|
costume.asset = storage.createAsset( |
|
storage.AssetType.ImageVector, |
|
costume.dataFormat, |
|
(new _TextEncoder()).encode(svg), |
|
null, |
|
true |
|
); |
|
costume.assetId = costume.asset.assetId; |
|
costume.md5 = `${costume.assetId}.${costume.dataFormat}`; |
|
this.emitTargetsUpdate(); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
addBackdrop(md5ext, backdropObject) { |
|
if (backdropObject.fromPenguinModLibrary === true) { |
|
return new Promise((resolve, reject) => { |
|
fetch(`${PM_LIBRARY_API}files/${backdropObject.libraryId}`) |
|
.then((r) => r.arrayBuffer()) |
|
.then((arrayBuffer) => { |
|
const dataFormat = backdropObject.dataFormat; |
|
const storage = this.runtime.storage; |
|
const asset = new storage.Asset( |
|
storage.AssetType[dataFormat === 'svg' ? "ImageVector" : "ImageBitmap"], |
|
null, |
|
storage.DataFormat[dataFormat.toUpperCase()], |
|
new Uint8Array(arrayBuffer), |
|
true |
|
); |
|
const newCostumeObject = { |
|
md5: asset.assetId + '.' + asset.dataFormat, |
|
asset: asset, |
|
name: backdropObject.name |
|
} |
|
loadCostume(newCostumeObject.md5, newCostumeObject, this.runtime).then(costumeAsset => { |
|
const stage = this.runtime.getTargetForStage(); |
|
stage.addCostume(newCostumeObject); |
|
stage.setCostume(stage.getCostumes().length - 1); |
|
this.runtime.emitProjectChanged(); |
|
resolve(costumeAsset, newCostumeObject); |
|
}) |
|
}).catch(reject); |
|
}); |
|
} |
|
return loadCostume(md5ext, backdropObject, this.runtime).then(() => { |
|
const stage = this.runtime.getTargetForStage(); |
|
stage.addCostume(backdropObject); |
|
stage.setCostume(stage.getCostumes().length - 1); |
|
this.runtime.emitProjectChanged(); |
|
}); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
|
.filter(runtimeTarget => runtimeTarget.isSprite() && runtimeTarget.id !== target.id) |
|
.map(runtimeTarget => runtimeTarget.sprite.name); |
|
const oldName = sprite.name; |
|
const newUnusedName = StringUtil.unusedName(newName, names); |
|
sprite.name = newUnusedName; |
|
if (oldName === newUnusedName) { |
|
return; |
|
} |
|
const allTargets = this.runtime.targets; |
|
for (let i = 0; i < allTargets.length; i++) { |
|
const currTarget = allTargets[i]; |
|
currTarget.blocks.updateAssetName(oldName, newName, 'sprite'); |
|
} |
|
|
|
if (newUnusedName !== oldName) this.emitTargetsUpdate(); |
|
} |
|
} else { |
|
throw new Error('No target with the provided id.'); |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
deleteSprite (targetId) { |
|
const target = this.runtime.getTargetById(targetId); |
|
|
|
if (target) { |
|
const targetIndexBeforeDelete = this.runtime.targets.map(t => t.id).indexOf(target.id); |
|
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.'); |
|
} |
|
const spritePromise = this.exportSprite(targetId, 'uint8array'); |
|
const restoreSprite = () => spritePromise.then(spriteBuffer => this.addSprite(spriteBuffer)); |
|
|
|
|
|
target.deleteMonitors(); |
|
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]); |
|
|
|
if (clone === currentEditingTarget) { |
|
const nextTargetIndex = Math.min(this.runtime.targets.length - 1, targetIndexBeforeDelete); |
|
if (this.runtime.targets.length > 0){ |
|
this.setEditingTarget(this.runtime.targets[nextTargetIndex].id); |
|
} else { |
|
this.editingTarget = null; |
|
} |
|
} |
|
} |
|
|
|
this.emitTargetsUpdate(); |
|
return restoreSprite; |
|
} |
|
|
|
throw new Error('No target with the provided id.'); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
deleteSpriteInternal(targetId) { |
|
const target = this.runtime.getTargetById(targetId); |
|
|
|
if (target) { |
|
const targetIndexBeforeDelete = this.runtime.targets.map(t => t.id).indexOf(target.id); |
|
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.'); |
|
} |
|
const spritePromise = this.exportSprite(targetId, 'uint8array'); |
|
const restoreSprite = () => spritePromise.then(spriteBuffer => this.addSprite(spriteBuffer)); |
|
|
|
|
|
target.deleteMonitors(); |
|
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]); |
|
|
|
if (clone === currentEditingTarget) { |
|
const nextTargetIndex = Math.min(this.runtime.targets.length - 1, targetIndexBeforeDelete); |
|
if (this.runtime.targets.length > 0) { |
|
this.setEditingTarget(this.runtime.targets[nextTargetIndex].id); |
|
} else { |
|
this.editingTarget = null; |
|
} |
|
} |
|
} |
|
|
|
this.emitTargetsUpdate(); |
|
return restoreSprite; |
|
} |
|
|
|
throw new Error('No target with the provided id.'); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
duplicateSprite (targetId) { |
|
const target = this.runtime.getTargetById(targetId); |
|
if (!target) { |
|
throw new Error('No target with the provided id.'); |
|
} 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.'); |
|
} |
|
return target.duplicate().then(newTarget => { |
|
this.runtime.addTarget(newTarget); |
|
newTarget.goBehindOther(target); |
|
this.setEditingTarget(newTarget.id); |
|
}); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
attachAudioEngine (audioEngine) { |
|
this.runtime.attachAudioEngine(audioEngine); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
attachRenderer (renderer) { |
|
this.runtime.attachRenderer(renderer); |
|
} |
|
|
|
|
|
|
|
|
|
get renderer () { |
|
return this.runtime && this.runtime.renderer; |
|
} |
|
|
|
|
|
attachV2SVGAdapter () { |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
attachV2BitmapAdapter (bitmapAdapter) { |
|
this.runtime.attachV2BitmapAdapter(bitmapAdapter); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
attachStorage (storage) { |
|
this.runtime.attachStorage(storage); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
setLocale (locale, messages) { |
|
if (locale !== formatMessage.setup().locale) { |
|
formatMessage.setup({locale: locale, translations: {[locale]: messages}}); |
|
} |
|
this.emit('LOCALE_CHANGED', locale); |
|
return this.extensionManager.refreshBlocks(); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
getLocale () { |
|
return formatMessage.setup().locale; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
blockListener (e) { |
|
if (this.editingTarget) { |
|
this.editingTarget.blocks.blocklyListen(e); |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
flyoutBlockListener (e) { |
|
this.runtime.flyoutBlocks.blocklyListen(e); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
monitorBlockListener (e) { |
|
|
|
|
|
if (['create', 'change'].indexOf(e.type) !== -1) { |
|
this.runtime.monitorBlocks.blocklyListen(e); |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
variableListener (e) { |
|
|
|
|
|
if (['var_create', 'var_rename', 'var_delete'].indexOf(e.type) !== -1) { |
|
this.runtime.getTargetForStage().blocks.blocklyListen(e); |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
setEditingTarget (targetId) { |
|
|
|
if (this.editingTarget && targetId === this.editingTarget.id) { |
|
return; |
|
} |
|
const target = this.runtime.getTargetById(targetId); |
|
if (target) { |
|
this.editingTarget = target; |
|
|
|
this.emitTargetsUpdate(false ); |
|
this.emitWorkspaceUpdate(); |
|
this.runtime.setEditingTarget(target); |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
exportStandaloneBlocks (blockObjects) { |
|
const sb3 = require('./serialization/sb3'); |
|
const serialized = sb3.serializeStandaloneBlocks(blockObjects, this.runtime); |
|
return serialized; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
shareBlocksToTarget (blocks, targetId, optFromTargetId) { |
|
const sb3 = require('./serialization/sb3'); |
|
|
|
const {blocks: copiedBlocks, extensionURLs} = sb3.deserializeStandaloneBlocks(blocks); |
|
newBlockIds(copiedBlocks); |
|
const target = this.runtime.getTargetById(targetId); |
|
|
|
if (optFromTargetId) { |
|
|
|
|
|
const fromTarget = this.runtime.getTargetById(optFromTargetId); |
|
fromTarget.resolveVariableSharingConflictsWithTarget(copiedBlocks, target); |
|
} |
|
|
|
|
|
const extensionIDs = new Set(copiedBlocks |
|
.map(b => sb3.getExtensionIdForOpcode(b.opcode)) |
|
.filter(id => !!id) |
|
.filter(id => !this.extensionManager.isExtensionLoaded(id)) |
|
); |
|
|
|
return this._loadExtensions(extensionIDs, extensionURLs).then(() => { |
|
copiedBlocks.forEach(block => { |
|
target.blocks.createBlock(block); |
|
}); |
|
target.blocks.updateTargetSpecificBlocks(target.isStage); |
|
}); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
|
); |
|
} |
|
}); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
shareSoundToTarget (soundIndex, targetId) { |
|
const originalSound = this.editingTarget.getSounds()[soundIndex]; |
|
const clone = Object.assign({}, originalSound); |
|
const target = this.runtime.getTargetById(targetId); |
|
return loadSound(clone, this.runtime, target.sprite.soundBank).then(() => { |
|
if (target) { |
|
target.addSound(clone); |
|
this.emitTargetsUpdate(); |
|
} |
|
}); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
refreshWorkspace () { |
|
if (this.editingTarget) { |
|
this.emitWorkspaceUpdate(); |
|
this.runtime.setEditingTarget(this.editingTarget); |
|
this.emitTargetsUpdate(false ); |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
emitTargetsUpdate (triggerProjectChange) { |
|
if (typeof triggerProjectChange === 'undefined') triggerProjectChange = true; |
|
let lazyTargetList; |
|
const getTargetListLazily = () => { |
|
if (!lazyTargetList) { |
|
lazyTargetList = this.runtime.targets |
|
.filter( |
|
|
|
target => !target.hasOwnProperty('isOriginal') || target.isOriginal |
|
).map( |
|
target => target.toJSON() |
|
); |
|
} |
|
return lazyTargetList; |
|
}; |
|
this.emit('targetsUpdate', { |
|
|
|
get targetList () { |
|
return getTargetListLazily(); |
|
}, |
|
|
|
editingTarget: this.editingTarget ? this.editingTarget.id : null |
|
}); |
|
if (triggerProjectChange) { |
|
this.runtime.emitProjectChanged(); |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
emitWorkspaceUpdate () { |
|
|
|
const stageVariables = this.runtime.getTargetForStage().variables; |
|
let messageIds = []; |
|
for (const varId in stageVariables) { |
|
if (stageVariables[varId].type === Variable.BROADCAST_MESSAGE_TYPE) { |
|
messageIds.push(varId); |
|
} |
|
} |
|
|
|
|
|
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)); |
|
} |
|
} |
|
} |
|
} |
|
|
|
for (let i = 0; i < messageIds.length; i++) { |
|
const id = messageIds[i]; |
|
delete this.runtime.getTargetForStage().variables[id]; |
|
} |
|
const globalVarMap = Object.assign({}, this.runtime.getTargetForStage().variables); |
|
const localVarMap = this.editingTarget.isStage ? |
|
Object.create(null) : |
|
Object.assign({}, this.editingTarget.variables); |
|
|
|
const globalVariables = Object.keys(globalVarMap).map(k => globalVarMap[k]); |
|
const localVariables = Object.keys(localVarMap).map(k => localVarMap[k]); |
|
const workspaceComments = Object.keys(this.editingTarget.comments) |
|
.map(k => this.editingTarget.comments[k]) |
|
.filter(c => c.blockId === null); |
|
|
|
const xmlString = `<xml xmlns="http://www.w3.org/1999/xhtml"> |
|
<variables> |
|
${globalVariables.map(v => v.toXML()).join()} |
|
${localVariables.map(v => v.toXML(true)).join()} |
|
</variables> |
|
${workspaceComments.map(c => c.toXML()).join()} |
|
${this.editingTarget.blocks.toXML(this.editingTarget.comments)} |
|
</xml>`; |
|
|
|
this.emit('workspaceUpdate', {xml: xmlString}); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
getTargetIdForDrawableId (drawableId) { |
|
const target = this.runtime.getTargetByDrawableId(drawableId); |
|
if (target && target.hasOwnProperty('id') && target.hasOwnProperty('isStage') && !target.isStage) { |
|
return target.id; |
|
} |
|
return null; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
reorderTarget (targetIndex, newIndex) { |
|
let targets = this.runtime.targets; |
|
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]; |
|
targets = targets.slice(0, targetIndex).concat(targets.slice(targetIndex + 1)); |
|
targets.splice(newIndex, 0, target); |
|
this.runtime.targets = targets; |
|
this.emitTargetsUpdate(); |
|
return true; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
reorderCostume (targetId, costumeIndex, newIndex) { |
|
const target = this.runtime.getTargetById(targetId); |
|
if (target) { |
|
const reorderSuccessful = target.reorderCostume(costumeIndex, newIndex); |
|
if (reorderSuccessful) { |
|
this.runtime.emitProjectChanged(); |
|
} |
|
return reorderSuccessful; |
|
} |
|
return false; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
reorderSound (targetId, soundIndex, newIndex) { |
|
const target = this.runtime.getTargetById(targetId); |
|
if (target) { |
|
const reorderSuccessful = target.reorderSound(soundIndex, newIndex); |
|
if (reorderSuccessful) { |
|
this.runtime.emitProjectChanged(); |
|
} |
|
return reorderSuccessful; |
|
} |
|
return false; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
startDrag (targetId) { |
|
const target = this.runtime.getTargetById(targetId); |
|
if (target) { |
|
this._dragTarget = target; |
|
target.startDrag(); |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
stopDrag (targetId) { |
|
const target = this.runtime.getTargetById(targetId); |
|
if (target) { |
|
this._dragTarget = null; |
|
target.stopDrag(); |
|
this.setEditingTarget(target.sprite && target.sprite.clones[0] ? |
|
target.sprite.clones[0].id : target.id); |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
postSpriteInfo (data) { |
|
if (this._dragTarget) { |
|
this._dragTarget.postSpriteInfo(data); |
|
} else { |
|
this.editingTarget.postSpriteInfo(data); |
|
} |
|
|
|
|
|
|
|
|
|
this.runtime.emitProjectChanged(); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
setVariableValue (targetId, variableId, value) { |
|
const target = this.runtime.getTargetById(targetId); |
|
if (target) { |
|
const variable = target.lookupVariableById(variableId); |
|
if (variable) { |
|
variable.value = value; |
|
|
|
if (variable.isCloud) { |
|
this.runtime.ioDevices.cloud.requestUpdateVariable(variable.name, variable.value); |
|
} |
|
|
|
return true; |
|
} |
|
} |
|
return false; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
getVariableValue (targetId, variableId) { |
|
const target = this.runtime.getTargetById(targetId); |
|
if (target) { |
|
const variable = target.lookupVariableById(variableId); |
|
if (variable) { |
|
return variable.value; |
|
} |
|
} |
|
return null; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
configureScratchLinkSocketFactory (factory) { |
|
this.runtime.configureScratchLinkSocketFactory(factory); |
|
} |
|
} |
|
|
|
module.exports = VirtualMachine; |
|
|