GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — DinosaurMod-Vm/src/virtual-machine.js at develop · Dinosaurmod/DinosaurMod-Vm Expand file tree/ Copy pathvirtual-machine.jsMore file actions 2144 lines (1974 loc) · 85.7 KB / Copy pathvirtual-machine.jsFile metadata and controls2144 lines (1974 loc) · 85.7 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 let _TextEncoder; if (typeof TextEncoder === 'undefined') { _TextEncoder = require('text-encoding').TextEncoder; } else { /* global TextEncoder */ _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 = [ // 'motion', // 'looks', // 'sound', // 'events', // 'control', // 'sensing', // 'operators', // 'variables', // 'myBlocks' ]; // Disable missing translation warnings in console 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; }; /** * Handles connections between blocks, stage, and extensions. * @constructor */ class VirtualMachine extends EventEmitter { constructor () { super(); /** * VM runtime, to store blocks, I/O devices, sprites/targets, etc. * @type {!Runtime} */ this.runtime = new Runtime(); centralDispatch.setService('runtime', createRuntimeService(this.runtime)).catch(e => { log.error(`Failed to register runtime service: ${JSON.stringify(e)}`); }); /** * The "currently editing"/selected target ID for the VM. * Block events from any Blockly workspace are routed to this target. * @type {Target} */ this.editingTarget = null; /** * The currently dragging target, for redirecting IO data. * @type {Target} */ this._dragTarget = null; // Runtime emits are passed along as VM emits. 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; // Load core extensions 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(); }); /** * Export some internal classes for extensions. */ 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 }; /** * For comptatibility with TurboWarp's * i_will_not_ask_for_help_when_these_break export. */ 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 running the VM - do this before anything else. */ start () { this.runtime.start(); } /** * tw: Stop running the VM * Note: This only stops the loop. It will not stop any threads the next time the VM starts */ stop () { this.runtime.stop(); } /** * "Green flag" handler - start all threads starting with a green flag. */ greenFlag () { this.runtime.greenFlag(); } /** * 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; if (this.runtime.turboMode) { this.emit(Runtime.TURBO_MODE_ON); } else { this.emit(Runtime.TURBO_MODE_OFF); } } /** * 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); } 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'; } /** * Stop all threads and running activities. */ stopAll () { this.runtime.stopAll(); } /** * Clear out current running project data. */ clear () { this.runtime.dispose(); this.editingTarget = null; this.emitTargetsUpdate(false /* Don't emit project change */); } /** * 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' || key === 'blockContainer') return; return value; }, 2); this.emit('playgroundData', { blocks: this.editingTarget.blocks, threads: filteredThreadData }); } /** * 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); } } setVideoProvider (videoProvider) { this.runtime.ioDevices.video.setProvider(videoProvider); } setCloudProvider (cloudProvider) { this.runtime.ioDevices.cloud.setProvider(cloudProvider); } /** * Tell the specified extension to scan for a peripheral. * @param {string} extensionId - the id of the extension. */ scanForPeripheral (extensionId) { this.runtime.scanForPeripheral(extensionId); } /** * 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); } /** * Disconnect from the extension's connected peripheral. * @param {string} extensionId - the id of the extension. */ disconnectPeripheral (extensionId) { this.runtime.disconnectPeripheral(extensionId); } /** * 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. */ getPeripheralIsConnected (extensionId) { return this.runtime.getPeripheralIsConnected(extensionId); } isSB2(json) { return Array.isArray(json.children) && !Array.isArray(json.targets); } /** * Load a Scratch project from a .sb, .sb2, .sb3 or json string. * @param {string | object} input A json string, object, or ArrayBuffer representing the project to load. * @return {!Promise} Promise that resolves after targets are installed. */ loadProject (input) { this.emit('DESERIALIZE', 'project'); 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); // generic objects return [object Object] on stringify if (input.toString() === '[object Object]') { input.projectVersion = this.isSB2(input) ? 2 : 3; return resolve([input, null]); } if (tag.slice(0, 2) !== 'PK') { // if it isnt a zip, maby its the project.json in ArrayBuffer form const decoder = new TextDecoder('UTF-8'); input = decoder.decode(input); if (typeof input === 'string') input = JSON.parse(input); // generic objects return [object Object] on stringify 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); // Intentionally rejecting here (want errors to be handled by caller) if (error.hasOwnProperty('validationError')) { return Promise.reject(JSON.stringify(error, null, 4)); } return Promise.reject(error); }); } /** * 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) { 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(); /** * @param {boolean?} beautiful If the json should be beautified or not * @returns {JSZip} JSZip zip object representing the sb3. */ _saveProjectZip (beautiful) { const projectJson = this.toJSON(null, {}, beautiful); // TODO want to eventually move zip creation out of here, and perhaps // into scratch-storage const zip = new JSZip(); // Put everything in a zip file zip.file('project.json', projectJson); this._addFileDescsToZip(this.serializeAssets(), zip); // extra assets implementation 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) } } // Use a fixed modification date for the files in the zip instead of letting JSZip use the // current time to avoid a very small metadata leak and make zipping deterministic. The magic // number is from the first TurboWarp/scratch-vm commit after forking const date = new Date(1591657163000); for (const file of Object.values(zip.files)) { file.date = date; } // Tell JSZip to only compress file formats where there will be a significant gain. 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; } /** * @param {JSZip.OutputType} [type] JSZip output type. Defaults to 'blob' for Scratch compatibility. * @returns {Promise<unknown>} Compressed sb3 file in a type determined by the type argument. */ saveProjectSb3 (type) { return this._saveProjectZip().generateAsync({ type: type || 'blob', mimeType: 'application/x.scratch.sb3', compression: 'DEFLATE' }); } /** * @param {JSZip.OutputType} [type] JSZip output type. Defaults to 'arraybuffer'. * @returns {StreamHelper} JSZip StreamHelper object generating the compressed sb3. * See: https://stuk.github.io/jszip/documentation/api_streamhelper.html */ saveProjectSb3Stream (type) { return this._saveProjectZip().generateInternalStream({ type: type || 'arraybuffer', mimeType: 'application/x.scratch.sb3', compression: 'DEFLATE' }); } /** * tw: Serialize the project into a map of files without actually zipping the project. * The buffers returned are the exact same ones used internally, not copies. Avoid directly * manipulating them (except project.json, which is created by this function). * @returns {Record<string, Uint8Array>} Map of file name to the raw data for that file. */ 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; } /** * @type {Array<object>} Array of all assets currently in the runtime */ 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 ]; } /** * @param {string} targetId Optional ID of target to export * @returns {Array<{fileName: string; fileContent: Uint8Array;}} list of file descs */ 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); } } /** * 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) { 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 } }); } /** * Export project or sprite as a Scratch 3.0 JSON representation. * @param {string=} optTargetId - Optional id of a sprite to serialize * @param {*} serializationOptions Options to pass to the serializer * @return {string} Serialized state of the runtime. */ toJSON (optTargetId, serializationOptions, beautiful) { this.emit('SERIALIZE', optTargetId); const sb3 = require('./serialization/sb3'); return StringUtil.stringify(sb3.serialize(this.runtime, optTargetId, serializationOptions), beautiful); } // TODO do we still need this function? Keeping it here so as not to introduce // a breaking change. /** * Load a project from a Scratch JSON representation. * @param {string} json JSON string representing a project. * @returns {Promise} Promise that resolves after the project has loaded */ fromJSON (json) { log.warning('fromJSON is now just a wrapper around loadProject, please use that function instead.'); return this.loadProject(json); } /** * Load a project from a Scratch JSON representation. * @param {string} projectJSON JSON string representing a project. * @param {?JSZip} zip Optional zipped project containing assets to be loaded. * @returns {Promise} Promise that resolves after the project has loaded */ deserializeProject (projectJSON, zip) { // Clear the current runtime 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'); // eslint-disable-next-line no-invalid-this 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) { // performance.measure() will throw an error if the start deserialize // marker was removed from memory before we finished deserializing // the project. We've seen this happen a couple times when loading // very large projects. log.error(e); } } return this.installTargets(targets, extensions, true); }); } /** * @param {string[]} extensionIDs The IDs of the extensions * @param {Map<string, string>} extensionURLs A map of extension ID to URL */ async _loadExtensions (extensionIDs, extensionURLs = new Map()) { const defaultExtensionURLs = require('./extension-support/tw-default-extension-urls'); const extensionPromises = []; for (const extensionID of extensionIDs) { let url = extensionURLs.get(extensionID); if (!url && Object.prototype.hasOwnProperty.call(defaultExtensionURLs, extensionID)) { url = defaultExtensionURLs[extensionID]; } if (this.extensionManager.isExtensionLoaded(extensionID)) { // Already loaded } else if (url) { // extension 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)) { // Builtin extension this.extensionManager.loadExtensionIdSync(extensionID); } else { throw new Error(`Unknown extension: ${extensionID}`); } } return Promise.all(extensionPromises); } /** * 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. * @returns {Promise} resolved once targets have been installed */ 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); (/** @type RenderedTarget */ target).updateAllDrawableProperties(); // Ensure unique sprite name 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"] }); // Sort the executable targets by layerOrder. // Remove layerOrder property after use. this.runtime.executableTargets.sort((a, b) => a.layerOrder - b.layerOrder); targets.forEach(target => { delete target.layerOrder; }); // Select the first target for editing, e.g., the first sprite. if (wholeProject && (targets.length > 1)) { this.editingTarget = targets[1]; } else { this.editingTarget = targets[0]; } if (!wholeProject) { this.editingTarget.fixUpVariableReferences(); } if (wholeProject) { this.runtime.parseProjectOptions(); } // Update the VM user's knowledge of targets and blocks on the workspace. this.emitTargetsUpdate(false /* Don't emit project change */); this.emitWorkspaceUpdate(); this.runtime.setEditingTarget(this.editingTarget); this.runtime.ioDevices.cloud.setStage(this.runtime.getTargetForStage()); }); } /** * 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) { const errorPrefix = 'Sprite Upload Error:'; 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) => { const validate = require('scratch-parser'); // The second argument of true below indicates to the parser/validator // the given input should be treated as a single sprite and not // an entire project 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 => { // Intentionally rejecting here (want errors to be handled by caller) if (error.hasOwnProperty('validationError')) { return Promise.reject(JSON.stringify(error)); } return Promise.reject(`${errorPrefix} ${error}`); }); } /** * Add a single sprite from the "Sprite2" (i.e., SB2 sprite) format. * @param {object} sprite Object representing 2.0 sprite to be added. * @param {?ArrayBuffer} zip Optional zip of assets being referenced by json * @returns {Promise} Promise that resolves after the sprite is added */ _addSprite2 (sprite, zip) { // Validate & parse const sb2 = require('./serialization/sb2'); return sb2.deserialize(sprite, this.runtime, true, zip) .then(({targets, extensions}) => this.installTargets(targets, extensions, false)); } /** * Add a single sb3 sprite. * @param {object} sprite Object rperesenting 3.0 sprite to be added. * @param {?ArrayBuffer} zip Optional zip of assets being referenced by target json * @returns {Promise} Promise that resolves after the sprite is added */ _addSprite3 (sprite, zip) { // Validate & parse const sb3 = require('./serialization/sb3'); return sb3 .deserialize(sprite, this.runtime, zip, true) .then(({targets, extensions}) => this.installTargets(targets, extensions, false)); } /** * Add a costume to the current editing target. |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |