@kubohiroya/turbowarp-plus-editor-workbench 0.16.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.ja.md CHANGED
@@ -134,6 +134,17 @@ Editor のルートから、`site/source.json` の GUI を `npm run build:pages`
134
134
 
135
135
  `debugger-panel.css` はアドオンのクラス名を上書きするため、ホストはグローバルなスタイルシートとして読み込む。タブと浮動ウィンドウの両方で、アドオン固有の青緑の代わりに GUI のテーマ変数を使う。
136
136
 
137
+ ## ブロックを置かないブレークポイント
138
+
139
+ `attachBreakpointMenu({vm, getBlockly, getLocale})` は、コード領域のコマンドブロックの右クリックメニューに「ブレークポイントを設定」「ブレークポイントを外す」を加え、編集中のスプライトで印を付けたブロックを赤い縁と左側の赤い点で示す(規則は `debugger-panel.css`)。`getBreakpoints(vm)` は VM ごとの印を返す。印は編集中のセッションだけに持ち、作品には書かない。作品を読み込むと消える。
140
+
141
+ 印を付けたブロックが動く直前に、デバッガーアドオン自身の一時停止で止める。そのため、アドオンの Threads タブ・Step・再開は、ブレークポイントブロックのときと同じように使える。アドオンが無効なときは、メニューに項目を出さない。
142
+
143
+ VM は変更しない。印がひとつでもある間だけ `runtime.getOpcodeFunction`・`runtime._pushThread`・`runtime._restartThread` を包み、最後の印を外すと元に戻す。
144
+
145
+ - スレッドが印の付いたブロックに着くと、そのブロックが最初に動かす関数の代わりに一時停止し、レポーターの応答を待つときと同じようにフレームを待たせる。再開すると、ブロックを最初から実行する。同じブロックに留まって待つ間や、ループの頭へ戻ったときは、着いたときの一度だけ止まる。
146
+ - コンパイル済みのスクリプトはブロックごとの関数を呼ばないため、印のあるスプライト(クローンを含む)で始まるスクリプトはコンパイルしない。印のないスプライトはこれまでどおりコンパイルする。すでにコンパイル済みで動いているスクリプトは、もう一度始めるまで止まらない。メニューの項目でそのことを示す。
147
+
137
148
  ## Editor と組み合わせたローカル検証
138
149
 
139
150
  `npm test` でタブの状態管理、ファイルメニューの操作、既存レイアウトを検証する。
