|
const EventEmitter = require('events'); |
|
const {OrderedMap} = require('immutable'); |
|
const ExtendedJSON = require('@turbowarp/json'); |
|
|
|
const ArgumentType = require('../extension-support/argument-type'); |
|
const Blocks = require('./blocks'); |
|
const BlocksRuntimeCache = require('./blocks-runtime-cache'); |
|
const BlockType = require('../extension-support/block-type'); |
|
const BlockShape = require('../extension-support/block-shape'); |
|
const Profiler = require('./profiler'); |
|
const Sequencer = require('./sequencer'); |
|
const execute = require('./execute.js'); |
|
const compilerExecute = require('../compiler/jsexecute'); |
|
const ScratchBlocksConstants = require('./scratch-blocks-constants'); |
|
const TargetType = require('../extension-support/target-type'); |
|
const Thread = require('./thread'); |
|
const log = require('../util/log'); |
|
const maybeFormatMessage = require('../util/maybe-format-message'); |
|
const StageLayering = require('./stage-layering'); |
|
const Variable = require('./variable'); |
|
const xmlEscape = require('../util/xml-escape'); |
|
const ScratchLinkWebSocket = require('../util/scratch-link-websocket'); |
|
const FontManager = require('./tw-font-manager'); |
|
const { validateJSON } = require('../util/json-block-utilities'); |
|
const Color = require('../util/color'); |
|
const TabManager = require('../extension-support/pm-tab-manager'); |
|
const ModalManager = require('../extension-support/pm-modal-manager'); |
|
const MathUtil = require('../util/math-util'); |
|
const Cast = require('../util/cast'); |
|
const ExtensionStorage = require('../util/deprecated-extension-storage.js'); |
|
|
|
|
|
const Clock = require('../io/clock'); |
|
const Cloud = require('../io/cloud'); |
|
const Keyboard = require('../io/keyboard'); |
|
const Mouse = require('../io/mouse'); |
|
const MouseWheel = require('../io/mouseWheel'); |
|
const UserData = require('../io/userData'); |
|
const Video = require('../io/video'); |
|
const Touch = require('../io/touch'); |
|
|
|
const StringUtil = require('../util/string-util'); |
|
const uid = require('../util/uid'); |
|
|
|
const coreVariableTypes = [ |
|
Variable.SCALAR_TYPE, |
|
Variable.LIST_TYPE, |
|
Variable.BROADCAST_MESSAGE_TYPE |
|
]; |
|
const defaultBlockPackages = { |
|
scratch3_control: require('../blocks/scratch3_control'), |
|
scratch3_event: require('../blocks/scratch3_event'), |
|
scratch3_looks: require('../blocks/scratch3_looks'), |
|
scratch3_motion: require('../blocks/scratch3_motion'), |
|
scratch3_operators: require('../blocks/scratch3_operators'), |
|
scratch3_sound: require('../blocks/scratch3_sound'), |
|
scratch3_sensing: require('../blocks/scratch3_sensing'), |
|
scratch3_data: require('../blocks/scratch3_data'), |
|
scratch3_procedures: require('../blocks/scratch3_procedures'), |
|
pm_liveTests: require('../blocks/pm_live tests') |
|
}; |
|
|
|
const interpolate = require('./tw-interpolate'); |
|
const FrameLoop = require('./tw-frame-loop'); |
|
|
|
const defaultExtensionColors = ['#0FBD8C', '#0DA57A', '#0B8E69']; |
|
|
|
const COMMENT_CONFIG_MAGIC = ' // _twconfig_'; |
|
|
|
|
|
|
|
|
|
|
|
const ArgumentTypeMap = (() => { |
|
const map = {}; |
|
map[ArgumentType.ANGLE] = { |
|
shadow: { |
|
type: 'math_angle', |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
fieldName: 'NUM' |
|
} |
|
}; |
|
map[ArgumentType.COLOR] = { |
|
shadow: { |
|
type: 'colour_picker', |
|
fieldName: 'COLOUR' |
|
} |
|
}; |
|
map[ArgumentType.NUMBER] = { |
|
shadow: { |
|
type: 'math_number', |
|
fieldName: 'NUM' |
|
} |
|
}; |
|
map[ArgumentType.STRING] = { |
|
shadow: { |
|
type: 'text', |
|
fieldName: 'TEXT' |
|
} |
|
}; |
|
map[ArgumentType.BOOLEAN] = { |
|
check: 'Boolean', |
|
shadow: { |
|
type: 'checkbox', |
|
fieldName: 'CHECKBOX' |
|
} |
|
}; |
|
map[ArgumentType.MATRIX] = { |
|
shadow: { |
|
type: 'matrix', |
|
fieldName: 'MATRIX' |
|
} |
|
}; |
|
map[ArgumentType.NOTE] = { |
|
shadow: { |
|
type: 'note', |
|
fieldName: 'NOTE' |
|
} |
|
}; |
|
map[ArgumentType.IMAGE] = { |
|
|
|
|
|
fieldType: 'field_image' |
|
}; |
|
map[ArgumentType.POLYGON] = { |
|
check: 'math_polygon', |
|
shadow: { |
|
type: 'polygon' |
|
} |
|
}; |
|
map[ArgumentType.CUSTOM] = { |
|
fieldType: 'field_customInput' |
|
}; |
|
map[ArgumentType.COSTUME] = { |
|
shadow: { |
|
type: 'looks_costume', |
|
fieldName: 'COSTUME' |
|
} |
|
}; |
|
map[ArgumentType.SOUND] = { |
|
shadow: { |
|
type: 'sound_sounds_menu', |
|
fieldName: 'SOUND_MENU' |
|
} |
|
}; |
|
|
|
|
|
map[ArgumentType.VARIABLE] = { |
|
fieldType: "field_variable", |
|
fieldName: "VARIABLE" |
|
}; |
|
map[ArgumentType.LIST] = { |
|
fieldType: "field_variable", |
|
fieldName: "LIST", |
|
variableType: 'list' |
|
}; |
|
map[ArgumentType.BROADCAST] = { |
|
fieldType: "field_variable", |
|
fieldName: "BROADCAST", |
|
variableType: 'broadcast_msg' |
|
}; |
|
map[ArgumentType.SEPERATOR] = { |
|
fieldType: 'field_vertical_separator' |
|
}; |
|
|
|
return map; |
|
})(); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
const cloudDataManager = cloudOptions => { |
|
let count = 0; |
|
|
|
const canAddCloudVariable = () => count < cloudOptions.limit; |
|
|
|
const addCloudVariable = () => { |
|
count++; |
|
}; |
|
|
|
const removeCloudVariable = () => { |
|
count--; |
|
}; |
|
|
|
const hasCloudVariables = () => count > 0; |
|
|
|
const getNumberOfCloudVariables = () => count; |
|
|
|
return { |
|
canAddCloudVariable, |
|
addCloudVariable, |
|
removeCloudVariable, |
|
hasCloudVariables, |
|
getNumberOfCloudVariables |
|
}; |
|
}; |
|
|
|
|
|
|
|
|
|
|
|
let stepProfilerId = -1; |
|
|
|
|
|
|
|
|
|
|
|
let stepThreadsProfilerId = -1; |
|
|
|
|
|
|
|
|
|
|
|
let rendererDrawProfilerId = -1; |
|
|
|
|
|
|
|
|
|
|
|
class Runtime extends EventEmitter { |
|
constructor () { |
|
super(); |
|
|
|
|
|
|
|
|
|
|
|
this.targets = []; |
|
|
|
|
|
|
|
|
|
|
|
this.executableTargets = []; |
|
|
|
|
|
|
|
|
|
|
|
|
|
this.threads = []; |
|
|
|
this.threadMap = new Map(); |
|
|
|
|
|
this.sequencer = new Sequencer(this); |
|
|
|
|
|
|
|
|
|
|
|
|
|
this.flyoutBlocks = new Blocks(this, true ); |
|
|
|
|
|
|
|
|
|
|
|
|
|
this.monitorBlocks = new Blocks(this, true ); |
|
|
|
|
|
|
|
|
|
|
|
this._editingTarget = null; |
|
|
|
|
|
|
|
|
|
|
|
|
|
this._primitives = {}; |
|
|
|
|
|
|
|
|
|
|
|
|
|
this._blockInfo = []; |
|
|
|
|
|
|
|
|
|
|
|
|
|
this._hats = {}; |
|
|
|
|
|
|
|
|
|
|
|
this._scriptGlowsPreviousFrame = []; |
|
|
|
|
|
|
|
|
|
|
|
this._nonMonitorThreadCount = 0; |
|
|
|
|
|
|
|
|
|
|
|
|
|
this._lastStepDoneThreads = null; |
|
|
|
|
|
|
|
|
|
this.tabManager = new TabManager(this); |
|
|
|
|
|
|
|
|
|
this.modalManager = new ModalManager(this); |
|
|
|
|
|
|
|
|
|
|
|
this._cloneCounter = 0; |
|
|
|
|
|
|
|
|
|
|
|
|
|
this._refreshTargets = false; |
|
|
|
|
|
|
|
|
|
|
|
|
|
this.monitorBlockInfo = {}; |
|
|
|
|
|
|
|
|
|
this._monitorState = OrderedMap({}); |
|
|
|
|
|
|
|
|
|
this._prevMonitorState = OrderedMap({}); |
|
|
|
|
|
|
|
|
|
|
|
this.turboMode = false; |
|
|
|
|
|
|
|
|
|
this.frameLoop = new FrameLoop(this); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
this.currentStepTime = 1000 / 30; |
|
|
|
|
|
this.updateCurrentMSecs(); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
this.redrawRequested = false; |
|
|
|
|
|
this._registerBlockPackages(); |
|
|
|
|
|
|
|
|
|
this.ioDevices = { |
|
clock: new Clock(this), |
|
cloud: new Cloud(this), |
|
keyboard: new Keyboard(this), |
|
mouse: new Mouse(this), |
|
mouseWheel: new MouseWheel(this), |
|
userData: new UserData(), |
|
video: new Video(this), |
|
touch: new Touch(this) |
|
}; |
|
|
|
|
|
|
|
|
|
this.peripheralExtensions = {}; |
|
|
|
|
|
|
|
|
|
|
|
|
|
this.profiler = null; |
|
|
|
this.cloudOptions = { |
|
limit: 10 |
|
}; |
|
|
|
this.extensionRuntimeOptions = { |
|
javascriptUnsandboxed: false |
|
}; |
|
|
|
const newCloudDataManager = cloudDataManager(this.cloudOptions); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
this.hasCloudData = newCloudDataManager.hasCloudVariables; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
this.canAddCloudVariable = newCloudDataManager.canAddCloudVariable; |
|
|
|
|
|
|
|
|
|
|
|
this.getNumberOfCloudVariables = newCloudDataManager.getNumberOfCloudVariables; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
this.addCloudVariable = this._initializeAddCloudVariable(newCloudDataManager); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
this.removeCloudVariable = this._initializeRemoveCloudVariable(newCloudDataManager); |
|
|
|
|
|
|
|
|
|
|
|
|
|
this.origin = null; |
|
|
|
this._stageTarget = null; |
|
|
|
this.addonBlocks = {}; |
|
|
|
this.stageWidth = Runtime.STAGE_WIDTH; |
|
this.stageHeight = Runtime.STAGE_HEIGHT; |
|
|
|
this.runtimeOptions = { |
|
maxClones: Runtime.MAX_CLONES, |
|
miscLimits: true, |
|
fencing: true, |
|
dangerousOptimizations: false, |
|
disableOffscreenRendering: false |
|
}; |
|
|
|
this.compilerOptions = { |
|
enabled: true, |
|
warpTimer: false |
|
}; |
|
|
|
this.optimizationUtil = { |
|
sin: new Array(360), |
|
cos: new Array(360) |
|
}; |
|
for (let i = 0; i < 360; i++) { |
|
this.optimizationUtil.sin[i] = Math.round(Math.sin((Math.PI * i) / 180) * 1e10) / 1e10; |
|
this.optimizationUtil.cos[i] = Math.round(Math.cos((Math.PI * i) / 180) * 1e10) / 1e10; |
|
} |
|
|
|
this.debug = false; |
|
|
|
this._lastStepTime = Date.now(); |
|
this.interpolationEnabled = false; |
|
this.interpolate = interpolate; |
|
|
|
this._defaultStoredSettings = this._generateAllProjectOptions(); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
this.isPackaged = false; |
|
|
|
|
|
|
|
|
|
|
|
|
|
this.isProjectPermissionManagerDisabled = true; |
|
|
|
|
|
|
|
|
|
|
|
|
|
this.isPackagedProject = false; |
|
|
|
|
|
|
|
|
|
|
|
|
|
this.externalCommunicationMethods = { |
|
cloudVariables: false, |
|
customExtensions: false |
|
}; |
|
this.on(Runtime.HAS_CLOUD_DATA_UPDATE, enabled => { |
|
this.setExternalCommunicationMethod('cloudVariables', enabled); |
|
}); |
|
|
|
|
|
this.setMaxListeners(50); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
this.enforcePrivacy = true; |
|
|
|
|
|
|
|
|
|
|
|
this.extensionButtons = new Map(); |
|
|
|
|
|
|
|
|
|
|
|
|
|
this._extensionAudioObjects = new Map(); |
|
|
|
|
|
|
|
|
|
this.fontManager = new FontManager(this); |
|
|
|
this.cameraStates = { |
|
default: { |
|
pos: [0, 0], |
|
dir: 0, |
|
scale: 1 |
|
} |
|
}; |
|
|
|
|
|
this._extensionVariables = {}; |
|
|
|
this.serializers = { |
|
'pm-rendered-target': { |
|
serialize: target => ({ id: target.id, name: target.getName() }), |
|
deserialize: ({ id, name }) => this.getTargetById(id) ?? this.getSpriteTargetByName(name) |
|
}, |
|
'pm-costume-asset': { |
|
serialize: asset => ({ id: asset.assetId, name: asset.name }), |
|
deserialize: ({ assetId, name }) => { |
|
for (let i = 0; i < this.targets.length; i++) { |
|
const assets = this.targets[i].getCostumes(); |
|
const found = assets.find(asset => asset.assetId === assetId || asset.name === name); |
|
if (found) return found; |
|
} |
|
} |
|
}, |
|
'pm-sound-asset': { |
|
serialize: asset => ({ id: asset.assetId, name: asset.name }), |
|
deserialize: ({ assetId, name }) => { |
|
for (let i = 0; i < this.targets.length; i++) { |
|
const assets = this.targets[i].getSounds(); |
|
const found = assets.find(asset => asset.assetId === assetId || asset.name === name); |
|
if (found) return found; |
|
} |
|
} |
|
} |
|
}; |
|
|
|
|
|
|
|
|
|
|
|
|
|
this.variables = Object.create(null); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
this.extensionStorage = ExtensionStorage(); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get STAGE_WIDTH () { |
|
|
|
return 480; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get STAGE_HEIGHT () { |
|
|
|
return 360; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get SCRIPT_GLOW_ON () { |
|
return 'SCRIPT_GLOW_ON'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get SCRIPT_GLOW_OFF () { |
|
return 'SCRIPT_GLOW_OFF'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get BLOCK_GLOW_ON () { |
|
return 'BLOCK_GLOW_ON'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get BLOCK_GLOW_OFF () { |
|
return 'BLOCK_GLOW_OFF'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
static get HAS_CLOUD_DATA_UPDATE () { |
|
return 'HAS_CLOUD_DATA_UPDATE'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get TURBO_MODE_ON () { |
|
return 'TURBO_MODE_ON'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get TURBO_MODE_OFF () { |
|
return 'TURBO_MODE_OFF'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get RUNTIME_OPTIONS_CHANGED () { |
|
return 'RUNTIME_OPTIONS_CHANGED'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get COMPILER_OPTIONS_CHANGED () { |
|
return 'COMPILER_OPTIONS_CHANGED'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get FRAMERATE_CHANGED () { |
|
return 'FRAMERATE_CHANGED'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get INTERPOLATION_CHANGED () { |
|
return 'INTERPOLATION_CHANGED'; |
|
} |
|
|
|
|
|
|
|
|
|
static get BEFORE_INTERPOLATE () { |
|
return 'BEFORE_INTERPOLATE'; |
|
} |
|
|
|
|
|
|
|
|
|
static get AFTER_INTERPOLATE () { |
|
return 'AFTER_INTERPOLATE'; |
|
} |
|
|
|
|
|
|
|
|
|
static get BEFORE_EXECUTE () { |
|
return 'BEFORE_EXECUTE'; |
|
} |
|
|
|
|
|
|
|
|
|
static get AFTER_EXECUTE () { |
|
return 'AFTER_EXECUTE'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get STAGE_SIZE_CHANGED () { |
|
return 'STAGE_SIZE_CHANGED'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get MOUSE_SCROLLED () { |
|
return 'MOUSE_SCROLLED'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get COMPILE_ERROR () { |
|
return 'COMPILE_ERROR'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
static get PROJECT_START () { |
|
return 'PROJECT_START'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get PROJECT_START_BEFORE_RESET () { |
|
return 'PROJECT_START_BEFORE_RESET'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
static get PROJECT_RUN_START () { |
|
return 'PROJECT_RUN_START'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
static get PROJECT_RUN_STOP () { |
|
return 'PROJECT_RUN_STOP'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
static get PROJECT_STOP_ALL () { |
|
return 'PROJECT_STOP_ALL'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
static get STOP_FOR_TARGET () { |
|
return 'STOP_FOR_TARGET'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get VISUAL_REPORT () { |
|
return 'VISUAL_REPORT'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get BLOCK_STACK_ERROR () { |
|
return 'BLOCK_STACK_ERROR'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get PROJECT_LOADED () { |
|
return 'PROJECT_LOADED'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get PROJECT_CHANGED () { |
|
return 'PROJECT_CHANGED'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get TOOLBOX_EXTENSIONS_NEED_UPDATE () { |
|
return 'TOOLBOX_EXTENSIONS_NEED_UPDATE'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get TARGETS_UPDATE () { |
|
return 'TARGETS_UPDATE'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get MONITORS_UPDATE () { |
|
return 'MONITORS_UPDATE'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get BLOCK_DRAG_UPDATE () { |
|
return 'BLOCK_DRAG_UPDATE'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get BLOCK_DRAG_END () { |
|
return 'BLOCK_DRAG_END'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get EXTENSION_ADDED () { |
|
return 'EXTENSION_ADDED'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get EXTENSION_REMOVED () { |
|
return 'EXTENSION_REMOVED'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get EXTENSION_FIELD_ADDED () { |
|
return 'EXTENSION_FIELD_ADDED'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
static get PERIPHERAL_LIST_UPDATE () { |
|
return 'PERIPHERAL_LIST_UPDATE'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
static get USER_PICKED_PERIPHERAL () { |
|
return 'USER_PICKED_PERIPHERAL'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
static get PERIPHERAL_CONNECTED () { |
|
return 'PERIPHERAL_CONNECTED'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
static get PERIPHERAL_DISCONNECTED () { |
|
return 'PERIPHERAL_DISCONNECTED'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
static get PERIPHERAL_REQUEST_ERROR () { |
|
return 'PERIPHERAL_REQUEST_ERROR'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
static get PERIPHERAL_CONNECTION_LOST_ERROR () { |
|
return 'PERIPHERAL_CONNECTION_LOST_ERROR'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
static get PERIPHERAL_SCAN_TIMEOUT () { |
|
return 'PERIPHERAL_SCAN_TIMEOUT'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get MIC_LISTENING () { |
|
return 'MIC_LISTENING'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get BLOCKSINFO_UPDATE () { |
|
return 'BLOCKSINFO_UPDATE'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get RUNTIME_STARTED () { |
|
return 'RUNTIME_STARTED'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get RUNTIME_STOPPED () { |
|
return 'RUNTIME_STOPPED'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get RUNTIME_PAUSED () { |
|
return 'RUNTIME_PAUSED'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
static get RUNTIME_PRE_PAUSED () { |
|
return 'RUNTIME_PRE_PAUSED'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get RUNTIME_UNPAUSED () { |
|
return 'RUNTIME_UNPAUSED'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get RUNTIME_DISPOSED () { |
|
return 'RUNTIME_DISPOSED'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get RUNTIME_STEP_START () { |
|
return 'RUNTIME_STEP_START'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get RUNTIME_STEP_END () { |
|
return 'RUNTIME_STEP_END'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get EDITOR_TABS_NEW () { |
|
return 'EDITOR_TABS_NEW'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get EDITOR_TABS_UPDATE () { |
|
return 'EDITOR_TABS_UPDATE'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get BLOCKS_NEED_UPDATE () { |
|
return 'BLOCKS_NEED_UPDATE'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get CAMERA_CHANGED () { |
|
return 'CAMERA_CHANGED'; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
static get HATS_STARTED () { |
|
return 'HATS_STARTED' |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get THREAD_FINISHED () { |
|
return 'THREAD_FINISHED' |
|
} |
|
|
|
|
|
|
|
|
|
static get THREAD_STEP_INTERVAL () { |
|
|
|
return 1000 / 60; |
|
} |
|
|
|
|
|
|
|
|
|
static get THREAD_STEP_INTERVAL_COMPATIBILITY () { |
|
|
|
return 1000 / 30; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static get MAX_CLONES () { |
|
|
|
return 300; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
_initializeAddCloudVariable (newCloudDataManager) { |
|
|
|
return (() => { |
|
const hadCloudVarsBefore = this.hasCloudData(); |
|
newCloudDataManager.addCloudVariable(); |
|
if (!hadCloudVarsBefore && this.hasCloudData()) { |
|
this.emit(Runtime.HAS_CLOUD_DATA_UPDATE, true); |
|
} |
|
}); |
|
} |
|
|
|
|
|
_initializeRemoveCloudVariable (newCloudDataManager) { |
|
return (() => { |
|
const hadCloudVarsBefore = this.hasCloudData(); |
|
newCloudDataManager.removeCloudVariable(); |
|
if (hadCloudVarsBefore && !this.hasCloudData()) { |
|
this.emit(Runtime.HAS_CLOUD_DATA_UPDATE, false); |
|
} |
|
}); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
_registerBlockPackages () { |
|
for (const packageName in defaultBlockPackages) { |
|
if (defaultBlockPackages.hasOwnProperty(packageName)) { |
|
|
|
const packageObject = new (defaultBlockPackages[packageName])(this); |
|
|
|
if (packageObject.getPrimitives) { |
|
const packagePrimitives = packageObject.getPrimitives(); |
|
for (const op in packagePrimitives) { |
|
if (packagePrimitives.hasOwnProperty(op)) { |
|
this._primitives[op] = |
|
packagePrimitives[op].bind(packageObject); |
|
} |
|
} |
|
} |
|
|
|
if (packageObject.getHats) { |
|
const packageHats = packageObject.getHats(); |
|
for (const hatName in packageHats) { |
|
if (packageHats.hasOwnProperty(hatName)) { |
|
this._hats[hatName] = packageHats[hatName]; |
|
} |
|
} |
|
} |
|
|
|
if (packageObject.getMonitored) { |
|
this.monitorBlockInfo = Object.assign({}, this.monitorBlockInfo, packageObject.getMonitored()); |
|
} |
|
|
|
this.compilerRegisterExtension(packageName, packageObject); |
|
} |
|
} |
|
} |
|
|
|
compilerRegisterExtension (name, extensionObject) { |
|
this[`ext_${name}`] = extensionObject; |
|
} |
|
registerCompiledExtensionBlocks (extensionId, information) { |
|
if (!information) return; |
|
if (!information.ir) return; |
|
if (!information.js) return; |
|
|
|
|
|
|
|
const JSGenerator = require('../compiler/jsgen'); |
|
const IRGenerator = require('../compiler/irgen'); |
|
|
|
IRGenerator.setExtensionIr(extensionId, information.ir); |
|
JSGenerator.setExtensionJs(extensionId, information.js); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
registerExtensionAudioContext(extensionId, audioContext, gainNode) { |
|
if (typeof extensionId !== "string") throw new TypeError('Extension ID must be string'); |
|
if (!extensionId) throw new Error('No extension ID specified'); |
|
|
|
const obj = {}; |
|
if (audioContext) { |
|
obj.audioContext = audioContext; |
|
} |
|
if (gainNode) { |
|
obj.gainNode = gainNode; |
|
} |
|
this._extensionAudioObjects.set(extensionId, obj); |
|
} |
|
|
|
getMonitorState () { |
|
return this._monitorState; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
_makeExtensionMenuId (menuName, extensionId) { |
|
return `${extensionId}_menu_${menuName}`; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
makeMessageContextForTarget (target) { |
|
const context = {}; |
|
target = target || this.getEditingTarget() || this.getTargetForStage(); |
|
if (target) { |
|
context.targetType = (target.isStage ? TargetType.STAGE : TargetType.SPRITE); |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
_registerExtensionPrimitives (extensionInfo) { |
|
const categoryInfo = { |
|
id: extensionInfo.id, |
|
name: maybeFormatMessage(extensionInfo.name), |
|
showStatusButton: extensionInfo.showStatusButton, |
|
blockIconURI: extensionInfo.blockIconURI, |
|
menuIconURI: extensionInfo.menuIconURI |
|
}; |
|
|
|
if (extensionInfo.color1) { |
|
const color1 = Color.hexToRgb(extensionInfo.color1); |
|
categoryInfo.color1 = extensionInfo.color1; |
|
categoryInfo.color2 = extensionInfo.color2; |
|
if (!extensionInfo.color2) { |
|
const mixed = Color.mixRgb(color1, Color.RGB_BLACK, 0.1); |
|
categoryInfo.color2 = Color.rgbToHex(mixed); |
|
} |
|
categoryInfo.color3 = extensionInfo.color3; |
|
if (!extensionInfo.color3) { |
|
const mixed = Color.mixRgb(color1, Color.RGB_BLACK, 0.2); |
|
categoryInfo.color3 = Color.rgbToHex(mixed); |
|
} |
|
} else { |
|
categoryInfo.color1 = defaultExtensionColors[0]; |
|
categoryInfo.color2 = defaultExtensionColors[1]; |
|
categoryInfo.color3 = defaultExtensionColors[2]; |
|
} |
|
|
|
|
|
categoryInfo.blockText = extensionInfo.blockText; |
|
|
|
if (extensionInfo.isDynamic) { |
|
categoryInfo.isDynamic = extensionInfo.isDynamic; |
|
categoryInfo.orderBlocks = extensionInfo.orderBlocks; |
|
} |
|
|
|
categoryInfo.tbShow = extensionInfo.tbShow || false |
|
|
|
this._blockInfo.push(categoryInfo); |
|
|
|
this._fillExtensionCategory(categoryInfo, extensionInfo); |
|
|
|
for (const fieldTypeName in categoryInfo.customFieldTypes) { |
|
if (extensionInfo.customFieldTypes.hasOwnProperty(fieldTypeName)) { |
|
const fieldTypeInfo = categoryInfo.customFieldTypes[fieldTypeName]; |
|
|
|
|
|
this.emit(Runtime.EXTENSION_FIELD_ADDED, { |
|
name: `field_${fieldTypeInfo.extendedName}`, |
|
implementation: fieldTypeInfo.fieldImplementation |
|
}); |
|
} |
|
} |
|
|
|
this.emit(Runtime.EXTENSION_ADDED, categoryInfo); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
_refreshExtensionPrimitives (extensionInfo) { |
|
const categoryInfo = this._blockInfo.find(info => info.id === extensionInfo.id); |
|
if (categoryInfo) { |
|
categoryInfo.name = maybeFormatMessage(extensionInfo.name); |
|
this._fillExtensionCategory(categoryInfo, extensionInfo); |
|
|
|
this.emit(Runtime.BLOCKSINFO_UPDATE, categoryInfo); |
|
} |
|
} |
|
|
|
_removeExtensionPrimitive(extensionId) { |
|
const extIdx = this._blockInfo.findIndex(ext => ext.id === extensionId); |
|
const info = this._blockInfo[extIdx]; |
|
this._blockInfo.splice(extIdx, 1); |
|
this.emit(Runtime.EXTENSION_REMOVED); |
|
|
|
for (const target of this.targets) { |
|
for (const blockId in target.blocks._blocks) { |
|
const {opcode} = target.blocks.getBlock(blockId); |
|
if (info.blocks.find(block => block.json?.type === opcode)) { |
|
target.blocks.deleteBlock(blockId, true); |
|
} |
|
} |
|
} |
|
this.emit(Runtime.BLOCKS_NEED_UPDATE); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
_fillExtensionCategory (categoryInfo, extensionInfo) { |
|
categoryInfo.blocks = []; |
|
categoryInfo.customFieldTypes = {}; |
|
categoryInfo.menus = []; |
|
categoryInfo.menuInfo = {}; |
|
|
|
for (const menuName in extensionInfo.menus) { |
|
if (extensionInfo.menus.hasOwnProperty(menuName)) { |
|
const menuInfo = extensionInfo.menus[menuName]; |
|
const convertedMenu = this._buildMenuForScratchBlocks(menuName, menuInfo, categoryInfo); |
|
categoryInfo.menus.push(convertedMenu); |
|
categoryInfo.menuInfo[menuName] = menuInfo; |
|
} |
|
} |
|
for (const fieldTypeName in extensionInfo.customFieldTypes) { |
|
if (extensionInfo.customFieldTypes.hasOwnProperty(fieldTypeName)) { |
|
const fieldType = extensionInfo.customFieldTypes[fieldTypeName]; |
|
const fieldTypeInfo = this._buildCustomFieldInfo( |
|
fieldTypeName, |
|
fieldType, |
|
extensionInfo.id, |
|
categoryInfo |
|
); |
|
|
|
categoryInfo.customFieldTypes[fieldTypeName] = fieldTypeInfo; |
|
} |
|
} |
|
|
|
if (extensionInfo.docsURI) { |
|
const xml = '<button ' + |
|
`text="${xmlEscape(maybeFormatMessage({ |
|
id: 'tw.blocks.openDocs', |
|
default: 'Open Documentation', |
|
description: 'Button that opens site with more documentation about an extension' |
|
}))}" ` + |
|
'callbackKey="OPEN_EXTENSION_DOCS" ' + |
|
`callbackData="${xmlEscape(extensionInfo.docsURI)}"></button>`; |
|
const block = { |
|
info: {}, |
|
xml |
|
}; |
|
categoryInfo.blocks.push(block); |
|
} |
|
|
|
for (const blockInfo of extensionInfo.blocks) { |
|
try { |
|
const convertedBlock = this._convertForScratchBlocks(blockInfo, categoryInfo); |
|
categoryInfo.blocks.push(convertedBlock); |
|
if (convertedBlock.json) { |
|
const opcode = convertedBlock.json.type; |
|
if (blockInfo.blockType !== BlockType.EVENT && blockInfo.blockType !== BlockType.BUTTON) { |
|
this._primitives[opcode] = convertedBlock.info.func; |
|
} |
|
if (blockInfo.blockType === BlockType.EVENT || blockInfo.blockType === BlockType.HAT) { |
|
this._hats[opcode] = { |
|
edgeActivated: blockInfo.isEdgeActivated, |
|
restartExistingThreads: blockInfo.shouldRestartExistingThreads |
|
}; |
|
} |
|
} |
|
} catch (e) { |
|
log.error('Error parsing block: ', {block: blockInfo, error: e}); |
|
} |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
_convertMenuItems (menuItems) { |
|
if (Array.isArray(menuItems)) { |
|
const extensionMessageContext = this.makeMessageContextForTarget(); |
|
return menuItems.map(item => { |
|
const formattedItem = maybeFormatMessage(item, extensionMessageContext); |
|
switch (typeof formattedItem) { |
|
case 'string': |
|
return [formattedItem, formattedItem]; |
|
case 'object': |
|
if (Array.isArray(item)) return item.slice(0, 2); |
|
return [maybeFormatMessage(item.text, extensionMessageContext), item.value]; |
|
default: |
|
throw new Error(`Can't interpret menu item: ${JSON.stringify(item)}`); |
|
} |
|
}); |
|
} |
|
return menuItems; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
_buildMenuForScratchBlocks (menuName, menuInfo, categoryInfo) { |
|
const menuId = this._makeExtensionMenuId(menuName, categoryInfo.id); |
|
const menuItems = this._convertMenuItems(menuInfo.items); |
|
return { |
|
json: { |
|
message0: '%1', |
|
type: menuId, |
|
inputsInline: true, |
|
output: 'String', |
|
colour: menuInfo.isTypeable |
|
? '#FFFFFF' |
|
: categoryInfo.color1, |
|
colourSecondary: menuInfo.isTypeable |
|
? '#FFFFFF' |
|
: categoryInfo.color2, |
|
colourTertiary: menuInfo.isTypeable |
|
? '#FFFFFF' |
|
: categoryInfo.color3, |
|
outputShape: menuInfo.acceptReporters || menuInfo.isTypeable ? |
|
ScratchBlocksConstants.OUTPUT_SHAPE_ROUND : ScratchBlocksConstants.OUTPUT_SHAPE_SQUARE, |
|
args0: [ |
|
(typeof menuInfo.variableType !== 'undefined' ? |
|
{ |
|
type: 'field_variable', |
|
name: menuName, |
|
variableTypes: [menuInfo.variableType === 'scalar' |
|
? Variable.SCALAR_TYPE |
|
: menuInfo.variableType] |
|
} : (menuInfo.isTypeable ? |
|
{ |
|
type: menuInfo.isNumeric |
|
? 'field_numberdropdown' |
|
: 'field_textdropdown', |
|
name: menuName, |
|
options: menuItems |
|
} : { |
|
type: 'field_dropdown', |
|
name: menuName, |
|
options: menuItems |
|
})) |
|
] |
|
} |
|
}; |
|
} |
|
|
|
_buildCustomFieldInfo (fieldName, fieldInfo, extensionId, categoryInfo) { |
|
const extendedName = `${extensionId}_${fieldName}`; |
|
return { |
|
fieldName: fieldName, |
|
extendedName: extendedName, |
|
argumentTypeInfo: { |
|
shadow: { |
|
type: extendedName, |
|
fieldName: `field_${extendedName}` |
|
} |
|
}, |
|
scratchBlocksDefinition: this._buildCustomFieldTypeForScratchBlocks( |
|
extendedName, |
|
fieldInfo.output, |
|
fieldInfo.outputShape, |
|
categoryInfo |
|
), |
|
fieldImplementation: fieldInfo.implementation |
|
}; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
_buildCustomFieldTypeForScratchBlocks (fieldName, output, outputShape, categoryInfo) { |
|
return { |
|
json: { |
|
type: fieldName, |
|
message0: '%1', |
|
inputsInline: true, |
|
output: output, |
|
colour: categoryInfo.color1, |
|
colourSecondary: categoryInfo.color2, |
|
colourTertiary: categoryInfo.color3, |
|
outputShape: outputShape, |
|
args0: [ |
|
{ |
|
name: `field_${fieldName}`, |
|
type: `field_${fieldName}` |
|
} |
|
] |
|
} |
|
}; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
_convertForScratchBlocks (blockInfo, categoryInfo) { |
|
if (blockInfo === '---') { |
|
return this._convertSeparatorForScratchBlocks(blockInfo); |
|
} |
|
|
|
if (blockInfo.blockType === BlockType.LABEL) |
|
return this._convertLabelForScratchBlocks(blockInfo); |
|
|
|
if (blockInfo.blockType === BlockType.BUTTON) { |
|
return this._convertButtonForScratchBlocks(blockInfo); |
|
} |
|
|
|
if (blockInfo.blockType === BlockType.XML) { |
|
return this._convertXmlForScratchBlocks(blockInfo); |
|
} |
|
|
|
return this._convertBlockForScratchBlocks(blockInfo, categoryInfo); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
_convertBlockForScratchBlocks (blockInfo, categoryInfo) { |
|
const extendedOpcode = `${categoryInfo.id}_${blockInfo.opcode}`; |
|
|
|
const blockJSON = { |
|
type: extendedOpcode, |
|
inputsInline: true, |
|
category: categoryInfo.name, |
|
extensions: blockInfo.extensions ?? [], |
|
colour: blockInfo.color1 ?? categoryInfo.color1, |
|
colourSecondary: blockInfo.color2 ?? categoryInfo.color2, |
|
colourTertiary: blockInfo.color3 ?? categoryInfo.color3, |
|
blockText: blockInfo.blockText ?? categoryInfo.blockText, |
|
canDragDuplicate: blockInfo.canDragDuplicate === true |
|
}; |
|
const context = { |
|
|
|
|
|
|
|
|
|
argsMap: {}, |
|
blockJSON, |
|
categoryInfo, |
|
blockInfo, |
|
inputList: [] |
|
}; |
|
|
|
|
|
|
|
|
|
const iconURI = blockInfo.blockIconURI || categoryInfo.blockIconURI; |
|
|
|
if (iconURI) { |
|
if (!blockJSON.extensions.includes('scratch_extension')) { |
|
blockJSON.extensions.push('scratch_extension'); |
|
} |
|
blockJSON.message0 = '%1 %2'; |
|
const iconJSON = { |
|
type: 'field_image', |
|
src: iconURI, |
|
width: 40, |
|
height: 40 |
|
}; |
|
const separatorJSON = { |
|
type: 'field_vertical_separator' |
|
}; |
|
blockJSON.args0 = [ |
|
iconJSON, |
|
separatorJSON |
|
]; |
|
} |
|
|
|
let notchAccepts = blockInfo.notchAccepts ?? 'normal' |
|
|
|
switch (blockInfo.blockType) { |
|
case BlockType.COMMAND: |
|
blockJSON.outputShape = ScratchBlocksConstants.OUTPUT_SHAPE_SQUARE; |
|
blockJSON.previousStatement = notchAccepts; |
|
if (!blockInfo.isTerminal) { |
|
blockJSON.nextStatement = notchAccepts; |
|
} |
|
break; |
|
case BlockType.REPORTER: |
|
blockJSON.output = blockInfo.allowDropAnywhere ? null : 'String'; |
|
blockJSON.outputShape = ScratchBlocksConstants.OUTPUT_SHAPE_ROUND; |
|
break; |
|
case BlockType.BOOLEAN: |
|
blockJSON.output = 'Boolean'; |
|
blockJSON.outputShape = ScratchBlocksConstants.OUTPUT_SHAPE_HEXAGONAL; |
|
break; |
|
case BlockType.HAT: |
|
case BlockType.EVENT: |
|
if (!blockInfo.hasOwnProperty('isEdgeActivated')) { |
|
|
|
blockInfo.isEdgeActivated = true; |
|
} |
|
blockJSON.outputShape = ScratchBlocksConstants.OUTPUT_SHAPE_SQUARE; |
|
blockJSON.nextStatement = notchAccepts; |
|
break; |
|
case BlockType.CONDITIONAL: |
|
case BlockType.LOOP: |
|
blockInfo.branchCount = blockInfo.branchCount ?? 1; |
|
blockJSON.outputShape = ScratchBlocksConstants.OUTPUT_SHAPE_SQUARE; |
|
blockJSON.previousStatement = notchAccepts; |
|
if (!blockInfo.isTerminal) { |
|
blockJSON.nextStatement = notchAccepts; |
|
} |
|
break; |
|
} |
|
|
|
blockInfo.branches = blockInfo.branches || Array(Math.max(blockInfo.branchCount || 0, 0)).fill({}) |
|
|
|
const blockText = Array.isArray(blockInfo.text) ? blockInfo.text : [blockInfo.text]; |
|
let inTextNum = 0; |
|
let inBranchNum = 0; |
|
let outLineNum = 0; |
|
const convertPlaceholders = this._convertPlaceholders.bind(this, context); |
|
const extensionMessageContext = this.makeMessageContextForTarget(); |
|
|
|
|
|
while (inTextNum < blockText.length || inBranchNum < blockInfo.branches.length) { |
|
if (inTextNum < blockText.length) { |
|
context.outLineNum = outLineNum; |
|
const lineText = maybeFormatMessage(blockText[inTextNum], extensionMessageContext); |
|
const convertedText = lineText.replace(/\[(.+?)]/g, convertPlaceholders); |
|
if (blockJSON[`message${outLineNum}`]) { |
|
blockJSON[`message${outLineNum}`] += convertedText; |
|
} else { |
|
blockJSON[`message${outLineNum}`] = convertedText; |
|
} |
|
++inTextNum; |
|
++outLineNum; |
|
} |
|
if (inBranchNum < blockInfo.branches.length) { |
|
blockJSON[`message${outLineNum}`] = '%1'; |
|
blockJSON[`args${outLineNum}`] = [{ |
|
type: 'input_statement', |
|
name: `SUBSTACK${inBranchNum > 0 ? inBranchNum + 1 : ''}`, |
|
check: blockInfo.branches[inBranchNum].accepts ?? 'normal' |
|
}]; |
|
++inBranchNum; |
|
++outLineNum; |
|
} |
|
} |
|
|
|
if (blockInfo.blockType === BlockType.REPORTER || blockInfo.blockType === BlockType.BOOLEAN) { |
|
if (!blockInfo.disableMonitor && context.inputList.length === 0) { |
|
blockJSON.checkboxInFlyout = true; |
|
} |
|
} |
|
if ((blockInfo.blockType === BlockType.LOOP || ('branchIndicator' in blockInfo || 'branchIconURI' in blockInfo)) && blockInfo.branchIndicator !== "") { |
|
|
|
blockJSON[`lastDummyAlign${outLineNum}`] = 'RIGHT'; |
|
blockJSON[`message${outLineNum}`] = '%1'; |
|
blockJSON[`args${outLineNum}`] = [{ |
|
type: 'field_image', |
|
src: blockInfo.branchIndicator ?? blockInfo.branchIconURI ?? './static/blocks-media/repeat.svg', |
|
width: blockInfo.branchIndicatorWidth ?? 24, |
|
height: blockInfo.branchIndicatorHeight ?? 24, |
|
alt: '*', |
|
flip_rtl: true |
|
}]; |
|
++outLineNum; |
|
} |
|
|
|
if (Array.isArray(blockInfo.alignments)) { |
|
let idx = 0; |
|
|
|
for (const alignment of blockInfo.alignments) { |
|
if (typeof alignment === "string") { |
|
blockJSON[`lastDummyAlign${idx}`] = alignment.toUpperCase(); |
|
} |
|
idx++; |
|
} |
|
} |
|
|
|
const blockShape = blockInfo.blockShape; |
|
if (typeof blockShape === 'number') blockJSON.outputShape = blockShape; |
|
else if (typeof blockShape === 'string') { |
|
|
|
|
|
if (!blockShape.startsWith('custom-')) blockJSON.outputShape = 'custom-' + blockShape; |
|
else blockJSON.outputShape = blockShape; |
|
} |
|
if (blockInfo.forceOutputType) { |
|
blockJSON.output = blockInfo.forceOutputType; |
|
} |
|
|
|
const mutation = blockInfo.isDynamic |
|
? `<mutation blockInfo="${xmlEscape.escapeAttribute(JSON.stringify(blockInfo))}"/>` |
|
: ''; |
|
const inputs = context.inputList.join(''); |
|
const blockId = blockInfo.isSpriteSpecific ? `id="${xmlEscape.escapeAttribute(this.vm.editingTarget.id + '_' + extendedOpcode)}"` : ''; |
|
const blockXML = `<block type="${xmlEscape.escapeAttribute(extendedOpcode)}" ${blockId}>${mutation}${inputs}</block>`; |
|
|
|
return { |
|
info: context.blockInfo, |
|
json: context.blockJSON, |
|
xml: blockXML |
|
}; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
_convertSeparatorForScratchBlocks (blockInfo) { |
|
return { |
|
info: blockInfo, |
|
xml: '<sep gap="36"/>' |
|
}; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
_convertLabelForScratchBlocks (blockInfo) { |
|
const text = xmlEscape.escapeAttribute(blockInfo.text); |
|
return { |
|
info: blockInfo, |
|
xml: `<label text="${text}"></label>` |
|
}; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
_convertButtonForScratchBlocks (buttonInfo) { |
|
const extensionMessageContext = this.makeMessageContextForTarget(); |
|
const buttonText = xmlEscape.escapeAttribute(maybeFormatMessage(buttonInfo.text, extensionMessageContext)); |
|
const callback = xmlEscape.escapeAttribute(buttonInfo.opcode |
|
? buttonInfo.opcode |
|
: buttonInfo.func); |
|
|
|
return { |
|
info: buttonInfo, |
|
xml: `<button text="${buttonText}" callbackKey="${callback}"></button>` |
|
}; |
|
} |
|
|
|
_convertXmlForScratchBlocks (xmlInfo) { |
|
return { |
|
info: xmlInfo, |
|
xml: xmlInfo.xml |
|
}; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
_constructInlineImageJson (argInfo) { |
|
if (!argInfo.dataURI) { |
|
log.warn('Missing data URI in extension block with argument type IMAGE'); |
|
} |
|
return { |
|
type: 'field_image', |
|
src: argInfo.dataURI || '', |
|
|
|
width: argInfo.width ?? 24, |
|
height: argInfo.height ?? 24, |
|
|
|
|
|
|
|
flip_rtl: argInfo.flipRTL || false |
|
}; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
_constructVariableDropdown(argInfo, placeholder) { |
|
|
|
const isList = argInfo.type === 'list'; |
|
const isBroadcast = argInfo.type === 'broadcast'; |
|
return { |
|
type: 'field_variable', |
|
name: placeholder, |
|
variableTypes: isList ? ['list'] : (isBroadcast ? ['broadcast_msg'] : ['']), |
|
variable: isBroadcast ? 'message1' : null |
|
}; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
_convertPlaceholders (context, match, placeholder) { |
|
|
|
const argInfo = context.blockInfo.arguments[placeholder] || {}; |
|
let argTypeInfo = ArgumentTypeMap[argInfo.type] || {}; |
|
|
|
|
|
if (!ArgumentTypeMap[argInfo.type] && context.categoryInfo.customFieldTypes[argInfo.type]) { |
|
argTypeInfo = context.categoryInfo.customFieldTypes[argInfo.type].argumentTypeInfo; |
|
} |
|
|
|
|
|
|
|
let argJSON; |
|
|
|
|
|
|
|
if (argTypeInfo.fieldType === 'field_image') { |
|
argJSON = this._constructInlineImageJson(argInfo); |
|
} else if (argTypeInfo.fieldType === 'field_variable') { |
|
argJSON = this._constructVariableDropdown(argInfo, placeholder); |
|
} else if (argTypeInfo.fieldType === 'field_vertical_separator') { |
|
argJSON = { |
|
type: 'field_vertical_separator', |
|
}; |
|
} else if (argTypeInfo.fieldType === 'field_customInput') { |
|
argJSON = { |
|
type: 'field_customInput', |
|
name: placeholder, |
|
id: argInfo.id, |
|
value: argInfo.defaultValue |
|
}; |
|
} else { |
|
|
|
|
|
|
|
argJSON = { |
|
type: 'input_value', |
|
name: placeholder |
|
}; |
|
|
|
const defaultValue = |
|
typeof argInfo.defaultValue === 'undefined' ? '' : |
|
xmlEscape.escapeAttribute(maybeFormatMessage( |
|
argInfo.defaultValue, this.makeMessageContextForTarget()).toString()); |
|
|
|
if (argTypeInfo.check || argInfo.check) { |
|
|
|
|
|
|
|
argJSON.check = argInfo.check || argTypeInfo.check; |
|
} |
|
const argShape = argTypeInfo.shape || argInfo.shape; |
|
if (argShape) { |
|
if (typeof argShape === 'number') argJSON.shape = argShape; |
|
else { |
|
|
|
|
|
if (!argShape.startsWith('custom-')) argJSON.shape = 'custom-' + argShape; |
|
else argJSON.shape = argShape; |
|
} |
|
} |
|
|
|
let valueName; |
|
let shadowType; |
|
let blockType; |
|
let fieldName; |
|
let variableID; |
|
let variableName; |
|
let variableType; |
|
if (argInfo.menu) { |
|
const menuInfo = context.categoryInfo.menuInfo[argInfo.menu]; |
|
if (menuInfo.acceptReporters || menuInfo.isTypeable) { |
|
valueName = placeholder; |
|
shadowType = this._makeExtensionMenuId(argInfo.menu, context.categoryInfo.id); |
|
fieldName = argInfo.menu; |
|
} else if (typeof menuInfo.variableType !== 'undefined') { |
|
const args = Object.keys(context.blockInfo.arguments); |
|
const blockText = context.blockInfo.text.toString(); |
|
const isVariableGetter = args.length === 1 && blockText.length === args[0].length + 2; |
|
if (isVariableGetter) { |
|
context.blockJSON.extensions ??= []; |
|
context.blockJSON.extensions.push('contextMenu_getVariableBlockAnyType'); |
|
} |
|
argJSON.type = isVariableGetter |
|
? 'field_variable_getter' |
|
: 'field_variable'; |
|
argJSON.variableTypes = [menuInfo.variableType === 'scalar' |
|
? Variable.SCALAR_TYPE |
|
: menuInfo.variableType]; |
|
argJSON.variableType = argJSON.variableTypes[0]; |
|
valueName = null; |
|
shadowType = null; |
|
fieldName = placeholder; |
|
variableType = menuInfo.variableType === 'scalar' |
|
? Variable.SCALAR_TYPE |
|
: menuInfo.variableType |
|
const defaultVar = argInfo.defaultValue ?? []; |
|
variableID = defaultVar[0]; |
|
variableName = defaultVar[1]; |
|
} else { |
|
argJSON.type = 'field_dropdown'; |
|
argJSON.options = this._convertMenuItems(menuInfo.items); |
|
valueName = null; |
|
shadowType = null; |
|
fieldName = placeholder; |
|
} |
|
} else { |
|
valueName = placeholder; |
|
shadowType = (argTypeInfo.shadow && argTypeInfo.shadow.type) || null; |
|
fieldName = (argTypeInfo.shadow && argTypeInfo.shadow.fieldName) || null; |
|
} |
|
|
|
if (argInfo.fillIn || argInfo.fillInGlobal) { |
|
shadowType = argInfo.fillInGlobal || `${context.categoryInfo.id}_${argInfo.fillIn}`; |
|
} |
|
|
|
|
|
|
|
|
|
if (valueName) { |
|
context.inputList.push(`<value name="${xmlEscape.escapeAttribute(placeholder)}">`); |
|
} |
|
|
|
|
|
|
|
if (shadowType) { |
|
context.inputList.push(`<shadow type="${xmlEscape.escapeAttribute(shadowType)}">`); |
|
} |
|
|
|
|
|
if (blockType) { |
|
context.inputList.push(`<block type="${xmlEscape.escapeAttribute(blockType)}">`); |
|
} |
|
|
|
if (shadowType === 'polygon') { |
|
|
|
context.inputList.push(`<mutation expanded="false" points="${argInfo.nodes}" color="${context.blockJSON.colour}" midle="[0,0]" scale="${argInfo.defaultSize || 30}"/>`); |
|
} |
|
|
|
|
|
|
|
if (fieldName && !variableID) { |
|
if ((defaultValue) || ((argInfo.type === "string") && (!argInfo.menu))) { |
|
context.inputList.push(`<field name="${fieldName}">${defaultValue}</field>`); |
|
} |
|
} |
|
|
|
if (variableID) { |
|
|
|
context.inputList.push(`<field name="${fieldName}" id="${variableID}" variableType="${variableType}">${variableName}</field>`); |
|
} |
|
|
|
if (blockType) { |
|
context.inputList.push('</block>'); |
|
} |
|
|
|
if (shadowType) { |
|
context.inputList.push('</shadow>'); |
|
} |
|
|
|
if (valueName) { |
|
context.inputList.push('</value>'); |
|
} |
|
} |
|
|
|
const argsName = `args${context.outLineNum}`; |
|
const blockArgs = (context.blockJSON[argsName] = context.blockJSON[argsName] || []); |
|
if (argJSON) blockArgs.push(argJSON); |
|
const argNum = blockArgs.length; |
|
context.argsMap[placeholder] = argNum; |
|
|
|
return `%${argNum}`; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
getBlocksXML (target) { |
|
return this._blockInfo.map(categoryInfo => { |
|
const {name, color1, color2} = categoryInfo; |
|
let orderBlocks = categoryInfo.orderBlocks; |
|
|
|
|
|
const paletteBlocks = categoryInfo.blocks.filter(block => { |
|
let blockFilterIncludesTarget = true; |
|
|
|
|
|
if (target && block.info.filter) { |
|
blockFilterIncludesTarget = block.info.filter.includes( |
|
target.isStage ? TargetType.STAGE : TargetType.SPRITE |
|
); |
|
} |
|
|
|
return blockFilterIncludesTarget && !block.info.hideFromPalette; |
|
}); |
|
|
|
orderBlocks = orderBlocks |
|
? orderBlocks |
|
: blocks => blocks; |
|
|
|
const colorXML = `colour="${xmlEscape(color1)}" secondaryColour="${xmlEscape(color2)}"`; |
|
|
|
|
|
|
|
let menuIconURI = ''; |
|
if (categoryInfo.menuIconURI) { |
|
menuIconURI = categoryInfo.menuIconURI; |
|
} else if (categoryInfo.blockIconURI) { |
|
menuIconURI = categoryInfo.blockIconURI; |
|
} |
|
const menuIconXML = menuIconURI ? |
|
`iconURI="${xmlEscape(menuIconURI)}"` : ''; |
|
|
|
let statusButtonXML = ''; |
|
if (categoryInfo.showStatusButton) { |
|
statusButtonXML = 'showStatusButton="true"'; |
|
} |
|
|
|
let xml = `<category name="${xmlEscape.escapeAttribute(name)}"`; |
|
xml += ` id="${xmlEscape.escapeAttribute(categoryInfo.id)}"`; |
|
xml += ` options="extensionControls"`; |
|
xml += ` ${statusButtonXML}`; |
|
xml += ` ${colorXML}`; |
|
xml += ` ${menuIconXML}>`; |
|
xml += orderBlocks(paletteBlocks.map(block => block.xml)).join(''); |
|
xml += '</category>'; |
|
|
|
return { |
|
id: categoryInfo.id, |
|
xml |
|
}; |
|
}); |
|
} |
|
|
|
|
|
|
|
|
|
getBlocksJSON () { |
|
return this._blockInfo.reduce( |
|
(result, categoryInfo) => result.concat(categoryInfo.blocks.map(blockInfo => blockInfo.json)), []); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
getScratchLinkSocket (type) { |
|
const factory = this._linkSocketFactory || this._defaultScratchLinkSocketFactory; |
|
return factory(type); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
configureScratchLinkSocketFactory (factory) { |
|
this._linkSocketFactory = factory; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
_defaultScratchLinkSocketFactory (type) { |
|
return new ScratchLinkWebSocket(type); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
registerPeripheralExtension (extensionId, extension) { |
|
this.peripheralExtensions[extensionId] = extension; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
scanForPeripheral (extensionId) { |
|
if (this.peripheralExtensions[extensionId]) { |
|
this.peripheralExtensions[extensionId].scan(); |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
connectPeripheral (extensionId, peripheralId) { |
|
if (this.peripheralExtensions[extensionId]) { |
|
this.peripheralExtensions[extensionId].connect(peripheralId); |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
disconnectPeripheral (extensionId) { |
|
if (this.peripheralExtensions[extensionId]) { |
|
this.peripheralExtensions[extensionId].disconnect(); |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
getPeripheralIsConnected (extensionId) { |
|
let isConnected = false; |
|
if (this.peripheralExtensions[extensionId]) { |
|
isConnected = this.peripheralExtensions[extensionId].isConnected(); |
|
} |
|
return isConnected; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
emitMicListening (listening) { |
|
this.emit(Runtime.MIC_LISTENING, listening); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
getOpcodeFunction (opcode) { |
|
return this._primitives[opcode]; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
getIsHat (opcode) { |
|
return this._hats.hasOwnProperty(opcode); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
getIsEdgeActivatedHat (opcode) { |
|
return this._hats.hasOwnProperty(opcode) && |
|
this._hats[opcode].edgeActivated; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
attachAudioEngine (audioEngine) { |
|
this.audioEngine = audioEngine; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
attachRenderer (renderer) { |
|
this.renderer = renderer; |
|
this.renderer.setLayerGroupOrdering(StageLayering.LAYER_GROUPS); |
|
this.renderer.offscreenTouching = !this.runtimeOptions.fencing; |
|
this.renderer.renderOffscreen = this.runtimeOptions.disableOffscreenRendering; |
|
this.updatePrivacy(); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
registerSerializer (id, serialize, deserialize) { |
|
if (typeof serialize !== 'function') { |
|
throw new TypeError('serialize must be of type function'); |
|
} |
|
if (typeof deserialize !== 'function') { |
|
throw new TypeError('deserialize must be of type function'); |
|
} |
|
this.serializers[id] = { |
|
serialize, |
|
deserialize |
|
}; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
registerVariable (type, varClass) { |
|
this._extensionVariables[type] = varClass; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
unregisterVariable (type) { |
|
const variable = this._extensionVariables[type]; |
|
if (!variable) throw new Error(`can not remove a variable type that does not exist. removing ${type}`); |
|
delete this._extensionVariables[type]; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
newVariableInstance (type, ...args) { |
|
if (coreVariableTypes.includes(type)) { |
|
args.splice(2, 0, type); |
|
return new Variable(...args); |
|
} |
|
const variable = this._extensionVariables[type]; |
|
|
|
if (!variable) return { |
|
type, |
|
value: args, |
|
mustRecreate: true |
|
}; |
|
return new variable(this, ...args); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
attachV2BitmapAdapter (bitmapAdapter) { |
|
this.v2BitmapAdapter = bitmapAdapter; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
attachStorage (storage) { |
|
this.storage = storage; |
|
|
|
if (this.isPackaged) { |
|
|
|
|
|
const originalCreateAsset = storage.createAsset; |
|
let assetIdCounter = 0; |
|
|
|
storage.createAsset = function packagedCreateAsset (assetType, dataFormat, data, assetId, generateId) { |
|
if (!assetId) { |
|
assetId = (++assetIdCounter).toString(); |
|
} |
|
return originalCreateAsset.call( |
|
this, |
|
assetType, |
|
dataFormat, |
|
data, |
|
assetId, |
|
|
|
false |
|
); |
|
}; |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
_pushThread (id, target, opts) { |
|
const thread = new Thread(id); |
|
thread.target = target; |
|
thread.stackClick = Boolean(opts && opts.stackClick); |
|
thread.updateMonitor = Boolean(opts && opts.updateMonitor); |
|
thread.blockContainer = thread.updateMonitor ? |
|
this.monitorBlocks : |
|
((opts && opts.targetBlockLocation) || target.blocks); |
|
|
|
thread.pushStack(id); |
|
this.threads.push(thread); |
|
if (!thread.stackClick && !thread.updateMonitor) { |
|
this.threadMap.set(thread.getId(), thread); |
|
} |
|
|
|
|
|
if (!(opts && opts.updateMonitor) && this.compilerOptions.enabled) { |
|
thread.tryCompile(); |
|
} |
|
|
|
return thread; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
_stopThread (thread) { |
|
|
|
thread.isKilled = true; |
|
|
|
this.sequencer.retireThread(thread); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
_restartThread (thread) { |
|
const newThread = new Thread(thread.topBlock); |
|
newThread.target = thread.target; |
|
newThread.stackClick = thread.stackClick; |
|
newThread.updateMonitor = thread.updateMonitor; |
|
newThread.blockContainer = thread.blockContainer; |
|
newThread.pushStack(thread.topBlock); |
|
|
|
if (thread.triedToCompile && this.compilerOptions.enabled) { |
|
newThread.tryCompile(); |
|
} |
|
if (!newThread.stackClick && !newThread.updateMonitor) { |
|
this.threadMap.set(newThread.getId(), newThread); |
|
} |
|
const i = this.threads.indexOf(thread); |
|
if (i > -1) { |
|
this.threads[i] = newThread; |
|
return newThread; |
|
} |
|
this.threads.push(thread); |
|
return thread; |
|
} |
|
|
|
emitCompileError (target, error) { |
|
this.emit(Runtime.COMPILE_ERROR, target, error); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
isActiveThread (thread) { |
|
return ( |
|
( |
|
thread.stack.length > 0 && |
|
thread.status !== Thread.STATUS_DONE) && |
|
this.threads.indexOf(thread) > -1); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
isWaitingThread (thread) { |
|
return ( |
|
thread.status === Thread.STATUS_PROMISE_WAIT || |
|
thread.status === Thread.STATUS_YIELD_TICK || |
|
!this.isActiveThread(thread) |
|
); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
toggleScript (topBlockId, opts) { |
|
opts = Object.assign({ |
|
target: this._editingTarget, |
|
stackClick: false |
|
}, opts); |
|
|
|
for (let i = 0; i < this.threads.length; i++) { |
|
|
|
if (this.threads[i].topBlock === topBlockId && this.threads[i].status !== Thread.STATUS_DONE) { |
|
const blockContainer = opts.target.blocks; |
|
const opcode = blockContainer.getOpcode(blockContainer.getBlock(topBlockId)); |
|
|
|
if (this.getIsEdgeActivatedHat(opcode) && this.threads[i].stackClick !== opts.stackClick) { |
|
|
|
|
|
continue; |
|
} |
|
this._stopThread(this.threads[i]); |
|
return; |
|
} |
|
} |
|
|
|
this._pushThread(topBlockId, opts.target, opts); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
addMonitorScript (topBlockId, optTarget) { |
|
if (!optTarget) optTarget = this._editingTarget; |
|
for (let i = 0; i < this.threads.length; i++) { |
|
|
|
if (this.threads[i].topBlock === topBlockId && this.threads[i].status !== Thread.STATUS_DONE && |
|
this.threads[i].updateMonitor) { |
|
return; |
|
} |
|
} |
|
|
|
this._pushThread(topBlockId, optTarget, {updateMonitor: true}); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
allScriptsDo (f, optTarget) { |
|
let targets = this.executableTargets; |
|
if (optTarget) { |
|
targets = [optTarget]; |
|
} |
|
for (let t = targets.length - 1; t >= 0; t--) { |
|
const target = targets[t]; |
|
const scripts = target.blocks.getScripts(); |
|
for (let j = 0; j < scripts.length; j++) { |
|
const topBlockId = scripts[j]; |
|
f(topBlockId, target); |
|
} |
|
} |
|
} |
|
|
|
allScriptsByOpcodeDo (opcode, f, optTarget) { |
|
let targets = this.executableTargets; |
|
if (optTarget) { |
|
targets = [optTarget]; |
|
} |
|
for (let t = targets.length - 1; t >= 0; t--) { |
|
const target = targets[t]; |
|
const scripts = BlocksRuntimeCache.getScripts(target.blocks, opcode); |
|
for (let j = 0; j < scripts.length; j++) { |
|
f(scripts[j], target); |
|
} |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
startHats (requestedHatOpcode, optMatchFields, optTarget) { |
|
if (!this._hats.hasOwnProperty(requestedHatOpcode)) { |
|
|
|
return; |
|
} |
|
const instance = this; |
|
const newThreads = []; |
|
|
|
const hatMeta = instance._hats[requestedHatOpcode]; |
|
|
|
for (const opts in optMatchFields) { |
|
if (!optMatchFields.hasOwnProperty(opts)) continue; |
|
optMatchFields[opts] = Cast.toString(optMatchFields[opts]).toUpperCase(); |
|
} |
|
|
|
|
|
|
|
const startingThreadListLength = this.threads.length; |
|
|
|
|
|
this.allScriptsByOpcodeDo(requestedHatOpcode, (script, target) => { |
|
const { |
|
blockId: topBlockId, |
|
fieldsOfInputs: hatFields |
|
} = script; |
|
|
|
|
|
|
|
|
|
|
|
|
|
for (const matchField in optMatchFields) { |
|
if (hatFields[matchField].value !== optMatchFields[matchField]) { |
|
|
|
return; |
|
} |
|
} |
|
|
|
if (hatMeta.restartExistingThreads) { |
|
|
|
|
|
const existingThread = this.threadMap.get(Thread.getIdFromTargetAndBlock(target, topBlockId)); |
|
if (existingThread) { |
|
newThreads.push(this._restartThread(existingThread)); |
|
return; |
|
} |
|
} else { |
|
|
|
|
|
for (let j = 0; j < startingThreadListLength; j++) { |
|
if (this.threads[j].target === target && |
|
this.threads[j].topBlock === topBlockId && |
|
|
|
!this.threads[j].stackClick && |
|
this.threads[j].status !== Thread.STATUS_DONE) { |
|
|
|
return; |
|
} |
|
} |
|
} |
|
|
|
newThreads.push(this._pushThread(topBlockId, target)); |
|
}, optTarget); |
|
|
|
|
|
newThreads.forEach(thread => { |
|
|
|
if (this.paused) thread.pause(); |
|
if (thread.isCompiled) { |
|
if (thread.executableHat) { |
|
|
|
|
|
compilerExecute.saveGlobalState(); |
|
compilerExecute(thread); |
|
compilerExecute.restoreGlobalState(); |
|
} |
|
} else { |
|
execute(this.sequencer, thread); |
|
thread.goToNextBlock(); |
|
} |
|
}); |
|
this.emit(Runtime.HATS_STARTED, requestedHatOpcode, optMatchFields, optTarget, newThreads); |
|
return newThreads; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
dispose () { |
|
this.stopAll(); |
|
|
|
this.targets.forEach(target => { |
|
if (target.isOriginal) target.deleteMonitors(); |
|
}); |
|
|
|
this.targets.map(this.disposeTarget, this); |
|
|
|
const emptyMonitorState = OrderedMap({}); |
|
if (!emptyMonitorState.equals(this._monitorState)) { |
|
this._monitorState = emptyMonitorState; |
|
this.emit(Runtime.MONITORS_UPDATE, this._monitorState); |
|
} |
|
this.emit(Runtime.RUNTIME_DISPOSED); |
|
this.ioDevices.clock.resetProjectTimer(); |
|
this.fontManager.clear(); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if (this.hasCloudData()) { |
|
this.emit(Runtime.HAS_CLOUD_DATA_UPDATE, false); |
|
} |
|
|
|
this.ioDevices.cloud.clear(); |
|
|
|
|
|
const newCloudDataManager = cloudDataManager(this.cloudOptions); |
|
this.hasCloudData = newCloudDataManager.hasCloudVariables; |
|
this.canAddCloudVariable = newCloudDataManager.canAddCloudVariable; |
|
this.getNumberOfCloudVariables = newCloudDataManager.getNumberOfCloudVariables; |
|
this.addCloudVariable = this._initializeAddCloudVariable(newCloudDataManager); |
|
this.removeCloudVariable = this._initializeRemoveCloudVariable(newCloudDataManager); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
addTarget (target) { |
|
for (const varId in target.variables) { |
|
const variable = target.variables[varId]; |
|
if (variable.mustRecreate) { |
|
|
|
const newVar = this.newVariableInstance(variable.type, ...variable.value); |
|
|
|
if (newVar.mustRecreate) { |
|
delete target.variables[varId]; |
|
continue; |
|
} |
|
target.variables[varId] = newVar; |
|
} |
|
} |
|
this.targets.push(target); |
|
this.executableTargets.push(target); |
|
if (target.isStage && !this._stageTarget) { |
|
this._stageTarget = target; |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
moveExecutable (executableTarget, delta) { |
|
const oldIndex = this.executableTargets.indexOf(executableTarget); |
|
this.executableTargets.splice(oldIndex, 1); |
|
let newIndex = oldIndex + delta; |
|
if (newIndex > this.executableTargets.length) { |
|
newIndex = this.executableTargets.length; |
|
} |
|
if (newIndex <= 0) { |
|
if (this.executableTargets.length > 0 && this.executableTargets[0].isStage) { |
|
newIndex = 1; |
|
} else { |
|
newIndex = 0; |
|
} |
|
} |
|
this.executableTargets.splice(newIndex, 0, executableTarget); |
|
return newIndex; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
setExecutablePosition (executableTarget, newIndex) { |
|
const oldIndex = this.executableTargets.indexOf(executableTarget); |
|
return this.moveExecutable(executableTarget, newIndex - oldIndex); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
removeExecutable (executableTarget) { |
|
const oldIndex = this.executableTargets.indexOf(executableTarget); |
|
if (oldIndex > -1) { |
|
this.executableTargets.splice(oldIndex, 1); |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
disposeTarget (disposingTarget) { |
|
this.targets = this.targets.filter(target => { |
|
if (disposingTarget !== target) return true; |
|
|
|
target.dispose(); |
|
|
|
return false; |
|
}); |
|
if (this._stageTarget === disposingTarget) { |
|
this._stageTarget = null; |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
stopForTarget (target, optThreadException) { |
|
|
|
this.emit(Runtime.STOP_FOR_TARGET, target, optThreadException); |
|
|
|
|
|
for (let i = 0; i < this.threads.length; i++) { |
|
if (this.threads[i] === optThreadException) { |
|
continue; |
|
} |
|
if (this.threads[i].target === target) { |
|
this._stopThread(this.threads[i]); |
|
} |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
greenFlag() { |
|
this.emit(Runtime.PROJECT_START_BEFORE_RESET); |
|
this.stopAll(); |
|
this.emit(Runtime.PROJECT_START); |
|
this.updateCurrentMSecs(); |
|
this.ioDevices.clock.resetProjectTimer(); |
|
this.targets.forEach(target => target.clearEdgeActivatedValues()); |
|
|
|
for (let i = 0; i < this.targets.length; i++) { |
|
this.targets[i].onGreenFlag(); |
|
} |
|
this.startHats('event_whenflagclicked'); |
|
} |
|
|
|
|
|
|
|
|
|
pause() { |
|
if (this.paused) return; |
|
this.emit(Runtime.RUNTIME_PRE_PAUSED); |
|
this.paused = true; |
|
|
|
this.audioEngine.audioContext.suspend(); |
|
for (const audioData of this._extensionAudioObjects.values()) { |
|
if (audioData.audioContext) { |
|
audioData.audioContext.suspend(); |
|
} |
|
} |
|
|
|
this.ioDevices.clock.pause(); |
|
for (const thread of this.threads) { |
|
thread.pause(); |
|
} |
|
this.emit(Runtime.RUNTIME_PAUSED); |
|
} |
|
|
|
|
|
|
|
|
|
play() { |
|
if (!this.paused) return; |
|
this.paused = false; |
|
|
|
this.audioEngine.audioContext.resume(); |
|
for (const audioData of this._extensionAudioObjects.values()) { |
|
if (audioData.audioContext) { |
|
audioData.audioContext.resume(); |
|
} |
|
} |
|
|
|
this.ioDevices.clock.resume(); |
|
for (const thread of this.threads) { |
|
thread.play(); |
|
} |
|
this.emit(Runtime.RUNTIME_UNPAUSED); |
|
} |
|
|
|
|
|
|
|
|
|
stopAll () { |
|
|
|
this.play(); |
|
|
|
this.emit(Runtime.PROJECT_STOP_ALL); |
|
|
|
this.variables = Object.create(null); |
|
|
|
|
|
const newTargets = []; |
|
for (let i = 0; i < this.targets.length; i++) { |
|
this.targets[i].onStopAll(); |
|
if (this.targets[i].hasOwnProperty('isOriginal') && |
|
!this.targets[i].isOriginal) { |
|
this.targets[i].dispose(); |
|
} else { |
|
newTargets.push(this.targets[i]); |
|
} |
|
} |
|
this.targets = newTargets; |
|
|
|
if (this.sequencer.activeThread !== null) { |
|
this._stopThread(this.sequencer.activeThread); |
|
} |
|
|
|
this.threads.forEach(v => v.status !== Thread.STATUS_DONE && this.emit(Runtime.THREAD_FINISHED, v)) |
|
this.threads = []; |
|
this.threadMap.clear(); |
|
} |
|
|
|
_renderInterpolatedPositions () { |
|
const frameStarted = this._lastStepTime; |
|
const now = Date.now(); |
|
const timeSinceStart = now - frameStarted; |
|
const progressInFrame = Math.min(1, Math.max(0, timeSinceStart / this.currentStepTime)); |
|
|
|
interpolate.interpolate(this, progressInFrame); |
|
|
|
if (this.renderer) { |
|
this.renderer.draw(); |
|
} |
|
} |
|
|
|
updateThreadMap () { |
|
this.threadMap.clear(); |
|
for (const thread of this.threads) { |
|
if (!thread.stackClick && !thread.updateMonitor) { |
|
this.threadMap.set(thread.getId(), thread); |
|
} |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
_step () { |
|
|
|
|
|
this.frameLoop._stepCounter++; |
|
this.emit(Runtime.RUNTIME_STEP_START); |
|
|
|
if (this.interpolationEnabled) { |
|
interpolate.setupInitialState(this); |
|
} |
|
|
|
if (this.profiler !== null) { |
|
if (stepProfilerId === -1) { |
|
stepProfilerId = this.profiler.idByName('Runtime._step'); |
|
} |
|
this.profiler.start(stepProfilerId); |
|
} |
|
|
|
|
|
this.threads = this.threads.filter(thread => !thread.isKilled); |
|
this.updateThreadMap(); |
|
|
|
|
|
for (const hatType in this._hats) { |
|
if (!this._hats.hasOwnProperty(hatType)) continue; |
|
const hat = this._hats[hatType]; |
|
if (hat.edgeActivated) { |
|
this.startHats(hatType); |
|
} |
|
} |
|
this.redrawRequested = false; |
|
this._pushMonitors(); |
|
if (this.profiler !== null) { |
|
if (stepThreadsProfilerId === -1) { |
|
stepThreadsProfilerId = this.profiler.idByName('Sequencer.stepThreads'); |
|
} |
|
this.profiler.start(stepThreadsProfilerId); |
|
} |
|
this.emit(Runtime.BEFORE_EXECUTE); |
|
const doneThreads = this.sequencer.stepThreads(); |
|
if (this.profiler !== null) { |
|
this.profiler.stop(); |
|
} |
|
this.emit(Runtime.AFTER_EXECUTE); |
|
this._updateGlows(doneThreads); |
|
|
|
|
|
this._emitProjectRunStatus( |
|
this.threads.length + doneThreads.length - |
|
this._getMonitorThreadCount([...this.threads, ...doneThreads])); |
|
|
|
|
|
this._lastStepDoneThreads = doneThreads; |
|
if (this.renderer) { |
|
|
|
if (this.profiler !== null) { |
|
if (rendererDrawProfilerId === -1) { |
|
rendererDrawProfilerId = this.profiler.idByName('RenderWebGL.draw'); |
|
} |
|
this.profiler.start(rendererDrawProfilerId); |
|
} |
|
|
|
|
|
|
|
if (!document.hidden && !this.frameLoop._interpolationAnimation) { |
|
this.renderer.draw(); |
|
} |
|
if (this.profiler !== null) { |
|
this.profiler.stop(); |
|
} |
|
} |
|
|
|
if (this._refreshTargets) { |
|
this.emit(Runtime.TARGETS_UPDATE, false ); |
|
this._refreshTargets = false; |
|
} |
|
|
|
let forceUpd = false; |
|
|
|
if (this._monitorState.some(item => |
|
typeof item.get('value') === 'object' && |
|
'_monitorUpToDate' in item.get('value') && |
|
!item.get('value')._monitorUpToDate |
|
)) { |
|
const old = this._monitorState; |
|
|
|
this._monitorState = this._monitorState.toOrderedMap(); |
|
if (!(old !== this._monitorState)) |
|
throw new Error('Expected OrderedMap.toOrderedMap() to produce a truly unique value'); |
|
forceUpd = true; |
|
} |
|
if (!this._prevMonitorState.equals(this._monitorState) || forceUpd) { |
|
this.emit(Runtime.MONITORS_UPDATE, this._monitorState); |
|
this._prevMonitorState = this._monitorState; |
|
} |
|
|
|
if (this.profiler !== null) { |
|
this.profiler.stop(); |
|
this.profiler.reportFrames(); |
|
} |
|
|
|
if (this.interpolationEnabled) { |
|
this._lastStepTime = Date.now(); |
|
} |
|
|
|
|
|
this.emit(Runtime.RUNTIME_STEP_END); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
_getMonitorThreadCount (threads) { |
|
let count = 0; |
|
threads.forEach(thread => { |
|
if (thread.updateMonitor) count++; |
|
}); |
|
return count; |
|
} |
|
|
|
|
|
|
|
|
|
_pushMonitors () { |
|
this.monitorBlocks.runAllMonitored(this); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
setEditingTarget (editingTarget) { |
|
const oldEditingTarget = this._editingTarget; |
|
this._editingTarget = editingTarget; |
|
|
|
this._scriptGlowsPreviousFrame = []; |
|
this._updateGlows(); |
|
|
|
if (oldEditingTarget !== this._editingTarget) { |
|
this.requestToolboxExtensionsUpdate(); |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
setCompatibilityMode (compatibilityModeOn) { |
|
|
|
|
|
if (compatibilityModeOn) { |
|
this.setFramerate(30); |
|
} else { |
|
this.setFramerate(60); |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
setFramerate (framerate) { |
|
|
|
|
|
if (framerate > 250) framerate = 250; |
|
|
|
|
|
if (framerate < 0) framerate = 1; |
|
this.frameLoop.setFramerate(framerate); |
|
this.emit(Runtime.FRAMERATE_CHANGED, framerate); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
setInterpolation (interpolationEnabled) { |
|
this.interpolationEnabled = interpolationEnabled; |
|
this.frameLoop.setInterpolation(this.interpolationEnabled); |
|
this.emit(Runtime.INTERPOLATION_CHANGED, interpolationEnabled); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
setRuntimeOptions (runtimeOptions) { |
|
this.runtimeOptions = Object.assign({}, this.runtimeOptions, runtimeOptions); |
|
this.emit(Runtime.RUNTIME_OPTIONS_CHANGED, this.runtimeOptions); |
|
if (this.renderer) { |
|
this.renderer.offscreenTouching = !this.runtimeOptions.fencing; |
|
|
|
if (this.runtimeOptions.disableOffscreenRendering === this.renderer.renderOffscreen) { |
|
this.renderer.setRenderOffscreen(!this.runtimeOptions.disableOffscreenRendering); |
|
} |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
setCompilerOptions (compilerOptions) { |
|
this.compilerOptions = Object.assign({}, this.compilerOptions, compilerOptions); |
|
this.resetAllCaches(); |
|
this.emit(Runtime.COMPILER_OPTIONS_CHANGED, this.compilerOptions); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
setStageSize (width, height) { |
|
width = Math.round(Math.max(1, width)); |
|
height = Math.round(Math.max(1, height)); |
|
if (this.stageWidth !== width || this.stageHeight !== height) { |
|
const deltaX = width - this.stageWidth; |
|
const deltaY = height - this.stageHeight; |
|
|
|
if (this._monitorState.size > 0) { |
|
const offsetX = deltaX / 2; |
|
const offsetY = deltaY / 2; |
|
for (const monitor of this._monitorState.valueSeq()) { |
|
const newMonitor = monitor |
|
.set('x', monitor.get('x') + offsetX) |
|
.set('y', monitor.get('y') + offsetY); |
|
this.requestUpdateMonitor(newMonitor); |
|
} |
|
this.emit(Runtime.MONITORS_UPDATE, this._monitorState); |
|
} |
|
|
|
this.stageWidth = width; |
|
this.stageHeight = height; |
|
if (this.renderer) { |
|
this.renderer.setStageSize( |
|
-width / 2, |
|
width / 2, |
|
-height / 2, |
|
height / 2 |
|
); |
|
} |
|
this.emit(Runtime.STAGE_SIZE_CHANGED, width, height); |
|
} |
|
} |
|
|
|
|
|
setInEditor (inEditor) { |
|
|
|
} |
|
|
|
|
|
|
|
|
|
convertToPackagedRuntime () { |
|
if (this.storage) { |
|
throw new Error('convertToPackagedRuntime must be called before attachStorage'); |
|
} |
|
|
|
this.isPackaged = true; |
|
} |
|
|
|
|
|
|
|
|
|
resetAllCaches () { |
|
for (const target of this.targets) { |
|
if (target.isOriginal) { |
|
target.blocks.resetCache(); |
|
} |
|
} |
|
this.flyoutBlocks.resetCache(); |
|
this.monitorBlocks.resetCache(); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
addAddonBlock (options) { |
|
const procedureCode = options.procedureCode; |
|
const names = options.arguments; |
|
const ids = options.arguments.map((_, i) => `arg${i}`); |
|
const defaults = options.arguments.map(() => ''); |
|
this.addonBlocks[procedureCode] = { |
|
namesIdsDefaults: [names, ids, defaults], |
|
...options |
|
}; |
|
|
|
if (!options.hidden) { |
|
const ID = 'a-b'; |
|
let blockInfo = this._blockInfo.find(i => i.id === ID); |
|
if (!blockInfo) { |
|
|
|
const ICON = '<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48"><path d="M14.92 1.053A13.835 13.835 0 0 0 1.052 14.919v18.162a13.835 13.835 0 0 0 13.866 13.866h18.162a13.835 13.835 0 0 0 13.866-13.866V14.919A13.835 13.835 0 0 0 33.081 1.053zm16.6 12.746L41.72 24 31.52 34.201l-3.276-3.275L35.17 24l-6.926-6.926Zm-15.116.073 3.278 3.278L12.83 24l6.926 6.926L16.48 34.2 6.28 24Z" style="fill:#29beb8;fill-opacity:1;stroke:none;stroke-width:1.51371;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"/></svg>'; |
|
blockInfo = { |
|
id: ID, |
|
name: 'Addons', |
|
color1: '#29beb8', |
|
color2: '#3aa8a4', |
|
color3: '#3aa8a4', |
|
menuIconURI: `data:image/svg+xml;,${encodeURIComponent(ICON)}`, |
|
blocks: [], |
|
customFieldTypes: {}, |
|
menus: [] |
|
}; |
|
this._blockInfo.unshift(blockInfo); |
|
} |
|
blockInfo.blocks.push({ |
|
info: {}, |
|
xml: |
|
'<block type="procedures_call" gap="16"><mutation generateshadows="true" warp="false"' + |
|
` proccode="${xmlEscape(procedureCode)}"` + |
|
` argumentnames="${xmlEscape(JSON.stringify(names))}"` + |
|
` argumentids="${xmlEscape(JSON.stringify(ids))}"` + |
|
` argumentdefaults="${xmlEscape(JSON.stringify(defaults))}"` + |
|
'></mutation></block>' |
|
}); |
|
} |
|
|
|
this.resetAllCaches(); |
|
} |
|
|
|
getAddonBlock (procedureCode) { |
|
if (Object.prototype.hasOwnProperty.call(this.addonBlocks, procedureCode)) { |
|
return this.addonBlocks[procedureCode]; |
|
} |
|
return null; |
|
} |
|
|
|
findProjectOptionsComment () { |
|
const target = this.getTargetForStage(); |
|
const comments = target.comments; |
|
for (const comment of Object.values(comments)) { |
|
if (comment.text.includes(COMMENT_CONFIG_MAGIC)) { |
|
return comment; |
|
} |
|
} |
|
return null; |
|
} |
|
|
|
parseProjectOptions (optComment) { |
|
const comment = optComment ?? this.findProjectOptionsComment(); |
|
if (!comment) return; |
|
const lineWithMagic = comment.text.split('\n').find(i => i.endsWith(COMMENT_CONFIG_MAGIC)); |
|
if (!lineWithMagic) { |
|
log.warn('Config comment does not contain valid line'); |
|
return; |
|
} |
|
|
|
const jsonText = lineWithMagic.slice(0, lineWithMagic.length - COMMENT_CONFIG_MAGIC.length); |
|
let parsed; |
|
try { |
|
parsed = ExtendedJSON.parse(jsonText); |
|
if (!parsed || typeof parsed !== 'object') { |
|
throw new Error('Invalid object'); |
|
} |
|
} catch (e) { |
|
log.warn('Config comment has invalid JSON', e); |
|
return; |
|
} |
|
|
|
if (typeof parsed.framerate === 'number') { |
|
this.setFramerate(parsed.framerate); |
|
} |
|
if (parsed.turbo) { |
|
this.turboMode = true; |
|
this.emit(Runtime.TURBO_MODE_ON); |
|
} |
|
if (parsed.interpolation) { |
|
this.setInterpolation(true); |
|
} |
|
if (parsed.runtimeOptions) { |
|
this.setRuntimeOptions(parsed.runtimeOptions); |
|
} |
|
if (typeof parsed.hq === 'boolean' && this.renderer) { |
|
this.renderer.setUseHighQualityRender(parsed.hq); |
|
} |
|
const storedWidth = +parsed.width || this.stageWidth; |
|
const storedHeight = +parsed.height || this.stageHeight; |
|
if (storedWidth !== this.stageWidth || storedHeight !== this.stageHeight) { |
|
this.setStageSize(storedWidth, storedHeight); |
|
} |
|
} |
|
|
|
_generateAllProjectOptions () { |
|
return { |
|
framerate: this.frameLoop.framerate, |
|
runtimeOptions: this.runtimeOptions, |
|
interpolation: this.interpolationEnabled, |
|
turbo: this.turboMode, |
|
hq: this.renderer ? this.renderer.useHighQualityRender : true, |
|
width: this.stageWidth, |
|
height: this.stageHeight |
|
}; |
|
} |
|
|
|
generateDifferingProjectOptions () { |
|
const difference = (oldObject, newObject) => { |
|
const result = {}; |
|
for (const key of Object.keys(newObject)) { |
|
const newValue = newObject[key]; |
|
const oldValue = oldObject[key]; |
|
if (typeof newValue === 'object' && newValue) { |
|
const valueDiffering = difference(oldValue, newValue); |
|
if (Object.keys(valueDiffering).length > 0) { |
|
result[key] = valueDiffering; |
|
} |
|
} else if (newValue !== oldValue) { |
|
result[key] = newValue; |
|
} |
|
} |
|
return result; |
|
}; |
|
return difference(this._defaultStoredSettings, this._generateAllProjectOptions()); |
|
} |
|
|
|
storeProjectOptions () { |
|
const options = this.generateDifferingProjectOptions(); |
|
|
|
const text = `Configuration for https://penguinmod.com/\nYou can move, resize, and minimize this comment, but don't edit it by hand. This comment can be deleted to remove the stored settings.\n${ExtendedJSON.stringify(options)}${COMMENT_CONFIG_MAGIC}`; |
|
const existingComment = this.findProjectOptionsComment(); |
|
if (existingComment) { |
|
existingComment.text = text; |
|
} else { |
|
const target = this.getTargetForStage(); |
|
|
|
target.createComment(uid(), null, text, 50, 50, 350, 170, false); |
|
} |
|
this.emitProjectChanged(); |
|
} |
|
|
|
|
|
|
|
|
|
precompile () { |
|
this.allScriptsDo((topBlockId, target) => { |
|
const topBlock = target.blocks.getBlock(topBlockId); |
|
if (this.getIsHat(topBlock.opcode)) { |
|
const thread = new Thread(topBlockId); |
|
thread.target = target; |
|
thread.blockContainer = target.blocks; |
|
thread.tryCompile(); |
|
} |
|
}); |
|
} |
|
|
|
enableDebug () { |
|
this.resetAllCaches(); |
|
this.debug = true; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
_updateGlows (optExtraThreads) { |
|
const searchThreads = []; |
|
searchThreads.push.apply(searchThreads, this.threads); |
|
if (optExtraThreads) { |
|
searchThreads.push.apply(searchThreads, optExtraThreads); |
|
} |
|
|
|
const requestedGlowsThisFrame = []; |
|
|
|
const finalScriptGlows = []; |
|
|
|
for (let i = 0; i < searchThreads.length; i++) { |
|
const thread = searchThreads[i]; |
|
const target = thread.target; |
|
if (target === this._editingTarget) { |
|
const blockForThread = thread.blockGlowInFrame; |
|
if (thread.requestScriptGlowInFrame || thread.stackClick) { |
|
let script = target.blocks.getTopLevelScript(blockForThread); |
|
if (!script) { |
|
|
|
script = this.flyoutBlocks.getTopLevelScript( |
|
blockForThread |
|
); |
|
} |
|
if (script) { |
|
requestedGlowsThisFrame.push(script); |
|
} |
|
} |
|
} |
|
} |
|
|
|
for (let j = 0; j < this._scriptGlowsPreviousFrame.length; j++) { |
|
const previousFrameGlow = this._scriptGlowsPreviousFrame[j]; |
|
if (requestedGlowsThisFrame.indexOf(previousFrameGlow) < 0) { |
|
|
|
this.glowScript(previousFrameGlow, false); |
|
} else { |
|
|
|
finalScriptGlows.push(previousFrameGlow); |
|
} |
|
} |
|
for (let k = 0; k < requestedGlowsThisFrame.length; k++) { |
|
const currentFrameGlow = requestedGlowsThisFrame[k]; |
|
if (this._scriptGlowsPreviousFrame.indexOf(currentFrameGlow) < 0) { |
|
|
|
this.glowScript(currentFrameGlow, true); |
|
finalScriptGlows.push(currentFrameGlow); |
|
} |
|
} |
|
this._scriptGlowsPreviousFrame = finalScriptGlows; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
_emitProjectRunStatus (nonMonitorThreadCount) { |
|
if (this._nonMonitorThreadCount === 0 && nonMonitorThreadCount > 0) { |
|
this.emit(Runtime.PROJECT_RUN_START); |
|
} |
|
if (this._nonMonitorThreadCount > 0 && nonMonitorThreadCount === 0) { |
|
this.emit(Runtime.PROJECT_RUN_STOP); |
|
} |
|
this._nonMonitorThreadCount = nonMonitorThreadCount; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
quietGlow (scriptBlockId) { |
|
const index = this._scriptGlowsPreviousFrame.indexOf(scriptBlockId); |
|
if (index > -1) { |
|
this._scriptGlowsPreviousFrame.splice(index, 1); |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
glowBlock (blockId, isGlowing) { |
|
if (isGlowing) { |
|
this.emit(Runtime.BLOCK_GLOW_ON, {id: blockId}); |
|
} else { |
|
this.emit(Runtime.BLOCK_GLOW_OFF, {id: blockId}); |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
glowScript (topBlockId, isGlowing) { |
|
if (isGlowing) { |
|
this.emit(Runtime.SCRIPT_GLOW_ON, {id: topBlockId}); |
|
} else { |
|
this.emit(Runtime.SCRIPT_GLOW_OFF, {id: topBlockId}); |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
emitBlockDragUpdate (areBlocksOverGui) { |
|
this.emit(Runtime.BLOCK_DRAG_UPDATE, areBlocksOverGui); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
emitBlockEndDrag (blocks, topBlockId) { |
|
this.emit(Runtime.BLOCK_DRAG_END, blocks, topBlockId); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
visualReport (blockId, value) { |
|
this.emit(Runtime.VISUAL_REPORT, {id: blockId, value}); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
requestAddMonitor (monitor) { |
|
const id = monitor.get('id'); |
|
if (!this.requestUpdateMonitor(monitor)) { |
|
|
|
this._monitorState = this._monitorState.set(id, monitor); |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
requestUpdateMonitor (monitor) { |
|
const id = monitor.get('id'); |
|
if (this._monitorState.has(id)) { |
|
this._monitorState = |
|
|
|
this._monitorState.set(id, this._monitorState.get(id).mergeWith((prev, next) => { |
|
if (typeof next === 'undefined' || next === null) { |
|
return prev; |
|
} |
|
return next; |
|
}, monitor)); |
|
return true; |
|
} |
|
return false; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
requestRemoveMonitor (monitorId) { |
|
this._monitorState = this._monitorState.delete(monitorId); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
requestHideMonitor (monitorId) { |
|
return this.requestUpdateMonitor(new Map([ |
|
['id', monitorId], |
|
['visible', false] |
|
])); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
requestShowMonitor (monitorId) { |
|
return this.requestUpdateMonitor(new Map([ |
|
['id', monitorId], |
|
['visible', true] |
|
])); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
requestRemoveMonitorByTargetId (targetId) { |
|
this._monitorState = this._monitorState.filterNot(value => value.targetId === targetId); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
getTargetById (targetId) { |
|
for (let i = 0; i < this.targets.length; i++) { |
|
const target = this.targets[i]; |
|
if (target.id === targetId) { |
|
return target; |
|
} |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
getSpriteTargetByName (spriteName) { |
|
const json = validateJSON(spriteName); |
|
if (json.id) return this.getTargetById(json.id); |
|
for (let i = 0; i < this.targets.length; i++) { |
|
const target = this.targets[i]; |
|
if (target.isStage) { |
|
continue; |
|
} |
|
if (target.sprite && target.sprite.name === spriteName) { |
|
return target; |
|
} |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
getTargetByDrawableId (drawableID) { |
|
for (let i = 0; i < this.targets.length; i++) { |
|
const target = this.targets[i]; |
|
if (target.drawableID === drawableID) return target; |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
changeCloneCounter (changeAmount) { |
|
this._cloneCounter += changeAmount; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
clonesAvailable () { |
|
return this._cloneCounter < this.runtimeOptions.maxClones; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
emitProjectLoaded () { |
|
for (const target of this.targets) { |
|
for (const varId in target.variables) { |
|
const variable = target.variables[varId]; |
|
if (variable.type === Variable.LIST_TYPE) { |
|
for (const idx in variable.value) { |
|
const item = variable.value[idx]; |
|
if (item.customType) { |
|
const {deserialize} = this.serializers[item.typeId]; |
|
variable.value[idx] = deserialize(item.serialized, target); |
|
} |
|
} |
|
} |
|
if (variable.value?.customType) { |
|
const customData = variable.value; |
|
const {deserialize} = this.serializers[customData.typeId]; |
|
variable.value = deserialize(customData.serialized, target); |
|
} |
|
} |
|
} |
|
this.emit(Runtime.PROJECT_LOADED); |
|
} |
|
|
|
|
|
|
|
|
|
emitProjectChanged () { |
|
this.emit(Runtime.PROJECT_CHANGED); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
fireTargetWasCreated (newTarget, sourceTarget) { |
|
this.emit('targetWasCreated', newTarget, sourceTarget); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
fireTargetWasRemoved (target) { |
|
this.emit('targetWasRemoved', target); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
getBranchAndTarget (id, branchId) { |
|
for (const target of this.targets) { |
|
const result = target.blocks.getBranch(id, branchId); |
|
if (result) { |
|
return [result, target]; |
|
} |
|
} |
|
return null; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
getCamera(screen) { |
|
if (typeof this.cameraStates[screen] !== 'object') { |
|
this.cameraStates[screen] = { |
|
pos: [0, 0], |
|
dir: 0, |
|
scale: 1 |
|
}; |
|
} |
|
return this.cameraStates[screen]; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
updateCamera(screen, state, silent) { |
|
if (state.dir) state.dir = MathUtil.wrapClamp(state.dir, -179, 180); |
|
if (typeof this.cameraStates[screen] !== 'object') { |
|
this.cameraStates[screen] = { |
|
pos: [0, 0], |
|
dir: 0, |
|
scale: 1 |
|
}; |
|
} |
|
this.cameraStates[screen] = state = |
|
Object.assign(this.cameraStates[screen], state); |
|
if (!silent ?? state.silent) this.emitCameraChanged(screen); |
|
} |
|
emitCameraChanged(screen) { |
|
for (let i = 0; i < this.targets.length; i++) |
|
if (this.targets[i].cameraBound === screen) |
|
this.targets[i].cameraUpdateEvent(); |
|
this.emit(Runtime.CAMERA_CHANGED, screen); |
|
this.requestRedraw(); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
getTargetForStage () { |
|
if (this._stageTarget) { |
|
return this._stageTarget; |
|
} |
|
for (let i = 0; i < this.targets.length; i++) { |
|
const target = this.targets[i]; |
|
if (target.isStage) { |
|
this._stageTarget = target; |
|
return target; |
|
} |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
getEditingTarget () { |
|
return this._editingTarget; |
|
} |
|
|
|
getAllVarNamesOfType (varType) { |
|
let varNames = []; |
|
for (const target of this.targets) { |
|
const targetVarNames = target.getAllVariableNamesInScopeByType(varType, true); |
|
varNames = varNames.concat(targetVarNames); |
|
} |
|
return varNames; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
getLabelForOpcode (extendedOpcode) { |
|
const [category, opcode] = StringUtil.splitFirst(extendedOpcode, '_'); |
|
if (!(category && opcode)) return; |
|
|
|
const categoryInfo = this._blockInfo.find(ci => ci.id === category); |
|
if (!categoryInfo) return; |
|
|
|
const block = categoryInfo.blocks.find(b => b.info.opcode === opcode); |
|
if (!block) return; |
|
|
|
const categoryInstance = this[`ext_${category}`]; |
|
let labelFn = block.info.labelFn ? categoryInstance[block.info.labelFn] : undefined; |
|
|
|
|
|
return { |
|
category: block.info.color1 ?? categoryInfo.color1 ?? "extension", |
|
label: block.info.label ?? `${categoryInfo.name}: ${block.info.text}`, |
|
labelFn, |
|
}; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
createNewGlobalVariable (variableName, optVarId, optVarType) { |
|
const varType = (typeof optVarType === 'string') ? optVarType : Variable.SCALAR_TYPE; |
|
const allVariableNames = this.getAllVarNamesOfType(varType); |
|
const newName = StringUtil.unusedName(variableName, allVariableNames); |
|
|
|
const variable = this.newVariableInstance(varType, optVarId || uid(), newName); |
|
const stage = this.getTargetForStage(); |
|
stage.variables[variable.id] = variable; |
|
return variable; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
requestRedraw () { |
|
this.redrawRequested = true; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
requestTargetsUpdate (target) { |
|
if (!target.isOriginal) return; |
|
this._refreshTargets = true; |
|
} |
|
|
|
|
|
|
|
|
|
requestBlocksUpdate () { |
|
this.emit(Runtime.BLOCKS_NEED_UPDATE); |
|
} |
|
|
|
|
|
|
|
|
|
requestToolboxExtensionsUpdate () { |
|
this.emit(Runtime.TOOLBOX_EXTENSIONS_NEED_UPDATE); |
|
} |
|
|
|
|
|
|
|
|
|
start () { |
|
|
|
if (this.frameLoop.running) return; |
|
this.frameLoop.start(); |
|
this.emit(Runtime.RUNTIME_STARTED); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
stop () { |
|
if (!this.frameLoop.running) { |
|
return; |
|
} |
|
this.frameLoop.stop(); |
|
this.emit(Runtime.RUNTIME_STOPPED); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
enableProfiling (onFrame) { |
|
if (Profiler.available()) { |
|
this.profiler = new Profiler(onFrame); |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
disableProfiling () { |
|
this.profiler = null; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
updateCurrentMSecs () { |
|
this.currentMSecs = Date.now(); |
|
} |
|
|
|
updatePrivacy () { |
|
const enforceRestrictions = ( |
|
this.enforcePrivacy && |
|
Object.values(this.externalCommunicationMethods).some(i => i) |
|
); |
|
if (this.renderer && this.renderer.setPrivateSkinAccess) { |
|
this.renderer.setPrivateSkinAccess(!enforceRestrictions); |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
setEnforcePrivacy (enabled) { |
|
this.enforcePrivacy = enabled; |
|
this.updatePrivacy(); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
setExternalCommunicationMethod (method, enabled) { |
|
if (!Object.prototype.hasOwnProperty.call(this.externalCommunicationMethods, method)) { |
|
throw new Error(`Unknown method: ${method}`); |
|
} |
|
this.externalCommunicationMethods[method] = enabled; |
|
this.updatePrivacy(); |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
module.exports = Runtime; |
|
|