Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/engine/runtime-events.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,10 @@ const RuntimeEvents = {
*/
BEFORE_EXECUTE: 'BEFORE_EXECUTE',

RUNTIME_PAUSED: 'RUNTIME_PAUSED',

RUNTIME_UNPAUSED: 'RUNTIME_UNPAUSED',

/**
* Event called after every block in the project has been executed.
*/
Expand Down
91 changes: 86 additions & 5 deletions src/engine/runtime.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,22 @@ const defaultBlockPackages = {
scratch3_assets: require('../blocks/scratch3_assets')
};

const withListener = (listeners, listener) => (listeners === null ? [listener] : listeners.concat(listener));

const withoutListener = (listeners, listener) => {
const index = listeners === null ? -1 : listeners.indexOf(listener);
if (index === -1) return listeners;
if (listeners.length === 1) return null;
return listeners.slice(0, index).concat(listeners.slice(index + 1));
};

const callListeners = listeners => {
for (let i = 0; i < listeners.length; i++) {
listeners[i]();
}
};

const ThreadPause = require('./thread-pause');
const interpolate = require('./tw-interpolate');
const FrameLoop = require('./tw-frame-loop');
const MonitorRecord = require('./monitor-record.js');
Expand Down Expand Up @@ -172,6 +188,12 @@ class Runtime extends EventEmitter {

this._threadsKilled = false;

this._beforeStepListeners = null;
this._afterStepListeners = null;

this._paused = false;
this._pausedThreads = null;

/**
* Live monitor threads by the block that started them. Saves a scan of every
* thread for every monitored block, on every frame.
Expand Down Expand Up @@ -1531,6 +1553,10 @@ class Runtime extends EventEmitter {
const newThreads = [];
// Look up metadata for the relevant hat.
const hatMeta = instance._hats[requestedHatOpcode];
if (this._paused && !hatMeta.edgeActivated && requestedHatOpcode !== 'event_whenbroadcastreceived' &&
requestedHatOpcode !== 'control_start_as_clone') {
return newThreads;
}

let matchFields = null;
if (optMatchFields) {
Expand Down Expand Up @@ -1861,6 +1887,40 @@ class Runtime extends EventEmitter {
this._monitorThreads.clear();

this.resetRunId();
this.setPaused(false);
}

isPaused () {
return this._paused;
}

setPaused (paused) {
paused = !!paused;
if (paused === this._paused) return;
this._paused = paused;
const clock = this.ioDevices.clock;
if (paused) {
if (!clock._paused) clock.pause();
this._pausedThreads = new Map();
for (let i = 0; i < this.threads.length; i++) {
this.pauseThread(this.threads[i]);
}
this.emit(Runtime.RUNTIME_PAUSED);
} else {
if (clock._paused) clock.resume();
const pausedThreads = this._pausedThreads;
this._pausedThreads = null;
ThreadPause.releaseThreads(pausedThreads, this.threads, this.currentMSecs);
this.emit(Runtime.RUNTIME_UNPAUSED);
}
}

pauseThread (thread) {
if (this._pausedThreads !== null) ThreadPause.holdThread(this._pausedThreads, thread, this.currentMSecs);
}

getPausedThreadState (thread) {
return this._pausedThreads === null ? null : this._pausedThreads.get(thread) || null;
}

_renderInterpolatedPositions () {
Expand Down Expand Up @@ -1912,6 +1972,7 @@ class Runtime extends EventEmitter {
*/
_step () {
if (this.sampler.enableBasic) this.sampler.pc[0] = Sampler.RUNTIME;
if (this._beforeStepListeners !== null) callListeners(this._beforeStepListeners);

if (this.interpolationEnabled) {
interpolate.setupInitialState(this);
Expand Down Expand Up @@ -1946,11 +2007,13 @@ class Runtime extends EventEmitter {
}

// Find all edge-activated hats, and add them to threads to be evaluated.
for (const hatType in this._hats) {
if (!Object.prototype.hasOwnProperty.call(this._hats, hatType)) continue;
const hat = this._hats[hatType];
if (hat.edgeActivated) {
this.startHats(hatType);
if (!this._paused) {
for (const hatType in this._hats) {
if (!Object.prototype.hasOwnProperty.call(this._hats, hatType)) continue;
const hat = this._hats[hatType];
if (hat.edgeActivated) {
this.startHats(hatType);
}
}
}
this.redrawRequested = false;
Expand All @@ -1961,6 +2024,7 @@ class Runtime extends EventEmitter {
}
this.profiler.start(stepThreadsProfilerId);
}
if (this._pausedThreads !== null) ThreadPause.keepThreadsHeld(this._pausedThreads, this.threads);
this.emit(Runtime.BEFORE_EXECUTE);
const doneThreads = this.sequencer.stepThreads();
if (this.profiler !== null) {
Expand Down Expand Up @@ -1998,9 +2062,25 @@ class Runtime extends EventEmitter {
this.profiler.reportFrames();
}

if (this._afterStepListeners !== null) callListeners(this._afterStepListeners);
if (this.sampler.enableBasic) this.sampler.pc[0] = Sampler.IDLE;
}

addStepListener ({before, after}) {
if (typeof before !== 'function' && typeof after !== 'function') {
throw new TypeError('A step listener needs a before or after function');
}
if (typeof before === 'function') this._beforeStepListeners = withListener(this._beforeStepListeners, before);
if (typeof after === 'function') this._afterStepListeners = withListener(this._afterStepListeners, after);
let removed = false;
return () => {
if (removed) return;
removed = true;
this._beforeStepListeners = withoutListener(this._beforeStepListeners, before);
this._afterStepListeners = withoutListener(this._afterStepListeners, after);
};
}

/**
* Get the number of threads in the given array that are monitor threads (threads
* that update monitor values, and don't count as running a script).
Expand All @@ -2012,6 +2092,7 @@ class Runtime extends EventEmitter {
for (let i = 0; i < threads.length; i++) {
if (threads[i].updateMonitor) count++;
}
if (this._pausedThreads !== null) count += ThreadPause.countHeldThreads(this._pausedThreads, threads);
return count;
}

Expand Down
50 changes: 50 additions & 0 deletions src/engine/thread-pause.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
const Thread = require('./thread');

const shiftTimer = (timer, elapsed) => {
if (timer) timer.startTime += elapsed;
};

const holdThread = (pausedThreads, thread, now) => {
if (thread.updateMonitor || pausedThreads.has(thread)) return;
pausedThreads.set(thread, {status: thread.status, time: now});
thread.status = Thread.STATUS_PROMISE_WAIT;
};

const keepThreadsHeld = (pausedThreads, threads) => {
for (let i = 0; i < threads.length; i++) {
const thread = threads[i];
const state = pausedThreads.get(thread);
if (!state || thread.status === Thread.STATUS_DONE || thread.status === Thread.STATUS_PROMISE_WAIT) continue;
state.status = thread.status;
thread.status = Thread.STATUS_PROMISE_WAIT;
}
};

const releaseThreads = (pausedThreads, threads, now) => {
for (let i = 0; i < threads.length; i++) {
const thread = threads[i];
const state = pausedThreads.get(thread);
if (!state || thread.status === Thread.STATUS_DONE) continue;
const elapsed = now - state.time;
shiftTimer(thread.timer, elapsed);
if (thread.compatibilityStackFrame) shiftTimer(thread.compatibilityStackFrame.timer, elapsed);
const stackFrame = thread.peekStackFrame();
if (stackFrame && stackFrame.executionContext) shiftTimer(stackFrame.executionContext.timer, elapsed);
if (thread.status === Thread.STATUS_PROMISE_WAIT) thread.status = state.status;
}
};

const countHeldThreads = (pausedThreads, threads) => {
let count = 0;
for (let i = 0; i < threads.length; i++) {
if (pausedThreads.has(threads[i])) count++;
}
return count;
};

module.exports = {
holdThread,
keepThreadsHeld,
releaseThreads,
countHeldThreads
};
91 changes: 90 additions & 1 deletion src/virtual-machine.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ const {replaceTargetScripts} = require('./engine/replace-target-scripts');

const RESERVED_NAMES = ['_mouse_', '_stage_', '_edge_', '_myself_', '_random_'];

const RESERVED_METADATA_KEYS = ['semver', 'vm', 'origin', 'platform'];

if (typeof document === 'undefined') {
global.document = {
createElement: tagName => {
Expand Down Expand Up @@ -210,6 +212,12 @@ class VirtualMachine extends EventEmitter {
this.runtime.on(Runtime.RUNTIME_STOPPED, () => {
this.emit(Runtime.RUNTIME_STOPPED);
});
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.HAS_CLOUD_DATA_UPDATE, hasCloudData => {
this.emit(Runtime.HAS_CLOUD_DATA_UPDATE, hasCloudData);
});
Expand Down Expand Up @@ -241,6 +249,9 @@ class VirtualMachine extends EventEmitter {
this.emit(Runtime.TURBO_MODE_ON);
});

this._loadProjectInterceptors = [];
this._projectMetadata = new Map();

this.extensionManager = new ExtensionManager(this);
this.securityManager = this.extensionManager.securityManager;
this.runtime.extensionManager = this.extensionManager;
Expand Down Expand Up @@ -389,6 +400,14 @@ class VirtualMachine extends EventEmitter {
this.runtime.setStageSize(width, height);
}

setPaused (paused) {
this.runtime.setPaused(paused);
}

isPaused () {
return this.runtime.isPaused();
}

setProjectName (name) {
this.runtime.setProjectName(name);
}
Expand Down Expand Up @@ -569,6 +588,34 @@ class VirtualMachine extends EventEmitter {
* @return {!Promise} Promise that resolves after targets are installed.
*/
loadProject (input, options = {}) {
if (this._loadProjectInterceptors.length === 0) return this._loadProjectDirectly(input, options);
const interceptors = this._loadProjectInterceptors.slice();
const run = (index, currentInput, currentOptions) => {
if (index < 0) return this._loadProjectDirectly(currentInput, currentOptions);
const next = (nextInput = currentInput, nextOptions = currentOptions) =>
run(index - 1, nextInput, nextOptions);
try {
return Promise.resolve(interceptors[index](currentInput, currentOptions, next));
} catch (error) {
return Promise.reject(error);
}
};
return run(interceptors.length - 1, input, options);
}

addLoadProjectInterceptor (interceptor) {
if (typeof interceptor !== 'function') throw new TypeError('A load project interceptor must be a function');
this._loadProjectInterceptors.push(interceptor);
let removed = false;
return () => {
if (removed) return;
removed = true;
const index = this._loadProjectInterceptors.indexOf(interceptor);
if (index !== -1) this._loadProjectInterceptors.splice(index, 1);
};
}

_loadProjectDirectly (input, options = {}) {
const generation = (this._projectLoadGeneration || 0) + 1;
this._projectLoadGeneration = generation;
const active = () => this._projectLoadGeneration === generation &&
Expand Down Expand Up @@ -851,7 +898,48 @@ class VirtualMachine extends EventEmitter {
*/
toJSON (optTargetId, serializationOptions) {
const sb3 = require('./serialization/sb3');
return StringUtil.stringify(sb3.serialize(this.runtime, optTargetId, serializationOptions));
const json = sb3.serialize(this.runtime, optTargetId, serializationOptions);
if (!optTargetId && this._projectMetadata.size !== 0) this._serializeProjectMetadata(json.meta);
return StringUtil.stringify(json);
}

registerProjectMetadata (key, {serialize, deserialize}) {
if (typeof key !== 'string' || key === '' || RESERVED_METADATA_KEYS.includes(key)) {
throw new TypeError(`Project metadata cannot use the key ${key}`);
}
if (this._projectMetadata.has(key)) throw new Error(`Project metadata ${key} is already registered`);
const handler = {
serialize: typeof serialize === 'function' ? serialize : null,
deserialize: typeof deserialize === 'function' ? deserialize : null
};
this._projectMetadata.set(key, handler);
return () => {
if (this._projectMetadata.get(key) === handler) this._projectMetadata.delete(key);
};
}

_serializeProjectMetadata (meta) {
for (const [key, handler] of this._projectMetadata) {
if (!handler.serialize) continue;
try {
const value = handler.serialize(meta[key]);
if (typeof value !== 'undefined') meta[key] = value;
} catch (error) {
log.error(`Could not save project metadata ${key}`, error);
}
}
}

_deserializeProjectMetadata (meta) {
const loaded = meta !== null && typeof meta === 'object' ? meta : {};
for (const [key, handler] of this._projectMetadata) {
if (!handler.deserialize) continue;
try {
handler.deserialize(Object.prototype.hasOwnProperty.call(loaded, key) ? loaded[key] : void 0);
} catch (error) {
log.error(`Could not load project metadata ${key}`, error);
}
}
}

// TODO do we still need this function? Keeping it here so as not to introduce
Expand Down Expand Up @@ -883,6 +971,7 @@ class VirtualMachine extends EventEmitter {
* @returns {Promise} Promise that resolves after the project has loaded
*/
deserializeProject (projectJSON, zip, active = () => true) {
if (this._projectMetadata.size !== 0) this._deserializeProjectMetadata(projectJSON && projectJSON.meta);
// Clear the current runtime
this.clear();

Expand Down
Loading