package/README.md CHANGED
@@ -137,6 +137,17 @@ The panes inside a sprite editing tab (assets and variables, messages, the prope
137
137
 
138
138
  `debugger-panel.css` restyles the add-on's own class names, so the host loads it as a global stylesheet. In the tab and the floating window alike it replaces the add-on's fixed teal with the GUI's theme variables.
139
139
 
140
+ ## Breakpoints without breakpoint blocks
141
+
142
+ `attachBreakpointMenu({vm, getBlockly, getLocale})` adds "Add breakpoint" and "Remove breakpoint" to the context menu of a command block in the code area, and marks the blocks of the sprite being edited with a red outline and a red dot on their left (the rules are in `debugger-panel.css`). `getBreakpoints(vm)` returns the marks of one VM. A mark lives in the editing session and is never written to the project; a project load clears it.
143
+
144
+ The project stops right before a marked block runs, through the debugger add-on's own pause, so the add-on's Threads tab, Step and Continue work as they do for its breakpoint block. Without the add-on the menu item is not offered.
145
+
146
+ The VM is not changed. While at least one mark exists, `runtime.getOpcodeFunction`, `runtime._pushThread` and `runtime._restartThread` are wrapped, and they are restored when the last mark goes:
147
+
148
+ - When a thread arrives at a marked block, the first function the block runs pauses instead, and the frame waits the way it waits for a reporter. Continuing runs the block from its start. A block that waits in place, or a loop that comes back to its head, stops only on arrival.
149
+ - Compiled scripts run no per-block functions, so a script that starts in a sprite with a mark (clones included) is not compiled. Sprites without a mark compile as before. A script that was already running compiled keeps running until it starts again, and the menu item says so.
150
+
140
151
  ## Local verification with the Editor
141
152
 
142
153
  Run `npm test` to check tab state, file menu actions, and the existing layout. Set `TW_PLUS_LAYOUT_EDITOR_URL` to an Editor URL built with the pinned Scratch GUI and run `npm run test:browser` to verify Dockview through the existing tab strip and editor panel integration. Set `TW_PLUS_LAYOUT_FILE_MENU_URL` for the same command to check a GUI build with the optional file menu integration.
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Breakpoints marked on blocks instead of placed as blocks.
3
+ *
4
+ * The editor add-on's debugger stops a project when a "breakpoint" block runs. That block is part
5
+ * of the project, so it is saved and shipped unless someone remembers to take it out. Here a block
6
+ * is only marked in the editor: the mark lives in this session, never in the project, and the
7
+ * project stops right before a marked block runs.
8
+ *
9
+ * Stopping is the add-on's own pause (its hidden `sa-pause` block), so its Threads tab, Step and
10
+ * Continue work unchanged. Without the add-on nothing can pause, and no menu item is offered.
11
+ *
12
+ * The VM is not changed. Two of its methods are wrapped, and only while at least one mark exists:
13
+ *
14
+ * - `getOpcodeFunction`: the block functions the interpreter caches. When a thread arrives at a
15
+ * marked block, the first function the block runs pauses instead, and the frame waits the way it
16
+ * waits for a reporter. Continuing runs the block from its start. The mark is kept in the
17
+ * frame's execution context, which the VM clears when the thread moves to another block, so a
18
+ * block that waits in place or a loop that comes back to its head stops only on arrival.
19
+ * - `_pushThread` and `_restartThread`: compiled scripts run no per-block functions, so a script
20
+ * that starts in a sprite with a mark is not compiled. Sprites without a mark compile as before.
21
+ * A script that was already running compiled keeps running until it starts again.
22
+ */
23
+ export declare const breakpointClass = "tw-plus-breakpoint";
24
+ export declare const breakpointDotClass = "tw-plus-breakpoint-dot";
25
+ export interface Breakpoints {
26
+ /** Whether a pause is possible: the debugger add-on is on and has registered its pause. */
27
+ canPause(): boolean;
28
+ has(blocks: object, blockId: string): boolean;
29
+ set(blocks: object, blockId: string, marked: boolean): void;
30
+ toggle(blocks: object, blockId: string): boolean;
31
+ /** The marked blocks of one block container that still exist. */
32
+ ids(blocks: object): string[];
33
+ /** Whether a script in this container is running compiled, so a new mark misses it until it starts again. */
34
+ runsCompiled(blocks: object): boolean;
35
+ clear(): void;
36
+ subscribe(listener: () => void): () => void;
37
+ }
38
+ /**
39
+ * The breakpoints of one VM. Every caller gets the same instance, so the menu and the runtime
40
+ * agree on what is marked.
41
+ * @param {object} vm The VM.
42
+ * @returns {object} The breakpoints.
43
+ */
44
+ export declare function getBreakpoints(vm: object): Breakpoints;
45
+ interface ScratchBlocksLike {
46
+ ContextMenu: {
47
+ show(event: unknown, items: MenuItem[], rtl: boolean): void;
48
+ };
49
+ getMainWorkspace?(): WorkspaceLike | null;
50
+ mainWorkspace?: WorkspaceLike | null;
51
+ }
52
+ interface MenuItem {
53
+ text: string;
54
+ enabled: boolean;
55
+ callback(): void;
56
+ separator?: boolean;
57
+ }
58
+ interface BlockSvgLike {
59
+ id: string;
60
+ isShadow?(): boolean;
61
+ previousConnection?: unknown;
62
+ workspace?: WorkspaceLike;
63
+ getSvgRoot?(): Element | null;
64
+ }
65
+ interface WorkspaceLike {
66
+ isFlyout?: boolean;
67
+ currentGesture_?: {
68
+ targetBlock_?: BlockSvgLike | null;
69
+ flyout_?: unknown;
70
+ } | null;
71
+ getBlockById(id: string): BlockSvgLike | null;
72
+ getParentSvg?(): Element | null;
73
+ addChangeListener?(listener: (event: unknown) => void): unknown;
74
+ removeChangeListener?(listener: unknown): void;
75
+ }
76
+ interface BreakpointMenuOptions {
77
+ vm: object;
78
+ getBlockly(): Promise<ScratchBlocksLike> | ScratchBlocksLike;
79
+ getLocale?(): string | undefined;
80
+ }
81
+ export declare const breakpointMenuText: (locale: string | undefined, marked: boolean, runsCompiled: boolean) => "ブレークポイントを外す" | "ブレークポイントを設定(次に始めたときから止まる)" | "ブレークポイントを設定" | "Remove breakpoint" | "Add breakpoint (stops from the next start)" | "Add breakpoint";
82
+ /**
83
+ * Offer "Add breakpoint" on the context menu of a command block in the code area, and outline the
84
+ * marked blocks of the sprite being edited.
85
+ * @param {object} options The VM, a way to get ScratchBlocks, and the GUI's language.
86
+ * @returns {object} Something to dispose.
87
+ */
88
+ export declare function attachBreakpointMenu(options: BreakpointMenuOptions): {
89
+ dispose(): void;
90
+ };
91
+ export {};
@@ -0,0 +1,310 @@
1
+ /**
2
+ * Breakpoints marked on blocks instead of placed as blocks.
3
+ *
4
+ * The editor add-on's debugger stops a project when a "breakpoint" block runs. That block is part
5
+ * of the project, so it is saved and shipped unless someone remembers to take it out. Here a block
6
+ * is only marked in the editor: the mark lives in this session, never in the project, and the
7
+ * project stops right before a marked block runs.
8
+ *
9
+ * Stopping is the add-on's own pause (its hidden `sa-pause` block), so its Threads tab, Step and
10
+ * Continue work unchanged. Without the add-on nothing can pause, and no menu item is offered.
11
+ *
12
+ * The VM is not changed. Two of its methods are wrapped, and only while at least one mark exists:
13
+ *
14
+ * - `getOpcodeFunction`: the block functions the interpreter caches. When a thread arrives at a
15
+ * marked block, the first function the block runs pauses instead, and the frame waits the way it
16
+ * waits for a reporter. Continuing runs the block from its start. The mark is kept in the
17
+ * frame's execution context, which the VM clears when the thread moves to another block, so a
18
+ * block that waits in place or a loop that comes back to its head stops only on arrival.
19
+ * - `_pushThread` and `_restartThread`: compiled scripts run no per-block functions, so a script
20
+ * that starts in a sprite with a mark is not compiled. Sprites without a mark compile as before.
21
+ * A script that was already running compiled keeps running until it starts again.
22
+ */
23
+ const PROMISE_WAIT = 1;
24
+ const pauseProcedure = 'sa-pause';
25
+ const hitKey = Symbol('tw-plus-breakpoint-hit');
26
+ export const breakpointClass = 'tw-plus-breakpoint';
27
+ export const breakpointDotClass = 'tw-plus-breakpoint-dot';
28
+ const svgNamespace = 'http://www.w3.org/2000/svg';
29
+ const breakpointsByVm = new WeakMap();
30
+ const ownMethod = (object, key) => Object.prototype.hasOwnProperty.call(object, key) ? { value: object[key] } : null;
31
+ const restoreMethod = (object, key, saved) => {
32
+ if (saved)
33
+ object[key] = saved.value;
34
+ else
35
+ delete object[key];
36
+ };
37
+ /**
38
+ * The breakpoints of one VM. Every caller gets the same instance, so the menu and the runtime
39
+ * agree on what is marked.
40
+ * @param {object} vm The VM.
41
+ * @returns {object} The breakpoints.
42
+ */
43
+ export function getBreakpoints(vm) {
44
+ let breakpoints = breakpointsByVm.get(vm);
45
+ if (!breakpoints) {
46
+ breakpoints = createBreakpoints(vm);
47
+ breakpointsByVm.set(vm, breakpoints);
48
+ }
49
+ return breakpoints;
50
+ }
51
+ function createBreakpoints(vm) {
52
+ const runtime = vm.runtime;
53
+ const marks = new Map();
54
+ const listeners = new Set();
55
+ const gated = new WeakMap();
56
+ let installed = null;
57
+ const notify = () => {
58
+ for (const listener of [...listeners])
59
+ listener();
60
+ };
61
+ const marked = (blocks, blockId) => Boolean(blocks && blockId && marks.get(blocks)?.has(blockId));
62
+ const pause = (thread) => {
63
+ const block = runtime.getAddonBlock?.(pauseProcedure);
64
+ if (!block)
65
+ return false;
66
+ block.callback({}, { thread });
67
+ return thread.status === PROMISE_WAIT;
68
+ };
69
+ const gate = (blockFunction) => {
70
+ let wrapped = gated.get(blockFunction);
71
+ if (wrapped)
72
+ return wrapped;
73
+ wrapped = function (args, util) {
74
+ const thread = util?.thread;
75
+ if (thread && !thread.isCompiled && marked(thread.blockContainer, thread.peekStack())) {
76
+ const context = util.stackFrame;
77
+ if (context && !context[hitKey]) {
78
+ context[hitKey] = true;
79
+ if (pause(thread)) {
80
+ // The interpreter keeps the frame and runs the block again from its start
81
+ // when the thread runs again, as it does after a reporter it waited for.
82
+ thread.peekStackFrame().waitingReporter = true;
83
+ return undefined;
84
+ }
85
+ }
86
+ }
87
+ return blockFunction.call(this, args, util);
88
+ };
89
+ gated.set(blockFunction, wrapped);
90
+ return wrapped;
91
+ };
92
+ const withoutCompiler = (blocks, start) => {
93
+ const options = runtime.compilerOptions;
94
+ if (!options?.enabled || !blocks || !marks.get(blocks)?.size)
95
+ return start();
96
+ runtime.compilerOptions = { ...options, enabled: false };
97
+ try {
98
+ return start();
99
+ }
100
+ finally {
101
+ runtime.compilerOptions = options;
102
+ }
103
+ };
104
+ const install = () => {
105
+ if (installed)
106
+ return;
107
+ const saved = {
108
+ getOpcodeFunction: ownMethod(runtime, 'getOpcodeFunction'),
109
+ _pushThread: ownMethod(runtime, '_pushThread'),
110
+ _restartThread: ownMethod(runtime, '_restartThread')
111
+ };
112
+ const getOpcodeFunction = runtime.getOpcodeFunction;
113
+ const pushThread = runtime._pushThread;
114
+ const restartThread = runtime._restartThread;
115
+ runtime.getOpcodeFunction = function (opcode) {
116
+ const blockFunction = getOpcodeFunction.call(this, opcode);
117
+ return typeof blockFunction === 'function' ? gate(blockFunction) : blockFunction;
118
+ };
119
+ runtime._pushThread = function (id, target, options) {
120
+ return withoutCompiler(target?.blocks, () => pushThread.call(this, id, target, options));
121
+ };
122
+ runtime._restartThread = function (thread) {
123
+ return withoutCompiler(thread?.blockContainer, () => restartThread.call(this, thread));
124
+ };
125
+ // The interpreter caches each block's function. Dropping the caches makes it look them up again.
126
+ runtime.resetAllCaches?.();
127
+ installed = () => {
128
+ restoreMethod(runtime, 'getOpcodeFunction', saved.getOpcodeFunction);
129
+ restoreMethod(runtime, '_pushThread', saved._pushThread);
130
+ restoreMethod(runtime, '_restartThread', saved._restartThread);
131
+ runtime.resetAllCaches?.();
132
+ };
133
+ };
134
+ const uninstall = () => {
135
+ const restore = installed;
136
+ installed = null;
137
+ restore?.();
138
+ };
139
+ const update = () => {
140
+ for (const [blocks, ids] of marks) {
141
+ if (!ids.size)
142
+ marks.delete(blocks);
143
+ }
144
+ if (marks.size)
145
+ install();
146
+ else
147
+ uninstall();
148
+ notify();
149
+ };
150
+ const clear = () => {
151
+ if (!marks.size)
152
+ return;
153
+ marks.clear();
154
+ update();
155
+ };
156
+ // A project load replaces every block container, so the marks have nothing left to point at.
157
+ runtime.on?.('RUNTIME_DISPOSED', clear);
158
+ const breakpoints = {
159
+ canPause: () => Boolean(runtime.getAddonBlock?.(pauseProcedure)),
160
+ has: (blocks, blockId) => marked(blocks, blockId),
161
+ set(blocks, blockId, on) {
162
+ if (marked(blocks, blockId) === on)
163
+ return;
164
+ if (on) {
165
+ let ids = marks.get(blocks);
166
+ if (!ids)
167
+ marks.set(blocks, ids = new Set());
168
+ ids.add(blockId);
169
+ }
170
+ else {
171
+ marks.get(blocks)?.delete(blockId);
172
+ }
173
+ update();
174
+ },
175
+ toggle(blocks, blockId) {
176
+ const on = !marked(blocks, blockId);
177
+ breakpoints.set(blocks, blockId, on);
178
+ return on;
179
+ },
180
+ ids(blocks) {
181
+ const ids = marks.get(blocks);
182
+ if (!ids)
183
+ return [];
184
+ return [...ids].filter(id => blocks.getBlock?.(id));
185
+ },
186
+ runsCompiled: blocks => runtime.threads.some(thread => thread.isCompiled && thread.blockContainer === blocks),
187
+ clear,
188
+ subscribe(listener) {
189
+ listeners.add(listener);
190
+ return () => listeners.delete(listener);
191
+ }
192
+ };
193
+ return breakpoints;
194
+ }
195
+ const japanese = (locale) => /^ja(?:-|$)/i.test(locale || '');
196
+ export const breakpointMenuText = (locale, marked, runsCompiled) => {
197
+ if (japanese(locale)) {
198
+ if (marked)
199
+ return 'ブレークポイントを外す';
200
+ return runsCompiled ? 'ブレークポイントを設定(次に始めたときから止まる)' : 'ブレークポイントを設定';
201
+ }
202
+ if (marked)
203
+ return 'Remove breakpoint';
204
+ return runsCompiled ? 'Add breakpoint (stops from the next start)' : 'Add breakpoint';
205
+ };
206
+ /**
207
+ * Offer "Add breakpoint" on the context menu of a command block in the code area, and outline the
208
+ * marked blocks of the sprite being edited.
209
+ * @param {object} options The VM, a way to get ScratchBlocks, and the GUI's language.
210
+ * @returns {object} Something to dispose.
211
+ */
212
+ export function attachBreakpointMenu(options) {
213
+ const vm = options.vm;
214
+ // Without a runtime there is nothing to pause.
215
+ if (!vm?.runtime)
216
+ return { dispose() { } };
217
+ const breakpoints = getBreakpoints(vm);
218
+ let disposed = false;
219
+ let detach = () => { };
220
+ const editingBlocks = () => vm.editingTarget?.blocks;
221
+ const connect = (ScratchBlocks) => {
222
+ const workspace = () => ScratchBlocks.getMainWorkspace?.() || ScratchBlocks.mainWorkspace || null;
223
+ const menu = ScratchBlocks.ContextMenu;
224
+ const show = menu.show;
225
+ let active = true;
226
+ const patched = function (event, items, rtl) {
227
+ const main = workspace();
228
+ const gesture = main?.currentGesture_;
229
+ const block = gesture && !gesture.flyout_ ? gesture.targetBlock_ : null;
230
+ const blocks = editingBlocks();
231
+ if (active && block && blocks && block.previousConnection && !block.isShadow?.() &&
232
+ block.workspace === main && breakpoints.canPause()) {
233
+ const on = breakpoints.has(blocks, block.id);
234
+ items = [...items, {
235
+ text: breakpointMenuText(options.getLocale?.(), on, !on && breakpoints.runsCompiled(blocks)),
236
+ enabled: true,
237
+ separator: true,
238
+ callback: () => breakpoints.toggle(blocks, block.id)
239
+ }];
240
+ }
241
+ return show.call(this, event, items, rtl);
242
+ };
243
+ menu.show = patched;
244
+ let frame = 0;
245
+ const refresh = () => {
246
+ frame = 0;
247
+ const main = workspace();
248
+ const root = main?.getParentSvg?.();
249
+ if (!main || !root)
250
+ return;
251
+ for (const element of root.querySelectorAll(`.${breakpointClass}`))
252
+ element.classList.remove(breakpointClass);
253
+ for (const dot of root.querySelectorAll(`.${breakpointDotClass}`))
254
+ dot.remove();
255
+ const blocks = editingBlocks();
256
+ if (!blocks)
257
+ return;
258
+ for (const id of breakpoints.ids(blocks)) {
259
+ const element = main.getBlockById(id)?.getSvgRoot?.();
260
+ if (!element)
261
+ continue;
262
+ element.classList.add(breakpointClass);
263
+ // A dot left of the block, like the gutter mark of a code editor. The outline alone is
264
+ // hard to see on the orange and yellow categories.
265
+ const dot = element.ownerDocument.createElementNS(svgNamespace, 'circle');
266
+ dot.setAttribute('class', breakpointDotClass);
267
+ dot.setAttribute('cx', '-9');
268
+ dot.setAttribute('cy', '12');
269
+ dot.setAttribute('r', '6');
270
+ element.append(dot);
271
+ }
272
+ };
273
+ const schedule = () => {
274
+ if (frame)
275
+ return;
276
+ const view = globalThis.requestAnimationFrame ? globalThis : null;
277
+ frame = view ? view.requestAnimationFrame(refresh) : setTimeout(refresh, 0);
278
+ };
279
+ const unsubscribe = breakpoints.subscribe(schedule);
280
+ const main = workspace();
281
+ const changeListener = main?.addChangeListener?.(schedule);
282
+ // Switching sprites reloads the workspace, and the new block elements have no outline yet.
283
+ vm.on?.('workspaceUpdate', schedule);
284
+ schedule();
285
+ detach = () => {
286
+ // Another patch may have wrapped ours since. Then ours stays in the chain and passes everything through.
287
+ active = false;
288
+ if (menu.show === patched)
289
+ menu.show = show;
290
+ unsubscribe();
291
+ if (changeListener)
292
+ main?.removeChangeListener?.(changeListener);
293
+ vm.off?.('workspaceUpdate', schedule);
294
+ if (frame && globalThis.cancelAnimationFrame)
295
+ globalThis.cancelAnimationFrame(frame);
296
+ };
297
+ };
298
+ Promise.resolve().then(() => options.getBlockly?.()).then(ScratchBlocks => {
299
+ if (!disposed && ScratchBlocks?.ContextMenu)
300
+ connect(ScratchBlocks);
301
+ }, () => {
302
+ // Without ScratchBlocks there is no code area to mark blocks in.
303
+ });
304
+ return {
305
+ dispose() {
306
+ disposed = true;
307
+ detach();
308
+ }
309
+ };
310
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/turbowarp-plus-editor-workbench",
3
- "version": "0.16.0",
3
+ "version": "0.17.0",
4
4
  "description": "The TurboWarp Plus Editor workbench: layout, dockable sprite tabs, stage, debugger tab and file menu",
5
5
  "type": "module",
6
6
  "license": "MPL-2.0",
@@ -30,6 +30,10 @@
30
30
  "default": "./dist/debugger-panel.js"
31
31
  },
32
32
  "./debugger-panel.css": "./src/debugger-panel.css",
33
+ "./debugger-breakpoints": {
34
+ "types": "./dist/debugger-breakpoints.d.ts",
35
+ "default": "./dist/debugger-breakpoints.js"
36
+ },
33
37
  "./dockview-styles": "./dist/dockview-styles.js",
34
38
  "./edit-menu": {
35
39
  "types": "./dist/edit-menu.d.ts",
@@ -117,7 +121,7 @@
117
121
  "test:browser": "npm run build && node --test test/*.browser.ts"
118
122
  },
119
123
  "devDependencies": {
120
- "@kubohiroya/turbowarp-plus-editor-git": "0.21.0",
124
+ "@kubohiroya/turbowarp-plus-editor-git": "0.22.0",
121
125
  "@kubohiroya/turbowarp-plus-editor-windows": "0.2.0",
122
126
  "@playwright/test": "1.64.1",
123
127
  "@types/react": "18.3.31",
@@ -139,7 +143,7 @@
139
143
  "dockview": "8.8.3"
140
144
  },
141
145
  "peerDependencies": {
142
- "@kubohiroya/turbowarp-plus-editor-git": ">=0.21.0 <0.22.0",
146
+ "@kubohiroya/turbowarp-plus-editor-git": ">=0.21.0 <0.23.0",
143
147
  "@kubohiroya/turbowarp-plus-editor-windows": ">=0.2.0 <0.3.0",
144
148
  "react": ">=16.14",
145
149
  "react-dom": ">=16.14"
@@ -0,0 +1,413 @@
1
+ /**
2
+ * Breakpoints marked on blocks instead of placed as blocks.
3
+ *
4
+ * The editor add-on's debugger stops a project when a "breakpoint" block runs. That block is part
5
+ * of the project, so it is saved and shipped unless someone remembers to take it out. Here a block
6
+ * is only marked in the editor: the mark lives in this session, never in the project, and the
7
+ * project stops right before a marked block runs.
8
+ *
9
+ * Stopping is the add-on's own pause (its hidden `sa-pause` block), so its Threads tab, Step and
10
+ * Continue work unchanged. Without the add-on nothing can pause, and no menu item is offered.
11
+ *
12
+ * The VM is not changed. Two of its methods are wrapped, and only while at least one mark exists:
13
+ *
14
+ * - `getOpcodeFunction`: the block functions the interpreter caches. When a thread arrives at a
15
+ * marked block, the first function the block runs pauses instead, and the frame waits the way it
16
+ * waits for a reporter. Continuing runs the block from its start. The mark is kept in the
17
+ * frame's execution context, which the VM clears when the thread moves to another block, so a
18
+ * block that waits in place or a loop that comes back to its head stops only on arrival.
19
+ * - `_pushThread` and `_restartThread`: compiled scripts run no per-block functions, so a script
20
+ * that starts in a sprite with a mark is not compiled. Sprites without a mark compile as before.
21
+ * A script that was already running compiled keeps running until it starts again.
22
+ */
23
+
24
+ const PROMISE_WAIT = 1;
25
+ const pauseProcedure = 'sa-pause';
26
+ const hitKey = Symbol('tw-plus-breakpoint-hit');
27
+
28
+ export const breakpointClass = 'tw-plus-breakpoint';
29
+ export const breakpointDotClass = 'tw-plus-breakpoint-dot';
30
+ const svgNamespace = 'http://www.w3.org/2000/svg';
31
+
32
+ type BlockFunction = (args: unknown, util: BlockUtilityLike) => unknown;
33
+
34
+ interface StackFrameLike {
35
+ waitingReporter: boolean | null;
36
+ }
37
+
38
+ interface ThreadLike {
39
+ status: number;
40
+ isCompiled?: boolean;
41
+ topBlock?: string;
42
+ target?: TargetLike | null;
43
+ blockContainer?: object;
44
+ peekStack(): string | undefined;
45
+ peekStackFrame(): StackFrameLike | null;
46
+ }
47
+
48
+ interface BlockUtilityLike {
49
+ thread?: ThreadLike;
50
+ readonly stackFrame?: Record<PropertyKey, unknown>;
51
+ }
52
+
53
+ interface BlocksLike {
54
+ getBlock(id: string): {topLevel?: boolean; opcode?: string} | undefined;
55
+ }
56
+
57
+ interface TargetLike {
58
+ blocks: BlocksLike;
59
+ }
60
+
61
+ interface CompilerOptions {
62
+ enabled?: boolean;
63
+ }
64
+
65
+ interface RuntimeLike {
66
+ threads: ThreadLike[];
67
+ compilerOptions?: CompilerOptions;
68
+ getOpcodeFunction(opcode: string): BlockFunction | undefined;
69
+ getAddonBlock?(procedureCode: string): {callback(args: object, util: {thread: ThreadLike}): unknown} | undefined;
70
+ resetAllCaches?(): void;
71
+ _pushThread(id: string, target: TargetLike, options?: object): ThreadLike;
72
+ _restartThread(thread: ThreadLike): ThreadLike;
73
+ on?(event: string, listener: () => void): void;
74
+ off?(event: string, listener: () => void): void;
75
+ }
76
+
77
+ interface VirtualMachineLike {
78
+ runtime: RuntimeLike;
79
+ editingTarget?: TargetLike | null;
80
+ on?(event: string, listener: () => void): void;
81
+ off?(event: string, listener: () => void): void;
82
+ }
83
+
84
+ export interface Breakpoints {
85
+ /** Whether a pause is possible: the debugger add-on is on and has registered its pause. */
86
+ canPause(): boolean;
87
+ has(blocks: object, blockId: string): boolean;
88
+ set(blocks: object, blockId: string, marked: boolean): void;
89
+ toggle(blocks: object, blockId: string): boolean;
90
+ /** The marked blocks of one block container that still exist. */
91
+ ids(blocks: object): string[];
92
+ /** Whether a script in this container is running compiled, so a new mark misses it until it starts again. */
93
+ runsCompiled(blocks: object): boolean;
94
+ clear(): void;
95
+ subscribe(listener: () => void): () => void;
96
+ }
97
+
98
+ const breakpointsByVm = new WeakMap<object, Breakpoints>();
99
+
100
+ const ownMethod = (object: object, key: string) =>
101
+ Object.prototype.hasOwnProperty.call(object, key) ? {value: object[key]} : null;
102
+
103
+ const restoreMethod = (object: object, key: string, saved: {value: unknown} | null) => {
104
+ if (saved) object[key] = saved.value;
105
+ else delete object[key];
106
+ };
107
+
108
+ /**
109
+ * The breakpoints of one VM. Every caller gets the same instance, so the menu and the runtime
110
+ * agree on what is marked.
111
+ * @param {object} vm The VM.
112
+ * @returns {object} The breakpoints.
113
+ */
114
+ export function getBreakpoints (vm: object): Breakpoints {
115
+ let breakpoints = breakpointsByVm.get(vm);
116
+ if (!breakpoints) {
117
+ breakpoints = createBreakpoints(vm as VirtualMachineLike);
118
+ breakpointsByVm.set(vm, breakpoints);
119
+ }
120
+ return breakpoints;
121
+ }
122
+
123
+ function createBreakpoints (vm: VirtualMachineLike): Breakpoints {
124
+ const runtime = vm.runtime;
125
+ const marks = new Map<object, Set<string>>();
126
+ const listeners = new Set<() => void>();
127
+ const gated = new WeakMap<BlockFunction, BlockFunction>();
128
+ let installed: null | (() => void) = null;
129
+
130
+ const notify = () => {
131
+ for (const listener of [...listeners]) listener();
132
+ };
133
+
134
+ const marked = (blocks: object | undefined, blockId: string | undefined) =>
135
+ Boolean(blocks && blockId && marks.get(blocks)?.has(blockId));
136
+
137
+ const pause = (thread: ThreadLike) => {
138
+ const block = runtime.getAddonBlock?.(pauseProcedure);
139
+ if (!block) return false;
140
+ block.callback({}, {thread});
141
+ return thread.status === PROMISE_WAIT;
142
+ };
143
+
144
+ const gate = (blockFunction: BlockFunction): BlockFunction => {
145
+ let wrapped = gated.get(blockFunction);
146
+ if (wrapped) return wrapped;
147
+ wrapped = function (this: unknown, args: unknown, util: BlockUtilityLike) {
148
+ const thread = util?.thread;
149
+ if (thread && !thread.isCompiled && marked(thread.blockContainer, thread.peekStack())) {
150
+ const context = util.stackFrame;
151
+ if (context && !context[hitKey]) {
152
+ context[hitKey] = true;
153
+ if (pause(thread)) {
154
+ // The interpreter keeps the frame and runs the block again from its start
155
+ // when the thread runs again, as it does after a reporter it waited for.
156
+ thread.peekStackFrame().waitingReporter = true;
157
+ return undefined;
158
+ }
159
+ }
160
+ }
161
+ return blockFunction.call(this, args, util);
162
+ };
163
+ gated.set(blockFunction, wrapped);
164
+ return wrapped;
165
+ };
166
+
167
+ const withoutCompiler = <T>(blocks: object | undefined, start: () => T): T => {
168
+ const options = runtime.compilerOptions;
169
+ if (!options?.enabled || !blocks || !marks.get(blocks)?.size) return start();
170
+ runtime.compilerOptions = {...options, enabled: false};
171
+ try {
172
+ return start();
173
+ } finally {
174
+ runtime.compilerOptions = options;
175
+ }
176
+ };
177
+
178
+ const install = () => {
179
+ if (installed) return;
180
+ const saved = {
181
+ getOpcodeFunction: ownMethod(runtime, 'getOpcodeFunction'),
182
+ _pushThread: ownMethod(runtime, '_pushThread'),
183
+ _restartThread: ownMethod(runtime, '_restartThread')
184
+ };
185
+ const getOpcodeFunction = runtime.getOpcodeFunction;
186
+ const pushThread = runtime._pushThread;
187
+ const restartThread = runtime._restartThread;
188
+ runtime.getOpcodeFunction = function (opcode) {
189
+ const blockFunction = getOpcodeFunction.call(this, opcode);
190
+ return typeof blockFunction === 'function' ? gate(blockFunction) : blockFunction;
191
+ };
192
+ runtime._pushThread = function (id, target, options) {
193
+ return withoutCompiler(target?.blocks, () => pushThread.call(this, id, target, options));
194
+ };
195
+ runtime._restartThread = function (thread) {
196
+ return withoutCompiler(thread?.blockContainer, () => restartThread.call(this, thread));
197
+ };
198
+ // The interpreter caches each block's function. Dropping the caches makes it look them up again.
199
+ runtime.resetAllCaches?.();
200
+ installed = () => {
201
+ restoreMethod(runtime, 'getOpcodeFunction', saved.getOpcodeFunction);
202
+ restoreMethod(runtime, '_pushThread', saved._pushThread);
203
+ restoreMethod(runtime, '_restartThread', saved._restartThread);
204
+ runtime.resetAllCaches?.();
205
+ };
206
+ };
207
+
208
+ const uninstall = () => {
209
+ const restore = installed;
210
+ installed = null;
211
+ restore?.();
212
+ };
213
+
214
+ const update = () => {
215
+ for (const [blocks, ids] of marks) {
216
+ if (!ids.size) marks.delete(blocks);
217
+ }
218
+ if (marks.size) install();
219
+ else uninstall();
220
+ notify();
221
+ };
222
+
223
+ const clear = () => {
224
+ if (!marks.size) return;
225
+ marks.clear();
226
+ update();
227
+ };
228
+
229
+ // A project load replaces every block container, so the marks have nothing left to point at.
230
+ runtime.on?.('RUNTIME_DISPOSED', clear);
231
+
232
+ const breakpoints: Breakpoints = {
233
+ canPause: () => Boolean(runtime.getAddonBlock?.(pauseProcedure)),
234
+ has: (blocks, blockId) => marked(blocks, blockId),
235
+ set (blocks, blockId, on) {
236
+ if (marked(blocks, blockId) === on) return;
237
+ if (on) {
238
+ let ids = marks.get(blocks);
239
+ if (!ids) marks.set(blocks, ids = new Set());
240
+ ids.add(blockId);
241
+ } else {
242
+ marks.get(blocks)?.delete(blockId);
243
+ }
244
+ update();
245
+ },
246
+ toggle (blocks, blockId) {
247
+ const on = !marked(blocks, blockId);
248
+ breakpoints.set(blocks, blockId, on);
249
+ return on;
250
+ },
251
+ ids (blocks) {
252
+ const ids = marks.get(blocks);
253
+ if (!ids) return [];
254
+ return [...ids].filter(id => (blocks as BlocksLike).getBlock?.(id));
255
+ },
256
+ runsCompiled: blocks => runtime.threads.some(thread => thread.isCompiled && thread.blockContainer === blocks),
257
+ clear,
258
+ subscribe (listener) {
259
+ listeners.add(listener);
260
+ return () => listeners.delete(listener);
261
+ }
262
+ };
263
+ return breakpoints;
264
+ }
265
+
266
+ interface ScratchBlocksLike {
267
+ ContextMenu: {show(event: unknown, items: MenuItem[], rtl: boolean): void};
268
+ getMainWorkspace?(): WorkspaceLike | null;
269
+ mainWorkspace?: WorkspaceLike | null;
270
+ }
271
+
272
+ interface MenuItem {
273
+ text: string;
274
+ enabled: boolean;
275
+ callback(): void;
276
+ separator?: boolean;
277
+ }
278
+
279
+ interface BlockSvgLike {
280
+ id: string;
281
+ isShadow?(): boolean;
282
+ previousConnection?: unknown;
283
+ workspace?: WorkspaceLike;
284
+ getSvgRoot?(): Element | null;
285
+ }
286
+
287
+ interface WorkspaceLike {
288
+ isFlyout?: boolean;
289
+ currentGesture_?: {targetBlock_?: BlockSvgLike | null; flyout_?: unknown} | null;
290
+ getBlockById(id: string): BlockSvgLike | null;
291
+ getParentSvg?(): Element | null;
292
+ addChangeListener?(listener: (event: unknown) => void): unknown;
293
+ removeChangeListener?(listener: unknown): void;
294
+ }
295
+
296
+ interface BreakpointMenuOptions {
297
+ vm: object;
298
+ getBlockly(): Promise<ScratchBlocksLike> | ScratchBlocksLike;
299
+ getLocale?(): string | undefined;
300
+ }
301
+
302
+ const japanese = (locale: string | undefined) => /^ja(?:-|$)/i.test(locale || '');
303
+
304
+ export const breakpointMenuText = (locale: string | undefined, marked: boolean, runsCompiled: boolean) => {
305
+ if (japanese(locale)) {
306
+ if (marked) return 'ブレークポイントを外す';
307
+ return runsCompiled ? 'ブレークポイントを設定(次に始めたときから止まる)' : 'ブレークポイントを設定';
308
+ }
309
+ if (marked) return 'Remove breakpoint';
310
+ return runsCompiled ? 'Add breakpoint (stops from the next start)' : 'Add breakpoint';
311
+ };
312
+
313
+ /**
314
+ * Offer "Add breakpoint" on the context menu of a command block in the code area, and outline the
315
+ * marked blocks of the sprite being edited.
316
+ * @param {object} options The VM, a way to get ScratchBlocks, and the GUI's language.
317
+ * @returns {object} Something to dispose.
318
+ */
319
+ export function attachBreakpointMenu (options: BreakpointMenuOptions) {
320
+ const vm = options.vm as VirtualMachineLike;
321
+ // Without a runtime there is nothing to pause.
322
+ if (!vm?.runtime) return {dispose () {}};
323
+ const breakpoints = getBreakpoints(vm);
324
+ let disposed = false;
325
+ let detach = () => {};
326
+
327
+ const editingBlocks = () => vm.editingTarget?.blocks as object | undefined;
328
+
329
+ const connect = (ScratchBlocks: ScratchBlocksLike) => {
330
+ const workspace = () => ScratchBlocks.getMainWorkspace?.() || ScratchBlocks.mainWorkspace || null;
331
+ const menu = ScratchBlocks.ContextMenu;
332
+ const show = menu.show;
333
+ let active = true;
334
+ const patched = function (event, items, rtl) {
335
+ const main = workspace();
336
+ const gesture = main?.currentGesture_;
337
+ const block = gesture && !gesture.flyout_ ? gesture.targetBlock_ : null;
338
+ const blocks = editingBlocks();
339
+ if (active && block && blocks && block.previousConnection && !block.isShadow?.() &&
340
+ block.workspace === main && breakpoints.canPause()) {
341
+ const on = breakpoints.has(blocks, block.id);
342
+ items = [...items, {
343
+ text: breakpointMenuText(options.getLocale?.(), on, !on && breakpoints.runsCompiled(blocks)),
344
+ enabled: true,
345
+ separator: true,
346
+ callback: () => breakpoints.toggle(blocks, block.id)
347
+ }];
348
+ }
349
+ return show.call(this, event, items, rtl);
350
+ };
351
+ menu.show = patched;
352
+
353
+ let frame = 0;
354
+ const refresh = () => {
355
+ frame = 0;
356
+ const main = workspace();
357
+ const root = main?.getParentSvg?.();
358
+ if (!main || !root) return;
359
+ for (const element of root.querySelectorAll(`.${breakpointClass}`)) element.classList.remove(breakpointClass);
360
+ for (const dot of root.querySelectorAll(`.${breakpointDotClass}`)) dot.remove();
361
+ const blocks = editingBlocks();
362
+ if (!blocks) return;
363
+ for (const id of breakpoints.ids(blocks)) {
364
+ const element = main.getBlockById(id)?.getSvgRoot?.();
365
+ if (!element) continue;
366
+ element.classList.add(breakpointClass);
367
+ // A dot left of the block, like the gutter mark of a code editor. The outline alone is
368
+ // hard to see on the orange and yellow categories.
369
+ const dot = element.ownerDocument.createElementNS(svgNamespace, 'circle');
370
+ dot.setAttribute('class', breakpointDotClass);
371
+ dot.setAttribute('cx', '-9');
372
+ dot.setAttribute('cy', '12');
373
+ dot.setAttribute('r', '6');
374
+ element.append(dot);
375
+ }
376
+ };
377
+ const schedule = () => {
378
+ if (frame) return;
379
+ const view = globalThis.requestAnimationFrame ? globalThis : null;
380
+ frame = view ? view.requestAnimationFrame(refresh) : (setTimeout(refresh, 0) as unknown as number);
381
+ };
382
+
383
+ const unsubscribe = breakpoints.subscribe(schedule);
384
+ const main = workspace();
385
+ const changeListener = main?.addChangeListener?.(schedule);
386
+ // Switching sprites reloads the workspace, and the new block elements have no outline yet.
387
+ vm.on?.('workspaceUpdate', schedule);
388
+ schedule();
389
+
390
+ detach = () => {
391
+ // Another patch may have wrapped ours since. Then ours stays in the chain and passes everything through.
392
+ active = false;
393
+ if (menu.show === patched) menu.show = show;
394
+ unsubscribe();
395
+ if (changeListener) main?.removeChangeListener?.(changeListener);
396
+ vm.off?.('workspaceUpdate', schedule);
397
+ if (frame && globalThis.cancelAnimationFrame) globalThis.cancelAnimationFrame(frame);
398
+ };
399
+ };
400
+
401
+ Promise.resolve().then(() => options.getBlockly?.()).then(ScratchBlocks => {
402
+ if (!disposed && ScratchBlocks?.ContextMenu) connect(ScratchBlocks);
403
+ }, () => {
404
+ // Without ScratchBlocks there is no code area to mark blocks in.
405
+ });
406
+
407
+ return {
408
+ dispose () {
409
+ disposed = true;
410
+ detach();
411
+ }
412
+ };
413
+ }
@@ -129,3 +129,16 @@ html body .tw-plus-debugger-docked .sa-debugger-tabs li:not(.sa-debugger-tab-sel
129
129
  html body .tw-plus-debugger-docked [class*="modal_header-item-close"] {
130
130
  display: none;
131
131
  }
132
+
133
+ /* A block marked with a breakpoint (debugger-breakpoints.ts): a red outline, and a red dot on its left. */
134
+ html body .tw-plus-breakpoint > path.blocklyBlockBackground {
135
+ stroke: #e5484d;
136
+ stroke-width: 3px;
137
+ }
138
+
139
+ html body .tw-plus-breakpoint-dot {
140
+ fill: #e5484d;
141
+ stroke: #fff;
142
+ stroke-width: 2px;
143
+ pointer-events: none;
144
+ }