Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

fix(canvas): give gestures and session keys an explicit owner

Josh Corbett9fa1b363b5c6
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/interactionController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/interactionController.test.ts
index 7aae8c4d48..de51c01a45 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/interactionController.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/interactionController.test.ts
@@ -11,11 +11,15 @@ const createHarness = () => {
const publishActiveTool = vi.fn();
const updateCursor = vi.fn();
const invalidateOverlay = vi.fn();
- const beforeSwitch = vi.fn();
+ const order: string[] = [];
+ const beforeSwitch = vi.fn(() => order.push('beforeSwitch'));
+ const cancelGesture = vi.fn(() => order.push('cancelGesture'));
+ vi.mocked(view.onDeactivate!).mockImplementation(() => order.push('view:deactivate'));
const stepBrushSize = vi.fn();
let locked = false;
const controller = new InteractionController({
beforeSwitch,
+ cancelGesture,
getTool: (id) => tools[id as keyof typeof tools],
getToolContext: () => ({}) as never,
invalidateOverlay,
@@ -27,6 +31,8 @@ const createHarness = () => {
return {
beforeSwitch,
brush,
+ cancelGesture,
+ order,
controller,
invalidateOverlay,
lock: () => (locked = true),
@@ -51,6 +57,17 @@ describe('InteractionController', () => {
expect(h.invalidateOverlay).toHaveBeenCalledOnce();
});
+ it('cancels an in-flight gesture through the outgoing tool before a genuine switch only', () => {
+ const h = createHarness();
+ h.controller.setTool('brush', { temporary: true });
+ expect(h.cancelGesture).not.toHaveBeenCalled();
+
+ h.controller.setTool('view');
+ h.order.length = 0;
+ h.controller.setTool('brush');
+ expect(h.order).toEqual(['cancelGesture', 'beforeSwitch', 'view:deactivate']);
+ });
+
it('blocks non-view transitions while locked and ignores commands after disposal', () => {
const h = createHarness();
h.lock();
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/interactionController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/interactionController.ts
index 25eba1292c..a54112319e 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/interactionController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/interactionController.ts
@@ -7,6 +7,8 @@ export interface InteractionControllerOptions {
readonly getTool: (toolId: ToolId) => Tool | undefined;
readonly getToolContext: () => ToolContext;
readonly isLocked: () => boolean;
+ /** Cancels an in-flight gesture through the still-active outgoing tool. */
+ readonly cancelGesture?: () => void;
readonly beforeSwitch?: (from: ToolId, to: ToolId, options?: { temporary?: boolean }) => void;
readonly publishActiveTool: (toolId: ToolId) => void;
readonly updateCursor: () => void;
@@ -44,6 +46,9 @@ export class InteractionController {
if (this.disposed || (this.options.isLocked() && toolId !== 'view') || toolId === this.activeToolId) {
return;
}
+ if (!switchOptions?.temporary) {
+ this.options.cancelGesture?.();
+ }
const previous = this.activeToolId;
this.options.beforeSwitch?.(previous, toolId, switchOptions);
this.options.getTool(previous)?.onDeactivate?.(this.options.getToolContext(), switchOptions);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
index 2d7bc24287..8507baa6d4 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
@@ -14385,6 +14385,12 @@ describe('brush cursor ring: live size updates', () => {
// The options-bar slider path (a direct store write) likewise invalidates.
engine.stores.brushOptions.set({ ...engine.stores.brushOptions.get(), size: 123 });
expect(raf.pendingCount()).toBeGreaterThan(0);
+ raf.flush();
+
+ // Non-size option edits and the inactive eraser's size leave the overlay alone.
+ engine.stores.brushOptions.set({ ...engine.stores.brushOptions.get(), color: '#123456', opacity: 0.4 });
+ engine.stores.eraserOptions.set({ ...engine.stores.eraserOptions.get(), size: 77 });
+ expect(raf.pendingCount()).toBe(0);
engine.lifecycle.dispose();
});
@@ -14508,6 +14514,55 @@ describe('doc-replace mid-gesture: cancels the active tool gesture', () => {
});
});
+describe('genuine tool switch mid-gesture', () => {
+ it('cancels the stroke through the outgoing brush and routes none of the drag tail to the new tool', () => {
+ const raf = createControllableRaf();
+ vi.stubGlobal('requestAnimationFrame', raf.requestFrame);
+ vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);
+ vi.stubGlobal(
+ 'Path2D',
+ class FakePath2D {
+ closePath() {}
+ lineTo() {}
+ moveTo() {}
+ quadraticCurveTo() {}
+ }
+ );
+
+ const { store } = createReactiveStore(paintDoc());
+ const dispatch = store.dispatch as Mock;
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ bitmapStore: createSpyBitmapStore(),
+ imageResolver: () => Promise.resolve(new Blob()),
+ projectId: 'p1',
+ store,
+ });
+ const strokes: StrokeCommittedEvent[] = [];
+ engine.tools.onStrokeCommitted((event) => strokes.push(event));
+ const overlay = createInputCanvas();
+ const screen = createInputCanvas();
+ engine.surface.attach(screen.element, overlay.element);
+ engine.tools.setTool('brush');
+
+ overlay.fire('pointerdown', pointerAt(20, 20));
+ overlay.fire('pointermove', pointerAt(40, 40));
+ engine.tools.setTool('move');
+
+ // The gesture ended with the brush: context menus and undo are no longer blocked by it.
+ expect(engine.tools.canTargetLayerFromContextMenu()).toBe(true);
+ const dispatchesAfterSwitch = dispatch.mock.calls.length;
+ overlay.fire('pointermove', pointerAt(80, 60));
+ overlay.fire('pointerup', pointerAt(80, 60, { buttons: 0 }));
+
+ expect(dispatch.mock.calls.length).toBe(dispatchesAfterSwitch);
+ expect(strokes).toEqual([]);
+ expect(engine.stores.canUndo.get()).toBe(false);
+
+ engine.lifecycle.dispose();
+ });
+});
+
// Overlay-only frames must skip document compositing, whose fill cost grows with zoom. Zoomed composites disable
// smoothing for crisp pixels without bilinear upscaling.
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index 0cbc9f9755..3b8640679f 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -1643,8 +1643,21 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
}
});
- const unsubscribeBrushOptions = stores.brushOptions.subscribe(refreshBrushCursorRadius);
- const unsubscribeEraserOptions = stores.eraserOptions.subscribe(refreshBrushCursorRadius);
+ // Only a diameter change moves the ring; other option edits (color, opacity) leave the overlay untouched.
+ const subscribeSizeChange = (store: ScalarStore<{ size: number }>, toolId: ToolId): (() => void) => {
+ let size = store.get().size;
+ return store.subscribe(() => {
+ const next = store.get().size;
+ if (next !== size) {
+ size = next;
+ if (interactionController.getActiveToolId() === toolId) {
+ refreshBrushCursorRadius();
+ }
+ }
+ });
+ };
+ const unsubscribeBrushOptions = subscribeSizeChange(stores.brushOptions, 'brush');
+ const unsubscribeEraserOptions = subscribeSizeChange(stores.eraserOptions, 'eraser');
const unsubscribeCheckerboard = stores.checkerboard.subscribe(() => scheduler.invalidate({ all: true }));
const unsubscribeCheckerColors = stores.checkerColors.subscribe(() => {
checkerboardTile = null;
@@ -1685,6 +1698,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
listener({ from, temporary: switchOptions?.temporary === true, to });
}
},
+ cancelGesture: () => pipeline.cancelGestureForToolSwitch(),
getTool: (toolId) => tools.get(toolId),
getToolContext: () => toolContext,
invalidateOverlay: () => scheduler.invalidate({ overlay: true }),
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.browser.test.ts
new file mode 100644
index 0000000000..e228d20566
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.browser.test.ts
@@ -0,0 +1,166 @@
+import type { Tool, ToolContext } from '@workbench/canvas-engine/tools/tool';
+import type { ToolId } from '@workbench/canvas-engine/types';
+
+import { InteractionController } from '@workbench/canvas-engine/controllers/interactionController';
+import { createPointerPipeline } from '@workbench/canvas-engine/input/pointerPipeline';
+import { createViewport } from '@workbench/canvas-engine/viewport';
+import { afterEach, describe, expect, it } from 'vitest';
+import { userEvent } from 'vitest/browser';
+
+const cleanups: (() => void)[] = [];
+
+afterEach(() => {
+ for (const cleanup of cleanups.splice(0).reverse()) {
+ cleanup();
+ }
+});
+
+/** The engine's input wiring over a real surface: focusable container, overlay canvas, window key listeners. */
+const createInputHarness = () => {
+ const surface = document.createElement('div');
+ surface.tabIndex = -1;
+ const canvas = document.createElement('canvas');
+ // Synthetic pointer ids are never active, so real capture would throw.
+ canvas.setPointerCapture = () => undefined;
+ canvas.releasePointerCapture = () => undefined;
+ surface.append(canvas);
+ const button = document.createElement('button');
+ button.textContent = 'Toolbar action';
+ let clicks = 0;
+ button.addEventListener('click', () => {
+ clicks += 1;
+ });
+ document.body.append(surface, button);
+
+ const events: string[] = [];
+ const tools = Object.fromEntries(
+ (['brush', 'view', 'transform'] as const).map((id): [ToolId, Tool] => [
+ id,
+ {
+ id,
+ onKeyCommand: (_ctx, command) => events.push(`${id}:${command}`),
+ onPointerCancel: () => events.push(`${id}:cancel`),
+ onPointerDown: () => events.push(`${id}:down`),
+ onPointerMove: () => events.push(`${id}:move`),
+ onPointerUp: () => events.push(`${id}:up`),
+ },
+ ])
+ ) as Record<string, Tool>;
+ const ctx = {} as ToolContext;
+ const interaction = new InteractionController({
+ cancelGesture: () => pipeline.cancelGestureForToolSwitch(),
+ getTool: (id) => tools[id],
+ getToolContext: () => ctx,
+ initialToolId: 'brush',
+ invalidateOverlay: () => undefined,
+ isLocked: () => false,
+ publishActiveTool: () => undefined,
+ stepBrushSize: () => undefined,
+ updateCursor: () => undefined,
+ });
+ const pipeline = createPointerPipeline({
+ getActiveTool: () => interaction.getActiveTool(),
+ getActiveToolId: () => interaction.getActiveToolId(),
+ getInputElement: () => canvas,
+ getToolContext: () => ctx,
+ hasTool: (id) => id in tools,
+ setTool: (id, options) => interaction.setTool(id, options),
+ updateCursor: () => undefined,
+ viewport: createViewport(),
+ });
+ // Registered after the pipeline's listener, so it reads the event after the pipeline handled it.
+ const observed: { type: string; defaultPrevented: boolean }[] = [];
+ const observe = (event: KeyboardEvent): void => {
+ observed.push({ defaultPrevented: event.defaultPrevented, type: event.type });
+ };
+ globalThis.addEventListener('keydown', pipeline.onKeyDown);
+ globalThis.addEventListener('keyup', pipeline.onKeyUp);
+ globalThis.addEventListener('keydown', observe);
+ globalThis.addEventListener('keyup', observe);
+ cleanups.push(() => {
+ globalThis.removeEventListener('keydown', pipeline.onKeyDown);
+ globalThis.removeEventListener('keyup', pipeline.onKeyUp);
+ globalThis.removeEventListener('keydown', observe);
+ globalThis.removeEventListener('keyup', observe);
+ pipeline.reset();
+ surface.remove();
+ button.remove();
+ });
+ const pointer = (type: string, buttons: number): PointerEvent =>
+ new PointerEvent(type, { bubbles: true, button: 0, buttons, pointerId: 1 });
+ return { button, canvas, clicks: () => clicks, events, interaction, observed, pipeline, pointer, surface };
+};
+
+describe('pointer pipeline in Chromium: keyboard ownership', () => {
+ it('leaves Enter and Space to a focused toolbar control', async () => {
+ const h = createInputHarness();
+ h.interaction.setTool('transform');
+ h.pipeline.onPointerEnter();
+ h.button.focus();
+
+ await userEvent.keyboard('{Enter}');
+ await userEvent.keyboard('{Control>}{Enter}{/Control}');
+ await userEvent.keyboard(' ');
+ expect(h.clicks()).toBe(2);
+ expect(h.events).toEqual([]);
+ expect(h.interaction.getActiveToolId()).toBe('transform');
+ expect(h.observed.filter((event) => event.defaultPrevented)).toEqual([]);
+ });
+
+ it('applies on Enter only when the focused surface owns an unmodified, unprevented key', async () => {
+ const h = createInputHarness();
+ h.interaction.setTool('transform');
+ h.surface.focus();
+
+ await userEvent.keyboard('{Control>}{Enter}{/Control}');
+ await userEvent.keyboard('{Shift>}{Enter}{/Shift}');
+ const prevented = new KeyboardEvent('keydown', { bubbles: true, cancelable: true, key: 'Enter' });
+ prevented.preventDefault();
+ h.surface.dispatchEvent(prevented);
+ expect(h.events).toEqual([]);
+
+ await userEvent.keyboard('{Enter}');
+ expect(h.events).toEqual(['transform:apply']);
+ });
+
+ it('restores a held tool when Space is released after focus moved, without consuming the release', async () => {
+ const h = createInputHarness();
+ h.pipeline.onPointerEnter();
+ h.surface.focus();
+
+ await userEvent.keyboard('{Space>}');
+ expect(h.interaction.getActiveToolId()).toBe('view');
+ h.pipeline.onPointerLeave();
+ h.button.focus();
+ await userEvent.keyboard('{/Space}');
+
+ expect(h.interaction.getActiveToolId()).toBe('brush');
+ expect(h.observed.at(-1)).toEqual({ defaultPrevented: false, type: 'keyup' });
+ expect(h.clicks()).toBe(0);
+ });
+});
+
+describe('pointer pipeline in Chromium: gesture ownership across tool switches', () => {
+ it('cancels a drag through the outgoing tool on a genuine switch and never routes its tail to the new tool', () => {
+ const h = createInputHarness();
+ h.pipeline.onPointerDown(h.pointer('pointerdown', 1));
+ h.interaction.setTool('transform');
+
+ expect(h.pipeline.isGestureActive()).toBe(false);
+ h.pipeline.onPointerMove(h.pointer('pointermove', 1));
+ h.pipeline.onPointerUp(h.pointer('pointerup', 0));
+ expect(h.events).toEqual(['brush:down', 'brush:cancel']);
+ });
+
+ it('reset cancels the temporary tool that owns the gesture, then restores the held tool', () => {
+ const h = createInputHarness();
+ h.pipeline.onPointerEnter();
+ h.surface.focus();
+ h.surface.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, cancelable: true, code: 'Space', key: ' ' }));
+ h.pipeline.onPointerDown(h.pointer('pointerdown', 1));
+
+ h.pipeline.reset();
+ expect(h.events).toEqual(['view:down', 'view:cancel']);
+ expect(h.interaction.getActiveToolId()).toBe('brush');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.test.ts
index 4d9c8f009f..d19401e087 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.test.ts
@@ -42,21 +42,34 @@ const makePointerEvent = (init: FakePointerInit = {}): PointerEvent => {
};
const makeKeyEvent = (init: {
+ altKey?: boolean;
code?: string;
+ ctrlKey?: boolean;
+ defaultPrevented?: boolean;
key?: string;
+ metaKey?: boolean;
repeat?: boolean;
shiftKey?: boolean;
target?: unknown;
}): KeyboardEvent =>
({
+ altKey: init.altKey ?? false,
code: init.code ?? '',
+ ctrlKey: init.ctrlKey ?? false,
+ defaultPrevented: init.defaultPrevented ?? false,
key: init.key ?? '',
+ metaKey: init.metaKey ?? false,
preventDefault: vi.fn(),
repeat: init.repeat ?? false,
shiftKey: init.shiftKey ?? false,
target: init.target ?? null,
}) as unknown as KeyboardEvent;
+/** A key target inside the canvas surface; the harness surface claims it through `contains`. */
+const SURFACE_TARGET = { tagName: 'DIV' };
+/** A focused toolbar button outside the surface; its `closest` resolves the interactive selector. */
+const BUTTON_TARGET = { closest: () => ({}), tagName: 'BUTTON' };
+
const createHarness = (
opts: {
tools?: ToolId[];
@@ -94,6 +107,7 @@ const createHarness = (
const releases: number[] = [];
const element = {
getBoundingClientRect: () => ({ left: 0, top: 0 }) as DOMRect,
+ parentElement: { contains: (node: unknown) => node === SURFACE_TARGET },
releasePointerCapture: (id: number) => releases.push(id),
setPointerCapture: (id: number) => captures.push(id),
} as unknown as HTMLElement;
@@ -509,8 +523,111 @@ describe('pointer pipeline: temporary modifier tools', () => {
h.pipeline.onKeyDown(makeKeyEvent({ code: 'AltLeft', target: { isContentEditable: true } }));
expect(h.setTool).not.toHaveBeenCalled();
- // A non-editable target (e.g. the canvas) still triggers the hold.
- h.pipeline.onKeyDown(makeKeyEvent({ code: 'Space', target: { tagName: 'CANVAS' } }));
+ // A non-editable target inside the surface still triggers the hold.
+ h.pipeline.onKeyDown(makeKeyEvent({ code: 'Space', target: SURFACE_TARGET }));
expect(h.setTool).toHaveBeenLastCalledWith('view', { temporary: true });
});
});
+
+describe('pointer pipeline: canvas keyboard ownership', () => {
+ const applyHarness = () => {
+ const h = createHarness();
+ const commands: string[] = [];
+ h.tool.onKeyCommand = (_ctx, command) => commands.push(command);
+ return { ...h, commands };
+ };
+
+ it('applies a session on Enter only while the surface (or no control) owns focus', () => {
+ const h = applyHarness();
+ h.pipeline.onKeyDown(makeKeyEvent({ key: 'Enter', target: SURFACE_TARGET }));
+ h.pipeline.onKeyDown(makeKeyEvent({ key: 'Enter', target: { tagName: 'BODY' } }));
+ expect(h.commands).toEqual(['apply', 'apply']);
+
+ h.pipeline.onKeyDown(makeKeyEvent({ key: 'Enter', target: BUTTON_TARGET }));
+ h.pipeline.onKeyDown(makeKeyEvent({ key: 'Enter', target: { tagName: 'DIV' } }));
+ h.pipeline.onKeyDown(makeKeyEvent({ defaultPrevented: true, key: 'Enter', target: SURFACE_TARGET }));
+ for (const modifier of ['altKey', 'ctrlKey', 'metaKey', 'shiftKey'] as const) {
+ h.pipeline.onKeyDown(makeKeyEvent({ key: 'Enter', [modifier]: true, target: SURFACE_TARGET }));
+ }
+ expect(h.commands).toEqual(['apply', 'apply']);
+ });
+
+ it('leaves Space to a focused control and to Ctrl/Meta/Alt chords', () => {
+ const h = createHarness();
+ h.pipeline.onPointerEnter();
+ const onButton = makeKeyEvent({ code: 'Space', key: ' ', target: BUTTON_TARGET });
+ h.pipeline.onKeyDown(onButton);
+ h.pipeline.onKeyDown(makeKeyEvent({ code: 'Space', ctrlKey: true, target: SURFACE_TARGET }));
+ h.pipeline.onKeyDown(makeKeyEvent({ code: 'Space', metaKey: true, target: SURFACE_TARGET }));
+ h.pipeline.onKeyDown(makeKeyEvent({ code: 'Space', defaultPrevented: true, target: SURFACE_TARGET }));
+ expect(h.setTool).not.toHaveBeenCalled();
+ expect(onButton.preventDefault).not.toHaveBeenCalled();
+
+ const owned = makeKeyEvent({ code: 'Space', key: ' ', shiftKey: true, target: SURFACE_TARGET });
+ h.pipeline.onKeyDown(owned);
+ expect(h.setTool).toHaveBeenLastCalledWith('view', { temporary: true });
+ expect(owned.preventDefault).toHaveBeenCalledOnce();
+ });
+
+ it('restores a held tool on a release observed after focus moved, without consuming the key', () => {
+ const h = createHarness();
+ h.pipeline.onPointerEnter();
+ h.pipeline.onKeyDown(makeKeyEvent({ code: 'Space', target: SURFACE_TARGET }));
+ h.pipeline.onPointerLeave();
+
+ const release = makeKeyEvent({ code: 'Space', key: ' ', target: BUTTON_TARGET });
+ h.pipeline.onKeyUp(release);
+ expect(h.setTool).toHaveBeenLastCalledWith('brush', { temporary: true });
+ expect(release.preventDefault).not.toHaveBeenCalled();
+ });
+});
+
+describe('pointer pipeline: cancellation ownership', () => {
+ it('a tool-switch cancel drops the rest of the pressed drag until the pointer is released', () => {
+ const h = createHarness();
+ h.pipeline.onPointerDown(makePointerEvent({ pointerId: 4 }));
+ h.pipeline.cancelGestureForToolSwitch();
+ expect(h.tool.cancels).toBe(1);
+ expect(h.releases).toEqual([4]);
+
+ h.pipeline.onPointerMove(makePointerEvent({ clientX: 5, pointerId: 4 }));
+ h.pipeline.onPointerUp(makePointerEvent({ buttons: 0, pointerId: 4 }));
+ expect(h.tool.moves).toHaveLength(0);
+ expect(h.tool.ups).toHaveLength(0);
+
+ // The released pointer hovers normally again.
+ h.pipeline.onPointerMove(makePointerEvent({ buttons: 0, clientX: 6, pointerId: 4 }));
+ expect(h.tool.moves).toHaveLength(1);
+ });
+
+ it('a tool-switch cancel drops, rather than restores, a hold released mid-gesture', () => {
+ const h = createHarness();
+ h.pipeline.onPointerEnter();
+ h.pipeline.onKeyDown(makeKeyEvent({ code: 'Space', target: SURFACE_TARGET }));
+ h.pipeline.onPointerDown(makePointerEvent({ pointerId: 2 }));
+ h.pipeline.onKeyUp(makeKeyEvent({ code: 'Space' }));
+ h.setTool.mockClear();
+
+ h.pipeline.cancelGestureForToolSwitch();
+ expect(h.tool.cancels).toBe(1);
+ expect(h.setTool).not.toHaveBeenCalled();
+ h.pipeline.onKeyUp(makeKeyEvent({ code: 'Space' }));
+ expect(h.setTool).not.toHaveBeenCalled();
+ });
+
+ it('reset cancels through the held temporary tool before restoring the prior tool', () => {
+ const h = createHarness();
+ const order: string[] = [];
+ h.tool.onPointerCancel = () => order.push(`cancel:${h.deps.getActiveToolId()}`);
+ h.pipeline.onPointerEnter();
+ h.pipeline.onKeyDown(makeKeyEvent({ code: 'Space', target: SURFACE_TARGET }));
+ h.pipeline.onPointerDown(makePointerEvent({ pointerId: 3 }));
+ h.setTool.mockImplementation((id: ToolId) => {
+ order.push(`set:${id}`);
+ });
+
+ h.pipeline.reset();
+ expect(order).toEqual(['cancel:view', 'set:brush']);
+ expect(h.pipeline.isGestureActive()).toBe(false);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.ts
index 90589e8438..2288db3414 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.ts
@@ -2,7 +2,8 @@
* Normalizes DOM events into tool input with capture, coalesced samples and default mouse pressure 0.5. Middle
* mouse pans independently. Space, Alt and held C temporarily select view, picker and bbox; release restores the
* tool, while quick C selects bbox persistently. Temporary switches preserve sessions and are blocked mid-gesture.
- * Escape/pointercancel cancel; extra buttons are ignored mid-gesture. DOM access is injected.
+ * Escape/pointercancel cancel; extra buttons are ignored mid-gesture. Enter and Space act only while the canvas
+ * surface owns the keyboard; key releases are always observed and never consumed. DOM access is injected.
*/
import type { Tool, ToolContext } from '@workbench/canvas-engine/tools/tool';
@@ -62,6 +63,11 @@ export interface PointerPipeline {
* commit stale drag state; idle calls do nothing.
*/
cancelActiveGesture(): void;
+ /**
+ * Cancels through the outgoing tool before a genuine tool switch. A hold whose key was released mid-gesture is
+ * dropped instead of restored, so the requested tool wins.
+ */
+ cancelGestureForToolSwitch(): void;
/** Replaces a matching tool id that a currently-held temporary tool would restore on release. */
replaceTemporaryRestoreTool(current: ToolId, replacement: ToolId): void;
/** Clears hover/gesture/temp-tool state, cancelling any in-flight gesture (called on detach/blur). */
@@ -88,6 +94,48 @@ const isEditableTarget = (target: EventTarget | null): boolean => {
return tagName === 'INPUT' || tagName === 'TEXTAREA' || el.isContentEditable === true;
};
+/** Controls whose own keyboard activation must win over canvas session keys. */
+const INTERACTIVE_SELECTOR = [
+ 'a[href]',
+ 'button',
+ 'input',
+ 'select',
+ 'summary',
+ 'textarea',
+ '[contenteditable]:not([contenteditable="false"])',
+ ...[
+ 'button',
+ 'checkbox',
+ 'combobox',
+ 'gridcell',
+ 'link',
+ 'menuitem',
+ 'menuitemcheckbox',
+ 'menuitemradio',
+ 'option',
+ 'radio',
+ 'slider',
+ 'spinbutton',
+ 'switch',
+ 'tab',
+ 'textbox',
+ 'treeitem',
+ ].map((role) => `[role="${role}"]`),
+].join(', ');
+
+type KeyTarget = { tagName?: unknown; closest?: (selector: string) => unknown } | null;
+
+const isInteractiveTarget = (target: EventTarget | null): boolean => {
+ const el = target as KeyTarget;
+ return isEditableTarget(target) || (typeof el?.closest === 'function' && el.closest(INTERACTIVE_SELECTOR) !== null);
+};
+
+/** A document root target means no control holds focus, so the canvas may take the key. */
+const isDocumentRootTarget = (target: EventTarget | null): boolean => {
+ const tagName = (target as KeyTarget)?.tagName;
+ return !target || tagName === 'BODY' || tagName === 'HTML';
+};
+
/** Creates a pointer pipeline bound to the engine's injected deps. */
export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipeline => {
let hovered = false;
@@ -104,6 +152,8 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelin
let restoreTempAfterGesture = false;
let bboxQuickTap = false;
let bboxTapTimer: ReturnType<typeof setTimeout> | null = null;
+ // A cancelled gesture's pointer keeps reporting pressed moves; none may reach a tool until it is released.
+ let cancelledPointerId: number | null = null;
/**
* Reads the input element's viewport offset. Hoisted out of
@@ -136,23 +186,39 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelin
return [buildPointerInput(event, origin)];
};
+ /** Session keys belong to the canvas only when focus is on its surface (or nowhere) and no control claims them. */
+ const ownsKeyboard = (event: KeyboardEvent): boolean => {
+ if (event.defaultPrevented || isInteractiveTarget(event.target)) {
+ return false;
+ }
+ const input = deps.getInputElement();
+ const surface = (input?.parentElement ?? input) as { contains?: (node: unknown) => boolean } | null;
+ return isDocumentRootTarget(event.target) || surface?.contains?.(event.target) === true;
+ };
+
const releaseCapture = (pointerId: number): void => {
deps.getInputElement()?.releasePointerCapture?.(pointerId);
};
- const cancelGesture = (): void => {
+ /** `restoreTemporary: false` lets a genuine tool switch win over a hold whose key was released mid-gesture. */
+ const cancelGesture = (restoreTemporary = true): void => {
if (!gestureActive) {
return;
}
gestureActive = false;
if (activePointerId !== null) {
releaseCapture(activePointerId);
+ cancelledPointerId = activePointerId;
activePointerId = null;
}
deps.getActiveTool()?.onPointerCancel?.(deps.getToolContext());
deps.updateCursor();
if (restoreTempAfterGesture && tempHold) {
- endTempTool();
+ if (restoreTemporary) {
+ endTempTool();
+ } else {
+ clearTempHold();
+ }
}
};
@@ -207,17 +273,22 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelin
}
};
- function endTempTool(): void {
+ function clearTempHold(): void {
clearBboxTapTimer();
- if (tempSwitched) {
- deps.setTool(priorToolId, { temporary: true });
- }
tempHold = null;
tempSwitched = false;
restoreTempAfterGesture = false;
bboxQuickTap = false;
}
+ function endTempTool(): void {
+ const restore = tempSwitched;
+ clearTempHold();
+ if (restore) {
+ deps.setTool(priorToolId, { temporary: true });
+ }
+ }
+
const releaseTempTool = (): void => {
if (!tempHold) {
return;
@@ -257,6 +328,9 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelin
cancelActiveGesture: () => {
cancelGesture();
},
+ cancelGestureForToolSwitch: () => {
+ cancelGesture(false);
+ },
onKeyDown: (event) => {
if (event.key === 'Escape') {
// Cancel the gesture before the engine Escape ladder. Editable fields keep Escape; gesture-consuming
@@ -274,10 +348,15 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelin
}
if (event.key === 'Enter') {
// Enter applies a session-bearing tool's edit (transform). No-op otherwise.
- deps.getActiveTool()?.onKeyCommand?.(deps.getToolContext(), 'apply');
+ if (!event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey && ownsKeyboard(event)) {
+ deps.getActiveTool()?.onKeyCommand?.(deps.getToolContext(), 'apply');
+ }
return;
}
if (event.code === 'Space' && !event.repeat) {
+ if (event.ctrlKey || event.metaKey || event.altKey || !ownsKeyboard(event)) {
+ return;
+ }
beginTempTool('space', SPACE_TEMP_TOOL);
if (tempHold === 'space') {
event.preventDefault();
@@ -336,6 +415,7 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelin
if (event.button !== 0) {
return;
}
+ cancelledPointerId = null;
// Commit and consume modal text presses before gesture activation; prevent default focus/selection after
// closing the session.
if (deps.maybeCommitModalSession?.()) {
@@ -367,6 +447,12 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelin
middleLast = screenPoint;
return;
}
+ if (cancelledPointerId === event.pointerId) {
+ if (event.buttons !== 0) {
+ return;
+ }
+ cancelledPointerId = null;
+ }
const batch = buildBatch(event);
const last = batch[batch.length - 1];
if (!last) {
@@ -380,6 +466,9 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelin
return;
}
releaseCapture(event.pointerId);
+ if (cancelledPointerId === event.pointerId) {
+ cancelledPointerId = null;
+ }
if (middlePanning) {
middlePanning = false;
middleLast = null;
@@ -403,17 +492,16 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelin
}
},
reset: () => {
- clearBboxTapTimer();
+ // Cancel through the tool that owns the gesture before a held temporary tool is restored.
+ cancelGesture();
if (tempHold) {
endTempTool();
}
- // Cancel an in-flight gesture through the same path Esc uses, so the active
- // tool's `onPointerCancel` runs and clears its transient state (rather than
- // silently dropping `gestureActive` and stranding stale tool state).
- cancelGesture();
+ clearBboxTapTimer();
hovered = false;
gestureActive = false;
activePointerId = null;
+ cancelledPointerId = null;
middlePanning = false;
middleLast = null;
},
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.test.ts
index 247af3b32b..22742994f6 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.test.ts
@@ -117,14 +117,33 @@ describe('lassoTool: cancel + guards', () => {
expect(commits).toHaveLength(0);
});
- it('decimates points closer than the minimum distance', () => {
- const tool = createLassoTool();
- const { ctx, stores } = createHarness();
- down(tool, ctx, pointer(0, 0));
- // These are all within 1px of each other → decimated away.
- move(tool, ctx, pointer(0.5, 0));
- move(tool, ctx, pointer(1, 0));
- expect(stores.lassoPreview.get()?.points).toHaveLength(1);
+ it('decimates by on-screen travel, stores document points, and always keeps the release point', () => {
+ const at = (x: number, y: number, zoom: number): PointerInput => ({
+ ...pointer(x, y),
+ screenPoint: { x: x * zoom, y: y * zoom },
+ });
+ // Zoomed in 10×: half-pixel document steps are 5 CSS px apart and all survive.
+ const zoomedIn = createLassoTool();
+ const near = createHarness();
+ down(zoomedIn, near.ctx, at(0, 0, 10));
+ move(zoomedIn, near.ctx, at(0.5, 0, 10));
+ move(zoomedIn, near.ctx, at(0.5, 0.5, 10));
+ expect(near.stores.lassoPreview.get()?.points).toEqual([
+ { x: 0, y: 0 },
+ { x: 0.5, y: 0 },
+ { x: 0.5, y: 0.5 },
+ ]);
+
+ // Zoomed out 10×: 10-unit document steps are 1 CSS px apart and decimate away, but the release point stays.
+ const zoomedOut = createLassoTool();
+ const far = createHarness();
+ down(zoomedOut, far.ctx, at(0, 0, 0.1));
+ move(zoomedOut, far.ctx, at(10, 0, 0.1));
+ expect(far.stores.lassoPreview.get()?.points).toHaveLength(1);
+ move(zoomedOut, far.ctx, at(40, 0, 0.1));
+ move(zoomedOut, far.ctx, at(40, 40, 0.1));
+ up(zoomedOut, far.ctx, at(41, 40, 0.1));
+ expect(far.commits[0]?.bounds).toEqual({ height: 40, width: 41, x: 0, y: 0 });
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.ts
index 05bbc8429f..b38329e7a3 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.ts
@@ -13,26 +13,26 @@ import { selectionOpFor } from '@workbench/canvas-engine/selection/selectionOpMo
import type { Tool, ToolContext } from './tool';
import {
+ extendFreehandTrace,
+ finishFreehandTrace,
MIN_POLYLINE_POINTS,
movePolyline,
polylinePreview,
pressPolyline,
+ startFreehandTrace,
startPolyline,
+ type FreehandTrace,
type PolylineSession,
} from './polylineSession';
/** Bit for the primary (usually left) mouse button in `PointerEvent.buttons`. */
const PRIMARY_BUTTON = 1;
-/** Minimum document-space gap between stored polygon points (input decimation). */
-export const LASSO_MIN_POINT_DISTANCE = 2;
-
const distance = (a: Vec2, b: Vec2): number => Math.hypot(a.x - b.x, a.y - b.y);
/** A freehand drag in progress. */
-interface FreehandSession {
+interface FreehandSession extends FreehandTrace {
kind: 'freehand';
- points: Vec2[];
}
/** A polygon vertex-placing session spanning multiple clicks. */
@@ -50,14 +50,6 @@ export const createLassoTool = (): Tool => {
session = null;
};
- /** Appends a point if it is far enough from the last stored one. */
- const pushDecimated = (points: Vec2[], p: Vec2): void => {
- const last = points[points.length - 1];
- if (!last || distance(last, p) >= LASSO_MIN_POINT_DISTANCE) {
- points.push({ x: p.x, y: p.y });
- }
- };
-
/** Publishes the in-progress outline for the overlay. */
const publishPreview = (ctx: ToolContext): void => {
if (!session || session.points.length === 0) {
@@ -144,7 +136,7 @@ export const createLassoTool = (): Tool => {
if (session) {
return;
}
- session = { kind: 'freehand', points: [{ x: input.documentPoint.x, y: input.documentPoint.y }] };
+ session = { ...startFreehandTrace(input), kind: 'freehand' };
publishPreview(ctx);
return;
}
@@ -174,9 +166,7 @@ export const createLassoTool = (): Tool => {
ctx.updateCursor();
}
} else {
- for (const sample of batch) {
- pushDecimated(session.points, sample.documentPoint);
- }
+ extendFreehandTrace(session, batch);
}
publishPreview(ctx);
},
@@ -186,8 +176,7 @@ export const createLassoTool = (): Tool => {
if (!session || session.kind === 'polygon') {
return;
}
- pushDecimated(session.points, input.documentPoint);
- const polygon = session.points.slice();
+ const polygon = finishFreehandTrace(session, input);
reset();
clearPreview(ctx);
commit(ctx, polygon, input.modifiers);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/polylineSession.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/polylineSession.ts
index 94e3412f0b..5415368e59 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/polylineSession.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/polylineSession.ts
@@ -1,6 +1,6 @@
/**
* Shared click-to-place polyline with cursor band. Close on double-click, Enter or first-vertex screen-radius hit;
- * preview that hit with a ring.
+ * preview that hit with a ring. Freehand traces share the same CSS-pixel input decimation.
*/
import type { LassoPreview } from '@workbench/canvas-engine/engineStores';
@@ -85,3 +85,35 @@ export const polylinePreview = (session: PolylineSession): LassoPreview => ({
kind: 'polygon',
points: session.points.slice(),
});
+
+/** Minimum on-screen gap (CSS px) between stored freehand points, independent of zoom. */
+export const FREEHAND_MIN_POINT_SPACING_PX = 2;
+
+/** A dragged freehand outline: document-space points, decimated by on-screen travel. */
+export interface FreehandTrace {
+ points: Vec2[];
+ lastScreen: Vec2;
+}
+
+export const startFreehandTrace = (input: PointerInput): FreehandTrace => ({
+ lastScreen: input.screenPoint,
+ points: [{ x: input.documentPoint.x, y: input.documentPoint.y }],
+});
+
+export const extendFreehandTrace = (trace: FreehandTrace, samples: readonly PointerInput[]): void => {
+ for (const sample of samples) {
+ if (distance(trace.lastScreen, sample.screenPoint) >= FREEHAND_MIN_POINT_SPACING_PX) {
+ trace.points.push({ x: sample.documentPoint.x, y: sample.documentPoint.y });
+ trace.lastScreen = sample.screenPoint;
+ }
+ }
+};
+
+/** The completed outline, always ending on the release point. */
+export const finishFreehandTrace = (trace: FreehandTrace, input: PointerInput): Vec2[] => {
+ const last = trace.points[trace.points.length - 1];
+ const final = input.documentPoint;
+ return last && last.x === final.x && last.y === final.y
+ ? trace.points.slice()
+ : [...trace.points, { x: final.x, y: final.y }];
+};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.test.ts
index 8aba0be0ec..312e0907c0 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.test.ts
@@ -291,6 +291,38 @@ describe('shape tool: polygon and freehand kinds', () => {
}
});
+ it('decimates a freehand trace by on-screen travel and keeps the release point', () => {
+ const h = createHarness(makeDoc());
+ h.stores.shapeOptions.set({ ...h.stores.shapeOptions.get(), kind: 'freehand' });
+ const tool = createShapeTool();
+ const zoomedOut = (x: number, y: number): PointerInput => ({
+ ...pointer(x, y),
+ screenPoint: { x: x / 10, y: y / 10 },
+ });
+
+ down(tool, h.ctx, zoomedOut(0, 0));
+ // 10 document units are 1 CSS px at 0.1× zoom: decimated away.
+ move(tool, h.ctx, zoomedOut(10, 0));
+ move(tool, h.ctx, zoomedOut(30, 0));
+ move(tool, h.ctx, zoomedOut(30, 30));
+ expect(h.stores.lassoPreview.get()).toMatchObject({
+ points: [
+ { x: 0, y: 0 },
+ { x: 30, y: 0 },
+ { x: 30, y: 30 },
+ ],
+ });
+ up(tool, h.ctx, zoomedOut(5, 30));
+
+ const forward = h.commits[0]?.forward;
+ if (forward?.type === 'addCanvasLayer' && forward.layer.type === 'raster') {
+ expect((forward.layer.source as { points?: unknown[] }).points).toHaveLength(4);
+ expect(forward.layer.source).toMatchObject({ height: 30, width: 30 });
+ } else {
+ throw new Error('expected a polygon layer');
+ }
+ });
+
it('commits nothing for a flat polygon', () => {
// The third point survives the 1px dedupe; only the sub-pixel bounds reject it.
expect(
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.ts
index 7743833175..a99d8c7fc6 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.ts
@@ -23,11 +23,15 @@ import type { Tool, ToolContext } from './tool';
import { layerMatrix } from './moveHitTest';
import {
+ extendFreehandTrace,
+ finishFreehandTrace,
MIN_POLYLINE_POINTS,
movePolyline,
polylinePreview,
pressPolyline,
+ startFreehandTrace,
startPolyline,
+ type FreehandTrace,
type PolylineSession,
} from './polylineSession';
@@ -39,13 +43,10 @@ const PRIMARY_BUTTON = 1;
/** Screen-space distance (CSS px) the pointer must travel before a press becomes a drag. */
export const SHAPE_DRAG_THRESHOLD_PX = 3;
-/** Minimum document-space gap between stored freehand points (input decimation). */
-const FREEHAND_MIN_POINT_DISTANCE = 2;
-
type Session =
| { kind: 'drag'; startDoc: Vec2; startScreen: Vec2; moved: boolean }
| { kind: 'polyline'; session: PolylineSession }
- | { kind: 'freehand'; points: Vec2[] };
+ | ({ kind: 'freehand' } & FreehandTrace);
const distance = (a: Vec2, b: Vec2): number => Math.hypot(a.x - b.x, a.y - b.y);
@@ -305,7 +306,7 @@ export const createShapeTool = (): Tool => {
}
session =
kind === 'freehand'
- ? { kind: 'freehand', points: [{ x: input.documentPoint.x, y: input.documentPoint.y }] }
+ ? { ...startFreehandTrace(input), kind: 'freehand' }
: { kind: 'drag', moved: false, startDoc: input.documentPoint, startScreen: input.screenPoint };
},
onPointerMove: (ctx, input, batch) => {
@@ -326,12 +327,7 @@ export const createShapeTool = (): Tool => {
return;
}
if (session.kind === 'freehand') {
- for (const sample of batch) {
- const last = session.points[session.points.length - 1];
- if (!last || distance(last, sample.documentPoint) >= FREEHAND_MIN_POINT_DISTANCE) {
- session.points.push({ x: sample.documentPoint.x, y: sample.documentPoint.y });
- }
- }
+ extendFreehandTrace(session, batch);
ctx.stores.lassoPreview.set({ kind: 'freehand', points: session.points.slice() });
ctx.invalidate({ overlay: true });
return;
@@ -355,7 +351,7 @@ export const createShapeTool = (): Tool => {
return;
}
if (session.kind === 'freehand') {
- commit(ctx, polygonShapeFrom([...session.points, input.documentPoint], styleFromOptions(ctx)));
+ commit(ctx, polygonShapeFrom(finishFreehandTrace(session, input), styleFromOptions(ctx)));
return;
}
if (!session.moved) {