From ec1979fe2b2f3a844bee617004469f570c56286d Mon Sep 17 00:00:00 2001 From: BenPaoDeXiaoZhi Date: Sun, 20 Jul 2025 22:09:50 +0800 Subject: [PATCH 01/28] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E4=BA=86=E8=B7=B3?= =?UTF-8?q?=E8=BD=AC=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/l10n/en.json | 5 +- src/l10n/zh-cn.json | 5 +- src/plugins-entry.ts | 1 + src/plugins-manifest.ts | 2 + src/plugins/find-definition/index.js | 83 +++++++++++++++++++++++++ src/plugins/find-definition/manifest.ts | 10 +++ src/plugins/find-definition/styles.less | 0 src/plugins/plugins-manager/index.tsx | 1 + 8 files changed, 105 insertions(+), 2 deletions(-) create mode 100644 src/plugins/find-definition/index.js create mode 100644 src/plugins/find-definition/manifest.ts create mode 100644 src/plugins/find-definition/styles.less diff --git a/src/l10n/en.json b/src/l10n/en.json index 6196415..474703a 100644 --- a/src/l10n/en.json +++ b/src/l10n/en.json @@ -283,5 +283,8 @@ "plugins.cleanPro.description": "Clean Blocks Pro! Quickly clean headless blocks~", "plugins.cleanPro.docs": "###### Plugin Usage Instructions\nRight-click in the code area, select【Clean Headless Blocks】to delete all【blocks without head connections】and【head blocks without subsequent connections】in the current character\n###### Plugin Usage Background\n1.Reduce test block accumulation to reduce lag\n2.Increase code readability\n3.Facilitate sharing, reduce project file size\n4.When creating a hot update for a work, it can be used to purify the work file, preventing headless blocks from interfering\n 5.……", "plugins.cleanPro.cleanHeadlessBlocks": "Clean Headless Blocks", - "plugins.cleanPro.docs.title": "Plugin Doc" + "plugins.cleanPro.docs.title": "Plugin Doc", + "plugins.findDefinition.name": "find definition of custom block", + "plugins.findDefinition.description": "Right-click on a custom block in the code area and select【Jump To Definition】to jump to the definition location of that custom block.", + "plugins.findDefinition.goToDefinition": "Jump To Definition" } diff --git a/src/l10n/zh-cn.json b/src/l10n/zh-cn.json index 5184016..1da901e 100644 --- a/src/l10n/zh-cn.json +++ b/src/l10n/zh-cn.json @@ -284,5 +284,8 @@ "plugins.cleanPro.description": "整理积木 Pro!快速清理无头积木~", "plugins.cleanPro.docs": "###### 插件使用方法\n在代码区按下【右键】,点击【清理无头块】即可删除当前角色内全部【没有头积木拼接的积木】和【没有后续拼接的头积木】\n###### 插件使用背景\n1.减少测试块堆积,以减少卡顿\n2.增加代码可读性\n3.便于分享,减少工程文件体积\n4.制作作品热更新时,可用于净化作品文件,防止无头块干扰\n 5.……", "plugins.cleanPro.cleanHeadlessBlocks": "清理无头块", - "plugins.cleanPro.docs.title": "插件文档" + "plugins.cleanPro.docs.title": "插件文档", + "plugins.findDefinition.name": "查找自定义块的定义位置", + "plugins.findDefinition.description": "在代码区右键单击自定义块,选择【跳转到定义】即可跳转到该自定义块的定义位置。", + "plugins.findDefinition.goToDefinition": "跳转到定义" } diff --git a/src/plugins-entry.ts b/src/plugins-entry.ts index f280c6f..2eaf5da 100644 --- a/src/plugins-entry.ts +++ b/src/plugins-entry.ts @@ -26,4 +26,5 @@ export default { "data-category-tweaks": () => import(/* webpackChunkName: "plugin-data-category-tweaks" */ "plugins/data-category-tweaks"), "mobile-code-batch-select": () => import(/* webpackChunkName: "plugin-mobile-code-batch-select" */ "src/plugins/mobile-code-batch-select"), "clean-pro": () => import(/* webpackChunkName: "plugin-clean-pro" */ "src/plugins/clean-pro"), + "find-definition": () => import(/* webpackChunkName: "plugin-find-definition" */ "src/plugins/find-definition"), } as const; diff --git a/src/plugins-manifest.ts b/src/plugins-manifest.ts index e289d10..1c00270 100644 --- a/src/plugins-manifest.ts +++ b/src/plugins-manifest.ts @@ -22,6 +22,7 @@ import costumePiskel from "src/plugins/costume-piskel/manifest"; import dataCategoryTweaks from "plugins/data-category-tweaks/manifest"; import mobileCodeBatchSelect from "src/plugins/mobile-code-batch-select/manifest"; import cleanPro from "src/plugins/clean-pro/manifest"; +import findDefinition from "src/plugins/find-definition/manifest"; export default { folder, @@ -48,4 +49,5 @@ export default { "data-category-tweaks": dataCategoryTweaks, "mobile-code-batch-select": mobileCodeBatchSelect, "clean-pro": cleanPro, + "find-definition": findDefinition, }; diff --git a/src/plugins/find-definition/index.js b/src/plugins/find-definition/index.js new file mode 100644 index 0000000..890392e --- /dev/null +++ b/src/plugins/find-definition/index.js @@ -0,0 +1,83 @@ +let PROTOTYPE_OPCODE; +import { scrollBlockIntoView } from "utils/block-helper"; +const goToDefinition = (procCode,vm,workspace) => { + let prototypeBlockInTarget,targetId; + for(let target of vm.runtime.targets){ + if(target.id !== vm.editingTarget.id && !target.sprite.name.startsWith('#modules/')){ + continue + } + console.log(target.blocks) + for(let block of Object.values(target.blocks._blocks)){ + if(block.opcode === PROTOTYPE_OPCODE && (block.mutation.isglobal || target.id === vm.editingTarget.id) && block.mutation.proccode === procCode){ + prototypeBlockInTarget = block; + targetId = target.id; + break; + } + } + } + if(!prototypeBlockInTarget){ + console.warn('没有找到定义块,无法跳转') + return; + } + if(targetId !== vm.editingTarget.id){ + console.log('切换目标',targetId) + vm.setEditingTarget(targetId); + } + console.log('prototype block',workspace.blockDB_[prototypeBlockInTarget.id]) + const prototypeBlock = workspace.blockDB_[prototypeBlockInTarget.id] + const defineBlock = prototypeBlock.parentBlock_ + scrollBlockIntoView(defineBlock,workspace); +} +const handleGoToDefinition = function(vm,blockly){ + const procCode = this.procCode_; + console.log('被点了',procCode) + console.log(vm.runtime) + if(!procCode){ + console.warn('没有procCode,无法跳转') + return; + } + const target = vm.editingTarget; + goToDefinition(procCode,vm,blockly.getMainWorkspace()); +} +const FindDefinition = ({blockly,vm,registerSettings,msg}) => { + console.log(blockly,vm,registerSettings) + if(blockly.Blocks[blockly.PROCEDURES_CALL_BLOCK_TYPE]){ + console.log('检测到自定义快,可以替换blockly') + PROTOTYPE_OPCODE = blockly.PROCEDURES_PROTOTYPE_BLOCK_TYPE + const ctx_menu_ext = blockly.ScratchBlocks.VerticalExtensions.PROCEDURE_CALL_CONTEXTMENU + ctx_menu_ext._orig = ctx_menu_ext.customContextMenu + ctx_menu_ext.customContextMenu = function(menuOptions){ + ctx_menu_ext._orig.call(this,menuOptions)//block sharing插件的插入方式不太对,会把ui顶开,还是让白猫来解决吧 2025/7/20 + menuOptions.push({ + 'text':msg("plugins.findDefinition.goToDefinition"), + 'enabled':true, + 'callback':handleGoToDefinition.bind(this,vm,blockly), + }) + + } + } + const register = registerSettings( + msg("plugins.findDefinition.name"), + 'plugin-find-definition', + [ + { + key: "plugin-find-definition", + label: msg("plugins.findDefinition.name"), + description: msg("plugins.findDefinition.description"), + items:[] + } + ], + '' + ); + return { + dispose: () => { + /** Remove some side effects */ + const ctx_menu_ext = blockly.ScratchBlocks.VerticalExtensions.PROCEDURE_CALL_CONTEXTMENU + ctx_menu_ext.customContextMenu = ctx_menu_ext._orig + ctx_menu_ext._orig = undefined + register.dispose() + }, + }; +}; + +export default FindDefinition; diff --git a/src/plugins/find-definition/manifest.ts b/src/plugins/find-definition/manifest.ts new file mode 100644 index 0000000..b73d782 --- /dev/null +++ b/src/plugins/find-definition/manifest.ts @@ -0,0 +1,10 @@ +export default { + name: "find-definition", + type: "function", + description: "a plugin that can find where the definition of custom block is", + credits: [ + { + name: "BenPaoDeXiaoZhi", + }, + ], +}; diff --git a/src/plugins/find-definition/styles.less b/src/plugins/find-definition/styles.less new file mode 100644 index 0000000..e69de29 diff --git a/src/plugins/plugins-manager/index.tsx b/src/plugins/plugins-manager/index.tsx index 870e90d..1576f65 100644 --- a/src/plugins/plugins-manager/index.tsx +++ b/src/plugins/plugins-manager/index.tsx @@ -12,6 +12,7 @@ import styles from "./styles.less"; const ALL_PLUGINS = Object.keys(Plugins); // When the line numbers of the variables below change, plopfile.js needs to be updated. const DEFAULT_INJECT_PLUGINS = [ + "find-definition", "block-sharing", "custom-plugin", "folder", From 77f843aab6f94e4ff753b4f24fc88bd826d0739c Mon Sep 17 00:00:00 2001 From: BenPaoDeXiaoZhi Date: Mon, 21 Jul 2025 14:09:16 +0800 Subject: [PATCH 02/28] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E4=BA=86=E5=90=8D?= =?UTF-8?q?=E7=A7=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/l10n/en.json | 2 +- src/l10n/zh-cn.json | 2 +- src/plugins/find-definition/index.js | 173 +++++++++++++++------------ 3 files changed, 96 insertions(+), 81 deletions(-) diff --git a/src/l10n/en.json b/src/l10n/en.json index 474703a..8e4015b 100644 --- a/src/l10n/en.json +++ b/src/l10n/en.json @@ -284,7 +284,7 @@ "plugins.cleanPro.docs": "###### Plugin Usage Instructions\nRight-click in the code area, select【Clean Headless Blocks】to delete all【blocks without head connections】and【head blocks without subsequent connections】in the current character\n###### Plugin Usage Background\n1.Reduce test block accumulation to reduce lag\n2.Increase code readability\n3.Facilitate sharing, reduce project file size\n4.When creating a hot update for a work, it can be used to purify the work file, preventing headless blocks from interfering\n 5.……", "plugins.cleanPro.cleanHeadlessBlocks": "Clean Headless Blocks", "plugins.cleanPro.docs.title": "Plugin Doc", - "plugins.findDefinition.name": "find definition of custom block", + "plugins.findDefinition.title": "find definition of custom block", "plugins.findDefinition.description": "Right-click on a custom block in the code area and select【Jump To Definition】to jump to the definition location of that custom block.", "plugins.findDefinition.goToDefinition": "Jump To Definition" } diff --git a/src/l10n/zh-cn.json b/src/l10n/zh-cn.json index 1da901e..277a86a 100644 --- a/src/l10n/zh-cn.json +++ b/src/l10n/zh-cn.json @@ -285,7 +285,7 @@ "plugins.cleanPro.docs": "###### 插件使用方法\n在代码区按下【右键】,点击【清理无头块】即可删除当前角色内全部【没有头积木拼接的积木】和【没有后续拼接的头积木】\n###### 插件使用背景\n1.减少测试块堆积,以减少卡顿\n2.增加代码可读性\n3.便于分享,减少工程文件体积\n4.制作作品热更新时,可用于净化作品文件,防止无头块干扰\n 5.……", "plugins.cleanPro.cleanHeadlessBlocks": "清理无头块", "plugins.cleanPro.docs.title": "插件文档", - "plugins.findDefinition.name": "查找自定义块的定义位置", + "plugins.findDefinition.title": "查找自定义块的定义位置", "plugins.findDefinition.description": "在代码区右键单击自定义块,选择【跳转到定义】即可跳转到该自定义块的定义位置。", "plugins.findDefinition.goToDefinition": "跳转到定义" } diff --git a/src/plugins/find-definition/index.js b/src/plugins/find-definition/index.js index 890392e..41ed34c 100644 --- a/src/plugins/find-definition/index.js +++ b/src/plugins/find-definition/index.js @@ -1,83 +1,98 @@ -let PROTOTYPE_OPCODE; +let PROTOTYPE_OPCODE, CALL_OPCODE, CALL_RETURN_OPCODE, CTX_MENU_EXT; import { scrollBlockIntoView } from "utils/block-helper"; -const goToDefinition = (procCode,vm,workspace) => { - let prototypeBlockInTarget,targetId; - for(let target of vm.runtime.targets){ - if(target.id !== vm.editingTarget.id && !target.sprite.name.startsWith('#modules/')){ - continue - } - console.log(target.blocks) - for(let block of Object.values(target.blocks._blocks)){ - if(block.opcode === PROTOTYPE_OPCODE && (block.mutation.isglobal || target.id === vm.editingTarget.id) && block.mutation.proccode === procCode){ - prototypeBlockInTarget = block; - targetId = target.id; - break; - } - } - } - if(!prototypeBlockInTarget){ - console.warn('没有找到定义块,无法跳转') - return; - } - if(targetId !== vm.editingTarget.id){ - console.log('切换目标',targetId) - vm.setEditingTarget(targetId); - } - console.log('prototype block',workspace.blockDB_[prototypeBlockInTarget.id]) - const prototypeBlock = workspace.blockDB_[prototypeBlockInTarget.id] - const defineBlock = prototypeBlock.parentBlock_ - scrollBlockIntoView(defineBlock,workspace); -} -const handleGoToDefinition = function(vm,blockly){ - const procCode = this.procCode_; - console.log('被点了',procCode) - console.log(vm.runtime) - if(!procCode){ - console.warn('没有procCode,无法跳转') - return; - } - const target = vm.editingTarget; - goToDefinition(procCode,vm,blockly.getMainWorkspace()); -} -const FindDefinition = ({blockly,vm,registerSettings,msg}) => { - console.log(blockly,vm,registerSettings) - if(blockly.Blocks[blockly.PROCEDURES_CALL_BLOCK_TYPE]){ - console.log('检测到自定义快,可以替换blockly') - PROTOTYPE_OPCODE = blockly.PROCEDURES_PROTOTYPE_BLOCK_TYPE - const ctx_menu_ext = blockly.ScratchBlocks.VerticalExtensions.PROCEDURE_CALL_CONTEXTMENU - ctx_menu_ext._orig = ctx_menu_ext.customContextMenu - ctx_menu_ext.customContextMenu = function(menuOptions){ - ctx_menu_ext._orig.call(this,menuOptions)//block sharing插件的插入方式不太对,会把ui顶开,还是让白猫来解决吧 2025/7/20 - menuOptions.push({ - 'text':msg("plugins.findDefinition.goToDefinition"), - 'enabled':true, - 'callback':handleGoToDefinition.bind(this,vm,blockly), - }) - - } - } - const register = registerSettings( - msg("plugins.findDefinition.name"), - 'plugin-find-definition', - [ - { - key: "plugin-find-definition", - label: msg("plugins.findDefinition.name"), - description: msg("plugins.findDefinition.description"), - items:[] - } - ], - '' - ); - return { - dispose: () => { - /** Remove some side effects */ - const ctx_menu_ext = blockly.ScratchBlocks.VerticalExtensions.PROCEDURE_CALL_CONTEXTMENU - ctx_menu_ext.customContextMenu = ctx_menu_ext._orig - ctx_menu_ext._orig = undefined - register.dispose() - }, - }; +const goToDefinition = (procCode, vm, workspace) => { + let prototypeBlockInTarget, targetId; + for (let target of vm.runtime.targets) { + if (target.id !== vm.editingTarget.id && !target.sprite.name.startsWith("#modules/")) { + continue; + } + console.log(target.blocks); + for (let block of Object.values(target.blocks._blocks)) { + if ( + block.opcode === PROTOTYPE_OPCODE && + (block.mutation.isglobal || target.id === vm.editingTarget.id) && + block.mutation.proccode === procCode + ) { + prototypeBlockInTarget = block; + targetId = target.id; + break; + } + } + } + if (!prototypeBlockInTarget) { + console.warn("没有找到定义块,无法跳转"); + return; + } + if (targetId !== vm.editingTarget.id) { + console.log("切换目标", targetId); + vm.setEditingTarget(targetId); + } + console.log("prototype block", workspace.blockDB_[prototypeBlockInTarget.id]); + const prototypeBlock = workspace.blockDB_[prototypeBlockInTarget.id]; + const defineBlock = prototypeBlock.parentBlock_; + scrollBlockIntoView(defineBlock, workspace); +}; +const handleGoToDefinition = function (vm, blockly) { + const procCode = this.procCode_; + console.log("被点了", procCode); + debugger + if (!procCode) { + console.warn("没有procCode,无法跳转"); + return; + } + goToDefinition(procCode, vm, blockly.getMainWorkspace()); +}; +const FindDefinition = ({ blockly, vm, registerSettings, msg }) => { + console.log(blockly, vm, registerSettings); + if (blockly.Blocks[blockly.PROCEDURES_CALL_BLOCK_TYPE]) { + console.log("检测到自定义快,可以替换blockly"); + PROTOTYPE_OPCODE = blockly.PROCEDURES_PROTOTYPE_BLOCK_TYPE; + CALL_OPCODE = blockly.PROCEDURES_CALL_BLOCK_TYPE; + CALL_RETURN_OPCODE = blockly.PROCEDURES_CALL_WITH_RETURN_BLOCK_TYPE; + CTX_MENU_EXT = blockly.ScratchBlocks.VerticalExtensions.PROCEDURE_CALL_CONTEXTMENU; + CTX_MENU_EXT._orig = CTX_MENU_EXT.customContextMenu; + CTX_MENU_EXT.customContextMenu = function (menuOptions) { + if(CTX_MENU_EXT._orig === undefined) { + console.warn("菜单需刷新"); + return; + } + CTX_MENU_EXT._orig.call(this, menuOptions); + menuOptions.push({ + text: msg("plugins.findDefinition.goToDefinition"), + enabled: true, + callback: handleGoToDefinition.bind(this, vm, blockly), + }); + }; + + } + const register = registerSettings( + msg("plugins.findDefinition.title"), + "plugin-find-definition", + [ + { + key: "plugin-find-definition", + label: msg("plugins.findDefinition.title"), + description: msg("plugins.findDefinition.description"), + items: [], + }, + ], + "", + ); + return { + dispose: () => { + /** Remove some side effects */ + CTX_MENU_EXT = blockly.ScratchBlocks.VerticalExtensions.PROCEDURE_CALL_CONTEXTMENU; + console.log(CTX_MENU_EXT._orig === CTX_MENU_EXT.customContextMenu); + CTX_MENU_EXT.customContextMenu = CTX_MENU_EXT._orig; + CTX_MENU_EXT._orig = undefined; + const workspace = blockly.getMainWorkspace(); + if (!workspace) { + console.warn("没有工作区,无法删除原有菜单"); + return; + } + register.dispose(); + }, + }; }; export default FindDefinition; From f0e50d57e892e14c25ca67fec04c30ffe3a74bac Mon Sep 17 00:00:00 2001 From: BenPaoDeXiaoZhi Date: Tue, 22 Jul 2025 12:55:33 +0800 Subject: [PATCH 03/28] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E4=BA=86=E8=BF=94?= =?UTF-8?q?=E5=9B=9E=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/plugins/find-definition/index.js | 66 +++++++++++++++++++++++++--- 1 file changed, 59 insertions(+), 7 deletions(-) diff --git a/src/plugins/find-definition/index.js b/src/plugins/find-definition/index.js index 41ed34c..cba2c84 100644 --- a/src/plugins/find-definition/index.js +++ b/src/plugins/find-definition/index.js @@ -1,6 +1,20 @@ let PROTOTYPE_OPCODE, CALL_OPCODE, CALL_RETURN_OPCODE, CTX_MENU_EXT; import { scrollBlockIntoView } from "utils/block-helper"; -const goToDefinition = (procCode, vm, workspace) => { +const getBlockInMainWorkspace = (blockly, blockId) => { + const workspace = blockly.getMainWorkspace(); + if (!workspace) { + console.warn("没有工作区,无法获取块"); + return null; + } + const block = workspace.blockDB_[blockId]; + if (!block) { + console.warn("没有找到块", blockId); + return null; + } + return block; +}; +const goToDefinition = (call_block, vm, workspace, blockly) => { + const procCode = call_block.procCode_ let prototypeBlockInTarget, targetId; for (let target of vm.runtime.targets) { if (target.id !== vm.editingTarget.id && !target.sprite.name.startsWith("#modules/")) { @@ -10,7 +24,7 @@ const goToDefinition = (procCode, vm, workspace) => { for (let block of Object.values(target.blocks._blocks)) { if ( block.opcode === PROTOTYPE_OPCODE && - (block.mutation.isglobal || target.id === vm.editingTarget.id) && + (block.mutation.isglobal === 'true' || target.id === vm.editingTarget.id) && block.mutation.proccode === procCode ) { prototypeBlockInTarget = block; @@ -23,14 +37,41 @@ const goToDefinition = (procCode, vm, workspace) => { console.warn("没有找到定义块,无法跳转"); return; } + const src_target_id = vm.editingTarget.id; + const dst_target_id = targetId; if (targetId !== vm.editingTarget.id) { console.log("切换目标", targetId); vm.setEditingTarget(targetId); } - console.log("prototype block", workspace.blockDB_[prototypeBlockInTarget.id]); - const prototypeBlock = workspace.blockDB_[prototypeBlockInTarget.id]; + console.log("prototype block", getBlockInMainWorkspace(blockly, prototypeBlockInTarget.id)); + const prototypeBlock = getBlockInMainWorkspace(blockly, prototypeBlockInTarget.id); const defineBlock = prototypeBlock.parentBlock_; scrollBlockIntoView(defineBlock, workspace); + class MoveWorkspaceEvent extends blockly.Events.Abstract { + constructor(src_target_id, src_block_id, dst_target_id, dst_block_id, workspace) { + super() + this.type = 'GOTO_DEF' + this.src_target_id = src_target_id + this.src_block_id = src_block_id + this.dst_target_id = dst_target_id + this.dst_block_id = dst_block_id + this.workspace = workspace + this.recordUndo = true + } + run(redo) { + console.log(redo, this) + if (redo) { + vm.setEditingTarget(this.dst_target_id); + scrollBlockIntoView(getBlockInMainWorkspace(blockly, this.dst_block_id), this.workspace) + } + else { + vm.setEditingTarget(this.src_target_id); + scrollBlockIntoView(getBlockInMainWorkspace(blockly, this.src_block_id), this.workspace) + } + } + } + console.log(blockly.Events.isEnabled()) + workspace.fireChangeListener(new MoveWorkspaceEvent(src_target_id, call_block.id, dst_target_id, defineBlock.id, workspace)) }; const handleGoToDefinition = function (vm, blockly) { const procCode = this.procCode_; @@ -40,8 +81,17 @@ const handleGoToDefinition = function (vm, blockly) { console.warn("没有procCode,无法跳转"); return; } - goToDefinition(procCode, vm, blockly.getMainWorkspace()); + goToDefinition(this, vm, blockly.getMainWorkspace(), blockly); }; +const refreshBlocksWithOpcodes = (blockly, opcodes) => { + for (let block of blockly.getMainWorkspace().getAllBlocks()) { + if (opcodes.includes(block.type)) { + console.log("刷新块", block); + block.customContextMenu = CTX_MENU_EXT.customContextMenu + } + } + blockly.getMainWorkspace().getToolbox().showAll_() +} const FindDefinition = ({ blockly, vm, registerSettings, msg }) => { console.log(blockly, vm, registerSettings); if (blockly.Blocks[blockly.PROCEDURES_CALL_BLOCK_TYPE]) { @@ -52,7 +102,7 @@ const FindDefinition = ({ blockly, vm, registerSettings, msg }) => { CTX_MENU_EXT = blockly.ScratchBlocks.VerticalExtensions.PROCEDURE_CALL_CONTEXTMENU; CTX_MENU_EXT._orig = CTX_MENU_EXT.customContextMenu; CTX_MENU_EXT.customContextMenu = function (menuOptions) { - if(CTX_MENU_EXT._orig === undefined) { + if (CTX_MENU_EXT._orig === undefined) { console.warn("菜单需刷新"); return; } @@ -63,7 +113,8 @@ const FindDefinition = ({ blockly, vm, registerSettings, msg }) => { callback: handleGoToDefinition.bind(this, vm, blockly), }); }; - + refreshBlocksWithOpcodes(blockly, [CALL_OPCODE, CALL_RETURN_OPCODE]); + } const register = registerSettings( msg("plugins.findDefinition.title"), @@ -90,6 +141,7 @@ const FindDefinition = ({ blockly, vm, registerSettings, msg }) => { console.warn("没有工作区,无法删除原有菜单"); return; } + refreshBlocksWithOpcodes(blockly, [CALL_OPCODE, CALL_RETURN_OPCODE]); register.dispose(); }, }; From f4725cc954d209c3f970df8e8ad609eeb323b2c0 Mon Sep 17 00:00:00 2001 From: BenPaoDeXiaoZhi Date: Tue, 22 Jul 2025 13:12:13 +0800 Subject: [PATCH 04/28] =?UTF-8?q?=E6=B8=85=E9=99=A4=E4=BA=86=E4=B8=80?= =?UTF-8?q?=E4=BA=9B=E6=97=A5=E5=BF=97=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/plugins/find-definition/index.js | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/src/plugins/find-definition/index.js b/src/plugins/find-definition/index.js index cba2c84..d52ae0d 100644 --- a/src/plugins/find-definition/index.js +++ b/src/plugins/find-definition/index.js @@ -40,10 +40,8 @@ const goToDefinition = (call_block, vm, workspace, blockly) => { const src_target_id = vm.editingTarget.id; const dst_target_id = targetId; if (targetId !== vm.editingTarget.id) { - console.log("切换目标", targetId); vm.setEditingTarget(targetId); } - console.log("prototype block", getBlockInMainWorkspace(blockly, prototypeBlockInTarget.id)); const prototypeBlock = getBlockInMainWorkspace(blockly, prototypeBlockInTarget.id); const defineBlock = prototypeBlock.parentBlock_; scrollBlockIntoView(defineBlock, workspace); @@ -75,7 +73,6 @@ const goToDefinition = (call_block, vm, workspace, blockly) => { }; const handleGoToDefinition = function (vm, blockly) { const procCode = this.procCode_; - console.log("被点了", procCode); debugger if (!procCode) { console.warn("没有procCode,无法跳转"); @@ -86,14 +83,12 @@ const handleGoToDefinition = function (vm, blockly) { const refreshBlocksWithOpcodes = (blockly, opcodes) => { for (let block of blockly.getMainWorkspace().getAllBlocks()) { if (opcodes.includes(block.type)) { - console.log("刷新块", block); block.customContextMenu = CTX_MENU_EXT.customContextMenu } } blockly.getMainWorkspace().getToolbox().showAll_() } const FindDefinition = ({ blockly, vm, registerSettings, msg }) => { - console.log(blockly, vm, registerSettings); if (blockly.Blocks[blockly.PROCEDURES_CALL_BLOCK_TYPE]) { console.log("检测到自定义快,可以替换blockly"); PROTOTYPE_OPCODE = blockly.PROCEDURES_PROTOTYPE_BLOCK_TYPE; @@ -103,7 +98,7 @@ const FindDefinition = ({ blockly, vm, registerSettings, msg }) => { CTX_MENU_EXT._orig = CTX_MENU_EXT.customContextMenu; CTX_MENU_EXT.customContextMenu = function (menuOptions) { if (CTX_MENU_EXT._orig === undefined) { - console.warn("菜单需刷新"); + console.warn("菜单未刷新,可尝试切换角色"); return; } CTX_MENU_EXT._orig.call(this, menuOptions); From b5be7bbdc0c06ef601ca0ab158148c57cfb16856 Mon Sep 17 00:00:00 2001 From: BenPaoDeXiaoZhi Date: Tue, 22 Jul 2025 13:18:10 +0800 Subject: [PATCH 05/28] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=BA=86=E6=B3=A8?= =?UTF-8?q?=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/plugins/find-definition/index.js | 31 ++++++++++++++-------------- 1 file changed, 15 insertions(+), 16 deletions(-) diff --git a/src/plugins/find-definition/index.js b/src/plugins/find-definition/index.js index d52ae0d..b740a84 100644 --- a/src/plugins/find-definition/index.js +++ b/src/plugins/find-definition/index.js @@ -16,16 +16,16 @@ const getBlockInMainWorkspace = (blockly, blockId) => { const goToDefinition = (call_block, vm, workspace, blockly) => { const procCode = call_block.procCode_ let prototypeBlockInTarget, targetId; - for (let target of vm.runtime.targets) { + for (let target of vm.runtime.targets) {//遍历每一个角色,在模块或当前角色中搜索自制积木的定义块 if (target.id !== vm.editingTarget.id && !target.sprite.name.startsWith("#modules/")) { continue; } console.log(target.blocks); for (let block of Object.values(target.blocks._blocks)) { if ( - block.opcode === PROTOTYPE_OPCODE && - (block.mutation.isglobal === 'true' || target.id === vm.editingTarget.id) && - block.mutation.proccode === procCode + block.opcode === PROTOTYPE_OPCODE &&//如果是定义块 + (block.mutation.isglobal === 'true' || target.id === vm.editingTarget.id) &&//并且是全局的或当前角色 + block.mutation.proccode === procCode//并且定义块的procCode与调用块的procCode相同 ) { prototypeBlockInTarget = block; targetId = target.id; @@ -37,13 +37,13 @@ const goToDefinition = (call_block, vm, workspace, blockly) => { console.warn("没有找到定义块,无法跳转"); return; } - const src_target_id = vm.editingTarget.id; - const dst_target_id = targetId; + const src_target_id = vm.editingTarget.id;//记录调用自制积木的角色id + const dst_target_id = targetId;//记录定义自制积木的角色id if (targetId !== vm.editingTarget.id) { vm.setEditingTarget(targetId); } const prototypeBlock = getBlockInMainWorkspace(blockly, prototypeBlockInTarget.id); - const defineBlock = prototypeBlock.parentBlock_; + const defineBlock = prototypeBlock.parentBlock_;//prototype无法进行跳转,所以需要获取其父块definition scrollBlockIntoView(defineBlock, workspace); class MoveWorkspaceEvent extends blockly.Events.Abstract { constructor(src_target_id, src_block_id, dst_target_id, dst_block_id, workspace) { @@ -54,22 +54,20 @@ const goToDefinition = (call_block, vm, workspace, blockly) => { this.dst_target_id = dst_target_id this.dst_block_id = dst_block_id this.workspace = workspace - this.recordUndo = true + this.recordUndo = true//记录撤销 } run(redo) { - console.log(redo, this) if (redo) { vm.setEditingTarget(this.dst_target_id); - scrollBlockIntoView(getBlockInMainWorkspace(blockly, this.dst_block_id), this.workspace) + scrollBlockIntoView(getBlockInMainWorkspace(blockly, this.dst_block_id), this.workspace)//跳转至定义(要通过id获取,否则跨角色会获取失败) } else { vm.setEditingTarget(this.src_target_id); - scrollBlockIntoView(getBlockInMainWorkspace(blockly, this.src_block_id), this.workspace) + scrollBlockIntoView(getBlockInMainWorkspace(blockly, this.src_block_id), this.workspace)//跳转回引用 } } } - console.log(blockly.Events.isEnabled()) - workspace.fireChangeListener(new MoveWorkspaceEvent(src_target_id, call_block.id, dst_target_id, defineBlock.id, workspace)) + workspace.fireChangeListener(new MoveWorkspaceEvent(src_target_id, call_block.id, dst_target_id, defineBlock.id, workspace))//记录跳转事件 }; const handleGoToDefinition = function (vm, blockly) { const procCode = this.procCode_; @@ -98,11 +96,11 @@ const FindDefinition = ({ blockly, vm, registerSettings, msg }) => { CTX_MENU_EXT._orig = CTX_MENU_EXT.customContextMenu; CTX_MENU_EXT.customContextMenu = function (menuOptions) { if (CTX_MENU_EXT._orig === undefined) { - console.warn("菜单未刷新,可尝试切换角色"); + console.warn("菜单未刷新,可尝试切换角色");//一般不会运行,因为删除插件时会刷新 return; } - CTX_MENU_EXT._orig.call(this, menuOptions); - menuOptions.push({ + CTX_MENU_EXT._orig.call(this, menuOptions);//调用原有菜单 + menuOptions.push({//加入自定义菜单项 text: msg("plugins.findDefinition.goToDefinition"), enabled: true, callback: handleGoToDefinition.bind(this, vm, blockly), @@ -137,6 +135,7 @@ const FindDefinition = ({ blockly, vm, registerSettings, msg }) => { return; } refreshBlocksWithOpcodes(blockly, [CALL_OPCODE, CALL_RETURN_OPCODE]); + // TODO: 移除跳转事件 register.dispose(); }, }; From 43d9c2f96fcd82d255225bc16ae92636719d3503 Mon Sep 17 00:00:00 2001 From: BenPaoDeXiaoZhi Date: Tue, 22 Jul 2025 13:29:27 +0800 Subject: [PATCH 06/28] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E4=BA=86=E7=A7=BB?= =?UTF-8?q?=E9=99=A4=E8=B7=B3=E8=BD=AC=E4=BA=8B=E4=BB=B6=E7=9A=84=E5=8A=9F?= =?UTF-8?q?=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/plugins/find-definition/index.js | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/plugins/find-definition/index.js b/src/plugins/find-definition/index.js index b740a84..828ece9 100644 --- a/src/plugins/find-definition/index.js +++ b/src/plugins/find-definition/index.js @@ -135,7 +135,14 @@ const FindDefinition = ({ blockly, vm, registerSettings, msg }) => { return; } refreshBlocksWithOpcodes(blockly, [CALL_OPCODE, CALL_RETURN_OPCODE]); - // TODO: 移除跳转事件 + // workspace.clearUndo(); 我不想使用这个,因为会清除所有撤销记录 + // 可能导致用户无法撤销之前的操作 + // 但可以通过遍历undoStack并删除的方式来清除跳转事件 + const new_undo_stack = workspace.undoStack_.filter(event => event.type !== 'GOTO_DEF'); + workspace.undoStack_ = new_undo_stack; + //同时,也需要删除redoStack + const new_redo_stack = workspace.redoStack_.filter(event => event.type !== 'GOTO_DEF'); + workspace.redoStack_ = new_redo_stack; register.dispose(); }, }; From 03e77daea1140733ec89b9f68efe8ea603a68dd2 Mon Sep 17 00:00:00 2001 From: BenPaoDeXiaoZhi Date: Fri, 25 Jul 2025 15:59:12 +0800 Subject: [PATCH 07/28] =?UTF-8?q?=09modified:=20=20=20src/plugins/find-def?= =?UTF-8?q?inition/index.js=20=E8=A7=A3=E5=86=B3=E4=BA=86procode=E4=B8=BA?= =?UTF-8?q?=E7=A9=BA=E6=97=B6=E6=97=A0=E6=B3=95=E8=B7=B3=E8=BD=AC=E7=9A=84?= =?UTF-8?q?bug(=E8=B0=81=E9=97=B2=E7=9D=80=E6=B2=A1=E4=BA=8B=E6=8A=8A?= =?UTF-8?q?=E5=90=8D=E5=AD=97=E6=95=B4=E6=88=90=E7=A9=BA=E5=95=8A)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/plugins/find-definition/index.js | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/plugins/find-definition/index.js b/src/plugins/find-definition/index.js index 828ece9..b684d51 100644 --- a/src/plugins/find-definition/index.js +++ b/src/plugins/find-definition/index.js @@ -70,9 +70,7 @@ const goToDefinition = (call_block, vm, workspace, blockly) => { workspace.fireChangeListener(new MoveWorkspaceEvent(src_target_id, call_block.id, dst_target_id, defineBlock.id, workspace))//记录跳转事件 }; const handleGoToDefinition = function (vm, blockly) { - const procCode = this.procCode_; - debugger - if (!procCode) { + if (!this.getProcCode) { console.warn("没有procCode,无法跳转"); return; } From 3a545d6495c9279fd2396b54e9a7954c48051068 Mon Sep 17 00:00:00 2001 From: BenPaoDeXiaoZhi Date: Fri, 25 Jul 2025 16:51:44 +0800 Subject: [PATCH 08/28] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E4=BA=86=E5=88=A4?= =?UTF-8?q?=E6=96=AD=E9=80=BB=E8=BE=91=EF=BC=8C=E5=B0=9D=E8=AF=95=E5=8A=A0?= =?UTF-8?q?=E5=BF=AB=E6=90=9C=E7=B4=A2=E9=80=9F=E5=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/plugins/find-definition/index.js | 296 +++++++++++++++------------ 1 file changed, 162 insertions(+), 134 deletions(-) diff --git a/src/plugins/find-definition/index.js b/src/plugins/find-definition/index.js index b684d51..c3eb96d 100644 --- a/src/plugins/find-definition/index.js +++ b/src/plugins/find-definition/index.js @@ -1,149 +1,177 @@ let PROTOTYPE_OPCODE, CALL_OPCODE, CALL_RETURN_OPCODE, CTX_MENU_EXT; import { scrollBlockIntoView } from "utils/block-helper"; const getBlockInMainWorkspace = (blockly, blockId) => { - const workspace = blockly.getMainWorkspace(); - if (!workspace) { - console.warn("没有工作区,无法获取块"); - return null; - } - const block = workspace.blockDB_[blockId]; - if (!block) { - console.warn("没有找到块", blockId); - return null; - } - return block; + const workspace = blockly.getMainWorkspace(); + if (!workspace) { + console.warn("没有工作区,无法获取块"); + return null; + } + const block = workspace.blockDB_[blockId]; + if (!block) { + console.warn("没有找到块", blockId); + return null; + } + return block; }; const goToDefinition = (call_block, vm, workspace, blockly) => { - const procCode = call_block.procCode_ - let prototypeBlockInTarget, targetId; - for (let target of vm.runtime.targets) {//遍历每一个角色,在模块或当前角色中搜索自制积木的定义块 - if (target.id !== vm.editingTarget.id && !target.sprite.name.startsWith("#modules/")) { - continue; - } - console.log(target.blocks); - for (let block of Object.values(target.blocks._blocks)) { - if ( - block.opcode === PROTOTYPE_OPCODE &&//如果是定义块 - (block.mutation.isglobal === 'true' || target.id === vm.editingTarget.id) &&//并且是全局的或当前角色 - block.mutation.proccode === procCode//并且定义块的procCode与调用块的procCode相同 - ) { - prototypeBlockInTarget = block; - targetId = target.id; - break; - } - } - } - if (!prototypeBlockInTarget) { - console.warn("没有找到定义块,无法跳转"); - return; - } - const src_target_id = vm.editingTarget.id;//记录调用自制积木的角色id - const dst_target_id = targetId;//记录定义自制积木的角色id - if (targetId !== vm.editingTarget.id) { - vm.setEditingTarget(targetId); - } - const prototypeBlock = getBlockInMainWorkspace(blockly, prototypeBlockInTarget.id); - const defineBlock = prototypeBlock.parentBlock_;//prototype无法进行跳转,所以需要获取其父块definition - scrollBlockIntoView(defineBlock, workspace); - class MoveWorkspaceEvent extends blockly.Events.Abstract { - constructor(src_target_id, src_block_id, dst_target_id, dst_block_id, workspace) { - super() - this.type = 'GOTO_DEF' - this.src_target_id = src_target_id - this.src_block_id = src_block_id - this.dst_target_id = dst_target_id - this.dst_block_id = dst_block_id - this.workspace = workspace - this.recordUndo = true//记录撤销 - } - run(redo) { - if (redo) { - vm.setEditingTarget(this.dst_target_id); - scrollBlockIntoView(getBlockInMainWorkspace(blockly, this.dst_block_id), this.workspace)//跳转至定义(要通过id获取,否则跨角色会获取失败) - } - else { - vm.setEditingTarget(this.src_target_id); - scrollBlockIntoView(getBlockInMainWorkspace(blockly, this.src_block_id), this.workspace)//跳转回引用 - } - } - } - workspace.fireChangeListener(new MoveWorkspaceEvent(src_target_id, call_block.id, dst_target_id, defineBlock.id, workspace))//记录跳转事件 + const procCode = call_block.procCode_ + let prototypeBlockInTarget, targetId; + if (!call_block.isGlobal_) { + for (let block of Object.values(vm.editingTarget.blocks._blocks)) { + if ( + block.opcode === PROTOTYPE_OPCODE &&//如果是定义块 + block.mutation.proccode === procCode//并且定义块的procCode与调用块的procCode相同 + ) { + prototypeBlockInTarget = block; + targetId = vm.editingTarget.id; + break; + } + } + } else { + for (let target of vm.runtime.targets) {//遍历每一个角色,在模块或当前角色中搜索自制积木的定义块 + if (target.isModule) { + for (let block of Object.values(target.blocks._blocks)) { + if ( + block.opcode === PROTOTYPE_OPCODE &&//如果是定义块 + block.mutation.isglobal === 'true' &&//并且是全局的 + block.mutation.proccode === procCode//并且定义块的procCode与调用块的procCode相同 + ) { + prototypeBlockInTarget = block; + targetId = target.id; + break; + } + } + } + } + } + // for (let target of vm.runtime.targets) {//遍历每一个角色,在模块或当前角色中搜索自制积木的定义块 + // if (target.id !== vm.editingTarget.id && !target.isModule) { + // continue; + // } + // console.log(target.blocks); + // for (let block of Object.values(target.blocks._blocks)) { + // if ( + // block.opcode === PROTOTYPE_OPCODE &&//如果是定义块 + // (block.mutation.isglobal === 'true' || target.id === vm.editingTarget.id) &&//并且是全局的或当前角色 + // block.mutation.proccode === procCode//并且定义块的procCode与调用块的procCode相同 + // ) { + // prototypeBlockInTarget = block; + // targetId = target.id; + // break; + // } + // } + // } + if (!prototypeBlockInTarget) { + console.warn("没有找到定义块,无法跳转"); + return; + } + const src_target_id = vm.editingTarget.id;//记录调用自制积木的角色id + const dst_target_id = targetId;//记录定义自制积木的角色id + console.timeEnd('goToDef') + if (targetId !== vm.editingTarget.id) { + vm.setEditingTarget(targetId); + } + const prototypeBlock = getBlockInMainWorkspace(blockly, prototypeBlockInTarget.id); + const defineBlock = prototypeBlock.parentBlock_;//prototype无法进行跳转,所以需要获取其父块definition + scrollBlockIntoView(defineBlock, workspace); + class MoveWorkspaceEvent extends blockly.Events.Abstract { + constructor(src_target_id, src_block_id, dst_target_id, dst_block_id, workspace) { + super() + this.type = 'GOTO_DEF' + this.src_target_id = src_target_id + this.src_block_id = src_block_id + this.dst_target_id = dst_target_id + this.dst_block_id = dst_block_id + this.workspace = workspace + this.recordUndo = true//记录撤销 + } + run(redo) { + if (redo) { + vm.setEditingTarget(this.dst_target_id); + scrollBlockIntoView(getBlockInMainWorkspace(blockly, this.dst_block_id), this.workspace)//跳转至定义(要通过id获取,否则跨角色会获取失败) + } + else { + vm.setEditingTarget(this.src_target_id); + scrollBlockIntoView(getBlockInMainWorkspace(blockly, this.src_block_id), this.workspace)//跳转回引用 + } + } + } + workspace.fireChangeListener(new MoveWorkspaceEvent(src_target_id, call_block.id, dst_target_id, defineBlock.id, workspace))//记录跳转事件 }; const handleGoToDefinition = function (vm, blockly) { - if (!this.getProcCode) { - console.warn("没有procCode,无法跳转"); - return; - } - goToDefinition(this, vm, blockly.getMainWorkspace(), blockly); + console.time('goToDef') + if (!this.getProcCode) { + console.warn("没有procCode,无法跳转"); + return; + } + goToDefinition(this, vm, blockly.getMainWorkspace(), blockly); }; const refreshBlocksWithOpcodes = (blockly, opcodes) => { - for (let block of blockly.getMainWorkspace().getAllBlocks()) { - if (opcodes.includes(block.type)) { - block.customContextMenu = CTX_MENU_EXT.customContextMenu - } - } - blockly.getMainWorkspace().getToolbox().showAll_() + for (let block of blockly.getMainWorkspace().getAllBlocks()) { + if (opcodes.includes(block.type)) { + block.customContextMenu = CTX_MENU_EXT.customContextMenu + } + } + blockly.getMainWorkspace().getToolbox().showAll_() } const FindDefinition = ({ blockly, vm, registerSettings, msg }) => { - if (blockly.Blocks[blockly.PROCEDURES_CALL_BLOCK_TYPE]) { - console.log("检测到自定义快,可以替换blockly"); - PROTOTYPE_OPCODE = blockly.PROCEDURES_PROTOTYPE_BLOCK_TYPE; - CALL_OPCODE = blockly.PROCEDURES_CALL_BLOCK_TYPE; - CALL_RETURN_OPCODE = blockly.PROCEDURES_CALL_WITH_RETURN_BLOCK_TYPE; - CTX_MENU_EXT = blockly.ScratchBlocks.VerticalExtensions.PROCEDURE_CALL_CONTEXTMENU; - CTX_MENU_EXT._orig = CTX_MENU_EXT.customContextMenu; - CTX_MENU_EXT.customContextMenu = function (menuOptions) { - if (CTX_MENU_EXT._orig === undefined) { - console.warn("菜单未刷新,可尝试切换角色");//一般不会运行,因为删除插件时会刷新 - return; - } - CTX_MENU_EXT._orig.call(this, menuOptions);//调用原有菜单 - menuOptions.push({//加入自定义菜单项 - text: msg("plugins.findDefinition.goToDefinition"), - enabled: true, - callback: handleGoToDefinition.bind(this, vm, blockly), - }); - }; - refreshBlocksWithOpcodes(blockly, [CALL_OPCODE, CALL_RETURN_OPCODE]); + if (blockly.Blocks[blockly.PROCEDURES_CALL_BLOCK_TYPE]) { + PROTOTYPE_OPCODE = blockly.PROCEDURES_PROTOTYPE_BLOCK_TYPE; + CALL_OPCODE = blockly.PROCEDURES_CALL_BLOCK_TYPE; + CALL_RETURN_OPCODE = blockly.PROCEDURES_CALL_WITH_RETURN_BLOCK_TYPE; + CTX_MENU_EXT = blockly.ScratchBlocks.VerticalExtensions.PROCEDURE_CALL_CONTEXTMENU; + CTX_MENU_EXT._orig = CTX_MENU_EXT.customContextMenu; + CTX_MENU_EXT.customContextMenu = function (menuOptions) { + if (CTX_MENU_EXT._orig === undefined) { + console.warn("菜单未刷新,可尝试切换角色");//一般不会运行,因为删除插件时会刷新 + return; + } + CTX_MENU_EXT._orig.call(this, menuOptions);//调用原有菜单 + menuOptions.push({//加入自定义菜单项 + text: msg("plugins.findDefinition.goToDefinition"), + enabled: true, + callback: handleGoToDefinition.bind(this, vm, blockly), + }); + }; + refreshBlocksWithOpcodes(blockly, [CALL_OPCODE, CALL_RETURN_OPCODE]); - } - const register = registerSettings( - msg("plugins.findDefinition.title"), - "plugin-find-definition", - [ - { - key: "plugin-find-definition", - label: msg("plugins.findDefinition.title"), - description: msg("plugins.findDefinition.description"), - items: [], - }, - ], - "", - ); - return { - dispose: () => { - /** Remove some side effects */ - CTX_MENU_EXT = blockly.ScratchBlocks.VerticalExtensions.PROCEDURE_CALL_CONTEXTMENU; - console.log(CTX_MENU_EXT._orig === CTX_MENU_EXT.customContextMenu); - CTX_MENU_EXT.customContextMenu = CTX_MENU_EXT._orig; - CTX_MENU_EXT._orig = undefined; - const workspace = blockly.getMainWorkspace(); - if (!workspace) { - console.warn("没有工作区,无法删除原有菜单"); - return; - } - refreshBlocksWithOpcodes(blockly, [CALL_OPCODE, CALL_RETURN_OPCODE]); - // workspace.clearUndo(); 我不想使用这个,因为会清除所有撤销记录 - // 可能导致用户无法撤销之前的操作 - // 但可以通过遍历undoStack并删除的方式来清除跳转事件 - const new_undo_stack = workspace.undoStack_.filter(event => event.type !== 'GOTO_DEF'); - workspace.undoStack_ = new_undo_stack; - //同时,也需要删除redoStack - const new_redo_stack = workspace.redoStack_.filter(event => event.type !== 'GOTO_DEF'); - workspace.redoStack_ = new_redo_stack; - register.dispose(); - }, - }; + } + const register = registerSettings( + msg("plugins.findDefinition.title"), + "plugin-find-definition", + [ + { + key: "plugin-find-definition", + label: msg("plugins.findDefinition.title"), + description: msg("plugins.findDefinition.description"), + items: [], + }, + ], + "", + ); + return { + dispose: () => { + /** Remove some side effects */ + CTX_MENU_EXT = blockly.ScratchBlocks.VerticalExtensions.PROCEDURE_CALL_CONTEXTMENU; + CTX_MENU_EXT.customContextMenu = CTX_MENU_EXT._orig; + CTX_MENU_EXT._orig = undefined; + const workspace = blockly.getMainWorkspace(); + if (!workspace) { + console.warn("没有工作区,无法删除原有菜单"); + return; + } + refreshBlocksWithOpcodes(blockly, [CALL_OPCODE, CALL_RETURN_OPCODE]); + // workspace.clearUndo(); 我不想使用这个,因为会清除所有撤销记录 + // 可能导致用户无法撤销之前的操作 + // 但可以通过遍历undoStack并删除的方式来清除跳转事件 + const new_undo_stack = workspace.undoStack_.filter(event => event.type !== 'GOTO_DEF'); + workspace.undoStack_ = new_undo_stack; + //同时,也需要删除redoStack + const new_redo_stack = workspace.redoStack_.filter(event => event.type !== 'GOTO_DEF'); + workspace.redoStack_ = new_redo_stack; + register.dispose(); + }, + }; }; export default FindDefinition; From 5f9af27c6426329dc0a77241e6e4163e5288f3bb Mon Sep 17 00:00:00 2001 From: BenPaoDeXiaoZhi Date: Fri, 25 Jul 2025 22:13:38 +0800 Subject: [PATCH 09/28] =?UTF-8?q?=E6=B8=85=E9=99=A4=E8=B0=83=E8=AF=95?= =?UTF-8?q?=E4=BF=A1=E6=81=AF=EF=BC=8C=E4=BF=AE=E6=94=B9=E5=BC=80=E5=8F=91?= =?UTF-8?q?=E8=80=85=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/plugins/find-definition/index.js | 2 -- src/plugins/find-definition/manifest.ts | 3 ++- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/plugins/find-definition/index.js b/src/plugins/find-definition/index.js index c3eb96d..5bb5184 100644 --- a/src/plugins/find-definition/index.js +++ b/src/plugins/find-definition/index.js @@ -67,7 +67,6 @@ const goToDefinition = (call_block, vm, workspace, blockly) => { } const src_target_id = vm.editingTarget.id;//记录调用自制积木的角色id const dst_target_id = targetId;//记录定义自制积木的角色id - console.timeEnd('goToDef') if (targetId !== vm.editingTarget.id) { vm.setEditingTarget(targetId); } @@ -99,7 +98,6 @@ const goToDefinition = (call_block, vm, workspace, blockly) => { workspace.fireChangeListener(new MoveWorkspaceEvent(src_target_id, call_block.id, dst_target_id, defineBlock.id, workspace))//记录跳转事件 }; const handleGoToDefinition = function (vm, blockly) { - console.time('goToDef') if (!this.getProcCode) { console.warn("没有procCode,无法跳转"); return; diff --git a/src/plugins/find-definition/manifest.ts b/src/plugins/find-definition/manifest.ts index b73d782..2f7c392 100644 --- a/src/plugins/find-definition/manifest.ts +++ b/src/plugins/find-definition/manifest.ts @@ -4,7 +4,8 @@ export default { description: "a plugin that can find where the definition of custom block is", credits: [ { - name: "BenPaoDeXiaoZhi", + name: "BenPaoDeXiaoZhi @ CCW", + link:"https://www.ccw.site/student/63c2807d669fa967f17f5559" }, ], }; From 8d44880ea8b3200360ac575c56f6faeec32b4ee6 Mon Sep 17 00:00:00 2001 From: BenPaoDeXiaoZhi Date: Tue, 29 Jul 2025 17:01:36 +0800 Subject: [PATCH 10/28] createTypeDefinition --- src/l10n/en.json | 6 +- src/l10n/zh-cn.json | 6 +- src/plugins-entry.ts | 2 + src/plugins-manifest.ts | 4 + .../extension-type-definition/index.js | 41 + .../extension-type-definition/manifest.ts | 11 + .../scratch-vm-dts.d.ts.asset | 8466 +++++++++++++++++ .../wpp-monaco/assets/extension.ts.txt | 48 + .../wpp-monaco/assets/wpp.tmLanguage.json | 119 + src/plugins/wpp-monaco/index.js | 66 + src/plugins/wpp-monaco/manifest.ts | 11 + src/types.d.ts | 5 + webpack.config.js | 4 + webpackDevServer.config.js | 4 + 14 files changed, 8791 insertions(+), 2 deletions(-) create mode 100644 src/plugins/extension-type-definition/index.js create mode 100644 src/plugins/extension-type-definition/manifest.ts create mode 100644 src/plugins/extension-type-definition/scratch-vm-dts.d.ts.asset create mode 100644 src/plugins/wpp-monaco/assets/extension.ts.txt create mode 100644 src/plugins/wpp-monaco/assets/wpp.tmLanguage.json create mode 100644 src/plugins/wpp-monaco/index.js create mode 100644 src/plugins/wpp-monaco/manifest.ts diff --git a/src/l10n/en.json b/src/l10n/en.json index 8e4015b..0a69d95 100644 --- a/src/l10n/en.json +++ b/src/l10n/en.json @@ -286,5 +286,9 @@ "plugins.cleanPro.docs.title": "Plugin Doc", "plugins.findDefinition.title": "find definition of custom block", "plugins.findDefinition.description": "Right-click on a custom block in the code area and select【Jump To Definition】to jump to the definition location of that custom block.", - "plugins.findDefinition.goToDefinition": "Jump To Definition" + "plugins.findDefinition.goToDefinition": "Jump To Definition", + "plugins.extensionTypeDefinition.title": "Provide auto-completion for extensions development", + "plugins.extensionTypeDefinition.description": "After loading, type annotations will be automatically provided. By annotating variable types using jsdoc syntax, you can enjoy auto-completion. For example, \n/**\n* @type {Runtime}\n*/\nlet runtime;\nWhen typing \"runtime.\", it will prompt you with the methods supported by runtime", + "plugins.wppMonaco.title": "Provide highlight and auto-completion for wpp", + "plugins.wppMonaco.description": "Create .wpp file, and enjoy the highlight and auto-completion!" } diff --git a/src/l10n/zh-cn.json b/src/l10n/zh-cn.json index 277a86a..9b30d99 100644 --- a/src/l10n/zh-cn.json +++ b/src/l10n/zh-cn.json @@ -287,5 +287,9 @@ "plugins.cleanPro.docs.title": "插件文档", "plugins.findDefinition.title": "查找自定义块的定义位置", "plugins.findDefinition.description": "在代码区右键单击自定义块,选择【跳转到定义】即可跳转到该自定义块的定义位置。", - "plugins.findDefinition.goToDefinition": "跳转到定义" + "plugins.findDefinition.goToDefinition": "跳转到定义", + "plugins.extensionTypeDefinition.title": "为拓展开发提供自动补全", + "plugins.extensionTypeDefinition.description": "加载之后,会自动提供类型标注,使用jsdoc语法标注了变量类型后可以提供自动补全,如\n/**\n* @type{Runtime}\n*/\nlet runtime;\n键入\"runtime.\"后会提示runtime支持的方法", + "plugins.wppMonaco.title": "为白猫的解释器语言提供高亮与补全", + "plugins.wppMonaco.description": "在文件管理中新建wpp文件,立享补全与高亮!" } diff --git a/src/plugins-entry.ts b/src/plugins-entry.ts index 2eaf5da..f051be4 100644 --- a/src/plugins-entry.ts +++ b/src/plugins-entry.ts @@ -27,4 +27,6 @@ export default { "mobile-code-batch-select": () => import(/* webpackChunkName: "plugin-mobile-code-batch-select" */ "src/plugins/mobile-code-batch-select"), "clean-pro": () => import(/* webpackChunkName: "plugin-clean-pro" */ "src/plugins/clean-pro"), "find-definition": () => import(/* webpackChunkName: "plugin-find-definition" */ "src/plugins/find-definition"), + "extension-type-definition": () => import(/* webpackChunkName: "plugin-extension-type-definition" */ "plugins/extension-type-definition"), + "wpp-monaco": () => import(/* webpackChunkName: "plugin-wpp-monaco" */ "src/plugins/wpp-monaco"), } as const; diff --git a/src/plugins-manifest.ts b/src/plugins-manifest.ts index 1c00270..9a283d0 100644 --- a/src/plugins-manifest.ts +++ b/src/plugins-manifest.ts @@ -23,6 +23,8 @@ import dataCategoryTweaks from "plugins/data-category-tweaks/manifest"; import mobileCodeBatchSelect from "src/plugins/mobile-code-batch-select/manifest"; import cleanPro from "src/plugins/clean-pro/manifest"; import findDefinition from "src/plugins/find-definition/manifest"; +import extensionTypeDefinition from "plugins/extension-type-definition/manifest"; +import wppMonaco from "src/plugins/wpp-monaco/manifest"; export default { folder, @@ -50,4 +52,6 @@ export default { "mobile-code-batch-select": mobileCodeBatchSelect, "clean-pro": cleanPro, "find-definition": findDefinition, + "extension-type-definition": extensionTypeDefinition, + "wpp-monaco": wppMonaco, }; diff --git a/src/plugins/extension-type-definition/index.js b/src/plugins/extension-type-definition/index.js new file mode 100644 index 0000000..038e2fe --- /dev/null +++ b/src/plugins/extension-type-definition/index.js @@ -0,0 +1,41 @@ +/** + * dts 包含了用于extraLib载入的.d.ts的文件内容 + * @type {string} + */ +import dts from './scratch-vm-dts.d.ts.asset' + +const ExtensionTypeDefinition = ({ vm, registerSettings, msg }) => { + if (!window?.monaco?.languages?.typescript?.javascriptDefaults) { + console.warn('ide未在全局暴露monaco或其js语言功能,无法加载插件' + msg("plugins.extensionTypeDefinition.title")) + return { dispose: () => { } } + } + // vm.runtime.gandi._supportedAssetTypes.push({ //测试用 + // "contentType": "text/javascript", + // "name": "Extension", + // "runtimeFormat": "js", + // "immutable": true + // }) + const register = registerSettings( + msg("plugins.extensionTypeDefinition.title"), + "plugin-extension-type-definition", + [ + { + key: "plugin-extension-type-definition", + label: msg("plugins.extensionTypeDefinition.title"), + description: msg("plugins.extensionTypeDefinition.description"), + items: [], + }, + ], + "", + ); + window.monaco.languages.typescript.javascriptDefaults.addExtraLib(dts, 'global.d.ts') + console.log('monaco d.ts文件已载入') + return { + dispose: () => { + /** Remove some side effects */ + register.dispose() + }, + }; +}; + +export default ExtensionTypeDefinition; diff --git a/src/plugins/extension-type-definition/manifest.ts b/src/plugins/extension-type-definition/manifest.ts new file mode 100644 index 0000000..ffb6411 --- /dev/null +++ b/src/plugins/extension-type-definition/manifest.ts @@ -0,0 +1,11 @@ +export default { + name: "extension-type-definiton", + type: "function", + description: "create type definitions for extension", + credits: [ + { + name: "BenPaoDeXiaoZhi @ CCW", + link: "https://www.ccw.site/student/63c2807d669fa967f17f5559" + } + ], +}; diff --git a/src/plugins/extension-type-definition/scratch-vm-dts.d.ts.asset b/src/plugins/extension-type-definition/scratch-vm-dts.d.ts.asset new file mode 100644 index 0000000..784a74f --- /dev/null +++ b/src/plugins/extension-type-definition/scratch-vm-dts.d.ts.asset @@ -0,0 +1,8466 @@ +// Generated by dts-bundle v0.7.3 +// Dependencies for this module: +// ../events +// ../@turbowarp/jszip +// ../format-message +// ../immutable +// ../node:events +// ../jszizp +//monaco似乎不能处理import…from +declare type ArgumentType = import('scratch-vm-dts/extension-support/argument-type') +declare type Runtime = import("scratch-vm-dts/engine/runtime"); +declare type Target = import("scratch-vm-dts/engine/target"); +declare type RenderedTarget = import("scratch-vm-dts/sprites/rendered-target"); +declare type Sprite = import("scratch-vm-dts/sprites/sprite"); +declare type BlockType = import('scratch-vm-dts/extension-support/block-type') +declare module "scratch-vm-dts" { + export = VirtualMachine; + import VirtualMachine = require("scratch-vm-dts/virtual-machine"); +} + +declare module "scratch-vm-dts/virtual-machine" { + export = VirtualMachine; + //import Target = require('scratch-vm-dts/engine/target'); //我发现require也无法使用 + type Target = import("scratch-vm-dts/engine/target"); + import Sequencer = require("scratch-vm-dts/engine/sequencer"); + namespace Blockly { + class Event { } + } + class StreamHelper { } + class ImportedProject { } + class Gandi { } + class int extends Number { } + class Block { } + class bool extends Boolean { } + class Costume { } + class ImportedExtensionsInfo { } + class AudioEngine { } + class RenderWebGL { } + class ScratchStorage { } + /** + * Handles connections between blocks, stage, and extensions. + * @constructor + */ + class VirtualMachine extends EventEmitter<[never]> { + static get FIND_PYTHON_CODE(): string; + constructor(); + /** + * VM runtime, to store blocks, I/O devices, sprites/targets, etc. + * @type {!Runtime} + */ + runtime: Runtime; + /** + * The "currently editing"/selected target ID for the VM. + * Block events from any Blockly workspace are routed to this target. + * @type {Target} + */ + editingTarget: Target; + /** + * This variable indicates whether asynchronous loading of project resource files is supported + */ + asyncLoadingProjectAssetsSupported: boolean; + /** + * The currently dragging target, for redirecting IO data. + * @type {Target} + */ + _dragTarget: Target; + /** + * The current project resource loading progress. + * @type {Progress} + */ + _assetsLoadProgress: Progress; + extensionManager: ExtensionManager; + securityManager: import("scratch-vm-dts/extension-support/tw-security-manager"); + /** + * Handle a Blockly event for the current editing target. + * @param {!Blockly.Event} e Any Blockly event. + */ + blockListener(e: Blockly.Event): void; + /** + * Handle a Blockly event for the current editing target. + * @param {!Blockly.Event} e Any Blockly event. + */ + frameListener(e: Blockly.Event): void; + /** + * Handle a Blockly event for the flyout. + * @param {!Blockly.Event} e Any Blockly event. + */ + flyoutBlockListener(e: Blockly.Event): void; + /** + * Handle a Blockly event for the flyout to be passed to the monitor container. + * @param {!Blockly.Event} e Any Blockly event. + */ + monitorBlockListener(e: Blockly.Event): void; + /** + * Handle a Blockly event for the variable map. + * @param {!Blockly.Event} e Any Blockly event. + */ + variableListener(e: Blockly.Event): void; + /** + * Export some internal classes for extensions. + */ + exports: { + Sprite: Sprite; + RenderedTarget: RenderedTarget; + JSZip: JSZip; + i_will_not_ask_for_help_when_these_break: () => { + JSGenerator: typeof import("scratch-vm-dts/compiler/jsgen"); + IRGenerator: typeof import("scratch-vm-dts/compiler/irgen").IRGenerator; + ScriptTreeGenerator: typeof import("scratch-vm-dts/compiler/irgen").ScriptTreeGenerator; + Thread: import("scratch-vm-dts/engine/thread"); + execute: ( + sequencer: Sequencer, + thread: import("scratch-vm-dts/engine/thread") + ) => void; + }; + }; + _projectProcessingUniqueId: number; + /** + * Start running the VM - do this before anything else. + */ + start(): void; + /** + * @deprecated Used by old versions of TurboWarp. Superceded by upstream's quit() + */ + stop(): void; + /** + * Quit the VM, clearing any handles which might keep the process alive. + * Do not use the runtime after calling this method. This method is meant for test shutdown. + */ + quit(): void; + /** + * "Green flag" handler - start all threads starting with a green flag. + */ + greenFlag(): void; + /** + * Set whether the VM is in "turbo mode." + * When true, loops don't yield to redraw. + * @param {boolean} turboModeOn Whether turbo mode should be set. + */ + setTurboMode(turboModeOn: boolean): void; + /** + * Set whether the VM is in 2.0 "compatibility mode." + * When true, ticks go at 2.0 speed (30 TPS). + * @param {boolean} compatibilityModeOn Whether compatibility mode is set. + */ + setCompatibilityMode(compatibilityModeOn: boolean): void; + setFramerate(framerate: any): void; + setInterpolation(interpolationEnabled: any): void; + setRuntimeOptions(runtimeOptions: any): void; + /** + * ccw: Set ccw API to runtime support ccw block extensions + * @param {*} ccwAPI ccw API + */ + setCCWAPI(ccwAPI: any): void; + setCompilerOptions(compilerOptions: any): void; + setIsPlayerOnly(isPlayerOnly: any): void; + setStageSize(width: any, height: any): void; + setInEditor(inEditor: any): void; + convertToPackagedRuntime(): void; + addAddonBlock(options: any): void; + getAddonBlock(procedureCode: any): any; + storeProjectOptions(): void; + enableDebug(): string; + handleExtensionButtonPress(button: any): void; + /** + * Stop all threads and running activities. + */ + stopAll(): void; + disposeAll(): void; + /** + * Clear out current running project data. + */ + clear(): void; + /** + * Get data for playground. Data comes back in an emitted event. + */ + getPlaygroundData(): void; + /** + * Post I/O data to the virtual devices. + * @param {?string} device Name of virtual I/O device. + * @param {object} data Any data object to post to the I/O device. + */ + postIOData(device: string | null, data: object): void; + setVideoProvider(videoProvider: any): void; + setCloudProvider(cloudProvider: any): void; + /** + * Tell the specified extension to scan for a peripheral. + * @param {string} extensionId - the id of the extension. + */ + scanForPeripheral(extensionId: string): void; + /** + * Connect to the extension's specified peripheral. + * @param {string} extensionId - the id of the extension. + * @param {number} peripheralId - the id of the peripheral. + */ + connectPeripheral(extensionId: string, peripheralId: number): void; + /** + * Disconnect from the extension's connected peripheral. + * @param {string} extensionId - the id of the extension. + */ + disconnectPeripheral(extensionId: string): void; + /** + * Returns whether the extension has a currently connected peripheral. + * @param {string} extensionId - the id of the extension. + * @return {boolean} - whether the extension has a connected peripheral. + */ + getPeripheralIsConnected(extensionId: string): boolean; + /** + * Load a Scratch project from a .sb, .sb2, .sb3 or json string. + * @param {string | object} input A json string, object, or ArrayBuffer representing the project to load. + * @param {?function} jsonFormatter A function to format the project json. + * @return {!Promise} Promise that resolves after targets are installed. + */ + loadProject( + input: string | object, + jsonFormatter: Function | null, + options: any + ): Promise; + /** + * Load a project from the Scratch web site, by ID. + * @param {string} id - the ID of the project to download, as a string. + */ + downloadProjectId(id: string): void; + /** + * @returns {JSZip} JSZip zip object representing the sb3. + */ + _saveProjectZip(): JSZip; + /** + * @param {JSZip.OutputType} [type] JSZip output type. Defaults to 'blob' for Scratch compatibility. + * @returns {Promise} Compressed sb3 file in a type determined by the type argument. + */ + saveProjectSb3(type?: JSZip.OutputType): Promise; + /** + * @param {JSZip.OutputType} [type] JSZip output type. Defaults to 'arraybuffer'. + * @returns {StreamHelper} JSZip StreamHelper object generating the compressed sb3. + * See: https://stuk.github.io/jszip/documentation/api_streamhelper.html + */ + saveProjectSb3Stream(type?: JSZip.OutputType): StreamHelper; + /** + * tw: Serialize the project into a map of files without actually zipping the project. + * The buffers returned are the exact same ones used internally, not copies. Avoid directly + * manipulating them (except project.json, which is created by this function). + * @returns {Record} Map of file name to the raw data for that file. + */ + saveProjectSb3DontZip(): Record; + /** + * Serialize project. + * @param {object} whetherSerialize + * @param {boolean} whetherSerialize.isSerializeSounds whether to serialize sound + * @param {boolean} whetherSerialize.isSerializeCostumes whether to serialize costumes + * @param {boolean} whetherSerialize.isSerializeJson whether to serialize json + * @returns {Object} Serialized state of the runtime. + */ + serializeProject({ + isSerializeSounds, + isSerializeCostumes, + isSerializeJson, + }?: { + isSerializeSounds: boolean; + isSerializeCostumes: boolean; + isSerializeJson: boolean; + }): Object; + /** + * @type {Array} Array of all assets currently in the runtime + */ + get assets(): Array; + generateUid(): string; + getSb3Utils(): { + serialize: ( + runtime: Runtime, + targetId?: string | undefined, + { + allowOptimization, + saveVarId, + }?: { + allowOptimization?: boolean | undefined; + saveVarId?: boolean | undefined; + } + ) => object; + deserialize: ( + json: object, + runtime: Runtime, + zip: JSZip, + isSingleSprite: boolean + ) => Promise; + deserializeBlocks: (blocks: object) => object; + deserializeInputs: ( + inputs: object, + parentId: string, + blocks: object + ) => object; + deserializeFields: (fields: object) => object; + serializeBlocks: (blocks: object, saveVarId: boolean | null) => any[]; + serializeTarget: ( + target: object, + extensions: Set, + saveVarId: boolean | null + ) => object; + serializeMonitors: (monitors: any, runtime: any, extensions: any) => any; + deserializeMonitor: ( + monitorData: any, + runtime: any, + targets: any, + extensions: any + ) => void; + serializeSound: (sound: object) => object; + deserializeSound: ( + sound: object, + runtime: Runtime, + zip: JSZip, + assetFileName: string + ) => Promise; + serializeComments: (comments: any) => any; + serializeVariables: (variables: object) => object; + getExtensionIdForOpcode: (opcode: string) => string | null; + deserializeInputDesc: ( + inputDescOrId: string | Array, + parentId: string, + isShadow: boolean, + blocks: object, + blockId: any + ) => object; + serializePrimitiveBlock: ( + block: object, + saveVarId: boolean | null + ) => Array; + primitiveOpcodeInfoMap: { + math_number: (string | number)[]; + math_positive_number: (string | number)[]; + math_whole_number: (string | number)[]; + math_integer: (string | number)[]; + math_angle: (string | number)[]; + colour_picker: (string | number)[]; + text: (string | number)[]; + event_broadcast_menu: (string | number)[]; + data_variable: (string | number)[]; + data_listcontents: (string | number)[]; + }; + deserializeStandaloneBlocks: (blocks: unknown) => { + blocks: Block[]; + extensionURLs: Map; + }; + serializeStandaloneBlocks: (blocks: Block[], runtime: Runtime) => object; + }; + createGandiAssetFile(name: any, assetType: any, data?: string): void; + getGandiAssetsList(typesArray: any): any; + getGandiAssetContent(fileName: any): any; + getGandiAssetsFileList(type: any): any; + getGandiAssetFile(fileName: any): any; + getGandiAssetById(id: any): any; + getGandiAssetIndexAndFileById(id: any): { + file: any; + index: number; + }; + /** + * @param {string} targetId Optional ID of target to export + * @returns {Array<{fileName: string; fileContent: Uint8Array;}} list of file descs + */ + serializeAssets(targetId: string): Array<{ + fileName: string; + fileContent: Uint8Array; + }>; + _addFileDescsToZip(fileDescs: any, zip: any): void; + /** + * Exports a sprite in the sprite3 format. + * @param {string} targetId ID of the target to export + * @param {string=} optZipType Optional type that the resulting + * zip should be outputted in. Options are: base64, binarystring, + * array, uint8array, arraybuffer, blob, or nodebuffer. Defaults to + * blob if argument not provided. + * See https://stuk.github.io/jszip/documentation/api_jszip/generate_async.html#type-option + * for more information about these options. + * @return {object} A generated zip of the sprite and its assets in the format + * specified by optZipType or blob by default. + */ + exportSprite(targetId: string, optZipType?: string | undefined): object; + /** + * Export project or sprite as a Scratch 3.0 JSON representation. + * @param {string=} optTargetId - Optional id of a sprite to serialize + * @param {*} serializationOptions Options to pass to the serializer + * @return {string} Serialized state of the runtime. + */ + toJSON(optTargetId: string | undefined, serializationOptions: any): string; + /** + * Serialize a sprite in the sprite3 format. + * @param {string} targetId ID of the target to export + * @param {?Boolean} saveVarId Whether to save the variable ID or not + * @returns {Object} Serialized state of the runtime. + */ + serializeSprite(targetId: string, saveVarId: boolean | null): Object; + /** + * Serialize sprite assets for gui + * @param {string} targetId ID of the target to export + * @returns {Object} sound & costume & spriteJson result of serialize + */ + serializeSpriteAssets(targetId: string): Object; + /** + * Load a project from a Scratch JSON representation. + * @param {string} json JSON string representing a project. + * @returns {Promise} Promise that resolves after the project has loaded + */ + fromJSON(json: string): Promise; + /** + * Load a project from a Scratch JSON representation. + * @param {string} projectJSON JSON string representing a project. + * @param {?JSZip} zip Optional zipped project containing assets to be loaded. + * @param {number} _projectProcessingUniqueId 加载project的Id + * @returns {Promise} Promise that resolves after the project has loaded + */ + deserializeProject( + projectJSON: string, + zip: JSZip | null, + _projectProcessingUniqueId: number, + options: any + ): Promise; + /** + * Install `deserialize` results: zero or more targets after the extensions (if any) used by those targets. + * @param {Array.} targets - the targets to be installed + * @param {ImportedExtensionsInfo} extensions - metadata about extensions used by these targets + * @param {Gandi} gandiObject - the gandi Object to be merged + * @param {boolean} wholeProject - set to true if installing a whole project, as opposed to a single sprite. + * @param {number} _projectProcessingUniqueId 加载project的Id + * @param {boolean} isRemoteOperation - set to true if this is a remote operation + * @returns {Promise<{addedTargets:Target[], addedGandiObject:Gandi}>} resolved once targets and Gandi object have been installed + */ + installTargets( + targets: Array, + extensions: ImportedExtensionsInfo, + gandiObject: Gandi, + wholeProject: boolean, + _projectProcessingUniqueId: number, + isRemoteOperation: boolean, + options: any + ): Promise<{ + addedTargets: Target[]; + addedGandiObject: Gandi; + }>; + /** + * Add a sprite, this could be .sprite2 or .sprite3. Unpack and validate + * such a file first. + * @param {string | object} input A json string, object, or ArrayBuffer representing the project to load. + * @param {?string} isRemoteOperation - set to true if this is a remote operation + * @return {!Promise} Promise that resolves after targets are installed. + */ + addSprite( + input: string | object, + isRemoteOperation: string | null + ): Promise; + /** + * Add a single sprite from the "Sprite2" (i.e., SB2 sprite) format. + * @param {object} sprite Object representing 2.0 sprite to be added. + * @param {?ArrayBuffer} zip Optional zip of assets being referenced by json + * @param {?boolean} isRemoteOperation Whether to change editing target + * @returns {Promise} Promise that resolves after the sprite is added + */ + _addSprite2( + sprite: object, + zip: ArrayBuffer | null, + isRemoteOperation: boolean | null + ): Promise; + /** + * Add a single sb3 sprite. + * @param {object} sprite Object rperesenting 3.0 sprite to be added. + * @param {?ArrayBuffer} zip Optional zip of assets being referenced by target json + * @param {?boolean} isRemoteOperation Whether to change editing target + * @returns {Promise} Promise that resolves after the sprite is added + */ + _addSprite3( + sprite: object, + zip: ArrayBuffer | null, + isRemoteOperation: boolean | null + ): Promise; + /** + * Add a costume to the current editing target. + * @param {string} md5ext - the MD5 and extension of the costume to be loaded. + * @param {!object} costumeObject Object representing the costume. + * @param {string} target - the target to add to. + * @param {?int} index Index at which to add costume + * @returns {?Promise} - a promise that resolves when the costume has been added + */ + addCostumeFromRemote( + md5ext: string, + costumeObject: object, + target: string, + index: int | null + ): Promise | null; + /** + * Add a costume to the current editing target. + * @param {string} md5ext - the MD5 and extension of the costume to be loaded. + * @param {!object} costumeObject Object representing the costume. + * @property {int} skinId - the ID of the costume's render skin, once installed. + * @property {number} rotationCenterX - the X component of the costume's origin. + * @property {number} rotationCenterY - the Y component of the costume's origin. + * @property {number} [bitmapResolution] - the resolution scale for a bitmap costume. + * @param {string} optTargetId - the id of the target to add to, if not the editing target. + * @param {string} optVersion - if this is 2, load costume as sb2, otherwise load costume as sb3. + * @param {boolean} isRemoteOperation Whether this is a remote operation. + * @returns {?Promise} - a promise that resolves when the costume has been added + */ + addCostume( + md5ext: string, + costumeObject: object, + optTargetId: string, + optVersion: string, + isRemoteOperation: boolean + ): Promise | null; + /** + * Add a costume loaded from the library to the current editing target. + * @param {string} md5ext - the MD5 and extension of the costume to be loaded. + * @param {!object} costumeObject Object representing the costume. + * @property {int} skinId - the ID of the costume's render skin, once installed. + * @property {number} rotationCenterX - the X component of the costume's origin. + * @property {number} rotationCenterY - the Y component of the costume's origin. + * @property {number} [bitmapResolution] - the resolution scale for a bitmap costume. + * @returns {?Promise} - a promise that resolves when the costume has been added + */ + addCostumeFromLibrary( + md5ext: string, + costumeObject: object + ): Promise | null; + /** + * Duplicate the costume at the given index. Add it at that index + 1. + * @param {!int} costumeIndex Index of costume to duplicate + * @returns {?Promise} - a promise that resolves when the costume has been decoded and added + */ + duplicateCostume(costumeIndex: int): Promise | null; + /** + * Duplicate the sound at the given index. Add it at that index + 1. + * @param {!int} soundIndex Index of sound to duplicate + * @returns {?Promise} - a promise that resolves when the sound has been decoded and added + */ + duplicateSound(soundIndex: int): Promise | null; + /** + * Rename a costume on the current editing target. + * @param {int} costumeIndex - the index of the costume to be renamed. + * @param {string} newName - the desired new name of the costume (will be modified if already in use). + */ + renameCostume(costumeIndex: int, newName: string): void; + /** + * Delete a costume from the current editing target. + * @param {int} costumeIndex - the index of the costume to be removed. + * @return {?function} A function to restore the deleted costume, or null, + * if no costume was deleted. + */ + deleteCostume(costumeIndex: int): Function | null; + /** + * Add a sound to the current editing target. + * @param {!object} soundObject Object representing the sound. + * @param {string} optTargetId - the id of the target to add to, if not the editing target. + * @returns {?Promise} - a promise that resolves when the sound has been decoded and added + */ + addSound(soundObject: object, optTargetId: string): Promise | null; + /** + * Rename a sound on the current editing target. + * @param {int} soundIndex - the index of the sound to be renamed. + * @param {string} newName - the desired new name of the sound (will be modified if already in use). + */ + renameSound(soundIndex: int, newName: string): void; + /** + * Get a sound buffer from the audio engine. + * @param {int} soundIndex - the index of the sound to be got. + * @return {AudioBuffer} the sound's audio buffer. + */ + getSoundBuffer(soundIndex: int): AudioBuffer; + /** + * Sets a configuration property in the Gandi runtime. + * + * @param {string} key - The key of the configuration property to set. + * @param value - The value to set for the configuration property. + */ + setGandiConfigProperty(key: string, value: any): void; + /** + * Gets a configuration property from the Gandi runtime. + * + * @param {string} key - The key of the configuration property to retrieve. + * @returns The value of the configuration property. + */ + getGandiConfigProperty(key: string): any; + getMonitoredKeys(): any[]; + /** + * Updates global procedure call mutations in the project. + * + * @param {string} oldProccode - The old procedure code to be replaced. + * @param {string} newMutationText - The new mutation text to replace the old mutation. + * @returns {void} + */ + updateGlobalProcedureCallMutation( + oldProccode: string, + newMutationText: string + ): void; + /** + * Update a sound buffer. + * @param {int} soundIndex - the index of the sound to be updated. + * @param {AudioBuffer} newBuffer - new audio buffer for the audio engine. + * @param {ArrayBuffer} soundEncoding - the new (wav) encoded sound to be stored + * @param {string} targetId - the id of the target to be updated. + */ + updateSoundBuffer( + soundIndex: int, + newBuffer: AudioBuffer, + soundEncoding: ArrayBuffer, + targetId: string + ): void; + /** + * Delete a sound from the current editing target. + * @param {int} soundIndex - the index of the sound to be removed. + * @return {?Function} A function to restore the sound that was deleted, + * or null, if no sound was deleted. + */ + deleteSound(soundIndex: int): Function | null; + /** + * Get a string representation of the image from storage. + * @param {int} costumeIndex - the index of the costume to be got. + * @return {string} the costume's SVG string if it's SVG, + * a dataURI if it's a PNG or JPG, or null if it couldn't be found or decoded. + */ + getCostume(costumeIndex: int): string; + updateCostumeById(target: any, id: any, newCostume: any): void; + updateSoundById(target: any, id: any, newSound: any): void; + /** + * TW: Get the raw binary data to use when exporting a costume to the user's local file system. + * @param {Costume} costumeObject scratch-vm costume object + * @returns {Uint8Array} + */ + getExportedCostume(costumeObject: Costume): Uint8Array; + /** + * TW: Get a base64 string to use when exporting a costume to the user's local file system. + * @param {Costume} costumeObject scratch-vm costume object + * @returns {string} base64 string. Not a data: URI. + */ + getExportedCostumeBase64(costumeObject: Costume): string; + /** + * Update a costume with the given bitmap + * @param {!int} costumeIndex - the index of the costume to be updated. + * @param {!ImageData} bitmap - new bitmap for the renderer. + * @param {!number} rotationCenterX x of point about which the costume rotates, relative to its upper left corner + * @param {!number} rotationCenterY y of point about which the costume rotates, relative to its upper left corner + * @param {!number} bitmapResolution 1 for bitmaps that have 1 pixel per unit of stage, + * 2 for double-resolution bitmaps + * @param {string} targetId ID of a target. + */ + updateBitmap( + costumeIndex: int, + bitmap: ImageData, + rotationCenterX: number, + rotationCenterY: number, + bitmapResolution: number + ): void; + _updateBitmap( + costume: any, + bitmap: any, + rotationCenterX: any, + rotationCenterY: any, + bitmapResolution: any + ): void; + /** + * Update a costume with the given SVG + * @param {int} costumeIndex - the index of the costume to be updated. + * @param {string} svg - new SVG for the renderer. + * @param {number} rotationCenterX x of point about which the costume rotates, relative to its upper left corner + * @param {number} rotationCenterY y of point about which the costume rotates, relative to its upper left corner + * @param {string} targetId ID of a target. + */ + updateSvg( + costumeIndex: int, + svg: string, + rotationCenterX: number, + rotationCenterY: number, + targetId: string + ): void; + _updateSvg( + costume: any, + svg: any, + rotationCenterX: any, + rotationCenterY: any, + targetId: any + ): void; + /** + * Update a Gandi asset with the value + * @param {string} assetMd5 - the md5 of the asset to be updated. + * @param {string} newValue - new Value for the asset. + */ + updateGandiAssetData(fileName: any, newValue: string): void; + updateGandiAssetFromRemote(id: any, newAsset: any): void; + addGandiAssetFromRemote(id: any, newAsset: any): void; + deleteGandiAssetFromRemote(id: any): void; + /** + * rename a Gandi asset + * @param {string} id - The id of the asset to rename. + * @param {string} newName - new name for the asset. + */ + renameGandiAssetById(id: string, newName: string): any; + /** + * Delete a sprite and all its clones. + * @param {string} fileName name of a asset. + */ + deleteGandiAsset(fileName: string): void; + /** + * Delete a file from the Gandi assets. + * @param {string} id The id of the asset to delete. + */ + deleteGandiAssetById(id: string): void; + /** + * Add a backdrop to the stage. + * @param {string} md5ext - the MD5 and extension of the backdrop to be loaded. + * @param {!object} backdropObject Object representing the backdrop. + * @property {int} skinId - the ID of the backdrop's render skin, once installed. + * @property {number} rotationCenterX - the X component of the backdrop's origin. + * @property {number} rotationCenterY - the Y component of the backdrop's origin. + * @property {number} [bitmapResolution] - the resolution scale for a bitmap backdrop. + * @returns {?Promise} - a promise that resolves when the backdrop has been added + */ + addBackdrop(md5ext: string, backdropObject: object): Promise | null; + /** + * Rename a sprite. + * @param {string} targetId ID of a target whose sprite to rename. + * @param {string} newName New name of the sprite. + * @param {boolean} [sendNameChangedEvent = true] whether to send an event when the sprite name changes. + */ + renameSprite( + targetId: string, + newName: string, + sendNameChangedEvent?: boolean + ): void; + /** + * Delete a sprite and all its clones. + * @param {string} targetId ID of a target whose sprite to delete. + * @param {boolean} isRemoteOperation Whether this is a remote operation. + * @return {Function} Returns a function to restore the sprite that was deleted + */ + deleteSprite(targetId: string, isRemoteOperation: boolean): Function; + /** + * Duplicate a sprite. + * @param {string} targetId ID of a target whose sprite to duplicate. + * @returns {Promise} Promise that resolves when duplicated target has + * been added to the runtime. + */ + duplicateSprite(targetId: string): Promise; + /** + * Set the audio engine for the VM/runtime + * @param {!AudioEngine} audioEngine The audio engine to attach + */ + attachAudioEngine(audioEngine: AudioEngine): void; + /** + * Set the renderer for the VM/runtime + * @param {!RenderWebGL} renderer The renderer to attach + */ + attachRenderer(renderer: RenderWebGL): void; + /** + * @returns {RenderWebGL} The renderer attached to the vm + */ + get renderer(): RenderWebGL; + attachV2SVGAdapter(): void; + /** + * Set the bitmap adapter for the VM/runtime, which converts scratch 2 + * bitmaps to scratch 3 bitmaps. (Scratch 3 bitmaps are all bitmap resolution 2) + * @param {!function} bitmapAdapter The adapter to attach + */ + attachV2BitmapAdapter(bitmapAdapter: Function): void; + /** + * Set the storage module for the VM/runtime + * @param {!ScratchStorage} storage The storage module to attach + */ + attachStorage(storage: ScratchStorage): void; + /** + * set the current locale and builtin messages for the VM + * @param {!string} locale current locale + * @param {!object} messages builtin messages map for current locale + * @returns {Promise} Promise that resolves when all the blocks have been + * updated for a new locale (or empty if locale hasn't changed.) + */ + setLocale(locale: string, messages: object): Promise; + /** + * get the current locale for the VM + * @returns {string} the current locale in the VM + */ + getLocale(): string; + /** + * Delete all of the flyout blocks. + */ + clearFlyoutBlocks(): void; + /** + * Set an editing target. An editor UI can use this function to switch + * between editing different targets, sprites, etc. + * After switching the editing target, the VM may emit updates + * to the list of targets and any attached workspace blocks + * (see `emitTargetsUpdate` and `emitWorkspaceUpdate`). + * @param {string} targetId Id of target to set as editing. + */ + setEditingTarget(targetId: string): void; + /** + * @param {Block[]} blockObjects + * @returns {object} + */ + exportStandaloneBlocks(blockObjects: Block[]): object; + /** + * Called when blocks are dragged from one sprite to another. Adds the blocks to the + * workspace of the given target. + * @param {!Array} blocks Blocks to add. + * @param {!string} targetId Id of target to add blocks to. + * @param {?string} optFromTargetId Optional target id indicating that blocks are being + * shared from that target. This is needed for resolving any potential variable conflicts. + * @return {!Promise} Promise that resolves when the extensions and blocks have been added. + */ + shareBlocksToTarget( + blocks: Array, + targetId: string, + optFromTargetId: string | null + ): Promise; + /** + * Called when frame are dragged from one sprite to another. Adds the frame to the + * workspace of the given target. + * @param {!Array} frame Frame to add. + * @param {!string} targetId Id of target to add frame to. + * @param {?string} optFromTargetId Optional target id indicating that frame are being + * shared from that target. This is needed for resolving any potential variable conflicts. + * @return {!Promise} Promise that resolves when the extensions and frame have been added. + */ + shareFrameToTarget( + frame: Array, + targetId: string, + optFromTargetId: string | null + ): Promise; + /** + * Called when costumes are dragged from editing target to another target. + * Sets the newly added costume as the current costume. + * @param {!number} costumeIndex Index of the costume of the editing target to share. + * @param {!string} targetId Id of target to add the costume. + * @return {Promise} Promise that resolves when the new costume has been loaded. + */ + shareCostumeToTarget(costumeIndex: number, targetId: string): Promise; + /** + * Called when sounds are dragged from editing target to another target. + * @param {!number} soundIndex Index of the sound of the editing target to share. + * @param {!string} targetId Id of target to add the sound. + * @return {Promise} Promise that resolves when the new sound has been loaded. + */ + shareSoundToTarget(soundIndex: number, targetId: string): Promise; + /** + * Repopulate the workspace with the blocks of the current editingTarget. This + * allows us to get around bugs like gui#413. + */ + refreshWorkspace(): void; + /** + * Emit metadata about available targets. + * An editor UI could use this to display a list of targets and show + * the currently editing one. + * @param {boolean} triggerProjectChange If true, also emit a project changed event. + * Disabled selectively by updates that don't affect project serialization. + * Defaults to true. + */ + emitTargetsUpdate( + triggerProjectChange: boolean | undefined, + updatedTargets: any + ): void; + /** + * Emit an Blockly/scratch-blocks compatible XML representation + * of the current editing target's blocks. + */ + emitWorkspaceUpdate(): void; + /** + * Emit metadata about Gandi assets file. + * An editor UI could use this to display a list of files and show + * the currently editing one. + * @param {{data:object, type: 'add'|'update'|'delete', isFromRemote:bool}} action If true, also emit a project changed event. + * Defaults to true. + */ + emitGandiAssetsUpdate({ + data, + type, + }: { + data: object; + type: "add" | "update" | "delete"; + isFromRemote: bool; + }): void; + /** + * Get a target id for a drawable id. Useful for interacting with the renderer + * @param {number} drawableId The drawable id to request the target id for + * @returns {?string} The target id, if found. Will also be null if the target found is the stage. + */ + getTargetIdForDrawableId(drawableId: number): string | null; + /** + * CCW: Get all global procedures and pass to target + * @returns {Array} Array of XML strings + */ + getWorkspaceGlobalProcedures(): any[]; + /** + * Reorder target by index. Return whether a change was made. + * @param {!string} targetIndex Index of the target. + * @param {!number} newIndex index that the target should be moved to. + * @param {!boolean} isRemoteOperation - set to true if this is a remote operation + * @returns {boolean} Whether a target was reordered. + */ + reorderTarget( + targetIndex: string, + newIndex: number, + isRemoteOperation: boolean + ): boolean; + /** + * Reorder the costumes of a target if it exists. Return whether it succeeded. + * @param {!string} targetId ID of the target which owns the costumes. + * @param {!number} costumeIndex index of the costume to move. + * @param {!number} newIndex index that the costume should be moved to. + * @returns {boolean} Whether a costume was reordered. + */ + reorderCostume( + targetId: string, + costumeIndex: number, + newIndex: number + ): boolean; + /** + * Reorder the sounds of a target if it exists. Return whether it occured. + * @param {!string} targetId ID of the target which owns the sounds. + * @param {!number} soundIndex index of the sound to move. + * @param {!number} newIndex index that the sound should be moved to. + * @returns {boolean} Whether a sound was reordered. + */ + reorderSound( + targetId: string, + soundIndex: number, + newIndex: number + ): boolean; + /** + * Put a target into a "drag" state, during which its X/Y positions will be unaffected + * by blocks. + * @param {string} targetId The id for the target to put into a drag state + */ + startDrag(targetId: string): void; + /** + * Remove a target from a drag state, so blocks may begin affecting X/Y position again + * @param {string} targetId The id for the target to remove from the drag state + */ + stopDrag(targetId: string): void; + /** + * Post/edit sprite info for the current editing target or the drag target. + * @param {object} data An object with sprite info data to set. + * @param {?string} targetId The id for the target to set info. + */ + postSpriteInfo(data: object, targetId: string | null): void; + /** + * Set a target's variable's value. Return whether it succeeded. + * @param {!string} targetId ID of the target which owns the variable. + * @param {!string} variableId ID of the variable to set. + * @param {!*} value The new value of that variable. + * @returns {boolean} whether the target and variable were found and updated. + */ + setVariableValue(targetId: string, variableId: string, value: any): boolean; + /** + * Get a target's variable's value. Return null if the target or variable does not exist. + * @param {!string} targetId ID of the target which owns the variable. + * @param {!string} variableId ID of the variable to set. + * @returns {?*} The value of the variable, or null if it could not be looked up. + */ + getVariableValue(targetId: string, variableId: string): any | null; + /** + * Allow VM consumer to configure the ScratchLink socket creator. + * @param {Function} factory The custom ScratchLink socket factory. + */ + configureScratchLinkSocketFactory(factory: Function): void; + /** + * Adapts a given XML element for blocks or frames. + * + * @param {Element} xml - The XML element to be adapted. + * @returns {Array. | null} A list of block or frame from the adapted XML. + */ + xmlAdapter(xml: Element): Array | null; + } + // namespace VirtualMachine { + // export { Progress }; + // } + import EventEmitter = require("events"); + type Runtime = import("scratch-vm-dts/engine/runtime"); + type ExtensionManager = import("scratch-vm-dts/extension-support/extension-manager"); + type Sprite = import("scratch-vm-dts/sprites/sprite"); + type RenderedTarget = import("scratch-vm-dts/sprites/rendered-target"); + import JSZip = require("@turbowarp/jszip"); + /** + * - Information about the loading progress + */ + type Progress = { + /** + * - The total number of loaded things + */ + total: number; + /** + * - The number of loads completed + */ + loaded: number; + }; +} +//以下代码未被打包器载入,为手动编写 +declare module "scratch-vm-dts/compiler/jsgen" { + export = JSGenerator; + type Target = import("scratch-vm-dts/engine/target"); + class JSGenerator { + /** + * @param {IntermediateScript} script + * @param {IntermediateRepresentation} ir + * @param {Target} target + */ + constructor( + script: IntermediateScript, + ir: IntermediateRepresentation, + target: Target + ); + script: IntermediateScript; + ir: IntermediateRepresentation; + target: Target; + source: string; + /** + * @type {Object.} + */ + variableInputs: { + [x: string]: VariableInput; + }; + isWarp: boolean; + isProcedure: boolean; + warpTimer: boolean; + /** + * Stack of frames, most recent is last item. + * @type {Frame[]} + */ + frames: Frame[]; + /** + * The current Frame. + * @type {Frame} + */ + currentFrame: Frame; + namesOfCostumesAndSounds: Set; + localVariables: VariablePool; + _setupVariablesPool: VariablePool; + _setupVariables: {}; + descendedIntoModulo: boolean; + isInHat: boolean; + debug: any; + /** + * Enter a new frame + * @param {Frame} frame New frame. + */ + pushFrame(frame: Frame): void; + /** + * Exit the current frame + */ + popFrame(): void; + /** + * @returns {boolean} true if the current block is the last command of a loop + */ + isLastBlockInLoop(): boolean; + /** + * @param {object} node Input node to compile. + * @returns {Input} Compiled input. + */ + descendInput(node: object): Input; + /** + * @param {*} node Stacked node to compile. + */ + descendStackedBlock(node: any): TypedInput | undefined; + /** + * Compile a Record of input objects into a safe JS string. + * @param {Record} inputs + * @returns {string} + */ + descendInputRecord(inputs: Record): string; + resetVariableInputs(): void; + descendStack(nodes: any, frame: any): void; + descendVariable(variable: any): VariableInput; + descendProcedure(node: any): string | undefined; + referenceVariable(variable: any): any; + descendAddonCall(node: any): string; + evaluateOnce(source: any): any; + retire(): void; + stopScript(): void; + stopScript(): void; + /** + * @param {string} valueJS JS code of value to return. + */ + stopScriptAndReturn(valueJS: string): void; + /** + * @param {string} valueJS JS code of value to return. + */ + stopScriptAndReturn(valueJS: string): void; + yieldLoop(): void; + /** + * Write JS to yield the current thread if warp mode is disabled. + */ + yieldNotWarp(): void; + /** + * Write JS to yield the current thread if warp mode is disabled or if the script seems to be stuck. + */ + yieldStuckOrNotWarp(): void; + yielded(): void; + /** + * Write JS to request a redraw. + */ + requestRedraw(): void; + safeConstantInput(value: any): ConstantInput; + /** + * Generate a call into the compatibility layer. + * @param {*} node The "compat" kind node to generate from. + * @param {boolean} setFlags Whether flags should be set describing how this function was processed. + * @param {string|null} [frameName] Name of the stack frame variable, if any + * @returns {string} The JS of the call. + */ + generateCompatibilityLayerCall( + node: any, + setFlags: boolean, + frameName?: string | null + ): string; + getScriptFactoryName(): string; + getScriptName(yields: any): string; + /** + * Generate the JS to pass into eval() based on the current state of the compiler. + * @returns {string} JS to pass into eval() + */ + createScriptFactory(): string; + /** + * Compile this script. + * @returns {Function} The factory function for the script. + */ + compile(): Function; + } + namespace JSGenerator { + export { unstable_exports, testingApparatus, Input }; + } + type IntermediateScript = + import("scratch-vm-dts/compiler/intermediate").IntermediateScript; + type IntermediateRepresentation = + import("scratch-vm-dts/compiler/intermediate").IntermediateRepresentation; + /** + * @implements {Input} + */ + class VariableInput implements Input { + constructor(source: any); + source: any; + type: number; + /** + * The value this variable was most recently set to, if any. + * @type {Input} + * @private + */ + private _value; + /** + * @param {Input} input The input this variable was most recently set to. + */ + setInput(input: Input): void; + asNumber(): any; + asNumberOrNaN(): any; + asString(): any; + asBoolean(): any; + asColor(): any; + asUnknown(): any; + asSafe(): any; + isAlwaysNumber(): boolean; + isAlwaysNumberOrNaN(): boolean; + isNeverNumber(): boolean; + } + /** + * A frame contains some information about the current substack being compiled. + */ + class Frame { + constructor(isLoop: any); + /** + * Whether the current stack runs in a loop (while, for) + * @type {boolean} + * @readonly + */ + readonly isLoop: boolean; + /** + * Whether the current block is the last block in the stack. + * @type {boolean} + */ + isLastBlock: boolean; + } + type VariablePool = import("scratch-vm-dts/compiler/variable-pool"); + /** + * @typedef Input + * @property {() => string} asNumber + * @property {() => string} asNumberOrNaN + * @property {() => string} asString + * @property {() => string} asBoolean + * @property {() => string} asColor + * @property {() => string} asUnknown + * @property {() => string} asSafe + * @property {() => boolean} isAlwaysNumber + * @property {() => boolean} isAlwaysNumberOrNaN + * @property {() => boolean} isNeverNumber + */ + /** + * @implements {Input} + */ + class TypedInput implements Input { + constructor(source: any, type: any); + source: any; + type: number; + asNumber(): any; + asNumberOrNaN(): any; + asString(): any; + asBoolean(): any; + asColor(): any; + asUnknown(): any; + asSafe(): any; + asProcedureReturn(): string; + isAlwaysNumber(): boolean; + isAlwaysNumberOrNaN(): boolean; + isNeverNumber(): boolean; + } + /** + * @implements {Input} + */ + class ConstantInput implements Input { + constructor(constantValue: any, safe: any); + constantValue: any; + safe: any; + asNumber(): string; + asNumberOrNaN(): string; + asString(): string; + asBoolean(): string; + asColor(): any; + asUnknown(): any; + asSafe(): any; + isAlwaysNumber(): boolean; + isAlwaysNumberOrNaN(): boolean; + isNeverNumber(): boolean; + } + namespace unstable_exports { + export { TYPE_NUMBER }; + export { TYPE_STRING }; + export { TYPE_BOOLEAN }; + export { TYPE_UNKNOWN }; + export { TYPE_NUMBER_NAN }; + export { factoryNameVariablePool }; + export { functionNameVariablePool }; + export { generatorNameVariablePool }; + export { VariablePool }; + export { PEN_EXT }; + export { PEN_STATE }; + export { TypedInput }; + export { ConstantInput }; + export { VariableInput }; + export { Frame }; + export { sanitize }; + } + var testingApparatus: any; + type Input = { + asNumber: () => string; + asNumberOrNaN: () => string; + asString: () => string; + asBoolean: () => string; + asColor: () => string; + asUnknown: () => string; + asSafe: () => string; + isAlwaysNumber: () => boolean; + isAlwaysNumberOrNaN: () => boolean; + isNeverNumber: () => boolean; + }; + const TYPE_NUMBER: 1; + const TYPE_STRING: 2; + const TYPE_BOOLEAN: 3; + const TYPE_UNKNOWN: 4; + const TYPE_NUMBER_NAN: 5; + /** + * Variable pool used for factory function names. + */ + const factoryNameVariablePool: VariablePool; + /** + * Variable pool used for generated functions (non-generator) + */ + const functionNameVariablePool: VariablePool; + /** + * Variable pool used for generated generator functions. + */ + const generatorNameVariablePool: VariablePool; + const PEN_EXT: "runtime.ext_pen"; + const PEN_STATE: "runtime.ext_pen._getPenState(target)"; + /** + * @fileoverview Convert intermediate representations to JavaScript functions. + */ + function sanitize(string: any): string; +} + +declare module "scratch-vm-dts/compiler/intermediate" { + /** + * @fileoverview Common intermediates shared amongst parts of the compiler. + */ + /** + * An IntermediateScript describes a single script. + * Scripts do not necessarily have hats. + */ + type Target = import("scratch-vm-dts/engine/target"); + export class IntermediateScript { + /** + * The ID of the top block of this script. + * @type {string} + */ + topBlockId: string; + /** + * List of nodes that make up this script. + * @type {Array|null} + */ + stack: any[] | null; + /** + * Whether this script is a procedure. + * @type {boolean} + */ + isProcedure: boolean; + /** + * This procedure's variant, if any. + * @type {string} + */ + procedureVariant: string; + /** + * This procedure's code, if any. + * @type {string} + */ + procedureCode: string; + /** + * List of names of arguments accepted by this function, if it is a procedure. + * @type {string[]} + */ + arguments: string[]; + /** + * Whether this script should be run in warp mode. + * @type {boolean} + */ + isWarp: boolean; + /** + * Whether this script can `yield` + * If false, this script will be compiled as a regular JavaScript function (function) + * If true, this script will be compiled as a generator function (function*) + * @type {boolean} + */ + yields: boolean; + /** + * Whether this script should use the "warp timer" + * @type {boolean} + */ + warpTimer: boolean; + /** + * List of procedure IDs that this script needs. + * @readonly + */ + readonly dependedProcedures: any[]; + /** + * Cached result of compiling this script. + * @type {Function|null} + */ + cachedCompileResult: Function | null; + /** + * global procedure target + * @type {Target|null} + */ + target: Target | null; + /** + * Whether the top block of this script is an executable hat. + * @type {boolean} + */ + executableHat: boolean; + } + /** + * An IntermediateRepresentation contains scripts. + */ + export class IntermediateRepresentation { + /** + * The entry point of this IR. + * @type {IntermediateScript} + */ + entry: IntermediateScript; + /** + * Maps procedure variants to their intermediate script. + * @type {Object.} + */ + procedures: { + [x: string]: IntermediateScript; + }; + } +} + +declare module "scratch-vm-dts/compiler/variable-pool" { + export = VariablePool; + class VariablePool { + /** + * @param {string} prefix The prefix at the start of the variable name. + */ + constructor(prefix: string); + prefix: string; + /** + * @private + */ + private count; + next(): string; + } +} + +declare module "scratch-vm-dts/compiler/irgen" { + class Block { } + export type Node = { + [x: string]: any; + }; + export class ScriptTreeGenerator { + constructor(thread: any); + /** @private */ + private thread; + /** @private */ + private target; + /** @private */ + private blocks; + /** @private */ + private runtime; + /** @private */ + private stage; + /** + * This script's intermediate representation. + */ + script: IntermediateScript; + /** + * Cache of variable ID to variable data object. + * @type {Object.} + * @private + */ + private variableCache: { [key: string]: object }; + usesTimer: boolean; + setProcedureVariant(procedureVariant: any, globalTarget: any): void; + enableWarp(): void; + getBlockById(blockId: any): any; + getBlockInfo(fullOpcode: any): any; + /** + * Descend into a child input of a block. (eg. the input STRING of "length of ( )") + * @param {*} parentBlock The parent Scratch block that contains the input. + * @param {string} inputName The name of the input to descend into. + * @private + * @returns {Node} Compiled input node for this input. + */ + private descendInputOfBlock; + /** + * Descend into an input. (eg. "length of ( )") + * @param {*} block The parent Scratch block input. + * @private + * @returns {Node} Compiled input node for this input. + */ + private descendInput; + /** + * Descend into a stacked block. (eg. "move ( ) steps") + * @param {*} block The Scratch block to parse. + * @private + * @returns {Node} Compiled node for this block. + */ + private descendStackedBlock; + /** + * Descend into a stack of blocks (eg. the blocks contained within an "if" block) + * @param {*} parentBlock The parent Scratch block that contains the stack to parse. + * @param {*} substackName The name of the stack to descend into. + * @private + * @returns {Node[]} List of stacked block nodes. + */ + private descendSubstack; + /** + * Descend into and walk the siblings of a stack. + * @param {string} startingBlockId The ID of the first block of a stack. + * @private + * @returns {Node[]} List of stacked block nodes. + */ + private walkStack; + /** + * Descend into a variable. + * @param {*} block The block that has the variable. + * @param {string} fieldName The name of the field that the variable is stored in. + * @param {''|'list'} type Variable type, '' for scalar and 'list' for list. + * @private + * @returns {*} A parsed variable object. + */ + private descendVariable; + /** + * @param {string} id The ID of the variable. + * @param {string} name The name of the variable. + * @param {''|'list'} type The variable type. + * @private + * @returns {*} A parsed variable object. + */ + private _descendVariable; + descendProcedure(block: any): + | { + kind: string; + code?: undefined; + arguments?: undefined; + blockId?: undefined; + variant?: undefined; + } + | { + kind: string; + code: any; + arguments: {}; + blockId: any; + variant?: undefined; + } + | { + kind: string; + code: any; + variant: string; + arguments: { + [x: string]: any; + }[]; + blockId?: undefined; + }; + /** + * Descend into a block that uses the compatibility layer. + * @param {*} block The block to use the compatibility layer for. + * @private + * @returns {Node} The parsed node. + */ + private descendCompatLayer; + analyzeLoop(): void; + readTopBlockComment(commentId: any): void; + descendVisualReport(block: any): { + kind: string; + input: { + [x: string]: any; + }; + } | null; + /** + * @param {Block} hatBlock + */ + walkHat(hatBlock: Block): { + [x: string]: any; + }[]; + /** + * @param {string} topBlockId The ID of the top block of the script. + * @returns {IntermediateScript} + */ + generate(topBlockId: string): IntermediateScript; + } + export class IRGenerator { + constructor(thread: any); + thread: any; + blocks: any; + proceduresToCompile: Map; + compilingProcedures: Map; + /** @type {Object.} */ + procedures: { + [x: string]: IntermediateScript; + }; + analyzedProcedures: any[]; + getProcedureDefinitionAndTarget(procedureCode: any): any; + addProcedureDependencies(dependencies: any): void; + /** + * @param {ScriptTreeGenerator} generator The generator to run. + * @param {string} topBlockId The ID of the top block in the stack. + * @returns {IntermediateScript} Intermediate script. + */ + generateScriptTree( + generator: ScriptTreeGenerator, + topBlockId: string + ): IntermediateScript; + /** + * Recursively analyze a script and its dependencies. + * @param {IntermediateScript} script Intermediate script. + */ + analyzeScript(script: IntermediateScript): boolean; + /** + * @returns {IntermediateRepresentation} Intermediate representation. + */ + generate(): IntermediateRepresentation; + } + type IntermediateScript = + import("scratch-vm-dts/compiler/intermediate").IntermediateScript; + type IntermediateRepresentation = + import("scratch-vm-dts/compiler/intermediate").IntermediateRepresentation; +} + +declare module "scratch-vm-dts/extensions/scratch3_pen" { + export = Scratch3PenBlocks; + type Runtime = import("scratch-vm-dts/engine/runtime"); + class PenAttributes { } + /** + * @typedef {object} PenState - the pen state associated with a particular target. + * @property {Boolean} penDown - tracks whether the pen should draw for this target. + * @property {number} color - the current color (hue) of the pen. + * @property {PenAttributes} penAttributes - cached pen attributes for the renderer. This is the authoritative value for + * diameter but not for pen color. + */ + /** + * Host for the Pen-related blocks in Scratch 3.0 + * @param {Runtime} runtime - the runtime instantiating this block package. + * @constructor + */ + class Scratch3PenBlocks { + /** + * The default pen state, to be used when a target has no existing pen state. + * @type {PenState} + */ + static get DEFAULT_PEN_STATE(): PenState; + /** + * The minimum and maximum allowed pen size. + * The maximum is twice the diagonal of the stage, so that even an + * off-stage sprite can fill it. + * @type {{min: number, max: number}} + */ + static get PEN_SIZE_RANGE(): { + min: number; + max: number; + }; + /** + * The key to load & store a target's pen-related state. + * @type {string} + */ + static get STATE_KEY(): string; + constructor(runtime: any); + /** + * The runtime instantiating this block package. + * @type {Runtime} + */ + runtime: Runtime; + /** + * The ID of the renderer Drawable corresponding to the pen layer. + * @type {int} + * @private + */ + private _penDrawableId; + /** + * The ID of the renderer Skin corresponding to the pen layer. + * @type {int} + * @private + */ + private _penSkinId; + /** + * When a pen-using Target is cloned, clone the pen state. + * @param {Target} newTarget - the newly created target. + * @param {Target} [sourceTarget] - the target used as a source for the new clone, if any. + * @listens Runtime#event:targetWasCreated + * @private + */ + private _onTargetCreated; + /** + * Handle a target which has moved. This only fires when the pen is down. + * @param {RenderedTarget} target - the target which has moved. + * @param {number} oldX - the previous X position. + * @param {number} oldY - the previous Y position. + * @param {boolean} isForce - whether the movement was forced. + * @private + */ + private _onTargetMoved; + /** + * Clamp a pen size value to the range allowed by the pen. + * @param {number} requestedSize - the requested pen size. + * @returns {number} the clamped size. + * @private + */ + private _clampPenSize; + /** + * Retrieve the ID of the renderer "Skin" corresponding to the pen layer. If + * the pen Skin doesn't yet exist, create it. + * @returns {int} the Skin ID of the pen layer, or -1 on failure. + * @private + */ + private _getPenLayerID; + /** + * @param {Target} target - collect pen state for this target. Probably, but not necessarily, a RenderedTarget. + * @returns {PenState} the mutable pen state associated with that target. This will be created if necessary. + * @private + */ + private _getPenState; + /** + * Wrap a color input into the range (0,100). + * @param {number} value - the value to be wrapped. + * @returns {number} the wrapped value. + * @private + */ + private _wrapColor; + /** + * Initialize color parameters menu with localized strings + * @returns {array} of the localized text and values for each menu element + * @private + */ + private _initColorParam; + /** + * Clamp a pen color parameter to the range (0,100). + * @param {number} value - the value to be clamped. + * @returns {number} the clamped value. + * @private + */ + private _clampColorParam; + /** + * Convert an alpha value to a pen transparency value. + * Alpha ranges from 0 to 1, where 0 is transparent and 1 is opaque. + * Transparency ranges from 0 to 100, where 0 is opaque and 100 is transparent. + * @param {number} alpha - the input alpha value. + * @returns {number} the transparency value. + * @private + */ + private _alphaToTransparency; + /** + * Convert a pen transparency value to an alpha value. + * Alpha ranges from 0 to 1, where 0 is transparent and 1 is opaque. + * Transparency ranges from 0 to 100, where 0 is opaque and 100 is transparent. + * @param {number} transparency - the input transparency value. + * @returns {number} the alpha value. + * @private + */ + private _transparencyToAlpha; + /** + * @returns {object} metadata for this extension and its blocks. + */ + getInfo(): object; + /** + * The pen "clear" block clears the pen layer's contents. + */ + clear(): void; + /** + * The pen "stamp" block stamps the current drawable's image onto the pen layer. + * @param {object} args - the block arguments. + * @param {object} util - utility object provided by the runtime. + */ + stamp(args: object, util: object): void; + _stamp(target: any): void; + /** + * The pen "pen down" block causes the target to leave pen trails on future motion. + * @param {object} args - the block arguments. + * @param {object} util - utility object provided by the runtime. + */ + penDown(args: object, util: object): void; + _penDown(target: any): void; + /** + * The pen "pen up" block stops the target from leaving pen trails. + * @param {object} args - the block arguments. + * @param {object} util - utility object provided by the runtime. + */ + penUp(args: object, util: object): void; + _penUp(target: any): void; + /** + * The pen "set pen color to {color}" block sets the pen to a particular RGB color. + * The transparency is reset to 0. + * @param {object} args - the block arguments. + * @property {int} COLOR - the color to set, expressed as a 24-bit RGB value (0xRRGGBB). + * @param {object} util - utility object provided by the runtime. + */ + setPenColorToColor(args: object, util: object): void; + _setPenColorToColor(color: any, target: any): void; + /** + * Update the cached color from the color, saturation, brightness and transparency values + * in the provided PenState object. + * @param {PenState} penState - the pen state to update. + * @private + */ + private _updatePenColor; + /** + * Set or change a single color parameter on the pen state, and update the pen color. + * @param {ColorParam} param - the name of the color parameter to set or change. + * @param {number} value - the value to set or change the param by. + * @param {PenState} penState - the pen state to update. + * @param {boolean} change - if true change param by value, if false set param to value. + * @private + */ + private _setOrChangeColorParam; + /** + * The "change pen {ColorParam} by {number}" block changes one of the pen's color parameters + * by a given amound. + * @param {object} args - the block arguments. + * @property {ColorParam} COLOR_PARAM - the name of the selected color parameter. + * @property {number} VALUE - the amount to change the selected parameter by. + * @param {object} util - utility object provided by the runtime. + */ + changePenColorParamBy(args: object, util: object): void; + /** + * The "set pen {ColorParam} to {number}" block sets one of the pen's color parameters + * to a given amound. + * @param {object} args - the block arguments. + * @property {ColorParam} COLOR_PARAM - the name of the selected color parameter. + * @property {number} VALUE - the amount to set the selected parameter to. + * @param {object} util - utility object provided by the runtime. + */ + setPenColorParamTo(args: object, util: object): void; + /** + * The pen "change pen size by {number}" block changes the pen size by the given amount. + * @param {object} args - the block arguments. + * @property {number} SIZE - the amount of desired size change. + * @param {object} util - utility object provided by the runtime. + */ + changePenSizeBy(args: object, util: object): void; + _changePenSizeBy(size: any, target: any): void; + /** + * The pen "set pen size to {number}" block sets the pen size to the given amount. + * @param {object} args - the block arguments. + * @property {number} SIZE - the amount of desired size change. + * @param {object} util - utility object provided by the runtime. + */ + setPenSizeTo(args: object, util: object): void; + _setPenSizeTo(size: any, target: any): void; + /** + * Scratch 2 "hue" param is equivelant to twice the new "color" param. + * @param {object} args - the block arguments. + * @property {number} HUE - the amount to set the hue to. + * @param {object} util - utility object provided by the runtime. + */ + setPenHueToNumber(args: object, util: object): void; + _setPenHueToNumber(hueValue: any, target: any): void; + /** + * Scratch 2 "hue" param is equivelant to twice the new "color" param. + * @param {object} args - the block arguments. + * @property {number} HUE - the amount of desired hue change. + * @param {object} util - utility object provided by the runtime. + */ + changePenHueBy(args: object, util: object): void; + _changePenHueBy(hueChange: any, target: any): void; + /** + * Use legacy "set shade" code to calculate RGB value for shade, + * then convert back to HSV and store those components. + * It is important to also track the given shade in penState._shade + * because it cannot be accurately backed out of the new HSV later. + * @param {object} args - the block arguments. + * @property {number} SHADE - the amount to set the shade to. + * @param {object} util - utility object provided by the runtime. + */ + setPenShadeToNumber(args: object, util: object): void; + _setPenShadeToNumber(shade: any, target: any): void; + /** + * Because "shade" cannot be backed out of hsv consistently, use the previously + * stored penState._shade to make the shade change. + * @param {object} args - the block arguments. + * @property {number} SHADE - the amount of desired shade change. + * @param {object} util - utility object provided by the runtime. + */ + changePenShadeBy(args: object, util: object): void; + _changePenShadeBy(shade: any, target: any): void; + /** + * Update the pen state's color from its hue & shade values, Scratch 2.0 style. + * @param {object} penState - update the HSV & RGB values in this pen state from its hue & shade values. + * @private + */ + private _legacyUpdatePenColor; + } + namespace Scratch3PenBlocks { + export { PenState }; + } + /** + * - the pen state associated with a particular target. + */ + type PenState = { + /** + * - tracks whether the pen should draw for this target. + */ + penDown: boolean; + /** + * - the current color (hue) of the pen. + */ + color: number; + /** + * - cached pen attributes for the renderer. This is the authoritative value for + * diameter but not for pen color. + */ + penAttributes: PenAttributes; + }; +} + +declare module "scratch-vm-dts/engine/block-utility" { + export = BlockUtility; + type Sequencer = import("scratch-vm-dts/engine/sequencer"); + type Target = import("scratch-vm-dts/engine/target"); + type Runtime = import("scratch-vm-dts/engine/runtime"); + /** + * @fileoverview + * Interface provided to block primitive functions for interacting with the + * runtime, thread, target, and convenient methods. + */ + class BlockUtility { + constructor(sequencer?: null, thread?: null); + /** + * A sequencer block primitives use to branch or start procedures with + * @type {?Sequencer} + */ + sequencer: Sequencer | null; + /** + * The block primitives thread with the block's target, stackFrame and + * modifiable status. + * @type {?Thread} + */ + thread: Thread | null; + _nowObj: { + now: () => any; + }; + /** + * The target the primitive is working on. + * @type {Target} + */ + get target(): Target; + /** + * The runtime the block primitive is running in. + * @type {Runtime} + */ + get runtime(): Runtime; + /** + * Use the runtime's currentMSecs value as a timestamp value for now + * This is useful in some cases where we need compatibility with Scratch 2 + * @type {function} + */ + get nowObj(): Function; + /** + * The stack frame used by loop and other blocks to track internal state. + * @type {object} + */ + get stackFrame(): object; + /** + * Check the stack timer and return a boolean based on whether it has finished or not. + * @return {boolean} - true if the stack timer has finished. + */ + stackTimerFinished(): boolean; + /** + * Check if the stack timer needs initialization. + * @return {boolean} - true if the stack timer needs to be initialized. + */ + stackTimerNeedsInit(): boolean; + /** + * Create and start a stack timer + * @param {number} duration - a duration in milliseconds to set the timer for. + */ + startStackTimer(duration: number): void; + /** + * Set the thread to yield. + */ + yield(): void; + /** + * Set the thread to yield until the next tick of the runtime. + */ + yieldTick(): void; + /** + * Start a branch in the current block. + * @param {number} branchNum Which branch to step to (i.e., 1, 2). + * @param {boolean} isLoop Whether this block is a loop. + */ + startBranch(branchNum: number, isLoop: boolean): void; + /** + * Stop all threads. + */ + stopAll(): void; + /** + * Stop threads other on this target other than the thread holding the + * executed block. + */ + stopOtherTargetThreads(): void; + /** + * Stop this thread. + */ + stopThisScript(): void; + /** + * Start a specified procedure on this thread. + * @param {string} procedureCode Procedure code for procedure to start. + */ + startProcedure(procedureCode: string, globalTarget: any): void; + /** + * Get names and ids of parameters for the given procedure. + * @param {string} procedureCode Procedure code for procedure to query. + * @return {Array.} List of param names for a procedure. + */ + getProcedureParamNamesAndIds(procedureCode: string): Array; + /** + * Get names, ids, and defaults of parameters for the given procedure. + * @param {string} procedureCode Procedure code for procedure to query. + * @return {Array.} List of param names for a procedure. + */ + getProcedureParamNamesIdsAndDefaults( + procedureCode: string, + isGlobal: any + ): Array; + /** + * Initialize procedure parameters in the thread before pushing parameters. + */ + initParams(): void; + /** + * Store a procedure parameter value by its name. + * @param {string} paramName The procedure's parameter name. + * @param {*} paramValue The procedure's parameter value. + */ + pushParam(paramName: string, paramValue: any): void; + /** + * Retrieve the stored parameter value for a given parameter name. + * @param {string} paramName The procedure's parameter name. + * @return {*} The parameter's current stored value. + */ + getParam(paramName: string): any; + getHatParam(paramName: any): any; + /** + * Start all relevant hats. + * @param {!string} requestedHat Opcode of hats to start. + * @param {object=} optMatchFields Optionally, fields to match on the hat. + * @param {Target=} optTarget Optionally, a target to restrict to. + * @param {object=} hatParam Optionally, start hats with ccw_hat_parameter if true, + will skip field check and inject ccw_hat_parameter to thread. + * @return {Array.} List of threads started by this function. + */ + startHats( + requestedHat: string, + optMatchFields?: object | undefined, + optTarget?: Target | undefined, + hatParam?: object | undefined + ): Array; + /** + * CCW + startHatsWithParams is only used in block utility for extension, + WhitExtraMsg means skip field check when start a hat block. + define here is only for debug + * @param {!string} requestedHat Opcode of hats to start. + * @param {object} data Optionally, contains fields to match on the hat and parameters to ccw_hat_parameter. + * @param {Target=} optTarget Optionally, a target to restrict to. + * @return {Array.} List of threads started by this function. + */ + startHatsWithParams( + requestedHat: string, + data: object, + optTarget?: Target | undefined + ): Array; + /** + * Query a named IO device. + * @param {string} device The name of like the device, like keyboard. + * @param {string} func The name of the device's function to query. + * @param {Array.<*>} args Arguments to pass to the device's function. + * @return {*} The expected output for the device's function. + */ + ioQuery(device: string, func: string, args: Array): any; + } + type Thread = import("scratch-vm-dts/engine/thread"); +} +//以上代码未被打包器载入 +declare module "scratch-vm-dts/engine/target" { + export = Target; + type Runtime = import("scratch-vm-dts/engine/runtime"); + class bool extends Boolean { } + // 666,写类型注解不好好写,还要我定义接口 + interface Frame { + id: string; + title: string; + x: number; + y: number; + width: number; + height: number; + } + /** + * @fileoverview + * A Target is an abstract "code-running" object for the Scratch VM. + * Examples include sprites/clones or potentially physical-world devices. + */ + class Target extends EventEmitter<[never]> { + /** + * @param {Runtime} runtime Reference to the runtime. + * @param {?Blocks} blocks Blocks instance for the blocks owned by this target. + * @param {?Frames} frames Shared frames object for all clones of sprite. + * @param {?id} id Target id. + * @constructor + */ + constructor( + runtime: Runtime, + blocks: Blocks | null, + frames: Frames | null, + id: any | null + ); + /** + * Reference to the runtime. + * @type {Runtime} + */ + runtime: Runtime; + /** + * A unique ID for this target. + * @type {string} + */ + id: string; + /** + * Blocks run as code for this target. + * @type {!Blocks} + */ + blocks: Blocks; + /** + * Dictionary of variables and their values for this target. + * Key is the variable id. + * @type {Object.} + */ + variables: { + [x: string]: any; + }; + /** + * Dictionary of comments for this target. + * Key is the comment id. + * @type {Object.} + */ + comments: { + [x: string]: any; + }; + /** + * All frames that this target contains. + * @type {!Frames} + */ + frames: Frames; + /** + * Dictionary of custom state for this target. + * This can be used to store target-specific custom state for blocks which need it. + * TODO: do we want to persist this in SB3 files? + * @type {Object.} + */ + _customState: { + [x: string]: any; + }; + /** + * Currently known values for edge-activated hats. + * Keys are block ID for the hat; values are the currently known values. + * @type {Object.} + */ + _edgeActivatedHatValues: { + [x: string]: any; + }; + /** + * Maps extension ID to a JSON-serializable value. + * @type {Object.} + */ + extensionStorage: { + [x: string]: object; + }; + /** + * Called when the project receives a "green flag." + * @abstract + */ + onGreenFlag(): void; + /** + * Return a human-readable name for this target. + * Target implementations should override this. + * @abstract + * @returns {string} Human-readable name for the target. + */ + getName(): string; + /** + * Update an edge-activated hat block value. + * @param {!string} blockId ID of hat to store value for. + * @param {*} newValue Value to store for edge-activated hat. + * @return {*} The old value for the edge-activated hat. + */ + updateEdgeActivatedValue(blockId: string, newValue: any): any; + hasEdgeActivatedValue(blockId: any): boolean; + /** + * Clear all edge-activaed hat values. + */ + clearEdgeActivatedValues(): void; + /** + * Look up a variable object, first by id, and then by name if the id is not found. + * Create a new variable if both lookups fail. + * @param {string} id Id of the variable. + * @param {string} name Name of the variable. + * @return {!Variable} Variable object. + */ + lookupOrCreateVariable(id: string, name: string): Variable; + /** + * Look up a broadcast message object with the given id and return it + * if it exists. + * @param {string} id Id of the variable. + * @param {string} name Name of the variable. + * @return {?Variable} Variable object. + */ + lookupBroadcastMsg(id: string, name: string): Variable | null; + /** + * Look up a broadcast message with the given name and return the variable + * if it exists. Does not create a new broadcast message variable if + * it doesn't exist. + * @param {string} name Name of the variable. + * @return {?Variable} Variable object. + */ + lookupBroadcastByInputValue(name: string): Variable | null; + /** + * Look up a variable object. + * Search begins for local variables; then look for globals. + * @param {string} id Id of the variable. + * @param {string} name Name of the variable. + * @return {!Variable} Variable object. + */ + lookupVariableById(id: string): Variable; + /** + * Look up a variable object by its name and variable type. + * Search begins with local variables; then global variables if a local one + * was not found. + * @param {string} name Name of the variable. + * @param {string} type Type of the variable. Defaults to Variable.SCALAR_TYPE. + * @param {?bool} skipStage Optional flag to skip checking the stage + * @return {?Variable} Variable object if found, or null if not. + */ + lookupVariableByNameAndType( + name: string, + type: string, + skipStage: bool | null + ): Variable | null; + /** + * Look up if a variable is being used based on its name and type. + * @param {string} name Name of the variable. + * @param {string} type Type of the variable. Defaults to Variable.SCALAR_TYPE. + * @return {?bool} True if found, or false if not. + */ + findVariableUsage(name: string, type: string): bool | null; + /** + * Look up a list object for this target, and create it if one doesn't exist. + * Search begins for local lists; then look for globals. + * @param {!string} id Id of the list. + * @param {!string} name Name of the list. + * @return {!Variable} Variable object representing the found/created list. + */ + lookupOrCreateList(id: string, name: string): Variable; + /** + * Creates a variable with the given id and name and adds it to the + * dictionary of variables. + * @param {string} id Id of variable + * @param {string} name Name of variable. + * @param {string} type Type of variable, '', 'broadcast_msg', or 'list' + * @param {boolean} isCloud Whether the variable to create has the isCloud flag set. + * @param {boolean} isRemoteOperation - Set to true if this is a remote operation + * Additional checks are made that the variable can be created as a cloud variable. + */ + createVariable( + id: string, + name: string, + type: string, + isCloud: boolean, + isRemoteOperation: boolean + ): void; + /** + * Creates a comment with the given properties. + * @param {string} id Id of the comment. + * @param {string} blockId Optional id of the block the comment is attached + * to if it is a block comment. + * @param {string} text The text the comment contains. + * @param {number} x The x coordinate of the comment on the workspace. + * @param {number} y The y coordinate of the comment on the workspace. + * @param {number} width The width of the comment when it is full size + * @param {number} height The height of the comment when it is full size + * @param {boolean} minimized Whether the comment is minimized. + * @param {boolean} isRemoteOperation - set to true if this is a remote operation + */ + createComment( + id: string, + blockId: string, + text: string, + x: number, + y: number, + width: number, + height: number, + minimized: boolean, + isRemoteOperation: boolean + ): void; + /** + * Creates a frame with the given properties. + * @param {Frame} frame The definition of the frame. + */ + createFrame(frame: Frame): boolean; + /** + * Removes the frame with the given id from the dictionary of frames. + * @param {string} id Id of frame to delete. + */ + deleteFrame(id: string): void; + /** + * Renames the variable with the given id to newName. + * @param {string} id Id of variable to rename. + * @param {string} newName New name for the variable. + */ + renameVariable(id: string, newName: string): void; + /** + * Removes the variable with the given id from the dictionary of variables. + * @param {string} id Id of variable to delete. + * @param {boolean} isRemoteOperation - set to true if this is a remote operation + */ + deleteVariable(id: string, isRemoteOperation: boolean): void; + /** + * Remove this target's monitors from the runtime state and remove the + * target-specific monitored blocks (e.g. local variables, global variables for the stage, x-position). + * NOTE: This does not delete any of the stage monitors like backdrop name. + */ + deleteMonitors(): void; + /** + * Create a clone of the variable with the given id from the dictionary of + * this target's variables. + * @param {string} id Id of variable to duplicate. + * @param {boolean=} optKeepOriginalId Optional flag to keep the original variable ID + * @param {!object} targetId ID of the target which owns the variable. + * for the duplicate variable. This is necessary when cloning a sprite, for example. + * @return {?Variable} The duplicated variable, or null if + * the original variable was not found. + */ + duplicateVariable( + id: string, + optKeepOriginalId: boolean | undefined, + targetId: string + ): Variable | null; + /** + * Duplicate the dictionary of this target's variables as part of duplicating. + * this target or making a clone. + * @param {!object} targetId ID of the target which owns this variables. + * @param {object=} optBlocks Optional block container for the target being duplicated. + * If provided, new variables will be generated with new UIDs and any variable references + * in this blocks container will be updated to refer to the corresponding new IDs. + * @return {object} The duplicated dictionary of variables + */ + duplicateVariables( + targetId: object, + optBlocks?: object | undefined + ): object; + /** + * Post/edit sprite info. + * @param {object} data An object with sprite info data to set. + * @abstract + */ + postSpriteInfo(data: object): void; + /** + * Retrieve custom state associated with this target and the provided state ID. + * @param {string} stateId - specify which piece of state to retrieve. + * @returns {*} the associated state, if any was found. + */ + getCustomState(stateId: string): any; + /** + * Store custom state associated with this target and the provided state ID. + * @param {string} stateId - specify which piece of state to store on this target. + * @param {*} newValue - the state value to store. + */ + setCustomState(stateId: string, newValue: any): void; + /** + * Call to destroy a target. + * @abstract + */ + dispose(): void; + /** + * Get the names of all the variables of the given type that are in scope for this target. + * For targets that are not the stage, this includes any target-specific + * variables as well as any stage variables unless the skipStage flag is true. + * For the stage, this is all stage variables. + * @param {string} type The variable type to search for; defaults to Variable.SCALAR_TYPE + * @param {?bool} skipStage Optional flag to skip the stage. + * @return {Array} A list of variable names + */ + getAllVariableNamesInScopeByType( + type: string, + skipStage: bool | null + ): Array; + /** + * Merge variable references with another variable. + * @param {string} idToBeMerged ID of the variable whose references need to be updated + * @param {string} idToMergeWith ID of the variable that the old references should be replaced with + * @param {?Array} optReferencesToUpdate Optional context of the change. + * Defaults to all the blocks in this target. + * @param {?string} optNewName New variable name to merge with. The old + * variable name in the references being updated should be replaced with this new name. + * If this parameter is not provided or is '', no name change occurs. + */ + mergeVariables( + idToBeMerged: string, + idToMergeWith: string, + optReferencesToUpdate: Array | null, + optNewName: string | null + ): void; + /** + * Share a local variable (and given references for that variable) to the stage. + * @param {string} varId The ID of the variable to share. + * @param {Array} varRefs The list of variable references being shared, + * that reference the given variable ID. The names and IDs of these variable + * references will be updated to refer to the new (or pre-existing) global variable. + */ + shareLocalVariableToStage(varId: string, varRefs: Array): void; + /** + * Share a local variable with a sprite, merging with one of the same name and + * type if it already exists on the sprite, or create a new one. + * @param {string} varId Id of the variable to share + * @param {Target} sprite The sprite to share the variable with + * @param {Array} varRefs A list of all the variable references currently being shared. + */ + shareLocalVariableToSprite( + varId: string, + sprite: Target, + varRefs: Array + ): void; + /** + * Given a list of variable referencing fields, shares those variables with + * the target with the provided id, resolving any variable conflicts that arise + * using the following rules: + * + * If this target is the stage, exit. There are no conflicts that arise + * from sharing variables from the stage to another sprite. The variables + * already exist globally, so no further action is needed. + * + * If a variable being referenced is a global variable, do nothing. The + * global variable already exists so no further action is needed. + * + * If a variable being referenced is local, and + * 1) The receiving target is a sprite: + * create a new local variable or merge with an existing local variable + * of the same name and type. Update all the referencing fields + * for the original variable to reference the new variable. + * 2) The receiving target is the stage: + * Create a new global variable with a fresh name and update all the referencing + * fields to reference the new variable. + * + * @param {Array} blocks The blocks containing + * potential conflicting references to variables. + * @param {Target} receivingTarget The target receiving the variables + */ + resolveVariableSharingConflictsWithTarget( + blocks: Array, + receivingTarget: Target + ): void; + resolveVariableSharingConflicts(blocks: any): void; + /** + * Fixes up variable references in this target avoiding conflicts with + * pre-existing variables in the same scope. + * This is used when uploading this target as a new sprite into an existing + * project, where the new sprite may contain references + * to variable names that already exist as global variables in the project + * (and thus are in scope for variable references in the given sprite). + * + * If this target has a block that references an existing global variable and that + * variable *does not* exist in this target (e.g. it was a global variable in the + * project the sprite was originally exported from), merge the variables. This entails + * fixing the variable references in this sprite to reference the id of the pre-existing global variable. + * + * If this target has a block that references an existing global variable and that + * variable does exist in the target itself (e.g. it's a local variable in the sprite being uploaded), + * then the local variable is renamed to distinguish itself from the pre-existing variable. + * All blocks that reference the local variable will be updated to use the new name. + */ + fixUpVariableReferences(): void; + emitFast(...args: any[]): void; + } + type Blocks = import("scratch-vm-dts/engine/blocks"); + type Frames = import("scratch-vm-dts/engine/frame"); + type Variable = import("scratch-vm-dts/engine/variable"); +} + +declare module "scratch-vm-dts/engine/sequencer" { + export = Sequencer; + type Runtime = import("scratch-vm-dts/engine/runtime"); + class Sequencer { + /** + * Time to run a warp-mode thread, in ms. + * @type {number} + */ + static get WARP_TIME(): number; + constructor(runtime: any); + /** + * A utility timer for timing thread sequencing. + * @type {!Timer} + */ + timer: Timer; + /** + * Reference to the runtime owning this sequencer. + * @type {!Runtime} + */ + runtime: Runtime; + activeThread: any; + /** + * Step through all threads in `this.runtime.threads`, running them in order. + * @return {Array.} List of inactive threads after stepping. + */ + stepThreads(): Array; + /** + * Step the requested thread for as long as necessary. + * @param {!Thread} thread Thread object to step. + */ + stepThread(thread: Thread): void; + /** + * Step a thread into a block's branch. + * @param {!Thread} thread Thread object to step to branch. + * @param {number} branchNum Which branch to step to (i.e., 1, 2). + * @param {boolean} isLoop Whether this block is a loop. + */ + stepToBranch(thread: Thread, branchNum: number, isLoop: boolean): void; + /** + * Step a procedure. + * @param {!Thread} thread Thread object to step to procedure. + * @param {!string} procedureCode Procedure code of procedure to step to. + * @param {!Target} Target CCW: for globalProcedure. + */ + stepToProcedure( + thread: Thread, + procedureCode: string, + globalTarget: any + ): void; + /** + * Retire a thread in the middle, without considering further blocks. + * @param {!Thread} thread Thread object to retire. + */ + retireThread(thread: Thread): void; + } + import Timer = require("scratch-vm-dts/util/timer"); + import Thread = require("scratch-vm-dts/engine/thread"); +} + +declare module "scratch-vm-dts/engine/runtime" { + export = Runtime; + type Target = import("scratch-vm-dts/engine/target"); + + class ScratchLinkSocket { } + class AudioEngine { } + class RenderWebGL { } + class ScratchStorage { } + class MonitorRecord { } + /** + * Manages targets, scripts, and the sequencer. + * @constructor + */ + class Runtime extends EventEmitter<[never]> { + /** + * Width of the stage, in pixels. + * @const {number} + */ + static get STAGE_WIDTH(): number; + /** + * Height of the stage, in pixels. + * @const {number} + */ + static get STAGE_HEIGHT(): number; + /** + * Event name for glowing a script. + * @const {string} + */ + static get SCRIPT_GLOW_ON(): string; + /** + * Event name for unglowing a script. + * @const {string} + */ + static get SCRIPT_GLOW_OFF(): string; + /** + * Event name for glowing a block. + * @const {string} + */ + static get BLOCK_GLOW_ON(): string; + /** + * Event name for unglowing a block. + * @const {string} + */ + static get BLOCK_GLOW_OFF(): string; + /** + * Event name for a cloud data update + * to this project. + * @const {string} + */ + static get HAS_CLOUD_DATA_UPDATE(): string; + /** + * Event name for turning on turbo mode. + * @const {string} + */ + static get TURBO_MODE_ON(): string; + /** + * Event name for turning off turbo mode. + * @const {string} + */ + static get TURBO_MODE_OFF(): string; + /** + * Event name for runtime options changing. + * @const {string} + */ + static get RUNTIME_OPTIONS_CHANGED(): string; + /** + * Event name for compiler options changing. + * @const {string} + */ + static get COMPILER_OPTIONS_CHANGED(): string; + /** + * Event name for framerate changing. + * @const {string} + */ + static get FRAMERATE_CHANGED(): string; + static get TARGETS_INDEX_CHANGED(): string; + /** + * Event name for interpolation changing. + * @const {string} + */ + static get INTERPOLATION_CHANGED(): string; + /** + * Event name for stage size changing. + * @const {string} + */ + static get STAGE_SIZE_CHANGED(): string; + /** + * Event name for compiler errors. + * @const {string} + */ + static get COMPILE_ERROR(): string; + /** + * Event name for CCWAPI changing. + * @const {string} + */ + static get CCWAPI_CHANGED(): string; + /** + * Event name for assets loading progress. + */ + static get LOAD_ASSETS_PROGRESS(): string; + static get LOAD_ASSET_FAILED(): string; + /** + * Event name for start load a project from a Scratch JSON representation. + * @const {string} + */ + static get START_DESERIALIZE_PROJECT(): string; + /** + * Event name for the project completes loading the assets asynchronously + * @const {string} + */ + static get PROJECT_ASSETS_ASYNC_LOAD_DONE(): string; + /** + * Event called before any block is executed. + */ + static get BEFORE_EXECUTE(): string; + /** + * Event called after every block in the project has been executed. + */ + static get AFTER_EXECUTE(): string; + /** + * Event name for reporting asset download progress. Fired with finished, total + * @const {string} + */ + static get ASSET_PROGRESS(): string; + /** + * Event name when the project is started (threads may not necessarily be + * running). + * @const {string} + */ + static get PROJECT_START(): string; + /** + * Event name when threads start running. + * Used by the UI to indicate running status. + * @const {string} + */ + static get PROJECT_RUN_START(): string; + /** + * Event name when threads stop running + * Used by the UI to indicate not-running status. + * @const {string} + */ + static get PROJECT_RUN_STOP(): string; + /** + * Event name for pause. + * Used by the UI to indicate pause status. + * @const {string} + */ + static get PROJECT_RUN_PAUSE(): string; + /** + * Event name for resume + * Used by the UI to indicate resume status. + * @const {string} + */ + static get PROJECT_RUN_RESUME(): string; + /** + * Event name for project being stopped or restarted by the user. + * Used by blocks that need to reset state. + * @const {string} + */ + static get PROJECT_STOP_ALL(): string; + /** + * Event name for target being stopped by a stop for target call. + * Used by blocks that need to stop individual targets. + * @const {string} + */ + static get STOP_FOR_TARGET(): string; + /** + * Event name for visual value report. + * @const {string} + */ + static get VISUAL_REPORT(): string; + /** + * Event name for project loaded report. + * @const {string} + */ + static get PROJECT_LOADED(): string; + /** + * Event name for report that a change was made that can be saved + * @const {string} + */ + static get PROJECT_CHANGED(): string; + /** + * Event name for mobile buttons visible was changed. + * @const {string} + */ + static get TARGET_BLOCKS_CHANGED(): string; + /** + * Event name for editing target's blocks was changed. + * @const {string} + */ + static get MOBILE_BUTTONS_VISIBLE_CHANGED(): string; + /** + * Event name for editing target's simple property(name, size, x, y, etc) was changed. + * @const {string} + */ + static get TARGET_SIMPLE_PROPERTY_CHANGED(): string; + /** + * Event name for editing target's comments was changed. + * @const {string} + */ + static get TARGET_COMMENTS_CHANGED(): string; + /** + * Event name for editing target's frames was changed. + * @const {string} + */ + static get TARGET_FRAMES_CHANGED(): string; + /** + * Event name for editing target's costome was changed. + * @const {string} + */ + static get TARGET_COSTUME_CHANGED(): string; + /** + * Event name for editing target's currentCostome was changed. + * @const {string} + */ + static get TARGET_CURRENT_COSTUME_CHANGED(): string; + /** + * Event name for editing target's variables was changed. + * @const {string} + */ + static get TARGET_VARIABLES_CHANGED(): string; + /** + * Event name for user manipulated monitor and caused it to change. + * @const {string} + */ + static get MONITORS_CHANGED(): string; + /** + * Event name for report that a change was made to an extension in the toolbox. + * @const {string} + */ + static get TOOLBOX_EXTENSIONS_NEED_UPDATE(): string; + /** + * Event name for targets update report. + * @const {string} + */ + static get TARGETS_UPDATE(): string; + /** + * Event name for target update report. + * @const {string} + */ + static get TARGET_UPDATE(): string; + /** + * Event name for gandi asset update report. + * @const {string} + */ + static get GANDI_ASSET_UPDATE(): string; + static get GANDI_ASSET_UPDATE_FROM_SERVER(): string; + static get GANDI_CONFIGS_UPDATE(): string; + static get GANDI_SPINE_UPDATE(): string; + static get GANDI_DYNAMIC_MENU_ITEMS_UPDATE(): string; + static get GANDI_WILD_EXTENSIONS_CHANGED(): string; + static get GANDI_SHOW_SPINE_UPLOAD(): string; + /** + * Event name for monitors update. + * @const {string} + */ + static get MONITORS_UPDATE(): string; + /** + * Event name for monitors changed. + * @const {string} + */ + static get SOUNDS_CHANGED(): string; + /** + * Event name for block drag update. + * @const {string} + */ + static get BLOCK_DRAG_UPDATE(): string; + /** + * Event name for frame drag update. + * @const {string} + */ + static get FRAME_DRAG_UPDATE(): string; + /** + * Event name for frame drag update. + * @const {string} + */ + static get FRAME_DRAG_END(): string; + /** + * Event name for block drag end. + * @const {string} + */ + static get BLOCK_DRAG_END(): string; + /** + * Event name for reporting that an extension was added. + * @const {string} + */ + static get EXTENSION_ADDED(): string; + /** + * Event name for reporting that an extension was deleted. + * @const {string} + */ + static get EXTENSION_DELETED(): string; + /** + * Event name for reporting that an extension as asked for a custom field to be added + * @const {string} + */ + static get EXTENSION_FIELD_ADDED(): string; + /** + * Event name for updating the available set of peripheral devices. + * This causes the peripheral connection modal to update a list of + * available peripherals. + * @const {string} + */ + static get PERIPHERAL_LIST_UPDATE(): string; + /** + * Event name for when the user picks a bluetooth device to connect to + * via Companion Device Manager (CDM) + * @const {string} + */ + static get USER_PICKED_PERIPHERAL(): string; + /** + * Event name for reporting that a peripheral has connected. + * This causes the status button in the blocks menu to indicate 'connected'. + * @const {string} + */ + static get PERIPHERAL_CONNECTED(): string; + /** + * Event name for reporting that a peripheral has been intentionally disconnected. + * This causes the status button in the blocks menu to indicate 'disconnected'. + * @const {string} + */ + static get PERIPHERAL_DISCONNECTED(): string; + /** + * Event name for reporting that a peripheral has encountered a request error. + * This causes the peripheral connection modal to switch to an error state. + * @const {string} + */ + static get PERIPHERAL_REQUEST_ERROR(): string; + /** + * Event name for reporting that a peripheral connection has been lost. + * This causes a 'peripheral connection lost' error alert to display. + * @const {string} + */ + static get PERIPHERAL_CONNECTION_LOST_ERROR(): string; + /** + * Event name for reporting that a peripheral has not been discovered. + * This causes the peripheral connection modal to show a timeout state. + * @const {string} + */ + static get PERIPHERAL_SCAN_TIMEOUT(): string; + /** + * Event name to indicate that the microphone is being used to stream audio. + * @const {string} + */ + static get MIC_LISTENING(): string; + /** + * Event name to indicate that the custom blocks have been added or deleted. + * @const {string} + */ + static get CUSTOM_BLOCK_ARGUMENTS_LENGTH_CHANGED(): string; + static get EXTENSION_DATA_LOADING(): string; + /** + * Event name for reporting that blocksInfo was updated. + * @const {string} + */ + static get BLOCKSINFO_UPDATE(): string; + /** + * Event name when the runtime tick loop has been started. + * @const {string} + */ + static get RUNTIME_STARTED(): string; + /** + * Event name when the runtime tick loop has been stopped. + * @const {string} + */ + static get RUNTIME_STOPPED(): string; + /** + * Event name when the runtime dispose has been called. + * @const {string} + */ + static get RUNTIME_DISPOSED(): string; + /** + * Event name for reporting that a block was updated and needs to be rerendered. + * @const {string} + */ + static get BLOCKS_NEED_UPDATE(): string; + /** + * Event name when platform name inside a project does not match the runtime. + */ + static get PLATFORM_MISMATCH(): string; + /** + * How rapidly we try to step threads by default, in ms. + */ + static get THREAD_STEP_INTERVAL(): number; + /** + * In compatibility mode, how rapidly we try to step threads, in ms. + */ + static get THREAD_STEP_INTERVAL_COMPATIBILITY(): number; + /** + * How many clones can be created at a time. + * @const {number} + */ + static get MAX_CLONES(): number; + constructor(); + /** + * Target management and storage. + * @type {Array.} + */ + targets: Array; + /** + * Targets in reverse order of execution. Shares its order with drawables. + * @type {Array.} + */ + executableTargets: Array; + /** + * A list of threads that are currently running in the VM. + * Threads are added when execution starts and pruned when execution ends. + * @type {Array.} + */ + threads: Array; + threadMap: Map; + /** @type {!Sequencer} */ + sequencer: Sequencer; + /** + * Storage container for flyout blocks. + * These will execute on `_editingTarget.` + * @type {!Blocks} + */ + flyoutBlocks: Blocks; + /** + * Storage container for monitor blocks. + * These will execute on a target maybe + * @type {!Blocks} + */ + monitorBlocks: Blocks; + /** + * Currently known editing target for the VM. + * @type {?Target} + */ + _editingTarget: Target | null; + /** + * Map to look up a block primitive's implementation function by its opcode. + * This is a two-step lookup: package name first, then primitive name. + * @type {Object.} + */ + _primitives: { + [x: string]: Function; + }; + /** + * Map to look up hat blocks' metadata. + * Keys are opcode for hat, values are metadata objects. + * @type {Object.} + */ + _hats: { + [x: string]: Object; + }; + /** + * Map of opcode to information about whether the block's return value should be interpreted + * for control flow purposes. + * @type {Record} + */ + _flowing: Record< + string, + { + conditional: boolean; + } + >; + /** + * A list of script block IDs that were glowing during the previous frame. + * @type {!Array.} + */ + _scriptGlowsPreviousFrame: Array; + /** + * Number of non-monitor threads running during the previous frame. + * @type {number} + */ + _nonMonitorThreadCount: number; + /** + * All threads that finished running and were removed from this.threads + * by behaviour in Sequencer.stepThreads. + * @type {Array} + */ + _lastStepDoneThreads: Array; + /** + * Currently known number of clones, used to enforce clone limit. + * @type {number} + */ + _cloneCounter: number; + /** + * Flag to emit a targets update at the end of a step. When target data + * changes, this flag is set to true. + * @type {boolean} + */ + _refreshTargets: boolean; + /** + * Ordered map of all monitors, which are MonitorReporter objects. + */ + _monitorState: OrderedMap; + /** + * Monitor state from last tick + */ + _prevMonitorState: OrderedMap; + /** + * Whether the project is in "turbo mode." + * @type {Boolean} + */ + turboMode: boolean; + /** + * tw: Responsible for managing the VM's many timers. + */ + frameLoop: FrameLoop; + /** + * Current length of a step. + * Changes as mode switches, and used by the sequencer to calculate + * WORK_TIME. + * @type {!number} + */ + currentStepTime: number; + /** + * Whether any primitive has requested a redraw. + * Affects whether `Sequencer.stepThreads` will yield + * after stepping each thread. + * Reset on every frame. + * @type {boolean} + */ + redrawRequested: boolean; + /** @type {Object.} */ + ioDevices: { + [x: string]: Object; + }; + /** + * A list of extensions, used to manage hardware connection. + */ + peripheralExtensions: {}; + /** + * A runtime profiler that records timed events for later playback to + * diagnose Scratch performance. + * @type {Profiler} + */ + profiler: Profiler; + cloudOptions: { + limit: number; + }; + /** + * Check wether the runtime has any cloud data. + * @type {function} + * @return {boolean} Whether or not the runtime currently has any + * cloud variables. + */ + hasCloudData: Function; + /** + * A function which checks whether a new cloud variable can be added + * to the runtime. + * @type {function} + * @return {boolean} Whether or not a new cloud variable can be added + * to the runtime. + */ + canAddCloudVariable: Function; + /** + * A function which returns the number of cloud variables in the runtime. + * @returns {number} + */ + getNumberOfCloudVariables: Function; + /** + * A function that tracks a new cloud variable in the runtime, + * updating the cloud variable limit. Calling this function will + * emit a cloud data update event if this is the first cloud variable + * being added. + * @type {function} + */ + addCloudVariable: Function; + /** + * A function which updates the runtime's cloud variable limit + * when removing a cloud variable and emits a cloud update event + * if the last of the cloud variables is being removed. + * @type {function} + */ + removeCloudVariable: Function; + /** + * A string representing the origin of the current project from outside of the + * Scratch community, such as CSFirst. + * @type {?string} + */ + origin: string | null; + /** + * Provides the ability to log to the terminal. + * The default output is to the browser's console + * @type {LogSystem} + */ + logSystem: LogSystem; + /** + * New data structure in Gandi editor. + * @type {Gandi} + */ + gandi: Gandi; + _stageTarget: any; + /** + * Metadata about the platform this VM is part of. + */ + platform: { + name: string; + url: string; + }; + addonBlocks: {}; + stageWidth: number; + stageHeight: number; + runtimeOptions: { + maxClones: number; + miscLimits: boolean; + fencing: boolean; + hatsConcurrency: number; + }; + compilerOptions: { + enabled: boolean; + warpTimer: boolean; + }; + /** ccw: add ccwAPI init value {} + * + */ + ccwAPI: {}; + waitingLoadAssetCallbackQueue: any[]; + debug: boolean; + _lastStepTime: number; + interpolationEnabled: boolean; + _defaultStoredSettings: { + framerate: any; + runtimeOptions: { + maxClones: number; + miscLimits: boolean; + fencing: boolean; + hatsConcurrency: number; + }; + interpolation: boolean; + turbo: boolean; + hq: any; + width: number; + height: number; + }; + /** + * TW: We support a "packaged runtime" mode. This can be used when: + * - there will never be an editor attached such as scratch-gui or scratch-blocks + * - the project will never be exported with saveProjectSb3() + * - original costume and sound data is not needed + * In this mode, the runtime is able to discard large amounts of data and avoid some processing + * to make projects load faster and use less memory. + * This is not designed to protect projects from copying as someone can still copy the data that + * gets fed into the runtime in the first place. + * This mode is used by the TurboWarp Packager. + */ + isPackaged: boolean; + /** + * Contains information about the external communication methods that the scripts inside the project + * can use to send data from inside the project to an external server. + * Do not update this directly. Use Runtime.setExternalCommunicationMethod() instead. + */ + externalCommunicationMethods: { + cloudVariables: boolean; + customExtensions: boolean; + }; + /** + * If set to true, features such as reading colors from the user's webcam will be disabled + * when the project has access to any external communication method to protect user privacy. + * Requires TurboWarp/scratch-render. + * Do not update this directly. Use Runtime.setEnforcePrivacy() instead. + */ + enforcePrivacy: boolean; + /** + * Internal map of opaque identifiers to the callback to run that function. + * @type {Map} + */ + extensionButtons: Map; + /** + * Responsible for managing custom fonts. + */ + fontManager: FontManager; + /** + * Maps extension ID to a JSON-serializable value. + * @type {Object.} + */ + extensionStorage: { + [x: string]: object; + }; + /** + * Total number of scratch-storage load() requests since the runtime was created or cleared. + */ + totalAssetRequests: number; + /** + * Total number of finished or errored scratch-storage load() requests since the runtime was created or cleared. + */ + finishedAssetRequests: number; + _initializeAddCloudVariable(newCloudDataManager: any): () => void; + _initializeRemoveCloudVariable(newCloudDataManager: any): () => void; + compilerRegisterExtension(name: any, extensionObject: any): void; + getMonitorState(): OrderedMap; + /** + * Create a context ("args") object for use with `formatMessage` on messages which might be target-specific. + * @param {Target} [target] - the target to use as context. If a target is not provided, default to the current + * editing target or the stage. + */ + makeMessageContextForTarget(target?: Target): void; + /** + * remove extension + * @param {string} extensionId - id of extension to remove + */ + removeExtensionPrimitives(extensionId: string): void; + _buildCustomFieldInfo( + fieldName: any, + fieldInfo: any, + extensionId: any, + categoryInfo: any + ): { + fieldName: any; + extendedName: string; + argumentTypeInfo: { + shadow: { + type: string; + fieldName: string; + }; + }; + scratchBlocksDefinition: object; + fieldImplementation: any; + }; + /** + * Build the scratch-blocks JSON needed for a fieldType. + * Custom field types need to be namespaced to the extension so that extensions can't interfere with each other + * @param {string} fieldName - The name of the field + * @param {string} output - The output of the field + * @param {number} outputShape - Shape of the field (from ScratchBlocksConstants) + * @param {object} categoryInfo - The category the field belongs to (Used to set its colors) + * @returns {object} - Object to be inserted into scratch-blocks + */ + _buildCustomFieldTypeForScratchBlocks( + fieldName: string, + output: string, + outputShape: number, + categoryInfo: object + ): object; + _convertXmlForScratchBlocks(xmlInfo: any): { + info: any; + xml: any; + }; + handleExtensionButtonPress(button: any): void; + /** + * @returns {Array.} scratch-blocks XML for each category of extension blocks, in category order. + * @param {?Target} [target] - the active editing target (optional) + * @property {string} id - the category / extension ID + * @property {string} xml - the XML text for this category, starting with `` and ending with `` + */ + getBlocksXML(target?: Target | null): Array; + /** + * @returns {Array.} - an array containing the scratch-blocks JSON information for each dynamic block. + */ + getBlocksJSON(): Array; + /** + * One-time initialization for Scratch Link support. + */ + _initScratchLink(): void; + /** + * Get a scratch link socket. + * @param {string} type Either BLE or BT + * @returns {ScratchLinkSocket} The scratch link socket. + */ + getScratchLinkSocket(type: string): ScratchLinkSocket; + /** + * Configure how ScratchLink sockets are created. Factory must consume a "type" parameter + * either BT or BLE. + * @param {Function} factory The new factory for creating ScratchLink sockets. + */ + configureScratchLinkSocketFactory(factory: Function): void; + _linkSocketFactory: Function | undefined; + /** + * The default scratch link socket creator, using websockets to the installed device manager. + * @param {string} type Either BLE or BT + * @returns {ScratchLinkSocket} The new scratch link socket (a WebSocket object) + */ + _defaultScratchLinkSocketFactory(type: string): ScratchLinkSocket; + /** + * Register an extension that communications with a hardware peripheral by id, + * to have access to it and its peripheral functions in the future. + * @param {string} extensionId - the id of the extension. + * @param {object} extension - the extension to register. + */ + registerPeripheralExtension(extensionId: string, extension: object): void; + /** + * Tell the specified extension to scan for a peripheral. + * @param {string} extensionId - the id of the extension. + */ + scanForPeripheral(extensionId: string): void; + /** + * Connect to the extension's specified peripheral. + * @param {string} extensionId - the id of the extension. + * @param {number} peripheralId - the id of the peripheral. + */ + connectPeripheral(extensionId: string, peripheralId: number): void; + /** + * Disconnect from the extension's connected peripheral. + * @param {string} extensionId - the id of the extension. + */ + disconnectPeripheral(extensionId: string): void; + /** + * Returns whether the extension has a currently connected peripheral. + * @param {string} extensionId - the id of the extension. + * @return {boolean} - whether the extension has a connected peripheral. + */ + getPeripheralIsConnected(extensionId: string): boolean; + /** + * Emit an event to indicate that the microphone is being used to stream audio. + * @param {boolean} listening - true if the microphone is currently listening. + */ + emitMicListening(listening: boolean): void; + /** + * Retrieve the function associated with the given opcode. + * @param {!string} opcode The opcode to look up. + * @return {Function} The function which implements the opcode. + */ + getOpcodeFunction(opcode: string): Function; + /** + * Return whether an opcode represents a hat block. + * @param {!string} opcode The opcode to look up. + * @return {boolean} True if the op is known to be a hat. + */ + getIsHat(opcode: string): boolean; + /** + * Return whether an opcode represents an edge-activated hat block. + * @param {!string} opcode The opcode to look up. + * @return {boolean} True if the op is known to be a edge-activated hat. + */ + getIsEdgeActivatedHat(opcode: string): boolean; + /** + * Attach the audio engine + * @param {!AudioEngine} audioEngine The audio engine to attach + */ + attachAudioEngine(audioEngine: AudioEngine): void; + audioEngine: any; + /** + * Attach the renderer + * @param {!RenderWebGL} renderer The renderer to attach + */ + attachRenderer(renderer: RenderWebGL): void; + renderer: any; + /** + * Set the bitmap adapter for the VM/runtime, which converts scratch 2 + * bitmaps to scratch 3 bitmaps. (Scratch 3 bitmaps are all bitmap resolution 2) + * @param {!function} bitmapAdapter The adapter to attach + */ + attachV2BitmapAdapter(bitmapAdapter: Function): void; + v2BitmapAdapter: Function | undefined; + /** + * Attach the storage module + * @param {!ScratchStorage} storage The storage module to attach + */ + attachStorage(storage: ScratchStorage): void; + storage: any; + attachBlocks(scratchBlocks: any): void; + scratchBlocks: any; + /** + * Create a thread and push it to the list of threads. + * @param {!string} id ID of block that starts the stack. + * @param {!Target} target Target to run thread on. + * @param {?object} opts optional arguments + * @param {?boolean} opts.stackClick true if the script was activated by clicking on the stack + * @param {?boolean} opts.updateMonitor true if the script should update a monitor value + * @param {?object} opts.hatParam store ccw_hat_parameter + * @return {!Thread} The newly created thread. + */ + _pushThread(id: string, target: Target, opts: object | null): Thread; + /** + * Stop a thread: stop running it immediately, and remove it from the thread list later. + * @param {!Thread} thread Thread object to remove from actives + */ + _stopThread(thread: Thread): void; + /** + * Restart a thread in place, maintaining its position in the list of threads. + * This is used by `startHats` to and is necessary to ensure 2.0-like execution order. + * Test project: https://scratch.mit.edu/projects/130183108/ + * @param {!Thread} thread Thread object to restart. + * @return {Thread} The restarted thread. + */ + _restartThread(thread: Thread): Thread; + emitCompileError(target: any, error: any): void; + /** + * Return whether a thread is currently active/running. + * @param {?Thread} thread Thread object to check. + * @return {boolean} True if the thread is active/running. + */ + isActiveThread(thread: Thread | null): boolean; + /** + * Return whether a thread is waiting for more information or done. + * @param {?Thread} thread Thread object to check. + * @return {boolean} True if the thread is waiting + */ + isWaitingThread(thread: Thread | null): boolean; + /** + * Toggle a script. + * @param {!string} topBlockId ID of block that starts the script. + * @param {?object} opts optional arguments to toggle script + * @param {?string} opts.target target ID for target to run script on. If not supplied, uses editing target. + * @param {?boolean} opts.stackClick true if the user activated the stack by clicking, false if not. This + * determines whether we show a visual report when turning on the script. + */ + toggleScript(topBlockId: string, opts: object | null): void; + /** + * Enqueue a script that when finished will update the monitor for the block. + * @param {!string} topBlockId ID of block that starts the script. + * @param {?Target} optTarget target Target to run script on. If not supplied, uses editing target. + */ + addMonitorScript(topBlockId: string, optTarget: Target | null): void; + /** + * Run a function `f` for all scripts in a workspace. + * `f` will be called with two parameters: + * - the top block ID of the script. + * - the target that owns the script. + * @param {!Function} f Function to call for each script. + * @param {Target=} optTarget Optionally, a target to restrict to. + */ + allScriptsDo(f: Function, optTarget?: Target | undefined): void; + allScriptsByOpcodeDo(opcode: any, f: any, optTarget: any): void; + /** + * Start all relevant hats. + * @param {!string} requestedHatOpcode Opcode of hats to start. + * @param {object=} optMatchFields Optionally, fields to match on the hat. + * @param {Target=} optTarget Optionally, a target to restrict to. + * @param {object=} hatParam Optionally, start hats with ccw_hat_parameter if true, + will skip field check and inject ccw_hat_parameter to thread. + * @return {Array.} List of threads started by this function. + */ + startHats( + requestedHatOpcode: string, + optMatchFields?: object | undefined, + optTarget?: Target | undefined, + hatParam?: object | undefined + ): Array; + /** + * CCW + startHatsWithParams is only used in block utility for extension, + WhitExtraMsg means skip field check when start a hat block. + define here is only for debug + * @param {!string} requestedHatOpcode Opcode of hats to start. + * @param {object} data Optionally, contains fields to match on the hat and parameters to ccw_hat_parameter. + * @param {Target=} optTarget Optionally, a target to restrict to. + * @return {Array.} List of threads started by this function. + */ + startHatsWithParams( + requestedHat: any, + data: object, + optTarget?: Target | undefined + ): Array; + /** + * Dispose all targets. Return to clean state. + */ + dispose(): void; + disposeAll(): void; + _steppingInterval: any; + /** + * Add a target to the runtime. This tracks the sprite pane + * ordering of the target. The target still needs to be put + * into the correct execution order after calling this function. + * @param {Target} target target to add + */ + addTarget(target: Target): void; + /** + * Move a target in the execution order by a relative amount. + * + * A positve number will make the target execute earlier. A negative number + * will make the target execute later in the order. + * + * @param {Target} executableTarget target to move + * @param {number} delta number of positions to move target by + * @returns {number} new position in execution order + */ + moveExecutable(executableTarget: Target, delta: number): number; + /** + * Set a target to execute at a specific position in the execution order. + * + * Infinity will set the target to execute first. 0 will set the target to + * execute last (before the stage). + * + * @param {Target} executableTarget target to move + * @param {number} newIndex position in execution order to place the target + * @returns {number} new position in the execution order + */ + setExecutablePosition(executableTarget: Target, newIndex: number): number; + /** + * Remove a target from the execution set. + * @param {Target} executableTarget target to remove + */ + removeExecutable(executableTarget: Target): void; + /** + * Dispose of a target. + * @param {!Target} disposingTarget Target to dispose of. + */ + disposeTarget(disposingTarget: Target): void; + /** + * Stop any threads acting on the target. + * @param {!Target} target Target to stop threads for. + * @param {Thread=} optThreadException Optional thread to skip. + */ + stopForTarget( + target: Target, + optThreadException?: Thread | undefined + ): void; + /** + * Reset the Run ID. Call this any time the project logically starts, stops, or changes identity. + */ + resetRunId(): void; + /** + * Start all threads that start with the green flag. + */ + greenFlag(): void; + /** + * Stop "everything." + */ + stopAll(): void; + _renderInterpolatedPositions(): void; + updateThreadMap(): void; + /** + * Repeatedly run `sequencer.stepThreads` and filter out + * inactive threads after each iteration. + */ + _step(): void; + /** + * 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). + * @param {!Array.} threads The set of threads to look through. + * @return {number} The number of monitor threads in threads. + */ + _getMonitorThreadCount(threads: Array): number; + /** + * Queue monitor blocks to sequencer to be run. + */ + _pushMonitors(): void; + /** + * Set the current editing target known by the runtime. + * @param {!Target} editingTarget New editing target. + */ + setEditingTarget(editingTarget: Target): void; + /** + * Set whether we are in 30 TPS compatibility mode. + * @param {boolean} compatibilityModeOn True iff in compatibility mode. + */ + setCompatibilityMode(compatibilityModeOn: boolean): void; + /** + * tw: Change runtime target frames per second + * @param {number} framerate Target frames per second + */ + setFramerate(framerate: number): void; + /** + * tw: Enable or disable interpolation. + * @param {boolean} interpolationEnabled True if interpolation should be enabled. + */ + setInterpolation(interpolationEnabled: boolean): void; + /** + * tw: Update runtime options + * @param {*} runtimeOptions New options + */ + setRuntimeOptions(runtimeOptions: any): void; + /** + * ccw: Set ccw API to runtime support ccw block extensions + * @param {*} ccwAPI ccw API + */ + setCCWAPI(ccwAPI: any): void; + /** + * tw: Update compiler options + * @param {*} compilerOptions New options + */ + setCompilerOptions(compilerOptions: any): void; + /** + * @param {boolean} isPlayerOnly + */ + setIsPlayerOnly(isPlayerOnly: boolean): void; + isPlayerOnly: boolean | undefined; + /** + * Change width and height of stage. This will also inform the renderer of the new stage size. + * @param {number} width New stage width + * @param {number} height New stage height + */ + setStageSize(width: number, height: number): void; + setInEditor(inEditor: any): void; + /** + * TW: Enable "packaged runtime" mode. This is a one-way operation. + */ + convertToPackagedRuntime(): void; + /** + * tw: Reset the cache of all block containers. + */ + resetAllCaches(): void; + /** + * Add an "addon block" + * @param {object} options Options object + * @param {string} options.procedureCode The ID of the block + * @param {function} options.callback The callback, called with (args, BlockUtility). May return a promise. + * @param {string[]} [options.arguments] Names of the arguments accepted. Optional if no arguments. + * @param {boolean} [options.hidden] True to not include this block in the block palette + * @param {1|2} [options.return] 1 for round reporter, 2 for boolean reported, leave empty for statement. + */ + addAddonBlock(options: { + procedureCode: string; + callback: Function; + arguments?: string[] | undefined; + hidden?: boolean | undefined; + return?: 2 | 1 | undefined; + }): void; + getAddonBlock(procedureCode: any): any; + findProjectOptionsComment(): any; + parseProjectOptions(): void; + _generateAllProjectOptions(): { + framerate: any; + runtimeOptions: { + maxClones: number; + miscLimits: boolean; + fencing: boolean; + hatsConcurrency: number; + }; + interpolation: boolean; + turbo: boolean; + hq: any; + width: number; + height: number; + }; + generateDifferingProjectOptions(): {}; + storeProjectOptions(): void; + /** + * Eagerly (re)compile all scripts within this project. + */ + precompile(): void; + enableDebug(): void; + /** + * Emit glows/glow clears for scripts after a single tick. + * Looks at `this.threads` and notices which have turned on/off new glows. + * @param {Array.=} optExtraThreads Optional list of inactive threads. + */ + _updateGlows(optExtraThreads?: Array | undefined): void; + /** + * Emit run start/stop after each tick. Emits when `this.threads.length` goes + * between non-zero and zero + * + * @param {number} nonMonitorThreadCount The new nonMonitorThreadCount + */ + _emitProjectRunStatus(nonMonitorThreadCount: number): void; + /** + * "Quiet" a script's glow: stop the VM from generating glow/unglow events + * about that script. Use when a script has just been deleted, but we may + * still be tracking glow data about it. + * @param {!string} scriptBlockId Id of top-level block in script to quiet. + */ + quietGlow(scriptBlockId: string): void; + /** + * Emit feedback for block glowing (used in the sequencer). + * @param {?string} blockId ID for the block to update glow + * @param {boolean} isGlowing True to turn on glow; false to turn off. + */ + glowBlock(blockId: string | null, isGlowing: boolean): void; + /** + * Emit feedback for script glowing. + * @param {?string} topBlockId ID for the top block to update glow + * @param {boolean} isGlowing True to turn on glow; false to turn off. + */ + glowScript(topBlockId: string | null, isGlowing: boolean): void; + /** + * Emit whether blocks are being dragged over gui + * @param {boolean} areBlocksOverGui True if blocks are dragged out of blocks workspace, false otherwise + */ + emitBlockDragUpdate(areBlocksOverGui: boolean): void; + /** + * Emit whether frame are being dragged over gui + * @param {boolean} areBlocksOverGui True if frame are dragged out of the workspace, false otherwise + */ + emitFrameDragUpdate(areBlocksOverGui: boolean): void; + /** + * Emit event to indicate that the block drag has ended with the blocks outside the blocks workspace + * @param {Array.} blocks The set of blocks dragged to the GUI + * @param {string} topBlockId The original id of the top block being dragged + * @param {Array.} newBatchElements The set of batch selected blocks or frames + */ + emitBlockEndDrag( + blocks: Array, + topBlockId: string, + newBatchElements: Array + ): void; + /** + * Emit event to indicate that the frame drag has ended with the blocks outside the blocks workspace + * @param {Array.} frame The frame dragged to the GUI + * @param {string} frameId The original id of the frame being dragged + * @param {Array.=} newBatchElements The set of batch selected blocks or frames + */ + emitFrameEndDrag( + frame: Array, + frameId: string, + newBatchElements?: Array | undefined + ): void; + emitGandiSpineUpdate(type: any, id: any, data: any): void; + emitGandiConfigsUpdate(key: any, value: any): void; + emitGandiDynamicMenuItemsUpdate(type: any, id: any, data: any): void; + /** + * Emit value for reporter to show in the blocks. + * @param {string} blockId ID for the block. + * @param {string} value Value to show associated with the block. + */ + visualReport(blockId: string, value: string): void; + /** + * Add a monitor to the state. If the monitor already exists in the state, + * updates those properties that are defined in the given monitor record. + * @param {!MonitorRecord} monitor Monitor to add. + * @param {boolean} isRemoteOperation - set to true if this is a remote operation + */ + requestAddMonitor(monitor: MonitorRecord, isRemoteOperation: boolean): void; + /** + * Update a monitor in the state and report success/failure of update. + * @param {!Map} monitor Monitor values to update. Values on the monitor with overwrite + * values on the old monitor with the same ID. If a value isn't defined on the new monitor, + * the old monitor will keep its old value. + * @return {boolean} true if monitor exists in the state and was updated, false if it did not exist. + */ + requestUpdateMonitor(monitor: Map): boolean; + /** + * Removes a monitor from the state. Does nothing if the monitor already does + * not exist in the state. + * @param {!string} monitorId ID of the monitor to remove. + * @param {boolean} isRemoteOperation - set to true if this is a remote operation + */ + requestRemoveMonitor(monitorId: string, isRemoteOperation: boolean): void; + /** + * Hides a monitor and returns success/failure of action. + * @param {!string} monitorId ID of the monitor to hide. + * @param {boolean} isRuntimeOp Whether it is an operation at run time + * @return {boolean} true if monitor exists and was updated, false otherwise + */ + requestHideMonitor(monitorId: string, isRuntimeOp: boolean): boolean; + /** + * Shows a monitor and returns success/failure of action. + * not exist in the state. + * @param {!string} monitorId ID of the monitor to show. + * @param {boolean} isRuntimeOp Whether it is an operation at run time + * @return {boolean} true if monitor exists and was updated, false otherwise + */ + requestShowMonitor(monitorId: string, isRuntimeOp: boolean): boolean; + /** + * Removes all monitors with the given target ID from the state. Does nothing if + * the monitor already does not exist in the state. + * @param {!string} targetId Remove all monitors with given target ID. + */ + requestRemoveMonitorByTargetId(targetId: string): void; + /** + * Get a target by its id. + * @param {string} targetId Id of target to find. + * @return {?Target} The target, if found. + */ + getTargetById(targetId: string): Target | null; + /** + * Get the first original (non-clone-block-created) sprite given a name. + * @param {string} spriteName Name of sprite to look for. + * @return {?Target} Target representing a sprite of the given name. + */ + getSpriteTargetByName(spriteName: string): Target | null; + /** + * Get a target by its drawable id. + * @param {number} drawableID drawable id of target to find + * @return {?Target} The target, if found + */ + getTargetByDrawableId(drawableID: number): Target | null; + /** + * Update the clone counter to track how many clones are created. + * @param {number} changeAmount How many clones have been created/destroyed. + */ + changeCloneCounter(changeAmount: number): void; + /** + * Return whether there are clones available. + * @return {boolean} True until the number of clones hits runtimeOptions.maxClones + */ + clonesAvailable(): boolean; + /** + * Handle that the project has loaded in the Virtual Machine. + */ + handleProjectLoaded(): void; + /** + * Report that the project has changed in a way that would affect serialization + */ + emitProjectChanged(): void; + emitCustomBlockArgumentsLengthChanged(): void; + emitGandiAssetsUpdate(action: any): void; + emitGandiAssetsUpdateFromServer(action: any): void; + emitGandiWildExtensionsChanged(data: any): void; + /** + * Report that the project completes loading the assets asynchronously + */ + emitProjectAssetsAsyncLoadingDone(): void; + emitExtensionsChanged(): void; + emitMobileButtonsVisibleChanged(value: any): void; + /** + * Report that the target has changed in a way that would affect serialization + */ + emitTargetBlocksChanged(targeId: any, blocks: any, ext: any): void; + /** + * Report that the target has changed in a way that would affect serialization + * @param {Array>} data - An array consisting of roles that have undergone changes. + */ + emitTargetSimplePropertyChanged(data: Array>): void; + /** + * Report that the target has changed in a way that would affect serialization + */ + emitTargetCommentsChanged(targeId: any, data: any): void; + /** + * Report that the target has changed in a way that would affect serialization + */ + emitTargetFramesChanged(targeId: any, data: any): void; + /** + * Report that the target has changed in a way that would affect serialization + */ + emitTargetCostumeChanged(id: any, data: any): void; + /** + * Report that the target has changed in a way that would affect serialization + */ + emitTargetCurrentCostumeChanged(index: any): void; + /** + * Report that the target has changed in a way that would affect serialization + */ + emitTargetVariablesChanged(id: any, data: any): void; + emitMonitorsChanged(data: any): void; + emitTargetsIndexChanged(data: any): void; + /** + * Report that the monitors has changed + */ + emitTargetSoundsChanged(targetId: any, data: any): void; + /** + * Report that a new target has been created, possibly by cloning an existing target. + * @param {Target} newTarget - the newly created target. + * @param {Target} [sourceTarget] - the target used as a source for the new clone, if any. + * @fires Runtime#targetWasCreated + */ + fireTargetWasCreated(newTarget: Target, sourceTarget?: Target): void; + /** + * Report that a clone target is being removed. + * @param {Target} target - the target being removed + * @fires Runtime#targetWasRemoved + */ + fireTargetWasRemoved(target: Target): void; + /** + * Get a target representing the Scratch stage, if one exists. + * @return {?Target} The target, if found. + */ + getTargetForStage(): Target | null; + /** + * Get the editing target. + * @return {?Target} The editing target. + */ + getEditingTarget(): Target | null; + getAllVarNamesOfType(varType: any): any[]; + /** + * Get the label or label function for an opcode + * @param {string} extendedOpcode - the opcode you want a label for + * @return {object} - object with label and category + * @property {string} category - the category for this opcode + * @property {Function} [labelFn] - function to generate the label for this opcode + * @property {string} [label] - the label for this opcode if `labelFn` is absent + */ + getLabelForOpcode(extendedOpcode: string): object; + /** + * Create a new global variable avoiding conflicts with other variable names. + * @param {string} variableName The desired variable name for the new global variable. + * This can be turned into a fresh name as necessary. + * @param {string} optVarId An optional ID to use for the variable. A new one will be generated + * if a falsey value for this parameter is provided. + * @param {string} optVarType The type of the variable to create. Defaults to Variable.SCALAR_TYPE. + * @return {Variable} The new variable that was created. + */ + createNewGlobalVariable( + variableName: string, + optVarId: string, + optVarType: string + ): Variable; + /** + * Tell the runtime to request a redraw. + * Use after a clone/sprite has completed some visible operation on the stage. + */ + requestRedraw(): void; + /** + * Emit a targets update at the end of the step if the provided target is + * the original sprite + * @param {!Target} target Target requesting the targets update + */ + requestTargetsUpdate(target: Target): void; + /** + * Emit an event that indicates that the blocks on the workspace need updating. + */ + requestBlocksUpdate(): void; + /** + * Emit an event that indicates that the toolbox extension blocks need updating. + */ + requestToolboxExtensionsUpdate(): void; + /** + * Set up timers to repeatedly step in a browser. + */ + start(): void; + /** + * @deprecated Used by old versions of TurboWarp. Superceded by upstream's quit() + */ + stop(): void; + /** + * Quit the Runtime, clearing any handles which might keep the process alive. + * Do not use the runtime after calling this method. This method is meant for test shutdown. + */ + quit(): void; + /** + * Turn on profiling. + * @param {Profiler/FrameCallback} onFrame A callback handle passed a + * profiling frame when the profiler reports its collected data. + */ + enableProfiling(onFrame: any): void; + /** + * Turn off profiling. + */ + disableProfiling(): void; + /** + * Update a millisecond timestamp value that is saved on the Runtime. + * This value is helpful in certain instances for compatibility with Scratch 2, + * which sometimes uses a `currentMSecs` timestamp value in Interpreter.as + */ + updateCurrentMSecs(): void; + currentMSecs: number | undefined; + getFormatMessage(message: any): (...args: any[]) => string; + getOriginalFormatMessage(): typeof import("format-message"); + getGandiAssetsList(typesArray: any): any; + getGandiAssetContent(fileName: any): any; + getGandiAssetById(id: any): any; + getGandiAssetsFileList(type: any): any; + getGandiAssetFile(fileName: any): any; + addWaitingLoadCallback(callback: any): void; + fireWaitingLoadCallbackQueue(): void; + firingWaitingLoadCallbackQueue: boolean | undefined; + asyncLoadingProjectAssets: boolean | undefined; + requestAnimationFrameId: any; + /** + * Cancel all completed asynchronous resource loading tasks + */ + disposeFireWaitingLoadCallbackQueue(): void; + /** + * Add a costume to the current editing target. + * async costume should only existed in project running + * once project is stopped, all async costume should be removed + * @param {string} md5ext - the MD5 and extension of the costume to be loaded. + * @param {!object} costumeObject Object representing the costume. + * @param {object} target - the target to add to. + * @param {?boolean} show - show Costume immediately + * @returns {?Promise} - a promise that resolves when the costume has been added + */ + addAsyncCostumeToTarget( + md5ext: string, + costumeObject: object, + target: object, + show: boolean | null + ): Promise | null; + updatePrivacy(): void; + /** + * @param {boolean} enabled True if restrictions should be enforced to protect user privacy. + */ + setEnforcePrivacy(enabled: boolean): void; + /** + * @param {string} method Name of the method in Runtime.externalCommunicationMethods + * @param {boolean} enabled True if the feature is enabled. + */ + setExternalCommunicationMethod(method: string, enabled: boolean): void; + emitAssetProgress(): void; + resetProgress(): void; + /** + * Wrap an asset loading promise with progress support. + * @template T + * @param {() => Promise} callback + * @returns {Promise} + */ + wrapAssetRequest(callback: () => Promise): Promise; + } + namespace Runtime { + export { CloudDataManager }; + } + import EventEmitter = require("events"); + type Thread = import("scratch-vm-dts/engine/thread"); + type Sequencer = import("scratch-vm-dts/engine/sequencer"); + type Blocks = import("scratch-vm-dts/engine/blocks"); + import { OrderedMap } from "immutable"; + type FrameLoop = import("scratch-vm-dts/engine/tw-frame-loop"); + type Profiler = import("scratch-vm-dts/engine/profiler"); + type LogSystem = import("scratch-vm-dts/util/log-system"); + type Gandi = import("scratch-vm-dts/util/gandi"); + type FontManager = import("scratch-vm-dts/engine/tw-font-manager"); + type Variable = import("scratch-vm-dts/engine/variable"); + /** + * A pair of functions used to manage the cloud variable limit, + * to be used when adding (or attempting to add) or removing a cloud variable. + */ + type CloudDataManager = { + /** + * A function to call to check that + * a cloud variable can be added. + */ + canAddCloudVariable: Function; + /** + * A function to call to track a new + * cloud variable on the runtime. + */ + addCloudVariable: Function; + /** + * A function to call when + * removing an existing cloud variable. + */ + removeCloudVariable: Function; + /** + * A function to call to check that + * the runtime has any cloud variables. + */ + hasCloudVariables: Function; + /** + * A function that returns the + * number of cloud variables in the project. + */ + getNumberOfCloudVariables: Function; + }; +} + +declare module "scratch-vm-dts/extension-support/extension-manager" { + export = ExtensionManager; + class int extends Number { } + class bool extends Boolean { } + type ArgumentType = import("scratch-vm-dts/extension-support/argument-type"); + type VirtualMachine = import("scratch-vm-dts/virtual-machine"); + type Runtime = import("scratch-vm-dts/engine/runtime"); + type ExtensionBlockMetadata = import("scratch-vm-dts/extension-support/extension-metadata"); + + type Scratch3CoreExample = import("scratch-vm-dts/blocks/scratch3_core_example"); + type Scratch3PenBlocks = import("scratch-vm-dts/extensions/scratch3_pen"); + type Scratch3WeDo2Blocks = import("scratch-vm-dts/extensions/scratch3_wedo2"); + type Scratch3MicroBitBlocks = import("scratch-vm-dts/extensions/scratch3_microbit"); + type Scratch3Text2SpeechBlocks = import("scratch-vm-dts/extensions/scratch3_text2speech"); + type Scratch3TranslateBlocks = import("scratch-vm-dts/extensions/scratch3_translate"); + type Scratch3VideoSensingBlocks = import("scratch-vm-dts/extensions/scratch3_video_sensing"); + type Scratch3Ev3Blocks = import("scratch-vm-dts/extensions/scratch3_ev3"); + type Scratch3MakeyMakeyBlocks = import("scratch-vm-dts/extensions/scratch3_makeymakey"); + type Scratch3BoostBlocks = import("scratch-vm-dts/extensions/scratch3_boost"); + type Scratch3GdxForBlocks = import("scratch-vm-dts/extensions/scratch3_gdx_for"); + type TurboWarpBlocks = import("scratch-vm-dts/extensions/tw"); + class ExtensionManager { + constructor(vm: any); + /** + * The ID number to provide to the next extension worker. + * @type {int} + */ + nextExtensionWorker: int; + /** + * FIFO queue of extensions which have been requested but not yet loaded in a worker, + * along with promise resolution functions to call once the worker is ready or failed. + * + * @type {Array.} + */ + pendingExtensions: Array; + /** + * Map of worker ID to workers which have been allocated but have not yet finished initialization. + * @type {Array.} + */ + pendingWorkers: Array; + /** + * Map of worker ID to the URL where it was loaded from. + * @type {Array} + */ + workerURLs: Array; + /** + * Responsible for determining security policies related to custom extensions. + */ + securityManager: SecurityManager; + /** + * @type {VirtualMachine} + */ + vm: VirtualMachine; + /** + * Whether to show a warning that extensions are officially incompatible with Scratch. + * @type {boolean>} + */ + showCompatibilityWarning: boolean; + /** + * Keep a reference to the runtime so we can construct internal extension objects. + * @type {Runtime} + */ + runtime: Runtime; + loadingAsyncExtensions: number; + asyncExtensionsLoadedCallbacks: any[]; + _customExtensionInfo: {}; + _officialExtensionInfo: {}; + builtinExtensions: { + coreExample: Scratch3CoreExample; + pen: Scratch3PenBlocks; + wedo2: Scratch3WeDo2Blocks; + microbit: Scratch3MicroBitBlocks; + text2speech: Scratch3Text2SpeechBlocks; + translate: Scratch3TranslateBlocks; + videoSensing: Scratch3VideoSensingBlocks; + ev3: Scratch3Ev3Blocks; + makeymakey: Scratch3MakeyMakeyBlocks; + boost: Scratch3BoostBlocks; + gdxfor: Scratch3GdxForBlocks; + tw: TurboWarpBlocks; + }; + /** + * Check whether an extension is registered or is in the process of loading. This is intended to control loading or + * adding extensions so it may return `true` before the extension is ready to be used. Use the promise returned by + * `loadExtensionURL` if you need to wait until the extension is truly ready. + * @param {string} extensionID - the ID of the extension. + * @returns {boolean} - true if loaded, false otherwise. + */ + isExtensionLoaded(extensionID: string): boolean; + setLoadedExtension(extensionID: any, value: any): void; + registerExtension( + extensionId: any, + extension: any, + shouldReplace?: boolean + ): any; + /** + * Determine whether an extension with a given ID is built in to the VM, such as pen. + * Note that "core extensions" like motion will return false here. + * @param {string} extensionId + * @returns {boolean} + */ + isBuiltinExtension(extensionId: string): boolean; + /** + * Get the list of external extension service URLs. + * @returns {Array.} - The list of external extension service URLs. + */ + getGandiExternalExtensionServices(): Array; + /** + * Set a new list of external extension service URLs. + * This also resets the loaded flag to ensure the new services are loaded. + * @param {Array.} services - The list of new external extension service URLs. + */ + setGandiExternalExtensionServices(services: Array): void; + /** + * Synchronously load an internal extension (core or non-core) by ID. This call will + * fail if the provided id is not does not match an internal extension. + * @param {string} extensionId - the ID of an internal extension + */ + loadExtensionIdSync(extensionId: string): any; + addBuiltinExtension(extensionId: any, extensionClass: any): void; + _isValidExtensionURL(extensionURL: any): boolean; + /** + * Load an extension by URL or internal extension ID + * @param {string} extensionURL - the URL for the extension to load OR the ID of an internal extension + * @param {bool} shouldReplace - should replace extension that already loaded + * @returns {Promise} resolved once the extension is loaded and initialized or rejected on failure + */ + loadExtensionURL(extensionURL: string, shouldReplace?: bool): Promise; + /** + * Loads an extension URL in a worker. + * + * @param {string} extensionURL - The URL of the extension to load. + * @returns {Promise} A promise that resolves when the extension is loaded successfully, or rejects with an error if the extension is not found. + */ + loadExtensionURLInWorker(extensionURL: string): Promise; + /** + * Wait until all async extensions have loaded + * @returns {Promise} resolved when all async extensions have loaded + */ + allAsyncExtensionsLoaded(): Promise; + /** + * Creates a new extension worker. + * @returns {Promise} + */ + createExtensionWorker(): Promise; + /** + * Remove all extensions from services. + * If we don't do so, this will cause memory leak on Single Page Application. + */ + disposeExtensionServices(): void; + /** + * Regenerate blockinfo for any loaded extensions + * @returns {Promise} resolved once all the extensions have been reinitialized + */ + refreshBlocks(targetServiceName: any): Promise; + allocateWorker(): (string | number)[]; + /** + * Synchronously collect extension metadata from the specified service and begin the extension registration process. + * @param {string} serviceName - the name of the service hosting the extension. + */ + registerExtensionServiceSync(serviceName: string): void; + /** + * Collect extension metadata from the specified service and begin the extension registration process. + * @param {string} serviceName - the name of the service hosting the extension. + */ + registerExtensionService(serviceName: string): void; + _finishedLoadingExtensionScript(): void; + _failedLoadingExtensionScript(error: any): void; + /** + * Called by an extension worker to indicate that the worker has finished initialization. + * @param {int} id - the worker ID. + * @param {*?} e - the error encountered during initialization, if any. + */ + onWorkerInit(id: int, e: any | null): void; + /** + * Register an internal (non-Worker) extension object + * @param {object} extensionObject - the extension object to register + * @returns {string} The name of the registered extension service + */ + _registerInternalExtension(extensionObject: object): string; + /** + * @description register gandi extension when developer load custom extension + * @param {string} id extension id + * @param {string} url extension url + */ + saveWildExtensionsURL(id: string, url: string): void; + loadExternalExtensionById( + extensionId: any, + shouldReplace?: boolean + ): Promise | undefined; + isValidExtensionURL(extensionURL: any): boolean; + injectExtension(extensionId: any, extension: any): void; + isExternalExtension(extensionId: any): boolean; + clearLoadedExtensions(): void; + addOfficialExtensionInfo(obj: any): void; + addCustomExtensionInfo(obj: any, url: any): void; + updateExternalExtensionConstructor(extensionId: any, func: any): void; + getExternalExtensionConstructor(extensionId: any): Promise; + /** + * Loads an external extension to the library. + * + * @param {string} url - The URL of the external extension. + * @param {boolean} [shouldReplace=false] - Whether to replace existing extensions with the same ID. + * @param {boolean} [disallowIIFERegister=false] - Whether to disallow registering extensions using IIFE. + * @returns {Promise<{onlyAdded: string[], addedAndLoaded: string[]}>} - A promise that resolves with an object containing two arrays: `onlyAdded` and `addedAndLoaded`. + * - `onlyAdded` contains the IDs of the extensions that were only added to the library. + * - `addedAndLoaded` contains the IDs of the extensions that were both added to the library and loaded. + * @throws {Error} - If an error occurs while loading the extension. + */ + loadExternalExtensionToLibrary( + url: string, + shouldReplace?: boolean, + disallowIIFERegister?: boolean + ): Promise<{ + onlyAdded: string[]; + addedAndLoaded: string[]; + }>; + /** + * Checks if an extension ID is reserved. + * + * @param {string} extensionId - The extension ID to check. + * @returns {boolean} - Returns `false` if the extension ID is not reserved, `true` otherwise. + */ + isExtensionIdReserved(extensionId: string): boolean; + getLoadedExtensionURLs(): {}; + deleteExtensionById(extensionId: any): void; + getReplaceableExtensionInfo(): any[]; + getExtensionInfoById(extensionId: any): any; + replaceExtensionWithId(newId: any, oldId: any): void; + isExtensionURLLoaded(extensionURL: any): boolean; + getExtensionURLs(): {}; + } + namespace ExtensionManager { + export { + ArgumentInfo, + ConvertedBlockInfo, + CategoryInfo, + PendingExtensionWorker, + }; + } + import SecurityManager = require("scratch-vm-dts/extension-support/tw-security-manager"); + /** + * - Information about an extension block argument + */ + type ArgumentInfo = { + /** + * - the type of value this argument can take + */ + type: ArgumentType; + /** + * - the default value of this argument (default: blank) + */ + default: any | undefined; + }; + /** + * - Raw extension block data paired with processed data ready for scratch-blocks + */ + type ConvertedBlockInfo = { + /** + * - the raw block info + */ + info: ExtensionBlockMetadata; + /** + * - the scratch-blocks JSON definition for this block + */ + json: object; + /** + * - the scratch-blocks XML definition for this block + */ + xml: string; + }; + /** + * - Information about a block category + */ + type CategoryInfo = { + /** + * - the unique ID of this category + */ + id: string; + /** + * - the human-readable name of this category + */ + name: string; + /** + * - optional URI for the block icon image + */ + blockIconURI: string | undefined; + /** + * - the primary color for this category, in '#rrggbb' format + */ + color1: string; + /** + * - the secondary color for this category, in '#rrggbb' format + */ + color2: string; + /** + * - the tertiary color for this category, in '#rrggbb' format + */ + color3: string; + /** + * - the blocks, separators, etc. in this category + */ + blocks: Array; + /** + * - the menus provided by this category + */ + menus: Array; + }; + /** + * - Information about an extension worker still initializing + */ + type PendingExtensionWorker = { + /** + * - the URL of the extension to be loaded by this worker + */ + extensionURL: string; + /** + * - function to call on successful worker startup + */ + resolve: Function; + /** + * - function to call on failed worker startup + */ + reject: Function; + }; +} + +declare module "scratch-vm-dts/sprites/sprite" { + export = Sprite; + type Runtime = import("scratch-vm-dts/engine/runtime"); + class int extends Number { } + class Sprite { + /** + * Sprite to be used on the Scratch stage. + * All clones of a sprite have shared blocks, shared costumes, shared variables, + * shared sounds, etc. + * @param {?Blocks} blocks Shared blocks object for all clones of sprite. + * @param {Runtime} runtime Reference to the runtime. + * @param {?Frames} frames Shared frames object for all clones of sprite. + * @constructor + */ + constructor(blocks: Blocks | null, runtime: Runtime, frames: Frames | null); + runtime: any; + blocks: Blocks; + frames: Frames; + /** + * Human-readable name for this sprite (and all clones). + * @type {string} + */ + name: string; + /** + * List of costumes for this sprite. + * Each entry is an object, e.g., + * { + * skinId: 1, + * name: "Costume Name", + * bitmapResolution: 2, + * rotationCenterX: 0, + * rotationCenterY: 0 + * } + * @type {Array.} + */ + costumes_: Array; + /** + * List of sounds for this sprite. + */ + sounds: any[]; + /** + * List of clones for this sprite, including the original. + * @type {Array.} + */ + clones: Array; + soundBank: any; + /** + * Add an array of costumes, taking care to avoid duplicate names. + * @param {!Array} costumes Array of objects representing costumes. + */ + set costumes(costumes: Array); + /** + * Get full costume list + * @return {object[]} list of costumes. Note that mutating the returned list will not + * mutate the list on the sprite. The sprite list should be mutated by calling + * addCostumeAt, deleteCostumeAt, or setting costumes. + */ + get costumes(): object[]; + /** + * Add a costume at the given index, taking care to avoid duplicate names. + * @param {!object} costumeObject Object representing the costume. + * @param {!int} index Index at which to add costume + */ + addCostumeAt(costumeObject: object, index: int): void; + /** + * Delete a costume by index. + * @param {number} index Costume index to be deleted + * @return {?object} The deleted costume + */ + deleteCostumeAt(index: number): object | null; + /** + * Create a clone of this sprite. + * @param {string=} optLayerGroup Optional layer group the clone's drawable should be added to + * Defaults to the sprite layer group + * @returns {!RenderedTarget} Newly created clone. + */ + createClone(optLayerGroup?: string | undefined): RenderedTarget; + /** + * Disconnect a clone from this sprite. The clone is unmodified. + * In particular, the clone's dispose() method is not called. + * @param {!RenderedTarget} clone - the clone to be removed. + */ + removeClone(clone: RenderedTarget): void; + cloneCount(): number; + duplicate(): Promise; + dispose(): void; + } + import Blocks = require("scratch-vm-dts/engine/blocks"); + import Frames = require("scratch-vm-dts/engine/frame"); + import RenderedTarget = require("scratch-vm-dts/sprites/rendered-target"); +} + +declare module "scratch-vm-dts/sprites/rendered-target" { + export = RenderedTarget; + type Runtime = import("scratch-vm-dts/engine/runtime"); + type Sprite = import("scratch-vm-dts/sprites/sprite"); + class RenderWebGL { } + class int extends Number { } + /** + * Rendered target: instance of a sprite (clone), or the stage. + */ + class RenderedTarget extends Target { + /** + * Rotation style for "all around"/spinning. + * @type {string} + */ + static get ROTATION_STYLE_ALL_AROUND(): string; + /** + * Rotation style for "left-right"/flipping. + * @type {string} + */ + static get ROTATION_STYLE_LEFT_RIGHT(): string; + /** + * Rotation style for "no rotation." + * @type {string} + */ + static get ROTATION_STYLE_NONE(): string; + /** + * Available states for video input. + * @enum {string} + */ + static get VIDEO_STATE(): { + OFF: string; + ON: string; + ON_FLIPPED: string; + }; + /** + * @param {!Sprite} sprite Reference to the parent sprite. + * @param {Runtime} runtime Reference to the runtime. + * @constructor + */ + constructor(sprite: Sprite, runtime: Runtime); + /** + * Reference to the sprite that this is a render of. + * @type {!Sprite} + */ + sprite: Sprite; + /** + * Reference to the global renderer for this VM, if one exists. + * @type {?RenderWebGL} + */ + renderer: RenderWebGL | null; + /** + * ID of the drawable for this rendered target, + * returned by the renderer, if rendered. + * @type {?Number} + */ + drawableID: number | null; + /** + * Drag state of this rendered target. If true, x/y position can't be + * changed by blocks. + * @type {boolean} + */ + dragging: boolean; + /** + * Map of current graphic effect values. + * @type {!Object.} + */ + effects: { + [x: string]: number; + }; + /** + * Whether this represents an "original" non-clone rendered-target for a sprite, + * i.e., created by the editor and not clone blocks. + * @type {boolean} + */ + isOriginal: boolean; + /** + * Whether this rendered target represents the Scratch stage. + * @type {boolean} + */ + isStage: boolean; + /** + * Scratch X coordinate. Currently should range from -240 to 240. + * @type {Number} + */ + _x: number; + /** + * Scratch Y coordinate. Currently should range from -180 to 180. + * @type {number} + */ + _y: number; + /** + * Scratch direction. Currently should range from -179 to 180. + * @type {number} + */ + direction: number; + /** + * Whether the rendered target is draggable on the stage + * @type {boolean} + */ + draggable: boolean; + /** + * Whether the rendered target is currently visible. + * @type {boolean} + */ + _visible: boolean; + /** + * Size of rendered target as a percent of costume size. + * @type {number} + */ + _size: number; + /** + * Non-uniform scale dimensions of rendered target as a percent of original size. + */ + _size2d: number[]; + /** + * Currently selected costume index. + * @type {number} + */ + currentCostume: number; + /** + * Current rotation style. + * @type {!string} + */ + rotationStyle: string; + /** + * Loudness for sound playback for this target, as a percentage. + * @type {number} + */ + volume: number; + /** + * Current tempo (used by the music extension). + * This property is global to the project and stored in the stage. + * @type {number} + */ + tempo: number; + /** + * The transparency of the video (used by extensions with camera input). + * This property is global to the project and stored in the stage. + * @type {number} + */ + videoTransparency: number; + /** + * The state of the video input (used by extensions with camera input). + * This property is global to the project and stored in the stage. + * + * Defaults to ON. This setting does not turn the video by itself. A + * video extension once loaded will set the video device to this + * setting. Set to ON when a video extension is added in the editor the + * video will start ON. If the extension is loaded as part of loading a + * saved project the extension will see the value set when the stage + * was loaded from the saved values including the video state. + * + * @type {string} + */ + videoState: string; + /** + * The language to use for speech synthesis, in the text2speech extension. + * It is initialized to null so that on extension load, we can check for + * this and try setting it using the editor locale. + * @type {string} + */ + textToSpeechLanguage: string; + onTargetMoved: any; + onTargetVisualChange: any; + interpolationData: any; + extractProperties: {}; + isModule: any; + set size(size: number); + get size(): number; + set size2d([width, height]: number[]); + get size2d(): number[]; + set visible(visible: boolean); + get visible(): boolean; + set x(x: number); + get x(): number; + set y(y: number); + get y(): number; + get originalTargetId(): any; + /** + * Create a drawable with the this.renderer. + * @param {boolean} layerGroup The layer group this drawable should be added to + */ + initDrawable(layerGroup: boolean): void; + get audioPlayer(): { + playSound: (soundId: any) => any; + }; + /** + * Initialize the audio player for this sprite or clone. + */ + initAudio(): void; + emitVisualChange(): void; + /** + * Set the X and Y coordinates. + * @param {!number} x New X coordinate, in Scratch coordinates. + * @param {!number} y New Y coordinate, in Scratch coordinates. + * @param {?boolean} force Force setting X/Y, in case of dragging + */ + setXY(x: number, y: number, force: boolean | null): void; + /** + * Get the rendered direction and scale, after applying rotation style. + * @return {object} Direction and scale to render. + */ + _getRenderedDirectionAndScale(): object; + /** + * Set the direction. + * @param {!number} direction New direction. + */ + setDirection(direction: number): void; + /** + * Set draggability; i.e., whether it's able to be dragged in the player + * @param {!boolean} draggable True if should be draggable. + */ + setDraggable(draggable: boolean): void; + /** + * Set visibility; i.e., whether it's shown or hidden. + * @param {!boolean} visible True if should be shown. + */ + setVisible(visible: boolean): void; + /** + * Set size, as a percentage of the costume size. + * @param {!number} size Size of rendered target, as % of costume size. + */ + setSize(size: number): void; + /** + * Set a particular graphic effect value. + * @param {!string} effectName Name of effect (see `RenderedTarget.prototype.effects`). + * @param {!number} value Numerical magnitude of effect. + */ + setEffect(effectName: string, value: number): void; + /** + * Clear all graphic effects on this rendered target. + */ + clearEffects(): void; + /** + * Set the current costume. + * @param {number} index New index of costume. + */ + setCostume(index: number): void; + /** + * Add a costume, taking care to avoid duplicate names. + * @param {!object} costumeObject Object representing the costume. + * @param {?int} index Index at which to add costume + * @param {?boolean} isRemoteOperation Whether this is a remote operation + */ + addCostume( + costumeObject: object, + index: int | null, + isRemoteOperation: boolean | null + ): void; + /** + * Rename a costume, taking care to avoid duplicate names. + * @param {int} costumeIndex - the index of the costume to be renamed. + * @param {string} newName - the desired new name of the costume (will be modified if already in use). + * @param {boolean} [sendNameChangedEvent = true] whether to send an event when the name changes. + */ + renameCostume( + costumeIndex: int, + newName: string, + sendNameChangedEvent?: boolean + ): void; + /** + * Delete a costume by index. + * @param {number} index Costume index to be deleted + * @param {?boolean} isRemoteOperation Whether this is a remote operation + * @return {?object} The costume that was deleted or null + * if the index was out of bounds of the costumes list or + * this target only has one costume. + */ + deleteCostume( + index: number, + isRemoteOperation: boolean | null + ): object | null; + /** + * Add a sound, taking care to avoid duplicate names. + * @param {!object} soundObject Object representing the sound. + * @param {?int} index Index at which to add costume + */ + addSound(soundObject: object, index: int | null): void; + /** + * Rename a sound, taking care to avoid duplicate names. + * @param {int} soundIndex - the index of the sound to be renamed. + * @param {string} newName - the desired new name of the sound (will be modified if already in use). + * @param {boolean} [sendNameChangedEvent = true] whether to send an event when the name changes. + * @return {string} The new name of the sound. + */ + renameSound( + soundIndex: int, + newName: string, + sendNameChangedEvent?: boolean + ): string; + /** + * Delete a sound by index. + * @param {number} index Sound index to be deleted + * @return {object} The deleted sound object, or null if no sound was deleted. + */ + deleteSound(index: number): object; + /** + * Update the rotation style. + * @param {!string} rotationStyle New rotation style. + */ + setRotationStyle(rotationStyle: string): void; + /** + * Get a costume index of this rendered target, by name of the costume. + * @param {?string} costumeName Name of a costume. + * @return {number} Index of the named costume, or -1 if not present. + */ + getCostumeIndexByName(costumeName: string | null): number; + /** + * Get a costume index of this rendered target, by id of the costume. + * @param {?string} costumeId Id of a costume. + * @return {number} Index of the named costume, or -1 if not present. + */ + getCostumeIndexById(costumeId: string | null): number; + getCostumeById(id: any): object | null; + /** + * Get a costume of this rendered target by id. + * @return {object} current costume + */ + getCurrentCostume(): object; + /** + * Get full costume list + * @return {object[]} list of costumes + */ + getCostumes(): object[]; + /** + * Reorder costume list by moving costume at costumeIndex to newIndex. + * @param {!number} costumeIndex Index of the costume to move. + * @param {!number} newIndex New index for that costume. + * @returns {boolean} If a change occurred (i.e. if the indices do not match) + */ + reorderCostume(costumeIndex: number, newIndex: number): boolean; + /** + * Reorder sound list by moving sound at soundIndex to newIndex. + * @param {!number} soundIndex Index of the sound to move. + * @param {!number} newIndex New index for that sound. + * @returns {boolean} If a change occurred (i.e. if the indices do not match) + */ + reorderSound(soundIndex: number, newIndex: number): boolean; + /** + * Get full sound list + * @return {object[]} list of sounds + */ + getSounds(): object[]; + /** + * Get a sound index of this rendered target, by id of the sound. + * @param {?string} soundId Id of a sound. + * @return {number} Index of the named sound, or -1 if not present. + */ + getSoundIndexById(soundId: string | null): number; + getSoundById(id: any): object | null; + /** + * Update all drawable properties for this rendered target. + * Use when a batch has changed, e.g., when the drawable is first created. + */ + updateAllDrawableProperties(): void; + /** + * Return whether this rendered target is a sprite (not a clone, not the stage). + * @return {boolean} True if not a clone and not the stage. + */ + isSprite(): boolean; + /** + * Return the rendered target's tight bounding box. + * Includes top, left, bottom, right attributes in Scratch coordinates. + * @return {?object} Tight bounding box, or null. + */ + getBounds(): object | null; + /** + * Return the bounding box around a slice of the top 8px of the rendered target. + * Includes top, left, bottom, right attributes in Scratch coordinates. + * @return {?object} Tight bounding box, or null. + */ + getBoundsForBubble(): object | null; + /** + * Return whether this target is touching the mouse, an edge, or a sprite. + * @param {string} requestedObject an id for mouse or edge, or a sprite name. + * @return {boolean} True if the sprite is touching the object. + */ + isTouchingObject(requestedObject: string): boolean; + /** + * Return whether touching a point. + * @param {number} x X coordinate of test point. + * @param {number} y Y coordinate of test point. + * @return {boolean} True iff the rendered target is touching the point. + */ + isTouchingPoint(x: number, y: number): boolean; + /** + * Return whether touching a stage edge. + * @return {boolean} True iff the rendered target is touching the stage edge. + */ + isTouchingEdge(): boolean; + /** + * Return whether touching any of a named sprite's clones. + * @param {string} spriteName Name of the sprite. + * @return {boolean} True iff touching a clone of the sprite. + */ + isTouchingSprite(spriteName: string): boolean; + /** + * Return whether touching a color. + * @param {Array.} rgb [r,g,b], values between 0-255. + * @return {Promise.} True iff the rendered target is touching the color. + */ + isTouchingColor(rgb: Array): Promise; + /** + * Return whether rendered target's color is touching a color. + * @param {object} targetRgb {Array.} [r,g,b], values between 0-255. + * @param {object} maskRgb {Array.} [r,g,b], values between 0-255. + * @return {Promise.} True iff the color is touching the color. + */ + colorIsTouchingColor(targetRgb: object, maskRgb: object): Promise; + getLayerOrder(): any; + /** + * Move to the front layer. + */ + goToFront(): void; + /** + * Move to the back layer. + */ + goToBack(): void; + /** + * Move forward a number of layers. + * @param {number} nLayers How many layers to go forward. + */ + goForwardLayers(nLayers: number): void; + /** + * Move backward a number of layers. + * @param {number} nLayers How many layers to go backward. + */ + goBackwardLayers(nLayers: number): void; + /** + * Move behind some other rendered target. + * @param {!RenderedTarget} other Other rendered target to move behind. + */ + goBehindOther(other: RenderedTarget): void; + /** + * Keep a desired position within a fence. + * @param {number} newX New desired X position. + * @param {number} newY New desired Y position. + * @param {object=} optFence Optional fence with left, right, top bottom. + * @return {Array.} Fenced X and Y coordinates. + */ + keepInFence( + newX: number, + newY: number, + optFence?: object | undefined + ): Array; + /** + * Make a clone, copying any run-time properties. + * If we've hit the global clone limit, returns null. + * @return {RenderedTarget} New clone. + */ + makeClone(): RenderedTarget; + /** + * Make a duplicate using a duplicate sprite. + * @return {RenderedTarget} New clone. + */ + duplicate(): RenderedTarget; + /** + * Called when the project receives a "stop all" + * Stop all sounds and clear graphic effects. + */ + onStopAll(): void; + /** + * Post/edit sprite info. + * @param {object} data An object with sprite info data to set. + */ + postSpriteInfo(data: object): void; + /** + * Put the sprite into the drag state. While in effect, setXY must be forced + */ + startDrag(): void; + /** + * Remove the sprite from the drag state. + */ + stopDrag(): void; + /** + * Serialize sprite info, used when emitting events about the sprite + * @returns {object} Sprite data as a simple object + */ + toJSON(): object; + } + import Target from "scratch-vm-dts/engine/target"; +} + +declare module "scratch-vm-dts/engine/blocks" { + export = Blocks; + type Target = import("scratch-vm-dts/engine/target"); + /** + * Create a block container. + * @param {Runtime} runtime The runtime this block container operates within + * @param {boolean} optNoGlow Optional flag to indicate that blocks in this container + * should not request glows. This does not affect glows when clicking on a block to execute it. + */ + class Blocks { + /** + * Blockly inputs that represent statements/branch. + * are prefixed with this string. + * @const{string} + */ + static get BRANCH_INPUT_PREFIX(): string; + constructor(runtime: any, optNoGlow: any); + runtime: any; + /** + * All blocks in the workspace. + * Keys are block IDs, values are metadata about the block. + * @type {Object.} + */ + _blocks: { + [id: string]: Object; + }; + /** + * All top-level scripts in the workspace. + * A list of block IDs that represent scripts (i.e., first block in script). + * @type {Array.} + */ + _scripts: Array; + _cache: { + /** + * Cache block inputs by block id + * @type {object.>} + */ + inputs: { [key: string]: Array }; + /** + * Cache procedure Param Names by block id + * @type {object.>} + */ + procedureParamNames: { [key: string]: Array }; + /** + * Cache procedure definitions by block id + * @type {object.} + */ + procedureDefinitions: { [key: string]: string | null }; + /** + * A cache for execute to use and store on. Only available to + * execute. + * @type {object.} + */ + _executeCached: { [key: string]: object }; + /** + * A cache of block IDs and targets to start threads on as they are + * actively monitored. + * @type {Array<{blockId: string, target: Target}>} + */ + _monitored: Array<{ + blockId: string; + target: Target; + }>; + /** + * A cache of hat opcodes to collection of theads to execute. + * @type {object.} + */ + scripts: { [key: string]: object }; + /** + * tw: A cache of top block (usually hat, but not always) opcodes to compiled scripts. + * @type {object.} + */ + compiledScripts: { [key: string]: object }; + /** + * tw: A cache of procedure code opcodes to a parsed intermediate representation + * @type {object.} + */ + compiledProcedures: { [key: string]: object }; + /** + * tw: Whether populateProcedureCache has been run + */ + proceduresPopulated: boolean; + }; + /** + * Flag which indicates that blocks in this container should not glow. + * Blocks will still glow when clicked on, but this flag is used to control + * whether the blocks in this container can request a glow as part of + * a running stack. E.g. the flyout block container and the monitor block container + * should not be able to request a glow, but blocks containers belonging to + * sprites should. + * @type {boolean} + */ + forceNoGlow: boolean; + /** + * Get the cached compilation result of a block. + * @param {string} blockId ID of the top block. + * @returns {{success: boolean; value: any}|null} Cached success or error, or null if there is no cached value. + */ + getCachedCompileResult(blockId: string): { + success: boolean; + value: any; + } | null; + /** + * Set the cached compilation result of a script. + * @param {string} blockId ID of the top block. + * @param {*} value The compilation result to store. + */ + cacheCompileResult(blockId: string, value: any): void; + /** + * Set the cached error of a script. + * @param {string} blockId ID of the top block. + * @param {*} error The error to store. + */ + cacheCompileError(blockId: string, error: any): void; + /** + * Provide an object with metadata for the requested block ID. + * @param {!string} blockId ID of block we have stored. + * @return {?object} Metadata about the block, if it exists. + */ + getBlock(blockId: string): object | null; + /** + * Get all known top-level blocks that start scripts. + * @return {Array.} List of block IDs. + */ + getScripts(): Array; + /** + * Get the next block for a particular block + * @param {?string} id ID of block to get the next block for + * @return {?string} ID of next block in the sequence + */ + getNextBlock(id: string | null): string | null; + /** + * Get the branch for a particular C-shaped block. + * @param {?string} id ID for block to get the branch for. + * @param {?number} branchNum Which branch to select (e.g. for if-else). + * @return {?string} ID of block in the branch. + */ + getBranch(id: string | null, branchNum: number | null): string | null; + /** + * Get the opcode for a particular block + * @param {?object} block The block to query + * @return {?string} the opcode corresponding to that block + */ + getOpcode(block: object | null): string | null; + /** + * Get all fields and their values for a block. + * @param {?object} block The block to query. + * @return {?object} All fields and their values. + */ + getFields(block: object | null): object | null; + /** + * Get all non-branch inputs for a block. + * @param {?object} block the block to query. + * @return {?Array.} All non-branch inputs and their associated blocks. + */ + getInputs(block: object | null): Array | null; + /** + * Get mutation data for a block. + * @param {?object} block The block to query. + * @return {?object} Mutation for the block. + */ + getMutation(block: object | null): object | null; + /** + * Get the top-level script for a given block. + * @param {?string} id ID of block to query. + * @return {?string} ID of top-level script block. + */ + getTopLevelScript(id: string | null): string | null; + getGlobalProceduresXML(): string[]; + /** + * Get the procedure definition for a given name. + * @param {?string} name Name of procedure to query. + * @return {?string} ID of procedure definition. + */ + getProcedureDefinition(name: string | null): string | null; + getGlobalProcedureAndTarget(name: any): any[]; + /** + * Get names and ids of parameters for the given procedure. + * @param {?string} name Name of procedure to query. + * @return {?Array.} List of param names for a procedure. + */ + getProcedureParamNamesAndIds(name: string | null): Array | null; + /** + * Get names, ids, and defaults of parameters for the given procedure. + * @param {?string} name Name of procedure to query. + * @return {?Array.} List of param names for a procedure. + */ + _getProcedureParamNamesIdsAndDefaults( + name: string | null + ): Array | null; + /** CCW: for global procedure + * Get names, ids, and defaults of parameters for the given procedure. + * @param {?string} name Name of procedure to query. + * @param {?boolean} isGlobal need look up procedures from all runtime targets + * @return {?Array.} List of param names for a procedure. + */ + getProcedureParamNamesIdsAndDefaults( + name: string | null, + isGlobal: boolean | null + ): Array | null; + /** + * tw: Setup the procedureParamNames and procedureDefinitions caches all at once. + * This makes subsequent calls to these methods faster. + */ + populateProcedureCache(): void; + updateGlobalProcedure(oldProccode: any, newMutation: any): any[]; + duplicate(): Blocks; + /** + * Create event listener for blocks, variables, and comments. Handles validation and + * serves as a generic adapter between the blocks, variables, and the + * runtime interface. + * @param {object} e Blockly "block" or "variable" event + * @param {string} source Who triggered this function + */ + blocklyListen(e: object, source: string): void; + /** + * Reset all runtime caches. + */ + resetCache(): void; + /** + * Emit a project changed event if this is a block container + * that can affect the project state. + */ + emitProjectChanged(): void; + emitCustomBlockArgumentsLengthChanged(): void; + /** + * Block management: create blocks and scripts from a `create` event + * @param {!object} block Blockly create event to be processed + * @return {boolean} Whether the block successfully created + */ + createBlock(block: object, source: any): boolean; + /** + * Block management: change block field values + * @param {!object} args Blockly change event to be processed + * @param {boolean} isRuntimeOp Whether it is an operation at run time + */ + changeBlock(args: object, isRuntimeOp: boolean): void; + updateBlockMutation(block: any, args: any): void; + /** + * Block management: move blocks from parent to parent + * @param {!object} e Blockly move event to be processed + */ + moveBlock(e: object): void; + /** + * Block management: run all blocks. + * @param {!object} runtime Runtime to run all blocks in. + */ + runAllMonitored(runtime: object): void; + /** + * Block management: delete blocks and their associated scripts. Does nothing if a block + * with the given ID does not exist. + * @param {!string} blockId Id of block to delete + */ + deleteBlock(blockId: string, params?: {}): void; + /** + * Delete all blocks and their associated scripts. + */ + deleteAllBlocks(): void; + /** + * Returns a map of all references to variables or lists from blocks + * in this block container. + * @param {Array} optBlocks Optional list of blocks to constrain the search to. + * This is useful for getting variable/list references for a stack of blocks instead + * of all blocks on the workspace + * @param {?boolean} optIncludeBroadcast Optional whether to include broadcast fields. + * @return {object} A map of variable ID to a list of all variable references + * for that ID. A variable reference contains the field referencing that variable + * and also the type of the variable being referenced. + */ + getAllVariableAndListReferences( + optBlocks: Array, + optIncludeBroadcast: boolean | null + ): object; + getAllVariableAndListWithBlocks( + blocks: any, + optIncludeBroadcast: any + ): any[][]; + /** + * Keep blocks up to date after a variable gets renamed. + * @param {string} varId The id of the variable that was renamed + * @param {string} newName The new name of the variable that was renamed + */ + updateBlocksAfterVarRename(varId: string, newName: string): any[][]; + /** + * Keep blocks up to date after they are shared between targets. + * @param {boolean} isStage If the new target is a stage. + */ + updateTargetSpecificBlocks(isStage: boolean): void; + /** + * Update blocks after a sound, costume, or backdrop gets renamed. + * Any block referring to the old name of the asset should get updated + * to refer to the new name. + * @param {string} oldName The old name of the asset that was renamed. + * @param {string} newName The new name of the asset that was renamed. + * @param {string} assetType String representation of the kind of asset + * @param {?string} targetId The ID of the target to emit block changes for (optional). + * that was renamed. This can be one of 'sprite','costume', 'sound', or + * 'backdrop'. + */ + updateAssetName( + oldName: string, + newName: string, + assetType: string, + targetId: string | null + ): void; + /** + * Update sensing_of blocks after a variable gets renamed. + * @param {string} oldName The old name of the variable that was renamed. + * @param {string} newName The new name of the variable that was renamed. + * @param {string} targetName The name of the target the variable belongs to. + * @return {boolean} Returns true if any of the blocks were updated. + */ + updateSensingOfReference( + oldName: string, + newName: string, + targetName: string + ): boolean; + /** + * Helper function to retrieve a costume menu field from a block given its id. + * @param {string} blockId A unique identifier for a block + * @return {?object} The costume menu field of the block with the given block id. + * Null if either a block with the given id doesn't exist or if a costume menu field + * does not exist on the block with the given id. + */ + _getCostumeField(blockId: string): object | null; + /** + * Helper function to retrieve a sound menu field from a block given its id. + * @param {string} blockId A unique identifier for a block + * @return {?object} The sound menu field of the block with the given block id. + * Null, if either a block with the given id doesn't exist or if a sound menu field + * does not exist on the block with the given id. + */ + _getSoundField(blockId: string): object | null; + /** + * Helper function to retrieve a backdrop menu field from a block given its id. + * @param {string} blockId A unique identifier for a block + * @return {?object} The backdrop menu field of the block with the given block id. + * Null, if either a block with the given id doesn't exist or if a backdrop menu field + * does not exist on the block with the given id. + */ + _getBackdropField(blockId: string): object | null; + /** + * Helper function to retrieve a sprite menu field from a block given its id. + * @param {string} blockId A unique identifier for a block + * @return {?object} The sprite menu field of the block with the given block id. + * Null, if either a block with the given id doesn't exist or if a sprite menu field + * does not exist on the block with the given id. + */ + _getSpriteField(blockId: string): object | null; + /** + * Encode all of `this._blocks` as an XML string usable + * by a Blockly/scratch-blocks workspace. + * @param {object} comments Map of comments referenced by id + * @return {string} String of XML representing this object's blocks. + */ + toXML(comments: any): string; + /** + * Recursively encode an individual block and its children + * into a Blockly/scratch-blocks XML string. + * @param {!string} blockId ID of block to encode. + * @param {object} comments Map of comments referenced by id + * @return {string} String of XML representing this block and any children. + */ + blockToXML( + blockId: string, + comments: {[id:string]:Comment}, + blocks?: { + [id: string]: Object; + } + ): string; + /** + * Recursively encode a mutation object to XML. + * @param {!object} mutation Object representing a mutation. + * @return {string} XML string representing a mutation. + */ + mutationToXML(mutation: object): string; + /** + * Helper to serialize block fields and input fields for reporting new monitors + * @param {!object} block Block to be paramified. + * @return {!object} object of param key/values. + */ + _getBlockParams(block: object): object; + /** + * Helper to get the corresponding internal procedure definition block + * @param {!object} defineBlock Outer define block. + * @return {!object} internal definition block which has the mutation. + */ + _getCustomBlockInternal(defineBlock: object): object; + /** + * Helper to add a stack to `this._scripts`. + * @param {?string} topBlockId ID of block that starts the script. + * @return {boolean} Whether added successfully. + */ + _addScript(topBlockId: string | null): boolean; + /** + * Helper to remove a script from `this._scripts`. + * @param {?string} topBlockId ID of block that starts the script. + */ + _deleteScript(topBlockId: string | null): void; + } +} + +declare module "scratch-vm-dts/engine/frame" { + export = Frames; + /** + * Create a frame container. + * @param {Runtime} runtime The runtime this frame container operates within + */ + class Frames { + constructor(runtime: any); + runtime: any; + /** + * All frames in the workspace. + * Keys are frame IDs, values are metadata about the frame. + * @type {Object.} + */ + _frames: { + [x: string]: Object; + }; + /** + * Provide an object with metadata for the requested frame ID. + * @param {!string} frameId ID of frame we have stored. + * @return {?object} Metadata about the frame, if it exists. + */ + getFrame(frameId: string): object | null; + duplicate(): Frames; + /** + * Create event listener for frames. Handles validation and + * serves as a generic adapter between the frames, variables, and the + * runtime interface. + * @param {object} e Blockly "frame" event + */ + blocklyListen(e: object): void; + /** + * Emit a project changed event + * that can affect the project state. + */ + emitProjectChanged(): void; + /** + * Frame management: create frames from a `create` event + * @param {!object} e Blockly create event to be processed + */ + createFrame(e: object): boolean; + /** + * Frame management: delete frame. Does nothing if a frame with the given ID does not exist. + * @param {!string} id Id of frame to delete + */ + deleteFrame(id: string): boolean; + /** + * Frame management: delete frame. Does nothing if a frame with the given ID does not exist. + * @param {!string} id Id of frame to delete + * @param {!string} newTitle New title + */ + retitleFrame(id: string, newTitle: string): boolean; + /** + * Frame management: change frame field values + * @param {!string} id Id of the frame + * @param {string} element One of 'rect', 'blocks', 'disabled', etc. + * @param {*} value Previous value of element. + */ + changeFrame(id: string, element: string, value: any): boolean; + /** + * Recursively encode an individual frame into a Blockly/scratch-block XML string. + * @param {!string} id ID of frame to encode. + * @return {string} String of XML representing this frame. + */ + toXML(id: string): string; + frameToXML(frame: any): string; + } +} + +declare module "scratch-vm-dts/engine/variable" { + export = Variable; + class Variable { + /** + * Type representation for scalar variables. + * This is currently represented as '' + * for compatibility with blockly. + * @const {string} + */ + static get SCALAR_TYPE(): string; + /** + * Type representation for list variables. + * @const {string} + */ + static get LIST_TYPE(): string; + /** + * Type representation for list variables. + * @const {string} + */ + static get BROADCAST_MESSAGE_TYPE(): string; + /** + * @param {string} id Id of the variable. + * @param {string} name Name of the variable. + * @param {string} type Type of the variable, one of '' or 'list' + * @param {boolean} isCloud Whether the variable is stored in the cloud. + * @constructor + */ + constructor( + id: string, + name: string, + type: string, + isCloud: boolean, + targetId: any + ); + id: string; + name: string; + type: string; + isCloud: boolean; + targetId: any; + value: string | number | any[]; + toXML(isLocal: any): string; + } +} + +declare module "scratch-vm-dts/util/timer" { + export = Timer; + /** + * @fileoverview + * A utility for accurately measuring time. + * To use: + * --- + * var timer = new Timer(); + * timer.start(); + * ... pass some time ... + * var timeDifference = timer.timeElapsed(); + * --- + * Or, you can use the `time` function + * to do some measurement yourself. + */ + class Timer { + /** + * Disable use of self.performance for now as it results in lower performance + * However, instancing it like below (caching the self.performance to a local variable) negates most of the issues. + * @type {boolean} + */ + static get USE_PERFORMANCE(): boolean; + /** + * Legacy object to allow for us to call now to get the old style date time (for backwards compatibility) + * @deprecated This is only called via the nowObj.now() if no other means is possible... + */ + static get legacyDateCode(): { + now: () => number; + }; + /** + * Use this object to route all time functions through single access points. + */ + static get nowObj(): { + now: () => number; + }; + constructor(nowObj?: { now: () => number }); + /** + * Used to store the start time of a timer action. + * Updated when calling `timer.start`. + */ + startTime: number; + /** + * Used to pass custom logic for determining the value for "now", + * which is sometimes useful for compatibility with Scratch 2 + */ + nowObj: { + now: () => number; + }; + /** + * Return the currently known absolute time, in ms precision. + * @returns {number} ms elapsed since 1 January 1970 00:00:00 UTC. + */ + time(): number; + /** + * Start a timer for measuring elapsed time, + * at the most accurate precision possible. + */ + start(): void; + timeElapsed(): number; + /** + * Call a handler function after a specified amount of time has elapsed. + * @param {function} handler - function to call after the timeout + * @param {number} timeout - number of milliseconds to delay before calling the handler + * @returns {number} - the ID of the new timeout + */ + setTimeout(handler: Function, timeout: number): number; + /** + * Clear a timeout from the pending timeout pool. + * @param {number} timeoutId - the ID returned by `setTimeout()` + * @memberof Timer + */ + clearTimeout(timeoutId: number): void; + } +} + +declare module "scratch-vm-dts/engine/thread" { + export = Thread; + type Target = import("scratch-vm-dts/engine/target"); + type Blocks = import("scratch-vm-dts/engine/blocks"); + type Timer = import("scratch-vm-dts/util/timer"); + /** + * A thread is a running stack context and all the metadata needed. + * @param {?string} firstBlock First block to execute in the thread. + * @constructor + */ + class Thread { + /** + * Thread status for initialized or running thread. + * This is the default state for a thread - execution should run normally, + * stepping from block to block. + * @const + */ + static get STATUS_RUNNING(): number; + /** + * Threads are in this state when a primitive is waiting on a promise; + * execution is paused until the promise changes thread status. + * @const + */ + static get STATUS_PROMISE_WAIT(): number; + /** + * Thread status for yield. + * @const + */ + static get STATUS_YIELD(): number; + /** + * Thread status for a single-tick yield. This will be cleared when the + * thread is resumed. + * @const + */ + static get STATUS_YIELD_TICK(): number; + /** + * Thread status for a finished/done thread. + * Thread is in this state when there are no more blocks to execute. + * @const + */ + static get STATUS_DONE(): number; + /** + * @param {Target} target The target running the thread. + * @param {string} topBlock ID of the thread's top block. + * @returns {string} A unique ID for this target and thread. + */ + static getIdFromTargetAndBlock(target: Target, topBlock: string): string; + constructor(firstBlock: any); + /** + * ID of top block of the thread + * @type {!string} + */ + topBlock: string; + /** + * Stack for the thread. When the sequencer enters a control structure, + * the block is pushed onto the stack so we know where to exit. + * @type {Array.} + */ + stack: Array; + /** + * Stack frames for the thread. Store metadata for the executing blocks. + * @type {Array.<_StackFrame>} + */ + stackFrames: Array<_StackFrame>; + /** + * Status of the thread, one of three states (below) + * @type {number} + */ + status: number; + /** + * Whether the thread is killed in the middle of execution. + * @type {boolean} + */ + isKilled: boolean; + /** + * Target of this thread. + * @type {?Target} + */ + target: Target | null; + /** + * The Blocks this thread will execute. + * @type {Blocks} + */ + blockContainer: Blocks; + /** + * Whether the thread requests its script to glow during this frame. + * @type {boolean} + */ + requestScriptGlowInFrame: boolean; + /** + * Which block ID should glow during this frame, if any. + * @type {?string} + */ + blockGlowInFrame: string | null; + /** + * A timer for when the thread enters warp mode. + * Substitutes the sequencer's count toward WORK_TIME on a per-thread basis. + * @type {?Timer} + */ + warpTimer: Timer | null; + justReported: any; + triedToCompile: boolean; + isCompiled: boolean; + timer: any; + /** + * The thread's generator. + * @type {Generator} + */ + generator: Generator; + /** + * @type {Object.} + */ + procedures: { + [x: string]: any; + }; + stackClick: boolean; + updateMonitor: boolean; + /** + * store hat param. + * @type {Object} + */ + hatParam: Object; + executableHat: boolean; + compatibilityStackFrame: any; + getId(): string; + getCurrentGlobalTarget(): any; + /** + * Push stack and update stack frames appropriately. + * @param {string} blockId Block ID to push to stack. + * @param {Target} target CCW: the target execute in this stack frame, for global procedure. + */ + pushStack(blockId: string, target: Target): void; + /** + * Reset the stack frame for use by the next block. + * (avoids popping and re-pushing a new stack frame - keeps the warpmode the same + * @param {string} blockId Block ID to push to stack. + */ + reuseStackForNextBlock(blockId: string): void; + /** + * Pop last block on the stack and its stack frame. + * @return {string} Block ID popped from the stack. + */ + popStack(): string; + /** + * Pop back down the stack frame until we hit a procedure call or the stack frame is emptied + */ + stopThisScript(): void; + /** + * Get top stack item. + * @return {?string} Block ID on top of stack. + */ + peekStack(): string | null; + /** + * Get top stack frame. + * @return {?object} Last stack frame stored on this thread. + */ + peekStackFrame(): object | null; + /** + * Get stack frame above the current top. + * @return {?object} Second to last stack frame stored on this thread. + */ + peekParentStackFrame(): object | null; + /** + * Push a reported value to the parent of the current stack frame. + * @param {*} value Reported value to push. + */ + pushReportedValue(value: any): void; + /** + * Initialize procedure parameters on this stack frame. + */ + initParams(): void; + /** + * Add a parameter to the stack frame. + * Use when calling a procedure with parameter values. + * @param {!string} paramName Name of parameter. + * @param {*} value Value to set for parameter. + */ + pushParam(paramName: string, value: any): void; + getHatParam(paramName: any): any; + /** + * Get a parameter at the lowest possible level of the stack. + * @param {!string} paramName Name of parameter. + * @return {*} value Value for parameter. + */ + getParam(paramName: string): any; + getAllparams(): any; + /** + * Whether the current execution of a thread is at the top of the stack. + * @return {boolean} True if execution is at top of the stack. + */ + atStackTop(): boolean; + /** + * Switch the thread to the next block at the current level of the stack. + * For example, this is used in a standard sequence of blocks, + * where execution proceeds from one block to the next. + */ + goToNextBlock(): void; + /** + * Attempt to determine whether a procedure call is recursive, + * by examining the stack. + * @param {!string} procedureCode Procedure code of procedure being called. + * @return {boolean} True if the call appears recursive. + */ + isRecursiveCall(procedureCode: string): boolean; + /** + * Attempt to compile this thread. + */ + tryCompile(): void; + } + namespace Thread { + export { _StackFrame }; + } + /** + * A frame used for each level of the stack. A general purpose + * place to store a bunch of execution context and parameters + * @param {boolean} warpMode Whether this level of the stack is warping + * @constructor + * @private + */ + class _StackFrame { + /** + * Create or recycle a stack frame object. + * @param {boolean} warpMode Enable warpMode on this frame. + * @returns {_StackFrame} The clean stack frame with correct warpMode setting. + */ + static create(warpMode: boolean): _StackFrame; + /** + * Put a stack frame object into the recycle bin for reuse. + * @param {_StackFrame} stackFrame The frame to reset and recycle. + */ + static release(stackFrame: _StackFrame): void; + constructor(warpMode: any); + /** + * Whether this level of the stack is a loop. + * @type {boolean} + */ + isLoop: boolean; + /** + * Whether this level is in warp mode. Is set by some legacy blocks and + * "turbo mode" + * @type {boolean} + */ + warpMode: boolean; + /** + * Reported value from just executed block. + * @type {Any} + */ + justReported: any; + /** + * The active block that is waiting on a promise. + * @type {string} + */ + reporting: string; + /** + * Persists reported inputs during async block. + * @type {Object} + */ + reported: Object; + /** + * Name of waiting reporter. + * @type {string} + */ + waitingReporter: string; + /** + * Procedure parameters. + * @type {Object} + */ + params: Object; + /** + * A context passed to block implementations. + * @type {Object} + */ + executionContext: Object; + /** + * Internal block object being executed. This is *not* the same as the object found + * in target.blocks. + * @type {object} + */ + op: object; + /** + * Reset all properties of the frame to pristine null and false states. + * Used to recycle. + * @return {_StackFrame} this + */ + reset(): _StackFrame; + /** + * Reuse an active stack frame in the stack. + * @param {?boolean} warpMode defaults to current warpMode + * @returns {_StackFrame} this + */ + reuse(warpMode?: boolean | null): _StackFrame; + } +} + +declare module "scratch-vm-dts/engine/tw-frame-loop" { + export = FrameLoop; + class FrameLoop { + constructor(runtime: any); + runtime: any; + running: boolean; + stepCallback(): void; + interpolationCallback(): void; + _stepInterval: NodeJS.Timeout | null; + _interpolationAnimation: { + cancel: () => void; + } | null; + _stepAnimation: { + cancel: () => void; + } | null; + setFramerate(fps: any): void; + framerate: any; + setInterpolation(interpolation: any): void; + interpolation: any; + _restart(): void; + start(): void; + stop(): void; + } +} + +declare module "scratch-vm-dts/engine/profiler" { + export = Profiler; + class Profiler { + /** + * Lookup or create an id for a frame name. + * @static + * @param {string} name The name to return an id for. + * @return {number} The id for the passed name. + */ + static idByName(name: string): number; + /** + * Reverse lookup the name from a given frame id. + * @static + * @param {number} id The id to search for. + * @return {string} The name for the given id. + */ + static nameById(id: number): string; + /** + * Profiler is only available on platforms with the Performance API. + * @return {boolean} Can the Profiler run in this browser? + */ + static available(): boolean; + /** + * @param {FrameCallback} onFrame a handle called for each recorded frame. + * The passed frame value may not be stored as it'll be updated with later + * frame information. Any information that is further stored by the handler + * should make copies or reduce the information. + */ + constructor(onFrame?: FrameCallback); + /** + * A series of START and STOP values followed by arguments. After + * recording is complete the full set of records is reported back by + * stepping through the series to connect the relative START and STOP + * information. + * @type {Array.<*>} + */ + records: Array; + /** + * An array of frames incremented on demand instead as part of start + * and stop. + * @type {Array.} + */ + increments: Array; + /** + * An array of profiler frames separated by counter argument. Generally + * for Scratch these frames are separated by block function opcode. + * This tracks each time an opcode is called. + * @type {Array.} + */ + counters: Array; + /** + * A frame with no id or argument. + * @type {ProfilerFrame} + */ + nullFrame: ProfilerFrame; + /** + * A cache of ProfilerFrames to reuse when reporting the recorded + * frames in records. + * @type {Array.} + */ + _stack: Array; + /** + * A callback handle called with each decoded frame when reporting back + * all the recorded times. + * @type {FrameCallback} + */ + onFrame: FrameCallback; + /** + * A reference to the START record id constant. + * @const {number} + */ + START: number; + /** + * A reference to the STOP record id constant. + * @const {number} + */ + STOP: number; + /** + * Start recording a frame of time for an id and optional argument. + * @param {number} id The id returned by idByName for a name symbol like + * Runtime._step. + * @param {?*} arg An arbitrary argument value to store with the frame. + */ + start(id: number, arg: any | null): void; + /** + * Stop the current frame. + */ + stop(): void; + /** + * Increment the number of times this symbol is called. + * @param {number} id The id returned by idByName for a name symbol. + */ + increment(id: number): void; + /** + * Find or create a ProfilerFrame-like object whose counter can be + * incremented outside of the Profiler. + * @param {number} id The id returned by idByName for a name symbol. + * @param {*} arg The argument for a frame that identifies it in addition + * to the id. + * @return {{count: number}} A ProfilerFrame-like whose count should be + * incremented for each call. + */ + frame( + id: number, + arg: any + ): { + count: number; + }; + /** + * Decode records and report all frames to `this.onFrame`. + */ + reportFrames(): void; + /** + * Lookup or create an id for a frame name. + * @param {string} name The name to return an id for. + * @return {number} The id for the passed name. + */ + idByName(name: string): number; + /** + * Reverse lookup the name from a given frame id. + * @param {number} id The id to search for. + * @return {string} The name for the given id. + */ + nameById(id: number): string; + } + namespace Profiler { + export { START, STOP, FrameCallback }; + } + /** + * A set of information about a frame of execution that was recorded. + */ + class ProfilerFrame { + /** + * @param {number} depth Depth of the frame in the recorded stack. + */ + constructor(depth: number); + /** + * The numeric id of a record symbol like Runtime._step or + * blockFunction. + * @type {number} + */ + id: number; + /** + * The amount of time spent inside the recorded frame and any deeper + * frames. + * @type {number} + */ + totalTime: number; + /** + * The amount of time spent only inside this record frame. Not + * including time in any deeper frames. + * @type {number} + */ + selfTime: number; + /** + * An arbitrary argument for the recorded frame. For example a block + * function might record its opcode as an argument. + * @type {*} + */ + arg: any; + /** + * The depth of the recorded frame. This can help compare recursive + * funtions that are recorded. Each level of recursion with have a + * different depth value. + * @type {number} + */ + depth: number; + /** + * A summarized count of the number of calls to this frame. + * @type {number} + */ + count: number; + } + /** + * The START event identifier in Profiler records. + * @const {number} + */ + const START: 0; + /** + * The STOP event identifier in Profiler records. + * @const {number} + */ + const STOP: 1; + /** + * Callback handle called by Profiler for each frame it decodes from its + * records. + */ + type FrameCallback = (frame: ProfilerFrame) => any; +} + +declare module "scratch-vm-dts/util/log-system" { + export = LogSystem; + import { EventEmitter } from "node:events"; + class LogSystem extends EventEmitter { } +} + +declare module "scratch-vm-dts/util/gandi" { + export = Gandi; + class Gandi { + /** + * Constructor for the Gandi class. + * @constructor + * @param {Object} runtime - The runtime object. + */ + constructor(runtime: Object); + /** + * The runtime object. + * @member {Object} + */ + runtime: Object; + /** + * Array to store properties. + * @member {Array} + */ + properties: string[]; + /** + * default supported asset types + */ + _supportedAssetTypes: any[]; + merge(data: any): { + assets: any; + wildExtensions: any; + } | null; + configs: any; + wildExtensions: any; + dynamicMenuItems: any; + spine: any; + assets: any; + setup(): void; + set supportedAssetTypes(types: any[]); + get supportedAssetTypes(): any[]; + clear(): void; + /** + * Checks if all properties are empty. + * @method + * @returns {boolean} - True if all properties are empty, false otherwise. + */ + isEmpty(): boolean; + /** + * Checks if a specific property is empty. + * @method + * @param {string} propertyName - The name of the property to check. + * @returns {boolean} - True if the property is empty, false otherwise. + */ + istPropertyEmpty(propertyName: string): boolean; + /** + * Serializes Gandi assets. + * @method + * @param {Set} extensions - Set of extensions. + * @returns {Array} - Serialized Gandi assets. + */ + serializeGandiAssets(extensions: Set): any[]; + /** + * Checks if an object is empty. + * @method + * @param {Object} object - The object to check. + * @returns {boolean} - True if the object is empty, false otherwise. + */ + isEmptyObject(object: Object): boolean; + /** + * Serializes Gandi data. + * @method + * @param {Object} object - The object to serialize. + * @param {Set} extensions - Set of extensions. + */ + serialize(extensions: Set): + | { + wildExtensions: {}; + } + | { + spine: any; + } + | { + dynamicMenuItems: any; + } + | { + configs: any; + } + | { + assets: any[]; + } + | undefined; + /** + * Adds a Spine asset. + * @method + * @param {string} key - The key for the Spine asset. + * @param {Object} data - The data for the Spine asset. + */ + addSpineAsset(key: string, data: Object): void; + /** + * Deletes a Spine asset. + * @method + * @param {string} key - The key of the Spine asset to delete. + */ + deleteSpineAsset(key: string): void; + /** + * Gets a Spine asset by name. + * @method + * @param {string} name - The name of the Spine asset. + * @returns {Object} - The Spine asset data. + */ + getSpineAsset(name: string): Object; + /** + * Sets the value of a configuration item. + * @param {string} key - The key of the configuration item. + * @param {*} value - The value to set. + * @returns {void} + */ + setConfig(key: string, value: any): void; + /** + * Gets the value of a specified configuration item. + * @param {string} key - The key of the configuration item to retrieve the value. + * @returns {*} The value of the specified configuration item, or undefined if it doesn't exist. + */ + getConfig(key: string): any; + /** + * Adds a dynamic menu item. + * @method + * @param {string} menuName - The name of the dynamic menu. + * @param {Object} menuItem - The dynamic menu item to add. + */ + addDynamicMenuItem(menuName: string, menuItem: Object): void; + /** + * Gets dynamic menu items by name. + * @method + * @param {string} menuName - The name of the dynamic menu. + * @returns {Array} - Array of dynamic menu items. + */ + getDynamicMenuItems(menuName: string): any[]; + /** + * Deletes dynamic menu items. + * @method + * @param {string} menuName - The name of the dynamic menu. + * @param {string} id - The id of the dynamic menu item to delete. + * @throws Will throw an error if the menu name is not provided. + */ + deleteDynamicMenuItems(menuName: string, id: string): void; + /** + * Adds a wild extension. + * @method + * @param {Object} data - The data for the wild extension. + */ + addWildExtension(data: { id: string; url: string }): void; + /** + * Deletes a wild extension. + * @method + * @param {string} id - The id of the wild extension to delete. + */ + deleteWildExtension(id: string): void; + getExtensionAssets(): any; + isExtensionURLInGandiAssets(url: any): any; + } +} + +declare module "scratch-vm-dts/engine/tw-font-manager" { + export = FontManager; + type Runtime = import("scratch-vm-dts/engine/runtime"); + import JSZip from "jszip"; + class Asset { } + /** + * @typedef InternalFont + * @property {boolean} system True if the font is built in to the system + * @property {string} family The font's name + * @property {string} fallback Fallback font family list + * @property {Asset} [asset] scratch-storage asset if system: false + */ + class FontManager extends EventEmitter<[never]> { + /** + * @param {Runtime} runtime + */ + constructor(runtime: Runtime); + runtime: Runtime; + /** @type {Array} */ + fonts: Array; + /** + * @param {string} family An unknown font family + * @returns {boolean} true if the family is valid + */ + isValidFamily(family: string): boolean; + /** + * @param {string} family + * @returns {boolean} + */ + hasFont(family: string): boolean; + /** + * @param {string} family + * @returns {boolean} + */ + getSafeName(family: string): boolean; + changed(): void; + /** + * @param {string} family + * @param {string} fallback + */ + addSystemFont(family: string, fallback: string): void; + /** + * @param {string} family + * @param {string} fallback + * @param {Asset} asset scratch-storage asset + */ + addCustomFont(family: string, fallback: string, asset: Asset): void; + /** + * @returns {Array<{system: boolean; name: string; family: string; data: Uint8Array | null; format: string | null}>} + */ + getFonts(): Array<{ + system: boolean; + name: string; + family: string; + data: Uint8Array | null; + format: string | null; + }>; + /** + * @param {number} index Corresponds to index from getFonts() + */ + deleteFont(index: number): void; + clear(): void; + updateRenderer(): void; + /** + * Get data to save in project.json and sb3 files. + */ + serializeJSON(): + | { + system: boolean; + family: string; + fallback: string; + }[] + | null; + /** + * @returns {Asset[]} list of scratch-storage assets + */ + serializeAssets(): Asset[]; + /** + * @param {unknown} json + * @param {JSZip} [zip] + * @param {boolean} [keepExisting] + * @returns {Promise} + */ + deserialize( + json: unknown, + zip?: JSZip, + keepExisting?: boolean + ): Promise; + } + namespace FontManager { + export { InternalFont }; + } + import EventEmitter = require("events"); + type InternalFont = { + /** + * True if the font is built in to the system + */ + system: boolean; + /** + * The font's name + */ + family: string; + /** + * Fallback font family list + */ + fallback: string; + /** + * scratch-storage asset if system: false + */ + asset?: Asset; + }; +} + +declare module "scratch-vm-dts/extension-support/argument-type" { + export = ArgumentType; + /** + * Block argument types + */ + type ArgumentType = string; + namespace ArgumentType { + let ANGLE: string; + let BOOLEAN: string; + let COLOR: string; + let NUMBER: string; + let STRING: string; + let MATRIX: string; + let NOTE: string; + let IMAGE: string; + let XIGUA_MATRIX: string; + let XIGUA_WHITE_BOARD_NOTE: string; + let CCW_HAT_PARAMETER: string; + let COSTUME: string; + let SOUND: string; + } +} + +declare module "scratch-vm-dts/extension-support/extension-metadata" { + export = ExtensionMetadata; + type BlockType = import("scratch-vm-dts/extension-support/block-type"); + type ArgumentType = import("scratch-vm-dts/extension-support/argument-type"); + class int extends Number { } + /** + * All the metadata needed to register an extension. + */ + type ExtensionMetadata = { + /** + * - a unique alphanumeric identifier for this extension. No special characters allowed. + */ + id: string; + /** + * - the human-readable name of this extension. + */ + name?: string | undefined; + /** + * - URI for an image to be placed on each block in this extension. Data URI ok. + */ + blockIconURI?: string | undefined; + /** + * - URI for an image to be placed on this extension's category menu item. Data URI ok. + */ + menuIconURI?: string | undefined; + /** + * - link to documentation content for this extension. + */ + docsURI?: string | undefined; + /** + * - the blocks provided by this extension, plus separators. + */ + blocks: Array; + /** + * - map of menu name to metadata for each of this extension's menus. + */ + menus?: ExtensionMenuMetadata; + }; + /** + * All the metadata needed to register an extension block. + */ + type ExtensionBlockMetadata = { + /** + * - a unique alphanumeric identifier for this block. No special characters allowed. + */ + opcode: string; + /** + * - the name of the function implementing this block. Can be shared by other blocks/opcodes. + */ + func?: string | undefined; + /** + * - the type of block (command, reporter, etc.) being described. + */ + blockType: BlockType; + /** + * - the text on the block, with [PLACEHOLDERS] for arguments. + */ + text: string; + /** + * - the human-readable tooltip for this block. + */ + tooltip?: string | undefined; + /** + * - true if this block should not appear in the block palette. + */ + hideFromPalette?: boolean | undefined; + /** + * - true if the block ends a stack - no blocks can be connected after it. + */ + isTerminal?: boolean | undefined; + /** + * - true if this block is a reporter but should not allow a monitor. + */ + disableMonitor?: boolean | undefined; + /** + * - if this block is a reporter, this is the scope/context for its value. + */ + reporterScope?: object; + /** + * - sets whether a hat block is edge-activated. + */ + isEdgeActivated?: boolean | undefined; + /** + * - sets whether a hat/event block should restart existing threads. + */ + shouldRestartExistingThreads?: boolean | undefined; + /** + * - for flow control blocks, the number of branches/substacks for this block. + */ + branchCount?: int; + /** + * - map of argument placeholder to metadata about each arg. + */ + arguments?: ExtensionArgumentMetadata; + }; + /** + * All the metadata needed to register an argument for an extension block. + */ + type ExtensionArgumentMetadata = { + /** + * - the type of the argument (number, string, etc.) + */ + type: ArgumentType; + /** + * - the default value of this argument. + */ + defaultValue?: any; + /** + * - the name of the menu to use for this argument, if any. + */ + menu?: string | undefined; + }; + /** + * All the metadata needed to register an extension drop-down menu. + */ + type ExtensionMenuMetadata = ExtensionDynamicMenu | ExtensionMenuItems; + /** + * The string name of a function which returns menu items. + */ + type ExtensionDynamicMenu = string; + /** + * Items in an extension menu. + */ + type ExtensionMenuItems = Array< + ExtensionMenuItemSimple | ExtensionMenuItemComplex + >; + /** + * A menu item for which the label and value are identical strings. + */ + type ExtensionMenuItemSimple = string; + /** + * A menu item for which the label and value can differ. + */ + type ExtensionMenuItemComplex = { + /** + * - the value of the block argument when this menu item is selected. + */ + value: any; + /** + * - the human-readable label of this menu item in the menu. + */ + text: string; + }; +} + +declare module "scratch-vm-dts/blocks/scratch3_core_example" { + export = Scratch3CoreExample; + type Runtime = import("scratch-vm-dts/engine/runtime"); + /** + * An example core block implemented using the extension spec. + * This is not loaded as part of the core blocks in the VM but it is provided + * and used as part of tests. + */ + class Scratch3CoreExample { + constructor(runtime: any); + /** + * The runtime instantiating this block package. + * @type {Runtime} + */ + runtime: Runtime; + /** + * @returns {object} metadata for this extension and its blocks. + */ + getInfo(): object; + /** + * Example opcode just returns the name of the stage target. + * @returns {string} The name of the first target in the project. + */ + exampleOpcode(): string; + exampleWithInlineImage(): void; + } +} + +declare module "scratch-vm-dts/extensions/scratch3_wedo2" { + export = Scratch3WeDo2Blocks; + class int extends Number { } + class array extends Array { } + /** + * Scratch 3.0 blocks to interact with a LEGO WeDo 2.0 peripheral. + */ + class Scratch3WeDo2Blocks { + /** + * @return {string} - the ID of this extension. + */ + static get EXTENSION_ID(): string; + /** + * @return {number} - the tilt sensor counts as "tilted" if its tilt angle meets or exceeds this threshold. + */ + static get TILT_THRESHOLD(): number; + /** + * Construct a set of WeDo 2.0 blocks. + * @param {Runtime} runtime - the Scratch 3.0 runtime. + */ + constructor(runtime: Runtime); + /** + * The Scratch 3.0 runtime. + * @type {Runtime} + */ + runtime: Runtime; + _peripheral: WeDo2; + /** + * @returns {object} metadata for this extension and its blocks. + */ + getInfo(): object; + /** + * Turn specified motor(s) on for a specified duration. + * @param {object} args - the block's arguments. + * @property {MotorID} MOTOR_ID - the motor(s) to activate. + * @property {int} DURATION - the amount of time to run the motors. + * @return {Promise} - a promise which will resolve at the end of the duration. + */ + motorOnFor(args: object): Promise; + /** + * Turn specified motor(s) on indefinitely. + * @param {object} args - the block's arguments. + * @property {MotorID} MOTOR_ID - the motor(s) to activate. + * @return {Promise} - a Promise that resolves after some delay. + */ + motorOn(args: object): Promise; + /** + * Turn specified motor(s) off. + * @param {object} args - the block's arguments. + * @property {MotorID} MOTOR_ID - the motor(s) to deactivate. + * @return {Promise} - a Promise that resolves after some delay. + */ + motorOff(args: object): Promise; + /** + * Turn specified motor(s) off. + * @param {object} args - the block's arguments. + * @property {MotorID} MOTOR_ID - the motor(s) to be affected. + * @property {int} POWER - the new power level for the motor(s). + * @return {Promise} - a Promise that resolves after some delay. + */ + startMotorPower(args: object): Promise; + /** + * Set the direction of rotation for specified motor(s). + * If the direction is 'reverse' the motor(s) will be reversed individually. + * @param {object} args - the block's arguments. + * @property {MotorID} MOTOR_ID - the motor(s) to be affected. + * @property {MotorDirection} MOTOR_DIRECTION - the new direction for the motor(s). + * @return {Promise} - a Promise that resolves after some delay. + */ + setMotorDirection(args: object): Promise; + /** + * Set the LED's hue. + * @param {object} args - the block's arguments. + * @property {number} HUE - the hue to set, in the range [0,100]. + * @return {Promise} - a Promise that resolves after some delay. + */ + setLightHue(args: object): Promise; + /** + * Make the WeDo 2.0 peripheral play a MIDI note for the specified duration. + * @param {object} args - the block's arguments. + * @property {number} NOTE - the MIDI note to play. + * @property {number} DURATION - the duration of the note, in seconds. + * @return {Promise} - a promise which will resolve at the end of the duration. + */ + playNoteFor(args: object): Promise; + /** + * Compare the distance sensor's value to a reference. + * @param {object} args - the block's arguments. + * @property {string} OP - the comparison operation: '<' or '>'. + * @property {number} REFERENCE - the value to compare against. + * @return {boolean} - the result of the comparison, or false on error. + */ + whenDistance(args: object): boolean; + /** + * Test whether the tilt sensor is currently tilted. + * @param {object} args - the block's arguments. + * @property {TiltDirection} TILT_DIRECTION_ANY - the tilt direction to test (up, down, left, right, or any). + * @return {boolean} - true if the tilt sensor is tilted past a threshold in the specified direction. + */ + whenTilted(args: object): boolean; + /** + * @return {number} - the distance sensor's value, scaled to the [0,100] range. + */ + getDistance(): number; + /** + * Test whether the tilt sensor is currently tilted. + * @param {object} args - the block's arguments. + * @property {TiltDirection} TILT_DIRECTION_ANY - the tilt direction to test (up, down, left, right, or any). + * @return {boolean} - true if the tilt sensor is tilted past a threshold in the specified direction. + */ + isTilted(args: object): boolean; + /** + * @param {object} args - the block's arguments. + * @property {TiltDirection} TILT_DIRECTION - the direction (up, down, left, right) to check. + * @return {number} - the tilt sensor's angle in the specified direction. + * Note that getTiltAngle(up) = -getTiltAngle(down) and getTiltAngle(left) = -getTiltAngle(right). + */ + getTiltAngle(args: object): number; + } + /** + * Manage communication with a WeDo 2.0 peripheral over a Bluetooth Low Energy client socket. + */ + class WeDo2 { + constructor(runtime: any, extensionId: any); + /** + * The id of the extension this peripheral belongs to. + */ + _extensionId: any; + /** + * Reset all the state and timeout/interval ids. + */ + reset(): void; + /** + * Check the battery level on the WeDo 2.0. If the WeDo 2.0 has disconnected + * for some reason, the BLE socket will get an error back and automatically + * close the socket. + */ + _checkBatteryLevel(): void; + /** + * @return {number} - the latest value received for the tilt sensor's tilt about the X axis. + */ + get tiltX(): number; + /** + * @return {number} - the latest value received for the tilt sensor's tilt about the Y axis. + */ + get tiltY(): number; + /** + * @return {number} - the latest value received from the distance sensor. + */ + get distance(): number; + /** + * Access a particular motor on this peripheral. + * @param {int} index - the zero-based index of the desired motor. + * @return {WeDo2Motor} - the WeDo2Motor instance, if any, at that index. + */ + motor(index: int): WeDo2Motor; + /** + * Stop all the motors that are currently running. + */ + stopAllMotors(): void; + /** + * Set the WeDo 2.0 peripheral's LED to a specific color. + * @param {int} inputRGB - a 24-bit RGB color in 0xRRGGBB format. + * @return {Promise} - a promise of the completion of the set led send operation. + */ + setLED(inputRGB: int): Promise; + /** + * Sets the input mode of the LED to RGB. + * @return {Promise} - a promise returned by the send operation. + */ + setLEDMode(): Promise; + /** + * Switch off the LED on the WeDo 2.0. + * @return {Promise} - a promise of the completion of the stop led send operation. + */ + stopLED(): Promise; + /** + * Play a tone from the WeDo 2.0 peripheral for a specific amount of time. + * @param {int} tone - the pitch of the tone, in Hz. + * @param {int} milliseconds - the duration of the note, in milliseconds. + * @return {Promise} - a promise of the completion of the play tone send operation. + */ + playTone(tone: int, milliseconds: int): Promise; + /** + * Stop the tone playing from the WeDo 2.0 peripheral, if any. + * @return {Promise} - a promise that the command sent. + */ + stopTone(): Promise; + /** + * Stop the tone playing and motors on the WeDo 2.0 peripheral. + */ + stopAll(): void; + /** + * Called by the runtime when user wants to scan for a WeDo 2.0 peripheral. + */ + scan(): void; + /** + * Called by the runtime when user wants to connect to a certain WeDo 2.0 peripheral. + * @param {number} id - the id of the peripheral to connect to. + */ + connect(id: number): void; + /** + * Disconnects from the current BLE socket. + */ + disconnect(): void; + /** + * Called by the runtime to detect whether the WeDo 2.0 peripheral is connected. + * @return {boolean} - the connected state. + */ + isConnected(): boolean; + /** + * Write a message to the WeDo 2.0 peripheral BLE socket. + * @param {number} uuid - the UUID of the characteristic to write to + * @param {Array} message - the message to write. + * @param {boolean} [useLimiter=true] - if true, use the rate limiter + * @return {Promise} - a promise result of the write operation + */ + send(uuid: number, message: any[], useLimiter?: boolean): Promise; + /** + * Generate a WeDo 2.0 'Output Command' in the byte array format + * (CONNECT ID, COMMAND ID, NUMBER OF BYTES, VALUES ...). + * + * This sends a command to the WeDo 2.0 to actuate the specified outputs. + * + * @param {number} connectID - the port (Connect ID) to send a command to. + * @param {number} commandID - the id of the byte command. + * @param {array} values - the list of values to write to the command. + * @return {array} - a generated output command. + */ + generateOutputCommand( + connectID: number, + commandID: number, + values?: array + ): array; + /** + * Generate a WeDo 2.0 'Input Command' in the byte array format + * (COMMAND ID, COMMAND TYPE, CONNECT ID, TYPE ID, MODE, DELTA INTERVAL (4 BYTES), + * UNIT, NOTIFICATIONS ENABLED). + * + * This sends a command to the WeDo 2.0 that sets that input format + * of the specified inputs and sets value change notifications. + * + * @param {number} connectID - the port (Connect ID) to send a command to. + * @param {number} type - the type of input sensor. + * @param {number} mode - the mode of the input sensor. + * @param {number} delta - the delta change needed to trigger notification. + * @param {array} units - the unit of the input sensor value. + * @param {boolean} enableNotifications - whether to enable notifications. + * @return {array} - a generated input command. + */ + generateInputCommand( + connectID: number, + type: number, + mode: number, + delta: number, + units: array, + enableNotifications: boolean + ): array; + } + /** + * Manage power, direction, and timers for one WeDo 2.0 motor. + */ + class WeDo2Motor { + /** + * Construct a WeDo 2.0 Motor instance. + * @param {WeDo2} parent - the WeDo 2.0 peripheral which owns this motor. + * @param {int} index - the zero-based index of this motor on its parent peripheral. + */ + constructor(parent: WeDo2, index: int); + /** + * Start active braking on this motor. After a short time, the motor will turn off. + */ + startBraking(): void; + /** + * Turn this motor off. + * @param {boolean} [useLimiter=true] - if true, use the rate limiter + */ + turnOff(useLimiter?: boolean): void; + /** + * @param {int} value - this motor's new direction: 1 for "this way" or -1 for "that way" + */ + set direction(value: int); + /** + * @return {int} - this motor's current direction: 1 for "this way" or -1 for "that way" + */ + get direction(): int; + /** + * @param {int} value - this motor's new power level, in the range [0,100]. + */ + set power(value: int); + /** + * @return {int} - this motor's current power level, in the range [0,100]. + */ + get power(): int; + /** + * @return {boolean} - true if this motor is currently moving, false if this motor is off or braking. + */ + get isOn(): boolean; + /** + * @return {boolean} - time, in milliseconds, of when the pending timeout began. + */ + get pendingTimeoutStartTime(): boolean; + /** + * @return {boolean} - delay, in milliseconds, of the pending timeout. + */ + get pendingTimeoutDelay(): boolean; + /** + * Turn this motor on indefinitely. + */ + turnOn(): void; + /** + * Turn this motor on for a specific duration. + * @param {number} milliseconds - run the motor for this long. + */ + turnOnFor(milliseconds: number): void; + } +} + +declare module "scratch-vm-dts/extensions/scratch3_microbit" { + export = Scratch3MicroBitBlocks; + class array extends Array { } + /** + * Scratch 3.0 blocks to interact with a MicroBit peripheral. + */ + class Scratch3MicroBitBlocks { + /** + * @return {string} - the name of this extension. + */ + static get EXTENSION_NAME(): string; + /** + * @return {string} - the ID of this extension. + */ + static get EXTENSION_ID(): string; + /** + * @return {number} - the tilt sensor counts as "tilted" if its tilt angle meets or exceeds this threshold. + */ + static get TILT_THRESHOLD(): number; + /** + * Construct a set of MicroBit blocks. + * @param {Runtime} runtime - the Scratch 3.0 runtime. + */ + constructor(runtime: Runtime); + /** + * @return {array} - text and values for each buttons menu element + */ + get BUTTONS_MENU(): array; + /** + * @return {array} - text and values for each gestures menu element + */ + get GESTURES_MENU(): array; + /** + * @return {array} - text and values for each pin state menu element + */ + get PIN_STATE_MENU(): array; + /** + * @return {array} - text and values for each tilt direction menu element + */ + get TILT_DIRECTION_MENU(): array; + /** + * @return {array} - text and values for each tilt direction (plus "any") menu element + */ + get TILT_DIRECTION_ANY_MENU(): array; + /** + * The Scratch 3.0 runtime. + * @type {Runtime} + */ + runtime: Runtime; + _peripheral: MicroBit; + /** + * @returns {object} metadata for this extension and its blocks. + */ + getInfo(): object; + /** + * Test whether the A or B button is pressed + * @param {object} args - the block's arguments. + * @return {boolean} - true if the button is pressed. + */ + whenButtonPressed(args: object): boolean; + /** + * Test whether the A or B button is pressed + * @param {object} args - the block's arguments. + * @return {boolean} - true if the button is pressed. + */ + isButtonPressed(args: object): boolean; + /** + * Test whether the micro:bit is moving + * @param {object} args - the block's arguments. + * @return {boolean} - true if the micro:bit is moving. + */ + whenGesture(args: object): boolean; + /** + * Display a predefined symbol on the 5x5 LED matrix. + * @param {object} args - the block's arguments. + * @return {Promise} - a Promise that resolves after a tick. + */ + displaySymbol(args: object): Promise; + /** + * Display text on the 5x5 LED matrix. + * @param {object} args - the block's arguments. + * @return {Promise} - a Promise that resolves after the text is done printing. + * Note the limit is 19 characters + * The print time is calculated by multiplying the number of horizontal pixels + * by the default scroll delay of 120ms. + * The number of horizontal pixels = 6px for each character in the string, + * 1px before the string, and 5px after the string. + */ + displayText(args: object): Promise; + /** + * Turn all 5x5 matrix LEDs off. + * @return {Promise} - a Promise that resolves after a tick. + */ + displayClear(): Promise; + /** + * Test whether the tilt sensor is currently tilted. + * @param {object} args - the block's arguments. + * @property {TiltDirection} DIRECTION - the tilt direction to test (front, back, left, right, or any). + * @return {boolean} - true if the tilt sensor is tilted past a threshold in the specified direction. + */ + whenTilted(args: object): boolean; + /** + * Test whether the tilt sensor is currently tilted. + * @param {object} args - the block's arguments. + * @property {TiltDirection} DIRECTION - the tilt direction to test (front, back, left, right, or any). + * @return {boolean} - true if the tilt sensor is tilted past a threshold in the specified direction. + */ + isTilted(args: object): boolean; + /** + * @param {object} args - the block's arguments. + * @property {TiltDirection} DIRECTION - the direction (front, back, left, right) to check. + * @return {number} - the tilt sensor's angle in the specified direction. + * Note that getTiltAngle(front) = -getTiltAngle(back) and getTiltAngle(left) = -getTiltAngle(right). + */ + getTiltAngle(args: object): number; + } + /** + * Manage communication with a MicroBit peripheral over a Scrath Link client socket. + */ + class MicroBit { + /** + * Construct a MicroBit communication object. + * @param {Runtime} runtime - the Scratch 3.0 runtime + * @param {string} extensionId - the id of the extension + */ + constructor(runtime: Runtime, extensionId: string); + /** + * The id of the extension this peripheral belongs to. + */ + _extensionId: string; + /** + * ID for a timeout which is used to clear the busy flag if it has been + * true for a long time. + */ + _busyTimeoutID: number | null; + /** + * Reset all the state and timeout/interval ids. + */ + reset(): void; + /** + * @param {string} text - the text to display. + * @return {Promise} - a Promise that resolves when writing to peripheral. + */ + displayText(text: string): Promise; + /** + * @param {Uint8Array} matrix - the matrix to display. + * @return {Promise} - a Promise that resolves when writing to peripheral. + */ + displayMatrix(matrix: Uint8Array): Promise; + /** + * @return {number} - the latest value received for the tilt sensor's tilt about the X axis. + */ + get tiltX(): number; + /** + * @return {number} - the latest value received for the tilt sensor's tilt about the Y axis. + */ + get tiltY(): number; + /** + * @return {boolean} - the latest value received for the A button. + */ + get buttonA(): boolean; + /** + * @return {boolean} - the latest value received for the B button. + */ + get buttonB(): boolean; + /** + * @return {number} - the latest value received for the motion gesture states. + */ + get gestureState(): number; + /** + * @return {Uint8Array} - the current state of the 5x5 LED matrix. + */ + get ledMatrixState(): Uint8Array; + /** + * Called by the runtime when user wants to scan for a peripheral. + */ + scan(): void; + /** + * Called by the runtime when user wants to connect to a certain peripheral. + * @param {number} id - the id of the peripheral to connect to. + */ + connect(id: number): void; + /** + * Disconnect from the micro:bit. + */ + disconnect(): void; + /** + * Return true if connected to the micro:bit. + * @return {boolean} - whether the micro:bit is connected. + */ + isConnected(): boolean; + /** + * Send a message to the peripheral BLE socket. + * @param {number} command - the BLE command hex. + * @param {Uint8Array} message - the message to write + */ + send(command: number, message: Uint8Array): void; + } +} + +declare module "scratch-vm-dts/extensions/scratch3_text2speech" { + export = Scratch3Text2SpeechBlocks; + /** + * Class for the text2speech blocks. + * @constructor + */ + class array extends Array { } + interface Text2SpeechState { + voiceId: string; + } + interface SoundPlayer { + stop(): void; + connect(chain: any): void; + play(): void; + } + class Scratch3Text2SpeechBlocks { + /** + * The key to load & store a target's text2speech state. + * @return {string} The key. + */ + static get STATE_KEY(): string; + /** + * The default state, to be used when a target has no existing state. + * @type {Text2SpeechState} + */ + static get DEFAULT_TEXT2SPEECH_STATE(): Text2SpeechState; + constructor(runtime: any); + /** + * The runtime instantiating this block package. + * @type {Runtime} + */ + runtime: Runtime; + /** + * Map of soundPlayers by sound id. + * @type {Map} + */ + _soundPlayers: Map; + /** + * Stop all currently playing speech sounds. + */ + _stopAllSpeech(): void; + /** + * A list of all Scratch locales that are supported by the extension. + * @type {Array} + */ + _supportedLocales: any[]; + thirdPartApiKey: string; + host: any; + isCCWService: boolean | undefined; + /** + * An object with info for each voice. + */ + get VOICE_INFO(): { + ALTO: { + name: string; + gender: string; + playbackRate: number; + }; + TENOR: { + name: string; + gender: string; + playbackRate: number; + }; + SQUEAK: { + name: string; + gender: string; + playbackRate: number; + }; + GIANT: { + name: string; + gender: string; + playbackRate: number; + }; + KITTEN: { + name: string; + gender: string; + playbackRate: number; + }; + }; + /** + * An object with information for each language. + * + * A note on the different sets of locales referred to in this extension: + * + * SCRATCH LOCALE + * Set by the editor, and used to store the language state in the project. + * Listed in l10n: https://github.com/scratchfoundation/scratch-l10n/blob/master/src/supported-locales.js + * SUPPORTED LOCALE + * A Scratch locale that has a corresponding extension locale. + * EXTENSION LOCALE + * A locale corresponding to one of the available spoken languages + * in the extension. There can be multiple supported locales for a single + * extension locale. For example, for both written versions of chinese, + * zh-cn and zh-tw, we use a single spoken language (Mandarin). So there + * are two supported locales, with a single extension locale. + * SPEECH SYNTH LOCALE + * A different locale code system, used by our speech synthesis service. + * Each extension locale has a speech synth locale. + */ + get LANGUAGE_INFO(): { + ar: { + name: string; + locales: string[]; + speechSynthLocale: string; + singleGender: boolean; + }; + "zh-cn": { + name: string; + locales: string[]; + speechSynthLocale: string; + singleGender: boolean; + }; + en: { + name: string; + locales: string[]; + speechSynthLocale: string; + }; + fr: { + name: string; + locales: string[]; + speechSynthLocale: string; + }; + de: { + name: string; + locales: string[]; + speechSynthLocale: string; + }; + ja: { + name: string; + locales: string[]; + speechSynthLocale: string; + }; + ko: { + name: string; + locales: string[]; + speechSynthLocale: string; + singleGender: boolean; + }; + pt: { + name: string; + locales: string[]; + speechSynthLocale: string; + }; + ru: { + name: string; + locales: string[]; + speechSynthLocale: string; + }; + es: { + name: string; + locales: string[]; + speechSynthLocale: string; + }; + }; + /** + * A default language to use for speech synthesis. + * @type {string} + */ + get DEFAULT_LANGUAGE(): string; + /** + * @returns {object} metadata for this extension and its blocks. + */ + getInfo(): object; + /** + * Get the language code currently set in the editor, or fall back to the + * browser locale. + * @return {string} a Scratch locale code. + */ + getEditorLanguage(): string; + /** + * Get the language code currently set for the extension. + * @returns {string} a Scratch locale code. + */ + getCurrentLanguage(): string; + /** + * Set the language code for the extension. + * It is stored in the stage so it can be saved and loaded with the project. + * @param {string} locale a locale code. + */ + setCurrentLanguage(locale: string): void; + /** + * Get the extension locale for a supported locale, or null. + * @param {string} locale a locale code. + * @returns {?string} a locale supported by the extension. + */ + _getExtensionLocaleForSupportedLocale(locale: string): string | null; + /** + * Get the locale code used by the speech synthesis server corresponding to + * the current language code set for the extension. + * @returns {string} a speech synthesis locale. + */ + _getSpeechSynthLocale(): string; + /** + * Get an array of the locales supported by this extension. + * @returns {Array} An array of locale strings. + */ + _getSupportedLocales(): any[]; + /** + * Check if a Scratch language code is in the list of supported languages for the + * speech synthesis service. + * @param {string} languageCode the language code to check. + * @returns {boolean} true if the language code is supported. + */ + isSupportedLanguage(languageCode: string): boolean; + /** + * Get the menu of voices for the "set voice" block. + * @return {array} the text and value for each menu item. + */ + getVoiceMenu(): array; + /** + * Get the localized menu of languages for the "set language" block. + * For each language: + * if there is a custom translated spoken language name, use that; + * otherwise use the translation in the languageNames menuMap; + * otherwise fall back to the untranslated name in LANGUAGE_INFO. + * @return {array} the text and value for each menu item. + */ + getLanguageMenu(): array; + /** + * Set the voice for speech synthesis for this sprite. + * @param {object} args Block arguments + * @param {object} util Utility object provided by the runtime. + */ + setVoice(args: object, util: object): void; + /** + * Set the language for speech synthesis. + * @param {object} args Block arguments + */ + setLanguage(args: object): void; + /** + * Convert the provided text into a sound file and then play the file. + * @param {object} args Block arguments + * @param {object} util Utility object provided by the runtime. + * @return {Promise} A promise that resolves after playing the sound + */ + speakAndWait(args: object, util: object): Promise; + runWithCCWAPI(args: any, util: any): Promise; + runWithScratchAPI(args: any, util: any): Promise; + } +} + +declare module "scratch-vm-dts/extensions/scratch3_translate" { + export = Scratch3TranslateBlocks; + /** + * Class for the translate block in Scratch 3.0. + * @constructor + */ + class Scratch3TranslateBlocks { + /** + * The key to load & store a target's translate state. + * @return {string} The key. + */ + static get STATE_KEY(): string; + constructor(runtime: any); + thirdPartApiKey: string; + host: any; + isCCWService: boolean | undefined; + /** + * @returns {object} metadata for this extension and its blocks. + */ + getInfo(): object; + _getXiguaSupportedLanguages(code: any): { [key: string]: string }; + /** + * Get the human readable language value for the reporter block. + * @return {string} the language name of the project viewer. + */ + getViewerLanguage(): string; + /** + * Get the viewer's language code. + * @return {string} the language code. + */ + getViewerLanguageCode(): string; + /** + * Get a language code from a block argument. The arg can be a language code + * or a language name, written in any language. + * @param {object} arg A block argument. + * @return {string} A language code. + */ + getLanguageCodeFromArg(arg: object): string; + /** + * Translates the text in the translate block to the language specified in the menu. + * @param {object} args - the block arguments. + * @return {Promise} - a promise that resolves after the response from the translate server. + */ + getTranslate(args: object): Promise; + runWithCCWAPI(args: any, lang: any): Promise; + runWithScratchAPI(args: any, lang: any): Promise; + } +} + +declare module "scratch-vm-dts/extensions/scratch3_video_sensing" { + export = Scratch3VideoSensingBlocks; + interface MotionState { + motionFrameNumber: number; + motionAmount: number; + motionDirection: number; + } + type Target = import("scratch-vm-dts/engine/target"); + type BlockUtility = import("scratch-vm-dts/engine/block-utility"); + /** + * Class for the motion-related blocks in Scratch 3.0 + * @param {Runtime} runtime - the runtime instantiating this block package. + * @constructor + */ + class Scratch3VideoSensingBlocks { + /** + * After analyzing a frame the amount of milliseconds until another frame + * is analyzed. + * @type {number} + */ + static get INTERVAL(): number; + /** + * Dimensions the video stream is analyzed at after its rendered to the + * sample canvas. + * @type {Array.} + */ + static get DIMENSIONS(): Array; + /** + * The key to load & store a target's motion-related state. + * @type {string} + */ + static get STATE_KEY(): string; + /** + * The default motion-related state, to be used when a target has no existing motion state. + * @type {MotionState} + */ + static get DEFAULT_MOTION_STATE(): MotionState; + static get SensingAttribute(): { + /** The amount of motion. */ + MOTION: string; + /** The direction of the motion. */ + DIRECTION: string; + }; + static get SensingSubject(): { + /** The sensor traits of the whole stage. */ + STAGE: string; + /** The senosr traits of the area overlapped by this sprite. */ + SPRITE: string; + }; + /** + * States the video sensing activity can be set to. + * @readonly + * @enum {string} + */ + static get VideoState(): { + /** Video turned off. */ + OFF: string; + /** Video turned on with default y axis mirroring. */ + ON: string; + /** Video turned on without default y axis mirroring. */ + ON_FLIPPED: string; + }; + constructor(runtime: any); + /** + * The runtime instantiating this block package. + * @type {Runtime} + */ + runtime: Runtime; + /** + * The motion detection algoritm used to power the motion amount and + * direction values. + * @type {VideoMotion} + */ + detect: VideoMotion; + /** + * The last millisecond epoch timestamp that the video stream was + * analyzed. + * @type {number} + */ + _lastUpdate: number; + /** + * A flag to determine if this extension has been installed in a project. + * It is set to false the first time getInfo is run. + * @type {boolean} + */ + firstInstall: boolean; + set globalVideoTransparency(transparency: number); + /** + * The transparency setting of the video preview stored in a value + * accessible by any object connected to the virtual machine. + * @type {number} + */ + get globalVideoTransparency(): number; + set globalVideoState(state: string); + /** + * The video state of the video preview stored in a value accessible by any + * object connected to the virtual machine. + * @type {string} + */ + get globalVideoState(): string; + /** + * Get the latest values for video transparency and state, + * and set the video device to use them. + */ + updateVideoDisplay(): void; + /** + * Reset the extension's data motion detection data. This will clear out + * for example old frames, so the first analyzed frame will not be compared + * against a frame from before reset was called. + */ + reset(): void; + _loopInterval: NodeJS.Timeout | undefined; + /** + * Stop the video sampling loop. Only used for testing. + */ + _stopLoop(): void; + /** + * An array of choices of whether a reporter should return the frame's + * motion amount or direction. + * @type {object[]} + * @param {string} name - the translatable name to display in sensor + * attribute menu + * @param {string} value - the serializable value of the attribute + */ + get ATTRIBUTE_INFO(): object[]; + /** + * An array of info about the subject choices. + * @type {object[]} + * @param {string} name - the translatable name to display in the subject menu + * @param {string} value - the serializable value of the subject + */ + get SUBJECT_INFO(): object[]; + /** + * An array of info on video state options for the "turn video [STATE]" block. + * @type {object[]} + * @param {string} name - the translatable name to display in the video state menu + * @param {string} value - the serializable value stored in the block + */ + get VIDEO_STATE_INFO(): object[]; + /** + * @returns {object} metadata for this extension and its blocks. + */ + getInfo(): object; + /** + * Analyze a part of the frame that a target overlaps. + * @param {Target} target - a target to determine where to analyze + * @returns {MotionState} the motion state for the given target + */ + _analyzeLocalMotion(target: Target): MotionState; + /** + * A scratch reporter block handle that analyzes the last two frames and + * depending on the arguments, returns the motion or direction for the + * whole stage or just the target sprite. + * @param {object} args - the block arguments + * @param {BlockUtility} util - the block utility + * @returns {number} the motion amount or direction of the stage or sprite + */ + videoOn(args: object, util: BlockUtility): number; + /** + * A scratch hat block edge handle that analyzes the last two frames where + * the target sprite overlaps and if it has more motion than the given + * reference value. + * @param {object} args - the block arguments + * @param {BlockUtility} util - the block utility + * @returns {boolean} true if the sprite overlaps more motion than the + * reference + */ + whenMotionGreaterThan(args: object, util: BlockUtility): boolean; + /** + * A scratch command block handle that configures the video state from + * passed arguments. + * @param {object} args - the block arguments + * @param {VideoState} args.VIDEO_STATE - the video state to set the device to + */ + videoToggle(args: { VIDEO_STATE: VideoState }): void; + /** + * A scratch command block handle that configures the video preview's + * transparency from passed arguments. + * @param {object} args - the block arguments + * @param {number} args.TRANSPARENCY - the transparency to set the video + * preview to + */ + setVideoTransparency(args: { TRANSPARENCY: number }): void; + } + import Runtime = require("scratch-vm-dts/engine/runtime"); + import VideoMotion = require("scratch-vm-dts/extensions/scratch3_video_sensing/library"); + /** + * States the video sensing activity can be set to. + */ + type VideoState = string; + namespace VideoState { + let OFF: string; + let ON: string; + let ON_FLIPPED: string; + } +} + +declare module "scratch-vm-dts/extensions/scratch3_ev3" { + export = Scratch3Ev3Blocks; + class int extends Number { } + class array extends Array { } + class Scratch3Ev3Blocks { + /** + * The ID of the extension. + * @return {string} the id + */ + static get EXTENSION_ID(): string; + /** + * Creates a new instance of the EV3 extension. + * @param {object} runtime VM runtime + * @constructor + */ + constructor(runtime: object); + /** + * The Scratch 3.0 runtime. + * @type {Runtime} + */ + runtime: Runtime; + _peripheral: EV3; + _playNoteForPicker(note: any, category: any): void; + /** + * Define the EV3 extension. + * @return {object} Extension description. + */ + getInfo(): object; + motorTurnClockwise(args: any): Promise; + motorTurnCounterClockwise(args: any): Promise; + motorSetPower(args: any): void; + getMotorPosition(args: any): number | undefined; + whenButtonPressed(args: any): boolean | undefined; + whenDistanceLessThan(args: any): boolean; + whenBrightnessLessThan(args: any): boolean; + buttonPressed(args: any): boolean | undefined; + getDistance(): any; + getBrightness(): any; + beep(args: any): Promise | undefined; + } + class EV3 { + constructor(runtime: any, extensionId: any); + /** + * The id of the extension this peripheral belongs to. + */ + _extensionId: any; + /** + * Reset all the state and timeout/interval ids. + */ + reset(): void; + get distance(): any; + get brightness(): any; + /** + * Access a particular motor on this peripheral. + * @param {int} index - the zero-based index of the desired motor. + * @return {EV3Motor} - the EV3Motor instance, if any, at that index. + */ + motor(index: int): EV3Motor; + isButtonPressed(port: any): boolean; + beep(freq: any, time: any): void; + stopAll(): void; + stopSound(): void; + stopAllMotors(): void; + /** + * Called by the runtime when user wants to scan for an EV3 peripheral. + */ + scan(): void; + /** + * Called by the runtime when user wants to connect to a certain EV3 peripheral. + * @param {number} id - the id of the peripheral to connect to. + */ + connect(id: number): void; + /** + * Called by the runtime when user wants to disconnect from the EV3 peripheral. + */ + disconnect(): void; + /** + * Called by the runtime to detect whether the EV3 peripheral is connected. + * @return {boolean} - the connected state. + */ + isConnected(): boolean; + /** + * Send a message to the peripheral BT socket. + * @param {Uint8Array} message - the message to send. + * @param {boolean} [useLimiter=true] - if true, use the rate limiter + * @return {Promise} - a promise result of the send operation. + */ + send(message: Uint8Array, useLimiter?: boolean): Promise; + /** + * Genrates direct commands that are sent to the EV3 as a single or compounded byte arrays. + * See 'EV3 Communication Developer Kit', section 4, page 24 at + * https://education.lego.com/en-us/support/mindstorms-ev3/developer-kits. + * + * Direct commands are one of two types: + * DIRECT_COMMAND_NO_REPLY = a direct command where no reply is expected + * DIRECT_COMMAND_REPLY = a direct command where a reply is expected, and the + * number and length of returned values needs to be specified. + * + * The direct command byte array sent takes the following format: + * Byte 0 - 1: Command size, Little Endian. Command size not including these 2 bytes + * Byte 2 - 3: Message counter, Little Endian. Forth running counter + * Byte 4: Command type. Either DIRECT_COMMAND_REPLY or DIRECT_COMMAND_NO_REPLY + * Byte 5 - 6: Reservation (allocation) of global and local variables using a compressed format + * (globals reserved in byte 5 and the 2 lsb of byte 6, locals reserved in the upper + * 6 bits of byte 6) – see documentation for more details. + * Byte 7 - n: Byte codes as a single command or compound commands (I.e. more commands composed + * as a small program) + * + * @param {number} type - the direct command type. + * @param {string} byteCommands - a compound array of EV3 Opcode + arguments. + * @param {number} allocation - the allocation of global and local vars needed for replies. + * @return {array} - generated complete command byte array, with header and compounded commands. + */ + generateCommand( + type: number, + byteCommands: string, + allocation?: number + ): array; + _updateDevices: boolean | undefined; + } + /** + * Manage power, direction, and timers for one EV3 motor. + */ + class EV3Motor { + /** + * Construct a EV3 Motor instance, which could be of type 'largeMotor' or + * 'mediumMotor'. + * + * @param {EV3} parent - the EV3 peripheral which owns this motor. + * @param {int} index - the zero-based index of this motor on its parent peripheral. + * @param {string} type - the type of motor (i.e. 'largeMotor' or 'mediumMotor'). + */ + constructor(parent: EV3, index: int, type: string); + /** + * @param {string} value - this motor's new type: 'largeMotor' or 'mediumMotor' + */ + set type(value: string); + /** + * @return {string} - this motor's type: 'largeMotor' or 'mediumMotor' + */ + get type(): string; + /** + * @param {int} value - this motor's new direction: 1 for "clockwise" or -1 for "counterclockwise" + */ + set direction(value: int); + /** + * @return {int} - this motor's current direction: 1 for "clockwise" or -1 for "counterclockwise" + */ + get direction(): int; + /** + * @param {int} value - this motor's new power level, in the range [0,100]. + */ + set power(value: int); + /** + * @return {int} - this motor's current power level, in the range [0,100]. + */ + get power(): int; + /** + * @param {int} array - this motor's new position, in the range [0,360]. + */ + set position(array: int); + /** + * @return {int} - this motor's current position, in the range [-inf,inf]. + */ + get position(): int; + /** + * Turn this motor on for a specific duration. + * Found in the 'EV3 Firmware Developer Kit', page 56, at + * https://education.lego.com/en-us/support/mindstorms-ev3/developer-kits. + * + * Opcode arguments: + * (Data8) LAYER – Specify chain layer number [0 - 3] + * (Data8) NOS – Output bit field [0x00 – 0x0F] + * (Data8) SPEED – Power level, [-100 – 100] + * (Data32) STEP1 – Time in milliseconds for ramp up + * (Data32) STEP2 – Time in milliseconds for continues run + * (Data32) STEP3 – Time in milliseconds for ramp down + * (Data8) BRAKE - Specify break level [0: Float, 1: Break] + * + * @param {number} milliseconds - run the motor for this long. + */ + turnOnFor(milliseconds: number): void; + /** + * Set the motor to coast after a specified amount of time. + * @param {number} time - the time in milliseconds. + */ + coastAfter(time: number): void; + /** + * Set the motor to coast. + */ + coast(): void; + /** + * Generate motor run values for a given input. + * @param {number} run - run input. + * @return {array} - run values as a byte array. + */ + _runValues(run: number): array; + /** + * Return a port value for the EV3 that is in the format for 'output bit field' + * as 1/2/4/8, generally needed for motor ports, instead of the typical 0/1/2/3. + * The documentation in the 'EV3 Firmware Developer Kit' for motor port arguments + * is sometimes mistaken, but we believe motor ports are mostly addressed this way. + * @param {number} port - the port number to convert to an 'output bit field'. + * @return {number} - the converted port number. + */ + _portMask(port: number): number; + } +} + +declare module "scratch-vm-dts/extensions/scratch3_makeymakey" { + export = Scratch3MakeyMakeyBlocks; + /** + * Class for the makey makey blocks in Scratch 3.0 + * @constructor + */ + class Scratch3MakeyMakeyBlocks { + constructor(runtime: any); + /** + * The runtime instantiating this block package. + * @type {Runtime} + */ + runtime: Runtime; + /** + * A toggle that alternates true and false each frame, so that an + * edge-triggered hat can trigger on every other frame. + * @type {boolean} + */ + frameToggle: boolean; + keyPressed(key: any): void; + /** + * Clear the key press buffer. + */ + _clearkeyPressBuffer(): void; + sequences: {}; + keyPressBuffer: any[]; + get KEY_TEXT_SHORT(): { + SPACE: string; + LEFT: string; + UP: string; + RIGHT: string; + DOWN: string; + }; + get DEFAULT_SEQUENCES(): string[]; + /** + * @returns {object} metadata for this extension and its blocks. + */ + getInfo(): object; + buildSequenceMenu(sequencesArray: any): any; + getMenuItemForSequenceString(sequenceString: any): { + text: any; + value: any; + }; + whenMakeyKeyPressed(args: any, util: any): any; + addSequence(sequenceString: any, sequenceArray: any): void; + whenCodePressed(args: any): any; + } +} + +declare module "scratch-vm-dts/extensions/scratch3_boost" { + export = Scratch3BoostBlocks; + class int extends Number { } + class array extends Array { } + /** + * Scratch 3.0 blocks to interact with a LEGO Boost peripheral. + */ + class Scratch3BoostBlocks { + /** + * @return {string} - the ID of this extension. + */ + static get EXTENSION_ID(): string; + /** + * @return {number} - the tilt sensor counts as "tilted" if its tilt angle meets or exceeds this threshold. + */ + static get TILT_THRESHOLD(): number; + /** + * Construct a set of Boost blocks. + * @param {Runtime} runtime - the Scratch 3.0 runtime. + */ + constructor(runtime: Runtime); + /** + * The Scratch 3.0 runtime. + * @type {Runtime} + */ + runtime: Runtime; + _peripheral: Boost; + /** + * @returns {object} metadata for this extension and its blocks. + */ + getInfo(): object; + /** + * Turn specified motor(s) on for a specified duration. + * @param {object} args - the block's arguments. + * @property {MotorID} MOTOR_ID - the motor(s) to activate. + * @property {int} DURATION - the amount of time to run the motors. + * @return {Promise} - a promise which will resolve at the end of the duration. + */ + motorOnFor(args: object): Promise; + /** + * Turn specified motor(s) on for a specified rotation in full rotations. + * @param {object} args - the block's arguments. + * @property {MotorID} MOTOR_ID - the motor(s) to activate. + * @property {int} ROTATION - the amount of full rotations to turn the motors. + * @return {Promise} - a promise which will resolve at the end of the duration. + */ + motorOnForRotation(args: object): Promise; + /** + * Turn specified motor(s) on indefinitely. + * @param {object} args - the block's arguments. + * @property {MotorID} MOTOR_ID - the motor(s) to activate. + * @return {Promise} - a Promise that resolves after some delay. + */ + motorOn(args: object): Promise; + /** + * Turn specified motor(s) off. + * @param {object} args - the block's arguments. + * @property {MotorID} MOTOR_ID - the motor(s) to deactivate. + * @return {Promise} - a Promise that resolves after some delay. + */ + motorOff(args: object): Promise; + /** + * Set the power level of the specified motor(s). + * @param {object} args - the block's arguments. + * @property {MotorID} MOTOR_ID - the motor(s) to be affected. + * @property {int} POWER - the new power level for the motor(s). + * @return {Promise} - returns a promise to make sure the block yields. + */ + setMotorPower(args: object): Promise; + /** + * Set the direction of rotation for specified motor(s). + * If the direction is 'reverse' the motor(s) will be reversed individually. + * @param {object} args - the block's arguments. + * @property {MotorID} MOTOR_ID - the motor(s) to be affected. + * @property {MotorDirection} MOTOR_DIRECTION - the new direction for the motor(s). + * @return {Promise} - returns a promise to make sure the block yields. + */ + setMotorDirection(args: object): Promise; + /** + * @param {object} args - the block's arguments. + * @return {number} - returns the motor's position. + */ + getMotorPosition(args: object): number; + /** + * Test whether the tilt sensor is currently tilted. + * @param {object} args - the block's arguments. + * @property {TiltDirection} TILT_DIRECTION_ANY - the tilt direction to test (up, down, left, right, or any). + * @return {boolean} - true if the tilt sensor is tilted past a threshold in the specified direction. + */ + whenTilted(args: object): boolean; + /** + * Test whether the tilt sensor is currently tilted. + * @param {object} args - the block's arguments. + * @property {TiltDirection} TILT_DIRECTION_ANY - the tilt direction to test (up, down, left, right, or any). + * @return {boolean} - true if the tilt sensor is tilted past a threshold in the specified direction. + */ + isTilted(args: object): boolean; + /** + * @param {object} args - the block's arguments. + * @property {TiltDirection} TILT_DIRECTION - the direction (up, down, left, right) to check. + * @return {number} - the tilt sensor's angle in the specified direction. + * Note that getTiltAngle(up) = -getTiltAngle(down) and getTiltAngle(left) = -getTiltAngle(right). + */ + getTiltAngle(args: object): number; + /** + * Edge-triggering hat function, for when the vision sensor is detecting + * a certain color. + * @param {object} args - the block's arguments. + * @return {boolean} - true when the color sensor senses the specified color. + */ + whenColor(args: object): boolean; + /** + * A boolean reporter function, for whether the vision sensor is detecting + * a certain color. + * @param {object} args - the block's arguments. + * @return {boolean} - true when the color sensor senses the specified color. + */ + seeingColor(args: object): boolean; + /** + * Set the LED's hue. + * @param {object} args - the block's arguments. + * @property {number} HUE - the hue to set, in the range [0,100]. + * @return {Promise} - a Promise that resolves after some delay. + */ + setLightHue(args: object): Promise; + } + /** + * Manage communication with a Boost peripheral over a Bluetooth Low Energy client socket. + */ + class Boost { + constructor(runtime: any, extensionId: any); + /** + * The id of the extension this peripheral belongs to. + */ + _extensionId: any; + /** + * Reset all the state and timeout/interval ids. + */ + reset(): void; + /** + * @return {number} - the latest value received for the tilt sensor's tilt about the X axis. + */ + get tiltX(): number; + /** + * @return {number} - the latest value received for the tilt sensor's tilt about the Y axis. + */ + get tiltY(): number; + /** + * @return {number} - the latest color value received from the vision sensor. + */ + get color(): number; + /** + * @return {number} - the previous color value received from the vision sensor. + */ + get previousColor(): number; + /** + * Look up the color id for an index received from the vision sensor. + * @param {number} index - the color index to look up. + * @return {BoostColor} the color id for this index. + */ + boostColorForIndex(index: number): BoostColor; + /** + * Access a particular motor on this peripheral. + * @param {int} index - the index of the desired motor. + * @return {BoostMotor} - the BoostMotor instance, if any, at that index. + */ + motor(index: int): BoostMotor; + /** + * Stop all the motors that are currently running. + */ + stopAllMotors(): void; + /** + * Set the Boost peripheral's LED to a specific color. + * @param {int} inputRGB - a 24-bit RGB color in 0xRRGGBB format. + * @return {Promise} - a promise of the completion of the set led send operation. + */ + setLED(inputRGB: int): Promise; + /** + * Sets the input mode of the LED to RGB. + * @return {Promise} - a promise returned by the send operation. + */ + setLEDMode(): Promise; + /** + * Stop the motors on the Boost peripheral. + */ + stopAll(): void; + /** + * Called by the runtime when user wants to scan for a Boost peripheral. + */ + scan(): void; + /** + * Called by the runtime when user wants to connect to a certain Boost peripheral. + * @param {number} id - the id of the peripheral to connect to. + */ + connect(id: number): void; + /** + * Disconnects from the current BLE socket and resets state. + */ + disconnect(): void; + /** + * Called by the runtime to detect whether the Boost peripheral is connected. + * @return {boolean} - the connected state. + */ + isConnected(): boolean; + /** + * Write a message to the Boost peripheral BLE socket. + * @param {number} uuid - the UUID of the characteristic to write to + * @param {Array} message - the message to write. + * @param {boolean} [useLimiter=true] - if true, use the rate limiter + * @return {Promise} - a promise result of the write operation + */ + send(uuid: number, message: any[], useLimiter?: boolean): Promise; + /** + * Generate a Boost 'Output Command' in the byte array format + * (COMMON HEADER, PORT ID, EXECUTION BYTE, SUBCOMMAND ID, PAYLOAD). + * + * Payload is accepted as an array since these vary across different subcommands. + * + * @param {number} portID - the port (Connect ID) to send a command to. + * @param {number} execution - Byte containing startup/completion information + * @param {number} subCommand - the id of the subcommand byte. + * @param {array} payload - the list of bytes to send as subcommand payload + * @return {array} - a generated output command. + */ + generateOutputCommand( + portID: number, + execution: number, + subCommand: number, + payload: array + ): array; + /** + * Generate a Boost 'Input Command' in the byte array format + * (COMMAND ID, COMMAND TYPE, CONNECT ID, TYPE ID, MODE, DELTA INTERVAL (4 BYTES), + * UNIT, NOTIFICATIONS ENABLED). + * + * This sends a command to the Boost that sets that input format + * of the specified inputs and sets value change notifications. + * + * @param {number} portID - the port (Connect ID) to send a command to. + * @param {number} mode - the mode of the input sensor. + * @param {number} delta - the delta change needed to trigger notification. + * @param {boolean} enableNotifications - whether to enable notifications. + * @return {array} - a generated input command. + */ + generateInputCommand( + portID: number, + mode: number, + delta: number, + enableNotifications: boolean + ): array; + } + /** + * Ids for each color sensor value used by the extension. + */ + type BoostColor = string; + namespace BoostColor { + let ANY: string; + let NONE: string; + let RED: string; + let BLUE: string; + let GREEN: string; + let YELLOW: string; + let WHITE: string; + let BLACK: string; + } + /** + * Manage power, direction, position, and timers for one Boost motor. + */ + class BoostMotor { + /** + * Construct a Boost Motor instance. + * @param {Boost} parent - the Boost peripheral which owns this motor. + * @param {int} index - the zero-based index of this motor on its parent peripheral. + */ + constructor(parent: Boost, index: int); + /** + * Turn this motor off. + * @param {boolean} [useLimiter=true] - if true, use the rate limiter + */ + turnOff(useLimiter?: boolean): void; + /** + * @param {int} value - this motor's new direction: 1 for "this way" or -1 for "that way" + */ + set direction(value: int); + /** + * @return {int} - this motor's current direction: 1 for "this way" or -1 for "that way" + */ + get direction(): int; + /** + * @param {int} value - this motor's new power level, in the range [10,100]. + */ + set power(value: int); + /** + * @return {int} - this motor's current power level, in the range [0,100]. + */ + get power(): int; + /** + * @param {int} value - set this motor's current position. + */ + set position(value: int); + /** + * @return {int} - this motor's current position, in the range of [-MIN_INT32,MAX_INT32] + */ + get position(): int; + /** + * @param {BoostMotorState} value - set this motor's state. + */ + set status(value: { + OFF: number; + ON_FOREVER: number; + ON_FOR_TIME: number; + ON_FOR_ROTATION: number; + }); + /** + * @return {BoostMotorState} - the motor's current state. + */ + get status(): { + OFF: number; + ON_FOREVER: number; + ON_FOR_TIME: number; + ON_FOR_ROTATION: number; + }; + /** + * @return {number} - time, in milliseconds, of when the pending duration timeout began. + */ + get pendingDurationTimeoutStartTime(): number; + /** + * @return {number} - delay, in milliseconds, of the pending duration timeout. + */ + get pendingDurationTimeoutDelay(): number; + /** + * @return {number} - target position, in degrees, of the pending rotation. + */ + get pendingRotationDestination(): number; + /** + * @param {function} func - function to resolve pending rotation Promise + */ + set pendingRotationPromise(func: Function); + /** + * @return {Promise} - the Promise function for the pending rotation. + */ + get pendingRotationPromise(): Promise; + /** + * Turn this motor on indefinitely + */ + turnOnForever(): void; + /** + * Turn this motor on for a specific duration. + * @param {number} milliseconds - run the motor for this long. + */ + turnOnFor(milliseconds: number): void; + /** + * Turn this motor on for a specific rotation in degrees. + * @param {number} degrees - run the motor for this amount of degrees. + * @param {number} direction - rotate in this direction + */ + turnOnForDegrees(degrees: number, direction: number): void; + } +} + +declare module "scratch-vm-dts/extensions/scratch3_gdx_for" { + export = Scratch3GdxForBlocks; + /** + * Scratch 3.0 blocks to interact with a GDX-FOR peripheral. + */ + class Scratch3GdxForBlocks { + /** + * @return {string} - the name of this extension. + */ + static get EXTENSION_NAME(): string; + /** + * @return {string} - the ID of this extension. + */ + static get EXTENSION_ID(): string; + /** + * Construct a set of GDX-FOR blocks. + * @param {Runtime} runtime - the Scratch 3.0 runtime. + */ + constructor(runtime: Runtime); + get AXIS_MENU(): { + text: string; + value: string; + }[]; + get TILT_MENU(): { + text: string; + value: string; + }[]; + get TILT_MENU_ANY(): { + text: string; + value: string; + }[]; + get PUSH_PULL_MENU(): { + text: string; + value: string; + }[]; + get GESTURE_MENU(): { + text: string; + value: string; + }[]; + /** + * The Scratch 3.0 runtime. + * @type {Runtime} + */ + runtime: Runtime; + _peripheral: GdxFor; + /** + * @returns {object} metadata for this extension and its blocks. + */ + getInfo(): object; + whenForcePushedOrPulled(args: any): boolean; + getForce(): number; + whenGesture(args: any): boolean; + _isFacing(direction: any): boolean; + _facingUp: boolean | undefined; + _facingDown: boolean | undefined; + whenTilted(args: any): boolean; + isTilted(args: any): boolean; + getTilt(args: any): number | undefined; + _isTilted(direction: any): boolean; + _getTiltAngle(direction: any): number | undefined; + getSpinSpeed(args: any): number | undefined; + getAcceleration(args: any): number | undefined; + /** + * @param {number} x - x axis vector + * @param {number} y - y axis vector + * @param {number} z - z axis vector + * @return {number} - the magnitude of a three dimension vector. + */ + magnitude(x: number, y: number, z: number): number; + accelMagnitude(): number; + gestureMagnitude(): number; + spinMagnitude(): number; + isFreeFalling(): boolean; + } + /** + * Manage communication with a GDX-FOR peripheral over a Scratch Link client socket. + */ + class GdxFor { + /** + * Construct a GDX-FOR communication object. + * @param {Runtime} runtime - the Scratch 3.0 runtime + * @param {string} extensionId - the id of the extension + */ + constructor(runtime: Runtime, extensionId: string); + /** + * The id of the extension this peripheral belongs to. + */ + _extensionId: string; + /** + * Reset all the state and timeout/interval ids. + */ + reset(): void; + /** + * Called by the runtime when user wants to scan for a peripheral. + */ + scan(): void; + /** + * Called by the runtime when user wants to connect to a certain peripheral. + * @param {number} id - the id of the peripheral to connect to. + */ + connect(id: number): void; + /** + * Called by the runtime when a user exits the connection popup. + * Disconnect from the GDX FOR. + */ + disconnect(): void; + /** + * Return true if connected to the goforce device. + * @return {boolean} - whether the goforce is connected. + */ + isConnected(): boolean; + _spinSpeedFromGyro(val: any): any; + getForce(): number; + getTiltFrontBack(back?: boolean): number; + getTiltLeftRight(right?: boolean): number; + getAccelerationX(): number; + getAccelerationY(): number; + getAccelerationZ(): number; + getSpinSpeedX(): number; + getSpinSpeedY(): number; + getSpinSpeedZ(): number; + } +} + +declare module "scratch-vm-dts/extensions/tw" { + export = TurboWarpBlocks; + /** + * Class for TurboWarp blocks + * @constructor + */ + class TurboWarpBlocks { + constructor(runtime: any); + /** + * The runtime instantiating this block package. + * @type {Runtime} + */ + runtime: Runtime; + /** + * @returns {object} metadata for this extension and its blocks. + */ + getInfo(): object; + getLastKeyPressed(args: any, util: any): any; + getButtonIsDown(args: any, util: any): any; + } +} + +declare module "scratch-vm-dts/extension-support/tw-security-manager" { + export = SecurityManager; + /** + * Responsible for determining various policies related to custom extension security. + * The default implementation prevents automatic extension loading, but grants any + * loaded extensions the maximum possible capabilities so as to retain compatibility + * with a vanilla scratch-vm. You may override properties of an instance of this class + * to customize the security policies as you see fit, for example: + * ```js + * vm.securityManager.getSandboxMode = (url) => { + * if (url.startsWith("https://example.com/")) { + * return "unsandboxed"; + * } + * return "iframe"; + * }; + * vm.securityManager.canAutomaticallyLoadExtension = (url) => { + * return confirm("Automatically load extension: " + url); + * }; + * vm.securityManager.canFetch = (url) => { + * return url.startsWith('https://turbowarp.org/'); + * }; + * vm.securityManager.canOpenWindow = (url) => { + * return url.startsWith('https://turbowarp.org/'); + * }; + * vm.securityManager.canRedirect = (url) => { + * return url.startsWith('https://turbowarp.org/'); + * }; + * ``` + */ + class SecurityManager { + /** + * Determine the typeof sandbox to use for a certain custom extension. + * @param {string} extensionURL The URL of the custom extension. + * @returns {'worker'|'iframe'|'unsandboxed'|Promise<'worker'|'iframe'|'unsandboxed'>} + */ + getSandboxMode( + extensionURL: string + ): + | "worker" + | "iframe" + | "unsandboxed" + | Promise<"worker" | "iframe" | "unsandboxed">; + /** + * Determine whether a custom extension that was stored inside a project may be + * loaded. You could, for example, ask the user to confirm loading an extension + * before resolving. + * @param {string} extensionURL The URL of the custom extension. + * @returns {Promise|boolean} + */ + canLoadExtensionFromProject( + extensionURL: string + ): Promise | boolean; + /** + * Allows last-minute changing the real URL of the extension that gets loaded. + * @param {*} extensionURL The URL requested to be loaded. + * @returns {Promise|string} The URL to actually load. + */ + rewriteExtensionURL(extensionURL: any): Promise | string; + /** + * Determine whether an extension is allowed to fetch a remote resource URL. + * This only applies to unsandboxed extensions that use the appropriate Scratch.* APIs. + * Sandboxed extensions ignore this entirely as there is no way to force them to use our APIs. + * data: and blob: URLs are always allowed (this method is never called). + * @param {string} resourceURL + * @returns {Promise|boolean} + */ + canFetch(resourceURL: string): Promise | boolean; + /** + * Determine whether an extension is allowed to open a new window or tab to a given URL. + * This only applies to unsandboxed extensions. Sandboxed extensions are unable to open windows. + * javascript: URLs are always rejected (this method is never called). + * @param {string} websiteURL + * @returns {Promise|boolean} + */ + canOpenWindow(websiteURL: string): Promise | boolean; + /** + * Determine whether an extension is allowed to redirect the current tab to a given URL. + * This only applies to unsandboxed extensions. Sandboxed extensions are unable to redirect the parent + * window, but are free to redirect their own sandboxed window. + * javascript: URLs are always rejected (this method is never called). + * @param {string} websiteURL + * @returns {Promise|boolean} + */ + canRedirect(websiteURL: string): Promise | boolean; + /** + * Determine whether an extension is allowed to record audio from the user's microphone. + * This could include raw audio data or a transcriptions. + * Note that, even if this returns true, success is not guaranteed. + * @returns {Promise|boolean} + */ + canRecordAudio(): Promise | boolean; + /** + * Determine whether an extension is allowed to record video from the user's camera. + * Note that, even if this returns true, success is not guaranteed. + * @returns {Promise|boolean} + */ + canRecordVideo(): Promise | boolean; + /** + * Determine whether an extension is allowed to read values from the user's clipboard + * without user interaction. + * Note that, even if this returns true, success is not guaranteed. + * @returns {Promise|boolean} + */ + canReadClipboard(): Promise | boolean; + /** + * Determine whether an extension is allowed to show notifications. + * Note that, even if this returns true, success is not guaranteed. + * @returns {Promise|boolean} + */ + canNotify(): Promise | boolean; + /** + * Determine whether an extension is allowed to find the user's precise location using GPS + * and other techniques. Note that, even if this returns true, success is not guaranteed. + * @returns {Promise|boolean} + */ + canGeolocate(): Promise | boolean; + /** + * Determine whether an extension is allowed to embed content from a given URL. + * @param {string} documentURL The URL of the embed. + * @returns {Promise|boolean} + */ + canEmbed(documentURL: string): Promise | boolean; + } +} + +declare module "scratch-vm-dts/extension-support/block-type" { + export = BlockType; + /** + * Types of block + */ + type BlockType = string; + namespace BlockType { + let BOOLEAN: string; + let BUTTON: string; + let LABEL: string; + let COMMAND: string; + let CONDITIONAL: string; + let EVENT: string; + let HAT: string; + let LOOP: string; + let REPORTER: string; + let XML: string; + } +} + +declare module "scratch-vm-dts/extensions/scratch3_video_sensing/library" { + export = VideoMotion; + interface MotionState { + motionFrameNumber: number; + motionAmount: number; + motionDirection: number; + } + /** + * Store the necessary image pixel data to compares frames of a video and + * detect an amount and direction of motion in the full sample or in a + * specified area. + * @constructor + */ + class VideoMotion { + /** + * The number of frames that have been added from a source. + * @type {number} + */ + frameNumber: number; + /** + * The frameNumber last analyzed. + * @type {number} + */ + lastAnalyzedFrame: number; + /** + * The amount of motion detected in the current frame. + * @type {number} + */ + motionAmount: number; + /** + * The direction the motion detected in the frame is general moving in. + * @type {number} + */ + motionDirection: number; + /** + * A copy of the current frame's pixel values. A index of the array is + * represented in RGBA. The lowest byte is red. The next is green. The + * next is blue. And the last is the alpha value of that pixel. + * @type {Uint32Array} + */ + curr: Uint32Array; + /** + * A copy of the last frame's pixel values. + * @type {Uint32Array} + */ + prev: Uint32Array; + /** + * A buffer for holding one component of a pixel's full value twice. + * One for the current value. And one for the last value. + * @type {number} + */ + _arrays: number; + /** + * A clamped uint8 view of _arrays. One component of each index of the + * curr member is copied into this array. + * @type {number} + */ + _curr: number; + /** + * A clamped uint8 view of _arrays. One component of each index of the + * prev member is copied into this array. + * @type {number} + */ + _prev: number; + /** + * Reset internal state so future frame analysis does not consider values + * from before this method was called. + */ + reset(): void; + /** + * Add a frame to be next analyzed. The passed array represent a pixel with + * each index in the RGBA format. + * @param {Uint32Array} source - a source frame of pixels to copy + */ + addFrame(source: Uint32Array): void; + /** + * Analyze the current frame against the previous frame determining the + * amount of motion and direction of the motion. + */ + analyzeFrame(): void; + /** + * Build motion amount and direction values based on stored current and + * previous frame that overlaps a given drawable. + * @param {Drawable} drawable - touchable and bounded drawable to build motion for + * @param {MotionState} state - state to store built values to + */ + getLocalMotion(drawable: Drawable, state: MotionState): void; + } +} diff --git a/src/plugins/wpp-monaco/assets/extension.ts.txt b/src/plugins/wpp-monaco/assets/extension.ts.txt new file mode 100644 index 0000000..21c197b --- /dev/null +++ b/src/plugins/wpp-monaco/assets/extension.ts.txt @@ -0,0 +1,48 @@ +import * as vscode from 'vscode'; + +export function activate(context: vscode.ExtensionContext) { + context.subscriptions.push( + vscode.languages.registerDocumentFormattingEditProvider('wpp', { + provideDocumentFormattingEdits(document: vscode.TextDocument): vscode.TextEdit[] { + const edits: vscode.TextEdit[] = []; + let indentLevel = 0; + + for (let i = 0; i < document.lineCount; i++) { + const line = document.lineAt(i); + const original = line.text; + let text = original.trim(); + + // Adjust indent level before writing line + if (text.startsWith('}')) indentLevel = Math.max(0, indentLevel - 1); + + // 1. Add indent (2 spaces per level) + let formatted = ' '.repeat(indentLevel) + text; + + // 2. let a=1 → let a = 1 + formatted = formatted.replace(/\blet\s+(\S+)\s*=\s*(\S+)/, 'let $1 = $2'); + + // 3. func(a,b) → func(a, b) + formatted = formatted.replace(/\(([^)]*)\)/g, (_, args) => { + return '(' + args.split(',').map((s: string) => s.trim()).join(', ') + ')'; + }); + + // 4. ){} → ) {} + formatted = formatted.replace(/\)\s*\{/, ') {'); + + // 5. }后面如果是描述(非空行、非注释),插入一个空格 + formatted = formatted.replace(/\}(\S)/, '} $1'); + + if (formatted !== original) { + edits.push(vscode.TextEdit.replace(line.range, formatted)); + } + + if (text.endsWith('{')) indentLevel++; + } + + return edits; + } + }) + ); +} + +export function deactivate() {} diff --git a/src/plugins/wpp-monaco/assets/wpp.tmLanguage.json b/src/plugins/wpp-monaco/assets/wpp.tmLanguage.json new file mode 100644 index 0000000..28618b8 --- /dev/null +++ b/src/plugins/wpp-monaco/assets/wpp.tmLanguage.json @@ -0,0 +1,119 @@ +{ + "scopeName": "source.wpp", + "patterns": [ + { + "name": "comment.line.wpp", + "match": "//.*$" + }, + { + "name": "comment.line.escape.wpp", + "match": "(?<=^|[^\\\\])\\\\(?!\\\\)" + }, + { + "name": "markup.italic.description.wpp", + "match": "(?<=\\})\\s*(?!\\s*//)[^\\s\\r\\n].*?(?=\\s*//|$)", + "comment": "描述文本,但排除行尾注释" + }, + { + "name": "entity.name.function", + "match": "(?:^\\s*|(?<=:))(if|elif|else|for|while)\\b(?=\\s*\\()" + }, + { + "name": "keyword", + "match": "(?:^\\s*|(?<=:))(on|return|task)\\b(?=\\s*\\()" + }, + { + "name": "entity.name.function", + "match": "(?:^\\s*|(?<=:))[a-zA-Z_][a-zA-Z0-9_]*(?=\\s*\\()" + }, + { + "name": "storage.type", + "match": "\\blet\\b" + }, + { + "name": "punctuation.section.parens.wpp", + "match": "[\\{\\}]" + }, + { + "name": "punctuation.section.parens.wpp", + "match": "[()]" + }, + { + "begin": "\\(", + "end": "\\)", + "name": "meta.expression.wpp", + "beginCaptures": { + "0": { + "name": "punctuation.section.parens.wpp" + } + }, + "endCaptures": { + "0": { + "name": "punctuation.section.parens.wpp" + } + }, + "patterns": [] + }, + { + "include": "#variables" + }, + { + "include": "#expression-content" + } + ], + "repository": { + "expression-content": { + "patterns": [ + { + "name": "entity.name.function", + "match": "(?:^\\s*|(?<=:))[a-zA-Z_][a-zA-Z0-9_]*(?=\\s*\\()" + }, + { + "include": "#variables" + }, + { + "name": "punctuation.separator.comma.wpp", + "match": "," + }, + { + "name": "constant.numeric.wpp", + "match": "\\b\\d+\\b" + }, + { + "name": "keyword", + "match": "==|!=|>=|<=|>|<" + }, + { + "name": "keyword", + "match": "[+\\-*/]" + } + ] + }, + "variables": { + "patterns": [ + { + "match": "\\$(this\\.)([a-zA-Z_\\u4e00-\\u9fa5][a-zA-Z0-9_\\u4e00-\\u9fa5]*)\\$", + "captures": { + "1": { + "name": "variable.language.object.wpp" + }, + "2": { + "name": "variable.other.wpp" + } + } + }, + { + "match": "\\$([a-zA-Z_\\u4e00-\\u9fa5][a-zA-Z0-9_\\u4e00-\\u9fa5]*)\\$", + "captures": { + "1": { + "name": "variable.other.wpp" + } + } + } + ] + } + }, + "fileTypes": [ + "wpp" + ] +} \ No newline at end of file diff --git a/src/plugins/wpp-monaco/index.js b/src/plugins/wpp-monaco/index.js new file mode 100644 index 0000000..2ccdbee --- /dev/null +++ b/src/plugins/wpp-monaco/index.js @@ -0,0 +1,66 @@ + +const WppMonaco = ({ vm, registerSettings, msg }) => { + const supportedAssetTypes = vm.runtime.gandi.supportedAssetTypes + const wpp_asset = { contentType: 'text/plain', name: 'Wpp', runtimeFormat: 'wpp', immutable: true } + + if (!supportedAssetTypes.includes(wpp_asset)) { + supportedAssetTypes.push(wpp_asset) + } + const register = registerSettings( + msg("plugins.wppMonaco.title"), + "plugin-wpp-monaco", + [ + { + key: "plugin-wpp-monaco", + label: msg("plugins.wppMonaco.title"), + description: msg("plugins.wppMonaco.description"), + items: [], + }, + ], + "", + ); + const monaco = window.monaco + console.log(monaco) + debugger + monaco.languages.register({ id: 'wpp', extensions: ['.wpp'], mimetypes: ['text/plain'] }) + monaco.languages.setMonarchTokensProvider('wpp', { + keywords:['if'], + tokenizer: { + root: [ + [/\/\/.*$/, { token: "comment.line.wpp" }],//WPP语法1:不支持多行注释,注释应以//开头 + [/((if|elif|for|while|return|task|on)(?=\()|else(?={))/, { token: "keyword.wpp" }],//WPP语法:if,elif,for,while后加()为内置函数,else直接加{ + [/[a-zA-z0-9\s]+(?=\(.*\)\s*{)/,{ token: "entity.name.function.wpp" }], + [/[{}]+/,{token:'delimiter.curly'}], + [/[\(\)]+/,{token:'delimiter.parenthesis'}], + [/[\[\]]+/,{token:'delimiter.square'}], + ] + } + }) + monaco.languages.setLanguageConfiguration('wpp', { + autoClosingPairs: [ + { open: '{', close: '}' }, + { open: '[', close: ']' }, + { open: '(', close: ')' } + ], + surroundingPairs: [ + { open: '{', close: '}' }, + { open: '[', close: ']' }, + { open: '(', close: ')' } + ] + }) + monaco.editor.defineTheme('wpp-theme',{ + base:'vs-dark', + inherit: true, + rules:[ + {token:'entity.name.function.wpp',foreground:'#21b3bd'} + ] + }) + return { + dispose: () => { + /** Remove some side effects */ + register.dispose() + }, + }; +}; + +export default WppMonaco; diff --git a/src/plugins/wpp-monaco/manifest.ts b/src/plugins/wpp-monaco/manifest.ts new file mode 100644 index 0000000..dbe8c26 --- /dev/null +++ b/src/plugins/wpp-monaco/manifest.ts @@ -0,0 +1,11 @@ +export default { + name: "wpp-monaco", + type: "function", + description: "Provide auto-completion and highlighting for WPP language.", + credits: [ + { + name: "BenPaoDeXiaoZhi @ CCW", + link: "https://www.ccw.site/student/63c2807d669fa967f17f5559" + }, + ], +}; diff --git a/src/types.d.ts b/src/types.d.ts index 11d62be..ab67edd 100644 --- a/src/types.d.ts +++ b/src/types.d.ts @@ -10,6 +10,11 @@ declare module "*.svg" { export default src; } +declare module "*.asset" { + const data:string + export default data; +} + declare module "*.svg?url" { const src: string; export default src; diff --git a/webpack.config.js b/webpack.config.js index b4cdd31..efa6841 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -18,6 +18,10 @@ module.exports = { }, module: { rules: [ + { + test: /\.asset$/i, + type: 'asset/source', + }, { test: /\.tsx?$/, use: "ts-loader", diff --git a/webpackDevServer.config.js b/webpackDevServer.config.js index 5dea709..55ba3d2 100644 --- a/webpackDevServer.config.js +++ b/webpackDevServer.config.js @@ -20,6 +20,10 @@ module.exports = { }, module: { rules: [ + { + test: /\.asset$/i, + type: 'asset/source', + }, { test: /\.tsx?$/, use: "ts-loader", From d374d0c1792827c940db2cfc128ad205d7721ef8 Mon Sep 17 00:00:00 2001 From: BenPaoDeXiaoZhi Date: Tue, 29 Jul 2025 17:29:38 +0800 Subject: [PATCH 11/28] =?UTF-8?q?=E5=9C=A8=E5=BD=93=E5=89=8D=E5=88=86?= =?UTF-8?q?=E6=94=AF=E4=B8=AD=E4=B8=8D=E6=8F=90=E4=BA=A4wpp=E8=A1=A5?= =?UTF-8?q?=E5=85=A8=E6=8F=92=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index bdfebba..a570a0d 100644 --- a/.gitignore +++ b/.gitignore @@ -15,4 +15,6 @@ # style types *.less.d.ts -temp-wrapper.jsx \ No newline at end of file +temp-wrapper.jsx +#ignore for branch-typeDefiniton +/src/plugins/wpp-monaco \ No newline at end of file From 83bff3040376b2726aac1357641e39fc9e4904fd Mon Sep 17 00:00:00 2001 From: BenPaoDeXiaoZhi Date: Tue, 29 Jul 2025 17:36:42 +0800 Subject: [PATCH 12/28] =?UTF-8?q?=E5=9C=A8=E5=BD=93=E5=89=8D=E5=88=86?= =?UTF-8?q?=E6=94=AF=E4=B8=AD=E4=B8=8D=E8=BF=BD=E8=B8=AAtypeDefinition?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index a570a0d..0f24a71 100644 --- a/.gitignore +++ b/.gitignore @@ -16,5 +16,5 @@ *.less.d.ts temp-wrapper.jsx -#ignore for branch-typeDefiniton -/src/plugins/wpp-monaco \ No newline at end of file +#ignore for branch-wppMonaco +/src/plugins/extension-type-definition \ No newline at end of file From ab1b4193501e31d9e7adcbbe119e0faf9e90c6e4 Mon Sep 17 00:00:00 2001 From: BenPaoDeXiaoZhi Date: Tue, 29 Jul 2025 17:37:08 +0800 Subject: [PATCH 13/28] deleted: src/plugins/extension-type-definition/index.js deleted: src/plugins/extension-type-definition/manifest.ts deleted: src/plugins/extension-type-definition/scratch-vm-dts.d.ts.asset --- .../extension-type-definition/index.js | 41 - .../extension-type-definition/manifest.ts | 11 - .../scratch-vm-dts.d.ts.asset | 8466 ----------------- 3 files changed, 8518 deletions(-) delete mode 100644 src/plugins/extension-type-definition/index.js delete mode 100644 src/plugins/extension-type-definition/manifest.ts delete mode 100644 src/plugins/extension-type-definition/scratch-vm-dts.d.ts.asset diff --git a/src/plugins/extension-type-definition/index.js b/src/plugins/extension-type-definition/index.js deleted file mode 100644 index 038e2fe..0000000 --- a/src/plugins/extension-type-definition/index.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * dts 包含了用于extraLib载入的.d.ts的文件内容 - * @type {string} - */ -import dts from './scratch-vm-dts.d.ts.asset' - -const ExtensionTypeDefinition = ({ vm, registerSettings, msg }) => { - if (!window?.monaco?.languages?.typescript?.javascriptDefaults) { - console.warn('ide未在全局暴露monaco或其js语言功能,无法加载插件' + msg("plugins.extensionTypeDefinition.title")) - return { dispose: () => { } } - } - // vm.runtime.gandi._supportedAssetTypes.push({ //测试用 - // "contentType": "text/javascript", - // "name": "Extension", - // "runtimeFormat": "js", - // "immutable": true - // }) - const register = registerSettings( - msg("plugins.extensionTypeDefinition.title"), - "plugin-extension-type-definition", - [ - { - key: "plugin-extension-type-definition", - label: msg("plugins.extensionTypeDefinition.title"), - description: msg("plugins.extensionTypeDefinition.description"), - items: [], - }, - ], - "", - ); - window.monaco.languages.typescript.javascriptDefaults.addExtraLib(dts, 'global.d.ts') - console.log('monaco d.ts文件已载入') - return { - dispose: () => { - /** Remove some side effects */ - register.dispose() - }, - }; -}; - -export default ExtensionTypeDefinition; diff --git a/src/plugins/extension-type-definition/manifest.ts b/src/plugins/extension-type-definition/manifest.ts deleted file mode 100644 index ffb6411..0000000 --- a/src/plugins/extension-type-definition/manifest.ts +++ /dev/null @@ -1,11 +0,0 @@ -export default { - name: "extension-type-definiton", - type: "function", - description: "create type definitions for extension", - credits: [ - { - name: "BenPaoDeXiaoZhi @ CCW", - link: "https://www.ccw.site/student/63c2807d669fa967f17f5559" - } - ], -}; diff --git a/src/plugins/extension-type-definition/scratch-vm-dts.d.ts.asset b/src/plugins/extension-type-definition/scratch-vm-dts.d.ts.asset deleted file mode 100644 index 784a74f..0000000 --- a/src/plugins/extension-type-definition/scratch-vm-dts.d.ts.asset +++ /dev/null @@ -1,8466 +0,0 @@ -// Generated by dts-bundle v0.7.3 -// Dependencies for this module: -// ../events -// ../@turbowarp/jszip -// ../format-message -// ../immutable -// ../node:events -// ../jszizp -//monaco似乎不能处理import…from -declare type ArgumentType = import('scratch-vm-dts/extension-support/argument-type') -declare type Runtime = import("scratch-vm-dts/engine/runtime"); -declare type Target = import("scratch-vm-dts/engine/target"); -declare type RenderedTarget = import("scratch-vm-dts/sprites/rendered-target"); -declare type Sprite = import("scratch-vm-dts/sprites/sprite"); -declare type BlockType = import('scratch-vm-dts/extension-support/block-type') -declare module "scratch-vm-dts" { - export = VirtualMachine; - import VirtualMachine = require("scratch-vm-dts/virtual-machine"); -} - -declare module "scratch-vm-dts/virtual-machine" { - export = VirtualMachine; - //import Target = require('scratch-vm-dts/engine/target'); //我发现require也无法使用 - type Target = import("scratch-vm-dts/engine/target"); - import Sequencer = require("scratch-vm-dts/engine/sequencer"); - namespace Blockly { - class Event { } - } - class StreamHelper { } - class ImportedProject { } - class Gandi { } - class int extends Number { } - class Block { } - class bool extends Boolean { } - class Costume { } - class ImportedExtensionsInfo { } - class AudioEngine { } - class RenderWebGL { } - class ScratchStorage { } - /** - * Handles connections between blocks, stage, and extensions. - * @constructor - */ - class VirtualMachine extends EventEmitter<[never]> { - static get FIND_PYTHON_CODE(): string; - constructor(); - /** - * VM runtime, to store blocks, I/O devices, sprites/targets, etc. - * @type {!Runtime} - */ - runtime: Runtime; - /** - * The "currently editing"/selected target ID for the VM. - * Block events from any Blockly workspace are routed to this target. - * @type {Target} - */ - editingTarget: Target; - /** - * This variable indicates whether asynchronous loading of project resource files is supported - */ - asyncLoadingProjectAssetsSupported: boolean; - /** - * The currently dragging target, for redirecting IO data. - * @type {Target} - */ - _dragTarget: Target; - /** - * The current project resource loading progress. - * @type {Progress} - */ - _assetsLoadProgress: Progress; - extensionManager: ExtensionManager; - securityManager: import("scratch-vm-dts/extension-support/tw-security-manager"); - /** - * Handle a Blockly event for the current editing target. - * @param {!Blockly.Event} e Any Blockly event. - */ - blockListener(e: Blockly.Event): void; - /** - * Handle a Blockly event for the current editing target. - * @param {!Blockly.Event} e Any Blockly event. - */ - frameListener(e: Blockly.Event): void; - /** - * Handle a Blockly event for the flyout. - * @param {!Blockly.Event} e Any Blockly event. - */ - flyoutBlockListener(e: Blockly.Event): void; - /** - * Handle a Blockly event for the flyout to be passed to the monitor container. - * @param {!Blockly.Event} e Any Blockly event. - */ - monitorBlockListener(e: Blockly.Event): void; - /** - * Handle a Blockly event for the variable map. - * @param {!Blockly.Event} e Any Blockly event. - */ - variableListener(e: Blockly.Event): void; - /** - * Export some internal classes for extensions. - */ - exports: { - Sprite: Sprite; - RenderedTarget: RenderedTarget; - JSZip: JSZip; - i_will_not_ask_for_help_when_these_break: () => { - JSGenerator: typeof import("scratch-vm-dts/compiler/jsgen"); - IRGenerator: typeof import("scratch-vm-dts/compiler/irgen").IRGenerator; - ScriptTreeGenerator: typeof import("scratch-vm-dts/compiler/irgen").ScriptTreeGenerator; - Thread: import("scratch-vm-dts/engine/thread"); - execute: ( - sequencer: Sequencer, - thread: import("scratch-vm-dts/engine/thread") - ) => void; - }; - }; - _projectProcessingUniqueId: number; - /** - * Start running the VM - do this before anything else. - */ - start(): void; - /** - * @deprecated Used by old versions of TurboWarp. Superceded by upstream's quit() - */ - stop(): void; - /** - * Quit the VM, clearing any handles which might keep the process alive. - * Do not use the runtime after calling this method. This method is meant for test shutdown. - */ - quit(): void; - /** - * "Green flag" handler - start all threads starting with a green flag. - */ - greenFlag(): void; - /** - * Set whether the VM is in "turbo mode." - * When true, loops don't yield to redraw. - * @param {boolean} turboModeOn Whether turbo mode should be set. - */ - setTurboMode(turboModeOn: boolean): void; - /** - * Set whether the VM is in 2.0 "compatibility mode." - * When true, ticks go at 2.0 speed (30 TPS). - * @param {boolean} compatibilityModeOn Whether compatibility mode is set. - */ - setCompatibilityMode(compatibilityModeOn: boolean): void; - setFramerate(framerate: any): void; - setInterpolation(interpolationEnabled: any): void; - setRuntimeOptions(runtimeOptions: any): void; - /** - * ccw: Set ccw API to runtime support ccw block extensions - * @param {*} ccwAPI ccw API - */ - setCCWAPI(ccwAPI: any): void; - setCompilerOptions(compilerOptions: any): void; - setIsPlayerOnly(isPlayerOnly: any): void; - setStageSize(width: any, height: any): void; - setInEditor(inEditor: any): void; - convertToPackagedRuntime(): void; - addAddonBlock(options: any): void; - getAddonBlock(procedureCode: any): any; - storeProjectOptions(): void; - enableDebug(): string; - handleExtensionButtonPress(button: any): void; - /** - * Stop all threads and running activities. - */ - stopAll(): void; - disposeAll(): void; - /** - * Clear out current running project data. - */ - clear(): void; - /** - * Get data for playground. Data comes back in an emitted event. - */ - getPlaygroundData(): void; - /** - * Post I/O data to the virtual devices. - * @param {?string} device Name of virtual I/O device. - * @param {object} data Any data object to post to the I/O device. - */ - postIOData(device: string | null, data: object): void; - setVideoProvider(videoProvider: any): void; - setCloudProvider(cloudProvider: any): void; - /** - * Tell the specified extension to scan for a peripheral. - * @param {string} extensionId - the id of the extension. - */ - scanForPeripheral(extensionId: string): void; - /** - * Connect to the extension's specified peripheral. - * @param {string} extensionId - the id of the extension. - * @param {number} peripheralId - the id of the peripheral. - */ - connectPeripheral(extensionId: string, peripheralId: number): void; - /** - * Disconnect from the extension's connected peripheral. - * @param {string} extensionId - the id of the extension. - */ - disconnectPeripheral(extensionId: string): void; - /** - * Returns whether the extension has a currently connected peripheral. - * @param {string} extensionId - the id of the extension. - * @return {boolean} - whether the extension has a connected peripheral. - */ - getPeripheralIsConnected(extensionId: string): boolean; - /** - * Load a Scratch project from a .sb, .sb2, .sb3 or json string. - * @param {string | object} input A json string, object, or ArrayBuffer representing the project to load. - * @param {?function} jsonFormatter A function to format the project json. - * @return {!Promise} Promise that resolves after targets are installed. - */ - loadProject( - input: string | object, - jsonFormatter: Function | null, - options: any - ): Promise; - /** - * Load a project from the Scratch web site, by ID. - * @param {string} id - the ID of the project to download, as a string. - */ - downloadProjectId(id: string): void; - /** - * @returns {JSZip} JSZip zip object representing the sb3. - */ - _saveProjectZip(): JSZip; - /** - * @param {JSZip.OutputType} [type] JSZip output type. Defaults to 'blob' for Scratch compatibility. - * @returns {Promise} Compressed sb3 file in a type determined by the type argument. - */ - saveProjectSb3(type?: JSZip.OutputType): Promise; - /** - * @param {JSZip.OutputType} [type] JSZip output type. Defaults to 'arraybuffer'. - * @returns {StreamHelper} JSZip StreamHelper object generating the compressed sb3. - * See: https://stuk.github.io/jszip/documentation/api_streamhelper.html - */ - saveProjectSb3Stream(type?: JSZip.OutputType): StreamHelper; - /** - * tw: Serialize the project into a map of files without actually zipping the project. - * The buffers returned are the exact same ones used internally, not copies. Avoid directly - * manipulating them (except project.json, which is created by this function). - * @returns {Record} Map of file name to the raw data for that file. - */ - saveProjectSb3DontZip(): Record; - /** - * Serialize project. - * @param {object} whetherSerialize - * @param {boolean} whetherSerialize.isSerializeSounds whether to serialize sound - * @param {boolean} whetherSerialize.isSerializeCostumes whether to serialize costumes - * @param {boolean} whetherSerialize.isSerializeJson whether to serialize json - * @returns {Object} Serialized state of the runtime. - */ - serializeProject({ - isSerializeSounds, - isSerializeCostumes, - isSerializeJson, - }?: { - isSerializeSounds: boolean; - isSerializeCostumes: boolean; - isSerializeJson: boolean; - }): Object; - /** - * @type {Array} Array of all assets currently in the runtime - */ - get assets(): Array; - generateUid(): string; - getSb3Utils(): { - serialize: ( - runtime: Runtime, - targetId?: string | undefined, - { - allowOptimization, - saveVarId, - }?: { - allowOptimization?: boolean | undefined; - saveVarId?: boolean | undefined; - } - ) => object; - deserialize: ( - json: object, - runtime: Runtime, - zip: JSZip, - isSingleSprite: boolean - ) => Promise; - deserializeBlocks: (blocks: object) => object; - deserializeInputs: ( - inputs: object, - parentId: string, - blocks: object - ) => object; - deserializeFields: (fields: object) => object; - serializeBlocks: (blocks: object, saveVarId: boolean | null) => any[]; - serializeTarget: ( - target: object, - extensions: Set, - saveVarId: boolean | null - ) => object; - serializeMonitors: (monitors: any, runtime: any, extensions: any) => any; - deserializeMonitor: ( - monitorData: any, - runtime: any, - targets: any, - extensions: any - ) => void; - serializeSound: (sound: object) => object; - deserializeSound: ( - sound: object, - runtime: Runtime, - zip: JSZip, - assetFileName: string - ) => Promise; - serializeComments: (comments: any) => any; - serializeVariables: (variables: object) => object; - getExtensionIdForOpcode: (opcode: string) => string | null; - deserializeInputDesc: ( - inputDescOrId: string | Array, - parentId: string, - isShadow: boolean, - blocks: object, - blockId: any - ) => object; - serializePrimitiveBlock: ( - block: object, - saveVarId: boolean | null - ) => Array; - primitiveOpcodeInfoMap: { - math_number: (string | number)[]; - math_positive_number: (string | number)[]; - math_whole_number: (string | number)[]; - math_integer: (string | number)[]; - math_angle: (string | number)[]; - colour_picker: (string | number)[]; - text: (string | number)[]; - event_broadcast_menu: (string | number)[]; - data_variable: (string | number)[]; - data_listcontents: (string | number)[]; - }; - deserializeStandaloneBlocks: (blocks: unknown) => { - blocks: Block[]; - extensionURLs: Map; - }; - serializeStandaloneBlocks: (blocks: Block[], runtime: Runtime) => object; - }; - createGandiAssetFile(name: any, assetType: any, data?: string): void; - getGandiAssetsList(typesArray: any): any; - getGandiAssetContent(fileName: any): any; - getGandiAssetsFileList(type: any): any; - getGandiAssetFile(fileName: any): any; - getGandiAssetById(id: any): any; - getGandiAssetIndexAndFileById(id: any): { - file: any; - index: number; - }; - /** - * @param {string} targetId Optional ID of target to export - * @returns {Array<{fileName: string; fileContent: Uint8Array;}} list of file descs - */ - serializeAssets(targetId: string): Array<{ - fileName: string; - fileContent: Uint8Array; - }>; - _addFileDescsToZip(fileDescs: any, zip: any): void; - /** - * Exports a sprite in the sprite3 format. - * @param {string} targetId ID of the target to export - * @param {string=} optZipType Optional type that the resulting - * zip should be outputted in. Options are: base64, binarystring, - * array, uint8array, arraybuffer, blob, or nodebuffer. Defaults to - * blob if argument not provided. - * See https://stuk.github.io/jszip/documentation/api_jszip/generate_async.html#type-option - * for more information about these options. - * @return {object} A generated zip of the sprite and its assets in the format - * specified by optZipType or blob by default. - */ - exportSprite(targetId: string, optZipType?: string | undefined): object; - /** - * Export project or sprite as a Scratch 3.0 JSON representation. - * @param {string=} optTargetId - Optional id of a sprite to serialize - * @param {*} serializationOptions Options to pass to the serializer - * @return {string} Serialized state of the runtime. - */ - toJSON(optTargetId: string | undefined, serializationOptions: any): string; - /** - * Serialize a sprite in the sprite3 format. - * @param {string} targetId ID of the target to export - * @param {?Boolean} saveVarId Whether to save the variable ID or not - * @returns {Object} Serialized state of the runtime. - */ - serializeSprite(targetId: string, saveVarId: boolean | null): Object; - /** - * Serialize sprite assets for gui - * @param {string} targetId ID of the target to export - * @returns {Object} sound & costume & spriteJson result of serialize - */ - serializeSpriteAssets(targetId: string): Object; - /** - * Load a project from a Scratch JSON representation. - * @param {string} json JSON string representing a project. - * @returns {Promise} Promise that resolves after the project has loaded - */ - fromJSON(json: string): Promise; - /** - * Load a project from a Scratch JSON representation. - * @param {string} projectJSON JSON string representing a project. - * @param {?JSZip} zip Optional zipped project containing assets to be loaded. - * @param {number} _projectProcessingUniqueId 加载project的Id - * @returns {Promise} Promise that resolves after the project has loaded - */ - deserializeProject( - projectJSON: string, - zip: JSZip | null, - _projectProcessingUniqueId: number, - options: any - ): Promise; - /** - * Install `deserialize` results: zero or more targets after the extensions (if any) used by those targets. - * @param {Array.} targets - the targets to be installed - * @param {ImportedExtensionsInfo} extensions - metadata about extensions used by these targets - * @param {Gandi} gandiObject - the gandi Object to be merged - * @param {boolean} wholeProject - set to true if installing a whole project, as opposed to a single sprite. - * @param {number} _projectProcessingUniqueId 加载project的Id - * @param {boolean} isRemoteOperation - set to true if this is a remote operation - * @returns {Promise<{addedTargets:Target[], addedGandiObject:Gandi}>} resolved once targets and Gandi object have been installed - */ - installTargets( - targets: Array, - extensions: ImportedExtensionsInfo, - gandiObject: Gandi, - wholeProject: boolean, - _projectProcessingUniqueId: number, - isRemoteOperation: boolean, - options: any - ): Promise<{ - addedTargets: Target[]; - addedGandiObject: Gandi; - }>; - /** - * Add a sprite, this could be .sprite2 or .sprite3. Unpack and validate - * such a file first. - * @param {string | object} input A json string, object, or ArrayBuffer representing the project to load. - * @param {?string} isRemoteOperation - set to true if this is a remote operation - * @return {!Promise} Promise that resolves after targets are installed. - */ - addSprite( - input: string | object, - isRemoteOperation: string | null - ): Promise; - /** - * Add a single sprite from the "Sprite2" (i.e., SB2 sprite) format. - * @param {object} sprite Object representing 2.0 sprite to be added. - * @param {?ArrayBuffer} zip Optional zip of assets being referenced by json - * @param {?boolean} isRemoteOperation Whether to change editing target - * @returns {Promise} Promise that resolves after the sprite is added - */ - _addSprite2( - sprite: object, - zip: ArrayBuffer | null, - isRemoteOperation: boolean | null - ): Promise; - /** - * Add a single sb3 sprite. - * @param {object} sprite Object rperesenting 3.0 sprite to be added. - * @param {?ArrayBuffer} zip Optional zip of assets being referenced by target json - * @param {?boolean} isRemoteOperation Whether to change editing target - * @returns {Promise} Promise that resolves after the sprite is added - */ - _addSprite3( - sprite: object, - zip: ArrayBuffer | null, - isRemoteOperation: boolean | null - ): Promise; - /** - * Add a costume to the current editing target. - * @param {string} md5ext - the MD5 and extension of the costume to be loaded. - * @param {!object} costumeObject Object representing the costume. - * @param {string} target - the target to add to. - * @param {?int} index Index at which to add costume - * @returns {?Promise} - a promise that resolves when the costume has been added - */ - addCostumeFromRemote( - md5ext: string, - costumeObject: object, - target: string, - index: int | null - ): Promise | null; - /** - * Add a costume to the current editing target. - * @param {string} md5ext - the MD5 and extension of the costume to be loaded. - * @param {!object} costumeObject Object representing the costume. - * @property {int} skinId - the ID of the costume's render skin, once installed. - * @property {number} rotationCenterX - the X component of the costume's origin. - * @property {number} rotationCenterY - the Y component of the costume's origin. - * @property {number} [bitmapResolution] - the resolution scale for a bitmap costume. - * @param {string} optTargetId - the id of the target to add to, if not the editing target. - * @param {string} optVersion - if this is 2, load costume as sb2, otherwise load costume as sb3. - * @param {boolean} isRemoteOperation Whether this is a remote operation. - * @returns {?Promise} - a promise that resolves when the costume has been added - */ - addCostume( - md5ext: string, - costumeObject: object, - optTargetId: string, - optVersion: string, - isRemoteOperation: boolean - ): Promise | null; - /** - * Add a costume loaded from the library to the current editing target. - * @param {string} md5ext - the MD5 and extension of the costume to be loaded. - * @param {!object} costumeObject Object representing the costume. - * @property {int} skinId - the ID of the costume's render skin, once installed. - * @property {number} rotationCenterX - the X component of the costume's origin. - * @property {number} rotationCenterY - the Y component of the costume's origin. - * @property {number} [bitmapResolution] - the resolution scale for a bitmap costume. - * @returns {?Promise} - a promise that resolves when the costume has been added - */ - addCostumeFromLibrary( - md5ext: string, - costumeObject: object - ): Promise | null; - /** - * Duplicate the costume at the given index. Add it at that index + 1. - * @param {!int} costumeIndex Index of costume to duplicate - * @returns {?Promise} - a promise that resolves when the costume has been decoded and added - */ - duplicateCostume(costumeIndex: int): Promise | null; - /** - * Duplicate the sound at the given index. Add it at that index + 1. - * @param {!int} soundIndex Index of sound to duplicate - * @returns {?Promise} - a promise that resolves when the sound has been decoded and added - */ - duplicateSound(soundIndex: int): Promise | null; - /** - * Rename a costume on the current editing target. - * @param {int} costumeIndex - the index of the costume to be renamed. - * @param {string} newName - the desired new name of the costume (will be modified if already in use). - */ - renameCostume(costumeIndex: int, newName: string): void; - /** - * Delete a costume from the current editing target. - * @param {int} costumeIndex - the index of the costume to be removed. - * @return {?function} A function to restore the deleted costume, or null, - * if no costume was deleted. - */ - deleteCostume(costumeIndex: int): Function | null; - /** - * Add a sound to the current editing target. - * @param {!object} soundObject Object representing the sound. - * @param {string} optTargetId - the id of the target to add to, if not the editing target. - * @returns {?Promise} - a promise that resolves when the sound has been decoded and added - */ - addSound(soundObject: object, optTargetId: string): Promise | null; - /** - * Rename a sound on the current editing target. - * @param {int} soundIndex - the index of the sound to be renamed. - * @param {string} newName - the desired new name of the sound (will be modified if already in use). - */ - renameSound(soundIndex: int, newName: string): void; - /** - * Get a sound buffer from the audio engine. - * @param {int} soundIndex - the index of the sound to be got. - * @return {AudioBuffer} the sound's audio buffer. - */ - getSoundBuffer(soundIndex: int): AudioBuffer; - /** - * Sets a configuration property in the Gandi runtime. - * - * @param {string} key - The key of the configuration property to set. - * @param value - The value to set for the configuration property. - */ - setGandiConfigProperty(key: string, value: any): void; - /** - * Gets a configuration property from the Gandi runtime. - * - * @param {string} key - The key of the configuration property to retrieve. - * @returns The value of the configuration property. - */ - getGandiConfigProperty(key: string): any; - getMonitoredKeys(): any[]; - /** - * Updates global procedure call mutations in the project. - * - * @param {string} oldProccode - The old procedure code to be replaced. - * @param {string} newMutationText - The new mutation text to replace the old mutation. - * @returns {void} - */ - updateGlobalProcedureCallMutation( - oldProccode: string, - newMutationText: string - ): void; - /** - * Update a sound buffer. - * @param {int} soundIndex - the index of the sound to be updated. - * @param {AudioBuffer} newBuffer - new audio buffer for the audio engine. - * @param {ArrayBuffer} soundEncoding - the new (wav) encoded sound to be stored - * @param {string} targetId - the id of the target to be updated. - */ - updateSoundBuffer( - soundIndex: int, - newBuffer: AudioBuffer, - soundEncoding: ArrayBuffer, - targetId: string - ): void; - /** - * Delete a sound from the current editing target. - * @param {int} soundIndex - the index of the sound to be removed. - * @return {?Function} A function to restore the sound that was deleted, - * or null, if no sound was deleted. - */ - deleteSound(soundIndex: int): Function | null; - /** - * Get a string representation of the image from storage. - * @param {int} costumeIndex - the index of the costume to be got. - * @return {string} the costume's SVG string if it's SVG, - * a dataURI if it's a PNG or JPG, or null if it couldn't be found or decoded. - */ - getCostume(costumeIndex: int): string; - updateCostumeById(target: any, id: any, newCostume: any): void; - updateSoundById(target: any, id: any, newSound: any): void; - /** - * TW: Get the raw binary data to use when exporting a costume to the user's local file system. - * @param {Costume} costumeObject scratch-vm costume object - * @returns {Uint8Array} - */ - getExportedCostume(costumeObject: Costume): Uint8Array; - /** - * TW: Get a base64 string to use when exporting a costume to the user's local file system. - * @param {Costume} costumeObject scratch-vm costume object - * @returns {string} base64 string. Not a data: URI. - */ - getExportedCostumeBase64(costumeObject: Costume): string; - /** - * Update a costume with the given bitmap - * @param {!int} costumeIndex - the index of the costume to be updated. - * @param {!ImageData} bitmap - new bitmap for the renderer. - * @param {!number} rotationCenterX x of point about which the costume rotates, relative to its upper left corner - * @param {!number} rotationCenterY y of point about which the costume rotates, relative to its upper left corner - * @param {!number} bitmapResolution 1 for bitmaps that have 1 pixel per unit of stage, - * 2 for double-resolution bitmaps - * @param {string} targetId ID of a target. - */ - updateBitmap( - costumeIndex: int, - bitmap: ImageData, - rotationCenterX: number, - rotationCenterY: number, - bitmapResolution: number - ): void; - _updateBitmap( - costume: any, - bitmap: any, - rotationCenterX: any, - rotationCenterY: any, - bitmapResolution: any - ): void; - /** - * Update a costume with the given SVG - * @param {int} costumeIndex - the index of the costume to be updated. - * @param {string} svg - new SVG for the renderer. - * @param {number} rotationCenterX x of point about which the costume rotates, relative to its upper left corner - * @param {number} rotationCenterY y of point about which the costume rotates, relative to its upper left corner - * @param {string} targetId ID of a target. - */ - updateSvg( - costumeIndex: int, - svg: string, - rotationCenterX: number, - rotationCenterY: number, - targetId: string - ): void; - _updateSvg( - costume: any, - svg: any, - rotationCenterX: any, - rotationCenterY: any, - targetId: any - ): void; - /** - * Update a Gandi asset with the value - * @param {string} assetMd5 - the md5 of the asset to be updated. - * @param {string} newValue - new Value for the asset. - */ - updateGandiAssetData(fileName: any, newValue: string): void; - updateGandiAssetFromRemote(id: any, newAsset: any): void; - addGandiAssetFromRemote(id: any, newAsset: any): void; - deleteGandiAssetFromRemote(id: any): void; - /** - * rename a Gandi asset - * @param {string} id - The id of the asset to rename. - * @param {string} newName - new name for the asset. - */ - renameGandiAssetById(id: string, newName: string): any; - /** - * Delete a sprite and all its clones. - * @param {string} fileName name of a asset. - */ - deleteGandiAsset(fileName: string): void; - /** - * Delete a file from the Gandi assets. - * @param {string} id The id of the asset to delete. - */ - deleteGandiAssetById(id: string): void; - /** - * Add a backdrop to the stage. - * @param {string} md5ext - the MD5 and extension of the backdrop to be loaded. - * @param {!object} backdropObject Object representing the backdrop. - * @property {int} skinId - the ID of the backdrop's render skin, once installed. - * @property {number} rotationCenterX - the X component of the backdrop's origin. - * @property {number} rotationCenterY - the Y component of the backdrop's origin. - * @property {number} [bitmapResolution] - the resolution scale for a bitmap backdrop. - * @returns {?Promise} - a promise that resolves when the backdrop has been added - */ - addBackdrop(md5ext: string, backdropObject: object): Promise | null; - /** - * Rename a sprite. - * @param {string} targetId ID of a target whose sprite to rename. - * @param {string} newName New name of the sprite. - * @param {boolean} [sendNameChangedEvent = true] whether to send an event when the sprite name changes. - */ - renameSprite( - targetId: string, - newName: string, - sendNameChangedEvent?: boolean - ): void; - /** - * Delete a sprite and all its clones. - * @param {string} targetId ID of a target whose sprite to delete. - * @param {boolean} isRemoteOperation Whether this is a remote operation. - * @return {Function} Returns a function to restore the sprite that was deleted - */ - deleteSprite(targetId: string, isRemoteOperation: boolean): Function; - /** - * Duplicate a sprite. - * @param {string} targetId ID of a target whose sprite to duplicate. - * @returns {Promise} Promise that resolves when duplicated target has - * been added to the runtime. - */ - duplicateSprite(targetId: string): Promise; - /** - * Set the audio engine for the VM/runtime - * @param {!AudioEngine} audioEngine The audio engine to attach - */ - attachAudioEngine(audioEngine: AudioEngine): void; - /** - * Set the renderer for the VM/runtime - * @param {!RenderWebGL} renderer The renderer to attach - */ - attachRenderer(renderer: RenderWebGL): void; - /** - * @returns {RenderWebGL} The renderer attached to the vm - */ - get renderer(): RenderWebGL; - attachV2SVGAdapter(): void; - /** - * Set the bitmap adapter for the VM/runtime, which converts scratch 2 - * bitmaps to scratch 3 bitmaps. (Scratch 3 bitmaps are all bitmap resolution 2) - * @param {!function} bitmapAdapter The adapter to attach - */ - attachV2BitmapAdapter(bitmapAdapter: Function): void; - /** - * Set the storage module for the VM/runtime - * @param {!ScratchStorage} storage The storage module to attach - */ - attachStorage(storage: ScratchStorage): void; - /** - * set the current locale and builtin messages for the VM - * @param {!string} locale current locale - * @param {!object} messages builtin messages map for current locale - * @returns {Promise} Promise that resolves when all the blocks have been - * updated for a new locale (or empty if locale hasn't changed.) - */ - setLocale(locale: string, messages: object): Promise; - /** - * get the current locale for the VM - * @returns {string} the current locale in the VM - */ - getLocale(): string; - /** - * Delete all of the flyout blocks. - */ - clearFlyoutBlocks(): void; - /** - * Set an editing target. An editor UI can use this function to switch - * between editing different targets, sprites, etc. - * After switching the editing target, the VM may emit updates - * to the list of targets and any attached workspace blocks - * (see `emitTargetsUpdate` and `emitWorkspaceUpdate`). - * @param {string} targetId Id of target to set as editing. - */ - setEditingTarget(targetId: string): void; - /** - * @param {Block[]} blockObjects - * @returns {object} - */ - exportStandaloneBlocks(blockObjects: Block[]): object; - /** - * Called when blocks are dragged from one sprite to another. Adds the blocks to the - * workspace of the given target. - * @param {!Array} blocks Blocks to add. - * @param {!string} targetId Id of target to add blocks to. - * @param {?string} optFromTargetId Optional target id indicating that blocks are being - * shared from that target. This is needed for resolving any potential variable conflicts. - * @return {!Promise} Promise that resolves when the extensions and blocks have been added. - */ - shareBlocksToTarget( - blocks: Array, - targetId: string, - optFromTargetId: string | null - ): Promise; - /** - * Called when frame are dragged from one sprite to another. Adds the frame to the - * workspace of the given target. - * @param {!Array} frame Frame to add. - * @param {!string} targetId Id of target to add frame to. - * @param {?string} optFromTargetId Optional target id indicating that frame are being - * shared from that target. This is needed for resolving any potential variable conflicts. - * @return {!Promise} Promise that resolves when the extensions and frame have been added. - */ - shareFrameToTarget( - frame: Array, - targetId: string, - optFromTargetId: string | null - ): Promise; - /** - * Called when costumes are dragged from editing target to another target. - * Sets the newly added costume as the current costume. - * @param {!number} costumeIndex Index of the costume of the editing target to share. - * @param {!string} targetId Id of target to add the costume. - * @return {Promise} Promise that resolves when the new costume has been loaded. - */ - shareCostumeToTarget(costumeIndex: number, targetId: string): Promise; - /** - * Called when sounds are dragged from editing target to another target. - * @param {!number} soundIndex Index of the sound of the editing target to share. - * @param {!string} targetId Id of target to add the sound. - * @return {Promise} Promise that resolves when the new sound has been loaded. - */ - shareSoundToTarget(soundIndex: number, targetId: string): Promise; - /** - * Repopulate the workspace with the blocks of the current editingTarget. This - * allows us to get around bugs like gui#413. - */ - refreshWorkspace(): void; - /** - * Emit metadata about available targets. - * An editor UI could use this to display a list of targets and show - * the currently editing one. - * @param {boolean} triggerProjectChange If true, also emit a project changed event. - * Disabled selectively by updates that don't affect project serialization. - * Defaults to true. - */ - emitTargetsUpdate( - triggerProjectChange: boolean | undefined, - updatedTargets: any - ): void; - /** - * Emit an Blockly/scratch-blocks compatible XML representation - * of the current editing target's blocks. - */ - emitWorkspaceUpdate(): void; - /** - * Emit metadata about Gandi assets file. - * An editor UI could use this to display a list of files and show - * the currently editing one. - * @param {{data:object, type: 'add'|'update'|'delete', isFromRemote:bool}} action If true, also emit a project changed event. - * Defaults to true. - */ - emitGandiAssetsUpdate({ - data, - type, - }: { - data: object; - type: "add" | "update" | "delete"; - isFromRemote: bool; - }): void; - /** - * Get a target id for a drawable id. Useful for interacting with the renderer - * @param {number} drawableId The drawable id to request the target id for - * @returns {?string} The target id, if found. Will also be null if the target found is the stage. - */ - getTargetIdForDrawableId(drawableId: number): string | null; - /** - * CCW: Get all global procedures and pass to target - * @returns {Array} Array of XML strings - */ - getWorkspaceGlobalProcedures(): any[]; - /** - * Reorder target by index. Return whether a change was made. - * @param {!string} targetIndex Index of the target. - * @param {!number} newIndex index that the target should be moved to. - * @param {!boolean} isRemoteOperation - set to true if this is a remote operation - * @returns {boolean} Whether a target was reordered. - */ - reorderTarget( - targetIndex: string, - newIndex: number, - isRemoteOperation: boolean - ): boolean; - /** - * Reorder the costumes of a target if it exists. Return whether it succeeded. - * @param {!string} targetId ID of the target which owns the costumes. - * @param {!number} costumeIndex index of the costume to move. - * @param {!number} newIndex index that the costume should be moved to. - * @returns {boolean} Whether a costume was reordered. - */ - reorderCostume( - targetId: string, - costumeIndex: number, - newIndex: number - ): boolean; - /** - * Reorder the sounds of a target if it exists. Return whether it occured. - * @param {!string} targetId ID of the target which owns the sounds. - * @param {!number} soundIndex index of the sound to move. - * @param {!number} newIndex index that the sound should be moved to. - * @returns {boolean} Whether a sound was reordered. - */ - reorderSound( - targetId: string, - soundIndex: number, - newIndex: number - ): boolean; - /** - * Put a target into a "drag" state, during which its X/Y positions will be unaffected - * by blocks. - * @param {string} targetId The id for the target to put into a drag state - */ - startDrag(targetId: string): void; - /** - * Remove a target from a drag state, so blocks may begin affecting X/Y position again - * @param {string} targetId The id for the target to remove from the drag state - */ - stopDrag(targetId: string): void; - /** - * Post/edit sprite info for the current editing target or the drag target. - * @param {object} data An object with sprite info data to set. - * @param {?string} targetId The id for the target to set info. - */ - postSpriteInfo(data: object, targetId: string | null): void; - /** - * Set a target's variable's value. Return whether it succeeded. - * @param {!string} targetId ID of the target which owns the variable. - * @param {!string} variableId ID of the variable to set. - * @param {!*} value The new value of that variable. - * @returns {boolean} whether the target and variable were found and updated. - */ - setVariableValue(targetId: string, variableId: string, value: any): boolean; - /** - * Get a target's variable's value. Return null if the target or variable does not exist. - * @param {!string} targetId ID of the target which owns the variable. - * @param {!string} variableId ID of the variable to set. - * @returns {?*} The value of the variable, or null if it could not be looked up. - */ - getVariableValue(targetId: string, variableId: string): any | null; - /** - * Allow VM consumer to configure the ScratchLink socket creator. - * @param {Function} factory The custom ScratchLink socket factory. - */ - configureScratchLinkSocketFactory(factory: Function): void; - /** - * Adapts a given XML element for blocks or frames. - * - * @param {Element} xml - The XML element to be adapted. - * @returns {Array. | null} A list of block or frame from the adapted XML. - */ - xmlAdapter(xml: Element): Array | null; - } - // namespace VirtualMachine { - // export { Progress }; - // } - import EventEmitter = require("events"); - type Runtime = import("scratch-vm-dts/engine/runtime"); - type ExtensionManager = import("scratch-vm-dts/extension-support/extension-manager"); - type Sprite = import("scratch-vm-dts/sprites/sprite"); - type RenderedTarget = import("scratch-vm-dts/sprites/rendered-target"); - import JSZip = require("@turbowarp/jszip"); - /** - * - Information about the loading progress - */ - type Progress = { - /** - * - The total number of loaded things - */ - total: number; - /** - * - The number of loads completed - */ - loaded: number; - }; -} -//以下代码未被打包器载入,为手动编写 -declare module "scratch-vm-dts/compiler/jsgen" { - export = JSGenerator; - type Target = import("scratch-vm-dts/engine/target"); - class JSGenerator { - /** - * @param {IntermediateScript} script - * @param {IntermediateRepresentation} ir - * @param {Target} target - */ - constructor( - script: IntermediateScript, - ir: IntermediateRepresentation, - target: Target - ); - script: IntermediateScript; - ir: IntermediateRepresentation; - target: Target; - source: string; - /** - * @type {Object.} - */ - variableInputs: { - [x: string]: VariableInput; - }; - isWarp: boolean; - isProcedure: boolean; - warpTimer: boolean; - /** - * Stack of frames, most recent is last item. - * @type {Frame[]} - */ - frames: Frame[]; - /** - * The current Frame. - * @type {Frame} - */ - currentFrame: Frame; - namesOfCostumesAndSounds: Set; - localVariables: VariablePool; - _setupVariablesPool: VariablePool; - _setupVariables: {}; - descendedIntoModulo: boolean; - isInHat: boolean; - debug: any; - /** - * Enter a new frame - * @param {Frame} frame New frame. - */ - pushFrame(frame: Frame): void; - /** - * Exit the current frame - */ - popFrame(): void; - /** - * @returns {boolean} true if the current block is the last command of a loop - */ - isLastBlockInLoop(): boolean; - /** - * @param {object} node Input node to compile. - * @returns {Input} Compiled input. - */ - descendInput(node: object): Input; - /** - * @param {*} node Stacked node to compile. - */ - descendStackedBlock(node: any): TypedInput | undefined; - /** - * Compile a Record of input objects into a safe JS string. - * @param {Record} inputs - * @returns {string} - */ - descendInputRecord(inputs: Record): string; - resetVariableInputs(): void; - descendStack(nodes: any, frame: any): void; - descendVariable(variable: any): VariableInput; - descendProcedure(node: any): string | undefined; - referenceVariable(variable: any): any; - descendAddonCall(node: any): string; - evaluateOnce(source: any): any; - retire(): void; - stopScript(): void; - stopScript(): void; - /** - * @param {string} valueJS JS code of value to return. - */ - stopScriptAndReturn(valueJS: string): void; - /** - * @param {string} valueJS JS code of value to return. - */ - stopScriptAndReturn(valueJS: string): void; - yieldLoop(): void; - /** - * Write JS to yield the current thread if warp mode is disabled. - */ - yieldNotWarp(): void; - /** - * Write JS to yield the current thread if warp mode is disabled or if the script seems to be stuck. - */ - yieldStuckOrNotWarp(): void; - yielded(): void; - /** - * Write JS to request a redraw. - */ - requestRedraw(): void; - safeConstantInput(value: any): ConstantInput; - /** - * Generate a call into the compatibility layer. - * @param {*} node The "compat" kind node to generate from. - * @param {boolean} setFlags Whether flags should be set describing how this function was processed. - * @param {string|null} [frameName] Name of the stack frame variable, if any - * @returns {string} The JS of the call. - */ - generateCompatibilityLayerCall( - node: any, - setFlags: boolean, - frameName?: string | null - ): string; - getScriptFactoryName(): string; - getScriptName(yields: any): string; - /** - * Generate the JS to pass into eval() based on the current state of the compiler. - * @returns {string} JS to pass into eval() - */ - createScriptFactory(): string; - /** - * Compile this script. - * @returns {Function} The factory function for the script. - */ - compile(): Function; - } - namespace JSGenerator { - export { unstable_exports, testingApparatus, Input }; - } - type IntermediateScript = - import("scratch-vm-dts/compiler/intermediate").IntermediateScript; - type IntermediateRepresentation = - import("scratch-vm-dts/compiler/intermediate").IntermediateRepresentation; - /** - * @implements {Input} - */ - class VariableInput implements Input { - constructor(source: any); - source: any; - type: number; - /** - * The value this variable was most recently set to, if any. - * @type {Input} - * @private - */ - private _value; - /** - * @param {Input} input The input this variable was most recently set to. - */ - setInput(input: Input): void; - asNumber(): any; - asNumberOrNaN(): any; - asString(): any; - asBoolean(): any; - asColor(): any; - asUnknown(): any; - asSafe(): any; - isAlwaysNumber(): boolean; - isAlwaysNumberOrNaN(): boolean; - isNeverNumber(): boolean; - } - /** - * A frame contains some information about the current substack being compiled. - */ - class Frame { - constructor(isLoop: any); - /** - * Whether the current stack runs in a loop (while, for) - * @type {boolean} - * @readonly - */ - readonly isLoop: boolean; - /** - * Whether the current block is the last block in the stack. - * @type {boolean} - */ - isLastBlock: boolean; - } - type VariablePool = import("scratch-vm-dts/compiler/variable-pool"); - /** - * @typedef Input - * @property {() => string} asNumber - * @property {() => string} asNumberOrNaN - * @property {() => string} asString - * @property {() => string} asBoolean - * @property {() => string} asColor - * @property {() => string} asUnknown - * @property {() => string} asSafe - * @property {() => boolean} isAlwaysNumber - * @property {() => boolean} isAlwaysNumberOrNaN - * @property {() => boolean} isNeverNumber - */ - /** - * @implements {Input} - */ - class TypedInput implements Input { - constructor(source: any, type: any); - source: any; - type: number; - asNumber(): any; - asNumberOrNaN(): any; - asString(): any; - asBoolean(): any; - asColor(): any; - asUnknown(): any; - asSafe(): any; - asProcedureReturn(): string; - isAlwaysNumber(): boolean; - isAlwaysNumberOrNaN(): boolean; - isNeverNumber(): boolean; - } - /** - * @implements {Input} - */ - class ConstantInput implements Input { - constructor(constantValue: any, safe: any); - constantValue: any; - safe: any; - asNumber(): string; - asNumberOrNaN(): string; - asString(): string; - asBoolean(): string; - asColor(): any; - asUnknown(): any; - asSafe(): any; - isAlwaysNumber(): boolean; - isAlwaysNumberOrNaN(): boolean; - isNeverNumber(): boolean; - } - namespace unstable_exports { - export { TYPE_NUMBER }; - export { TYPE_STRING }; - export { TYPE_BOOLEAN }; - export { TYPE_UNKNOWN }; - export { TYPE_NUMBER_NAN }; - export { factoryNameVariablePool }; - export { functionNameVariablePool }; - export { generatorNameVariablePool }; - export { VariablePool }; - export { PEN_EXT }; - export { PEN_STATE }; - export { TypedInput }; - export { ConstantInput }; - export { VariableInput }; - export { Frame }; - export { sanitize }; - } - var testingApparatus: any; - type Input = { - asNumber: () => string; - asNumberOrNaN: () => string; - asString: () => string; - asBoolean: () => string; - asColor: () => string; - asUnknown: () => string; - asSafe: () => string; - isAlwaysNumber: () => boolean; - isAlwaysNumberOrNaN: () => boolean; - isNeverNumber: () => boolean; - }; - const TYPE_NUMBER: 1; - const TYPE_STRING: 2; - const TYPE_BOOLEAN: 3; - const TYPE_UNKNOWN: 4; - const TYPE_NUMBER_NAN: 5; - /** - * Variable pool used for factory function names. - */ - const factoryNameVariablePool: VariablePool; - /** - * Variable pool used for generated functions (non-generator) - */ - const functionNameVariablePool: VariablePool; - /** - * Variable pool used for generated generator functions. - */ - const generatorNameVariablePool: VariablePool; - const PEN_EXT: "runtime.ext_pen"; - const PEN_STATE: "runtime.ext_pen._getPenState(target)"; - /** - * @fileoverview Convert intermediate representations to JavaScript functions. - */ - function sanitize(string: any): string; -} - -declare module "scratch-vm-dts/compiler/intermediate" { - /** - * @fileoverview Common intermediates shared amongst parts of the compiler. - */ - /** - * An IntermediateScript describes a single script. - * Scripts do not necessarily have hats. - */ - type Target = import("scratch-vm-dts/engine/target"); - export class IntermediateScript { - /** - * The ID of the top block of this script. - * @type {string} - */ - topBlockId: string; - /** - * List of nodes that make up this script. - * @type {Array|null} - */ - stack: any[] | null; - /** - * Whether this script is a procedure. - * @type {boolean} - */ - isProcedure: boolean; - /** - * This procedure's variant, if any. - * @type {string} - */ - procedureVariant: string; - /** - * This procedure's code, if any. - * @type {string} - */ - procedureCode: string; - /** - * List of names of arguments accepted by this function, if it is a procedure. - * @type {string[]} - */ - arguments: string[]; - /** - * Whether this script should be run in warp mode. - * @type {boolean} - */ - isWarp: boolean; - /** - * Whether this script can `yield` - * If false, this script will be compiled as a regular JavaScript function (function) - * If true, this script will be compiled as a generator function (function*) - * @type {boolean} - */ - yields: boolean; - /** - * Whether this script should use the "warp timer" - * @type {boolean} - */ - warpTimer: boolean; - /** - * List of procedure IDs that this script needs. - * @readonly - */ - readonly dependedProcedures: any[]; - /** - * Cached result of compiling this script. - * @type {Function|null} - */ - cachedCompileResult: Function | null; - /** - * global procedure target - * @type {Target|null} - */ - target: Target | null; - /** - * Whether the top block of this script is an executable hat. - * @type {boolean} - */ - executableHat: boolean; - } - /** - * An IntermediateRepresentation contains scripts. - */ - export class IntermediateRepresentation { - /** - * The entry point of this IR. - * @type {IntermediateScript} - */ - entry: IntermediateScript; - /** - * Maps procedure variants to their intermediate script. - * @type {Object.} - */ - procedures: { - [x: string]: IntermediateScript; - }; - } -} - -declare module "scratch-vm-dts/compiler/variable-pool" { - export = VariablePool; - class VariablePool { - /** - * @param {string} prefix The prefix at the start of the variable name. - */ - constructor(prefix: string); - prefix: string; - /** - * @private - */ - private count; - next(): string; - } -} - -declare module "scratch-vm-dts/compiler/irgen" { - class Block { } - export type Node = { - [x: string]: any; - }; - export class ScriptTreeGenerator { - constructor(thread: any); - /** @private */ - private thread; - /** @private */ - private target; - /** @private */ - private blocks; - /** @private */ - private runtime; - /** @private */ - private stage; - /** - * This script's intermediate representation. - */ - script: IntermediateScript; - /** - * Cache of variable ID to variable data object. - * @type {Object.} - * @private - */ - private variableCache: { [key: string]: object }; - usesTimer: boolean; - setProcedureVariant(procedureVariant: any, globalTarget: any): void; - enableWarp(): void; - getBlockById(blockId: any): any; - getBlockInfo(fullOpcode: any): any; - /** - * Descend into a child input of a block. (eg. the input STRING of "length of ( )") - * @param {*} parentBlock The parent Scratch block that contains the input. - * @param {string} inputName The name of the input to descend into. - * @private - * @returns {Node} Compiled input node for this input. - */ - private descendInputOfBlock; - /** - * Descend into an input. (eg. "length of ( )") - * @param {*} block The parent Scratch block input. - * @private - * @returns {Node} Compiled input node for this input. - */ - private descendInput; - /** - * Descend into a stacked block. (eg. "move ( ) steps") - * @param {*} block The Scratch block to parse. - * @private - * @returns {Node} Compiled node for this block. - */ - private descendStackedBlock; - /** - * Descend into a stack of blocks (eg. the blocks contained within an "if" block) - * @param {*} parentBlock The parent Scratch block that contains the stack to parse. - * @param {*} substackName The name of the stack to descend into. - * @private - * @returns {Node[]} List of stacked block nodes. - */ - private descendSubstack; - /** - * Descend into and walk the siblings of a stack. - * @param {string} startingBlockId The ID of the first block of a stack. - * @private - * @returns {Node[]} List of stacked block nodes. - */ - private walkStack; - /** - * Descend into a variable. - * @param {*} block The block that has the variable. - * @param {string} fieldName The name of the field that the variable is stored in. - * @param {''|'list'} type Variable type, '' for scalar and 'list' for list. - * @private - * @returns {*} A parsed variable object. - */ - private descendVariable; - /** - * @param {string} id The ID of the variable. - * @param {string} name The name of the variable. - * @param {''|'list'} type The variable type. - * @private - * @returns {*} A parsed variable object. - */ - private _descendVariable; - descendProcedure(block: any): - | { - kind: string; - code?: undefined; - arguments?: undefined; - blockId?: undefined; - variant?: undefined; - } - | { - kind: string; - code: any; - arguments: {}; - blockId: any; - variant?: undefined; - } - | { - kind: string; - code: any; - variant: string; - arguments: { - [x: string]: any; - }[]; - blockId?: undefined; - }; - /** - * Descend into a block that uses the compatibility layer. - * @param {*} block The block to use the compatibility layer for. - * @private - * @returns {Node} The parsed node. - */ - private descendCompatLayer; - analyzeLoop(): void; - readTopBlockComment(commentId: any): void; - descendVisualReport(block: any): { - kind: string; - input: { - [x: string]: any; - }; - } | null; - /** - * @param {Block} hatBlock - */ - walkHat(hatBlock: Block): { - [x: string]: any; - }[]; - /** - * @param {string} topBlockId The ID of the top block of the script. - * @returns {IntermediateScript} - */ - generate(topBlockId: string): IntermediateScript; - } - export class IRGenerator { - constructor(thread: any); - thread: any; - blocks: any; - proceduresToCompile: Map; - compilingProcedures: Map; - /** @type {Object.} */ - procedures: { - [x: string]: IntermediateScript; - }; - analyzedProcedures: any[]; - getProcedureDefinitionAndTarget(procedureCode: any): any; - addProcedureDependencies(dependencies: any): void; - /** - * @param {ScriptTreeGenerator} generator The generator to run. - * @param {string} topBlockId The ID of the top block in the stack. - * @returns {IntermediateScript} Intermediate script. - */ - generateScriptTree( - generator: ScriptTreeGenerator, - topBlockId: string - ): IntermediateScript; - /** - * Recursively analyze a script and its dependencies. - * @param {IntermediateScript} script Intermediate script. - */ - analyzeScript(script: IntermediateScript): boolean; - /** - * @returns {IntermediateRepresentation} Intermediate representation. - */ - generate(): IntermediateRepresentation; - } - type IntermediateScript = - import("scratch-vm-dts/compiler/intermediate").IntermediateScript; - type IntermediateRepresentation = - import("scratch-vm-dts/compiler/intermediate").IntermediateRepresentation; -} - -declare module "scratch-vm-dts/extensions/scratch3_pen" { - export = Scratch3PenBlocks; - type Runtime = import("scratch-vm-dts/engine/runtime"); - class PenAttributes { } - /** - * @typedef {object} PenState - the pen state associated with a particular target. - * @property {Boolean} penDown - tracks whether the pen should draw for this target. - * @property {number} color - the current color (hue) of the pen. - * @property {PenAttributes} penAttributes - cached pen attributes for the renderer. This is the authoritative value for - * diameter but not for pen color. - */ - /** - * Host for the Pen-related blocks in Scratch 3.0 - * @param {Runtime} runtime - the runtime instantiating this block package. - * @constructor - */ - class Scratch3PenBlocks { - /** - * The default pen state, to be used when a target has no existing pen state. - * @type {PenState} - */ - static get DEFAULT_PEN_STATE(): PenState; - /** - * The minimum and maximum allowed pen size. - * The maximum is twice the diagonal of the stage, so that even an - * off-stage sprite can fill it. - * @type {{min: number, max: number}} - */ - static get PEN_SIZE_RANGE(): { - min: number; - max: number; - }; - /** - * The key to load & store a target's pen-related state. - * @type {string} - */ - static get STATE_KEY(): string; - constructor(runtime: any); - /** - * The runtime instantiating this block package. - * @type {Runtime} - */ - runtime: Runtime; - /** - * The ID of the renderer Drawable corresponding to the pen layer. - * @type {int} - * @private - */ - private _penDrawableId; - /** - * The ID of the renderer Skin corresponding to the pen layer. - * @type {int} - * @private - */ - private _penSkinId; - /** - * When a pen-using Target is cloned, clone the pen state. - * @param {Target} newTarget - the newly created target. - * @param {Target} [sourceTarget] - the target used as a source for the new clone, if any. - * @listens Runtime#event:targetWasCreated - * @private - */ - private _onTargetCreated; - /** - * Handle a target which has moved. This only fires when the pen is down. - * @param {RenderedTarget} target - the target which has moved. - * @param {number} oldX - the previous X position. - * @param {number} oldY - the previous Y position. - * @param {boolean} isForce - whether the movement was forced. - * @private - */ - private _onTargetMoved; - /** - * Clamp a pen size value to the range allowed by the pen. - * @param {number} requestedSize - the requested pen size. - * @returns {number} the clamped size. - * @private - */ - private _clampPenSize; - /** - * Retrieve the ID of the renderer "Skin" corresponding to the pen layer. If - * the pen Skin doesn't yet exist, create it. - * @returns {int} the Skin ID of the pen layer, or -1 on failure. - * @private - */ - private _getPenLayerID; - /** - * @param {Target} target - collect pen state for this target. Probably, but not necessarily, a RenderedTarget. - * @returns {PenState} the mutable pen state associated with that target. This will be created if necessary. - * @private - */ - private _getPenState; - /** - * Wrap a color input into the range (0,100). - * @param {number} value - the value to be wrapped. - * @returns {number} the wrapped value. - * @private - */ - private _wrapColor; - /** - * Initialize color parameters menu with localized strings - * @returns {array} of the localized text and values for each menu element - * @private - */ - private _initColorParam; - /** - * Clamp a pen color parameter to the range (0,100). - * @param {number} value - the value to be clamped. - * @returns {number} the clamped value. - * @private - */ - private _clampColorParam; - /** - * Convert an alpha value to a pen transparency value. - * Alpha ranges from 0 to 1, where 0 is transparent and 1 is opaque. - * Transparency ranges from 0 to 100, where 0 is opaque and 100 is transparent. - * @param {number} alpha - the input alpha value. - * @returns {number} the transparency value. - * @private - */ - private _alphaToTransparency; - /** - * Convert a pen transparency value to an alpha value. - * Alpha ranges from 0 to 1, where 0 is transparent and 1 is opaque. - * Transparency ranges from 0 to 100, where 0 is opaque and 100 is transparent. - * @param {number} transparency - the input transparency value. - * @returns {number} the alpha value. - * @private - */ - private _transparencyToAlpha; - /** - * @returns {object} metadata for this extension and its blocks. - */ - getInfo(): object; - /** - * The pen "clear" block clears the pen layer's contents. - */ - clear(): void; - /** - * The pen "stamp" block stamps the current drawable's image onto the pen layer. - * @param {object} args - the block arguments. - * @param {object} util - utility object provided by the runtime. - */ - stamp(args: object, util: object): void; - _stamp(target: any): void; - /** - * The pen "pen down" block causes the target to leave pen trails on future motion. - * @param {object} args - the block arguments. - * @param {object} util - utility object provided by the runtime. - */ - penDown(args: object, util: object): void; - _penDown(target: any): void; - /** - * The pen "pen up" block stops the target from leaving pen trails. - * @param {object} args - the block arguments. - * @param {object} util - utility object provided by the runtime. - */ - penUp(args: object, util: object): void; - _penUp(target: any): void; - /** - * The pen "set pen color to {color}" block sets the pen to a particular RGB color. - * The transparency is reset to 0. - * @param {object} args - the block arguments. - * @property {int} COLOR - the color to set, expressed as a 24-bit RGB value (0xRRGGBB). - * @param {object} util - utility object provided by the runtime. - */ - setPenColorToColor(args: object, util: object): void; - _setPenColorToColor(color: any, target: any): void; - /** - * Update the cached color from the color, saturation, brightness and transparency values - * in the provided PenState object. - * @param {PenState} penState - the pen state to update. - * @private - */ - private _updatePenColor; - /** - * Set or change a single color parameter on the pen state, and update the pen color. - * @param {ColorParam} param - the name of the color parameter to set or change. - * @param {number} value - the value to set or change the param by. - * @param {PenState} penState - the pen state to update. - * @param {boolean} change - if true change param by value, if false set param to value. - * @private - */ - private _setOrChangeColorParam; - /** - * The "change pen {ColorParam} by {number}" block changes one of the pen's color parameters - * by a given amound. - * @param {object} args - the block arguments. - * @property {ColorParam} COLOR_PARAM - the name of the selected color parameter. - * @property {number} VALUE - the amount to change the selected parameter by. - * @param {object} util - utility object provided by the runtime. - */ - changePenColorParamBy(args: object, util: object): void; - /** - * The "set pen {ColorParam} to {number}" block sets one of the pen's color parameters - * to a given amound. - * @param {object} args - the block arguments. - * @property {ColorParam} COLOR_PARAM - the name of the selected color parameter. - * @property {number} VALUE - the amount to set the selected parameter to. - * @param {object} util - utility object provided by the runtime. - */ - setPenColorParamTo(args: object, util: object): void; - /** - * The pen "change pen size by {number}" block changes the pen size by the given amount. - * @param {object} args - the block arguments. - * @property {number} SIZE - the amount of desired size change. - * @param {object} util - utility object provided by the runtime. - */ - changePenSizeBy(args: object, util: object): void; - _changePenSizeBy(size: any, target: any): void; - /** - * The pen "set pen size to {number}" block sets the pen size to the given amount. - * @param {object} args - the block arguments. - * @property {number} SIZE - the amount of desired size change. - * @param {object} util - utility object provided by the runtime. - */ - setPenSizeTo(args: object, util: object): void; - _setPenSizeTo(size: any, target: any): void; - /** - * Scratch 2 "hue" param is equivelant to twice the new "color" param. - * @param {object} args - the block arguments. - * @property {number} HUE - the amount to set the hue to. - * @param {object} util - utility object provided by the runtime. - */ - setPenHueToNumber(args: object, util: object): void; - _setPenHueToNumber(hueValue: any, target: any): void; - /** - * Scratch 2 "hue" param is equivelant to twice the new "color" param. - * @param {object} args - the block arguments. - * @property {number} HUE - the amount of desired hue change. - * @param {object} util - utility object provided by the runtime. - */ - changePenHueBy(args: object, util: object): void; - _changePenHueBy(hueChange: any, target: any): void; - /** - * Use legacy "set shade" code to calculate RGB value for shade, - * then convert back to HSV and store those components. - * It is important to also track the given shade in penState._shade - * because it cannot be accurately backed out of the new HSV later. - * @param {object} args - the block arguments. - * @property {number} SHADE - the amount to set the shade to. - * @param {object} util - utility object provided by the runtime. - */ - setPenShadeToNumber(args: object, util: object): void; - _setPenShadeToNumber(shade: any, target: any): void; - /** - * Because "shade" cannot be backed out of hsv consistently, use the previously - * stored penState._shade to make the shade change. - * @param {object} args - the block arguments. - * @property {number} SHADE - the amount of desired shade change. - * @param {object} util - utility object provided by the runtime. - */ - changePenShadeBy(args: object, util: object): void; - _changePenShadeBy(shade: any, target: any): void; - /** - * Update the pen state's color from its hue & shade values, Scratch 2.0 style. - * @param {object} penState - update the HSV & RGB values in this pen state from its hue & shade values. - * @private - */ - private _legacyUpdatePenColor; - } - namespace Scratch3PenBlocks { - export { PenState }; - } - /** - * - the pen state associated with a particular target. - */ - type PenState = { - /** - * - tracks whether the pen should draw for this target. - */ - penDown: boolean; - /** - * - the current color (hue) of the pen. - */ - color: number; - /** - * - cached pen attributes for the renderer. This is the authoritative value for - * diameter but not for pen color. - */ - penAttributes: PenAttributes; - }; -} - -declare module "scratch-vm-dts/engine/block-utility" { - export = BlockUtility; - type Sequencer = import("scratch-vm-dts/engine/sequencer"); - type Target = import("scratch-vm-dts/engine/target"); - type Runtime = import("scratch-vm-dts/engine/runtime"); - /** - * @fileoverview - * Interface provided to block primitive functions for interacting with the - * runtime, thread, target, and convenient methods. - */ - class BlockUtility { - constructor(sequencer?: null, thread?: null); - /** - * A sequencer block primitives use to branch or start procedures with - * @type {?Sequencer} - */ - sequencer: Sequencer | null; - /** - * The block primitives thread with the block's target, stackFrame and - * modifiable status. - * @type {?Thread} - */ - thread: Thread | null; - _nowObj: { - now: () => any; - }; - /** - * The target the primitive is working on. - * @type {Target} - */ - get target(): Target; - /** - * The runtime the block primitive is running in. - * @type {Runtime} - */ - get runtime(): Runtime; - /** - * Use the runtime's currentMSecs value as a timestamp value for now - * This is useful in some cases where we need compatibility with Scratch 2 - * @type {function} - */ - get nowObj(): Function; - /** - * The stack frame used by loop and other blocks to track internal state. - * @type {object} - */ - get stackFrame(): object; - /** - * Check the stack timer and return a boolean based on whether it has finished or not. - * @return {boolean} - true if the stack timer has finished. - */ - stackTimerFinished(): boolean; - /** - * Check if the stack timer needs initialization. - * @return {boolean} - true if the stack timer needs to be initialized. - */ - stackTimerNeedsInit(): boolean; - /** - * Create and start a stack timer - * @param {number} duration - a duration in milliseconds to set the timer for. - */ - startStackTimer(duration: number): void; - /** - * Set the thread to yield. - */ - yield(): void; - /** - * Set the thread to yield until the next tick of the runtime. - */ - yieldTick(): void; - /** - * Start a branch in the current block. - * @param {number} branchNum Which branch to step to (i.e., 1, 2). - * @param {boolean} isLoop Whether this block is a loop. - */ - startBranch(branchNum: number, isLoop: boolean): void; - /** - * Stop all threads. - */ - stopAll(): void; - /** - * Stop threads other on this target other than the thread holding the - * executed block. - */ - stopOtherTargetThreads(): void; - /** - * Stop this thread. - */ - stopThisScript(): void; - /** - * Start a specified procedure on this thread. - * @param {string} procedureCode Procedure code for procedure to start. - */ - startProcedure(procedureCode: string, globalTarget: any): void; - /** - * Get names and ids of parameters for the given procedure. - * @param {string} procedureCode Procedure code for procedure to query. - * @return {Array.} List of param names for a procedure. - */ - getProcedureParamNamesAndIds(procedureCode: string): Array; - /** - * Get names, ids, and defaults of parameters for the given procedure. - * @param {string} procedureCode Procedure code for procedure to query. - * @return {Array.} List of param names for a procedure. - */ - getProcedureParamNamesIdsAndDefaults( - procedureCode: string, - isGlobal: any - ): Array; - /** - * Initialize procedure parameters in the thread before pushing parameters. - */ - initParams(): void; - /** - * Store a procedure parameter value by its name. - * @param {string} paramName The procedure's parameter name. - * @param {*} paramValue The procedure's parameter value. - */ - pushParam(paramName: string, paramValue: any): void; - /** - * Retrieve the stored parameter value for a given parameter name. - * @param {string} paramName The procedure's parameter name. - * @return {*} The parameter's current stored value. - */ - getParam(paramName: string): any; - getHatParam(paramName: any): any; - /** - * Start all relevant hats. - * @param {!string} requestedHat Opcode of hats to start. - * @param {object=} optMatchFields Optionally, fields to match on the hat. - * @param {Target=} optTarget Optionally, a target to restrict to. - * @param {object=} hatParam Optionally, start hats with ccw_hat_parameter if true, - will skip field check and inject ccw_hat_parameter to thread. - * @return {Array.} List of threads started by this function. - */ - startHats( - requestedHat: string, - optMatchFields?: object | undefined, - optTarget?: Target | undefined, - hatParam?: object | undefined - ): Array; - /** - * CCW - startHatsWithParams is only used in block utility for extension, - WhitExtraMsg means skip field check when start a hat block. - define here is only for debug - * @param {!string} requestedHat Opcode of hats to start. - * @param {object} data Optionally, contains fields to match on the hat and parameters to ccw_hat_parameter. - * @param {Target=} optTarget Optionally, a target to restrict to. - * @return {Array.} List of threads started by this function. - */ - startHatsWithParams( - requestedHat: string, - data: object, - optTarget?: Target | undefined - ): Array; - /** - * Query a named IO device. - * @param {string} device The name of like the device, like keyboard. - * @param {string} func The name of the device's function to query. - * @param {Array.<*>} args Arguments to pass to the device's function. - * @return {*} The expected output for the device's function. - */ - ioQuery(device: string, func: string, args: Array): any; - } - type Thread = import("scratch-vm-dts/engine/thread"); -} -//以上代码未被打包器载入 -declare module "scratch-vm-dts/engine/target" { - export = Target; - type Runtime = import("scratch-vm-dts/engine/runtime"); - class bool extends Boolean { } - // 666,写类型注解不好好写,还要我定义接口 - interface Frame { - id: string; - title: string; - x: number; - y: number; - width: number; - height: number; - } - /** - * @fileoverview - * A Target is an abstract "code-running" object for the Scratch VM. - * Examples include sprites/clones or potentially physical-world devices. - */ - class Target extends EventEmitter<[never]> { - /** - * @param {Runtime} runtime Reference to the runtime. - * @param {?Blocks} blocks Blocks instance for the blocks owned by this target. - * @param {?Frames} frames Shared frames object for all clones of sprite. - * @param {?id} id Target id. - * @constructor - */ - constructor( - runtime: Runtime, - blocks: Blocks | null, - frames: Frames | null, - id: any | null - ); - /** - * Reference to the runtime. - * @type {Runtime} - */ - runtime: Runtime; - /** - * A unique ID for this target. - * @type {string} - */ - id: string; - /** - * Blocks run as code for this target. - * @type {!Blocks} - */ - blocks: Blocks; - /** - * Dictionary of variables and their values for this target. - * Key is the variable id. - * @type {Object.} - */ - variables: { - [x: string]: any; - }; - /** - * Dictionary of comments for this target. - * Key is the comment id. - * @type {Object.} - */ - comments: { - [x: string]: any; - }; - /** - * All frames that this target contains. - * @type {!Frames} - */ - frames: Frames; - /** - * Dictionary of custom state for this target. - * This can be used to store target-specific custom state for blocks which need it. - * TODO: do we want to persist this in SB3 files? - * @type {Object.} - */ - _customState: { - [x: string]: any; - }; - /** - * Currently known values for edge-activated hats. - * Keys are block ID for the hat; values are the currently known values. - * @type {Object.} - */ - _edgeActivatedHatValues: { - [x: string]: any; - }; - /** - * Maps extension ID to a JSON-serializable value. - * @type {Object.} - */ - extensionStorage: { - [x: string]: object; - }; - /** - * Called when the project receives a "green flag." - * @abstract - */ - onGreenFlag(): void; - /** - * Return a human-readable name for this target. - * Target implementations should override this. - * @abstract - * @returns {string} Human-readable name for the target. - */ - getName(): string; - /** - * Update an edge-activated hat block value. - * @param {!string} blockId ID of hat to store value for. - * @param {*} newValue Value to store for edge-activated hat. - * @return {*} The old value for the edge-activated hat. - */ - updateEdgeActivatedValue(blockId: string, newValue: any): any; - hasEdgeActivatedValue(blockId: any): boolean; - /** - * Clear all edge-activaed hat values. - */ - clearEdgeActivatedValues(): void; - /** - * Look up a variable object, first by id, and then by name if the id is not found. - * Create a new variable if both lookups fail. - * @param {string} id Id of the variable. - * @param {string} name Name of the variable. - * @return {!Variable} Variable object. - */ - lookupOrCreateVariable(id: string, name: string): Variable; - /** - * Look up a broadcast message object with the given id and return it - * if it exists. - * @param {string} id Id of the variable. - * @param {string} name Name of the variable. - * @return {?Variable} Variable object. - */ - lookupBroadcastMsg(id: string, name: string): Variable | null; - /** - * Look up a broadcast message with the given name and return the variable - * if it exists. Does not create a new broadcast message variable if - * it doesn't exist. - * @param {string} name Name of the variable. - * @return {?Variable} Variable object. - */ - lookupBroadcastByInputValue(name: string): Variable | null; - /** - * Look up a variable object. - * Search begins for local variables; then look for globals. - * @param {string} id Id of the variable. - * @param {string} name Name of the variable. - * @return {!Variable} Variable object. - */ - lookupVariableById(id: string): Variable; - /** - * Look up a variable object by its name and variable type. - * Search begins with local variables; then global variables if a local one - * was not found. - * @param {string} name Name of the variable. - * @param {string} type Type of the variable. Defaults to Variable.SCALAR_TYPE. - * @param {?bool} skipStage Optional flag to skip checking the stage - * @return {?Variable} Variable object if found, or null if not. - */ - lookupVariableByNameAndType( - name: string, - type: string, - skipStage: bool | null - ): Variable | null; - /** - * Look up if a variable is being used based on its name and type. - * @param {string} name Name of the variable. - * @param {string} type Type of the variable. Defaults to Variable.SCALAR_TYPE. - * @return {?bool} True if found, or false if not. - */ - findVariableUsage(name: string, type: string): bool | null; - /** - * Look up a list object for this target, and create it if one doesn't exist. - * Search begins for local lists; then look for globals. - * @param {!string} id Id of the list. - * @param {!string} name Name of the list. - * @return {!Variable} Variable object representing the found/created list. - */ - lookupOrCreateList(id: string, name: string): Variable; - /** - * Creates a variable with the given id and name and adds it to the - * dictionary of variables. - * @param {string} id Id of variable - * @param {string} name Name of variable. - * @param {string} type Type of variable, '', 'broadcast_msg', or 'list' - * @param {boolean} isCloud Whether the variable to create has the isCloud flag set. - * @param {boolean} isRemoteOperation - Set to true if this is a remote operation - * Additional checks are made that the variable can be created as a cloud variable. - */ - createVariable( - id: string, - name: string, - type: string, - isCloud: boolean, - isRemoteOperation: boolean - ): void; - /** - * Creates a comment with the given properties. - * @param {string} id Id of the comment. - * @param {string} blockId Optional id of the block the comment is attached - * to if it is a block comment. - * @param {string} text The text the comment contains. - * @param {number} x The x coordinate of the comment on the workspace. - * @param {number} y The y coordinate of the comment on the workspace. - * @param {number} width The width of the comment when it is full size - * @param {number} height The height of the comment when it is full size - * @param {boolean} minimized Whether the comment is minimized. - * @param {boolean} isRemoteOperation - set to true if this is a remote operation - */ - createComment( - id: string, - blockId: string, - text: string, - x: number, - y: number, - width: number, - height: number, - minimized: boolean, - isRemoteOperation: boolean - ): void; - /** - * Creates a frame with the given properties. - * @param {Frame} frame The definition of the frame. - */ - createFrame(frame: Frame): boolean; - /** - * Removes the frame with the given id from the dictionary of frames. - * @param {string} id Id of frame to delete. - */ - deleteFrame(id: string): void; - /** - * Renames the variable with the given id to newName. - * @param {string} id Id of variable to rename. - * @param {string} newName New name for the variable. - */ - renameVariable(id: string, newName: string): void; - /** - * Removes the variable with the given id from the dictionary of variables. - * @param {string} id Id of variable to delete. - * @param {boolean} isRemoteOperation - set to true if this is a remote operation - */ - deleteVariable(id: string, isRemoteOperation: boolean): void; - /** - * Remove this target's monitors from the runtime state and remove the - * target-specific monitored blocks (e.g. local variables, global variables for the stage, x-position). - * NOTE: This does not delete any of the stage monitors like backdrop name. - */ - deleteMonitors(): void; - /** - * Create a clone of the variable with the given id from the dictionary of - * this target's variables. - * @param {string} id Id of variable to duplicate. - * @param {boolean=} optKeepOriginalId Optional flag to keep the original variable ID - * @param {!object} targetId ID of the target which owns the variable. - * for the duplicate variable. This is necessary when cloning a sprite, for example. - * @return {?Variable} The duplicated variable, or null if - * the original variable was not found. - */ - duplicateVariable( - id: string, - optKeepOriginalId: boolean | undefined, - targetId: string - ): Variable | null; - /** - * Duplicate the dictionary of this target's variables as part of duplicating. - * this target or making a clone. - * @param {!object} targetId ID of the target which owns this variables. - * @param {object=} optBlocks Optional block container for the target being duplicated. - * If provided, new variables will be generated with new UIDs and any variable references - * in this blocks container will be updated to refer to the corresponding new IDs. - * @return {object} The duplicated dictionary of variables - */ - duplicateVariables( - targetId: object, - optBlocks?: object | undefined - ): object; - /** - * Post/edit sprite info. - * @param {object} data An object with sprite info data to set. - * @abstract - */ - postSpriteInfo(data: object): void; - /** - * Retrieve custom state associated with this target and the provided state ID. - * @param {string} stateId - specify which piece of state to retrieve. - * @returns {*} the associated state, if any was found. - */ - getCustomState(stateId: string): any; - /** - * Store custom state associated with this target and the provided state ID. - * @param {string} stateId - specify which piece of state to store on this target. - * @param {*} newValue - the state value to store. - */ - setCustomState(stateId: string, newValue: any): void; - /** - * Call to destroy a target. - * @abstract - */ - dispose(): void; - /** - * Get the names of all the variables of the given type that are in scope for this target. - * For targets that are not the stage, this includes any target-specific - * variables as well as any stage variables unless the skipStage flag is true. - * For the stage, this is all stage variables. - * @param {string} type The variable type to search for; defaults to Variable.SCALAR_TYPE - * @param {?bool} skipStage Optional flag to skip the stage. - * @return {Array} A list of variable names - */ - getAllVariableNamesInScopeByType( - type: string, - skipStage: bool | null - ): Array; - /** - * Merge variable references with another variable. - * @param {string} idToBeMerged ID of the variable whose references need to be updated - * @param {string} idToMergeWith ID of the variable that the old references should be replaced with - * @param {?Array} optReferencesToUpdate Optional context of the change. - * Defaults to all the blocks in this target. - * @param {?string} optNewName New variable name to merge with. The old - * variable name in the references being updated should be replaced with this new name. - * If this parameter is not provided or is '', no name change occurs. - */ - mergeVariables( - idToBeMerged: string, - idToMergeWith: string, - optReferencesToUpdate: Array | null, - optNewName: string | null - ): void; - /** - * Share a local variable (and given references for that variable) to the stage. - * @param {string} varId The ID of the variable to share. - * @param {Array} varRefs The list of variable references being shared, - * that reference the given variable ID. The names and IDs of these variable - * references will be updated to refer to the new (or pre-existing) global variable. - */ - shareLocalVariableToStage(varId: string, varRefs: Array): void; - /** - * Share a local variable with a sprite, merging with one of the same name and - * type if it already exists on the sprite, or create a new one. - * @param {string} varId Id of the variable to share - * @param {Target} sprite The sprite to share the variable with - * @param {Array} varRefs A list of all the variable references currently being shared. - */ - shareLocalVariableToSprite( - varId: string, - sprite: Target, - varRefs: Array - ): void; - /** - * Given a list of variable referencing fields, shares those variables with - * the target with the provided id, resolving any variable conflicts that arise - * using the following rules: - * - * If this target is the stage, exit. There are no conflicts that arise - * from sharing variables from the stage to another sprite. The variables - * already exist globally, so no further action is needed. - * - * If a variable being referenced is a global variable, do nothing. The - * global variable already exists so no further action is needed. - * - * If a variable being referenced is local, and - * 1) The receiving target is a sprite: - * create a new local variable or merge with an existing local variable - * of the same name and type. Update all the referencing fields - * for the original variable to reference the new variable. - * 2) The receiving target is the stage: - * Create a new global variable with a fresh name and update all the referencing - * fields to reference the new variable. - * - * @param {Array} blocks The blocks containing - * potential conflicting references to variables. - * @param {Target} receivingTarget The target receiving the variables - */ - resolveVariableSharingConflictsWithTarget( - blocks: Array, - receivingTarget: Target - ): void; - resolveVariableSharingConflicts(blocks: any): void; - /** - * Fixes up variable references in this target avoiding conflicts with - * pre-existing variables in the same scope. - * This is used when uploading this target as a new sprite into an existing - * project, where the new sprite may contain references - * to variable names that already exist as global variables in the project - * (and thus are in scope for variable references in the given sprite). - * - * If this target has a block that references an existing global variable and that - * variable *does not* exist in this target (e.g. it was a global variable in the - * project the sprite was originally exported from), merge the variables. This entails - * fixing the variable references in this sprite to reference the id of the pre-existing global variable. - * - * If this target has a block that references an existing global variable and that - * variable does exist in the target itself (e.g. it's a local variable in the sprite being uploaded), - * then the local variable is renamed to distinguish itself from the pre-existing variable. - * All blocks that reference the local variable will be updated to use the new name. - */ - fixUpVariableReferences(): void; - emitFast(...args: any[]): void; - } - type Blocks = import("scratch-vm-dts/engine/blocks"); - type Frames = import("scratch-vm-dts/engine/frame"); - type Variable = import("scratch-vm-dts/engine/variable"); -} - -declare module "scratch-vm-dts/engine/sequencer" { - export = Sequencer; - type Runtime = import("scratch-vm-dts/engine/runtime"); - class Sequencer { - /** - * Time to run a warp-mode thread, in ms. - * @type {number} - */ - static get WARP_TIME(): number; - constructor(runtime: any); - /** - * A utility timer for timing thread sequencing. - * @type {!Timer} - */ - timer: Timer; - /** - * Reference to the runtime owning this sequencer. - * @type {!Runtime} - */ - runtime: Runtime; - activeThread: any; - /** - * Step through all threads in `this.runtime.threads`, running them in order. - * @return {Array.} List of inactive threads after stepping. - */ - stepThreads(): Array; - /** - * Step the requested thread for as long as necessary. - * @param {!Thread} thread Thread object to step. - */ - stepThread(thread: Thread): void; - /** - * Step a thread into a block's branch. - * @param {!Thread} thread Thread object to step to branch. - * @param {number} branchNum Which branch to step to (i.e., 1, 2). - * @param {boolean} isLoop Whether this block is a loop. - */ - stepToBranch(thread: Thread, branchNum: number, isLoop: boolean): void; - /** - * Step a procedure. - * @param {!Thread} thread Thread object to step to procedure. - * @param {!string} procedureCode Procedure code of procedure to step to. - * @param {!Target} Target CCW: for globalProcedure. - */ - stepToProcedure( - thread: Thread, - procedureCode: string, - globalTarget: any - ): void; - /** - * Retire a thread in the middle, without considering further blocks. - * @param {!Thread} thread Thread object to retire. - */ - retireThread(thread: Thread): void; - } - import Timer = require("scratch-vm-dts/util/timer"); - import Thread = require("scratch-vm-dts/engine/thread"); -} - -declare module "scratch-vm-dts/engine/runtime" { - export = Runtime; - type Target = import("scratch-vm-dts/engine/target"); - - class ScratchLinkSocket { } - class AudioEngine { } - class RenderWebGL { } - class ScratchStorage { } - class MonitorRecord { } - /** - * Manages targets, scripts, and the sequencer. - * @constructor - */ - class Runtime extends EventEmitter<[never]> { - /** - * Width of the stage, in pixels. - * @const {number} - */ - static get STAGE_WIDTH(): number; - /** - * Height of the stage, in pixels. - * @const {number} - */ - static get STAGE_HEIGHT(): number; - /** - * Event name for glowing a script. - * @const {string} - */ - static get SCRIPT_GLOW_ON(): string; - /** - * Event name for unglowing a script. - * @const {string} - */ - static get SCRIPT_GLOW_OFF(): string; - /** - * Event name for glowing a block. - * @const {string} - */ - static get BLOCK_GLOW_ON(): string; - /** - * Event name for unglowing a block. - * @const {string} - */ - static get BLOCK_GLOW_OFF(): string; - /** - * Event name for a cloud data update - * to this project. - * @const {string} - */ - static get HAS_CLOUD_DATA_UPDATE(): string; - /** - * Event name for turning on turbo mode. - * @const {string} - */ - static get TURBO_MODE_ON(): string; - /** - * Event name for turning off turbo mode. - * @const {string} - */ - static get TURBO_MODE_OFF(): string; - /** - * Event name for runtime options changing. - * @const {string} - */ - static get RUNTIME_OPTIONS_CHANGED(): string; - /** - * Event name for compiler options changing. - * @const {string} - */ - static get COMPILER_OPTIONS_CHANGED(): string; - /** - * Event name for framerate changing. - * @const {string} - */ - static get FRAMERATE_CHANGED(): string; - static get TARGETS_INDEX_CHANGED(): string; - /** - * Event name for interpolation changing. - * @const {string} - */ - static get INTERPOLATION_CHANGED(): string; - /** - * Event name for stage size changing. - * @const {string} - */ - static get STAGE_SIZE_CHANGED(): string; - /** - * Event name for compiler errors. - * @const {string} - */ - static get COMPILE_ERROR(): string; - /** - * Event name for CCWAPI changing. - * @const {string} - */ - static get CCWAPI_CHANGED(): string; - /** - * Event name for assets loading progress. - */ - static get LOAD_ASSETS_PROGRESS(): string; - static get LOAD_ASSET_FAILED(): string; - /** - * Event name for start load a project from a Scratch JSON representation. - * @const {string} - */ - static get START_DESERIALIZE_PROJECT(): string; - /** - * Event name for the project completes loading the assets asynchronously - * @const {string} - */ - static get PROJECT_ASSETS_ASYNC_LOAD_DONE(): string; - /** - * Event called before any block is executed. - */ - static get BEFORE_EXECUTE(): string; - /** - * Event called after every block in the project has been executed. - */ - static get AFTER_EXECUTE(): string; - /** - * Event name for reporting asset download progress. Fired with finished, total - * @const {string} - */ - static get ASSET_PROGRESS(): string; - /** - * Event name when the project is started (threads may not necessarily be - * running). - * @const {string} - */ - static get PROJECT_START(): string; - /** - * Event name when threads start running. - * Used by the UI to indicate running status. - * @const {string} - */ - static get PROJECT_RUN_START(): string; - /** - * Event name when threads stop running - * Used by the UI to indicate not-running status. - * @const {string} - */ - static get PROJECT_RUN_STOP(): string; - /** - * Event name for pause. - * Used by the UI to indicate pause status. - * @const {string} - */ - static get PROJECT_RUN_PAUSE(): string; - /** - * Event name for resume - * Used by the UI to indicate resume status. - * @const {string} - */ - static get PROJECT_RUN_RESUME(): string; - /** - * Event name for project being stopped or restarted by the user. - * Used by blocks that need to reset state. - * @const {string} - */ - static get PROJECT_STOP_ALL(): string; - /** - * Event name for target being stopped by a stop for target call. - * Used by blocks that need to stop individual targets. - * @const {string} - */ - static get STOP_FOR_TARGET(): string; - /** - * Event name for visual value report. - * @const {string} - */ - static get VISUAL_REPORT(): string; - /** - * Event name for project loaded report. - * @const {string} - */ - static get PROJECT_LOADED(): string; - /** - * Event name for report that a change was made that can be saved - * @const {string} - */ - static get PROJECT_CHANGED(): string; - /** - * Event name for mobile buttons visible was changed. - * @const {string} - */ - static get TARGET_BLOCKS_CHANGED(): string; - /** - * Event name for editing target's blocks was changed. - * @const {string} - */ - static get MOBILE_BUTTONS_VISIBLE_CHANGED(): string; - /** - * Event name for editing target's simple property(name, size, x, y, etc) was changed. - * @const {string} - */ - static get TARGET_SIMPLE_PROPERTY_CHANGED(): string; - /** - * Event name for editing target's comments was changed. - * @const {string} - */ - static get TARGET_COMMENTS_CHANGED(): string; - /** - * Event name for editing target's frames was changed. - * @const {string} - */ - static get TARGET_FRAMES_CHANGED(): string; - /** - * Event name for editing target's costome was changed. - * @const {string} - */ - static get TARGET_COSTUME_CHANGED(): string; - /** - * Event name for editing target's currentCostome was changed. - * @const {string} - */ - static get TARGET_CURRENT_COSTUME_CHANGED(): string; - /** - * Event name for editing target's variables was changed. - * @const {string} - */ - static get TARGET_VARIABLES_CHANGED(): string; - /** - * Event name for user manipulated monitor and caused it to change. - * @const {string} - */ - static get MONITORS_CHANGED(): string; - /** - * Event name for report that a change was made to an extension in the toolbox. - * @const {string} - */ - static get TOOLBOX_EXTENSIONS_NEED_UPDATE(): string; - /** - * Event name for targets update report. - * @const {string} - */ - static get TARGETS_UPDATE(): string; - /** - * Event name for target update report. - * @const {string} - */ - static get TARGET_UPDATE(): string; - /** - * Event name for gandi asset update report. - * @const {string} - */ - static get GANDI_ASSET_UPDATE(): string; - static get GANDI_ASSET_UPDATE_FROM_SERVER(): string; - static get GANDI_CONFIGS_UPDATE(): string; - static get GANDI_SPINE_UPDATE(): string; - static get GANDI_DYNAMIC_MENU_ITEMS_UPDATE(): string; - static get GANDI_WILD_EXTENSIONS_CHANGED(): string; - static get GANDI_SHOW_SPINE_UPLOAD(): string; - /** - * Event name for monitors update. - * @const {string} - */ - static get MONITORS_UPDATE(): string; - /** - * Event name for monitors changed. - * @const {string} - */ - static get SOUNDS_CHANGED(): string; - /** - * Event name for block drag update. - * @const {string} - */ - static get BLOCK_DRAG_UPDATE(): string; - /** - * Event name for frame drag update. - * @const {string} - */ - static get FRAME_DRAG_UPDATE(): string; - /** - * Event name for frame drag update. - * @const {string} - */ - static get FRAME_DRAG_END(): string; - /** - * Event name for block drag end. - * @const {string} - */ - static get BLOCK_DRAG_END(): string; - /** - * Event name for reporting that an extension was added. - * @const {string} - */ - static get EXTENSION_ADDED(): string; - /** - * Event name for reporting that an extension was deleted. - * @const {string} - */ - static get EXTENSION_DELETED(): string; - /** - * Event name for reporting that an extension as asked for a custom field to be added - * @const {string} - */ - static get EXTENSION_FIELD_ADDED(): string; - /** - * Event name for updating the available set of peripheral devices. - * This causes the peripheral connection modal to update a list of - * available peripherals. - * @const {string} - */ - static get PERIPHERAL_LIST_UPDATE(): string; - /** - * Event name for when the user picks a bluetooth device to connect to - * via Companion Device Manager (CDM) - * @const {string} - */ - static get USER_PICKED_PERIPHERAL(): string; - /** - * Event name for reporting that a peripheral has connected. - * This causes the status button in the blocks menu to indicate 'connected'. - * @const {string} - */ - static get PERIPHERAL_CONNECTED(): string; - /** - * Event name for reporting that a peripheral has been intentionally disconnected. - * This causes the status button in the blocks menu to indicate 'disconnected'. - * @const {string} - */ - static get PERIPHERAL_DISCONNECTED(): string; - /** - * Event name for reporting that a peripheral has encountered a request error. - * This causes the peripheral connection modal to switch to an error state. - * @const {string} - */ - static get PERIPHERAL_REQUEST_ERROR(): string; - /** - * Event name for reporting that a peripheral connection has been lost. - * This causes a 'peripheral connection lost' error alert to display. - * @const {string} - */ - static get PERIPHERAL_CONNECTION_LOST_ERROR(): string; - /** - * Event name for reporting that a peripheral has not been discovered. - * This causes the peripheral connection modal to show a timeout state. - * @const {string} - */ - static get PERIPHERAL_SCAN_TIMEOUT(): string; - /** - * Event name to indicate that the microphone is being used to stream audio. - * @const {string} - */ - static get MIC_LISTENING(): string; - /** - * Event name to indicate that the custom blocks have been added or deleted. - * @const {string} - */ - static get CUSTOM_BLOCK_ARGUMENTS_LENGTH_CHANGED(): string; - static get EXTENSION_DATA_LOADING(): string; - /** - * Event name for reporting that blocksInfo was updated. - * @const {string} - */ - static get BLOCKSINFO_UPDATE(): string; - /** - * Event name when the runtime tick loop has been started. - * @const {string} - */ - static get RUNTIME_STARTED(): string; - /** - * Event name when the runtime tick loop has been stopped. - * @const {string} - */ - static get RUNTIME_STOPPED(): string; - /** - * Event name when the runtime dispose has been called. - * @const {string} - */ - static get RUNTIME_DISPOSED(): string; - /** - * Event name for reporting that a block was updated and needs to be rerendered. - * @const {string} - */ - static get BLOCKS_NEED_UPDATE(): string; - /** - * Event name when platform name inside a project does not match the runtime. - */ - static get PLATFORM_MISMATCH(): string; - /** - * How rapidly we try to step threads by default, in ms. - */ - static get THREAD_STEP_INTERVAL(): number; - /** - * In compatibility mode, how rapidly we try to step threads, in ms. - */ - static get THREAD_STEP_INTERVAL_COMPATIBILITY(): number; - /** - * How many clones can be created at a time. - * @const {number} - */ - static get MAX_CLONES(): number; - constructor(); - /** - * Target management and storage. - * @type {Array.} - */ - targets: Array; - /** - * Targets in reverse order of execution. Shares its order with drawables. - * @type {Array.} - */ - executableTargets: Array; - /** - * A list of threads that are currently running in the VM. - * Threads are added when execution starts and pruned when execution ends. - * @type {Array.} - */ - threads: Array; - threadMap: Map; - /** @type {!Sequencer} */ - sequencer: Sequencer; - /** - * Storage container for flyout blocks. - * These will execute on `_editingTarget.` - * @type {!Blocks} - */ - flyoutBlocks: Blocks; - /** - * Storage container for monitor blocks. - * These will execute on a target maybe - * @type {!Blocks} - */ - monitorBlocks: Blocks; - /** - * Currently known editing target for the VM. - * @type {?Target} - */ - _editingTarget: Target | null; - /** - * Map to look up a block primitive's implementation function by its opcode. - * This is a two-step lookup: package name first, then primitive name. - * @type {Object.} - */ - _primitives: { - [x: string]: Function; - }; - /** - * Map to look up hat blocks' metadata. - * Keys are opcode for hat, values are metadata objects. - * @type {Object.} - */ - _hats: { - [x: string]: Object; - }; - /** - * Map of opcode to information about whether the block's return value should be interpreted - * for control flow purposes. - * @type {Record} - */ - _flowing: Record< - string, - { - conditional: boolean; - } - >; - /** - * A list of script block IDs that were glowing during the previous frame. - * @type {!Array.} - */ - _scriptGlowsPreviousFrame: Array; - /** - * Number of non-monitor threads running during the previous frame. - * @type {number} - */ - _nonMonitorThreadCount: number; - /** - * All threads that finished running and were removed from this.threads - * by behaviour in Sequencer.stepThreads. - * @type {Array} - */ - _lastStepDoneThreads: Array; - /** - * Currently known number of clones, used to enforce clone limit. - * @type {number} - */ - _cloneCounter: number; - /** - * Flag to emit a targets update at the end of a step. When target data - * changes, this flag is set to true. - * @type {boolean} - */ - _refreshTargets: boolean; - /** - * Ordered map of all monitors, which are MonitorReporter objects. - */ - _monitorState: OrderedMap; - /** - * Monitor state from last tick - */ - _prevMonitorState: OrderedMap; - /** - * Whether the project is in "turbo mode." - * @type {Boolean} - */ - turboMode: boolean; - /** - * tw: Responsible for managing the VM's many timers. - */ - frameLoop: FrameLoop; - /** - * Current length of a step. - * Changes as mode switches, and used by the sequencer to calculate - * WORK_TIME. - * @type {!number} - */ - currentStepTime: number; - /** - * Whether any primitive has requested a redraw. - * Affects whether `Sequencer.stepThreads` will yield - * after stepping each thread. - * Reset on every frame. - * @type {boolean} - */ - redrawRequested: boolean; - /** @type {Object.} */ - ioDevices: { - [x: string]: Object; - }; - /** - * A list of extensions, used to manage hardware connection. - */ - peripheralExtensions: {}; - /** - * A runtime profiler that records timed events for later playback to - * diagnose Scratch performance. - * @type {Profiler} - */ - profiler: Profiler; - cloudOptions: { - limit: number; - }; - /** - * Check wether the runtime has any cloud data. - * @type {function} - * @return {boolean} Whether or not the runtime currently has any - * cloud variables. - */ - hasCloudData: Function; - /** - * A function which checks whether a new cloud variable can be added - * to the runtime. - * @type {function} - * @return {boolean} Whether or not a new cloud variable can be added - * to the runtime. - */ - canAddCloudVariable: Function; - /** - * A function which returns the number of cloud variables in the runtime. - * @returns {number} - */ - getNumberOfCloudVariables: Function; - /** - * A function that tracks a new cloud variable in the runtime, - * updating the cloud variable limit. Calling this function will - * emit a cloud data update event if this is the first cloud variable - * being added. - * @type {function} - */ - addCloudVariable: Function; - /** - * A function which updates the runtime's cloud variable limit - * when removing a cloud variable and emits a cloud update event - * if the last of the cloud variables is being removed. - * @type {function} - */ - removeCloudVariable: Function; - /** - * A string representing the origin of the current project from outside of the - * Scratch community, such as CSFirst. - * @type {?string} - */ - origin: string | null; - /** - * Provides the ability to log to the terminal. - * The default output is to the browser's console - * @type {LogSystem} - */ - logSystem: LogSystem; - /** - * New data structure in Gandi editor. - * @type {Gandi} - */ - gandi: Gandi; - _stageTarget: any; - /** - * Metadata about the platform this VM is part of. - */ - platform: { - name: string; - url: string; - }; - addonBlocks: {}; - stageWidth: number; - stageHeight: number; - runtimeOptions: { - maxClones: number; - miscLimits: boolean; - fencing: boolean; - hatsConcurrency: number; - }; - compilerOptions: { - enabled: boolean; - warpTimer: boolean; - }; - /** ccw: add ccwAPI init value {} - * - */ - ccwAPI: {}; - waitingLoadAssetCallbackQueue: any[]; - debug: boolean; - _lastStepTime: number; - interpolationEnabled: boolean; - _defaultStoredSettings: { - framerate: any; - runtimeOptions: { - maxClones: number; - miscLimits: boolean; - fencing: boolean; - hatsConcurrency: number; - }; - interpolation: boolean; - turbo: boolean; - hq: any; - width: number; - height: number; - }; - /** - * TW: We support a "packaged runtime" mode. This can be used when: - * - there will never be an editor attached such as scratch-gui or scratch-blocks - * - the project will never be exported with saveProjectSb3() - * - original costume and sound data is not needed - * In this mode, the runtime is able to discard large amounts of data and avoid some processing - * to make projects load faster and use less memory. - * This is not designed to protect projects from copying as someone can still copy the data that - * gets fed into the runtime in the first place. - * This mode is used by the TurboWarp Packager. - */ - isPackaged: boolean; - /** - * Contains information about the external communication methods that the scripts inside the project - * can use to send data from inside the project to an external server. - * Do not update this directly. Use Runtime.setExternalCommunicationMethod() instead. - */ - externalCommunicationMethods: { - cloudVariables: boolean; - customExtensions: boolean; - }; - /** - * If set to true, features such as reading colors from the user's webcam will be disabled - * when the project has access to any external communication method to protect user privacy. - * Requires TurboWarp/scratch-render. - * Do not update this directly. Use Runtime.setEnforcePrivacy() instead. - */ - enforcePrivacy: boolean; - /** - * Internal map of opaque identifiers to the callback to run that function. - * @type {Map} - */ - extensionButtons: Map; - /** - * Responsible for managing custom fonts. - */ - fontManager: FontManager; - /** - * Maps extension ID to a JSON-serializable value. - * @type {Object.} - */ - extensionStorage: { - [x: string]: object; - }; - /** - * Total number of scratch-storage load() requests since the runtime was created or cleared. - */ - totalAssetRequests: number; - /** - * Total number of finished or errored scratch-storage load() requests since the runtime was created or cleared. - */ - finishedAssetRequests: number; - _initializeAddCloudVariable(newCloudDataManager: any): () => void; - _initializeRemoveCloudVariable(newCloudDataManager: any): () => void; - compilerRegisterExtension(name: any, extensionObject: any): void; - getMonitorState(): OrderedMap; - /** - * Create a context ("args") object for use with `formatMessage` on messages which might be target-specific. - * @param {Target} [target] - the target to use as context. If a target is not provided, default to the current - * editing target or the stage. - */ - makeMessageContextForTarget(target?: Target): void; - /** - * remove extension - * @param {string} extensionId - id of extension to remove - */ - removeExtensionPrimitives(extensionId: string): void; - _buildCustomFieldInfo( - fieldName: any, - fieldInfo: any, - extensionId: any, - categoryInfo: any - ): { - fieldName: any; - extendedName: string; - argumentTypeInfo: { - shadow: { - type: string; - fieldName: string; - }; - }; - scratchBlocksDefinition: object; - fieldImplementation: any; - }; - /** - * Build the scratch-blocks JSON needed for a fieldType. - * Custom field types need to be namespaced to the extension so that extensions can't interfere with each other - * @param {string} fieldName - The name of the field - * @param {string} output - The output of the field - * @param {number} outputShape - Shape of the field (from ScratchBlocksConstants) - * @param {object} categoryInfo - The category the field belongs to (Used to set its colors) - * @returns {object} - Object to be inserted into scratch-blocks - */ - _buildCustomFieldTypeForScratchBlocks( - fieldName: string, - output: string, - outputShape: number, - categoryInfo: object - ): object; - _convertXmlForScratchBlocks(xmlInfo: any): { - info: any; - xml: any; - }; - handleExtensionButtonPress(button: any): void; - /** - * @returns {Array.} scratch-blocks XML for each category of extension blocks, in category order. - * @param {?Target} [target] - the active editing target (optional) - * @property {string} id - the category / extension ID - * @property {string} xml - the XML text for this category, starting with `` and ending with `` - */ - getBlocksXML(target?: Target | null): Array; - /** - * @returns {Array.} - an array containing the scratch-blocks JSON information for each dynamic block. - */ - getBlocksJSON(): Array; - /** - * One-time initialization for Scratch Link support. - */ - _initScratchLink(): void; - /** - * Get a scratch link socket. - * @param {string} type Either BLE or BT - * @returns {ScratchLinkSocket} The scratch link socket. - */ - getScratchLinkSocket(type: string): ScratchLinkSocket; - /** - * Configure how ScratchLink sockets are created. Factory must consume a "type" parameter - * either BT or BLE. - * @param {Function} factory The new factory for creating ScratchLink sockets. - */ - configureScratchLinkSocketFactory(factory: Function): void; - _linkSocketFactory: Function | undefined; - /** - * The default scratch link socket creator, using websockets to the installed device manager. - * @param {string} type Either BLE or BT - * @returns {ScratchLinkSocket} The new scratch link socket (a WebSocket object) - */ - _defaultScratchLinkSocketFactory(type: string): ScratchLinkSocket; - /** - * Register an extension that communications with a hardware peripheral by id, - * to have access to it and its peripheral functions in the future. - * @param {string} extensionId - the id of the extension. - * @param {object} extension - the extension to register. - */ - registerPeripheralExtension(extensionId: string, extension: object): void; - /** - * Tell the specified extension to scan for a peripheral. - * @param {string} extensionId - the id of the extension. - */ - scanForPeripheral(extensionId: string): void; - /** - * Connect to the extension's specified peripheral. - * @param {string} extensionId - the id of the extension. - * @param {number} peripheralId - the id of the peripheral. - */ - connectPeripheral(extensionId: string, peripheralId: number): void; - /** - * Disconnect from the extension's connected peripheral. - * @param {string} extensionId - the id of the extension. - */ - disconnectPeripheral(extensionId: string): void; - /** - * Returns whether the extension has a currently connected peripheral. - * @param {string} extensionId - the id of the extension. - * @return {boolean} - whether the extension has a connected peripheral. - */ - getPeripheralIsConnected(extensionId: string): boolean; - /** - * Emit an event to indicate that the microphone is being used to stream audio. - * @param {boolean} listening - true if the microphone is currently listening. - */ - emitMicListening(listening: boolean): void; - /** - * Retrieve the function associated with the given opcode. - * @param {!string} opcode The opcode to look up. - * @return {Function} The function which implements the opcode. - */ - getOpcodeFunction(opcode: string): Function; - /** - * Return whether an opcode represents a hat block. - * @param {!string} opcode The opcode to look up. - * @return {boolean} True if the op is known to be a hat. - */ - getIsHat(opcode: string): boolean; - /** - * Return whether an opcode represents an edge-activated hat block. - * @param {!string} opcode The opcode to look up. - * @return {boolean} True if the op is known to be a edge-activated hat. - */ - getIsEdgeActivatedHat(opcode: string): boolean; - /** - * Attach the audio engine - * @param {!AudioEngine} audioEngine The audio engine to attach - */ - attachAudioEngine(audioEngine: AudioEngine): void; - audioEngine: any; - /** - * Attach the renderer - * @param {!RenderWebGL} renderer The renderer to attach - */ - attachRenderer(renderer: RenderWebGL): void; - renderer: any; - /** - * Set the bitmap adapter for the VM/runtime, which converts scratch 2 - * bitmaps to scratch 3 bitmaps. (Scratch 3 bitmaps are all bitmap resolution 2) - * @param {!function} bitmapAdapter The adapter to attach - */ - attachV2BitmapAdapter(bitmapAdapter: Function): void; - v2BitmapAdapter: Function | undefined; - /** - * Attach the storage module - * @param {!ScratchStorage} storage The storage module to attach - */ - attachStorage(storage: ScratchStorage): void; - storage: any; - attachBlocks(scratchBlocks: any): void; - scratchBlocks: any; - /** - * Create a thread and push it to the list of threads. - * @param {!string} id ID of block that starts the stack. - * @param {!Target} target Target to run thread on. - * @param {?object} opts optional arguments - * @param {?boolean} opts.stackClick true if the script was activated by clicking on the stack - * @param {?boolean} opts.updateMonitor true if the script should update a monitor value - * @param {?object} opts.hatParam store ccw_hat_parameter - * @return {!Thread} The newly created thread. - */ - _pushThread(id: string, target: Target, opts: object | null): Thread; - /** - * Stop a thread: stop running it immediately, and remove it from the thread list later. - * @param {!Thread} thread Thread object to remove from actives - */ - _stopThread(thread: Thread): void; - /** - * Restart a thread in place, maintaining its position in the list of threads. - * This is used by `startHats` to and is necessary to ensure 2.0-like execution order. - * Test project: https://scratch.mit.edu/projects/130183108/ - * @param {!Thread} thread Thread object to restart. - * @return {Thread} The restarted thread. - */ - _restartThread(thread: Thread): Thread; - emitCompileError(target: any, error: any): void; - /** - * Return whether a thread is currently active/running. - * @param {?Thread} thread Thread object to check. - * @return {boolean} True if the thread is active/running. - */ - isActiveThread(thread: Thread | null): boolean; - /** - * Return whether a thread is waiting for more information or done. - * @param {?Thread} thread Thread object to check. - * @return {boolean} True if the thread is waiting - */ - isWaitingThread(thread: Thread | null): boolean; - /** - * Toggle a script. - * @param {!string} topBlockId ID of block that starts the script. - * @param {?object} opts optional arguments to toggle script - * @param {?string} opts.target target ID for target to run script on. If not supplied, uses editing target. - * @param {?boolean} opts.stackClick true if the user activated the stack by clicking, false if not. This - * determines whether we show a visual report when turning on the script. - */ - toggleScript(topBlockId: string, opts: object | null): void; - /** - * Enqueue a script that when finished will update the monitor for the block. - * @param {!string} topBlockId ID of block that starts the script. - * @param {?Target} optTarget target Target to run script on. If not supplied, uses editing target. - */ - addMonitorScript(topBlockId: string, optTarget: Target | null): void; - /** - * Run a function `f` for all scripts in a workspace. - * `f` will be called with two parameters: - * - the top block ID of the script. - * - the target that owns the script. - * @param {!Function} f Function to call for each script. - * @param {Target=} optTarget Optionally, a target to restrict to. - */ - allScriptsDo(f: Function, optTarget?: Target | undefined): void; - allScriptsByOpcodeDo(opcode: any, f: any, optTarget: any): void; - /** - * Start all relevant hats. - * @param {!string} requestedHatOpcode Opcode of hats to start. - * @param {object=} optMatchFields Optionally, fields to match on the hat. - * @param {Target=} optTarget Optionally, a target to restrict to. - * @param {object=} hatParam Optionally, start hats with ccw_hat_parameter if true, - will skip field check and inject ccw_hat_parameter to thread. - * @return {Array.} List of threads started by this function. - */ - startHats( - requestedHatOpcode: string, - optMatchFields?: object | undefined, - optTarget?: Target | undefined, - hatParam?: object | undefined - ): Array; - /** - * CCW - startHatsWithParams is only used in block utility for extension, - WhitExtraMsg means skip field check when start a hat block. - define here is only for debug - * @param {!string} requestedHatOpcode Opcode of hats to start. - * @param {object} data Optionally, contains fields to match on the hat and parameters to ccw_hat_parameter. - * @param {Target=} optTarget Optionally, a target to restrict to. - * @return {Array.} List of threads started by this function. - */ - startHatsWithParams( - requestedHat: any, - data: object, - optTarget?: Target | undefined - ): Array; - /** - * Dispose all targets. Return to clean state. - */ - dispose(): void; - disposeAll(): void; - _steppingInterval: any; - /** - * Add a target to the runtime. This tracks the sprite pane - * ordering of the target. The target still needs to be put - * into the correct execution order after calling this function. - * @param {Target} target target to add - */ - addTarget(target: Target): void; - /** - * Move a target in the execution order by a relative amount. - * - * A positve number will make the target execute earlier. A negative number - * will make the target execute later in the order. - * - * @param {Target} executableTarget target to move - * @param {number} delta number of positions to move target by - * @returns {number} new position in execution order - */ - moveExecutable(executableTarget: Target, delta: number): number; - /** - * Set a target to execute at a specific position in the execution order. - * - * Infinity will set the target to execute first. 0 will set the target to - * execute last (before the stage). - * - * @param {Target} executableTarget target to move - * @param {number} newIndex position in execution order to place the target - * @returns {number} new position in the execution order - */ - setExecutablePosition(executableTarget: Target, newIndex: number): number; - /** - * Remove a target from the execution set. - * @param {Target} executableTarget target to remove - */ - removeExecutable(executableTarget: Target): void; - /** - * Dispose of a target. - * @param {!Target} disposingTarget Target to dispose of. - */ - disposeTarget(disposingTarget: Target): void; - /** - * Stop any threads acting on the target. - * @param {!Target} target Target to stop threads for. - * @param {Thread=} optThreadException Optional thread to skip. - */ - stopForTarget( - target: Target, - optThreadException?: Thread | undefined - ): void; - /** - * Reset the Run ID. Call this any time the project logically starts, stops, or changes identity. - */ - resetRunId(): void; - /** - * Start all threads that start with the green flag. - */ - greenFlag(): void; - /** - * Stop "everything." - */ - stopAll(): void; - _renderInterpolatedPositions(): void; - updateThreadMap(): void; - /** - * Repeatedly run `sequencer.stepThreads` and filter out - * inactive threads after each iteration. - */ - _step(): void; - /** - * 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). - * @param {!Array.} threads The set of threads to look through. - * @return {number} The number of monitor threads in threads. - */ - _getMonitorThreadCount(threads: Array): number; - /** - * Queue monitor blocks to sequencer to be run. - */ - _pushMonitors(): void; - /** - * Set the current editing target known by the runtime. - * @param {!Target} editingTarget New editing target. - */ - setEditingTarget(editingTarget: Target): void; - /** - * Set whether we are in 30 TPS compatibility mode. - * @param {boolean} compatibilityModeOn True iff in compatibility mode. - */ - setCompatibilityMode(compatibilityModeOn: boolean): void; - /** - * tw: Change runtime target frames per second - * @param {number} framerate Target frames per second - */ - setFramerate(framerate: number): void; - /** - * tw: Enable or disable interpolation. - * @param {boolean} interpolationEnabled True if interpolation should be enabled. - */ - setInterpolation(interpolationEnabled: boolean): void; - /** - * tw: Update runtime options - * @param {*} runtimeOptions New options - */ - setRuntimeOptions(runtimeOptions: any): void; - /** - * ccw: Set ccw API to runtime support ccw block extensions - * @param {*} ccwAPI ccw API - */ - setCCWAPI(ccwAPI: any): void; - /** - * tw: Update compiler options - * @param {*} compilerOptions New options - */ - setCompilerOptions(compilerOptions: any): void; - /** - * @param {boolean} isPlayerOnly - */ - setIsPlayerOnly(isPlayerOnly: boolean): void; - isPlayerOnly: boolean | undefined; - /** - * Change width and height of stage. This will also inform the renderer of the new stage size. - * @param {number} width New stage width - * @param {number} height New stage height - */ - setStageSize(width: number, height: number): void; - setInEditor(inEditor: any): void; - /** - * TW: Enable "packaged runtime" mode. This is a one-way operation. - */ - convertToPackagedRuntime(): void; - /** - * tw: Reset the cache of all block containers. - */ - resetAllCaches(): void; - /** - * Add an "addon block" - * @param {object} options Options object - * @param {string} options.procedureCode The ID of the block - * @param {function} options.callback The callback, called with (args, BlockUtility). May return a promise. - * @param {string[]} [options.arguments] Names of the arguments accepted. Optional if no arguments. - * @param {boolean} [options.hidden] True to not include this block in the block palette - * @param {1|2} [options.return] 1 for round reporter, 2 for boolean reported, leave empty for statement. - */ - addAddonBlock(options: { - procedureCode: string; - callback: Function; - arguments?: string[] | undefined; - hidden?: boolean | undefined; - return?: 2 | 1 | undefined; - }): void; - getAddonBlock(procedureCode: any): any; - findProjectOptionsComment(): any; - parseProjectOptions(): void; - _generateAllProjectOptions(): { - framerate: any; - runtimeOptions: { - maxClones: number; - miscLimits: boolean; - fencing: boolean; - hatsConcurrency: number; - }; - interpolation: boolean; - turbo: boolean; - hq: any; - width: number; - height: number; - }; - generateDifferingProjectOptions(): {}; - storeProjectOptions(): void; - /** - * Eagerly (re)compile all scripts within this project. - */ - precompile(): void; - enableDebug(): void; - /** - * Emit glows/glow clears for scripts after a single tick. - * Looks at `this.threads` and notices which have turned on/off new glows. - * @param {Array.=} optExtraThreads Optional list of inactive threads. - */ - _updateGlows(optExtraThreads?: Array | undefined): void; - /** - * Emit run start/stop after each tick. Emits when `this.threads.length` goes - * between non-zero and zero - * - * @param {number} nonMonitorThreadCount The new nonMonitorThreadCount - */ - _emitProjectRunStatus(nonMonitorThreadCount: number): void; - /** - * "Quiet" a script's glow: stop the VM from generating glow/unglow events - * about that script. Use when a script has just been deleted, but we may - * still be tracking glow data about it. - * @param {!string} scriptBlockId Id of top-level block in script to quiet. - */ - quietGlow(scriptBlockId: string): void; - /** - * Emit feedback for block glowing (used in the sequencer). - * @param {?string} blockId ID for the block to update glow - * @param {boolean} isGlowing True to turn on glow; false to turn off. - */ - glowBlock(blockId: string | null, isGlowing: boolean): void; - /** - * Emit feedback for script glowing. - * @param {?string} topBlockId ID for the top block to update glow - * @param {boolean} isGlowing True to turn on glow; false to turn off. - */ - glowScript(topBlockId: string | null, isGlowing: boolean): void; - /** - * Emit whether blocks are being dragged over gui - * @param {boolean} areBlocksOverGui True if blocks are dragged out of blocks workspace, false otherwise - */ - emitBlockDragUpdate(areBlocksOverGui: boolean): void; - /** - * Emit whether frame are being dragged over gui - * @param {boolean} areBlocksOverGui True if frame are dragged out of the workspace, false otherwise - */ - emitFrameDragUpdate(areBlocksOverGui: boolean): void; - /** - * Emit event to indicate that the block drag has ended with the blocks outside the blocks workspace - * @param {Array.} blocks The set of blocks dragged to the GUI - * @param {string} topBlockId The original id of the top block being dragged - * @param {Array.} newBatchElements The set of batch selected blocks or frames - */ - emitBlockEndDrag( - blocks: Array, - topBlockId: string, - newBatchElements: Array - ): void; - /** - * Emit event to indicate that the frame drag has ended with the blocks outside the blocks workspace - * @param {Array.} frame The frame dragged to the GUI - * @param {string} frameId The original id of the frame being dragged - * @param {Array.=} newBatchElements The set of batch selected blocks or frames - */ - emitFrameEndDrag( - frame: Array, - frameId: string, - newBatchElements?: Array | undefined - ): void; - emitGandiSpineUpdate(type: any, id: any, data: any): void; - emitGandiConfigsUpdate(key: any, value: any): void; - emitGandiDynamicMenuItemsUpdate(type: any, id: any, data: any): void; - /** - * Emit value for reporter to show in the blocks. - * @param {string} blockId ID for the block. - * @param {string} value Value to show associated with the block. - */ - visualReport(blockId: string, value: string): void; - /** - * Add a monitor to the state. If the monitor already exists in the state, - * updates those properties that are defined in the given monitor record. - * @param {!MonitorRecord} monitor Monitor to add. - * @param {boolean} isRemoteOperation - set to true if this is a remote operation - */ - requestAddMonitor(monitor: MonitorRecord, isRemoteOperation: boolean): void; - /** - * Update a monitor in the state and report success/failure of update. - * @param {!Map} monitor Monitor values to update. Values on the monitor with overwrite - * values on the old monitor with the same ID. If a value isn't defined on the new monitor, - * the old monitor will keep its old value. - * @return {boolean} true if monitor exists in the state and was updated, false if it did not exist. - */ - requestUpdateMonitor(monitor: Map): boolean; - /** - * Removes a monitor from the state. Does nothing if the monitor already does - * not exist in the state. - * @param {!string} monitorId ID of the monitor to remove. - * @param {boolean} isRemoteOperation - set to true if this is a remote operation - */ - requestRemoveMonitor(monitorId: string, isRemoteOperation: boolean): void; - /** - * Hides a monitor and returns success/failure of action. - * @param {!string} monitorId ID of the monitor to hide. - * @param {boolean} isRuntimeOp Whether it is an operation at run time - * @return {boolean} true if monitor exists and was updated, false otherwise - */ - requestHideMonitor(monitorId: string, isRuntimeOp: boolean): boolean; - /** - * Shows a monitor and returns success/failure of action. - * not exist in the state. - * @param {!string} monitorId ID of the monitor to show. - * @param {boolean} isRuntimeOp Whether it is an operation at run time - * @return {boolean} true if monitor exists and was updated, false otherwise - */ - requestShowMonitor(monitorId: string, isRuntimeOp: boolean): boolean; - /** - * Removes all monitors with the given target ID from the state. Does nothing if - * the monitor already does not exist in the state. - * @param {!string} targetId Remove all monitors with given target ID. - */ - requestRemoveMonitorByTargetId(targetId: string): void; - /** - * Get a target by its id. - * @param {string} targetId Id of target to find. - * @return {?Target} The target, if found. - */ - getTargetById(targetId: string): Target | null; - /** - * Get the first original (non-clone-block-created) sprite given a name. - * @param {string} spriteName Name of sprite to look for. - * @return {?Target} Target representing a sprite of the given name. - */ - getSpriteTargetByName(spriteName: string): Target | null; - /** - * Get a target by its drawable id. - * @param {number} drawableID drawable id of target to find - * @return {?Target} The target, if found - */ - getTargetByDrawableId(drawableID: number): Target | null; - /** - * Update the clone counter to track how many clones are created. - * @param {number} changeAmount How many clones have been created/destroyed. - */ - changeCloneCounter(changeAmount: number): void; - /** - * Return whether there are clones available. - * @return {boolean} True until the number of clones hits runtimeOptions.maxClones - */ - clonesAvailable(): boolean; - /** - * Handle that the project has loaded in the Virtual Machine. - */ - handleProjectLoaded(): void; - /** - * Report that the project has changed in a way that would affect serialization - */ - emitProjectChanged(): void; - emitCustomBlockArgumentsLengthChanged(): void; - emitGandiAssetsUpdate(action: any): void; - emitGandiAssetsUpdateFromServer(action: any): void; - emitGandiWildExtensionsChanged(data: any): void; - /** - * Report that the project completes loading the assets asynchronously - */ - emitProjectAssetsAsyncLoadingDone(): void; - emitExtensionsChanged(): void; - emitMobileButtonsVisibleChanged(value: any): void; - /** - * Report that the target has changed in a way that would affect serialization - */ - emitTargetBlocksChanged(targeId: any, blocks: any, ext: any): void; - /** - * Report that the target has changed in a way that would affect serialization - * @param {Array>} data - An array consisting of roles that have undergone changes. - */ - emitTargetSimplePropertyChanged(data: Array>): void; - /** - * Report that the target has changed in a way that would affect serialization - */ - emitTargetCommentsChanged(targeId: any, data: any): void; - /** - * Report that the target has changed in a way that would affect serialization - */ - emitTargetFramesChanged(targeId: any, data: any): void; - /** - * Report that the target has changed in a way that would affect serialization - */ - emitTargetCostumeChanged(id: any, data: any): void; - /** - * Report that the target has changed in a way that would affect serialization - */ - emitTargetCurrentCostumeChanged(index: any): void; - /** - * Report that the target has changed in a way that would affect serialization - */ - emitTargetVariablesChanged(id: any, data: any): void; - emitMonitorsChanged(data: any): void; - emitTargetsIndexChanged(data: any): void; - /** - * Report that the monitors has changed - */ - emitTargetSoundsChanged(targetId: any, data: any): void; - /** - * Report that a new target has been created, possibly by cloning an existing target. - * @param {Target} newTarget - the newly created target. - * @param {Target} [sourceTarget] - the target used as a source for the new clone, if any. - * @fires Runtime#targetWasCreated - */ - fireTargetWasCreated(newTarget: Target, sourceTarget?: Target): void; - /** - * Report that a clone target is being removed. - * @param {Target} target - the target being removed - * @fires Runtime#targetWasRemoved - */ - fireTargetWasRemoved(target: Target): void; - /** - * Get a target representing the Scratch stage, if one exists. - * @return {?Target} The target, if found. - */ - getTargetForStage(): Target | null; - /** - * Get the editing target. - * @return {?Target} The editing target. - */ - getEditingTarget(): Target | null; - getAllVarNamesOfType(varType: any): any[]; - /** - * Get the label or label function for an opcode - * @param {string} extendedOpcode - the opcode you want a label for - * @return {object} - object with label and category - * @property {string} category - the category for this opcode - * @property {Function} [labelFn] - function to generate the label for this opcode - * @property {string} [label] - the label for this opcode if `labelFn` is absent - */ - getLabelForOpcode(extendedOpcode: string): object; - /** - * Create a new global variable avoiding conflicts with other variable names. - * @param {string} variableName The desired variable name for the new global variable. - * This can be turned into a fresh name as necessary. - * @param {string} optVarId An optional ID to use for the variable. A new one will be generated - * if a falsey value for this parameter is provided. - * @param {string} optVarType The type of the variable to create. Defaults to Variable.SCALAR_TYPE. - * @return {Variable} The new variable that was created. - */ - createNewGlobalVariable( - variableName: string, - optVarId: string, - optVarType: string - ): Variable; - /** - * Tell the runtime to request a redraw. - * Use after a clone/sprite has completed some visible operation on the stage. - */ - requestRedraw(): void; - /** - * Emit a targets update at the end of the step if the provided target is - * the original sprite - * @param {!Target} target Target requesting the targets update - */ - requestTargetsUpdate(target: Target): void; - /** - * Emit an event that indicates that the blocks on the workspace need updating. - */ - requestBlocksUpdate(): void; - /** - * Emit an event that indicates that the toolbox extension blocks need updating. - */ - requestToolboxExtensionsUpdate(): void; - /** - * Set up timers to repeatedly step in a browser. - */ - start(): void; - /** - * @deprecated Used by old versions of TurboWarp. Superceded by upstream's quit() - */ - stop(): void; - /** - * Quit the Runtime, clearing any handles which might keep the process alive. - * Do not use the runtime after calling this method. This method is meant for test shutdown. - */ - quit(): void; - /** - * Turn on profiling. - * @param {Profiler/FrameCallback} onFrame A callback handle passed a - * profiling frame when the profiler reports its collected data. - */ - enableProfiling(onFrame: any): void; - /** - * Turn off profiling. - */ - disableProfiling(): void; - /** - * Update a millisecond timestamp value that is saved on the Runtime. - * This value is helpful in certain instances for compatibility with Scratch 2, - * which sometimes uses a `currentMSecs` timestamp value in Interpreter.as - */ - updateCurrentMSecs(): void; - currentMSecs: number | undefined; - getFormatMessage(message: any): (...args: any[]) => string; - getOriginalFormatMessage(): typeof import("format-message"); - getGandiAssetsList(typesArray: any): any; - getGandiAssetContent(fileName: any): any; - getGandiAssetById(id: any): any; - getGandiAssetsFileList(type: any): any; - getGandiAssetFile(fileName: any): any; - addWaitingLoadCallback(callback: any): void; - fireWaitingLoadCallbackQueue(): void; - firingWaitingLoadCallbackQueue: boolean | undefined; - asyncLoadingProjectAssets: boolean | undefined; - requestAnimationFrameId: any; - /** - * Cancel all completed asynchronous resource loading tasks - */ - disposeFireWaitingLoadCallbackQueue(): void; - /** - * Add a costume to the current editing target. - * async costume should only existed in project running - * once project is stopped, all async costume should be removed - * @param {string} md5ext - the MD5 and extension of the costume to be loaded. - * @param {!object} costumeObject Object representing the costume. - * @param {object} target - the target to add to. - * @param {?boolean} show - show Costume immediately - * @returns {?Promise} - a promise that resolves when the costume has been added - */ - addAsyncCostumeToTarget( - md5ext: string, - costumeObject: object, - target: object, - show: boolean | null - ): Promise | null; - updatePrivacy(): void; - /** - * @param {boolean} enabled True if restrictions should be enforced to protect user privacy. - */ - setEnforcePrivacy(enabled: boolean): void; - /** - * @param {string} method Name of the method in Runtime.externalCommunicationMethods - * @param {boolean} enabled True if the feature is enabled. - */ - setExternalCommunicationMethod(method: string, enabled: boolean): void; - emitAssetProgress(): void; - resetProgress(): void; - /** - * Wrap an asset loading promise with progress support. - * @template T - * @param {() => Promise} callback - * @returns {Promise} - */ - wrapAssetRequest(callback: () => Promise): Promise; - } - namespace Runtime { - export { CloudDataManager }; - } - import EventEmitter = require("events"); - type Thread = import("scratch-vm-dts/engine/thread"); - type Sequencer = import("scratch-vm-dts/engine/sequencer"); - type Blocks = import("scratch-vm-dts/engine/blocks"); - import { OrderedMap } from "immutable"; - type FrameLoop = import("scratch-vm-dts/engine/tw-frame-loop"); - type Profiler = import("scratch-vm-dts/engine/profiler"); - type LogSystem = import("scratch-vm-dts/util/log-system"); - type Gandi = import("scratch-vm-dts/util/gandi"); - type FontManager = import("scratch-vm-dts/engine/tw-font-manager"); - type Variable = import("scratch-vm-dts/engine/variable"); - /** - * A pair of functions used to manage the cloud variable limit, - * to be used when adding (or attempting to add) or removing a cloud variable. - */ - type CloudDataManager = { - /** - * A function to call to check that - * a cloud variable can be added. - */ - canAddCloudVariable: Function; - /** - * A function to call to track a new - * cloud variable on the runtime. - */ - addCloudVariable: Function; - /** - * A function to call when - * removing an existing cloud variable. - */ - removeCloudVariable: Function; - /** - * A function to call to check that - * the runtime has any cloud variables. - */ - hasCloudVariables: Function; - /** - * A function that returns the - * number of cloud variables in the project. - */ - getNumberOfCloudVariables: Function; - }; -} - -declare module "scratch-vm-dts/extension-support/extension-manager" { - export = ExtensionManager; - class int extends Number { } - class bool extends Boolean { } - type ArgumentType = import("scratch-vm-dts/extension-support/argument-type"); - type VirtualMachine = import("scratch-vm-dts/virtual-machine"); - type Runtime = import("scratch-vm-dts/engine/runtime"); - type ExtensionBlockMetadata = import("scratch-vm-dts/extension-support/extension-metadata"); - - type Scratch3CoreExample = import("scratch-vm-dts/blocks/scratch3_core_example"); - type Scratch3PenBlocks = import("scratch-vm-dts/extensions/scratch3_pen"); - type Scratch3WeDo2Blocks = import("scratch-vm-dts/extensions/scratch3_wedo2"); - type Scratch3MicroBitBlocks = import("scratch-vm-dts/extensions/scratch3_microbit"); - type Scratch3Text2SpeechBlocks = import("scratch-vm-dts/extensions/scratch3_text2speech"); - type Scratch3TranslateBlocks = import("scratch-vm-dts/extensions/scratch3_translate"); - type Scratch3VideoSensingBlocks = import("scratch-vm-dts/extensions/scratch3_video_sensing"); - type Scratch3Ev3Blocks = import("scratch-vm-dts/extensions/scratch3_ev3"); - type Scratch3MakeyMakeyBlocks = import("scratch-vm-dts/extensions/scratch3_makeymakey"); - type Scratch3BoostBlocks = import("scratch-vm-dts/extensions/scratch3_boost"); - type Scratch3GdxForBlocks = import("scratch-vm-dts/extensions/scratch3_gdx_for"); - type TurboWarpBlocks = import("scratch-vm-dts/extensions/tw"); - class ExtensionManager { - constructor(vm: any); - /** - * The ID number to provide to the next extension worker. - * @type {int} - */ - nextExtensionWorker: int; - /** - * FIFO queue of extensions which have been requested but not yet loaded in a worker, - * along with promise resolution functions to call once the worker is ready or failed. - * - * @type {Array.} - */ - pendingExtensions: Array; - /** - * Map of worker ID to workers which have been allocated but have not yet finished initialization. - * @type {Array.} - */ - pendingWorkers: Array; - /** - * Map of worker ID to the URL where it was loaded from. - * @type {Array} - */ - workerURLs: Array; - /** - * Responsible for determining security policies related to custom extensions. - */ - securityManager: SecurityManager; - /** - * @type {VirtualMachine} - */ - vm: VirtualMachine; - /** - * Whether to show a warning that extensions are officially incompatible with Scratch. - * @type {boolean>} - */ - showCompatibilityWarning: boolean; - /** - * Keep a reference to the runtime so we can construct internal extension objects. - * @type {Runtime} - */ - runtime: Runtime; - loadingAsyncExtensions: number; - asyncExtensionsLoadedCallbacks: any[]; - _customExtensionInfo: {}; - _officialExtensionInfo: {}; - builtinExtensions: { - coreExample: Scratch3CoreExample; - pen: Scratch3PenBlocks; - wedo2: Scratch3WeDo2Blocks; - microbit: Scratch3MicroBitBlocks; - text2speech: Scratch3Text2SpeechBlocks; - translate: Scratch3TranslateBlocks; - videoSensing: Scratch3VideoSensingBlocks; - ev3: Scratch3Ev3Blocks; - makeymakey: Scratch3MakeyMakeyBlocks; - boost: Scratch3BoostBlocks; - gdxfor: Scratch3GdxForBlocks; - tw: TurboWarpBlocks; - }; - /** - * Check whether an extension is registered or is in the process of loading. This is intended to control loading or - * adding extensions so it may return `true` before the extension is ready to be used. Use the promise returned by - * `loadExtensionURL` if you need to wait until the extension is truly ready. - * @param {string} extensionID - the ID of the extension. - * @returns {boolean} - true if loaded, false otherwise. - */ - isExtensionLoaded(extensionID: string): boolean; - setLoadedExtension(extensionID: any, value: any): void; - registerExtension( - extensionId: any, - extension: any, - shouldReplace?: boolean - ): any; - /** - * Determine whether an extension with a given ID is built in to the VM, such as pen. - * Note that "core extensions" like motion will return false here. - * @param {string} extensionId - * @returns {boolean} - */ - isBuiltinExtension(extensionId: string): boolean; - /** - * Get the list of external extension service URLs. - * @returns {Array.} - The list of external extension service URLs. - */ - getGandiExternalExtensionServices(): Array; - /** - * Set a new list of external extension service URLs. - * This also resets the loaded flag to ensure the new services are loaded. - * @param {Array.} services - The list of new external extension service URLs. - */ - setGandiExternalExtensionServices(services: Array): void; - /** - * Synchronously load an internal extension (core or non-core) by ID. This call will - * fail if the provided id is not does not match an internal extension. - * @param {string} extensionId - the ID of an internal extension - */ - loadExtensionIdSync(extensionId: string): any; - addBuiltinExtension(extensionId: any, extensionClass: any): void; - _isValidExtensionURL(extensionURL: any): boolean; - /** - * Load an extension by URL or internal extension ID - * @param {string} extensionURL - the URL for the extension to load OR the ID of an internal extension - * @param {bool} shouldReplace - should replace extension that already loaded - * @returns {Promise} resolved once the extension is loaded and initialized or rejected on failure - */ - loadExtensionURL(extensionURL: string, shouldReplace?: bool): Promise; - /** - * Loads an extension URL in a worker. - * - * @param {string} extensionURL - The URL of the extension to load. - * @returns {Promise} A promise that resolves when the extension is loaded successfully, or rejects with an error if the extension is not found. - */ - loadExtensionURLInWorker(extensionURL: string): Promise; - /** - * Wait until all async extensions have loaded - * @returns {Promise} resolved when all async extensions have loaded - */ - allAsyncExtensionsLoaded(): Promise; - /** - * Creates a new extension worker. - * @returns {Promise} - */ - createExtensionWorker(): Promise; - /** - * Remove all extensions from services. - * If we don't do so, this will cause memory leak on Single Page Application. - */ - disposeExtensionServices(): void; - /** - * Regenerate blockinfo for any loaded extensions - * @returns {Promise} resolved once all the extensions have been reinitialized - */ - refreshBlocks(targetServiceName: any): Promise; - allocateWorker(): (string | number)[]; - /** - * Synchronously collect extension metadata from the specified service and begin the extension registration process. - * @param {string} serviceName - the name of the service hosting the extension. - */ - registerExtensionServiceSync(serviceName: string): void; - /** - * Collect extension metadata from the specified service and begin the extension registration process. - * @param {string} serviceName - the name of the service hosting the extension. - */ - registerExtensionService(serviceName: string): void; - _finishedLoadingExtensionScript(): void; - _failedLoadingExtensionScript(error: any): void; - /** - * Called by an extension worker to indicate that the worker has finished initialization. - * @param {int} id - the worker ID. - * @param {*?} e - the error encountered during initialization, if any. - */ - onWorkerInit(id: int, e: any | null): void; - /** - * Register an internal (non-Worker) extension object - * @param {object} extensionObject - the extension object to register - * @returns {string} The name of the registered extension service - */ - _registerInternalExtension(extensionObject: object): string; - /** - * @description register gandi extension when developer load custom extension - * @param {string} id extension id - * @param {string} url extension url - */ - saveWildExtensionsURL(id: string, url: string): void; - loadExternalExtensionById( - extensionId: any, - shouldReplace?: boolean - ): Promise | undefined; - isValidExtensionURL(extensionURL: any): boolean; - injectExtension(extensionId: any, extension: any): void; - isExternalExtension(extensionId: any): boolean; - clearLoadedExtensions(): void; - addOfficialExtensionInfo(obj: any): void; - addCustomExtensionInfo(obj: any, url: any): void; - updateExternalExtensionConstructor(extensionId: any, func: any): void; - getExternalExtensionConstructor(extensionId: any): Promise; - /** - * Loads an external extension to the library. - * - * @param {string} url - The URL of the external extension. - * @param {boolean} [shouldReplace=false] - Whether to replace existing extensions with the same ID. - * @param {boolean} [disallowIIFERegister=false] - Whether to disallow registering extensions using IIFE. - * @returns {Promise<{onlyAdded: string[], addedAndLoaded: string[]}>} - A promise that resolves with an object containing two arrays: `onlyAdded` and `addedAndLoaded`. - * - `onlyAdded` contains the IDs of the extensions that were only added to the library. - * - `addedAndLoaded` contains the IDs of the extensions that were both added to the library and loaded. - * @throws {Error} - If an error occurs while loading the extension. - */ - loadExternalExtensionToLibrary( - url: string, - shouldReplace?: boolean, - disallowIIFERegister?: boolean - ): Promise<{ - onlyAdded: string[]; - addedAndLoaded: string[]; - }>; - /** - * Checks if an extension ID is reserved. - * - * @param {string} extensionId - The extension ID to check. - * @returns {boolean} - Returns `false` if the extension ID is not reserved, `true` otherwise. - */ - isExtensionIdReserved(extensionId: string): boolean; - getLoadedExtensionURLs(): {}; - deleteExtensionById(extensionId: any): void; - getReplaceableExtensionInfo(): any[]; - getExtensionInfoById(extensionId: any): any; - replaceExtensionWithId(newId: any, oldId: any): void; - isExtensionURLLoaded(extensionURL: any): boolean; - getExtensionURLs(): {}; - } - namespace ExtensionManager { - export { - ArgumentInfo, - ConvertedBlockInfo, - CategoryInfo, - PendingExtensionWorker, - }; - } - import SecurityManager = require("scratch-vm-dts/extension-support/tw-security-manager"); - /** - * - Information about an extension block argument - */ - type ArgumentInfo = { - /** - * - the type of value this argument can take - */ - type: ArgumentType; - /** - * - the default value of this argument (default: blank) - */ - default: any | undefined; - }; - /** - * - Raw extension block data paired with processed data ready for scratch-blocks - */ - type ConvertedBlockInfo = { - /** - * - the raw block info - */ - info: ExtensionBlockMetadata; - /** - * - the scratch-blocks JSON definition for this block - */ - json: object; - /** - * - the scratch-blocks XML definition for this block - */ - xml: string; - }; - /** - * - Information about a block category - */ - type CategoryInfo = { - /** - * - the unique ID of this category - */ - id: string; - /** - * - the human-readable name of this category - */ - name: string; - /** - * - optional URI for the block icon image - */ - blockIconURI: string | undefined; - /** - * - the primary color for this category, in '#rrggbb' format - */ - color1: string; - /** - * - the secondary color for this category, in '#rrggbb' format - */ - color2: string; - /** - * - the tertiary color for this category, in '#rrggbb' format - */ - color3: string; - /** - * - the blocks, separators, etc. in this category - */ - blocks: Array; - /** - * - the menus provided by this category - */ - menus: Array; - }; - /** - * - Information about an extension worker still initializing - */ - type PendingExtensionWorker = { - /** - * - the URL of the extension to be loaded by this worker - */ - extensionURL: string; - /** - * - function to call on successful worker startup - */ - resolve: Function; - /** - * - function to call on failed worker startup - */ - reject: Function; - }; -} - -declare module "scratch-vm-dts/sprites/sprite" { - export = Sprite; - type Runtime = import("scratch-vm-dts/engine/runtime"); - class int extends Number { } - class Sprite { - /** - * Sprite to be used on the Scratch stage. - * All clones of a sprite have shared blocks, shared costumes, shared variables, - * shared sounds, etc. - * @param {?Blocks} blocks Shared blocks object for all clones of sprite. - * @param {Runtime} runtime Reference to the runtime. - * @param {?Frames} frames Shared frames object for all clones of sprite. - * @constructor - */ - constructor(blocks: Blocks | null, runtime: Runtime, frames: Frames | null); - runtime: any; - blocks: Blocks; - frames: Frames; - /** - * Human-readable name for this sprite (and all clones). - * @type {string} - */ - name: string; - /** - * List of costumes for this sprite. - * Each entry is an object, e.g., - * { - * skinId: 1, - * name: "Costume Name", - * bitmapResolution: 2, - * rotationCenterX: 0, - * rotationCenterY: 0 - * } - * @type {Array.} - */ - costumes_: Array; - /** - * List of sounds for this sprite. - */ - sounds: any[]; - /** - * List of clones for this sprite, including the original. - * @type {Array.} - */ - clones: Array; - soundBank: any; - /** - * Add an array of costumes, taking care to avoid duplicate names. - * @param {!Array} costumes Array of objects representing costumes. - */ - set costumes(costumes: Array); - /** - * Get full costume list - * @return {object[]} list of costumes. Note that mutating the returned list will not - * mutate the list on the sprite. The sprite list should be mutated by calling - * addCostumeAt, deleteCostumeAt, or setting costumes. - */ - get costumes(): object[]; - /** - * Add a costume at the given index, taking care to avoid duplicate names. - * @param {!object} costumeObject Object representing the costume. - * @param {!int} index Index at which to add costume - */ - addCostumeAt(costumeObject: object, index: int): void; - /** - * Delete a costume by index. - * @param {number} index Costume index to be deleted - * @return {?object} The deleted costume - */ - deleteCostumeAt(index: number): object | null; - /** - * Create a clone of this sprite. - * @param {string=} optLayerGroup Optional layer group the clone's drawable should be added to - * Defaults to the sprite layer group - * @returns {!RenderedTarget} Newly created clone. - */ - createClone(optLayerGroup?: string | undefined): RenderedTarget; - /** - * Disconnect a clone from this sprite. The clone is unmodified. - * In particular, the clone's dispose() method is not called. - * @param {!RenderedTarget} clone - the clone to be removed. - */ - removeClone(clone: RenderedTarget): void; - cloneCount(): number; - duplicate(): Promise; - dispose(): void; - } - import Blocks = require("scratch-vm-dts/engine/blocks"); - import Frames = require("scratch-vm-dts/engine/frame"); - import RenderedTarget = require("scratch-vm-dts/sprites/rendered-target"); -} - -declare module "scratch-vm-dts/sprites/rendered-target" { - export = RenderedTarget; - type Runtime = import("scratch-vm-dts/engine/runtime"); - type Sprite = import("scratch-vm-dts/sprites/sprite"); - class RenderWebGL { } - class int extends Number { } - /** - * Rendered target: instance of a sprite (clone), or the stage. - */ - class RenderedTarget extends Target { - /** - * Rotation style for "all around"/spinning. - * @type {string} - */ - static get ROTATION_STYLE_ALL_AROUND(): string; - /** - * Rotation style for "left-right"/flipping. - * @type {string} - */ - static get ROTATION_STYLE_LEFT_RIGHT(): string; - /** - * Rotation style for "no rotation." - * @type {string} - */ - static get ROTATION_STYLE_NONE(): string; - /** - * Available states for video input. - * @enum {string} - */ - static get VIDEO_STATE(): { - OFF: string; - ON: string; - ON_FLIPPED: string; - }; - /** - * @param {!Sprite} sprite Reference to the parent sprite. - * @param {Runtime} runtime Reference to the runtime. - * @constructor - */ - constructor(sprite: Sprite, runtime: Runtime); - /** - * Reference to the sprite that this is a render of. - * @type {!Sprite} - */ - sprite: Sprite; - /** - * Reference to the global renderer for this VM, if one exists. - * @type {?RenderWebGL} - */ - renderer: RenderWebGL | null; - /** - * ID of the drawable for this rendered target, - * returned by the renderer, if rendered. - * @type {?Number} - */ - drawableID: number | null; - /** - * Drag state of this rendered target. If true, x/y position can't be - * changed by blocks. - * @type {boolean} - */ - dragging: boolean; - /** - * Map of current graphic effect values. - * @type {!Object.} - */ - effects: { - [x: string]: number; - }; - /** - * Whether this represents an "original" non-clone rendered-target for a sprite, - * i.e., created by the editor and not clone blocks. - * @type {boolean} - */ - isOriginal: boolean; - /** - * Whether this rendered target represents the Scratch stage. - * @type {boolean} - */ - isStage: boolean; - /** - * Scratch X coordinate. Currently should range from -240 to 240. - * @type {Number} - */ - _x: number; - /** - * Scratch Y coordinate. Currently should range from -180 to 180. - * @type {number} - */ - _y: number; - /** - * Scratch direction. Currently should range from -179 to 180. - * @type {number} - */ - direction: number; - /** - * Whether the rendered target is draggable on the stage - * @type {boolean} - */ - draggable: boolean; - /** - * Whether the rendered target is currently visible. - * @type {boolean} - */ - _visible: boolean; - /** - * Size of rendered target as a percent of costume size. - * @type {number} - */ - _size: number; - /** - * Non-uniform scale dimensions of rendered target as a percent of original size. - */ - _size2d: number[]; - /** - * Currently selected costume index. - * @type {number} - */ - currentCostume: number; - /** - * Current rotation style. - * @type {!string} - */ - rotationStyle: string; - /** - * Loudness for sound playback for this target, as a percentage. - * @type {number} - */ - volume: number; - /** - * Current tempo (used by the music extension). - * This property is global to the project and stored in the stage. - * @type {number} - */ - tempo: number; - /** - * The transparency of the video (used by extensions with camera input). - * This property is global to the project and stored in the stage. - * @type {number} - */ - videoTransparency: number; - /** - * The state of the video input (used by extensions with camera input). - * This property is global to the project and stored in the stage. - * - * Defaults to ON. This setting does not turn the video by itself. A - * video extension once loaded will set the video device to this - * setting. Set to ON when a video extension is added in the editor the - * video will start ON. If the extension is loaded as part of loading a - * saved project the extension will see the value set when the stage - * was loaded from the saved values including the video state. - * - * @type {string} - */ - videoState: string; - /** - * The language to use for speech synthesis, in the text2speech extension. - * It is initialized to null so that on extension load, we can check for - * this and try setting it using the editor locale. - * @type {string} - */ - textToSpeechLanguage: string; - onTargetMoved: any; - onTargetVisualChange: any; - interpolationData: any; - extractProperties: {}; - isModule: any; - set size(size: number); - get size(): number; - set size2d([width, height]: number[]); - get size2d(): number[]; - set visible(visible: boolean); - get visible(): boolean; - set x(x: number); - get x(): number; - set y(y: number); - get y(): number; - get originalTargetId(): any; - /** - * Create a drawable with the this.renderer. - * @param {boolean} layerGroup The layer group this drawable should be added to - */ - initDrawable(layerGroup: boolean): void; - get audioPlayer(): { - playSound: (soundId: any) => any; - }; - /** - * Initialize the audio player for this sprite or clone. - */ - initAudio(): void; - emitVisualChange(): void; - /** - * Set the X and Y coordinates. - * @param {!number} x New X coordinate, in Scratch coordinates. - * @param {!number} y New Y coordinate, in Scratch coordinates. - * @param {?boolean} force Force setting X/Y, in case of dragging - */ - setXY(x: number, y: number, force: boolean | null): void; - /** - * Get the rendered direction and scale, after applying rotation style. - * @return {object} Direction and scale to render. - */ - _getRenderedDirectionAndScale(): object; - /** - * Set the direction. - * @param {!number} direction New direction. - */ - setDirection(direction: number): void; - /** - * Set draggability; i.e., whether it's able to be dragged in the player - * @param {!boolean} draggable True if should be draggable. - */ - setDraggable(draggable: boolean): void; - /** - * Set visibility; i.e., whether it's shown or hidden. - * @param {!boolean} visible True if should be shown. - */ - setVisible(visible: boolean): void; - /** - * Set size, as a percentage of the costume size. - * @param {!number} size Size of rendered target, as % of costume size. - */ - setSize(size: number): void; - /** - * Set a particular graphic effect value. - * @param {!string} effectName Name of effect (see `RenderedTarget.prototype.effects`). - * @param {!number} value Numerical magnitude of effect. - */ - setEffect(effectName: string, value: number): void; - /** - * Clear all graphic effects on this rendered target. - */ - clearEffects(): void; - /** - * Set the current costume. - * @param {number} index New index of costume. - */ - setCostume(index: number): void; - /** - * Add a costume, taking care to avoid duplicate names. - * @param {!object} costumeObject Object representing the costume. - * @param {?int} index Index at which to add costume - * @param {?boolean} isRemoteOperation Whether this is a remote operation - */ - addCostume( - costumeObject: object, - index: int | null, - isRemoteOperation: boolean | null - ): void; - /** - * Rename a costume, taking care to avoid duplicate names. - * @param {int} costumeIndex - the index of the costume to be renamed. - * @param {string} newName - the desired new name of the costume (will be modified if already in use). - * @param {boolean} [sendNameChangedEvent = true] whether to send an event when the name changes. - */ - renameCostume( - costumeIndex: int, - newName: string, - sendNameChangedEvent?: boolean - ): void; - /** - * Delete a costume by index. - * @param {number} index Costume index to be deleted - * @param {?boolean} isRemoteOperation Whether this is a remote operation - * @return {?object} The costume that was deleted or null - * if the index was out of bounds of the costumes list or - * this target only has one costume. - */ - deleteCostume( - index: number, - isRemoteOperation: boolean | null - ): object | null; - /** - * Add a sound, taking care to avoid duplicate names. - * @param {!object} soundObject Object representing the sound. - * @param {?int} index Index at which to add costume - */ - addSound(soundObject: object, index: int | null): void; - /** - * Rename a sound, taking care to avoid duplicate names. - * @param {int} soundIndex - the index of the sound to be renamed. - * @param {string} newName - the desired new name of the sound (will be modified if already in use). - * @param {boolean} [sendNameChangedEvent = true] whether to send an event when the name changes. - * @return {string} The new name of the sound. - */ - renameSound( - soundIndex: int, - newName: string, - sendNameChangedEvent?: boolean - ): string; - /** - * Delete a sound by index. - * @param {number} index Sound index to be deleted - * @return {object} The deleted sound object, or null if no sound was deleted. - */ - deleteSound(index: number): object; - /** - * Update the rotation style. - * @param {!string} rotationStyle New rotation style. - */ - setRotationStyle(rotationStyle: string): void; - /** - * Get a costume index of this rendered target, by name of the costume. - * @param {?string} costumeName Name of a costume. - * @return {number} Index of the named costume, or -1 if not present. - */ - getCostumeIndexByName(costumeName: string | null): number; - /** - * Get a costume index of this rendered target, by id of the costume. - * @param {?string} costumeId Id of a costume. - * @return {number} Index of the named costume, or -1 if not present. - */ - getCostumeIndexById(costumeId: string | null): number; - getCostumeById(id: any): object | null; - /** - * Get a costume of this rendered target by id. - * @return {object} current costume - */ - getCurrentCostume(): object; - /** - * Get full costume list - * @return {object[]} list of costumes - */ - getCostumes(): object[]; - /** - * Reorder costume list by moving costume at costumeIndex to newIndex. - * @param {!number} costumeIndex Index of the costume to move. - * @param {!number} newIndex New index for that costume. - * @returns {boolean} If a change occurred (i.e. if the indices do not match) - */ - reorderCostume(costumeIndex: number, newIndex: number): boolean; - /** - * Reorder sound list by moving sound at soundIndex to newIndex. - * @param {!number} soundIndex Index of the sound to move. - * @param {!number} newIndex New index for that sound. - * @returns {boolean} If a change occurred (i.e. if the indices do not match) - */ - reorderSound(soundIndex: number, newIndex: number): boolean; - /** - * Get full sound list - * @return {object[]} list of sounds - */ - getSounds(): object[]; - /** - * Get a sound index of this rendered target, by id of the sound. - * @param {?string} soundId Id of a sound. - * @return {number} Index of the named sound, or -1 if not present. - */ - getSoundIndexById(soundId: string | null): number; - getSoundById(id: any): object | null; - /** - * Update all drawable properties for this rendered target. - * Use when a batch has changed, e.g., when the drawable is first created. - */ - updateAllDrawableProperties(): void; - /** - * Return whether this rendered target is a sprite (not a clone, not the stage). - * @return {boolean} True if not a clone and not the stage. - */ - isSprite(): boolean; - /** - * Return the rendered target's tight bounding box. - * Includes top, left, bottom, right attributes in Scratch coordinates. - * @return {?object} Tight bounding box, or null. - */ - getBounds(): object | null; - /** - * Return the bounding box around a slice of the top 8px of the rendered target. - * Includes top, left, bottom, right attributes in Scratch coordinates. - * @return {?object} Tight bounding box, or null. - */ - getBoundsForBubble(): object | null; - /** - * Return whether this target is touching the mouse, an edge, or a sprite. - * @param {string} requestedObject an id for mouse or edge, or a sprite name. - * @return {boolean} True if the sprite is touching the object. - */ - isTouchingObject(requestedObject: string): boolean; - /** - * Return whether touching a point. - * @param {number} x X coordinate of test point. - * @param {number} y Y coordinate of test point. - * @return {boolean} True iff the rendered target is touching the point. - */ - isTouchingPoint(x: number, y: number): boolean; - /** - * Return whether touching a stage edge. - * @return {boolean} True iff the rendered target is touching the stage edge. - */ - isTouchingEdge(): boolean; - /** - * Return whether touching any of a named sprite's clones. - * @param {string} spriteName Name of the sprite. - * @return {boolean} True iff touching a clone of the sprite. - */ - isTouchingSprite(spriteName: string): boolean; - /** - * Return whether touching a color. - * @param {Array.} rgb [r,g,b], values between 0-255. - * @return {Promise.} True iff the rendered target is touching the color. - */ - isTouchingColor(rgb: Array): Promise; - /** - * Return whether rendered target's color is touching a color. - * @param {object} targetRgb {Array.} [r,g,b], values between 0-255. - * @param {object} maskRgb {Array.} [r,g,b], values between 0-255. - * @return {Promise.} True iff the color is touching the color. - */ - colorIsTouchingColor(targetRgb: object, maskRgb: object): Promise; - getLayerOrder(): any; - /** - * Move to the front layer. - */ - goToFront(): void; - /** - * Move to the back layer. - */ - goToBack(): void; - /** - * Move forward a number of layers. - * @param {number} nLayers How many layers to go forward. - */ - goForwardLayers(nLayers: number): void; - /** - * Move backward a number of layers. - * @param {number} nLayers How many layers to go backward. - */ - goBackwardLayers(nLayers: number): void; - /** - * Move behind some other rendered target. - * @param {!RenderedTarget} other Other rendered target to move behind. - */ - goBehindOther(other: RenderedTarget): void; - /** - * Keep a desired position within a fence. - * @param {number} newX New desired X position. - * @param {number} newY New desired Y position. - * @param {object=} optFence Optional fence with left, right, top bottom. - * @return {Array.} Fenced X and Y coordinates. - */ - keepInFence( - newX: number, - newY: number, - optFence?: object | undefined - ): Array; - /** - * Make a clone, copying any run-time properties. - * If we've hit the global clone limit, returns null. - * @return {RenderedTarget} New clone. - */ - makeClone(): RenderedTarget; - /** - * Make a duplicate using a duplicate sprite. - * @return {RenderedTarget} New clone. - */ - duplicate(): RenderedTarget; - /** - * Called when the project receives a "stop all" - * Stop all sounds and clear graphic effects. - */ - onStopAll(): void; - /** - * Post/edit sprite info. - * @param {object} data An object with sprite info data to set. - */ - postSpriteInfo(data: object): void; - /** - * Put the sprite into the drag state. While in effect, setXY must be forced - */ - startDrag(): void; - /** - * Remove the sprite from the drag state. - */ - stopDrag(): void; - /** - * Serialize sprite info, used when emitting events about the sprite - * @returns {object} Sprite data as a simple object - */ - toJSON(): object; - } - import Target from "scratch-vm-dts/engine/target"; -} - -declare module "scratch-vm-dts/engine/blocks" { - export = Blocks; - type Target = import("scratch-vm-dts/engine/target"); - /** - * Create a block container. - * @param {Runtime} runtime The runtime this block container operates within - * @param {boolean} optNoGlow Optional flag to indicate that blocks in this container - * should not request glows. This does not affect glows when clicking on a block to execute it. - */ - class Blocks { - /** - * Blockly inputs that represent statements/branch. - * are prefixed with this string. - * @const{string} - */ - static get BRANCH_INPUT_PREFIX(): string; - constructor(runtime: any, optNoGlow: any); - runtime: any; - /** - * All blocks in the workspace. - * Keys are block IDs, values are metadata about the block. - * @type {Object.} - */ - _blocks: { - [id: string]: Object; - }; - /** - * All top-level scripts in the workspace. - * A list of block IDs that represent scripts (i.e., first block in script). - * @type {Array.} - */ - _scripts: Array; - _cache: { - /** - * Cache block inputs by block id - * @type {object.>} - */ - inputs: { [key: string]: Array }; - /** - * Cache procedure Param Names by block id - * @type {object.>} - */ - procedureParamNames: { [key: string]: Array }; - /** - * Cache procedure definitions by block id - * @type {object.} - */ - procedureDefinitions: { [key: string]: string | null }; - /** - * A cache for execute to use and store on. Only available to - * execute. - * @type {object.} - */ - _executeCached: { [key: string]: object }; - /** - * A cache of block IDs and targets to start threads on as they are - * actively monitored. - * @type {Array<{blockId: string, target: Target}>} - */ - _monitored: Array<{ - blockId: string; - target: Target; - }>; - /** - * A cache of hat opcodes to collection of theads to execute. - * @type {object.} - */ - scripts: { [key: string]: object }; - /** - * tw: A cache of top block (usually hat, but not always) opcodes to compiled scripts. - * @type {object.} - */ - compiledScripts: { [key: string]: object }; - /** - * tw: A cache of procedure code opcodes to a parsed intermediate representation - * @type {object.} - */ - compiledProcedures: { [key: string]: object }; - /** - * tw: Whether populateProcedureCache has been run - */ - proceduresPopulated: boolean; - }; - /** - * Flag which indicates that blocks in this container should not glow. - * Blocks will still glow when clicked on, but this flag is used to control - * whether the blocks in this container can request a glow as part of - * a running stack. E.g. the flyout block container and the monitor block container - * should not be able to request a glow, but blocks containers belonging to - * sprites should. - * @type {boolean} - */ - forceNoGlow: boolean; - /** - * Get the cached compilation result of a block. - * @param {string} blockId ID of the top block. - * @returns {{success: boolean; value: any}|null} Cached success or error, or null if there is no cached value. - */ - getCachedCompileResult(blockId: string): { - success: boolean; - value: any; - } | null; - /** - * Set the cached compilation result of a script. - * @param {string} blockId ID of the top block. - * @param {*} value The compilation result to store. - */ - cacheCompileResult(blockId: string, value: any): void; - /** - * Set the cached error of a script. - * @param {string} blockId ID of the top block. - * @param {*} error The error to store. - */ - cacheCompileError(blockId: string, error: any): void; - /** - * Provide an object with metadata for the requested block ID. - * @param {!string} blockId ID of block we have stored. - * @return {?object} Metadata about the block, if it exists. - */ - getBlock(blockId: string): object | null; - /** - * Get all known top-level blocks that start scripts. - * @return {Array.} List of block IDs. - */ - getScripts(): Array; - /** - * Get the next block for a particular block - * @param {?string} id ID of block to get the next block for - * @return {?string} ID of next block in the sequence - */ - getNextBlock(id: string | null): string | null; - /** - * Get the branch for a particular C-shaped block. - * @param {?string} id ID for block to get the branch for. - * @param {?number} branchNum Which branch to select (e.g. for if-else). - * @return {?string} ID of block in the branch. - */ - getBranch(id: string | null, branchNum: number | null): string | null; - /** - * Get the opcode for a particular block - * @param {?object} block The block to query - * @return {?string} the opcode corresponding to that block - */ - getOpcode(block: object | null): string | null; - /** - * Get all fields and their values for a block. - * @param {?object} block The block to query. - * @return {?object} All fields and their values. - */ - getFields(block: object | null): object | null; - /** - * Get all non-branch inputs for a block. - * @param {?object} block the block to query. - * @return {?Array.} All non-branch inputs and their associated blocks. - */ - getInputs(block: object | null): Array | null; - /** - * Get mutation data for a block. - * @param {?object} block The block to query. - * @return {?object} Mutation for the block. - */ - getMutation(block: object | null): object | null; - /** - * Get the top-level script for a given block. - * @param {?string} id ID of block to query. - * @return {?string} ID of top-level script block. - */ - getTopLevelScript(id: string | null): string | null; - getGlobalProceduresXML(): string[]; - /** - * Get the procedure definition for a given name. - * @param {?string} name Name of procedure to query. - * @return {?string} ID of procedure definition. - */ - getProcedureDefinition(name: string | null): string | null; - getGlobalProcedureAndTarget(name: any): any[]; - /** - * Get names and ids of parameters for the given procedure. - * @param {?string} name Name of procedure to query. - * @return {?Array.} List of param names for a procedure. - */ - getProcedureParamNamesAndIds(name: string | null): Array | null; - /** - * Get names, ids, and defaults of parameters for the given procedure. - * @param {?string} name Name of procedure to query. - * @return {?Array.} List of param names for a procedure. - */ - _getProcedureParamNamesIdsAndDefaults( - name: string | null - ): Array | null; - /** CCW: for global procedure - * Get names, ids, and defaults of parameters for the given procedure. - * @param {?string} name Name of procedure to query. - * @param {?boolean} isGlobal need look up procedures from all runtime targets - * @return {?Array.} List of param names for a procedure. - */ - getProcedureParamNamesIdsAndDefaults( - name: string | null, - isGlobal: boolean | null - ): Array | null; - /** - * tw: Setup the procedureParamNames and procedureDefinitions caches all at once. - * This makes subsequent calls to these methods faster. - */ - populateProcedureCache(): void; - updateGlobalProcedure(oldProccode: any, newMutation: any): any[]; - duplicate(): Blocks; - /** - * Create event listener for blocks, variables, and comments. Handles validation and - * serves as a generic adapter between the blocks, variables, and the - * runtime interface. - * @param {object} e Blockly "block" or "variable" event - * @param {string} source Who triggered this function - */ - blocklyListen(e: object, source: string): void; - /** - * Reset all runtime caches. - */ - resetCache(): void; - /** - * Emit a project changed event if this is a block container - * that can affect the project state. - */ - emitProjectChanged(): void; - emitCustomBlockArgumentsLengthChanged(): void; - /** - * Block management: create blocks and scripts from a `create` event - * @param {!object} block Blockly create event to be processed - * @return {boolean} Whether the block successfully created - */ - createBlock(block: object, source: any): boolean; - /** - * Block management: change block field values - * @param {!object} args Blockly change event to be processed - * @param {boolean} isRuntimeOp Whether it is an operation at run time - */ - changeBlock(args: object, isRuntimeOp: boolean): void; - updateBlockMutation(block: any, args: any): void; - /** - * Block management: move blocks from parent to parent - * @param {!object} e Blockly move event to be processed - */ - moveBlock(e: object): void; - /** - * Block management: run all blocks. - * @param {!object} runtime Runtime to run all blocks in. - */ - runAllMonitored(runtime: object): void; - /** - * Block management: delete blocks and their associated scripts. Does nothing if a block - * with the given ID does not exist. - * @param {!string} blockId Id of block to delete - */ - deleteBlock(blockId: string, params?: {}): void; - /** - * Delete all blocks and their associated scripts. - */ - deleteAllBlocks(): void; - /** - * Returns a map of all references to variables or lists from blocks - * in this block container. - * @param {Array} optBlocks Optional list of blocks to constrain the search to. - * This is useful for getting variable/list references for a stack of blocks instead - * of all blocks on the workspace - * @param {?boolean} optIncludeBroadcast Optional whether to include broadcast fields. - * @return {object} A map of variable ID to a list of all variable references - * for that ID. A variable reference contains the field referencing that variable - * and also the type of the variable being referenced. - */ - getAllVariableAndListReferences( - optBlocks: Array, - optIncludeBroadcast: boolean | null - ): object; - getAllVariableAndListWithBlocks( - blocks: any, - optIncludeBroadcast: any - ): any[][]; - /** - * Keep blocks up to date after a variable gets renamed. - * @param {string} varId The id of the variable that was renamed - * @param {string} newName The new name of the variable that was renamed - */ - updateBlocksAfterVarRename(varId: string, newName: string): any[][]; - /** - * Keep blocks up to date after they are shared between targets. - * @param {boolean} isStage If the new target is a stage. - */ - updateTargetSpecificBlocks(isStage: boolean): void; - /** - * Update blocks after a sound, costume, or backdrop gets renamed. - * Any block referring to the old name of the asset should get updated - * to refer to the new name. - * @param {string} oldName The old name of the asset that was renamed. - * @param {string} newName The new name of the asset that was renamed. - * @param {string} assetType String representation of the kind of asset - * @param {?string} targetId The ID of the target to emit block changes for (optional). - * that was renamed. This can be one of 'sprite','costume', 'sound', or - * 'backdrop'. - */ - updateAssetName( - oldName: string, - newName: string, - assetType: string, - targetId: string | null - ): void; - /** - * Update sensing_of blocks after a variable gets renamed. - * @param {string} oldName The old name of the variable that was renamed. - * @param {string} newName The new name of the variable that was renamed. - * @param {string} targetName The name of the target the variable belongs to. - * @return {boolean} Returns true if any of the blocks were updated. - */ - updateSensingOfReference( - oldName: string, - newName: string, - targetName: string - ): boolean; - /** - * Helper function to retrieve a costume menu field from a block given its id. - * @param {string} blockId A unique identifier for a block - * @return {?object} The costume menu field of the block with the given block id. - * Null if either a block with the given id doesn't exist or if a costume menu field - * does not exist on the block with the given id. - */ - _getCostumeField(blockId: string): object | null; - /** - * Helper function to retrieve a sound menu field from a block given its id. - * @param {string} blockId A unique identifier for a block - * @return {?object} The sound menu field of the block with the given block id. - * Null, if either a block with the given id doesn't exist or if a sound menu field - * does not exist on the block with the given id. - */ - _getSoundField(blockId: string): object | null; - /** - * Helper function to retrieve a backdrop menu field from a block given its id. - * @param {string} blockId A unique identifier for a block - * @return {?object} The backdrop menu field of the block with the given block id. - * Null, if either a block with the given id doesn't exist or if a backdrop menu field - * does not exist on the block with the given id. - */ - _getBackdropField(blockId: string): object | null; - /** - * Helper function to retrieve a sprite menu field from a block given its id. - * @param {string} blockId A unique identifier for a block - * @return {?object} The sprite menu field of the block with the given block id. - * Null, if either a block with the given id doesn't exist or if a sprite menu field - * does not exist on the block with the given id. - */ - _getSpriteField(blockId: string): object | null; - /** - * Encode all of `this._blocks` as an XML string usable - * by a Blockly/scratch-blocks workspace. - * @param {object} comments Map of comments referenced by id - * @return {string} String of XML representing this object's blocks. - */ - toXML(comments: any): string; - /** - * Recursively encode an individual block and its children - * into a Blockly/scratch-blocks XML string. - * @param {!string} blockId ID of block to encode. - * @param {object} comments Map of comments referenced by id - * @return {string} String of XML representing this block and any children. - */ - blockToXML( - blockId: string, - comments: {[id:string]:Comment}, - blocks?: { - [id: string]: Object; - } - ): string; - /** - * Recursively encode a mutation object to XML. - * @param {!object} mutation Object representing a mutation. - * @return {string} XML string representing a mutation. - */ - mutationToXML(mutation: object): string; - /** - * Helper to serialize block fields and input fields for reporting new monitors - * @param {!object} block Block to be paramified. - * @return {!object} object of param key/values. - */ - _getBlockParams(block: object): object; - /** - * Helper to get the corresponding internal procedure definition block - * @param {!object} defineBlock Outer define block. - * @return {!object} internal definition block which has the mutation. - */ - _getCustomBlockInternal(defineBlock: object): object; - /** - * Helper to add a stack to `this._scripts`. - * @param {?string} topBlockId ID of block that starts the script. - * @return {boolean} Whether added successfully. - */ - _addScript(topBlockId: string | null): boolean; - /** - * Helper to remove a script from `this._scripts`. - * @param {?string} topBlockId ID of block that starts the script. - */ - _deleteScript(topBlockId: string | null): void; - } -} - -declare module "scratch-vm-dts/engine/frame" { - export = Frames; - /** - * Create a frame container. - * @param {Runtime} runtime The runtime this frame container operates within - */ - class Frames { - constructor(runtime: any); - runtime: any; - /** - * All frames in the workspace. - * Keys are frame IDs, values are metadata about the frame. - * @type {Object.} - */ - _frames: { - [x: string]: Object; - }; - /** - * Provide an object with metadata for the requested frame ID. - * @param {!string} frameId ID of frame we have stored. - * @return {?object} Metadata about the frame, if it exists. - */ - getFrame(frameId: string): object | null; - duplicate(): Frames; - /** - * Create event listener for frames. Handles validation and - * serves as a generic adapter between the frames, variables, and the - * runtime interface. - * @param {object} e Blockly "frame" event - */ - blocklyListen(e: object): void; - /** - * Emit a project changed event - * that can affect the project state. - */ - emitProjectChanged(): void; - /** - * Frame management: create frames from a `create` event - * @param {!object} e Blockly create event to be processed - */ - createFrame(e: object): boolean; - /** - * Frame management: delete frame. Does nothing if a frame with the given ID does not exist. - * @param {!string} id Id of frame to delete - */ - deleteFrame(id: string): boolean; - /** - * Frame management: delete frame. Does nothing if a frame with the given ID does not exist. - * @param {!string} id Id of frame to delete - * @param {!string} newTitle New title - */ - retitleFrame(id: string, newTitle: string): boolean; - /** - * Frame management: change frame field values - * @param {!string} id Id of the frame - * @param {string} element One of 'rect', 'blocks', 'disabled', etc. - * @param {*} value Previous value of element. - */ - changeFrame(id: string, element: string, value: any): boolean; - /** - * Recursively encode an individual frame into a Blockly/scratch-block XML string. - * @param {!string} id ID of frame to encode. - * @return {string} String of XML representing this frame. - */ - toXML(id: string): string; - frameToXML(frame: any): string; - } -} - -declare module "scratch-vm-dts/engine/variable" { - export = Variable; - class Variable { - /** - * Type representation for scalar variables. - * This is currently represented as '' - * for compatibility with blockly. - * @const {string} - */ - static get SCALAR_TYPE(): string; - /** - * Type representation for list variables. - * @const {string} - */ - static get LIST_TYPE(): string; - /** - * Type representation for list variables. - * @const {string} - */ - static get BROADCAST_MESSAGE_TYPE(): string; - /** - * @param {string} id Id of the variable. - * @param {string} name Name of the variable. - * @param {string} type Type of the variable, one of '' or 'list' - * @param {boolean} isCloud Whether the variable is stored in the cloud. - * @constructor - */ - constructor( - id: string, - name: string, - type: string, - isCloud: boolean, - targetId: any - ); - id: string; - name: string; - type: string; - isCloud: boolean; - targetId: any; - value: string | number | any[]; - toXML(isLocal: any): string; - } -} - -declare module "scratch-vm-dts/util/timer" { - export = Timer; - /** - * @fileoverview - * A utility for accurately measuring time. - * To use: - * --- - * var timer = new Timer(); - * timer.start(); - * ... pass some time ... - * var timeDifference = timer.timeElapsed(); - * --- - * Or, you can use the `time` function - * to do some measurement yourself. - */ - class Timer { - /** - * Disable use of self.performance for now as it results in lower performance - * However, instancing it like below (caching the self.performance to a local variable) negates most of the issues. - * @type {boolean} - */ - static get USE_PERFORMANCE(): boolean; - /** - * Legacy object to allow for us to call now to get the old style date time (for backwards compatibility) - * @deprecated This is only called via the nowObj.now() if no other means is possible... - */ - static get legacyDateCode(): { - now: () => number; - }; - /** - * Use this object to route all time functions through single access points. - */ - static get nowObj(): { - now: () => number; - }; - constructor(nowObj?: { now: () => number }); - /** - * Used to store the start time of a timer action. - * Updated when calling `timer.start`. - */ - startTime: number; - /** - * Used to pass custom logic for determining the value for "now", - * which is sometimes useful for compatibility with Scratch 2 - */ - nowObj: { - now: () => number; - }; - /** - * Return the currently known absolute time, in ms precision. - * @returns {number} ms elapsed since 1 January 1970 00:00:00 UTC. - */ - time(): number; - /** - * Start a timer for measuring elapsed time, - * at the most accurate precision possible. - */ - start(): void; - timeElapsed(): number; - /** - * Call a handler function after a specified amount of time has elapsed. - * @param {function} handler - function to call after the timeout - * @param {number} timeout - number of milliseconds to delay before calling the handler - * @returns {number} - the ID of the new timeout - */ - setTimeout(handler: Function, timeout: number): number; - /** - * Clear a timeout from the pending timeout pool. - * @param {number} timeoutId - the ID returned by `setTimeout()` - * @memberof Timer - */ - clearTimeout(timeoutId: number): void; - } -} - -declare module "scratch-vm-dts/engine/thread" { - export = Thread; - type Target = import("scratch-vm-dts/engine/target"); - type Blocks = import("scratch-vm-dts/engine/blocks"); - type Timer = import("scratch-vm-dts/util/timer"); - /** - * A thread is a running stack context and all the metadata needed. - * @param {?string} firstBlock First block to execute in the thread. - * @constructor - */ - class Thread { - /** - * Thread status for initialized or running thread. - * This is the default state for a thread - execution should run normally, - * stepping from block to block. - * @const - */ - static get STATUS_RUNNING(): number; - /** - * Threads are in this state when a primitive is waiting on a promise; - * execution is paused until the promise changes thread status. - * @const - */ - static get STATUS_PROMISE_WAIT(): number; - /** - * Thread status for yield. - * @const - */ - static get STATUS_YIELD(): number; - /** - * Thread status for a single-tick yield. This will be cleared when the - * thread is resumed. - * @const - */ - static get STATUS_YIELD_TICK(): number; - /** - * Thread status for a finished/done thread. - * Thread is in this state when there are no more blocks to execute. - * @const - */ - static get STATUS_DONE(): number; - /** - * @param {Target} target The target running the thread. - * @param {string} topBlock ID of the thread's top block. - * @returns {string} A unique ID for this target and thread. - */ - static getIdFromTargetAndBlock(target: Target, topBlock: string): string; - constructor(firstBlock: any); - /** - * ID of top block of the thread - * @type {!string} - */ - topBlock: string; - /** - * Stack for the thread. When the sequencer enters a control structure, - * the block is pushed onto the stack so we know where to exit. - * @type {Array.} - */ - stack: Array; - /** - * Stack frames for the thread. Store metadata for the executing blocks. - * @type {Array.<_StackFrame>} - */ - stackFrames: Array<_StackFrame>; - /** - * Status of the thread, one of three states (below) - * @type {number} - */ - status: number; - /** - * Whether the thread is killed in the middle of execution. - * @type {boolean} - */ - isKilled: boolean; - /** - * Target of this thread. - * @type {?Target} - */ - target: Target | null; - /** - * The Blocks this thread will execute. - * @type {Blocks} - */ - blockContainer: Blocks; - /** - * Whether the thread requests its script to glow during this frame. - * @type {boolean} - */ - requestScriptGlowInFrame: boolean; - /** - * Which block ID should glow during this frame, if any. - * @type {?string} - */ - blockGlowInFrame: string | null; - /** - * A timer for when the thread enters warp mode. - * Substitutes the sequencer's count toward WORK_TIME on a per-thread basis. - * @type {?Timer} - */ - warpTimer: Timer | null; - justReported: any; - triedToCompile: boolean; - isCompiled: boolean; - timer: any; - /** - * The thread's generator. - * @type {Generator} - */ - generator: Generator; - /** - * @type {Object.} - */ - procedures: { - [x: string]: any; - }; - stackClick: boolean; - updateMonitor: boolean; - /** - * store hat param. - * @type {Object} - */ - hatParam: Object; - executableHat: boolean; - compatibilityStackFrame: any; - getId(): string; - getCurrentGlobalTarget(): any; - /** - * Push stack and update stack frames appropriately. - * @param {string} blockId Block ID to push to stack. - * @param {Target} target CCW: the target execute in this stack frame, for global procedure. - */ - pushStack(blockId: string, target: Target): void; - /** - * Reset the stack frame for use by the next block. - * (avoids popping and re-pushing a new stack frame - keeps the warpmode the same - * @param {string} blockId Block ID to push to stack. - */ - reuseStackForNextBlock(blockId: string): void; - /** - * Pop last block on the stack and its stack frame. - * @return {string} Block ID popped from the stack. - */ - popStack(): string; - /** - * Pop back down the stack frame until we hit a procedure call or the stack frame is emptied - */ - stopThisScript(): void; - /** - * Get top stack item. - * @return {?string} Block ID on top of stack. - */ - peekStack(): string | null; - /** - * Get top stack frame. - * @return {?object} Last stack frame stored on this thread. - */ - peekStackFrame(): object | null; - /** - * Get stack frame above the current top. - * @return {?object} Second to last stack frame stored on this thread. - */ - peekParentStackFrame(): object | null; - /** - * Push a reported value to the parent of the current stack frame. - * @param {*} value Reported value to push. - */ - pushReportedValue(value: any): void; - /** - * Initialize procedure parameters on this stack frame. - */ - initParams(): void; - /** - * Add a parameter to the stack frame. - * Use when calling a procedure with parameter values. - * @param {!string} paramName Name of parameter. - * @param {*} value Value to set for parameter. - */ - pushParam(paramName: string, value: any): void; - getHatParam(paramName: any): any; - /** - * Get a parameter at the lowest possible level of the stack. - * @param {!string} paramName Name of parameter. - * @return {*} value Value for parameter. - */ - getParam(paramName: string): any; - getAllparams(): any; - /** - * Whether the current execution of a thread is at the top of the stack. - * @return {boolean} True if execution is at top of the stack. - */ - atStackTop(): boolean; - /** - * Switch the thread to the next block at the current level of the stack. - * For example, this is used in a standard sequence of blocks, - * where execution proceeds from one block to the next. - */ - goToNextBlock(): void; - /** - * Attempt to determine whether a procedure call is recursive, - * by examining the stack. - * @param {!string} procedureCode Procedure code of procedure being called. - * @return {boolean} True if the call appears recursive. - */ - isRecursiveCall(procedureCode: string): boolean; - /** - * Attempt to compile this thread. - */ - tryCompile(): void; - } - namespace Thread { - export { _StackFrame }; - } - /** - * A frame used for each level of the stack. A general purpose - * place to store a bunch of execution context and parameters - * @param {boolean} warpMode Whether this level of the stack is warping - * @constructor - * @private - */ - class _StackFrame { - /** - * Create or recycle a stack frame object. - * @param {boolean} warpMode Enable warpMode on this frame. - * @returns {_StackFrame} The clean stack frame with correct warpMode setting. - */ - static create(warpMode: boolean): _StackFrame; - /** - * Put a stack frame object into the recycle bin for reuse. - * @param {_StackFrame} stackFrame The frame to reset and recycle. - */ - static release(stackFrame: _StackFrame): void; - constructor(warpMode: any); - /** - * Whether this level of the stack is a loop. - * @type {boolean} - */ - isLoop: boolean; - /** - * Whether this level is in warp mode. Is set by some legacy blocks and - * "turbo mode" - * @type {boolean} - */ - warpMode: boolean; - /** - * Reported value from just executed block. - * @type {Any} - */ - justReported: any; - /** - * The active block that is waiting on a promise. - * @type {string} - */ - reporting: string; - /** - * Persists reported inputs during async block. - * @type {Object} - */ - reported: Object; - /** - * Name of waiting reporter. - * @type {string} - */ - waitingReporter: string; - /** - * Procedure parameters. - * @type {Object} - */ - params: Object; - /** - * A context passed to block implementations. - * @type {Object} - */ - executionContext: Object; - /** - * Internal block object being executed. This is *not* the same as the object found - * in target.blocks. - * @type {object} - */ - op: object; - /** - * Reset all properties of the frame to pristine null and false states. - * Used to recycle. - * @return {_StackFrame} this - */ - reset(): _StackFrame; - /** - * Reuse an active stack frame in the stack. - * @param {?boolean} warpMode defaults to current warpMode - * @returns {_StackFrame} this - */ - reuse(warpMode?: boolean | null): _StackFrame; - } -} - -declare module "scratch-vm-dts/engine/tw-frame-loop" { - export = FrameLoop; - class FrameLoop { - constructor(runtime: any); - runtime: any; - running: boolean; - stepCallback(): void; - interpolationCallback(): void; - _stepInterval: NodeJS.Timeout | null; - _interpolationAnimation: { - cancel: () => void; - } | null; - _stepAnimation: { - cancel: () => void; - } | null; - setFramerate(fps: any): void; - framerate: any; - setInterpolation(interpolation: any): void; - interpolation: any; - _restart(): void; - start(): void; - stop(): void; - } -} - -declare module "scratch-vm-dts/engine/profiler" { - export = Profiler; - class Profiler { - /** - * Lookup or create an id for a frame name. - * @static - * @param {string} name The name to return an id for. - * @return {number} The id for the passed name. - */ - static idByName(name: string): number; - /** - * Reverse lookup the name from a given frame id. - * @static - * @param {number} id The id to search for. - * @return {string} The name for the given id. - */ - static nameById(id: number): string; - /** - * Profiler is only available on platforms with the Performance API. - * @return {boolean} Can the Profiler run in this browser? - */ - static available(): boolean; - /** - * @param {FrameCallback} onFrame a handle called for each recorded frame. - * The passed frame value may not be stored as it'll be updated with later - * frame information. Any information that is further stored by the handler - * should make copies or reduce the information. - */ - constructor(onFrame?: FrameCallback); - /** - * A series of START and STOP values followed by arguments. After - * recording is complete the full set of records is reported back by - * stepping through the series to connect the relative START and STOP - * information. - * @type {Array.<*>} - */ - records: Array; - /** - * An array of frames incremented on demand instead as part of start - * and stop. - * @type {Array.} - */ - increments: Array; - /** - * An array of profiler frames separated by counter argument. Generally - * for Scratch these frames are separated by block function opcode. - * This tracks each time an opcode is called. - * @type {Array.} - */ - counters: Array; - /** - * A frame with no id or argument. - * @type {ProfilerFrame} - */ - nullFrame: ProfilerFrame; - /** - * A cache of ProfilerFrames to reuse when reporting the recorded - * frames in records. - * @type {Array.} - */ - _stack: Array; - /** - * A callback handle called with each decoded frame when reporting back - * all the recorded times. - * @type {FrameCallback} - */ - onFrame: FrameCallback; - /** - * A reference to the START record id constant. - * @const {number} - */ - START: number; - /** - * A reference to the STOP record id constant. - * @const {number} - */ - STOP: number; - /** - * Start recording a frame of time for an id and optional argument. - * @param {number} id The id returned by idByName for a name symbol like - * Runtime._step. - * @param {?*} arg An arbitrary argument value to store with the frame. - */ - start(id: number, arg: any | null): void; - /** - * Stop the current frame. - */ - stop(): void; - /** - * Increment the number of times this symbol is called. - * @param {number} id The id returned by idByName for a name symbol. - */ - increment(id: number): void; - /** - * Find or create a ProfilerFrame-like object whose counter can be - * incremented outside of the Profiler. - * @param {number} id The id returned by idByName for a name symbol. - * @param {*} arg The argument for a frame that identifies it in addition - * to the id. - * @return {{count: number}} A ProfilerFrame-like whose count should be - * incremented for each call. - */ - frame( - id: number, - arg: any - ): { - count: number; - }; - /** - * Decode records and report all frames to `this.onFrame`. - */ - reportFrames(): void; - /** - * Lookup or create an id for a frame name. - * @param {string} name The name to return an id for. - * @return {number} The id for the passed name. - */ - idByName(name: string): number; - /** - * Reverse lookup the name from a given frame id. - * @param {number} id The id to search for. - * @return {string} The name for the given id. - */ - nameById(id: number): string; - } - namespace Profiler { - export { START, STOP, FrameCallback }; - } - /** - * A set of information about a frame of execution that was recorded. - */ - class ProfilerFrame { - /** - * @param {number} depth Depth of the frame in the recorded stack. - */ - constructor(depth: number); - /** - * The numeric id of a record symbol like Runtime._step or - * blockFunction. - * @type {number} - */ - id: number; - /** - * The amount of time spent inside the recorded frame and any deeper - * frames. - * @type {number} - */ - totalTime: number; - /** - * The amount of time spent only inside this record frame. Not - * including time in any deeper frames. - * @type {number} - */ - selfTime: number; - /** - * An arbitrary argument for the recorded frame. For example a block - * function might record its opcode as an argument. - * @type {*} - */ - arg: any; - /** - * The depth of the recorded frame. This can help compare recursive - * funtions that are recorded. Each level of recursion with have a - * different depth value. - * @type {number} - */ - depth: number; - /** - * A summarized count of the number of calls to this frame. - * @type {number} - */ - count: number; - } - /** - * The START event identifier in Profiler records. - * @const {number} - */ - const START: 0; - /** - * The STOP event identifier in Profiler records. - * @const {number} - */ - const STOP: 1; - /** - * Callback handle called by Profiler for each frame it decodes from its - * records. - */ - type FrameCallback = (frame: ProfilerFrame) => any; -} - -declare module "scratch-vm-dts/util/log-system" { - export = LogSystem; - import { EventEmitter } from "node:events"; - class LogSystem extends EventEmitter { } -} - -declare module "scratch-vm-dts/util/gandi" { - export = Gandi; - class Gandi { - /** - * Constructor for the Gandi class. - * @constructor - * @param {Object} runtime - The runtime object. - */ - constructor(runtime: Object); - /** - * The runtime object. - * @member {Object} - */ - runtime: Object; - /** - * Array to store properties. - * @member {Array} - */ - properties: string[]; - /** - * default supported asset types - */ - _supportedAssetTypes: any[]; - merge(data: any): { - assets: any; - wildExtensions: any; - } | null; - configs: any; - wildExtensions: any; - dynamicMenuItems: any; - spine: any; - assets: any; - setup(): void; - set supportedAssetTypes(types: any[]); - get supportedAssetTypes(): any[]; - clear(): void; - /** - * Checks if all properties are empty. - * @method - * @returns {boolean} - True if all properties are empty, false otherwise. - */ - isEmpty(): boolean; - /** - * Checks if a specific property is empty. - * @method - * @param {string} propertyName - The name of the property to check. - * @returns {boolean} - True if the property is empty, false otherwise. - */ - istPropertyEmpty(propertyName: string): boolean; - /** - * Serializes Gandi assets. - * @method - * @param {Set} extensions - Set of extensions. - * @returns {Array} - Serialized Gandi assets. - */ - serializeGandiAssets(extensions: Set): any[]; - /** - * Checks if an object is empty. - * @method - * @param {Object} object - The object to check. - * @returns {boolean} - True if the object is empty, false otherwise. - */ - isEmptyObject(object: Object): boolean; - /** - * Serializes Gandi data. - * @method - * @param {Object} object - The object to serialize. - * @param {Set} extensions - Set of extensions. - */ - serialize(extensions: Set): - | { - wildExtensions: {}; - } - | { - spine: any; - } - | { - dynamicMenuItems: any; - } - | { - configs: any; - } - | { - assets: any[]; - } - | undefined; - /** - * Adds a Spine asset. - * @method - * @param {string} key - The key for the Spine asset. - * @param {Object} data - The data for the Spine asset. - */ - addSpineAsset(key: string, data: Object): void; - /** - * Deletes a Spine asset. - * @method - * @param {string} key - The key of the Spine asset to delete. - */ - deleteSpineAsset(key: string): void; - /** - * Gets a Spine asset by name. - * @method - * @param {string} name - The name of the Spine asset. - * @returns {Object} - The Spine asset data. - */ - getSpineAsset(name: string): Object; - /** - * Sets the value of a configuration item. - * @param {string} key - The key of the configuration item. - * @param {*} value - The value to set. - * @returns {void} - */ - setConfig(key: string, value: any): void; - /** - * Gets the value of a specified configuration item. - * @param {string} key - The key of the configuration item to retrieve the value. - * @returns {*} The value of the specified configuration item, or undefined if it doesn't exist. - */ - getConfig(key: string): any; - /** - * Adds a dynamic menu item. - * @method - * @param {string} menuName - The name of the dynamic menu. - * @param {Object} menuItem - The dynamic menu item to add. - */ - addDynamicMenuItem(menuName: string, menuItem: Object): void; - /** - * Gets dynamic menu items by name. - * @method - * @param {string} menuName - The name of the dynamic menu. - * @returns {Array} - Array of dynamic menu items. - */ - getDynamicMenuItems(menuName: string): any[]; - /** - * Deletes dynamic menu items. - * @method - * @param {string} menuName - The name of the dynamic menu. - * @param {string} id - The id of the dynamic menu item to delete. - * @throws Will throw an error if the menu name is not provided. - */ - deleteDynamicMenuItems(menuName: string, id: string): void; - /** - * Adds a wild extension. - * @method - * @param {Object} data - The data for the wild extension. - */ - addWildExtension(data: { id: string; url: string }): void; - /** - * Deletes a wild extension. - * @method - * @param {string} id - The id of the wild extension to delete. - */ - deleteWildExtension(id: string): void; - getExtensionAssets(): any; - isExtensionURLInGandiAssets(url: any): any; - } -} - -declare module "scratch-vm-dts/engine/tw-font-manager" { - export = FontManager; - type Runtime = import("scratch-vm-dts/engine/runtime"); - import JSZip from "jszip"; - class Asset { } - /** - * @typedef InternalFont - * @property {boolean} system True if the font is built in to the system - * @property {string} family The font's name - * @property {string} fallback Fallback font family list - * @property {Asset} [asset] scratch-storage asset if system: false - */ - class FontManager extends EventEmitter<[never]> { - /** - * @param {Runtime} runtime - */ - constructor(runtime: Runtime); - runtime: Runtime; - /** @type {Array} */ - fonts: Array; - /** - * @param {string} family An unknown font family - * @returns {boolean} true if the family is valid - */ - isValidFamily(family: string): boolean; - /** - * @param {string} family - * @returns {boolean} - */ - hasFont(family: string): boolean; - /** - * @param {string} family - * @returns {boolean} - */ - getSafeName(family: string): boolean; - changed(): void; - /** - * @param {string} family - * @param {string} fallback - */ - addSystemFont(family: string, fallback: string): void; - /** - * @param {string} family - * @param {string} fallback - * @param {Asset} asset scratch-storage asset - */ - addCustomFont(family: string, fallback: string, asset: Asset): void; - /** - * @returns {Array<{system: boolean; name: string; family: string; data: Uint8Array | null; format: string | null}>} - */ - getFonts(): Array<{ - system: boolean; - name: string; - family: string; - data: Uint8Array | null; - format: string | null; - }>; - /** - * @param {number} index Corresponds to index from getFonts() - */ - deleteFont(index: number): void; - clear(): void; - updateRenderer(): void; - /** - * Get data to save in project.json and sb3 files. - */ - serializeJSON(): - | { - system: boolean; - family: string; - fallback: string; - }[] - | null; - /** - * @returns {Asset[]} list of scratch-storage assets - */ - serializeAssets(): Asset[]; - /** - * @param {unknown} json - * @param {JSZip} [zip] - * @param {boolean} [keepExisting] - * @returns {Promise} - */ - deserialize( - json: unknown, - zip?: JSZip, - keepExisting?: boolean - ): Promise; - } - namespace FontManager { - export { InternalFont }; - } - import EventEmitter = require("events"); - type InternalFont = { - /** - * True if the font is built in to the system - */ - system: boolean; - /** - * The font's name - */ - family: string; - /** - * Fallback font family list - */ - fallback: string; - /** - * scratch-storage asset if system: false - */ - asset?: Asset; - }; -} - -declare module "scratch-vm-dts/extension-support/argument-type" { - export = ArgumentType; - /** - * Block argument types - */ - type ArgumentType = string; - namespace ArgumentType { - let ANGLE: string; - let BOOLEAN: string; - let COLOR: string; - let NUMBER: string; - let STRING: string; - let MATRIX: string; - let NOTE: string; - let IMAGE: string; - let XIGUA_MATRIX: string; - let XIGUA_WHITE_BOARD_NOTE: string; - let CCW_HAT_PARAMETER: string; - let COSTUME: string; - let SOUND: string; - } -} - -declare module "scratch-vm-dts/extension-support/extension-metadata" { - export = ExtensionMetadata; - type BlockType = import("scratch-vm-dts/extension-support/block-type"); - type ArgumentType = import("scratch-vm-dts/extension-support/argument-type"); - class int extends Number { } - /** - * All the metadata needed to register an extension. - */ - type ExtensionMetadata = { - /** - * - a unique alphanumeric identifier for this extension. No special characters allowed. - */ - id: string; - /** - * - the human-readable name of this extension. - */ - name?: string | undefined; - /** - * - URI for an image to be placed on each block in this extension. Data URI ok. - */ - blockIconURI?: string | undefined; - /** - * - URI for an image to be placed on this extension's category menu item. Data URI ok. - */ - menuIconURI?: string | undefined; - /** - * - link to documentation content for this extension. - */ - docsURI?: string | undefined; - /** - * - the blocks provided by this extension, plus separators. - */ - blocks: Array; - /** - * - map of menu name to metadata for each of this extension's menus. - */ - menus?: ExtensionMenuMetadata; - }; - /** - * All the metadata needed to register an extension block. - */ - type ExtensionBlockMetadata = { - /** - * - a unique alphanumeric identifier for this block. No special characters allowed. - */ - opcode: string; - /** - * - the name of the function implementing this block. Can be shared by other blocks/opcodes. - */ - func?: string | undefined; - /** - * - the type of block (command, reporter, etc.) being described. - */ - blockType: BlockType; - /** - * - the text on the block, with [PLACEHOLDERS] for arguments. - */ - text: string; - /** - * - the human-readable tooltip for this block. - */ - tooltip?: string | undefined; - /** - * - true if this block should not appear in the block palette. - */ - hideFromPalette?: boolean | undefined; - /** - * - true if the block ends a stack - no blocks can be connected after it. - */ - isTerminal?: boolean | undefined; - /** - * - true if this block is a reporter but should not allow a monitor. - */ - disableMonitor?: boolean | undefined; - /** - * - if this block is a reporter, this is the scope/context for its value. - */ - reporterScope?: object; - /** - * - sets whether a hat block is edge-activated. - */ - isEdgeActivated?: boolean | undefined; - /** - * - sets whether a hat/event block should restart existing threads. - */ - shouldRestartExistingThreads?: boolean | undefined; - /** - * - for flow control blocks, the number of branches/substacks for this block. - */ - branchCount?: int; - /** - * - map of argument placeholder to metadata about each arg. - */ - arguments?: ExtensionArgumentMetadata; - }; - /** - * All the metadata needed to register an argument for an extension block. - */ - type ExtensionArgumentMetadata = { - /** - * - the type of the argument (number, string, etc.) - */ - type: ArgumentType; - /** - * - the default value of this argument. - */ - defaultValue?: any; - /** - * - the name of the menu to use for this argument, if any. - */ - menu?: string | undefined; - }; - /** - * All the metadata needed to register an extension drop-down menu. - */ - type ExtensionMenuMetadata = ExtensionDynamicMenu | ExtensionMenuItems; - /** - * The string name of a function which returns menu items. - */ - type ExtensionDynamicMenu = string; - /** - * Items in an extension menu. - */ - type ExtensionMenuItems = Array< - ExtensionMenuItemSimple | ExtensionMenuItemComplex - >; - /** - * A menu item for which the label and value are identical strings. - */ - type ExtensionMenuItemSimple = string; - /** - * A menu item for which the label and value can differ. - */ - type ExtensionMenuItemComplex = { - /** - * - the value of the block argument when this menu item is selected. - */ - value: any; - /** - * - the human-readable label of this menu item in the menu. - */ - text: string; - }; -} - -declare module "scratch-vm-dts/blocks/scratch3_core_example" { - export = Scratch3CoreExample; - type Runtime = import("scratch-vm-dts/engine/runtime"); - /** - * An example core block implemented using the extension spec. - * This is not loaded as part of the core blocks in the VM but it is provided - * and used as part of tests. - */ - class Scratch3CoreExample { - constructor(runtime: any); - /** - * The runtime instantiating this block package. - * @type {Runtime} - */ - runtime: Runtime; - /** - * @returns {object} metadata for this extension and its blocks. - */ - getInfo(): object; - /** - * Example opcode just returns the name of the stage target. - * @returns {string} The name of the first target in the project. - */ - exampleOpcode(): string; - exampleWithInlineImage(): void; - } -} - -declare module "scratch-vm-dts/extensions/scratch3_wedo2" { - export = Scratch3WeDo2Blocks; - class int extends Number { } - class array extends Array { } - /** - * Scratch 3.0 blocks to interact with a LEGO WeDo 2.0 peripheral. - */ - class Scratch3WeDo2Blocks { - /** - * @return {string} - the ID of this extension. - */ - static get EXTENSION_ID(): string; - /** - * @return {number} - the tilt sensor counts as "tilted" if its tilt angle meets or exceeds this threshold. - */ - static get TILT_THRESHOLD(): number; - /** - * Construct a set of WeDo 2.0 blocks. - * @param {Runtime} runtime - the Scratch 3.0 runtime. - */ - constructor(runtime: Runtime); - /** - * The Scratch 3.0 runtime. - * @type {Runtime} - */ - runtime: Runtime; - _peripheral: WeDo2; - /** - * @returns {object} metadata for this extension and its blocks. - */ - getInfo(): object; - /** - * Turn specified motor(s) on for a specified duration. - * @param {object} args - the block's arguments. - * @property {MotorID} MOTOR_ID - the motor(s) to activate. - * @property {int} DURATION - the amount of time to run the motors. - * @return {Promise} - a promise which will resolve at the end of the duration. - */ - motorOnFor(args: object): Promise; - /** - * Turn specified motor(s) on indefinitely. - * @param {object} args - the block's arguments. - * @property {MotorID} MOTOR_ID - the motor(s) to activate. - * @return {Promise} - a Promise that resolves after some delay. - */ - motorOn(args: object): Promise; - /** - * Turn specified motor(s) off. - * @param {object} args - the block's arguments. - * @property {MotorID} MOTOR_ID - the motor(s) to deactivate. - * @return {Promise} - a Promise that resolves after some delay. - */ - motorOff(args: object): Promise; - /** - * Turn specified motor(s) off. - * @param {object} args - the block's arguments. - * @property {MotorID} MOTOR_ID - the motor(s) to be affected. - * @property {int} POWER - the new power level for the motor(s). - * @return {Promise} - a Promise that resolves after some delay. - */ - startMotorPower(args: object): Promise; - /** - * Set the direction of rotation for specified motor(s). - * If the direction is 'reverse' the motor(s) will be reversed individually. - * @param {object} args - the block's arguments. - * @property {MotorID} MOTOR_ID - the motor(s) to be affected. - * @property {MotorDirection} MOTOR_DIRECTION - the new direction for the motor(s). - * @return {Promise} - a Promise that resolves after some delay. - */ - setMotorDirection(args: object): Promise; - /** - * Set the LED's hue. - * @param {object} args - the block's arguments. - * @property {number} HUE - the hue to set, in the range [0,100]. - * @return {Promise} - a Promise that resolves after some delay. - */ - setLightHue(args: object): Promise; - /** - * Make the WeDo 2.0 peripheral play a MIDI note for the specified duration. - * @param {object} args - the block's arguments. - * @property {number} NOTE - the MIDI note to play. - * @property {number} DURATION - the duration of the note, in seconds. - * @return {Promise} - a promise which will resolve at the end of the duration. - */ - playNoteFor(args: object): Promise; - /** - * Compare the distance sensor's value to a reference. - * @param {object} args - the block's arguments. - * @property {string} OP - the comparison operation: '<' or '>'. - * @property {number} REFERENCE - the value to compare against. - * @return {boolean} - the result of the comparison, or false on error. - */ - whenDistance(args: object): boolean; - /** - * Test whether the tilt sensor is currently tilted. - * @param {object} args - the block's arguments. - * @property {TiltDirection} TILT_DIRECTION_ANY - the tilt direction to test (up, down, left, right, or any). - * @return {boolean} - true if the tilt sensor is tilted past a threshold in the specified direction. - */ - whenTilted(args: object): boolean; - /** - * @return {number} - the distance sensor's value, scaled to the [0,100] range. - */ - getDistance(): number; - /** - * Test whether the tilt sensor is currently tilted. - * @param {object} args - the block's arguments. - * @property {TiltDirection} TILT_DIRECTION_ANY - the tilt direction to test (up, down, left, right, or any). - * @return {boolean} - true if the tilt sensor is tilted past a threshold in the specified direction. - */ - isTilted(args: object): boolean; - /** - * @param {object} args - the block's arguments. - * @property {TiltDirection} TILT_DIRECTION - the direction (up, down, left, right) to check. - * @return {number} - the tilt sensor's angle in the specified direction. - * Note that getTiltAngle(up) = -getTiltAngle(down) and getTiltAngle(left) = -getTiltAngle(right). - */ - getTiltAngle(args: object): number; - } - /** - * Manage communication with a WeDo 2.0 peripheral over a Bluetooth Low Energy client socket. - */ - class WeDo2 { - constructor(runtime: any, extensionId: any); - /** - * The id of the extension this peripheral belongs to. - */ - _extensionId: any; - /** - * Reset all the state and timeout/interval ids. - */ - reset(): void; - /** - * Check the battery level on the WeDo 2.0. If the WeDo 2.0 has disconnected - * for some reason, the BLE socket will get an error back and automatically - * close the socket. - */ - _checkBatteryLevel(): void; - /** - * @return {number} - the latest value received for the tilt sensor's tilt about the X axis. - */ - get tiltX(): number; - /** - * @return {number} - the latest value received for the tilt sensor's tilt about the Y axis. - */ - get tiltY(): number; - /** - * @return {number} - the latest value received from the distance sensor. - */ - get distance(): number; - /** - * Access a particular motor on this peripheral. - * @param {int} index - the zero-based index of the desired motor. - * @return {WeDo2Motor} - the WeDo2Motor instance, if any, at that index. - */ - motor(index: int): WeDo2Motor; - /** - * Stop all the motors that are currently running. - */ - stopAllMotors(): void; - /** - * Set the WeDo 2.0 peripheral's LED to a specific color. - * @param {int} inputRGB - a 24-bit RGB color in 0xRRGGBB format. - * @return {Promise} - a promise of the completion of the set led send operation. - */ - setLED(inputRGB: int): Promise; - /** - * Sets the input mode of the LED to RGB. - * @return {Promise} - a promise returned by the send operation. - */ - setLEDMode(): Promise; - /** - * Switch off the LED on the WeDo 2.0. - * @return {Promise} - a promise of the completion of the stop led send operation. - */ - stopLED(): Promise; - /** - * Play a tone from the WeDo 2.0 peripheral for a specific amount of time. - * @param {int} tone - the pitch of the tone, in Hz. - * @param {int} milliseconds - the duration of the note, in milliseconds. - * @return {Promise} - a promise of the completion of the play tone send operation. - */ - playTone(tone: int, milliseconds: int): Promise; - /** - * Stop the tone playing from the WeDo 2.0 peripheral, if any. - * @return {Promise} - a promise that the command sent. - */ - stopTone(): Promise; - /** - * Stop the tone playing and motors on the WeDo 2.0 peripheral. - */ - stopAll(): void; - /** - * Called by the runtime when user wants to scan for a WeDo 2.0 peripheral. - */ - scan(): void; - /** - * Called by the runtime when user wants to connect to a certain WeDo 2.0 peripheral. - * @param {number} id - the id of the peripheral to connect to. - */ - connect(id: number): void; - /** - * Disconnects from the current BLE socket. - */ - disconnect(): void; - /** - * Called by the runtime to detect whether the WeDo 2.0 peripheral is connected. - * @return {boolean} - the connected state. - */ - isConnected(): boolean; - /** - * Write a message to the WeDo 2.0 peripheral BLE socket. - * @param {number} uuid - the UUID of the characteristic to write to - * @param {Array} message - the message to write. - * @param {boolean} [useLimiter=true] - if true, use the rate limiter - * @return {Promise} - a promise result of the write operation - */ - send(uuid: number, message: any[], useLimiter?: boolean): Promise; - /** - * Generate a WeDo 2.0 'Output Command' in the byte array format - * (CONNECT ID, COMMAND ID, NUMBER OF BYTES, VALUES ...). - * - * This sends a command to the WeDo 2.0 to actuate the specified outputs. - * - * @param {number} connectID - the port (Connect ID) to send a command to. - * @param {number} commandID - the id of the byte command. - * @param {array} values - the list of values to write to the command. - * @return {array} - a generated output command. - */ - generateOutputCommand( - connectID: number, - commandID: number, - values?: array - ): array; - /** - * Generate a WeDo 2.0 'Input Command' in the byte array format - * (COMMAND ID, COMMAND TYPE, CONNECT ID, TYPE ID, MODE, DELTA INTERVAL (4 BYTES), - * UNIT, NOTIFICATIONS ENABLED). - * - * This sends a command to the WeDo 2.0 that sets that input format - * of the specified inputs and sets value change notifications. - * - * @param {number} connectID - the port (Connect ID) to send a command to. - * @param {number} type - the type of input sensor. - * @param {number} mode - the mode of the input sensor. - * @param {number} delta - the delta change needed to trigger notification. - * @param {array} units - the unit of the input sensor value. - * @param {boolean} enableNotifications - whether to enable notifications. - * @return {array} - a generated input command. - */ - generateInputCommand( - connectID: number, - type: number, - mode: number, - delta: number, - units: array, - enableNotifications: boolean - ): array; - } - /** - * Manage power, direction, and timers for one WeDo 2.0 motor. - */ - class WeDo2Motor { - /** - * Construct a WeDo 2.0 Motor instance. - * @param {WeDo2} parent - the WeDo 2.0 peripheral which owns this motor. - * @param {int} index - the zero-based index of this motor on its parent peripheral. - */ - constructor(parent: WeDo2, index: int); - /** - * Start active braking on this motor. After a short time, the motor will turn off. - */ - startBraking(): void; - /** - * Turn this motor off. - * @param {boolean} [useLimiter=true] - if true, use the rate limiter - */ - turnOff(useLimiter?: boolean): void; - /** - * @param {int} value - this motor's new direction: 1 for "this way" or -1 for "that way" - */ - set direction(value: int); - /** - * @return {int} - this motor's current direction: 1 for "this way" or -1 for "that way" - */ - get direction(): int; - /** - * @param {int} value - this motor's new power level, in the range [0,100]. - */ - set power(value: int); - /** - * @return {int} - this motor's current power level, in the range [0,100]. - */ - get power(): int; - /** - * @return {boolean} - true if this motor is currently moving, false if this motor is off or braking. - */ - get isOn(): boolean; - /** - * @return {boolean} - time, in milliseconds, of when the pending timeout began. - */ - get pendingTimeoutStartTime(): boolean; - /** - * @return {boolean} - delay, in milliseconds, of the pending timeout. - */ - get pendingTimeoutDelay(): boolean; - /** - * Turn this motor on indefinitely. - */ - turnOn(): void; - /** - * Turn this motor on for a specific duration. - * @param {number} milliseconds - run the motor for this long. - */ - turnOnFor(milliseconds: number): void; - } -} - -declare module "scratch-vm-dts/extensions/scratch3_microbit" { - export = Scratch3MicroBitBlocks; - class array extends Array { } - /** - * Scratch 3.0 blocks to interact with a MicroBit peripheral. - */ - class Scratch3MicroBitBlocks { - /** - * @return {string} - the name of this extension. - */ - static get EXTENSION_NAME(): string; - /** - * @return {string} - the ID of this extension. - */ - static get EXTENSION_ID(): string; - /** - * @return {number} - the tilt sensor counts as "tilted" if its tilt angle meets or exceeds this threshold. - */ - static get TILT_THRESHOLD(): number; - /** - * Construct a set of MicroBit blocks. - * @param {Runtime} runtime - the Scratch 3.0 runtime. - */ - constructor(runtime: Runtime); - /** - * @return {array} - text and values for each buttons menu element - */ - get BUTTONS_MENU(): array; - /** - * @return {array} - text and values for each gestures menu element - */ - get GESTURES_MENU(): array; - /** - * @return {array} - text and values for each pin state menu element - */ - get PIN_STATE_MENU(): array; - /** - * @return {array} - text and values for each tilt direction menu element - */ - get TILT_DIRECTION_MENU(): array; - /** - * @return {array} - text and values for each tilt direction (plus "any") menu element - */ - get TILT_DIRECTION_ANY_MENU(): array; - /** - * The Scratch 3.0 runtime. - * @type {Runtime} - */ - runtime: Runtime; - _peripheral: MicroBit; - /** - * @returns {object} metadata for this extension and its blocks. - */ - getInfo(): object; - /** - * Test whether the A or B button is pressed - * @param {object} args - the block's arguments. - * @return {boolean} - true if the button is pressed. - */ - whenButtonPressed(args: object): boolean; - /** - * Test whether the A or B button is pressed - * @param {object} args - the block's arguments. - * @return {boolean} - true if the button is pressed. - */ - isButtonPressed(args: object): boolean; - /** - * Test whether the micro:bit is moving - * @param {object} args - the block's arguments. - * @return {boolean} - true if the micro:bit is moving. - */ - whenGesture(args: object): boolean; - /** - * Display a predefined symbol on the 5x5 LED matrix. - * @param {object} args - the block's arguments. - * @return {Promise} - a Promise that resolves after a tick. - */ - displaySymbol(args: object): Promise; - /** - * Display text on the 5x5 LED matrix. - * @param {object} args - the block's arguments. - * @return {Promise} - a Promise that resolves after the text is done printing. - * Note the limit is 19 characters - * The print time is calculated by multiplying the number of horizontal pixels - * by the default scroll delay of 120ms. - * The number of horizontal pixels = 6px for each character in the string, - * 1px before the string, and 5px after the string. - */ - displayText(args: object): Promise; - /** - * Turn all 5x5 matrix LEDs off. - * @return {Promise} - a Promise that resolves after a tick. - */ - displayClear(): Promise; - /** - * Test whether the tilt sensor is currently tilted. - * @param {object} args - the block's arguments. - * @property {TiltDirection} DIRECTION - the tilt direction to test (front, back, left, right, or any). - * @return {boolean} - true if the tilt sensor is tilted past a threshold in the specified direction. - */ - whenTilted(args: object): boolean; - /** - * Test whether the tilt sensor is currently tilted. - * @param {object} args - the block's arguments. - * @property {TiltDirection} DIRECTION - the tilt direction to test (front, back, left, right, or any). - * @return {boolean} - true if the tilt sensor is tilted past a threshold in the specified direction. - */ - isTilted(args: object): boolean; - /** - * @param {object} args - the block's arguments. - * @property {TiltDirection} DIRECTION - the direction (front, back, left, right) to check. - * @return {number} - the tilt sensor's angle in the specified direction. - * Note that getTiltAngle(front) = -getTiltAngle(back) and getTiltAngle(left) = -getTiltAngle(right). - */ - getTiltAngle(args: object): number; - } - /** - * Manage communication with a MicroBit peripheral over a Scrath Link client socket. - */ - class MicroBit { - /** - * Construct a MicroBit communication object. - * @param {Runtime} runtime - the Scratch 3.0 runtime - * @param {string} extensionId - the id of the extension - */ - constructor(runtime: Runtime, extensionId: string); - /** - * The id of the extension this peripheral belongs to. - */ - _extensionId: string; - /** - * ID for a timeout which is used to clear the busy flag if it has been - * true for a long time. - */ - _busyTimeoutID: number | null; - /** - * Reset all the state and timeout/interval ids. - */ - reset(): void; - /** - * @param {string} text - the text to display. - * @return {Promise} - a Promise that resolves when writing to peripheral. - */ - displayText(text: string): Promise; - /** - * @param {Uint8Array} matrix - the matrix to display. - * @return {Promise} - a Promise that resolves when writing to peripheral. - */ - displayMatrix(matrix: Uint8Array): Promise; - /** - * @return {number} - the latest value received for the tilt sensor's tilt about the X axis. - */ - get tiltX(): number; - /** - * @return {number} - the latest value received for the tilt sensor's tilt about the Y axis. - */ - get tiltY(): number; - /** - * @return {boolean} - the latest value received for the A button. - */ - get buttonA(): boolean; - /** - * @return {boolean} - the latest value received for the B button. - */ - get buttonB(): boolean; - /** - * @return {number} - the latest value received for the motion gesture states. - */ - get gestureState(): number; - /** - * @return {Uint8Array} - the current state of the 5x5 LED matrix. - */ - get ledMatrixState(): Uint8Array; - /** - * Called by the runtime when user wants to scan for a peripheral. - */ - scan(): void; - /** - * Called by the runtime when user wants to connect to a certain peripheral. - * @param {number} id - the id of the peripheral to connect to. - */ - connect(id: number): void; - /** - * Disconnect from the micro:bit. - */ - disconnect(): void; - /** - * Return true if connected to the micro:bit. - * @return {boolean} - whether the micro:bit is connected. - */ - isConnected(): boolean; - /** - * Send a message to the peripheral BLE socket. - * @param {number} command - the BLE command hex. - * @param {Uint8Array} message - the message to write - */ - send(command: number, message: Uint8Array): void; - } -} - -declare module "scratch-vm-dts/extensions/scratch3_text2speech" { - export = Scratch3Text2SpeechBlocks; - /** - * Class for the text2speech blocks. - * @constructor - */ - class array extends Array { } - interface Text2SpeechState { - voiceId: string; - } - interface SoundPlayer { - stop(): void; - connect(chain: any): void; - play(): void; - } - class Scratch3Text2SpeechBlocks { - /** - * The key to load & store a target's text2speech state. - * @return {string} The key. - */ - static get STATE_KEY(): string; - /** - * The default state, to be used when a target has no existing state. - * @type {Text2SpeechState} - */ - static get DEFAULT_TEXT2SPEECH_STATE(): Text2SpeechState; - constructor(runtime: any); - /** - * The runtime instantiating this block package. - * @type {Runtime} - */ - runtime: Runtime; - /** - * Map of soundPlayers by sound id. - * @type {Map} - */ - _soundPlayers: Map; - /** - * Stop all currently playing speech sounds. - */ - _stopAllSpeech(): void; - /** - * A list of all Scratch locales that are supported by the extension. - * @type {Array} - */ - _supportedLocales: any[]; - thirdPartApiKey: string; - host: any; - isCCWService: boolean | undefined; - /** - * An object with info for each voice. - */ - get VOICE_INFO(): { - ALTO: { - name: string; - gender: string; - playbackRate: number; - }; - TENOR: { - name: string; - gender: string; - playbackRate: number; - }; - SQUEAK: { - name: string; - gender: string; - playbackRate: number; - }; - GIANT: { - name: string; - gender: string; - playbackRate: number; - }; - KITTEN: { - name: string; - gender: string; - playbackRate: number; - }; - }; - /** - * An object with information for each language. - * - * A note on the different sets of locales referred to in this extension: - * - * SCRATCH LOCALE - * Set by the editor, and used to store the language state in the project. - * Listed in l10n: https://github.com/scratchfoundation/scratch-l10n/blob/master/src/supported-locales.js - * SUPPORTED LOCALE - * A Scratch locale that has a corresponding extension locale. - * EXTENSION LOCALE - * A locale corresponding to one of the available spoken languages - * in the extension. There can be multiple supported locales for a single - * extension locale. For example, for both written versions of chinese, - * zh-cn and zh-tw, we use a single spoken language (Mandarin). So there - * are two supported locales, with a single extension locale. - * SPEECH SYNTH LOCALE - * A different locale code system, used by our speech synthesis service. - * Each extension locale has a speech synth locale. - */ - get LANGUAGE_INFO(): { - ar: { - name: string; - locales: string[]; - speechSynthLocale: string; - singleGender: boolean; - }; - "zh-cn": { - name: string; - locales: string[]; - speechSynthLocale: string; - singleGender: boolean; - }; - en: { - name: string; - locales: string[]; - speechSynthLocale: string; - }; - fr: { - name: string; - locales: string[]; - speechSynthLocale: string; - }; - de: { - name: string; - locales: string[]; - speechSynthLocale: string; - }; - ja: { - name: string; - locales: string[]; - speechSynthLocale: string; - }; - ko: { - name: string; - locales: string[]; - speechSynthLocale: string; - singleGender: boolean; - }; - pt: { - name: string; - locales: string[]; - speechSynthLocale: string; - }; - ru: { - name: string; - locales: string[]; - speechSynthLocale: string; - }; - es: { - name: string; - locales: string[]; - speechSynthLocale: string; - }; - }; - /** - * A default language to use for speech synthesis. - * @type {string} - */ - get DEFAULT_LANGUAGE(): string; - /** - * @returns {object} metadata for this extension and its blocks. - */ - getInfo(): object; - /** - * Get the language code currently set in the editor, or fall back to the - * browser locale. - * @return {string} a Scratch locale code. - */ - getEditorLanguage(): string; - /** - * Get the language code currently set for the extension. - * @returns {string} a Scratch locale code. - */ - getCurrentLanguage(): string; - /** - * Set the language code for the extension. - * It is stored in the stage so it can be saved and loaded with the project. - * @param {string} locale a locale code. - */ - setCurrentLanguage(locale: string): void; - /** - * Get the extension locale for a supported locale, or null. - * @param {string} locale a locale code. - * @returns {?string} a locale supported by the extension. - */ - _getExtensionLocaleForSupportedLocale(locale: string): string | null; - /** - * Get the locale code used by the speech synthesis server corresponding to - * the current language code set for the extension. - * @returns {string} a speech synthesis locale. - */ - _getSpeechSynthLocale(): string; - /** - * Get an array of the locales supported by this extension. - * @returns {Array} An array of locale strings. - */ - _getSupportedLocales(): any[]; - /** - * Check if a Scratch language code is in the list of supported languages for the - * speech synthesis service. - * @param {string} languageCode the language code to check. - * @returns {boolean} true if the language code is supported. - */ - isSupportedLanguage(languageCode: string): boolean; - /** - * Get the menu of voices for the "set voice" block. - * @return {array} the text and value for each menu item. - */ - getVoiceMenu(): array; - /** - * Get the localized menu of languages for the "set language" block. - * For each language: - * if there is a custom translated spoken language name, use that; - * otherwise use the translation in the languageNames menuMap; - * otherwise fall back to the untranslated name in LANGUAGE_INFO. - * @return {array} the text and value for each menu item. - */ - getLanguageMenu(): array; - /** - * Set the voice for speech synthesis for this sprite. - * @param {object} args Block arguments - * @param {object} util Utility object provided by the runtime. - */ - setVoice(args: object, util: object): void; - /** - * Set the language for speech synthesis. - * @param {object} args Block arguments - */ - setLanguage(args: object): void; - /** - * Convert the provided text into a sound file and then play the file. - * @param {object} args Block arguments - * @param {object} util Utility object provided by the runtime. - * @return {Promise} A promise that resolves after playing the sound - */ - speakAndWait(args: object, util: object): Promise; - runWithCCWAPI(args: any, util: any): Promise; - runWithScratchAPI(args: any, util: any): Promise; - } -} - -declare module "scratch-vm-dts/extensions/scratch3_translate" { - export = Scratch3TranslateBlocks; - /** - * Class for the translate block in Scratch 3.0. - * @constructor - */ - class Scratch3TranslateBlocks { - /** - * The key to load & store a target's translate state. - * @return {string} The key. - */ - static get STATE_KEY(): string; - constructor(runtime: any); - thirdPartApiKey: string; - host: any; - isCCWService: boolean | undefined; - /** - * @returns {object} metadata for this extension and its blocks. - */ - getInfo(): object; - _getXiguaSupportedLanguages(code: any): { [key: string]: string }; - /** - * Get the human readable language value for the reporter block. - * @return {string} the language name of the project viewer. - */ - getViewerLanguage(): string; - /** - * Get the viewer's language code. - * @return {string} the language code. - */ - getViewerLanguageCode(): string; - /** - * Get a language code from a block argument. The arg can be a language code - * or a language name, written in any language. - * @param {object} arg A block argument. - * @return {string} A language code. - */ - getLanguageCodeFromArg(arg: object): string; - /** - * Translates the text in the translate block to the language specified in the menu. - * @param {object} args - the block arguments. - * @return {Promise} - a promise that resolves after the response from the translate server. - */ - getTranslate(args: object): Promise; - runWithCCWAPI(args: any, lang: any): Promise; - runWithScratchAPI(args: any, lang: any): Promise; - } -} - -declare module "scratch-vm-dts/extensions/scratch3_video_sensing" { - export = Scratch3VideoSensingBlocks; - interface MotionState { - motionFrameNumber: number; - motionAmount: number; - motionDirection: number; - } - type Target = import("scratch-vm-dts/engine/target"); - type BlockUtility = import("scratch-vm-dts/engine/block-utility"); - /** - * Class for the motion-related blocks in Scratch 3.0 - * @param {Runtime} runtime - the runtime instantiating this block package. - * @constructor - */ - class Scratch3VideoSensingBlocks { - /** - * After analyzing a frame the amount of milliseconds until another frame - * is analyzed. - * @type {number} - */ - static get INTERVAL(): number; - /** - * Dimensions the video stream is analyzed at after its rendered to the - * sample canvas. - * @type {Array.} - */ - static get DIMENSIONS(): Array; - /** - * The key to load & store a target's motion-related state. - * @type {string} - */ - static get STATE_KEY(): string; - /** - * The default motion-related state, to be used when a target has no existing motion state. - * @type {MotionState} - */ - static get DEFAULT_MOTION_STATE(): MotionState; - static get SensingAttribute(): { - /** The amount of motion. */ - MOTION: string; - /** The direction of the motion. */ - DIRECTION: string; - }; - static get SensingSubject(): { - /** The sensor traits of the whole stage. */ - STAGE: string; - /** The senosr traits of the area overlapped by this sprite. */ - SPRITE: string; - }; - /** - * States the video sensing activity can be set to. - * @readonly - * @enum {string} - */ - static get VideoState(): { - /** Video turned off. */ - OFF: string; - /** Video turned on with default y axis mirroring. */ - ON: string; - /** Video turned on without default y axis mirroring. */ - ON_FLIPPED: string; - }; - constructor(runtime: any); - /** - * The runtime instantiating this block package. - * @type {Runtime} - */ - runtime: Runtime; - /** - * The motion detection algoritm used to power the motion amount and - * direction values. - * @type {VideoMotion} - */ - detect: VideoMotion; - /** - * The last millisecond epoch timestamp that the video stream was - * analyzed. - * @type {number} - */ - _lastUpdate: number; - /** - * A flag to determine if this extension has been installed in a project. - * It is set to false the first time getInfo is run. - * @type {boolean} - */ - firstInstall: boolean; - set globalVideoTransparency(transparency: number); - /** - * The transparency setting of the video preview stored in a value - * accessible by any object connected to the virtual machine. - * @type {number} - */ - get globalVideoTransparency(): number; - set globalVideoState(state: string); - /** - * The video state of the video preview stored in a value accessible by any - * object connected to the virtual machine. - * @type {string} - */ - get globalVideoState(): string; - /** - * Get the latest values for video transparency and state, - * and set the video device to use them. - */ - updateVideoDisplay(): void; - /** - * Reset the extension's data motion detection data. This will clear out - * for example old frames, so the first analyzed frame will not be compared - * against a frame from before reset was called. - */ - reset(): void; - _loopInterval: NodeJS.Timeout | undefined; - /** - * Stop the video sampling loop. Only used for testing. - */ - _stopLoop(): void; - /** - * An array of choices of whether a reporter should return the frame's - * motion amount or direction. - * @type {object[]} - * @param {string} name - the translatable name to display in sensor - * attribute menu - * @param {string} value - the serializable value of the attribute - */ - get ATTRIBUTE_INFO(): object[]; - /** - * An array of info about the subject choices. - * @type {object[]} - * @param {string} name - the translatable name to display in the subject menu - * @param {string} value - the serializable value of the subject - */ - get SUBJECT_INFO(): object[]; - /** - * An array of info on video state options for the "turn video [STATE]" block. - * @type {object[]} - * @param {string} name - the translatable name to display in the video state menu - * @param {string} value - the serializable value stored in the block - */ - get VIDEO_STATE_INFO(): object[]; - /** - * @returns {object} metadata for this extension and its blocks. - */ - getInfo(): object; - /** - * Analyze a part of the frame that a target overlaps. - * @param {Target} target - a target to determine where to analyze - * @returns {MotionState} the motion state for the given target - */ - _analyzeLocalMotion(target: Target): MotionState; - /** - * A scratch reporter block handle that analyzes the last two frames and - * depending on the arguments, returns the motion or direction for the - * whole stage or just the target sprite. - * @param {object} args - the block arguments - * @param {BlockUtility} util - the block utility - * @returns {number} the motion amount or direction of the stage or sprite - */ - videoOn(args: object, util: BlockUtility): number; - /** - * A scratch hat block edge handle that analyzes the last two frames where - * the target sprite overlaps and if it has more motion than the given - * reference value. - * @param {object} args - the block arguments - * @param {BlockUtility} util - the block utility - * @returns {boolean} true if the sprite overlaps more motion than the - * reference - */ - whenMotionGreaterThan(args: object, util: BlockUtility): boolean; - /** - * A scratch command block handle that configures the video state from - * passed arguments. - * @param {object} args - the block arguments - * @param {VideoState} args.VIDEO_STATE - the video state to set the device to - */ - videoToggle(args: { VIDEO_STATE: VideoState }): void; - /** - * A scratch command block handle that configures the video preview's - * transparency from passed arguments. - * @param {object} args - the block arguments - * @param {number} args.TRANSPARENCY - the transparency to set the video - * preview to - */ - setVideoTransparency(args: { TRANSPARENCY: number }): void; - } - import Runtime = require("scratch-vm-dts/engine/runtime"); - import VideoMotion = require("scratch-vm-dts/extensions/scratch3_video_sensing/library"); - /** - * States the video sensing activity can be set to. - */ - type VideoState = string; - namespace VideoState { - let OFF: string; - let ON: string; - let ON_FLIPPED: string; - } -} - -declare module "scratch-vm-dts/extensions/scratch3_ev3" { - export = Scratch3Ev3Blocks; - class int extends Number { } - class array extends Array { } - class Scratch3Ev3Blocks { - /** - * The ID of the extension. - * @return {string} the id - */ - static get EXTENSION_ID(): string; - /** - * Creates a new instance of the EV3 extension. - * @param {object} runtime VM runtime - * @constructor - */ - constructor(runtime: object); - /** - * The Scratch 3.0 runtime. - * @type {Runtime} - */ - runtime: Runtime; - _peripheral: EV3; - _playNoteForPicker(note: any, category: any): void; - /** - * Define the EV3 extension. - * @return {object} Extension description. - */ - getInfo(): object; - motorTurnClockwise(args: any): Promise; - motorTurnCounterClockwise(args: any): Promise; - motorSetPower(args: any): void; - getMotorPosition(args: any): number | undefined; - whenButtonPressed(args: any): boolean | undefined; - whenDistanceLessThan(args: any): boolean; - whenBrightnessLessThan(args: any): boolean; - buttonPressed(args: any): boolean | undefined; - getDistance(): any; - getBrightness(): any; - beep(args: any): Promise | undefined; - } - class EV3 { - constructor(runtime: any, extensionId: any); - /** - * The id of the extension this peripheral belongs to. - */ - _extensionId: any; - /** - * Reset all the state and timeout/interval ids. - */ - reset(): void; - get distance(): any; - get brightness(): any; - /** - * Access a particular motor on this peripheral. - * @param {int} index - the zero-based index of the desired motor. - * @return {EV3Motor} - the EV3Motor instance, if any, at that index. - */ - motor(index: int): EV3Motor; - isButtonPressed(port: any): boolean; - beep(freq: any, time: any): void; - stopAll(): void; - stopSound(): void; - stopAllMotors(): void; - /** - * Called by the runtime when user wants to scan for an EV3 peripheral. - */ - scan(): void; - /** - * Called by the runtime when user wants to connect to a certain EV3 peripheral. - * @param {number} id - the id of the peripheral to connect to. - */ - connect(id: number): void; - /** - * Called by the runtime when user wants to disconnect from the EV3 peripheral. - */ - disconnect(): void; - /** - * Called by the runtime to detect whether the EV3 peripheral is connected. - * @return {boolean} - the connected state. - */ - isConnected(): boolean; - /** - * Send a message to the peripheral BT socket. - * @param {Uint8Array} message - the message to send. - * @param {boolean} [useLimiter=true] - if true, use the rate limiter - * @return {Promise} - a promise result of the send operation. - */ - send(message: Uint8Array, useLimiter?: boolean): Promise; - /** - * Genrates direct commands that are sent to the EV3 as a single or compounded byte arrays. - * See 'EV3 Communication Developer Kit', section 4, page 24 at - * https://education.lego.com/en-us/support/mindstorms-ev3/developer-kits. - * - * Direct commands are one of two types: - * DIRECT_COMMAND_NO_REPLY = a direct command where no reply is expected - * DIRECT_COMMAND_REPLY = a direct command where a reply is expected, and the - * number and length of returned values needs to be specified. - * - * The direct command byte array sent takes the following format: - * Byte 0 - 1: Command size, Little Endian. Command size not including these 2 bytes - * Byte 2 - 3: Message counter, Little Endian. Forth running counter - * Byte 4: Command type. Either DIRECT_COMMAND_REPLY or DIRECT_COMMAND_NO_REPLY - * Byte 5 - 6: Reservation (allocation) of global and local variables using a compressed format - * (globals reserved in byte 5 and the 2 lsb of byte 6, locals reserved in the upper - * 6 bits of byte 6) – see documentation for more details. - * Byte 7 - n: Byte codes as a single command or compound commands (I.e. more commands composed - * as a small program) - * - * @param {number} type - the direct command type. - * @param {string} byteCommands - a compound array of EV3 Opcode + arguments. - * @param {number} allocation - the allocation of global and local vars needed for replies. - * @return {array} - generated complete command byte array, with header and compounded commands. - */ - generateCommand( - type: number, - byteCommands: string, - allocation?: number - ): array; - _updateDevices: boolean | undefined; - } - /** - * Manage power, direction, and timers for one EV3 motor. - */ - class EV3Motor { - /** - * Construct a EV3 Motor instance, which could be of type 'largeMotor' or - * 'mediumMotor'. - * - * @param {EV3} parent - the EV3 peripheral which owns this motor. - * @param {int} index - the zero-based index of this motor on its parent peripheral. - * @param {string} type - the type of motor (i.e. 'largeMotor' or 'mediumMotor'). - */ - constructor(parent: EV3, index: int, type: string); - /** - * @param {string} value - this motor's new type: 'largeMotor' or 'mediumMotor' - */ - set type(value: string); - /** - * @return {string} - this motor's type: 'largeMotor' or 'mediumMotor' - */ - get type(): string; - /** - * @param {int} value - this motor's new direction: 1 for "clockwise" or -1 for "counterclockwise" - */ - set direction(value: int); - /** - * @return {int} - this motor's current direction: 1 for "clockwise" or -1 for "counterclockwise" - */ - get direction(): int; - /** - * @param {int} value - this motor's new power level, in the range [0,100]. - */ - set power(value: int); - /** - * @return {int} - this motor's current power level, in the range [0,100]. - */ - get power(): int; - /** - * @param {int} array - this motor's new position, in the range [0,360]. - */ - set position(array: int); - /** - * @return {int} - this motor's current position, in the range [-inf,inf]. - */ - get position(): int; - /** - * Turn this motor on for a specific duration. - * Found in the 'EV3 Firmware Developer Kit', page 56, at - * https://education.lego.com/en-us/support/mindstorms-ev3/developer-kits. - * - * Opcode arguments: - * (Data8) LAYER – Specify chain layer number [0 - 3] - * (Data8) NOS – Output bit field [0x00 – 0x0F] - * (Data8) SPEED – Power level, [-100 – 100] - * (Data32) STEP1 – Time in milliseconds for ramp up - * (Data32) STEP2 – Time in milliseconds for continues run - * (Data32) STEP3 – Time in milliseconds for ramp down - * (Data8) BRAKE - Specify break level [0: Float, 1: Break] - * - * @param {number} milliseconds - run the motor for this long. - */ - turnOnFor(milliseconds: number): void; - /** - * Set the motor to coast after a specified amount of time. - * @param {number} time - the time in milliseconds. - */ - coastAfter(time: number): void; - /** - * Set the motor to coast. - */ - coast(): void; - /** - * Generate motor run values for a given input. - * @param {number} run - run input. - * @return {array} - run values as a byte array. - */ - _runValues(run: number): array; - /** - * Return a port value for the EV3 that is in the format for 'output bit field' - * as 1/2/4/8, generally needed for motor ports, instead of the typical 0/1/2/3. - * The documentation in the 'EV3 Firmware Developer Kit' for motor port arguments - * is sometimes mistaken, but we believe motor ports are mostly addressed this way. - * @param {number} port - the port number to convert to an 'output bit field'. - * @return {number} - the converted port number. - */ - _portMask(port: number): number; - } -} - -declare module "scratch-vm-dts/extensions/scratch3_makeymakey" { - export = Scratch3MakeyMakeyBlocks; - /** - * Class for the makey makey blocks in Scratch 3.0 - * @constructor - */ - class Scratch3MakeyMakeyBlocks { - constructor(runtime: any); - /** - * The runtime instantiating this block package. - * @type {Runtime} - */ - runtime: Runtime; - /** - * A toggle that alternates true and false each frame, so that an - * edge-triggered hat can trigger on every other frame. - * @type {boolean} - */ - frameToggle: boolean; - keyPressed(key: any): void; - /** - * Clear the key press buffer. - */ - _clearkeyPressBuffer(): void; - sequences: {}; - keyPressBuffer: any[]; - get KEY_TEXT_SHORT(): { - SPACE: string; - LEFT: string; - UP: string; - RIGHT: string; - DOWN: string; - }; - get DEFAULT_SEQUENCES(): string[]; - /** - * @returns {object} metadata for this extension and its blocks. - */ - getInfo(): object; - buildSequenceMenu(sequencesArray: any): any; - getMenuItemForSequenceString(sequenceString: any): { - text: any; - value: any; - }; - whenMakeyKeyPressed(args: any, util: any): any; - addSequence(sequenceString: any, sequenceArray: any): void; - whenCodePressed(args: any): any; - } -} - -declare module "scratch-vm-dts/extensions/scratch3_boost" { - export = Scratch3BoostBlocks; - class int extends Number { } - class array extends Array { } - /** - * Scratch 3.0 blocks to interact with a LEGO Boost peripheral. - */ - class Scratch3BoostBlocks { - /** - * @return {string} - the ID of this extension. - */ - static get EXTENSION_ID(): string; - /** - * @return {number} - the tilt sensor counts as "tilted" if its tilt angle meets or exceeds this threshold. - */ - static get TILT_THRESHOLD(): number; - /** - * Construct a set of Boost blocks. - * @param {Runtime} runtime - the Scratch 3.0 runtime. - */ - constructor(runtime: Runtime); - /** - * The Scratch 3.0 runtime. - * @type {Runtime} - */ - runtime: Runtime; - _peripheral: Boost; - /** - * @returns {object} metadata for this extension and its blocks. - */ - getInfo(): object; - /** - * Turn specified motor(s) on for a specified duration. - * @param {object} args - the block's arguments. - * @property {MotorID} MOTOR_ID - the motor(s) to activate. - * @property {int} DURATION - the amount of time to run the motors. - * @return {Promise} - a promise which will resolve at the end of the duration. - */ - motorOnFor(args: object): Promise; - /** - * Turn specified motor(s) on for a specified rotation in full rotations. - * @param {object} args - the block's arguments. - * @property {MotorID} MOTOR_ID - the motor(s) to activate. - * @property {int} ROTATION - the amount of full rotations to turn the motors. - * @return {Promise} - a promise which will resolve at the end of the duration. - */ - motorOnForRotation(args: object): Promise; - /** - * Turn specified motor(s) on indefinitely. - * @param {object} args - the block's arguments. - * @property {MotorID} MOTOR_ID - the motor(s) to activate. - * @return {Promise} - a Promise that resolves after some delay. - */ - motorOn(args: object): Promise; - /** - * Turn specified motor(s) off. - * @param {object} args - the block's arguments. - * @property {MotorID} MOTOR_ID - the motor(s) to deactivate. - * @return {Promise} - a Promise that resolves after some delay. - */ - motorOff(args: object): Promise; - /** - * Set the power level of the specified motor(s). - * @param {object} args - the block's arguments. - * @property {MotorID} MOTOR_ID - the motor(s) to be affected. - * @property {int} POWER - the new power level for the motor(s). - * @return {Promise} - returns a promise to make sure the block yields. - */ - setMotorPower(args: object): Promise; - /** - * Set the direction of rotation for specified motor(s). - * If the direction is 'reverse' the motor(s) will be reversed individually. - * @param {object} args - the block's arguments. - * @property {MotorID} MOTOR_ID - the motor(s) to be affected. - * @property {MotorDirection} MOTOR_DIRECTION - the new direction for the motor(s). - * @return {Promise} - returns a promise to make sure the block yields. - */ - setMotorDirection(args: object): Promise; - /** - * @param {object} args - the block's arguments. - * @return {number} - returns the motor's position. - */ - getMotorPosition(args: object): number; - /** - * Test whether the tilt sensor is currently tilted. - * @param {object} args - the block's arguments. - * @property {TiltDirection} TILT_DIRECTION_ANY - the tilt direction to test (up, down, left, right, or any). - * @return {boolean} - true if the tilt sensor is tilted past a threshold in the specified direction. - */ - whenTilted(args: object): boolean; - /** - * Test whether the tilt sensor is currently tilted. - * @param {object} args - the block's arguments. - * @property {TiltDirection} TILT_DIRECTION_ANY - the tilt direction to test (up, down, left, right, or any). - * @return {boolean} - true if the tilt sensor is tilted past a threshold in the specified direction. - */ - isTilted(args: object): boolean; - /** - * @param {object} args - the block's arguments. - * @property {TiltDirection} TILT_DIRECTION - the direction (up, down, left, right) to check. - * @return {number} - the tilt sensor's angle in the specified direction. - * Note that getTiltAngle(up) = -getTiltAngle(down) and getTiltAngle(left) = -getTiltAngle(right). - */ - getTiltAngle(args: object): number; - /** - * Edge-triggering hat function, for when the vision sensor is detecting - * a certain color. - * @param {object} args - the block's arguments. - * @return {boolean} - true when the color sensor senses the specified color. - */ - whenColor(args: object): boolean; - /** - * A boolean reporter function, for whether the vision sensor is detecting - * a certain color. - * @param {object} args - the block's arguments. - * @return {boolean} - true when the color sensor senses the specified color. - */ - seeingColor(args: object): boolean; - /** - * Set the LED's hue. - * @param {object} args - the block's arguments. - * @property {number} HUE - the hue to set, in the range [0,100]. - * @return {Promise} - a Promise that resolves after some delay. - */ - setLightHue(args: object): Promise; - } - /** - * Manage communication with a Boost peripheral over a Bluetooth Low Energy client socket. - */ - class Boost { - constructor(runtime: any, extensionId: any); - /** - * The id of the extension this peripheral belongs to. - */ - _extensionId: any; - /** - * Reset all the state and timeout/interval ids. - */ - reset(): void; - /** - * @return {number} - the latest value received for the tilt sensor's tilt about the X axis. - */ - get tiltX(): number; - /** - * @return {number} - the latest value received for the tilt sensor's tilt about the Y axis. - */ - get tiltY(): number; - /** - * @return {number} - the latest color value received from the vision sensor. - */ - get color(): number; - /** - * @return {number} - the previous color value received from the vision sensor. - */ - get previousColor(): number; - /** - * Look up the color id for an index received from the vision sensor. - * @param {number} index - the color index to look up. - * @return {BoostColor} the color id for this index. - */ - boostColorForIndex(index: number): BoostColor; - /** - * Access a particular motor on this peripheral. - * @param {int} index - the index of the desired motor. - * @return {BoostMotor} - the BoostMotor instance, if any, at that index. - */ - motor(index: int): BoostMotor; - /** - * Stop all the motors that are currently running. - */ - stopAllMotors(): void; - /** - * Set the Boost peripheral's LED to a specific color. - * @param {int} inputRGB - a 24-bit RGB color in 0xRRGGBB format. - * @return {Promise} - a promise of the completion of the set led send operation. - */ - setLED(inputRGB: int): Promise; - /** - * Sets the input mode of the LED to RGB. - * @return {Promise} - a promise returned by the send operation. - */ - setLEDMode(): Promise; - /** - * Stop the motors on the Boost peripheral. - */ - stopAll(): void; - /** - * Called by the runtime when user wants to scan for a Boost peripheral. - */ - scan(): void; - /** - * Called by the runtime when user wants to connect to a certain Boost peripheral. - * @param {number} id - the id of the peripheral to connect to. - */ - connect(id: number): void; - /** - * Disconnects from the current BLE socket and resets state. - */ - disconnect(): void; - /** - * Called by the runtime to detect whether the Boost peripheral is connected. - * @return {boolean} - the connected state. - */ - isConnected(): boolean; - /** - * Write a message to the Boost peripheral BLE socket. - * @param {number} uuid - the UUID of the characteristic to write to - * @param {Array} message - the message to write. - * @param {boolean} [useLimiter=true] - if true, use the rate limiter - * @return {Promise} - a promise result of the write operation - */ - send(uuid: number, message: any[], useLimiter?: boolean): Promise; - /** - * Generate a Boost 'Output Command' in the byte array format - * (COMMON HEADER, PORT ID, EXECUTION BYTE, SUBCOMMAND ID, PAYLOAD). - * - * Payload is accepted as an array since these vary across different subcommands. - * - * @param {number} portID - the port (Connect ID) to send a command to. - * @param {number} execution - Byte containing startup/completion information - * @param {number} subCommand - the id of the subcommand byte. - * @param {array} payload - the list of bytes to send as subcommand payload - * @return {array} - a generated output command. - */ - generateOutputCommand( - portID: number, - execution: number, - subCommand: number, - payload: array - ): array; - /** - * Generate a Boost 'Input Command' in the byte array format - * (COMMAND ID, COMMAND TYPE, CONNECT ID, TYPE ID, MODE, DELTA INTERVAL (4 BYTES), - * UNIT, NOTIFICATIONS ENABLED). - * - * This sends a command to the Boost that sets that input format - * of the specified inputs and sets value change notifications. - * - * @param {number} portID - the port (Connect ID) to send a command to. - * @param {number} mode - the mode of the input sensor. - * @param {number} delta - the delta change needed to trigger notification. - * @param {boolean} enableNotifications - whether to enable notifications. - * @return {array} - a generated input command. - */ - generateInputCommand( - portID: number, - mode: number, - delta: number, - enableNotifications: boolean - ): array; - } - /** - * Ids for each color sensor value used by the extension. - */ - type BoostColor = string; - namespace BoostColor { - let ANY: string; - let NONE: string; - let RED: string; - let BLUE: string; - let GREEN: string; - let YELLOW: string; - let WHITE: string; - let BLACK: string; - } - /** - * Manage power, direction, position, and timers for one Boost motor. - */ - class BoostMotor { - /** - * Construct a Boost Motor instance. - * @param {Boost} parent - the Boost peripheral which owns this motor. - * @param {int} index - the zero-based index of this motor on its parent peripheral. - */ - constructor(parent: Boost, index: int); - /** - * Turn this motor off. - * @param {boolean} [useLimiter=true] - if true, use the rate limiter - */ - turnOff(useLimiter?: boolean): void; - /** - * @param {int} value - this motor's new direction: 1 for "this way" or -1 for "that way" - */ - set direction(value: int); - /** - * @return {int} - this motor's current direction: 1 for "this way" or -1 for "that way" - */ - get direction(): int; - /** - * @param {int} value - this motor's new power level, in the range [10,100]. - */ - set power(value: int); - /** - * @return {int} - this motor's current power level, in the range [0,100]. - */ - get power(): int; - /** - * @param {int} value - set this motor's current position. - */ - set position(value: int); - /** - * @return {int} - this motor's current position, in the range of [-MIN_INT32,MAX_INT32] - */ - get position(): int; - /** - * @param {BoostMotorState} value - set this motor's state. - */ - set status(value: { - OFF: number; - ON_FOREVER: number; - ON_FOR_TIME: number; - ON_FOR_ROTATION: number; - }); - /** - * @return {BoostMotorState} - the motor's current state. - */ - get status(): { - OFF: number; - ON_FOREVER: number; - ON_FOR_TIME: number; - ON_FOR_ROTATION: number; - }; - /** - * @return {number} - time, in milliseconds, of when the pending duration timeout began. - */ - get pendingDurationTimeoutStartTime(): number; - /** - * @return {number} - delay, in milliseconds, of the pending duration timeout. - */ - get pendingDurationTimeoutDelay(): number; - /** - * @return {number} - target position, in degrees, of the pending rotation. - */ - get pendingRotationDestination(): number; - /** - * @param {function} func - function to resolve pending rotation Promise - */ - set pendingRotationPromise(func: Function); - /** - * @return {Promise} - the Promise function for the pending rotation. - */ - get pendingRotationPromise(): Promise; - /** - * Turn this motor on indefinitely - */ - turnOnForever(): void; - /** - * Turn this motor on for a specific duration. - * @param {number} milliseconds - run the motor for this long. - */ - turnOnFor(milliseconds: number): void; - /** - * Turn this motor on for a specific rotation in degrees. - * @param {number} degrees - run the motor for this amount of degrees. - * @param {number} direction - rotate in this direction - */ - turnOnForDegrees(degrees: number, direction: number): void; - } -} - -declare module "scratch-vm-dts/extensions/scratch3_gdx_for" { - export = Scratch3GdxForBlocks; - /** - * Scratch 3.0 blocks to interact with a GDX-FOR peripheral. - */ - class Scratch3GdxForBlocks { - /** - * @return {string} - the name of this extension. - */ - static get EXTENSION_NAME(): string; - /** - * @return {string} - the ID of this extension. - */ - static get EXTENSION_ID(): string; - /** - * Construct a set of GDX-FOR blocks. - * @param {Runtime} runtime - the Scratch 3.0 runtime. - */ - constructor(runtime: Runtime); - get AXIS_MENU(): { - text: string; - value: string; - }[]; - get TILT_MENU(): { - text: string; - value: string; - }[]; - get TILT_MENU_ANY(): { - text: string; - value: string; - }[]; - get PUSH_PULL_MENU(): { - text: string; - value: string; - }[]; - get GESTURE_MENU(): { - text: string; - value: string; - }[]; - /** - * The Scratch 3.0 runtime. - * @type {Runtime} - */ - runtime: Runtime; - _peripheral: GdxFor; - /** - * @returns {object} metadata for this extension and its blocks. - */ - getInfo(): object; - whenForcePushedOrPulled(args: any): boolean; - getForce(): number; - whenGesture(args: any): boolean; - _isFacing(direction: any): boolean; - _facingUp: boolean | undefined; - _facingDown: boolean | undefined; - whenTilted(args: any): boolean; - isTilted(args: any): boolean; - getTilt(args: any): number | undefined; - _isTilted(direction: any): boolean; - _getTiltAngle(direction: any): number | undefined; - getSpinSpeed(args: any): number | undefined; - getAcceleration(args: any): number | undefined; - /** - * @param {number} x - x axis vector - * @param {number} y - y axis vector - * @param {number} z - z axis vector - * @return {number} - the magnitude of a three dimension vector. - */ - magnitude(x: number, y: number, z: number): number; - accelMagnitude(): number; - gestureMagnitude(): number; - spinMagnitude(): number; - isFreeFalling(): boolean; - } - /** - * Manage communication with a GDX-FOR peripheral over a Scratch Link client socket. - */ - class GdxFor { - /** - * Construct a GDX-FOR communication object. - * @param {Runtime} runtime - the Scratch 3.0 runtime - * @param {string} extensionId - the id of the extension - */ - constructor(runtime: Runtime, extensionId: string); - /** - * The id of the extension this peripheral belongs to. - */ - _extensionId: string; - /** - * Reset all the state and timeout/interval ids. - */ - reset(): void; - /** - * Called by the runtime when user wants to scan for a peripheral. - */ - scan(): void; - /** - * Called by the runtime when user wants to connect to a certain peripheral. - * @param {number} id - the id of the peripheral to connect to. - */ - connect(id: number): void; - /** - * Called by the runtime when a user exits the connection popup. - * Disconnect from the GDX FOR. - */ - disconnect(): void; - /** - * Return true if connected to the goforce device. - * @return {boolean} - whether the goforce is connected. - */ - isConnected(): boolean; - _spinSpeedFromGyro(val: any): any; - getForce(): number; - getTiltFrontBack(back?: boolean): number; - getTiltLeftRight(right?: boolean): number; - getAccelerationX(): number; - getAccelerationY(): number; - getAccelerationZ(): number; - getSpinSpeedX(): number; - getSpinSpeedY(): number; - getSpinSpeedZ(): number; - } -} - -declare module "scratch-vm-dts/extensions/tw" { - export = TurboWarpBlocks; - /** - * Class for TurboWarp blocks - * @constructor - */ - class TurboWarpBlocks { - constructor(runtime: any); - /** - * The runtime instantiating this block package. - * @type {Runtime} - */ - runtime: Runtime; - /** - * @returns {object} metadata for this extension and its blocks. - */ - getInfo(): object; - getLastKeyPressed(args: any, util: any): any; - getButtonIsDown(args: any, util: any): any; - } -} - -declare module "scratch-vm-dts/extension-support/tw-security-manager" { - export = SecurityManager; - /** - * Responsible for determining various policies related to custom extension security. - * The default implementation prevents automatic extension loading, but grants any - * loaded extensions the maximum possible capabilities so as to retain compatibility - * with a vanilla scratch-vm. You may override properties of an instance of this class - * to customize the security policies as you see fit, for example: - * ```js - * vm.securityManager.getSandboxMode = (url) => { - * if (url.startsWith("https://example.com/")) { - * return "unsandboxed"; - * } - * return "iframe"; - * }; - * vm.securityManager.canAutomaticallyLoadExtension = (url) => { - * return confirm("Automatically load extension: " + url); - * }; - * vm.securityManager.canFetch = (url) => { - * return url.startsWith('https://turbowarp.org/'); - * }; - * vm.securityManager.canOpenWindow = (url) => { - * return url.startsWith('https://turbowarp.org/'); - * }; - * vm.securityManager.canRedirect = (url) => { - * return url.startsWith('https://turbowarp.org/'); - * }; - * ``` - */ - class SecurityManager { - /** - * Determine the typeof sandbox to use for a certain custom extension. - * @param {string} extensionURL The URL of the custom extension. - * @returns {'worker'|'iframe'|'unsandboxed'|Promise<'worker'|'iframe'|'unsandboxed'>} - */ - getSandboxMode( - extensionURL: string - ): - | "worker" - | "iframe" - | "unsandboxed" - | Promise<"worker" | "iframe" | "unsandboxed">; - /** - * Determine whether a custom extension that was stored inside a project may be - * loaded. You could, for example, ask the user to confirm loading an extension - * before resolving. - * @param {string} extensionURL The URL of the custom extension. - * @returns {Promise|boolean} - */ - canLoadExtensionFromProject( - extensionURL: string - ): Promise | boolean; - /** - * Allows last-minute changing the real URL of the extension that gets loaded. - * @param {*} extensionURL The URL requested to be loaded. - * @returns {Promise|string} The URL to actually load. - */ - rewriteExtensionURL(extensionURL: any): Promise | string; - /** - * Determine whether an extension is allowed to fetch a remote resource URL. - * This only applies to unsandboxed extensions that use the appropriate Scratch.* APIs. - * Sandboxed extensions ignore this entirely as there is no way to force them to use our APIs. - * data: and blob: URLs are always allowed (this method is never called). - * @param {string} resourceURL - * @returns {Promise|boolean} - */ - canFetch(resourceURL: string): Promise | boolean; - /** - * Determine whether an extension is allowed to open a new window or tab to a given URL. - * This only applies to unsandboxed extensions. Sandboxed extensions are unable to open windows. - * javascript: URLs are always rejected (this method is never called). - * @param {string} websiteURL - * @returns {Promise|boolean} - */ - canOpenWindow(websiteURL: string): Promise | boolean; - /** - * Determine whether an extension is allowed to redirect the current tab to a given URL. - * This only applies to unsandboxed extensions. Sandboxed extensions are unable to redirect the parent - * window, but are free to redirect their own sandboxed window. - * javascript: URLs are always rejected (this method is never called). - * @param {string} websiteURL - * @returns {Promise|boolean} - */ - canRedirect(websiteURL: string): Promise | boolean; - /** - * Determine whether an extension is allowed to record audio from the user's microphone. - * This could include raw audio data or a transcriptions. - * Note that, even if this returns true, success is not guaranteed. - * @returns {Promise|boolean} - */ - canRecordAudio(): Promise | boolean; - /** - * Determine whether an extension is allowed to record video from the user's camera. - * Note that, even if this returns true, success is not guaranteed. - * @returns {Promise|boolean} - */ - canRecordVideo(): Promise | boolean; - /** - * Determine whether an extension is allowed to read values from the user's clipboard - * without user interaction. - * Note that, even if this returns true, success is not guaranteed. - * @returns {Promise|boolean} - */ - canReadClipboard(): Promise | boolean; - /** - * Determine whether an extension is allowed to show notifications. - * Note that, even if this returns true, success is not guaranteed. - * @returns {Promise|boolean} - */ - canNotify(): Promise | boolean; - /** - * Determine whether an extension is allowed to find the user's precise location using GPS - * and other techniques. Note that, even if this returns true, success is not guaranteed. - * @returns {Promise|boolean} - */ - canGeolocate(): Promise | boolean; - /** - * Determine whether an extension is allowed to embed content from a given URL. - * @param {string} documentURL The URL of the embed. - * @returns {Promise|boolean} - */ - canEmbed(documentURL: string): Promise | boolean; - } -} - -declare module "scratch-vm-dts/extension-support/block-type" { - export = BlockType; - /** - * Types of block - */ - type BlockType = string; - namespace BlockType { - let BOOLEAN: string; - let BUTTON: string; - let LABEL: string; - let COMMAND: string; - let CONDITIONAL: string; - let EVENT: string; - let HAT: string; - let LOOP: string; - let REPORTER: string; - let XML: string; - } -} - -declare module "scratch-vm-dts/extensions/scratch3_video_sensing/library" { - export = VideoMotion; - interface MotionState { - motionFrameNumber: number; - motionAmount: number; - motionDirection: number; - } - /** - * Store the necessary image pixel data to compares frames of a video and - * detect an amount and direction of motion in the full sample or in a - * specified area. - * @constructor - */ - class VideoMotion { - /** - * The number of frames that have been added from a source. - * @type {number} - */ - frameNumber: number; - /** - * The frameNumber last analyzed. - * @type {number} - */ - lastAnalyzedFrame: number; - /** - * The amount of motion detected in the current frame. - * @type {number} - */ - motionAmount: number; - /** - * The direction the motion detected in the frame is general moving in. - * @type {number} - */ - motionDirection: number; - /** - * A copy of the current frame's pixel values. A index of the array is - * represented in RGBA. The lowest byte is red. The next is green. The - * next is blue. And the last is the alpha value of that pixel. - * @type {Uint32Array} - */ - curr: Uint32Array; - /** - * A copy of the last frame's pixel values. - * @type {Uint32Array} - */ - prev: Uint32Array; - /** - * A buffer for holding one component of a pixel's full value twice. - * One for the current value. And one for the last value. - * @type {number} - */ - _arrays: number; - /** - * A clamped uint8 view of _arrays. One component of each index of the - * curr member is copied into this array. - * @type {number} - */ - _curr: number; - /** - * A clamped uint8 view of _arrays. One component of each index of the - * prev member is copied into this array. - * @type {number} - */ - _prev: number; - /** - * Reset internal state so future frame analysis does not consider values - * from before this method was called. - */ - reset(): void; - /** - * Add a frame to be next analyzed. The passed array represent a pixel with - * each index in the RGBA format. - * @param {Uint32Array} source - a source frame of pixels to copy - */ - addFrame(source: Uint32Array): void; - /** - * Analyze the current frame against the previous frame determining the - * amount of motion and direction of the motion. - */ - analyzeFrame(): void; - /** - * Build motion amount and direction values based on stored current and - * previous frame that overlaps a given drawable. - * @param {Drawable} drawable - touchable and bounded drawable to build motion for - * @param {MotionState} state - state to store built values to - */ - getLocalMotion(drawable: Drawable, state: MotionState): void; - } -} From 585b1e37c12c5fe3e505754ceff630e38b83e3e4 Mon Sep 17 00:00:00 2001 From: BenPaoDeXiaoZhi Date: Tue, 29 Jul 2025 19:32:31 +0800 Subject: [PATCH 14/28] =?UTF-8?q?=E5=88=A0=E9=99=A4=E4=BA=86=E4=B8=8D?= =?UTF-8?q?=E5=8F=AF=E8=BE=BE=E7=9A=84=E6=96=87=E4=BB=B6=E5=BC=95=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/plugins-entry.ts | 2 +- src/plugins-manifest.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/plugins-entry.ts b/src/plugins-entry.ts index f051be4..1df9d53 100644 --- a/src/plugins-entry.ts +++ b/src/plugins-entry.ts @@ -27,6 +27,6 @@ export default { "mobile-code-batch-select": () => import(/* webpackChunkName: "plugin-mobile-code-batch-select" */ "src/plugins/mobile-code-batch-select"), "clean-pro": () => import(/* webpackChunkName: "plugin-clean-pro" */ "src/plugins/clean-pro"), "find-definition": () => import(/* webpackChunkName: "plugin-find-definition" */ "src/plugins/find-definition"), - "extension-type-definition": () => import(/* webpackChunkName: "plugin-extension-type-definition" */ "plugins/extension-type-definition"), + // "extension-type-definition": () => import(/* webpackChunkName: "plugin-extension-type-definition" */ "plugins/extension-type-definition"), "wpp-monaco": () => import(/* webpackChunkName: "plugin-wpp-monaco" */ "src/plugins/wpp-monaco"), } as const; diff --git a/src/plugins-manifest.ts b/src/plugins-manifest.ts index 9a283d0..338fa0f 100644 --- a/src/plugins-manifest.ts +++ b/src/plugins-manifest.ts @@ -23,7 +23,7 @@ import dataCategoryTweaks from "plugins/data-category-tweaks/manifest"; import mobileCodeBatchSelect from "src/plugins/mobile-code-batch-select/manifest"; import cleanPro from "src/plugins/clean-pro/manifest"; import findDefinition from "src/plugins/find-definition/manifest"; -import extensionTypeDefinition from "plugins/extension-type-definition/manifest"; +// import extensionTypeDefinition from "plugins/extension-type-definition/manifest"; import wppMonaco from "src/plugins/wpp-monaco/manifest"; export default { @@ -52,6 +52,6 @@ export default { "mobile-code-batch-select": mobileCodeBatchSelect, "clean-pro": cleanPro, "find-definition": findDefinition, - "extension-type-definition": extensionTypeDefinition, + // "extension-type-definition": extensionTypeDefinition, "wpp-monaco": wppMonaco, }; From a10a284a4ecd9920e6ca42b6ba8d1a6cce5334b9 Mon Sep 17 00:00:00 2001 From: BenPaoDeXiaoZhi Date: Tue, 29 Jul 2025 19:37:18 +0800 Subject: [PATCH 15/28] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E4=BA=86=E5=AF=B9?= =?UTF-8?q?=E4=BA=8E=E5=87=BD=E6=95=B0=E5=90=8D=E4=B8=AD=E5=90=AB=E4=B8=8B?= =?UTF-8?q?=E5=88=92=E7=BA=BF=E4=BB=A5=E5=8F=8A=E5=90=8D=E7=A7=B0=E6=9C=80?= =?UTF-8?q?=E5=90=8E=E4=BB=BB=E6=84=8F=E6=95=B0=E9=87=8F=E7=A9=BA=E6=A0=BC?= =?UTF-8?q?=E7=9A=84=E6=94=AF=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/plugins/wpp-monaco/index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/plugins/wpp-monaco/index.js b/src/plugins/wpp-monaco/index.js index 2ccdbee..a1e4107 100644 --- a/src/plugins/wpp-monaco/index.js +++ b/src/plugins/wpp-monaco/index.js @@ -29,7 +29,7 @@ const WppMonaco = ({ vm, registerSettings, msg }) => { root: [ [/\/\/.*$/, { token: "comment.line.wpp" }],//WPP语法1:不支持多行注释,注释应以//开头 [/((if|elif|for|while|return|task|on)(?=\()|else(?={))/, { token: "keyword.wpp" }],//WPP语法:if,elif,for,while后加()为内置函数,else直接加{ - [/[a-zA-z0-9\s]+(?=\(.*\)\s*{)/,{ token: "entity.name.function.wpp" }], + [/[a-zA-z0-9_]+(?=\s*\(.*\)\s*{)/,{ token: "entity.name.function.wpp" }], [/[{}]+/,{token:'delimiter.curly'}], [/[\(\)]+/,{token:'delimiter.parenthesis'}], [/[\[\]]+/,{token:'delimiter.square'}], From b6eb6461d10f921ea1035085e9bda5b3db4008ab Mon Sep 17 00:00:00 2001 From: BenPaoDeXiaoZhi Date: Wed, 30 Jul 2025 17:02:40 +0800 Subject: [PATCH 16/28] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E4=BA=86=E6=95=B0?= =?UTF-8?q?=E5=AD=97=E5=8C=B9=E9=85=8D=E3=80=81=E5=8F=98=E9=87=8F=E5=90=8D?= =?UTF-8?q?=E5=8C=B9=E9=85=8D=E3=80=81let=E5=8C=B9=E9=85=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/plugins/wpp-monaco/index.js | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/src/plugins/wpp-monaco/index.js b/src/plugins/wpp-monaco/index.js index a1e4107..88c88fe 100644 --- a/src/plugins/wpp-monaco/index.js +++ b/src/plugins/wpp-monaco/index.js @@ -21,7 +21,6 @@ const WppMonaco = ({ vm, registerSettings, msg }) => { ); const monaco = window.monaco console.log(monaco) - debugger monaco.languages.register({ id: 'wpp', extensions: ['.wpp'], mimetypes: ['text/plain'] }) monaco.languages.setMonarchTokensProvider('wpp', { keywords:['if'], @@ -29,10 +28,15 @@ const WppMonaco = ({ vm, registerSettings, msg }) => { root: [ [/\/\/.*$/, { token: "comment.line.wpp" }],//WPP语法1:不支持多行注释,注释应以//开头 [/((if|elif|for|while|return|task|on)(?=\()|else(?={))/, { token: "keyword.wpp" }],//WPP语法:if,elif,for,while后加()为内置函数,else直接加{ - [/[a-zA-z0-9_]+(?=\s*\(.*\)\s*{)/,{ token: "entity.name.function.wpp" }], + [/[a-zA-z\u4e00-\u9fa5][\w\u4e00-\u9fa5]*\w*(?=\s*\(.*\)\s*{)/,{ token: "entity.name.function.wpp" }], [/[{}]+/,{token:'delimiter.curly'}], [/[\(\)]+/,{token:'delimiter.parenthesis'}], [/[\[\]]+/,{token:'delimiter.square'}], + [/let(?=\s+[a-zA-z\u4e00-\u9fa5][\w\u4e00-\u9fa5]*\s*=)/, { token: "keyword.wpp" }], + [/this*/, { token: "keyword.wpp"}], + [/[a-zA-z\u4e00-\u9fa5][\w\u4e00-\u9fa5]*/, { token: "identifier.wpp"}], + [/(=|==|>=|<=|>|<|\+|\-|\*|\/)/, { token: ''}], + [/(? { { open: '(', close: ')' } ] }) - monaco.editor.defineTheme('wpp-theme',{ - base:'vs-dark', - inherit: true, - rules:[ - {token:'entity.name.function.wpp',foreground:'#21b3bd'} - ] - }) return { dispose: () => { /** Remove some side effects */ From 5f015f638fe416232b1e02faf76e03205cc182b7 Mon Sep 17 00:00:00 2001 From: BenPaoDeXiaoZhi Date: Wed, 30 Jul 2025 17:05:55 +0800 Subject: [PATCH 17/28] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E4=BA=86=E5=AD=97?= =?UTF-8?q?=E7=AC=A6=E4=B8=B2=E5=8C=B9=E9=85=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/plugins/wpp-monaco/index.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/plugins/wpp-monaco/index.js b/src/plugins/wpp-monaco/index.js index 88c88fe..eefe31b 100644 --- a/src/plugins/wpp-monaco/index.js +++ b/src/plugins/wpp-monaco/index.js @@ -36,7 +36,8 @@ const WppMonaco = ({ vm, registerSettings, msg }) => { [/this*/, { token: "keyword.wpp"}], [/[a-zA-z\u4e00-\u9fa5][\w\u4e00-\u9fa5]*/, { token: "identifier.wpp"}], [/(=|==|>=|<=|>|<|\+|\-|\*|\/)/, { token: ''}], - [/(? Date: Thu, 31 Jul 2025 12:51:45 +0800 Subject: [PATCH 18/28] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E4=BA=86break=E5=92=8C?= =?UTF-8?q?continue=EF=BC=8C=E5=88=A0=E9=99=A4=E4=BA=86=E4=B8=8D=E6=94=AF?= =?UTF-8?q?=E6=8C=81=E7=9A=84=E5=90=8E=E8=A1=8C=E6=96=AD=E8=A8=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/plugins/wpp-monaco/index.js | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/src/plugins/wpp-monaco/index.js b/src/plugins/wpp-monaco/index.js index eefe31b..eb05757 100644 --- a/src/plugins/wpp-monaco/index.js +++ b/src/plugins/wpp-monaco/index.js @@ -27,17 +27,21 @@ const WppMonaco = ({ vm, registerSettings, msg }) => { tokenizer: { root: [ [/\/\/.*$/, { token: "comment.line.wpp" }],//WPP语法1:不支持多行注释,注释应以//开头 - [/((if|elif|for|while|return|task|on)(?=\()|else(?={))/, { token: "keyword.wpp" }],//WPP语法:if,elif,for,while后加()为内置函数,else直接加{ - [/[a-zA-z\u4e00-\u9fa5][\w\u4e00-\u9fa5]*\w*(?=\s*\(.*\)\s*{)/,{ token: "entity.name.function.wpp" }], - [/[{}]+/,{token:'delimiter.curly'}], - [/[\(\)]+/,{token:'delimiter.parenthesis'}], - [/[\[\]]+/,{token:'delimiter.square'}], + [/((if|elif|for|while|return|task|on|rmtask)(?=\()|else(?={))/, { token: "keyword.wpp" }],//WPP语法:if,elif,for,while后加()为内置函数,else直接加{ + [/(break|continue)/, { token: "keyword.wpp" }], + [/[a-zA-z\u4e00-\u9fa5][\w\u4e00-\u9fa5]*\w*(?=\s*\(.*\))/,{ token: "entity.name.function.wpp" }], + // [/(?<=.)[a-zA-z\u4e00-\u9fa5][\w\u4e00-\u9fa5]*/, {token: 'string.wpp'}], //monaco不支持正向后行断言 [/let(?=\s+[a-zA-z\u4e00-\u9fa5][\w\u4e00-\u9fa5]*\s*=)/, { token: "keyword.wpp" }], [/this*/, { token: "keyword.wpp"}], - [/[a-zA-z\u4e00-\u9fa5][\w\u4e00-\u9fa5]*/, { token: "identifier.wpp"}], + [/\$[a-zA-z\u4e00-\u9fa5][\w\u4e00-\u9fa5]*\$/, { token: "identifier.wpp"}], + [/[a-zA-z\u4e00-\u9fa5][\w\u4e00-\u9fa5]*(?=\s*=)/, { token: "identifier.wpp"}], [/(=|==|>=|<=|>|<|\+|\-|\*|\/)/, { token: ''}], - [/(? { autoClosingPairs: [ { open: '{', close: '}' }, { open: '[', close: ']' }, - { open: '(', close: ')' } + { open: '(', close: ')' }, + { open: '\'', close: '\'' }, + { open: '\"', close: '\"' }, ], surroundingPairs: [ { open: '{', close: '}' }, From cbabc5189e50742f228730cf4934afd6f0834c6d Mon Sep 17 00:00:00 2001 From: BenPaoDeXiaoZhi Date: Thu, 31 Jul 2025 14:10:06 +0800 Subject: [PATCH 19/28] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E4=BA=86=E5=85=B3?= =?UTF-8?q?=E9=94=AE=E5=AD=97=E6=8F=90=E7=A4=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/plugins/wpp-monaco/index.js | 74 ++++++++++++++++++++++++++++----- 1 file changed, 63 insertions(+), 11 deletions(-) diff --git a/src/plugins/wpp-monaco/index.js b/src/plugins/wpp-monaco/index.js index eb05757..e69e35d 100644 --- a/src/plugins/wpp-monaco/index.js +++ b/src/plugins/wpp-monaco/index.js @@ -23,25 +23,25 @@ const WppMonaco = ({ vm, registerSettings, msg }) => { console.log(monaco) monaco.languages.register({ id: 'wpp', extensions: ['.wpp'], mimetypes: ['text/plain'] }) monaco.languages.setMonarchTokensProvider('wpp', { - keywords:['if'], + keywords: ['if'], tokenizer: { root: [ [/\/\/.*$/, { token: "comment.line.wpp" }],//WPP语法1:不支持多行注释,注释应以//开头 [/((if|elif|for|while|return|task|on|rmtask)(?=\()|else(?={))/, { token: "keyword.wpp" }],//WPP语法:if,elif,for,while后加()为内置函数,else直接加{ [/(break|continue)/, { token: "keyword.wpp" }], - [/[a-zA-z\u4e00-\u9fa5][\w\u4e00-\u9fa5]*\w*(?=\s*\(.*\))/,{ token: "entity.name.function.wpp" }], + [/[a-zA-z\u4e00-\u9fa5][\w\u4e00-\u9fa5]*\w*(?=\s*\(.*\))/, { token: "entity.name.function.wpp" }], // [/(?<=.)[a-zA-z\u4e00-\u9fa5][\w\u4e00-\u9fa5]*/, {token: 'string.wpp'}], //monaco不支持正向后行断言 [/let(?=\s+[a-zA-z\u4e00-\u9fa5][\w\u4e00-\u9fa5]*\s*=)/, { token: "keyword.wpp" }], - [/this*/, { token: "keyword.wpp"}], - [/\$[a-zA-z\u4e00-\u9fa5][\w\u4e00-\u9fa5]*\$/, { token: "identifier.wpp"}], - [/[a-zA-z\u4e00-\u9fa5][\w\u4e00-\u9fa5]*(?=\s*=)/, { token: "identifier.wpp"}], - [/(=|==|>=|<=|>|<|\+|\-|\*|\/)/, { token: ''}], + [/this*/, { token: "keyword.wpp" }], + [/\$[a-zA-z\u4e00-\u9fa5][\w\u4e00-\u9fa5]*\$/, { token: "identifier.wpp" }], + [/[a-zA-z\u4e00-\u9fa5][\w\u4e00-\u9fa5]*(?=\s*=)/, { token: "identifier.wpp" }], + [/(=|==|>=|<=|>|<|\+|\-|\*|\/)/, { token: '' }], // [/(? { { open: '(', close: ')' } ] }) + const keyword_suggestions = [ + { + label: 'let VAR = DATA', + insertText: 'let = ', + detail: '赋值或修改一个变量,VAR为变量名,DATA为数据' + }, + { + label: 'if(COND){}', + insertText: 'if(){}', + detail: '当条件成立时,执行此分支' + }, + { + label: 'elif(COND){}', + insertText: 'elif(){}', + detail: '当if分支不成立时,检查条件是否成立,成立则进行此分支' + }, + { + label: 'else{}', + insertText: 'else{}', + detail: '当if分支和elif分支都不成立时,进行此分支' + } + ] + keyword_suggestions.map(m=>{ + m.kind = monaco.languages.CompletionItemKind.Keyword; + m.insertTextRules = monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet + }) + monaco.languages.registerCompletionItemProvider('wpp', { + provideCompletionItems: (model, position) => { + /** + * @type{string} + */ + const lineText = model.getValueInRange({ + startLineNumber:position.lineNumber, + startColumn:1, + endLineNumber:position.lineNumber, + endColumn:position.column + }) + const charPos = lineText.search(/\S/) + console.log(lineText) + console.log(charPos) + const suggestions = []; + keyword_suggestions.map(m=>{ + m.range = new monaco.Range( + position.lineNumber,charPos+1, + position.lineNumber,position.column + ) + suggestions.push(m); + }) + console.log(suggestions) + return { suggestions:suggestions}; + } + }); return { dispose: () => { /** Remove some side effects */ From d5b60cafcae677cc0b14b71d28148180df53abfc Mon Sep 17 00:00:00 2001 From: BenPaoDeXiaoZhi <121215648+BenPaoDeXiaoZhi@users.noreply.github.com> Date: Tue, 5 Aug 2025 16:40:42 +0800 Subject: [PATCH 20/28] =?UTF-8?q?=E5=88=9B=E5=BB=BA=20index.js?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/plugins/wpp-monaco/dist/index.js | 122 +++++++++++++++++++++++++++ 1 file changed, 122 insertions(+) create mode 100644 src/plugins/wpp-monaco/dist/index.js diff --git a/src/plugins/wpp-monaco/dist/index.js b/src/plugins/wpp-monaco/dist/index.js new file mode 100644 index 0000000..ffb8c97 --- /dev/null +++ b/src/plugins/wpp-monaco/dist/index.js @@ -0,0 +1,122 @@ +//用于直接通过自定义插件加载 +const WppMonaco = ({ vm, registerSettings, msg }) => { + const supportedAssetTypes = vm.runtime.gandi.supportedAssetTypes + const wpp_asset = { contentType: 'text/plain', name: 'Wpp', runtimeFormat: 'wpp', immutable: true } + + if (!supportedAssetTypes.includes(wpp_asset)) { + supportedAssetTypes.push(wpp_asset) + } + const register = registerSettings( + msg("plugins.wppMonaco.title"), + "plugin-wpp-monaco", + [ + { + key: "plugin-wpp-monaco", + label: msg("plugins.wppMonaco.title"), + description: msg("plugins.wppMonaco.description"), + items: [], + }, + ], + "", + ); + const monaco = window.monaco + console.log(monaco) + monaco.languages.register({ id: 'wpp', extensions: ['.wpp'], mimetypes: ['text/plain'] }) + monaco.languages.setMonarchTokensProvider('wpp', { + keywords: ['if'], + tokenizer: { + root: [ + [/\/\/.*$/, { token: "comment.line.wpp" }],//WPP语法1:不支持多行注释,注释应以//开头 + [/((if|elif|for|while|return|task|on|rmtask)(?=\()|else(?={))/, { token: "keyword.wpp" }],//WPP语法:if,elif,for,while后加()为内置函数,else直接加{ + [/(break|continue)/, { token: "keyword.wpp" }], + [/[a-zA-z\u4e00-\u9fa5][\w\u4e00-\u9fa5]*\w*(?=\s*\(.*\))/, { token: "entity.name.function.wpp" }], + // [/(?<=.)[a-zA-z\u4e00-\u9fa5][\w\u4e00-\u9fa5]*/, {token: 'string.wpp'}], //monaco不支持正向后行断言 + [/let(?=\s+[a-zA-z\u4e00-\u9fa5][\w\u4e00-\u9fa5]*\s*=)/, { token: "keyword.wpp" }], + [/this*/, { token: "keyword.wpp" }], + [/\$[a-zA-z\u4e00-\u9fa5][\w\u4e00-\u9fa5]*\$/, { token: "identifier.wpp" }], + [/[a-zA-z\u4e00-\u9fa5][\w\u4e00-\u9fa5]*(?=\s*=)/, { token: "identifier.wpp" }], + [/(=|==|>=|<=|>|<|\+|\-|\*|\/)/, { token: '' }], + // [/(?{ + m.kind = monaco.languages.CompletionItemKind.Keyword; + m.insertTextRules = monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet + }) + monaco.languages.registerCompletionItemProvider('wpp', { + provideCompletionItems: (model, position) => { + /** + * @type{string} + */ + const lineText = model.getValueInRange({ + startLineNumber:position.lineNumber, + startColumn:1, + endLineNumber:position.lineNumber, + endColumn:position.column + }) + const charPos = lineText.search(/\S/) + console.log(lineText) + console.log(charPos) + const suggestions = []; + keyword_suggestions.map(m=>{ + m.range = new monaco.Range( + position.lineNumber,charPos+1, + position.lineNumber,position.column + ) + suggestions.push(m); + }) + console.log(suggestions) + return { suggestions:suggestions}; + } + }); + return { + dispose: () => { + /** Remove some side effects */ + register.dispose() + }, + }; +}; + +export default WppMonaco; From b2cb08503ff451711921c90fc6003166a303557c Mon Sep 17 00:00:00 2001 From: BenPaoDeXiaoZhi <121215648+BenPaoDeXiaoZhi@users.noreply.github.com> Date: Tue, 5 Aug 2025 16:46:17 +0800 Subject: [PATCH 21/28] =?UTF-8?q?=E6=9B=B4=E6=96=B0=20index.js?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/plugins/wpp-monaco/dist/index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/plugins/wpp-monaco/dist/index.js b/src/plugins/wpp-monaco/dist/index.js index ffb8c97..2496fd3 100644 --- a/src/plugins/wpp-monaco/dist/index.js +++ b/src/plugins/wpp-monaco/dist/index.js @@ -119,4 +119,4 @@ const WppMonaco = ({ vm, registerSettings, msg }) => { }; }; -export default WppMonaco; +window.Scratch.plugins.register(WppMonaco,"Monaco for wpp") From 959a06a7f69e0f9594464a51a320a039410db358 Mon Sep 17 00:00:00 2001 From: BenPaoDeXiaoZhi Date: Fri, 8 Aug 2025 14:42:37 +0800 Subject: [PATCH 22/28] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E4=BA=86=E8=87=AA?= =?UTF-8?q?=E5=8A=A8=E7=BC=A9=E8=BF=9B=E3=80=81=E5=90=A6=E5=88=99=E5=A6=82?= =?UTF-8?q?=E6=9E=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/plugins/wpp-monaco/index.js | 57 +++++++++++++++++++++++++++++---- 1 file changed, 51 insertions(+), 6 deletions(-) diff --git a/src/plugins/wpp-monaco/index.js b/src/plugins/wpp-monaco/index.js index e69e35d..7e4cbd1 100644 --- a/src/plugins/wpp-monaco/index.js +++ b/src/plugins/wpp-monaco/index.js @@ -1,3 +1,4 @@ +import { after } from "node:test"; const WppMonaco = ({ vm, registerSettings, msg }) => { const supportedAssetTypes = vm.runtime.gandi.supportedAssetTypes @@ -57,22 +58,32 @@ const WppMonaco = ({ vm, registerSettings, msg }) => { { open: '{', close: '}' }, { open: '[', close: ']' }, { open: '(', close: ')' } + ], + onEnterRules: [ + { + beforeText: /{$/, + action: { indentAction: monaco.languages.IndentAction.Indent } + }, + { + beforeText: /}/, + action: { indentAction: monaco.languages.IndentAction.Outdent } + } ] }) const keyword_suggestions = [ { label: 'let VAR = DATA', - insertText: 'let = ', + insertText: 'let $1 = ', detail: '赋值或修改一个变量,VAR为变量名,DATA为数据' }, { - label: 'if(COND){}', - insertText: 'if(){}', + label: 'if(COND) {}', + insertText: 'if($1) {}', detail: '当条件成立时,执行此分支' }, { - label: 'elif(COND){}', - insertText: 'elif(){}', + label: 'elif(COND) {}', + insertText: 'elif($1) {}', detail: '当if分支不成立时,检查条件是否成立,成立则进行此分支' }, { @@ -100,17 +111,51 @@ const WppMonaco = ({ vm, registerSettings, msg }) => { console.log(lineText) console.log(charPos) const suggestions = []; - keyword_suggestions.map(m=>{ + keyword_suggestions.map(suggestion=>{ + const m = JSON.parse(JSON.stringify(suggestion)); m.range = new monaco.Range( position.lineNumber,charPos+1, position.lineNumber,position.column ) suggestions.push(m); }) + if(lineText.trim().startsWith('}')){ + let indentLevel = 0; + for(let lineCount = position.lineNumber - 1; lineCount >= 1; lineCount--){ + /** + * @type{string} + */ + const firstLineText = model.getLineContent(lineCount); + if(firstLineText.trim().endsWith('{')){ + if(indentLevel > 0){ + indentLevel--; + }else{ + console.log(firstLineText) + if(firstLineText.trim().startsWith('if')|| firstLineText.trim().search('elif') !== -1){ + suggestions.map(m=>{ + if(m.label.startsWith('else') || m.label.startsWith('elif')){ + m.insertText = ' '+m.insertText + m.range = new monaco.Range( + position.lineNumber,lineText.lastIndexOf('}')+2, + position.lineNumber,position.column + ) + } + }) + } + break + } + }else if(firstLineText.trim().startsWith('}')){ + indentLevel++; + } + + } + } console.log(suggestions) return { suggestions:suggestions}; } }); + // monaco.languages.registerDocumentFormattingEditProvider('wpp', { + // provideDocumentFormattingEdits( return { dispose: () => { /** Remove some side effects */ From b575aa0240121a715386a22afee5f5e6e357d4e1 Mon Sep 17 00:00:00 2001 From: BenPaoDeXiaoZhi Date: Thu, 14 Aug 2025 18:24:22 +0800 Subject: [PATCH 23/28] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E4=BA=8B=E4=BB=B6?= =?UTF-8?q?=E8=B7=9F=E8=B8=AA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/plugins/wpp-monaco/index.js | 52 +++++++++++++++++++++++++++++++-- 1 file changed, 49 insertions(+), 3 deletions(-) diff --git a/src/plugins/wpp-monaco/index.js b/src/plugins/wpp-monaco/index.js index 7e4cbd1..d3c7acf 100644 --- a/src/plugins/wpp-monaco/index.js +++ b/src/plugins/wpp-monaco/index.js @@ -1,5 +1,3 @@ -import { after } from "node:test"; - const WppMonaco = ({ vm, registerSettings, msg }) => { const supportedAssetTypes = vm.runtime.gandi.supportedAssetTypes const wpp_asset = { contentType: 'text/plain', name: 'Wpp', runtimeFormat: 'wpp', immutable: true } @@ -22,6 +20,20 @@ const WppMonaco = ({ vm, registerSettings, msg }) => { ); const monaco = window.monaco console.log(monaco) + console.log(vm.runtime) + let warnLimit = 3 + vm.runtime.on('TARGET_BLOCKS_CHANGED',()=>{ + if(!vm.runtime?.['ext_WitCatInterpreter']){ + if(warnLimit>0){ + console.warn('未加载白猫的wpp,方法解释补全不可用') + warnLimit-- + } + return + } + const wpp = vm.runtime['ext_WitCatInterpreter'] + console.log(wpp) + }) + monaco.languages.register({ id: 'wpp', extensions: ['.wpp'], mimetypes: ['text/plain'] }) monaco.languages.setMonarchTokensProvider('wpp', { keywords: ['if'], @@ -90,6 +102,41 @@ const WppMonaco = ({ vm, registerSettings, msg }) => { label: 'else{}', insertText: 'else{}', detail: '当if分支和elif分支都不成立时,进行此分支' + }, + { + label: 'task()', + insertText: 'task($1)', + detail: '传入一个参数,线程名。此代码将会调用一个线程,若不存在指定线程将不会执行,此代码返回调用的线程的返回值,若没有返回值,返回 null' + }, + { + label:'on(){}', + insertText: 'on($1){}', + detail: '传入一个参数,线程名。此代码将会创建一个线程,线程可以被调用执行。' + }, + { + label:'break', + insertText: 'break', + detail: '在循环里面调用,退出循环,在线程中调用,退出线程' + }, + { + label:'continue', + insertText: 'continue', + detail: ' 在循环里面调用,下一次循环,在线程中调用,退出线程' + }, + { + label:'rmtask()', + insertText: 'rmtask($1)', + detail: '传入一个参数,线程名。 移除某个使用task指定的线程缓存' + }, + { + label:'while() {}', + insertText: 'while() {}', + detail: '如果第一个参数的返回值为true,则继续重复执行,否则,停止循环继续执行下面的' + }, + { + label:'for() {}', + insertText: 'for($1) {}', + detail: '传入三个参数,初始值,终值,步长。在循环开始时执行初始值,每次循环结束后执行步长,每次循环开始时,通过终值等于true来判断是否继续循环还是退出循环执行下面的' } ] keyword_suggestions.map(m=>{ @@ -147,7 +194,6 @@ const WppMonaco = ({ vm, registerSettings, msg }) => { }else if(firstLineText.trim().startsWith('}')){ indentLevel++; } - } } console.log(suggestions) From f435ef98801547c6232322cfd967abd99197c8e4 Mon Sep 17 00:00:00 2001 From: BenPaoDeXiaoZhi Date: Sun, 12 Oct 2025 09:02:25 +0800 Subject: [PATCH 24/28] a --- .../wpp-monaco/assets/extension.ts.txt | 48 ---- .../wpp-monaco/assets/wpp.tmLanguage.json | 119 ---------- src/plugins/wpp-monaco/dist/index.js | 122 ---------- src/plugins/wpp-monaco/index.js | 213 ------------------ src/plugins/wpp-monaco/manifest.ts | 11 - 5 files changed, 513 deletions(-) delete mode 100644 src/plugins/wpp-monaco/assets/extension.ts.txt delete mode 100644 src/plugins/wpp-monaco/assets/wpp.tmLanguage.json delete mode 100644 src/plugins/wpp-monaco/dist/index.js delete mode 100644 src/plugins/wpp-monaco/index.js delete mode 100644 src/plugins/wpp-monaco/manifest.ts diff --git a/src/plugins/wpp-monaco/assets/extension.ts.txt b/src/plugins/wpp-monaco/assets/extension.ts.txt deleted file mode 100644 index 21c197b..0000000 --- a/src/plugins/wpp-monaco/assets/extension.ts.txt +++ /dev/null @@ -1,48 +0,0 @@ -import * as vscode from 'vscode'; - -export function activate(context: vscode.ExtensionContext) { - context.subscriptions.push( - vscode.languages.registerDocumentFormattingEditProvider('wpp', { - provideDocumentFormattingEdits(document: vscode.TextDocument): vscode.TextEdit[] { - const edits: vscode.TextEdit[] = []; - let indentLevel = 0; - - for (let i = 0; i < document.lineCount; i++) { - const line = document.lineAt(i); - const original = line.text; - let text = original.trim(); - - // Adjust indent level before writing line - if (text.startsWith('}')) indentLevel = Math.max(0, indentLevel - 1); - - // 1. Add indent (2 spaces per level) - let formatted = ' '.repeat(indentLevel) + text; - - // 2. let a=1 → let a = 1 - formatted = formatted.replace(/\blet\s+(\S+)\s*=\s*(\S+)/, 'let $1 = $2'); - - // 3. func(a,b) → func(a, b) - formatted = formatted.replace(/\(([^)]*)\)/g, (_, args) => { - return '(' + args.split(',').map((s: string) => s.trim()).join(', ') + ')'; - }); - - // 4. ){} → ) {} - formatted = formatted.replace(/\)\s*\{/, ') {'); - - // 5. }后面如果是描述(非空行、非注释),插入一个空格 - formatted = formatted.replace(/\}(\S)/, '} $1'); - - if (formatted !== original) { - edits.push(vscode.TextEdit.replace(line.range, formatted)); - } - - if (text.endsWith('{')) indentLevel++; - } - - return edits; - } - }) - ); -} - -export function deactivate() {} diff --git a/src/plugins/wpp-monaco/assets/wpp.tmLanguage.json b/src/plugins/wpp-monaco/assets/wpp.tmLanguage.json deleted file mode 100644 index 28618b8..0000000 --- a/src/plugins/wpp-monaco/assets/wpp.tmLanguage.json +++ /dev/null @@ -1,119 +0,0 @@ -{ - "scopeName": "source.wpp", - "patterns": [ - { - "name": "comment.line.wpp", - "match": "//.*$" - }, - { - "name": "comment.line.escape.wpp", - "match": "(?<=^|[^\\\\])\\\\(?!\\\\)" - }, - { - "name": "markup.italic.description.wpp", - "match": "(?<=\\})\\s*(?!\\s*//)[^\\s\\r\\n].*?(?=\\s*//|$)", - "comment": "描述文本,但排除行尾注释" - }, - { - "name": "entity.name.function", - "match": "(?:^\\s*|(?<=:))(if|elif|else|for|while)\\b(?=\\s*\\()" - }, - { - "name": "keyword", - "match": "(?:^\\s*|(?<=:))(on|return|task)\\b(?=\\s*\\()" - }, - { - "name": "entity.name.function", - "match": "(?:^\\s*|(?<=:))[a-zA-Z_][a-zA-Z0-9_]*(?=\\s*\\()" - }, - { - "name": "storage.type", - "match": "\\blet\\b" - }, - { - "name": "punctuation.section.parens.wpp", - "match": "[\\{\\}]" - }, - { - "name": "punctuation.section.parens.wpp", - "match": "[()]" - }, - { - "begin": "\\(", - "end": "\\)", - "name": "meta.expression.wpp", - "beginCaptures": { - "0": { - "name": "punctuation.section.parens.wpp" - } - }, - "endCaptures": { - "0": { - "name": "punctuation.section.parens.wpp" - } - }, - "patterns": [] - }, - { - "include": "#variables" - }, - { - "include": "#expression-content" - } - ], - "repository": { - "expression-content": { - "patterns": [ - { - "name": "entity.name.function", - "match": "(?:^\\s*|(?<=:))[a-zA-Z_][a-zA-Z0-9_]*(?=\\s*\\()" - }, - { - "include": "#variables" - }, - { - "name": "punctuation.separator.comma.wpp", - "match": "," - }, - { - "name": "constant.numeric.wpp", - "match": "\\b\\d+\\b" - }, - { - "name": "keyword", - "match": "==|!=|>=|<=|>|<" - }, - { - "name": "keyword", - "match": "[+\\-*/]" - } - ] - }, - "variables": { - "patterns": [ - { - "match": "\\$(this\\.)([a-zA-Z_\\u4e00-\\u9fa5][a-zA-Z0-9_\\u4e00-\\u9fa5]*)\\$", - "captures": { - "1": { - "name": "variable.language.object.wpp" - }, - "2": { - "name": "variable.other.wpp" - } - } - }, - { - "match": "\\$([a-zA-Z_\\u4e00-\\u9fa5][a-zA-Z0-9_\\u4e00-\\u9fa5]*)\\$", - "captures": { - "1": { - "name": "variable.other.wpp" - } - } - } - ] - } - }, - "fileTypes": [ - "wpp" - ] -} \ No newline at end of file diff --git a/src/plugins/wpp-monaco/dist/index.js b/src/plugins/wpp-monaco/dist/index.js deleted file mode 100644 index 2496fd3..0000000 --- a/src/plugins/wpp-monaco/dist/index.js +++ /dev/null @@ -1,122 +0,0 @@ -//用于直接通过自定义插件加载 -const WppMonaco = ({ vm, registerSettings, msg }) => { - const supportedAssetTypes = vm.runtime.gandi.supportedAssetTypes - const wpp_asset = { contentType: 'text/plain', name: 'Wpp', runtimeFormat: 'wpp', immutable: true } - - if (!supportedAssetTypes.includes(wpp_asset)) { - supportedAssetTypes.push(wpp_asset) - } - const register = registerSettings( - msg("plugins.wppMonaco.title"), - "plugin-wpp-monaco", - [ - { - key: "plugin-wpp-monaco", - label: msg("plugins.wppMonaco.title"), - description: msg("plugins.wppMonaco.description"), - items: [], - }, - ], - "", - ); - const monaco = window.monaco - console.log(monaco) - monaco.languages.register({ id: 'wpp', extensions: ['.wpp'], mimetypes: ['text/plain'] }) - monaco.languages.setMonarchTokensProvider('wpp', { - keywords: ['if'], - tokenizer: { - root: [ - [/\/\/.*$/, { token: "comment.line.wpp" }],//WPP语法1:不支持多行注释,注释应以//开头 - [/((if|elif|for|while|return|task|on|rmtask)(?=\()|else(?={))/, { token: "keyword.wpp" }],//WPP语法:if,elif,for,while后加()为内置函数,else直接加{ - [/(break|continue)/, { token: "keyword.wpp" }], - [/[a-zA-z\u4e00-\u9fa5][\w\u4e00-\u9fa5]*\w*(?=\s*\(.*\))/, { token: "entity.name.function.wpp" }], - // [/(?<=.)[a-zA-z\u4e00-\u9fa5][\w\u4e00-\u9fa5]*/, {token: 'string.wpp'}], //monaco不支持正向后行断言 - [/let(?=\s+[a-zA-z\u4e00-\u9fa5][\w\u4e00-\u9fa5]*\s*=)/, { token: "keyword.wpp" }], - [/this*/, { token: "keyword.wpp" }], - [/\$[a-zA-z\u4e00-\u9fa5][\w\u4e00-\u9fa5]*\$/, { token: "identifier.wpp" }], - [/[a-zA-z\u4e00-\u9fa5][\w\u4e00-\u9fa5]*(?=\s*=)/, { token: "identifier.wpp" }], - [/(=|==|>=|<=|>|<|\+|\-|\*|\/)/, { token: '' }], - // [/(?{ - m.kind = monaco.languages.CompletionItemKind.Keyword; - m.insertTextRules = monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet - }) - monaco.languages.registerCompletionItemProvider('wpp', { - provideCompletionItems: (model, position) => { - /** - * @type{string} - */ - const lineText = model.getValueInRange({ - startLineNumber:position.lineNumber, - startColumn:1, - endLineNumber:position.lineNumber, - endColumn:position.column - }) - const charPos = lineText.search(/\S/) - console.log(lineText) - console.log(charPos) - const suggestions = []; - keyword_suggestions.map(m=>{ - m.range = new monaco.Range( - position.lineNumber,charPos+1, - position.lineNumber,position.column - ) - suggestions.push(m); - }) - console.log(suggestions) - return { suggestions:suggestions}; - } - }); - return { - dispose: () => { - /** Remove some side effects */ - register.dispose() - }, - }; -}; - -window.Scratch.plugins.register(WppMonaco,"Monaco for wpp") diff --git a/src/plugins/wpp-monaco/index.js b/src/plugins/wpp-monaco/index.js deleted file mode 100644 index d3c7acf..0000000 --- a/src/plugins/wpp-monaco/index.js +++ /dev/null @@ -1,213 +0,0 @@ -const WppMonaco = ({ vm, registerSettings, msg }) => { - const supportedAssetTypes = vm.runtime.gandi.supportedAssetTypes - const wpp_asset = { contentType: 'text/plain', name: 'Wpp', runtimeFormat: 'wpp', immutable: true } - - if (!supportedAssetTypes.includes(wpp_asset)) { - supportedAssetTypes.push(wpp_asset) - } - const register = registerSettings( - msg("plugins.wppMonaco.title"), - "plugin-wpp-monaco", - [ - { - key: "plugin-wpp-monaco", - label: msg("plugins.wppMonaco.title"), - description: msg("plugins.wppMonaco.description"), - items: [], - }, - ], - "", - ); - const monaco = window.monaco - console.log(monaco) - console.log(vm.runtime) - let warnLimit = 3 - vm.runtime.on('TARGET_BLOCKS_CHANGED',()=>{ - if(!vm.runtime?.['ext_WitCatInterpreter']){ - if(warnLimit>0){ - console.warn('未加载白猫的wpp,方法解释补全不可用') - warnLimit-- - } - return - } - const wpp = vm.runtime['ext_WitCatInterpreter'] - console.log(wpp) - }) - - monaco.languages.register({ id: 'wpp', extensions: ['.wpp'], mimetypes: ['text/plain'] }) - monaco.languages.setMonarchTokensProvider('wpp', { - keywords: ['if'], - tokenizer: { - root: [ - [/\/\/.*$/, { token: "comment.line.wpp" }],//WPP语法1:不支持多行注释,注释应以//开头 - [/((if|elif|for|while|return|task|on|rmtask)(?=\()|else(?={))/, { token: "keyword.wpp" }],//WPP语法:if,elif,for,while后加()为内置函数,else直接加{ - [/(break|continue)/, { token: "keyword.wpp" }], - [/[a-zA-z\u4e00-\u9fa5][\w\u4e00-\u9fa5]*\w*(?=\s*\(.*\))/, { token: "entity.name.function.wpp" }], - // [/(?<=.)[a-zA-z\u4e00-\u9fa5][\w\u4e00-\u9fa5]*/, {token: 'string.wpp'}], //monaco不支持正向后行断言 - [/let(?=\s+[a-zA-z\u4e00-\u9fa5][\w\u4e00-\u9fa5]*\s*=)/, { token: "keyword.wpp" }], - [/this*/, { token: "keyword.wpp" }], - [/\$[a-zA-z\u4e00-\u9fa5][\w\u4e00-\u9fa5]*\$/, { token: "identifier.wpp" }], - [/[a-zA-z\u4e00-\u9fa5][\w\u4e00-\u9fa5]*(?=\s*=)/, { token: "identifier.wpp" }], - [/(=|==|>=|<=|>|<|\+|\-|\*|\/)/, { token: '' }], - // [/(?{ - m.kind = monaco.languages.CompletionItemKind.Keyword; - m.insertTextRules = monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet - }) - monaco.languages.registerCompletionItemProvider('wpp', { - provideCompletionItems: (model, position) => { - /** - * @type{string} - */ - const lineText = model.getValueInRange({ - startLineNumber:position.lineNumber, - startColumn:1, - endLineNumber:position.lineNumber, - endColumn:position.column - }) - const charPos = lineText.search(/\S/) - console.log(lineText) - console.log(charPos) - const suggestions = []; - keyword_suggestions.map(suggestion=>{ - const m = JSON.parse(JSON.stringify(suggestion)); - m.range = new monaco.Range( - position.lineNumber,charPos+1, - position.lineNumber,position.column - ) - suggestions.push(m); - }) - if(lineText.trim().startsWith('}')){ - let indentLevel = 0; - for(let lineCount = position.lineNumber - 1; lineCount >= 1; lineCount--){ - /** - * @type{string} - */ - const firstLineText = model.getLineContent(lineCount); - if(firstLineText.trim().endsWith('{')){ - if(indentLevel > 0){ - indentLevel--; - }else{ - console.log(firstLineText) - if(firstLineText.trim().startsWith('if')|| firstLineText.trim().search('elif') !== -1){ - suggestions.map(m=>{ - if(m.label.startsWith('else') || m.label.startsWith('elif')){ - m.insertText = ' '+m.insertText - m.range = new monaco.Range( - position.lineNumber,lineText.lastIndexOf('}')+2, - position.lineNumber,position.column - ) - } - }) - } - break - } - }else if(firstLineText.trim().startsWith('}')){ - indentLevel++; - } - } - } - console.log(suggestions) - return { suggestions:suggestions}; - } - }); - // monaco.languages.registerDocumentFormattingEditProvider('wpp', { - // provideDocumentFormattingEdits( - return { - dispose: () => { - /** Remove some side effects */ - register.dispose() - }, - }; -}; - -export default WppMonaco; diff --git a/src/plugins/wpp-monaco/manifest.ts b/src/plugins/wpp-monaco/manifest.ts deleted file mode 100644 index dbe8c26..0000000 --- a/src/plugins/wpp-monaco/manifest.ts +++ /dev/null @@ -1,11 +0,0 @@ -export default { - name: "wpp-monaco", - type: "function", - description: "Provide auto-completion and highlighting for WPP language.", - credits: [ - { - name: "BenPaoDeXiaoZhi @ CCW", - link: "https://www.ccw.site/student/63c2807d669fa967f17f5559" - }, - ], -}; From 5b7e3a0dfbe7bcd3396407d6f930edd6ca98ebae Mon Sep 17 00:00:00 2001 From: BenPaoDeXiaoZhi Date: Sun, 12 Oct 2025 09:06:30 +0800 Subject: [PATCH 25/28] =?UTF-8?q?=E6=89=8B=E6=BB=91=E4=BA=86...?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/plugins-entry.ts | 1 - src/plugins-manifest.ts | 2 -- src/plugins/find-definition/{index.js => index.ts} | 0 3 files changed, 3 deletions(-) rename src/plugins/find-definition/{index.js => index.ts} (100%) diff --git a/src/plugins-entry.ts b/src/plugins-entry.ts index 1df9d53..19d58c8 100644 --- a/src/plugins-entry.ts +++ b/src/plugins-entry.ts @@ -28,5 +28,4 @@ export default { "clean-pro": () => import(/* webpackChunkName: "plugin-clean-pro" */ "src/plugins/clean-pro"), "find-definition": () => import(/* webpackChunkName: "plugin-find-definition" */ "src/plugins/find-definition"), // "extension-type-definition": () => import(/* webpackChunkName: "plugin-extension-type-definition" */ "plugins/extension-type-definition"), - "wpp-monaco": () => import(/* webpackChunkName: "plugin-wpp-monaco" */ "src/plugins/wpp-monaco"), } as const; diff --git a/src/plugins-manifest.ts b/src/plugins-manifest.ts index 338fa0f..b7b3a22 100644 --- a/src/plugins-manifest.ts +++ b/src/plugins-manifest.ts @@ -24,7 +24,6 @@ import mobileCodeBatchSelect from "src/plugins/mobile-code-batch-select/manifest import cleanPro from "src/plugins/clean-pro/manifest"; import findDefinition from "src/plugins/find-definition/manifest"; // import extensionTypeDefinition from "plugins/extension-type-definition/manifest"; -import wppMonaco from "src/plugins/wpp-monaco/manifest"; export default { folder, @@ -53,5 +52,4 @@ export default { "clean-pro": cleanPro, "find-definition": findDefinition, // "extension-type-definition": extensionTypeDefinition, - "wpp-monaco": wppMonaco, }; diff --git a/src/plugins/find-definition/index.js b/src/plugins/find-definition/index.ts similarity index 100% rename from src/plugins/find-definition/index.js rename to src/plugins/find-definition/index.ts From fbf02d850418a84f4d5d85d0df46b88bd7fb113c Mon Sep 17 00:00:00 2001 From: BenPaoDeXiaoZhi Date: Sun, 12 Oct 2025 11:23:56 +0800 Subject: [PATCH 26/28] =?UTF-8?q?=E4=BD=BF=E7=94=A8ts,=E5=8A=A0=E9=80=9F,?= =?UTF-8?q?=E4=BF=AE=E6=94=B9=E9=83=A8=E5=88=86=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/plugins/find-definition/index.ts | 381 ++++++++++++++++----------- 1 file changed, 221 insertions(+), 160 deletions(-) diff --git a/src/plugins/find-definition/index.ts b/src/plugins/find-definition/index.ts index 5bb5184..01db2e3 100644 --- a/src/plugins/find-definition/index.ts +++ b/src/plugins/find-definition/index.ts @@ -1,175 +1,236 @@ -let PROTOTYPE_OPCODE, CALL_OPCODE, CALL_RETURN_OPCODE, CTX_MENU_EXT; import { scrollBlockIntoView } from "utils/block-helper"; -const getBlockInMainWorkspace = (blockly, blockId) => { - const workspace = blockly.getMainWorkspace(); - if (!workspace) { - console.warn("没有工作区,无法获取块"); - return null; - } - const block = workspace.blockDB_[blockId]; - if (!block) { - console.warn("没有找到块", blockId); - return null; - } - return block; + +//类型定义中... +type ContextMenuFunction = (options: Array) => void; + +interface BlockMenuOption { + text: string; + enabled: boolean; + callback: Function; +} + +interface IBlockly{ + getMainWorkspace(): Blockly.WorkspaceSvg; + Events: { + Abstract:any + } +} + +interface ProcedureBlockSVG extends Blockly.BlockSvg{ + isGlobal_:boolean; //是否为全局块 + procCode_:string; //对应的积木名称 +} +//--- + +let PROTOTYPE_OPCODE: string, + CALL_OPCODE: string, + CALL_RETURN_OPCODE: string, + ORIGIN_CONTEXT_MENU: null | ContextMenuFunction; + +const getBlockInMainWorkspace = (blockly: IBlockly, blockId: string) => { + const workspace = blockly.getMainWorkspace(); + if (!workspace) { + console.warn("没有工作区,无法获取块"); + return null; + } + const block = workspace.blockDB_[blockId]; + if (!block) { + console.warn("没有找到块", blockId); + return null; + } + return block; }; -const goToDefinition = (call_block, vm, workspace, blockly) => { - const procCode = call_block.procCode_ - let prototypeBlockInTarget, targetId; - if (!call_block.isGlobal_) { - for (let block of Object.values(vm.editingTarget.blocks._blocks)) { - if ( - block.opcode === PROTOTYPE_OPCODE &&//如果是定义块 - block.mutation.proccode === procCode//并且定义块的procCode与调用块的procCode相同 - ) { - prototypeBlockInTarget = block; - targetId = vm.editingTarget.id; - break; - } - } - } else { - for (let target of vm.runtime.targets) {//遍历每一个角色,在模块或当前角色中搜索自制积木的定义块 - if (target.isModule) { - for (let block of Object.values(target.blocks._blocks)) { - if ( - block.opcode === PROTOTYPE_OPCODE &&//如果是定义块 - block.mutation.isglobal === 'true' &&//并且是全局的 - block.mutation.proccode === procCode//并且定义块的procCode与调用块的procCode相同 - ) { - prototypeBlockInTarget = block; - targetId = target.id; - break; - } - } - } - } + +/** + * @param call_block 右键菜单的块 + */ +const goToDefinition = (call_block: ProcedureBlockSVG, vm: VirtualMachine, workspace: Blockly.WorkspaceSvg, blockly: IBlockly) => { + console.log(call_block) + const procCode = call_block.procCode_; + let prototypeBlockInTarget:Scratch.BlockState, targetId:string; + for (let block of Object.values(vm.editingTarget.blocks._blocks)) { + //在当前角色中寻找 + if ( + block.opcode === PROTOTYPE_OPCODE && //如果是定义块 + block.mutation.proccode === procCode //并且定义块的procCode与调用块的procCode相同 + ) { + prototypeBlockInTarget = block; + targetId = vm.editingTarget.id; + break; } - // for (let target of vm.runtime.targets) {//遍历每一个角色,在模块或当前角色中搜索自制积木的定义块 - // if (target.id !== vm.editingTarget.id && !target.isModule) { - // continue; - // } - // console.log(target.blocks); - // for (let block of Object.values(target.blocks._blocks)) { - // if ( - // block.opcode === PROTOTYPE_OPCODE &&//如果是定义块 - // (block.mutation.isglobal === 'true' || target.id === vm.editingTarget.id) &&//并且是全局的或当前角色 - // block.mutation.proccode === procCode//并且定义块的procCode与调用块的procCode相同 - // ) { - // prototypeBlockInTarget = block; - // targetId = target.id; - // break; - // } - // } - // } - if (!prototypeBlockInTarget) { - console.warn("没有找到定义块,无法跳转"); - return; + } + if ( + !prototypeBlockInTarget && //在当前角色中未找到 + call_block.isGlobal_ //可能在全局中 + ) { + const moduleName = call_block.procCode_.split('.')[0] + const moduleTargets = vm.runtime.targets.filter((t)=>{ + if(t.sprite.name.endsWith('/'+moduleName) && t.isModule){//这可能导致不是指定模块的模块被整进来,但还是比遍历每一个快多了 + return true + } + return false + }) + console.log(moduleName,vm,moduleTargets) + for (let target of moduleTargets) { + //遍历每一个模块,搜索自制积木的定义块 + if (target.isModule) { + for (let block of Object.values(target.blocks._blocks)) { + if ( + block.opcode === PROTOTYPE_OPCODE && //如果是定义块 + block.mutation.proccode === procCode && //并且定义块的procCode与调用块的procCode相同 + block.mutation.isglobal === "true" //并且是全局的 + ) { + prototypeBlockInTarget = block; + targetId = target.id; + break; + } + } + } } - const src_target_id = vm.editingTarget.id;//记录调用自制积木的角色id - const dst_target_id = targetId;//记录定义自制积木的角色id - if (targetId !== vm.editingTarget.id) { - vm.setEditingTarget(targetId); + } + + if (!prototypeBlockInTarget) { + console.warn("没有找到定义块,无法跳转"); + return; + } + + const src_target_id = vm.editingTarget.id; //记录调用自制积木的角色id + const dst_target_id = targetId; //记录定义自制积木的角色id + if (targetId !== vm.editingTarget.id) { + vm.setEditingTarget(targetId); + } + + const prototypeBlock = getBlockInMainWorkspace(blockly, prototypeBlockInTarget.id); + const definitionBlock:Blockly.Block = prototypeBlock.parentBlock_; //prototype无法进行跳转,所以需要获取其父块definition + scrollBlockIntoView(definitionBlock, workspace); + class MoveWorkspaceEvent extends blockly.Events.Abstract { + type: 'GOTO_DEF'; + src_target_id: string; + src_block_id: string; + dst_target_id: string; + dst_block_id: string; + workspace: Blockly.WorkspaceSvg; + recordUndo:boolean; + constructor( + src_target_id: string, + src_block_id: string, + dst_target_id: string, + dst_block_id: string, + workspace: Blockly.WorkspaceSvg, + ) { + super(); + this.type = "GOTO_DEF"; + this.src_target_id = src_target_id; + this.src_block_id = src_block_id; + this.dst_target_id = dst_target_id; + this.dst_block_id = dst_block_id; + this.workspace = workspace; + this.recordUndo = true; //记录撤销 } - const prototypeBlock = getBlockInMainWorkspace(blockly, prototypeBlockInTarget.id); - const defineBlock = prototypeBlock.parentBlock_;//prototype无法进行跳转,所以需要获取其父块definition - scrollBlockIntoView(defineBlock, workspace); - class MoveWorkspaceEvent extends blockly.Events.Abstract { - constructor(src_target_id, src_block_id, dst_target_id, dst_block_id, workspace) { - super() - this.type = 'GOTO_DEF' - this.src_target_id = src_target_id - this.src_block_id = src_block_id - this.dst_target_id = dst_target_id - this.dst_block_id = dst_block_id - this.workspace = workspace - this.recordUndo = true//记录撤销 - } - run(redo) { - if (redo) { - vm.setEditingTarget(this.dst_target_id); - scrollBlockIntoView(getBlockInMainWorkspace(blockly, this.dst_block_id), this.workspace)//跳转至定义(要通过id获取,否则跨角色会获取失败) - } - else { - vm.setEditingTarget(this.src_target_id); - scrollBlockIntoView(getBlockInMainWorkspace(blockly, this.src_block_id), this.workspace)//跳转回引用 - } - } + /** + * 执行撤销或重做 + * @param redo 为重做? + */ + run(redo:boolean) { + if (redo) { + vm.setEditingTarget(this.dst_target_id); + scrollBlockIntoView(getBlockInMainWorkspace(blockly, this.dst_block_id), this.workspace); //跳转至定义(要通过id获取,否则跨角色会获取失败) + } else { + vm.setEditingTarget(this.src_target_id); + scrollBlockIntoView(getBlockInMainWorkspace(blockly, this.src_block_id), this.workspace); //跳转回引用 + } } - workspace.fireChangeListener(new MoveWorkspaceEvent(src_target_id, call_block.id, dst_target_id, defineBlock.id, workspace))//记录跳转事件 + } + workspace.fireChangeListener( + ( + new MoveWorkspaceEvent(src_target_id, call_block.id, dst_target_id, definitionBlock.id, workspace)as any + ), + ); //记录跳转事件 }; + const handleGoToDefinition = function (vm, blockly) { - if (!this.getProcCode) { - console.warn("没有procCode,无法跳转"); - return; - } - goToDefinition(this, vm, blockly.getMainWorkspace(), blockly); + if (!this.getProcCode) { + console.warn("没有procCode,无法跳转"); + return; + } + console.log(this) + goToDefinition(this, vm, blockly.getMainWorkspace(), blockly); }; -const refreshBlocksWithOpcodes = (blockly, opcodes) => { - for (let block of blockly.getMainWorkspace().getAllBlocks()) { - if (opcodes.includes(block.type)) { - block.customContextMenu = CTX_MENU_EXT.customContextMenu - } + +function refreshBlocksMenuWithOpcodes( + blockly: typeof Blockly & { getMainWorkspace: () => Blockly.WorkspaceSvg }, + opcodes: Array, + newCtxFunc: (options:Array)=>void +) { + for (let block of blockly.getMainWorkspace().getAllBlocks()) { + if (opcodes.includes(block.type)) { + (block as Blockly.Block & { customContextMenu: ContextMenuFunction}).customContextMenu = + newCtxFunc; } - blockly.getMainWorkspace().getToolbox().showAll_() + } + (blockly.getMainWorkspace().getToolbox() as Blockly.Toolbox & {showAll_:()=>void}).showAll_(); } -const FindDefinition = ({ blockly, vm, registerSettings, msg }) => { - if (blockly.Blocks[blockly.PROCEDURES_CALL_BLOCK_TYPE]) { - PROTOTYPE_OPCODE = blockly.PROCEDURES_PROTOTYPE_BLOCK_TYPE; - CALL_OPCODE = blockly.PROCEDURES_CALL_BLOCK_TYPE; - CALL_RETURN_OPCODE = blockly.PROCEDURES_CALL_WITH_RETURN_BLOCK_TYPE; - CTX_MENU_EXT = blockly.ScratchBlocks.VerticalExtensions.PROCEDURE_CALL_CONTEXTMENU; - CTX_MENU_EXT._orig = CTX_MENU_EXT.customContextMenu; - CTX_MENU_EXT.customContextMenu = function (menuOptions) { - if (CTX_MENU_EXT._orig === undefined) { - console.warn("菜单未刷新,可尝试切换角色");//一般不会运行,因为删除插件时会刷新 - return; - } - CTX_MENU_EXT._orig.call(this, menuOptions);//调用原有菜单 - menuOptions.push({//加入自定义菜单项 - text: msg("plugins.findDefinition.goToDefinition"), - enabled: true, - callback: handleGoToDefinition.bind(this, vm, blockly), - }); - }; - refreshBlocksWithOpcodes(blockly, [CALL_OPCODE, CALL_RETURN_OPCODE]); - } - const register = registerSettings( - msg("plugins.findDefinition.title"), - "plugin-find-definition", - [ - { - key: "plugin-find-definition", - label: msg("plugins.findDefinition.title"), - description: msg("plugins.findDefinition.description"), - items: [], - }, - ], - "", - ); - return { - dispose: () => { - /** Remove some side effects */ - CTX_MENU_EXT = blockly.ScratchBlocks.VerticalExtensions.PROCEDURE_CALL_CONTEXTMENU; - CTX_MENU_EXT.customContextMenu = CTX_MENU_EXT._orig; - CTX_MENU_EXT._orig = undefined; - const workspace = blockly.getMainWorkspace(); - if (!workspace) { - console.warn("没有工作区,无法删除原有菜单"); - return; - } - refreshBlocksWithOpcodes(blockly, [CALL_OPCODE, CALL_RETURN_OPCODE]); - // workspace.clearUndo(); 我不想使用这个,因为会清除所有撤销记录 - // 可能导致用户无法撤销之前的操作 - // 但可以通过遍历undoStack并删除的方式来清除跳转事件 - const new_undo_stack = workspace.undoStack_.filter(event => event.type !== 'GOTO_DEF'); - workspace.undoStack_ = new_undo_stack; - //同时,也需要删除redoStack - const new_redo_stack = workspace.redoStack_.filter(event => event.type !== 'GOTO_DEF'); - workspace.redoStack_ = new_redo_stack; - register.dispose(); - }, +function FindDefinition({ blockly, vm, registerSettings, msg }: PluginContext): { dispose: () => void } { + if (blockly.Blocks[blockly.PROCEDURES_CALL_BLOCK_TYPE]) { + PROTOTYPE_OPCODE = blockly.PROCEDURES_PROTOTYPE_BLOCK_TYPE; + CALL_OPCODE = blockly.PROCEDURES_CALL_BLOCK_TYPE; + CALL_RETURN_OPCODE = blockly.PROCEDURES_CALL_WITH_RETURN_BLOCK_TYPE; + const ctxMenuClass: { customContextMenu: ContextMenuFunction } = + blockly.ScratchBlocks.VerticalExtensions.PROCEDURE_CALL_CONTEXTMENU; + ORIGIN_CONTEXT_MENU = ctxMenuClass.customContextMenu; + ctxMenuClass.customContextMenu = function (menuOptions: Array) { + if (ORIGIN_CONTEXT_MENU === null) { + console.warn("菜单未刷新,可尝试切换角色"); //一般不会运行,因为删除插件时会刷新 + return; + } + ORIGIN_CONTEXT_MENU.call(this, menuOptions); //调用原有菜单 + menuOptions.push({ + //加入自定义菜单项 + text: msg("plugins.findDefinition.goToDefinition"), + enabled: true, + callback: handleGoToDefinition.bind(this, vm, blockly), + }); }; -}; + refreshBlocksMenuWithOpcodes(blockly, [CALL_OPCODE, CALL_RETURN_OPCODE], ctxMenuClass.customContextMenu); + } + const register = registerSettings( + msg("plugins.findDefinition.title"), + "plugin-find-definition", + [ + { + key: "plugin-find-definition", + label: msg("plugins.findDefinition.title"), + description: msg("plugins.findDefinition.description"), + items: [], + }, + ], + "", + ); + return { + dispose: () => { + /** Remove some side effects */ + const ctxMenuClass: { customContextMenu: ContextMenuFunction } = + blockly.ScratchBlocks.VerticalExtensions.PROCEDURE_CALL_CONTEXTMENU; + ctxMenuClass.customContextMenu = ORIGIN_CONTEXT_MENU + ORIGIN_CONTEXT_MENU = undefined; + const workspace = blockly.getMainWorkspace(); + if (!workspace) { + console.warn("没有工作区,无法删除原有菜单"); + return; + } + refreshBlocksMenuWithOpcodes(blockly, [CALL_OPCODE, CALL_RETURN_OPCODE], ctxMenuClass.customContextMenu); + // workspace.clearUndo(); 我不想使用这个,因为会清除所有撤销记录 + // 可能导致用户无法撤销之前的操作 + // 但可以通过遍历undoStack并删除的方式来清除跳转事件 + const new_undo_stack = workspace.undoStack_.filter((event) => event.type !== "GOTO_DEF"); + workspace.undoStack_ = new_undo_stack; + //同时,也需要删除redoStack + const new_redo_stack = workspace.redoStack_.filter((event) => event.type !== "GOTO_DEF"); + workspace.redoStack_ = new_redo_stack; + register.dispose(); + }, + }; +} export default FindDefinition; From 5f423f6d569c5353fbc738e373654182360316cb Mon Sep 17 00:00:00 2001 From: BenPaoDeXiaoZhi <121215648+BenPaoDeXiaoZhi@users.noreply.github.com> Date: Sun, 12 Oct 2025 13:00:41 +0800 Subject: [PATCH 27/28] =?UTF-8?q?=E6=9B=B4=E6=96=B0=20index.ts?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 删除调试信息 --- src/plugins/find-definition/index.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/plugins/find-definition/index.ts b/src/plugins/find-definition/index.ts index 01db2e3..3ab3ceb 100644 --- a/src/plugins/find-definition/index.ts +++ b/src/plugins/find-definition/index.ts @@ -45,7 +45,6 @@ const getBlockInMainWorkspace = (blockly: IBlockly, blockId: string) => { * @param call_block 右键菜单的块 */ const goToDefinition = (call_block: ProcedureBlockSVG, vm: VirtualMachine, workspace: Blockly.WorkspaceSvg, blockly: IBlockly) => { - console.log(call_block) const procCode = call_block.procCode_; let prototypeBlockInTarget:Scratch.BlockState, targetId:string; for (let block of Object.values(vm.editingTarget.blocks._blocks)) { @@ -70,7 +69,6 @@ const goToDefinition = (call_block: ProcedureBlockSVG, vm: VirtualMachine, works } return false }) - console.log(moduleName,vm,moduleTargets) for (let target of moduleTargets) { //遍历每一个模块,搜索自制积木的定义块 if (target.isModule) { From 7e418166e721bdfffbc126587ecaf22ceaba35db Mon Sep 17 00:00:00 2001 From: BenPaoDeXiaoZhi <121215648+BenPaoDeXiaoZhi@users.noreply.github.com> Date: Sun, 12 Oct 2025 13:01:24 +0800 Subject: [PATCH 28/28] =?UTF-8?q?=E6=9B=B4=E6=96=B0=20index.ts?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 删除调试信息 --- src/plugins/find-definition/index.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/plugins/find-definition/index.ts b/src/plugins/find-definition/index.ts index 3ab3ceb..57f35e8 100644 --- a/src/plugins/find-definition/index.ts +++ b/src/plugins/find-definition/index.ts @@ -151,7 +151,6 @@ const handleGoToDefinition = function (vm, blockly) { console.warn("没有procCode,无法跳转"); return; } - console.log(this) goToDefinition(this, vm, blockly.getMainWorkspace(), blockly); };