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.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(canvas): pan and pinch-zoom on trackpads, detected per gesture (#10106)
Josh Corbettc9a2392a1764
diff --git a/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx b/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdxindex 18c3a6fbd4..f764f7158f 100644--- a/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx+++ b/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx@@ -48,7 +48,7 @@ A pick that changes a layer is one undoable step. Gradient stops are not picked### Tool options-* **Brush** — **Size**, **Opacity** and **Hardness**; the **Foreground** color; and, under **Dynamics**, whether pen pressure affects the width or the opacity. **[** and **]** make the brush smaller or larger, and so does **Ctrl**+scroll. Painting on an image layer, such as an accepted result or an added picture, paints on that layer itself instead of adding a new one; one undo restores the original image. **Shift**-click joins the click to the end of the last Brush or Eraser stroke on the same layer with a straight line. The line follows the selection and the frame clipping like any stroke, and one undo removes it. Undo, redo or deleting the layer clears the remembered point, so the next **Shift**-click paints a dot.+* **Brush** — **Size**, **Opacity** and **Hardness**; the **Foreground** color; and, under **Dynamics**, whether pen pressure affects the width or the opacity. **[** and **]** make the brush smaller or larger, and so does **Ctrl**+scroll with a mouse wheel. On a trackpad, **Ctrl**+scroll zooms instead. Painting on an image layer, such as an accepted result or an added picture, paints on that layer itself instead of adding a new one; one undo restores the original image. **Shift**-click joins the click to the end of the last Brush or Eraser stroke on the same layer with a straight line. The line follows the selection and the frame clipping like any stroke, and one undo removes it. Undo, redo or deleting the layer clears the remembered point, so the next **Shift**-click paints a dot.* **Eraser** — **Size**, **Opacity** and **Hardness**; and, under **Dynamics**, whether pen pressure affects the width. Pressure never changes how strongly the eraser erases.The Brush, Eraser, Shape and Text options are remembered for your account, so they are the same in every project and after a reload. Colors are the project's own.@@ -95,7 +95,7 @@ In InvokeAI 6, the Lasso drew directly into an inpaint mask, and created one if## Navigating the canvas-* **Zoom** with the mouse wheel, which zooms around the pointer, or choose a level from the zoom menu in the header (25% to 500%). **Ctrl+1**, **Ctrl+2**, **Ctrl+3** and **Ctrl+4** zoom to 100%, 200%, 400% and 800% around the center of the view. Many browsers use these keys to switch tabs and do not pass them to the page; there, choose **Zoom to 100%**, **Zoom to 200%**, **Zoom to 400%** or **Zoom to 800%** from the command palette (**Ctrl+K**), or assign other keys in **Settings → Hotkeys**.+* **Zoom** with the mouse wheel, which zooms around the pointer, or choose a level from the zoom menu in the header (25% to 500%). **Ctrl+1**, **Ctrl+2**, **Ctrl+3** and **Ctrl+4** zoom to 100%, 200%, 400% and 800% around the center of the view. Many browsers use these keys to switch tabs and do not pass them to the page; there, choose **Zoom to 100%**, **Zoom to 200%**, **Zoom to 400%** or **Zoom to 800%** from the command palette (**Ctrl+K**), or assign other keys in **Settings → Hotkeys**. On a trackpad, two-finger scrolling pans the view and pinching zooms around the pointer. The canvas recognizes a trackpad the first time you pinch or scroll diagonally on it, and remembers it in that browser; a mouse wheel keeps zooming. If it gets your device wrong, set **Scroll input** in the canvas settings.* **Pan** with the Pan tool, by holding **Space**, or by dragging with the middle mouse button.* **Fit to view**, at the top of the header's zoom menu, fits the generation frame and all layers into the window.@@ -213,6 +213,7 @@ The gear button in the header opens the canvas settings. They are saved with the<Image src={canvasSettings} alt="The Canvas settings popover with Behavior, Display and Grid options." width={420} />* **Behavior**+ * **Scroll input** — **Auto-detect** (the default) zooms with a mouse wheel, and pans and pinch-zooms with a trackpad. If your device is misread, choose it: a mouse with smooth scrolling can look like a trackpad once one was recognized. With **Mouse wheel**, scrolling zooms and **Ctrl**+scroll resizes the brush. With **Trackpad**, scrolling pans and **Ctrl**+scroll zooms. **[** and **]** resize the brush in every mode.* **Invert scroll for brush size** — reverses **Ctrl**+scroll brush sizing.* **Clip strokes to frame** — keeps painting inside the generation frame.* **Output only generated regions** — when on, an inpainting or outpainting result contains only the regenerated area, with the rest transparent; when off, it includes the whole frame.diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.jsonindex e73ed8fc53..358b5bbb88 100644--- a/invokeai/frontend/webv2/performance/browser-baseline.json+++ b/invokeai/frontend/webv2/performance/browser-baseline.json@@ -1509,6 +1509,7 @@"source:src/workbench/canvas-engine/history/layerSnapshot.ts","source:src/workbench/canvas-engine/input/pointerPipeline.ts","source:src/workbench/canvas-engine/input/wheel.ts",+ "source:src/workbench/canvas-engine/input/wheelDevice.ts","source:src/workbench/canvas-engine/layerExportGuards.ts","source:src/workbench/canvas-engine/layerRasterizer.ts","source:src/workbench/canvas-engine/math/mat2d.ts",@@ -2698,6 +2699,7 @@"source:src/workbench/canvas-engine/history/layerSnapshot.ts","source:src/workbench/canvas-engine/input/pointerPipeline.ts","source:src/workbench/canvas-engine/input/wheel.ts",+ "source:src/workbench/canvas-engine/input/wheelDevice.ts","source:src/workbench/canvas-engine/layerExportGuards.ts","source:src/workbench/canvas-engine/layerRasterizer.ts","source:src/workbench/canvas-engine/math/mat2d.ts",@@ -3085,6 +3087,7 @@"source:src/workbench/widgets/canvas/CanvasImageDropOverlay.tsx","source:src/workbench/widgets/canvas/CanvasImageDropZone.tsx","source:src/workbench/widgets/canvas/CanvasSaveToGallerySubmenu.tsx",+ "source:src/workbench/widgets/canvas/CanvasScrollInputFeed.tsx","source:src/workbench/widgets/canvas/CanvasStagedRegionsFeed.tsx","source:src/workbench/widgets/canvas/CanvasSurface.tsx","source:src/workbench/widgets/canvas/CanvasSurfaceContextLayout.tsx",@@ -4119,6 +4122,7 @@"source:src/workbench/canvas-engine/history/layerSnapshot.ts","source:src/workbench/canvas-engine/input/pointerPipeline.ts","source:src/workbench/canvas-engine/input/wheel.ts",+ "source:src/workbench/canvas-engine/input/wheelDevice.ts","source:src/workbench/canvas-engine/layerExportGuards.ts","source:src/workbench/canvas-engine/layerRasterizer.ts","source:src/workbench/canvas-engine/math/mat2d.ts",diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 6d96cbdaf4..d0eeb5a809 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -4666,6 +4666,13 @@"logDebugInfo": "Log debug info","outputOnlyMaskedRegions": "Output only generated regions","ruleOfThirds": "Rule of thirds",+ "scrollInput": "Scroll input",+ "scrollInputDescription": "Auto-detect zooms with a mouse wheel, and pans and pinch-zooms with a trackpad. Once a trackpad has been used in this browser, a smooth-scrolling mouse wheel pans too; choose Mouse wheel if yours does.",+ "scrollInputOptions": {+ "auto": "Auto-detect",+ "mouse": "Mouse wheel",+ "trackpad": "Trackpad"+ },"sections": {"behavior": "Behavior","debug": "Debug",diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.mdindex 613996f381..896fd37392 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md@@ -314,6 +314,8 @@ Capability returns `exported`, `busy`, `nothing`, `too-large` (PSD format or serPointer pipeline (`input/pointerPipeline.ts`) owns gesture capture and temporary holds (Space → view, Alt → picker, C → bbox). Keyboard ownership is explicit. Widget passes its focusable keyboard root and a `resolveKeyOwner` judge to `surface.attach`; the judge names the workbench region that owns a keydown (`surface`, a `companion` widget acting on this canvas's layers, or `elsewhere`) and is asked only on keydown, after the pipeline's own refusals, so the engine imports nothing from Workbench focus and pointer paths never pay for it. No key acts over an editable field, a control reached by keyboard (pipeline records on `focusin` whether focus arrived by pointer: Chromium marks focused element `:focus-visible` at any keydown, so arrival is the only reliable signal), an open dialog, menu or listbox, or beneath a modal. Past those refusals: Enter applies a session only from the `surface` with focus on its root or nowhere, never on a control; the Escape ladder and C act from the `surface` or a `companion`. Escape first cancels the pointer gesture, then the engine ladder runs, most local first: a color pick, a defocused text edit, a transform session or pending transform, a float, the open session of the tool the user is on (the held tool under a Space, Alt or C hold: a polygon between clicks), an application operation (Filter, Select Object), and only then the selection. A tool's `onKeyCommand('cancel')` reports whether it dropped a session; one that did, or a gesture the Escape cancelled, keeps the committed selection; Space and Alt stay pointer-led, acting over the hovered canvas whatever the owner and otherwise only from the `surface`. Without a judge (tests, detached engines) focus alone decides: the root or no focus is the surface, and a control the pointer last clicked counts as a companion. Owned Space keydown is prevented, so a clicked control does not activate. An owned Alt keydown is prevented, and so is the release of an Alt the pipeline claimed, because Firefox and Windows otherwise activate the menu bar; that holds for a tool that reads Alt as a gesture modifier too (Marquee, Lasso, Move and the Frame tool's grid bypass, Transform's scale about the centre, Shape's draw from the centre), which keeps the key and only gets no picker hold, since pointer events still carry `altKey`; the Color picker tool (I) covers those tools. Every other release is observed, never consumed. Alt from the surface while the pointer is elsewhere arms a pending hold that the next `pointerenter` with Alt still held, or a `pointerdown` with Alt, begins before the press is routed, so a pen landing without hover samples on contact; release, tool switch, blur, reset and detach clear it. Genuine tool switch first cancels the gesture through outgoing tool and ends any hold, restoring held tool, so the switch leaves the tool the user was really on and a later key release restores nothing.+Wheel routing (`input/wheel.ts`) follows the `scrollInput` interaction setting. Mouse behavior: wheel zooms, resting on snap points, and Ctrl+wheel steps the brush or eraser size. Trackpad behavior: wheel pans on both axes and Ctrl+wheel, how browsers deliver a pinch, zooms continuously about the pointer. `auto` classifies each event (`input/wheelDevice.ts`, which reads `deltaMode` first, because Firefox otherwise reports a line-mode wheel in pixels, and normalizes deltas to CSS pixels for all routing). A notched wheel always gets mouse behavior. Smooth scrolling gets trackpad behavior once `trackpadDetected` is set and mouse behavior before, so a high-resolution mouse wheel keeps zooming; a sideways-only event, notched or smooth, pans either way. A two-axis event, or Ctrl+wheel while the physical Control key is known to be `up`, or, while that state is `unknown`, Ctrl+wheel carrying Chromium's pinch stamp (a whole-tick `wheelDeltaY` on a delta under 25px), proves a trackpad: the engine sets `trackpadDetected` before routing that event and never clears it, and the widget persists it per browser (`widgets/canvas/CanvasScrollInputFeed.tsx`). The pipeline tracks Control from capture-phase window key events, so a handler that stops propagation cannot hide them, and from pointer event modifiers and wheel events without `ctrlKey`, which show it up only while the document has focus; it is `unknown` until the first such event and again after window focus, blur or a hidden page, since a press made meanwhile is never seen. Safari's pinch arrives as `gesturestart`/`gesturechange` instead; in every mode it is prevented, so the page does not magnify, zooms by `scale` from the gesture's start and sets `trackpadDetected`. A pinch that starts during a pointer gesture is ignored: iPadOS sends the same events for a touch pinch, whose first finger is already drawing. A view change under a still pointer delivers a hover move (`refreshHover`) with hover pressure, so hover state such as the brush ring stays under the pointer; it is skipped during a gesture, where a synthesized move would paint a segment the user never drew.+`ColorSampleController` routes picks. A pick previews each sampled color to the one-shot request or the workbench router (`setColorSampleRouter`), then commits the last preview once on release or cancels it once when the press ends any other way (Escape, a tool change, a cancelled pointer); a declined preview falls back to the brush color. The sink that took a pick's first preview gets its commit or cancel, so a request armed or settled mid-pick never sends the router a stray phase, nor the reverse. Brush and eraser share an engine-lifetime memory (`PaintLineEndController`) of where the last committed stroke ended on each layer, kept in that layer's local space: a Shift press on a layer with a remembered end draws a straight segment from it, placed through the layer's current transform, as part of the one stroke. The engine routes every layer change to it. A change of transform alone (move, nudge, Fit to frame, a transform parameter) carries the end with the layer; a change that rewrites content and transform together (crop, conversion, a baked float or result) keeps its document position and re-expresses it in the new local space; an applied Transform on a paint layer, which redraws only the pixels, rebases it from the session's transform. It survives tool switches but forgets on replay, document replacement, the layer's removal and a transform it cannot invert. `layers.beginTransform` (`TransformEditingController.request`) selects a leaf, switches to transform and opens its session even when transform is already active, cancelling a session on another layer; it refuses a locked or ineligible leaf, a running gesture, a live float or locked edits without changing selection or tool. A leaf whose only content is a stroke persistence has not acknowledged yet (a new paint layer's first upload) has no persisted extent to frame, so the request waits in the `pendingTransformLayerId` interaction store and the session opens when the bitmap lands, while the leaf is still selected, transform is the tool the user is on (a Space, Alt or C hold over it counts) and no other session opened. The wait ends without a session on a genuine tool switch, a selection change, the leaf's removal, Escape, a history replay, a document replacement, disposal, or an upload of that leaf failing with no retry to follow (retried failures keep the wait), which also reports a `not-ready` refusal through `tools.onEditRefused`.`RenderScheduler.beforeNextFrame(task)` runs tasks once before next frame takes its flags, so their invalidations join that frame. Tools reach it through required `ToolContext.scheduleFrame`; detached engine runs the task immediately because it produces no frames. Brush strokes append samples and decimate them incrementally per event, render accumulated stroke at most once per presented frame, render synchronously on commit.diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.tsindex beff6dd461..128c157a14 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts@@ -45,6 +45,7 @@ import type {LayerQuickSwitchState,LayerThumbnailStatus,MarqueeToolOptions,+ ScrollInput,ShapeToolOptions,TextEditSession,TextToolOptions,@@ -204,6 +205,7 @@ export interface CanvasInteractionState {/** Advances after the engine reacted to the document change. */documentEpoch: number;ruleOfThirds: boolean;+ scrollInput: ScrollInput;shapeOptions: ShapeToolOptions;showBbox: boolean;showGrid: boolean;@@ -212,6 +214,8 @@ export interface CanvasInteractionState {stagingHidesOverlays: boolean;textEditSession: TextEditSession | null;textOptions: TextToolOptions;+ /** Engine-set on trackpad proof; callers restore it. */+ trackpadDetected: boolean;transformOptions: TransformOptions;transformSession: TransformSession | null;/** Waits for fresh pixels to persist; clears on tool switch, selection change, Escape, removal or failure. */@@ -237,11 +241,13 @@ export type CanvasWritableInteractionKey = Extract<| 'layerQuickSwitch'| 'marqueeOptions'| 'ruleOfThirds'+ | 'scrollInput'| 'shapeOptions'| 'showBbox'| 'showGrid'| 'snapToGrid'| 'textOptions'+ | 'trackpadDetected'| 'transformOptions'>;@@ -818,6 +824,7 @@ export type {LayerQuickSwitchState,LayerThumbnailStatus,MarqueeToolOptions,+ ScrollInput,ShapeToolKind,ShapeToolOptions,ShapeToolTarget,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/renderController.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/renderController.browser.test.tsnew file mode 100644index 0000000000..65411b1e30--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/renderController.browser.test.ts@@ -0,0 +1,120 @@+import type { ToolContext } from '@workbench/canvas-engine/tools/tool';++import { createPointerPipeline } from '@workbench/canvas-engine/input/pointerPipeline';+import { createWheelInput } from '@workbench/canvas-engine/input/wheel';+import { createViewport } from '@workbench/canvas-engine/viewport';+import { afterEach, describe, expect, it } from 'vitest';++import { RenderController } from './renderController';++const cleanups: (() => void)[] = [];++afterEach(() => {+ for (const cleanup of cleanups.splice(0).reverse()) {+ cleanup();+ }+});++/** A real pipeline bound through `attach`, with a control that stops every key event it receives. */+const createAttachedInput = () => {+ const surface = document.createElement('div');+ const screen = document.createElement('canvas');+ const overlay = document.createElement('canvas');+ const field = document.createElement('input');+ const stop = (event: Event): void => event.stopPropagation();+ field.addEventListener('keydown', stop);+ field.addEventListener('keyup', stop);+ surface.append(screen, overlay);+ document.body.append(surface, field);++ const ctx = {} as ToolContext;+ const viewport = createViewport();+ const pipeline = createPointerPipeline({+ getActiveTool: () => undefined,+ getActiveToolId: () => 'view',+ getInputElement: () => overlay,+ getKeyboardRoot: () => surface,+ getToolContext: () => ctx,+ hasTool: () => false,+ isReplaying: () => false,+ setTool: () => undefined,+ updateCursor: () => undefined,+ viewport,+ });+ const wheel = createWheelInput({+ getActiveTool: () => undefined,+ getControlKeyState: () => pipeline.controlKeyState(),+ getInputElement: () => overlay,+ getInvertBrushSizeScroll: () => false,+ getScrollInput: () => 'auto',+ invalidate: () => undefined,+ isGestureActive: () => pipeline.isGestureActive(),+ onWheelWithoutControl: () => pipeline.onWheelWithoutControl(),+ stepActiveBrushSize: () => undefined,+ trackpadDetected: { get: () => false, set: () => undefined },+ viewport,+ });+ const controller = new RenderController({+ applyCursor: () => undefined,+ getInputHandlers: () => ({ ...pipeline, ...wheel }),+ isEngineDisposed: () => false,+ onPageHide: () => undefined,+ onVisibilityChange: () => undefined,+ onWindowBlur: () => pipeline.reset(),+ render: () => undefined,+ setViewportReady: () => undefined,+ updateAnimation: () => undefined,+ updateCursor: () => undefined,+ });+ controller.attach(screen, overlay, surface);+ cleanups.push(() => {+ controller.dispose();+ surface.remove();+ field.remove();+ });+ const control = (type: 'keydown' | 'keyup') =>+ field.dispatchEvent(+ new KeyboardEvent(type, { bubbles: true, code: 'ControlLeft', ctrlKey: type === 'keydown', key: 'Control' })+ );+ const pinch = (type: 'gesturestart' | 'gesturechange', scale: number): Event => {+ const event = Object.assign(new Event(type, { cancelable: true }), { clientX: 0, clientY: 0, scale });+ overlay.dispatchEvent(event);+ return event;+ };+ return { control, controller, overlay, pinch, pipeline, viewport };+};++describe('RenderController in Chromium: physical Control key', () => {+ it('sees key events a control stops from bubbling, forgets it on window focus, relearns it from a scroll', () => {+ const { control, overlay, pipeline } = createAttachedInput();+ control('keydown');+ expect(pipeline.controlKeyState()).toBe('down');+ control('keyup');+ expect(pipeline.controlKeyState()).toBe('up');++ globalThis.dispatchEvent(new FocusEvent('focus'));+ expect(pipeline.controlKeyState()).toBe('unknown');+ overlay.dispatchEvent(new WheelEvent('wheel', { cancelable: true, deltaY: 4 }));+ expect(pipeline.controlKeyState()).toBe('up');+ });++ it('stops tracking once detached', () => {+ const { control, controller, pipeline } = createAttachedInput();+ controller.detach();+ control('keydown');+ expect(pipeline.controlKeyState()).toBe('unknown');+ });+});++describe('RenderController in Chromium: Safari pinch gestures', () => {+ it('takes them over from the page zoom while attached, and lets go once detached', () => {+ const { controller, pinch, viewport } = createAttachedInput();+ expect(pinch('gesturestart', 1).defaultPrevented).toBe(true);+ expect(pinch('gesturechange', 2).defaultPrevented).toBe(true);+ expect(viewport.getZoom()).toBeCloseTo(2, 10);++ controller.detach();+ expect(pinch('gesturechange', 3).defaultPrevented).toBe(false);+ expect(viewport.getZoom()).toBeCloseTo(2, 10);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/renderController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/renderController.tsindex d944dfd1fc..3265af32a0 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/renderController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/renderController.ts@@ -49,8 +49,13 @@ export interface RenderControllerOptions extends RenderSchedulerDeps {onPointerLeave: (event: PointerEvent) => void;onKeyDown: (event: KeyboardEvent) => void;onKeyUp: (event: KeyboardEvent) => void;+ /** Both key events in the capture phase, so no handler that stops propagation hides them. */+ onKeyCapture: (event: KeyboardEvent) => void;onFocusIn: (event: FocusEvent) => void;+ onWindowFocus: () => void;onWheel: (event: WheelEvent) => void;+ onPinchGestureStart: (event: Event) => void;+ onPinchGestureChange: (event: Event) => void;reset(): void;};readonly onPageHide: () => void;@@ -123,10 +128,15 @@ export class RenderController {this.input.addEventListener('pointerenter', handlers.onPointerEnter);this.input.addEventListener('pointerleave', handlers.onPointerLeave);this.input.addEventListener('wheel', handlers.onWheel, { passive: false });+ this.input.addEventListener('gesturestart', handlers.onPinchGestureStart, { passive: false });+ this.input.addEventListener('gesturechange', handlers.onPinchGestureChange, { passive: false });if (typeof globalThis.addEventListener === 'function') {globalThis.addEventListener('keydown', handlers.onKeyDown);globalThis.addEventListener('keyup', handlers.onKeyUp);+ globalThis.addEventListener('keydown', handlers.onKeyCapture, true);+ globalThis.addEventListener('keyup', handlers.onKeyCapture, true);globalThis.addEventListener('focusin', handlers.onFocusIn);+ globalThis.addEventListener('focus', handlers.onWindowFocus);globalThis.addEventListener('pagehide', this.options.onPageHide);globalThis.addEventListener('blur', this.options.onWindowBlur);}@@ -150,12 +160,17 @@ export class RenderController {this.input.removeEventListener('pointerenter', handlers.onPointerEnter);this.input.removeEventListener('pointerleave', handlers.onPointerLeave);this.input.removeEventListener('wheel', handlers.onWheel);+ this.input.removeEventListener('gesturestart', handlers.onPinchGestureStart);+ this.input.removeEventListener('gesturechange', handlers.onPinchGestureChange);this.options.applyCursor('');}if (typeof globalThis.removeEventListener === 'function') {globalThis.removeEventListener('keydown', handlers.onKeyDown);globalThis.removeEventListener('keyup', handlers.onKeyUp);+ globalThis.removeEventListener('keydown', handlers.onKeyCapture, true);+ globalThis.removeEventListener('keyup', handlers.onKeyCapture, true);globalThis.removeEventListener('focusin', handlers.onFocusIn);+ globalThis.removeEventListener('focus', handlers.onWindowFocus);globalThis.removeEventListener('pagehide', this.options.onPageHide);globalThis.removeEventListener('blur', this.options.onWindowBlur);}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.tsindex 439d2d5138..08797ba198 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts@@ -7395,9 +7395,9 @@ describe('masks while a result is staged', () => {quadraticCurveTo() {}});- const windowListeners = new Map<string, (event: unknown) => void>();+ const windowListeners = new Map<string, Set<(event: unknown) => void>>();vi.stubGlobal('addEventListener', (type: string, listener: (event: unknown) => void) =>- windowListeners.set(type, listener)+ windowListeners.set(type, (windowListeners.get(type) ?? new Set()).add(listener)));vi.stubGlobal('removeEventListener', () => {});const composite = vi.spyOn(compositor, 'compositeDocument');@@ -7451,7 +7451,11 @@ describe('masks while a result is staged', () => {raf.flush();};const key = (type: 'keydown' | 'keyup', code: string): void =>- windowListeners.get(type)?.({ code, key: code === 'Space' ? ' ' : code, preventDefault: () => {}, target: null });+ windowListeners+ .get(type)+ ?.forEach((listener) =>+ listener({ code, key: code === 'Space' ? ' ' : code, preventDefault: () => {}, target: null, type })+ );const expectPressHidden = (): void => {overlay.fire('pointerdown', pointerAt(5, 5));const pressed = frame();@@ -7581,11 +7585,13 @@ describe('beginTransform', () => {quadraticCurveTo() {}});- const windowListeners = new Map<string, (event: unknown) => void>();+ const windowListeners = new Map<string, Set<(event: unknown) => void>>();vi.stubGlobal('addEventListener', (type: string, listener: (event: unknown) => void) =>- windowListeners.set(type, listener)+ windowListeners.set(type, (windowListeners.get(type) ?? new Set()).add(listener))+ );+ vi.stubGlobal('removeEventListener', (type: string, listener: (event: unknown) => void) =>+ windowListeners.get(type)?.delete(listener));- vi.stubGlobal('removeEventListener', (type: string) => windowListeners.delete(type));const existing: CanvasLayerContract = {...(rasterLayer('paint') as CanvasRasterLayerContractV2),source: { bitmap: null, type: 'paint' },@@ -7619,7 +7625,11 @@ describe('beginTransform', () => {expect(engine.stores.transformSession.get()).toBeNull();expect(engine.interaction.get('pendingTransformLayerId')).toBe(stroke.layerId);const key = (type: 'keydown' | 'keyup', code: string) =>- windowListeners.get(type)?.({ code, key: code === 'Space' ? ' ' : code, preventDefault: () => {}, target: null });+ windowListeners+ .get(type)+ ?.forEach((listener) =>+ listener({ code, key: code === 'Space' ? ' ' : code, preventDefault: () => {}, target: null, type })+ );const persist = () =>dispatch({id: stroke.layerId,@@ -9466,11 +9476,13 @@ describe('edit feedback on the surface', () => {quadraticCurveTo() {}});- const windowListeners = new Map<string, (event: unknown) => void>();+ const windowListeners = new Map<string, Set<(event: unknown) => void>>();vi.stubGlobal('addEventListener', (type: string, listener: (event: unknown) => void) =>- windowListeners.set(type, listener)+ windowListeners.set(type, (windowListeners.get(type) ?? new Set()).add(listener))+ );+ vi.stubGlobal('removeEventListener', (type: string, listener: (event: unknown) => void) =>+ windowListeners.get(type)?.delete(listener));- vi.stubGlobal('removeEventListener', (type: string) => windowListeners.delete(type));const { dispatch, projectId, store } = createReducerBackedStore(document);const stubBackend = createTestStubRasterBackend();const surfaces: StubRasterSurface[] = [];@@ -9493,7 +9505,9 @@ describe('edit feedback on the surface', () => {const refusals: CanvasEditRefusal[] = [];engine.tools.onEditRefused((refusal) => refusals.push(refusal));const key = (type: 'keydown' | 'keyup', code: string) =>- windowListeners.get(type)?.({ code, key: code, preventDefault: () => {}, target: null });+ windowListeners+ .get(type)+ ?.forEach((listener) => listener({ code, key: code, preventDefault: () => {}, target: null, type }));return { dispatch, engine, key, overlay, refusals, surfaces };};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex d67e85d3b4..034b78d79f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -161,7 +161,7 @@ import {type RasterCompositeExportSnapshot,} from '@workbench/canvas-engine/exportRasterComposite';import { createPointerPipeline, type PointerPipeline } from '@workbench/canvas-engine/input/pointerPipeline';-import { createWheelHandler } from '@workbench/canvas-engine/input/wheel';+import { createWheelInput } from '@workbench/canvas-engine/input/wheel';import { isEmpty, union } from '@workbench/canvas-engine/math/rect';import { hasSpatialAdjustments } from '@workbench/canvas-engine/render/adjustments';import { createColorSampler } from '@workbench/canvas-engine/render/colorSample';@@ -393,6 +393,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreClayerPixelEpoch: stores.layerPixelEpoch,documentEpoch: stores.documentEpoch,ruleOfThirds: stores.ruleOfThirds,+ scrollInput: stores.scrollInput,shapeOptions: stores.shapeOptions,showBbox: stores.showBbox,showGrid: stores.showGrid,@@ -402,6 +403,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCvectorEditSession: stores.vectorEditSession,vectorToolsStatus: stores.vectorToolsStatus,textOptions: stores.textOptions,+ trackpadDetected: stores.trackpadDetected,transformOptions: stores.transformOptions,transformSession: stores.transformSession,pendingTransformLayerId: stores.pendingTransformLayerId,@@ -1502,7 +1504,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst renderController = new RenderController({applyCursor: (value) => applyCursorToInput(value),- getInputHandlers: () => ({ ...pipeline, onPointerLeave: onCanvasPointerLeave, onWheel, reset: resetInput }),+ getInputHandlers: () => ({ ...pipeline, ...wheelInput, onPointerLeave: onCanvasPointerLeave, reset: resetInput }),isEngineDisposed: () => disposed,onPageHide: () => onPageHide(),onVisibilityChange: () => onVisibilityChange(),@@ -2019,6 +2021,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCgetKeyOwnerResolver: () => renderController.getKeyOwnerResolver(),getToolContext: () => toolContext,handleEscape: handleEscapePriority,+ hasFocus: () => typeof document === 'undefined' || document.hasFocus(),hasTool: (id) => tools.has(id),isReplaying: () => history.isReplaying(),maybeCommitModalSession: () => commitOpenTextSession(),@@ -2028,13 +2031,20 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCviewport,});- const onWheel = createWheelHandler({+ // A view change under a still pointer moves the document beneath it; hover-derived tool state must follow.+ const unsubscribeHoverRefresh = viewport.subscribe(() => pipeline.refreshHover());++ const wheelInput = createWheelInput({getActiveTool: activeTool,+ getControlKeyState: () => pipeline.controlKeyState(),getInputElement: () => renderController.getInputElement(),getInvertBrushSizeScroll: () => stores.invertBrushSizeScroll.get(),- getToolContext: () => toolContext,+ getScrollInput: () => stores.scrollInput.get(),invalidate: (payload) => scheduler.invalidate(payload),+ isGestureActive: () => pipeline.isGestureActive(),+ onWheelWithoutControl: () => pipeline.onWheelWithoutControl(),stepActiveBrushSize,+ trackpadDetected: stores.trackpadDetected,viewport,});@@ -2049,6 +2059,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst onVisibilityChange = (): void => {if (typeof document !== 'undefined' && document.visibilityState === 'hidden') {kickPendingFlush();+ // Key releases while hidden never arrive; held keys (Space, Alt, Control) must not outlive the page.+ onWindowBlur();}};const onWindowBlur = (): void => {@@ -2631,6 +2643,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCcleanup.run(() => colorSamples.dispose());cleanup.run(() => activeTool()?.onDeactivate?.(toolContext));cleanup.run(unsubscribeViewport);+ cleanup.run(unsubscribeHoverRefresh);cleanup.run(unsubscribeBrushOptions);cleanup.run(unsubscribeEraserOptions);cleanup.run(unsubscribeCheckerboard);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.tsindex 544578cb28..a58e422cfc 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts@@ -225,6 +225,9 @@ export interface ControlLayerView {view: 'original' | 'overlay';}+/** How wheel events route: `auto` judges each one as a mouse wheel or a trackpad. */+export type ScrollInput = 'auto' | 'mouse' | 'trackpad';+export interface TransformOptions {smoothing: boolean;resampleMode: 'bilinear' | 'bicubic' | 'hamming' | 'lanczos';@@ -455,6 +458,9 @@ export interface EngineStores {showGrid: ScalarStore<boolean>;/** Default wheel-up grows. */invertBrushSizeScroll: ScalarStore<boolean>;+ scrollInput: ScalarStore<ScrollInput>;+ /** Set by the engine on trackpad proof, never cleared by it; the frontend persists and restores it. */+ trackpadDetected: ScalarStore<boolean>;/** The active bbox tool always draws its frame and handles. */showBbox: ScalarStore<boolean>;/** Toggling never recomposites document pixels. */@@ -660,6 +666,7 @@ export const createEngineStores = (initialTool: ToolId = 'view'): EngineStores =documentEpoch: createScalarStore<number>(0),ruleOfThirds: createScalarStore<boolean>(false),samInteraction: createScalarStore(null),+ scrollInput: createScalarStore<ScrollInput>('auto'),shapeOptions: createScalarStore<ShapeToolOptions>({ ...DEFAULT_SHAPE_OPTIONS }, shapeOptionsEqual),shapePreview: createScalarStore<{ rect: Rect; kind: ParametricShapeKind } | null>(null, rectShapePreviewEqual),vectorShapePreview: createScalarStore<VectorShapePreview | null>(null),@@ -671,6 +678,7 @@ export const createEngineStores = (initialTool: ToolId = 'view'): EngineStores =stagingHidesOverlays: createScalarStore<boolean>(false),textEditSession: createScalarStore<TextEditSession | null>(null, textEditSessionEqual),textOptions: createScalarStore<TextToolOptions>({ ...DEFAULT_TEXT_OPTIONS }, textOptionsEqual),+ trackpadDetected: createScalarStore<boolean>(false),thumbnailVersion: createKeyedVersionStore(),thumbnailStatus: createKeyedStatusStore<LayerThumbnailStatus>(),adjustmentStatus: createKeyedStatusStore<LayerAdjustmentStatus>(),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.tsindex 1c85e765d1..16c2ca2b85 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@@ -51,6 +51,7 @@ const makeKeyEvent = (init: {repeat?: boolean;shiftKey?: boolean;target?: unknown;+ type?: 'keydown' | 'keyup';}): KeyboardEvent =>({altKey: init.altKey ?? false,@@ -63,6 +64,7 @@ const makeKeyEvent = (init: {repeat: init.repeat ?? false,shiftKey: init.shiftKey ?? false,target: init.target ?? null,+ type: init.type ?? 'keydown',}) as unknown as KeyboardEvent;const SURFACE_TARGET = { tagName: 'DIV' };@@ -72,6 +74,7 @@ const createHarness = (opts: {tools?: ToolId[];handleEscape?: (o: { gestureWasActive: boolean }) => void;+ hasFocus?: () => boolean;maybeCommitModalSession?: () => boolean;replaying?: () => boolean;resolveKeyOwner?: (event: KeyboardEvent) => CanvasKeyOwner;@@ -126,6 +129,7 @@ const createHarness = (getKeyOwnerResolver: () => opts.resolveKeyOwner ?? null,getToolContext: () => ctx,handleEscape: opts.handleEscape,+ hasFocus: opts.hasFocus,hasTool: (id) => registered.has(id),isReplaying: () => opts.replaying?.() ?? false,maybeCommitModalSession: opts.maybeCommitModalSession,@@ -256,6 +260,125 @@ describe('pointer pipeline: middle-mouse pan', () => {});});+describe('pointer pipeline: physical Control key', () => {+ const control = (type: 'keydown' | 'keyup', ctrlKey: boolean) =>+ makeKeyEvent({ code: 'ControlLeft', ctrlKey, key: 'Control', type });++ it('is unknown until a key or pointer event shows it, then follows presses and releases', () => {+ const h = createHarness();+ expect(h.pipeline.controlKeyState()).toBe('unknown');+ h.pipeline.onKeyCapture(control('keydown', true));+ expect(h.pipeline.controlKeyState()).toBe('down');+ // Another key while Control stays down keeps it down.+ h.pipeline.onKeyCapture(makeKeyEvent({ code: 'KeyZ', ctrlKey: true, key: 'z', type: 'keyup' }));+ expect(h.pipeline.controlKeyState()).toBe('down');+ // Browsers may still report ctrlKey on the Control key's own release.+ h.pipeline.onKeyCapture(control('keyup', true));+ expect(h.pipeline.controlKeyState()).toBe('up');+ });++ it('takes the modifier state from pointer events, but a Control-free one shows it up only while focused', () => {+ const focus = { has: true };+ const h = createHarness({ hasFocus: () => focus.has });+ h.pipeline.onPointerMove(makePointerEvent({ buttons: 0, ctrlKey: true }));+ expect(h.pipeline.controlKeyState()).toBe('down');+ h.pipeline.onPointerMove(makePointerEvent({ buttons: 0 }));+ expect(h.pipeline.controlKeyState()).toBe('up');++ focus.has = false;+ h.pipeline.onPointerMove(makePointerEvent({ buttons: 0 }));+ expect(h.pipeline.controlKeyState()).toBe('unknown');+ h.pipeline.onPointerMove(makePointerEvent({ buttons: 0, ctrlKey: true }));+ expect(h.pipeline.controlKeyState()).toBe('down');+ });++ it('takes a wheel event without Control as the key up, but only while focused', () => {+ const focus = { has: true };+ const h = createHarness({ hasFocus: () => focus.has });+ h.pipeline.onWindowFocus();+ h.pipeline.onWheelWithoutControl();+ expect(h.pipeline.controlKeyState()).toBe('up');++ focus.has = false;+ h.pipeline.onWheelWithoutControl();+ expect(h.pipeline.controlKeyState()).toBe('unknown');+ });++ it('becomes unknown whenever focus may have changed hands: window focus, and reset on blur or a hidden page', () => {+ const focused = createHarness();+ focused.pipeline.onKeyCapture(control('keyup', false));+ expect(focused.pipeline.controlKeyState()).toBe('up');+ focused.pipeline.onWindowFocus();+ expect(focused.pipeline.controlKeyState()).toBe('unknown');++ const reset = createHarness();+ reset.pipeline.onKeyCapture(control('keyup', false));+ reset.pipeline.reset();+ expect(reset.pipeline.controlKeyState()).toBe('unknown');+ });+});++describe('pointer pipeline: hover refresh after a view change', () => {+ it('re-delivers the still pointer as a hover move at its new document point', () => {+ const h = createHarness();+ h.pipeline.onPointerEnter();+ h.pipeline.onPointerMove(+ makePointerEvent({ buttons: 0, clientX: 40, clientY: 30, ctrlKey: true, pointerType: 'pen' })+ );+ h.deps.viewport.panBy({ x: 10, y: -20 });+ h.pipeline.refreshHover();++ const last = h.tool.moves.at(-1)!;+ expect(h.tool.moves).toHaveLength(2);+ expect(last.input.screenPoint).toEqual({ x: 40, y: 30 });+ expect(last.input.documentPoint).toEqual({ x: 30, y: 50 });+ expect(last.input.buttons).toBe(0);+ expect(last.input.modifiers.ctrl).toBe(true);+ expect(last.input.pointerType).toBe('pen');+ expect(last.batch).toEqual([last.input]);+ });++ it('sends hover pressure, not the pressure of the stroke that ended under the still pen', () => {+ const h = createHarness();+ h.pipeline.onPointerEnter();+ h.pipeline.onPointerDown(makePointerEvent({ clientX: 40, pointerType: 'pen', pressure: 0.9 }));+ h.pipeline.onPointerMove(makePointerEvent({ clientX: 41, pointerType: 'pen', pressure: 0.8 }));+ h.pipeline.onPointerUp(makePointerEvent({ buttons: 0, clientX: 41, pointerType: 'pen', pressure: 0 }));+ h.deps.viewport.panBy({ x: 10, y: 0 });+ h.pipeline.refreshHover();++ const refreshed = h.tool.moves.at(-1)!.input;+ expect(h.tool.moves).toHaveLength(2);+ // A hovering pen reports no pressure, which tool input carries as the 0.5 default.+ expect(refreshed.pressure).toBe(0.5);+ expect(refreshed.buttons).toBe(0);+ expect(refreshed.pointerType).toBe('pen');+ });++ it('delivers nothing off the canvas, during a gesture, or during a middle-button pan', () => {+ const left = createHarness();+ left.pipeline.onPointerEnter();+ left.pipeline.onPointerMove(makePointerEvent({ buttons: 0, clientX: 5 }));+ left.pipeline.onPointerLeave();+ left.pipeline.refreshHover();+ expect(left.tool.moves).toHaveLength(1);++ const painting = createHarness();+ painting.pipeline.onPointerDown(makePointerEvent({ clientX: 5 }));+ painting.pipeline.onPointerMove(makePointerEvent({ clientX: 6 }));+ painting.pipeline.refreshHover();+ expect(painting.tool.moves).toHaveLength(1);++ const middle = createHarness();+ middle.pipeline.onPointerEnter();+ middle.pipeline.onPointerMove(makePointerEvent({ buttons: 0, clientX: 5 }));+ middle.pipeline.onPointerDown(makePointerEvent({ button: 1, buttons: 4, clientX: 5 }));+ middle.pipeline.onPointerMove(makePointerEvent({ buttons: 4, clientX: 25 }));+ middle.pipeline.refreshHover();+ expect(middle.tool.moves).toHaveLength(1);+ });+});+describe('pointer pipeline: multi-pointer isolation during an active gesture', () => {it('ignores move events from a second pointer while the first pointer is gesturing', () => {const h = createHarness();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.tsindex e201ca036c..1a07b3d295 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.ts@@ -12,6 +12,8 @@ const ALT_TEMP_TOOL: ToolId = 'colorPicker';const SPACE_TEMP_TOOL: ToolId = 'view';const BBOX_TEMP_TOOL: ToolId = 'bbox';const BBOX_QUICK_TAP_MS = 180;+/** Tool pressure for a pointer that reports none: a mouse, and any pointer while it hovers (the DOM reports 0). */+const UNREPORTED_PRESSURE = 0.5;export interface PointerPipelineDeps {viewport: Viewport;@@ -33,8 +35,13 @@ export interface PointerPipelineDeps {isReplaying(): boolean;/** Middle-button pans do not count. */onGestureChange?(active: boolean): void;+ /** Absent means focused. Unfocused, a pointer event's modifiers miss Control presses the page cannot see. */+ hasFocus?(): boolean;}+/** Whether the physical Control key is down, as far as the pipeline has seen. */+export type ControlKeyState = 'down' | 'up' | 'unknown';+export interface PointerPipeline {onPointerDown(event: PointerEvent): void;onPointerMove(event: PointerEvent): void;@@ -45,11 +52,21 @@ export interface PointerPipeline {onPointerLeave(): void;onKeyDown(event: KeyboardEvent): void;onKeyUp(event: KeyboardEvent): void;+ /** Capture-phase window key events, so a handler that stops propagation cannot hide Control. */+ onKeyCapture(event: KeyboardEvent): void;+ /** A Control press or release made while the window was away went unseen. */+ onWindowFocus(): void;+ /** A wheel event without Control shows the key up; one with it may be a pinch, which says nothing. */+ onWheelWithoutControl(): void;/** Records whether focus arrived by pointer, which decides hold-key ownership. */onFocusIn(event: FocusEvent): void;isGestureActive(): boolean;/** CSS pixels, including middle-pan moves; null once it left outside a gesture. */hoverPoint(): Vec2 | null;+ /** `unknown` until a key or a focused pointer or plain wheel event shows it, and again once focus may have moved. */+ controlKeyState(): ControlKeyState;+ /** Re-delivers a hover move after the view moved under a still pointer; skipped mid-gesture. */+ refreshHover(): void;/** Used on document replacement so a later release cannot commit stale drag state. */cancelActiveGesture(): void;/** Ends any held temporary tool, so a later key release restores nothing. */@@ -132,6 +149,9 @@ const isDocumentRootTarget = (target: EventTarget | null): boolean => {export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipeline => {let hovered = false;let hoverPoint: Vec2 | null = null;+ let controlKey: ControlKeyState = 'unknown';+ // The last move a tool received, so a hover refresh keeps its pointer type and modifiers.+ let lastToolMove: PointerInput | null = null;let gestureActive = false;let activePointerId: number | null = null;let middlePanning = false;@@ -155,6 +175,18 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelinconst inputOrigin = (): { left: number; top: number } =>deps.getInputElement()?.getBoundingClientRect() ?? { left: 0, top: 0 };+ const observeControlUp = (): void => {+ controlKey = deps.hasFocus?.() === false ? 'unknown' : 'up';+ };++ const observePointerControl = (event: PointerEvent): void => {+ if (event.ctrlKey) {+ controlKey = 'down';+ } else {+ observeControlUp();+ }+ };+const buildPointerInput = (event: PointerEvent, origin = inputOrigin()): PointerInput => {const screenPoint: Vec2 = { x: event.clientX - origin.left, y: event.clientY - origin.top };return {@@ -162,7 +194,7 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelindocumentPoint: deps.viewport.screenToDocument(screenPoint),modifiers: { alt: event.altKey, ctrl: event.ctrlKey, meta: event.metaKey, shift: event.shiftKey },pointerType: toPointerType(event.pointerType),- pressure: event.pressure > 0 ? event.pressure : 0.5,+ pressure: event.pressure > 0 ? event.pressure : UNREPORTED_PRESSURE,screenPoint,timeStamp: event.timeStamp,};@@ -353,6 +385,11 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelinendTempTool();}},+ onKeyCapture: (event) => {+ // Browsers may still report ctrlKey on the Control key's own release.+ const released = event.type === 'keyup' && event.key === 'Control';+ controlKey = !released && (event.key === 'Control' || event.ctrlKey) ? 'down' : 'up';+ },onKeyDown: (event) => {if (event.key === 'Escape') {const gestureWasActive = gestureActive;@@ -416,6 +453,7 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelindeps.getActiveTool()?.onModifierKey?.(deps.getToolContext(), 'Shift', true);}},+ controlKeyState: () => controlKey,heldRestoreToolId: () => (tempHold && tempSwitched ? priorToolId : null),hoverPoint: () => hoverPoint,isGestureActive: () => gestureActive,@@ -458,6 +496,7 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelincancelGesture();},onPointerDown: (event) => {+ observePointerControl(event);if (gestureActive || middlePanning) {return;}@@ -515,6 +554,7 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelinif (activePointerId !== null && event.pointerId !== activePointerId) {return;}+ observePointerControl(event);const origin = inputOrigin();hoverPoint = { x: event.clientX - origin.left, y: event.clientY - origin.top };if (middlePanning && middleLast) {@@ -534,6 +574,7 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelinif (!last) {return;}+ lastToolMove = last;deps.getActiveTool()?.onPointerMove?.(deps.getToolContext(), last, batch);},onPointerUp: (event) => {@@ -561,11 +602,28 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelinendTempTool();}},+ onWheelWithoutControl: observeControlUp,+ onWindowFocus: () => {+ controlKey = 'unknown';+ },replaceTemporaryRestoreTool: (current, replacement) => {if (tempHold && priorToolId === current) {priorToolId = replacement;}},+ refreshHover: () => {+ if (!hovered || !hoverPoint || !lastToolMove || gestureActive || middlePanning) {+ return;+ }+ const input: PointerInput = {+ ...lastToolMove,+ buttons: 0,+ documentPoint: deps.viewport.screenToDocument(hoverPoint),+ pressure: UNREPORTED_PRESSURE,+ screenPoint: hoverPoint,+ };+ deps.getActiveTool()?.onPointerMove?.(deps.getToolContext(), input, [input]);+ },reset: () => {cancelGesture();if (tempHold) {@@ -582,6 +640,8 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelinaltClaimed = false;hovered = false;hoverPoint = null;+ lastToolMove = null;+ controlKey = 'unknown';gestureActive = false;activePointerId = null;cancelledPointerId = null;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/wheel.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/wheel.test.tsindex 4d30d5fabb..93ca609d8e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/wheel.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/wheel.test.ts@@ -1,88 +1,263 @@-import type { WheelHandlerDeps } from '@workbench/canvas-engine/input/wheel';-import type { Tool, ToolContext } from '@workbench/canvas-engine/tools/tool';+import type { ScrollInput } from '@workbench/canvas-engine/engineStores';+import type { ControlKeyState } from '@workbench/canvas-engine/input/pointerPipeline';+import type { Tool } from '@workbench/canvas-engine/tools/tool';import type { ToolId } from '@workbench/canvas-engine/types';-import { createWheelHandler } from '@workbench/canvas-engine/input/wheel';+import { createWheelInput } from '@workbench/canvas-engine/input/wheel';import { createViewport } from '@workbench/canvas-engine/viewport';import { describe, expect, it, vi } from 'vitest';-const makeWheelEvent = (deltaY: number, opts: { ctrlKey?: boolean } = {}): WheelEvent =>- ({- altKey: false,- clientX: 10,- clientY: 10,- ctrlKey: opts.ctrlKey ?? false,- deltaY,- metaKey: false,- preventDefault: vi.fn(),- shiftKey: false,- }) as unknown as WheelEvent;--const createHarness = (tool: Tool | undefined, invertBrushSizeScroll = false) => {+interface WheelInit {+ ctrlKey?: boolean;+ deltaMode?: number;+ deltaX?: number;+ wheelDeltaY?: number;+}++const ANCHOR = { x: 10, y: 10 };++const createHarness = (+ opts: {+ controlKey?: ControlKeyState;+ gestureActive?: boolean;+ invertBrushSizeScroll?: boolean;+ scrollInput?: ScrollInput;+ tool?: ToolId;+ trackpadDetected?: boolean;+ } = {}+) => {const viewport = createViewport();const stepActiveBrushSize = vi.fn();const invalidate = vi.fn();- const deps: WheelHandlerDeps = {+ const detected = { value: opts.trackpadDetected ?? false };+ const tool: Tool = { id: opts.tool ?? 'brush' };+ let controlKey = opts.controlKey ?? 'down';+ const input = createWheelInput({getActiveTool: () => tool,+ getControlKeyState: () => controlKey,getInputElement: () => ({ getBoundingClientRect: () => ({ left: 0, top: 0 }) }) as unknown as HTMLElement,- getInvertBrushSizeScroll: () => invertBrushSizeScroll,- getToolContext: () => ({}) as ToolContext,+ getInvertBrushSizeScroll: () => opts.invertBrushSizeScroll ?? false,+ getScrollInput: () => opts.scrollInput ?? 'auto',invalidate,+ isGestureActive: () => opts.gestureActive ?? false,+ // As the focused pipeline does.+ onWheelWithoutControl: () => {+ controlKey = 'up';+ },stepActiveBrushSize,+ trackpadDetected: {+ get: () => detected.value,+ set: (value) => {+ detected.value = value;+ },+ },viewport,+ });+ // Each event starts its own stream unless a test says otherwise.+ let timeStamp = 0;+ const wheel = (deltaY: number, init: WheelInit = {}): void => {+ timeStamp += 1000;+ input.onWheel({+ clientX: ANCHOR.x,+ clientY: ANCHOR.y,+ ctrlKey: init.ctrlKey ?? false,+ deltaMode: init.deltaMode ?? 0,+ deltaX: init.deltaX ?? 0,+ deltaY,+ preventDefault: vi.fn(),+ timeStamp,+ wheelDeltaY: init.wheelDeltaY ?? 0,+ } as unknown as WheelEvent);};- return { handler: createWheelHandler(deps), invalidate, stepActiveBrushSize, viewport };+ const notch = (direction: 1 | -1, init: WheelInit = {}) =>+ wheel(100 * direction, { wheelDeltaY: -120 * direction, ...init });+ const smooth = (deltaY: number, init: WheelInit = {}) => wheel(deltaY, { wheelDeltaY: -3 * deltaY, ...init });+ const wheelZoom = vi.spyOn(viewport, 'wheelZoom');+ return { detected, input, invalidate, notch, smooth, stepActiveBrushSize, viewport, wheel, wheelZoom };};-const toolWithId = (id: ToolId, onWheel?: Tool['onWheel']): Tool => ({ id, onWheel });+describe('wheel input: mouse wheel', () => {+ it('zooms around the pointer, whatever the event looks like', () => {+ const h = createHarness({ scrollInput: 'mouse' });+ h.notch(-1);+ h.smooth(-6, { deltaX: 2 });+ expect(h.wheelZoom.mock.calls).toEqual([+ [-100, ANCHOR],+ [-6, ANCHOR],+ ]);+ expect(h.invalidate).toHaveBeenCalledWith({ view: true });+ expect(h.detected.value).toBe(false);+ });++ it('steps the brush or eraser size on ctrl+wheel, inverted by the preference', () => {+ const brush = createHarness({ scrollInput: 'mouse' });+ brush.notch(-1, { ctrlKey: true });+ brush.notch(1, { ctrlKey: true });+ expect(brush.stepActiveBrushSize.mock.calls).toEqual([[1], [-1]]);++ const inverted = createHarness({ invertBrushSizeScroll: true, scrollInput: 'mouse', tool: 'eraser' });+ inverted.notch(-1, { ctrlKey: true });+ expect(inverted.stepActiveBrushSize).toHaveBeenCalledWith(-1);+ });++ it('swallows ctrl+wheel for other tools', () => {+ const h = createHarness({ scrollInput: 'mouse', tool: 'view' });+ h.notch(-1, { ctrlKey: true });+ expect(h.stepActiveBrushSize).not.toHaveBeenCalled();+ expect(h.wheelZoom).not.toHaveBeenCalled();+ expect(h.viewport.getState()).toEqual({ pan: { x: 0, y: 0 }, zoom: 1 });+ });+});++describe('wheel input: trackpad', () => {+ it('pans on both axes so content follows the fingers, a notch included', () => {+ const h = createHarness({ scrollInput: 'trackpad', tool: 'view' });+ h.smooth(30, { deltaX: -12 });+ h.notch(1);+ expect(h.viewport.getState()).toEqual({ pan: { x: 12, y: -130 }, zoom: 1 });+ expect(h.invalidate).toHaveBeenCalledWith({ view: true });+ });++ it('zooms continuously around the pointer on ctrl+wheel, at most 1.25x per event, without sizing the brush', () => {+ const h = createHarness({ scrollInput: 'trackpad' });+ const documentUnderPointer = h.viewport.screenToDocument(ANCHOR);+ h.smooth(-10, { ctrlKey: true });+ expect(h.viewport.getZoom()).toBeCloseTo(Math.exp(0.1), 10);+ const after = h.viewport.screenToDocument(ANCHOR);+ expect(after.x).toBeCloseTo(documentUnderPointer.x, 10);+ expect(after.y).toBeCloseTo(documentUnderPointer.y, 10);++ h.notch(1, { ctrlKey: true });+ expect(h.viewport.getZoom()).toBeCloseTo(Math.exp(0.1) / 1.25, 10);+ expect(h.stepActiveBrushSize).not.toHaveBeenCalled();+ });+});-describe('wheel handler: ctrl+wheel brush size step', () => {- it('grows the size on ctrl+wheel-up when brush is active', () => {- const h = createHarness(toolWithId('brush'));- h.handler(makeWheelEvent(-100, { ctrlKey: true }));+describe('wheel input: auto', () => {+ it('zooms on a notch and sizes the brush on ctrl+notch, even after a trackpad was detected', () => {+ const h = createHarness({ trackpadDetected: true });+ h.notch(-1);+ h.notch(-1, { ctrlKey: true });+ expect(h.wheelZoom.mock.calls).toEqual([[-100, ANCHOR]]);expect(h.stepActiveBrushSize).toHaveBeenCalledWith(1);});- it('shrinks the size on ctrl+wheel-down when eraser is active', () => {- const h = createHarness(toolWithId('eraser'));- h.handler(makeWheelEvent(100, { ctrlKey: true }));- expect(h.stepActiveBrushSize).toHaveBeenCalledWith(-1);+ it('zooms on smooth scrolling until a trackpad is detected, then pans', () => {+ const h = createHarness();+ h.smooth(-6);+ expect(h.wheelZoom).toHaveBeenCalledWith(-6, ANCHOR);++ h.detected.value = true;+ h.smooth(-6);+ expect(h.wheelZoom).toHaveBeenCalledOnce();+ expect(h.viewport.getState().pan).toEqual({ x: 0, y: 6 });+ });++ it('detects a trackpad from a two-axis event and pans by that event', () => {+ const h = createHarness();+ h.smooth(6, { deltaX: 2 });+ expect(h.detected.value).toBe(true);+ expect(h.wheelZoom).not.toHaveBeenCalled();+ expect(h.viewport.getState().pan).toEqual({ x: -2, y: -6 });+ });++ it.each(['up', 'unknown'] as const)(+ 'detects a pinch, a whole-tick ctrl+wheel step with Control %s, and zooms by it instead of sizing the brush',+ (controlKey) => {+ const h = createHarness({ controlKey });+ // Chromium stamps each pinch step as one whole wheel tick.+ h.wheel(-10, { ctrlKey: true, wheelDeltaY: 120 });+ expect(h.detected.value).toBe(true);+ expect(h.stepActiveBrushSize).not.toHaveBeenCalled();+ expect(h.viewport.getZoom()).toBeCloseTo(Math.exp(0.1), 10);+ }+ );++ it('sizes the brush on a whole-tick ctrl+wheel step while Control is held', () => {+ const h = createHarness({ controlKey: 'down' });+ h.wheel(-10, { ctrlKey: true, wheelDeltaY: 120 });+ expect(h.stepActiveBrushSize).toHaveBeenCalledWith(1);+ expect(h.detected.value).toBe(false);});- it('inverts the step direction when the invert-scroll preference is on', () => {- const grow = createHarness(toolWithId('brush'), true);- grow.handler(makeWheelEvent(-100, { ctrlKey: true }));- expect(grow.stepActiveBrushSize).toHaveBeenCalledWith(-1);+ it('zooms by a pinch whose first step is large, which Chromium also stamps as a whole tick', () => {+ const h = createHarness({ controlKey: 'up' });+ h.wheel(-30, { ctrlKey: true, wheelDeltaY: 120 });+ expect(h.stepActiveBrushSize).not.toHaveBeenCalled();+ expect(h.viewport.getZoom()).toBeCloseTo(1.25, 10);+ });- const shrink = createHarness(toolWithId('eraser'), true);- shrink.handler(makeWheelEvent(100, { ctrlKey: true }));- expect(shrink.stepActiveBrushSize).toHaveBeenCalledWith(1);+ it('sizes the brush on a ctrl+notch that arrives with Control up, as Sticky Keys sends it', () => {+ const h = createHarness({ controlKey: 'up' });+ h.notch(-1, { ctrlKey: true });+ h.wheel(-3, { ctrlKey: true, deltaMode: 1 });+ expect(h.stepActiveBrushSize.mock.calls).toEqual([[1], [1]]);+ expect(h.detected.value).toBe(false);});- it('swallows ctrl+wheel (no size step, no zoom) for non-paint tools', () => {- const h = createHarness(toolWithId('view'));- const wheelZoom = vi.spyOn(h.viewport, 'wheelZoom');- h.handler(makeWheelEvent(-100, { ctrlKey: true }));+ it('reads an unstamped pinch, as Firefox sends it, once a plain scroll after focus showed Control up', () => {+ const h = createHarness({ controlKey: 'unknown' });+ h.smooth(4);+ h.smooth(-10, { ctrlKey: true });+ expect(h.detected.value).toBe(true);expect(h.stepActiveBrushSize).not.toHaveBeenCalled();- expect(wheelZoom).not.toHaveBeenCalled();+ });++ it('sizes the brush on smooth ctrl+wheel while Control may be held', () => {+ for (const controlKey of ['down', 'unknown'] as const) {+ const h = createHarness({ controlKey });+ h.smooth(-4, { ctrlKey: true });+ expect(h.detected.value).toBe(false);+ expect(h.stepActiveBrushSize).toHaveBeenCalledWith(1);+ }+ });++ it('pans on a sideways-only wheel before detection, without detecting, in pixels or lines', () => {+ const h = createHarness();+ h.wheel(0, { deltaX: 8 });+ h.wheel(0, { deltaMode: 1, deltaX: 1 });+ expect(h.viewport.getState().pan).toEqual({ x: -24, y: 0 });+ expect(h.wheelZoom).not.toHaveBeenCalled();+ expect(h.detected.value).toBe(false);+ });++ it('measures line-mode deltas at 16px per line', () => {+ const h = createHarness({ trackpadDetected: true });+ h.wheel(3, { deltaMode: 1 });+ expect(h.wheelZoom).toHaveBeenCalledWith(48, ANCHOR);++ const trackpad = createHarness({ scrollInput: 'trackpad' });+ trackpad.wheel(3, { deltaMode: 1, deltaX: 1 });+ expect(trackpad.viewport.getState().pan).toEqual({ x: -16, y: -48 });});});-describe('wheel handler: plain wheel', () => {- it('zooms the viewport when the active tool defines no onWheel', () => {- const h = createHarness(toolWithId('brush'));- const wheelZoom = vi.spyOn(h.viewport, 'wheelZoom');- h.handler(makeWheelEvent(-120));- expect(wheelZoom).toHaveBeenCalledWith(-120, { x: 10, y: 10 });- expect(h.invalidate).toHaveBeenCalledWith({ view: true });+const pinchGesture = (h: ReturnType<typeof createHarness>, type: 'gesturestart' | 'gesturechange', scale: number) => {+ const event = { clientX: ANCHOR.x, clientY: ANCHOR.y, preventDefault: vi.fn(), scale, type };+ (type === 'gesturestart' ? h.input.onPinchGestureStart : h.input.onPinchGestureChange)(event as unknown as Event);+ return event.preventDefault;+};++describe('wheel input: Safari pinch gesture', () => {+ it('leaves the view alone while a pointer gesture is under way, as an iPad touch pinch mid-stroke', () => {+ const h = createHarness({ gestureActive: true });+ expect(pinchGesture(h, 'gesturestart', 1)).toHaveBeenCalled();+ expect(pinchGesture(h, 'gesturechange', 2)).toHaveBeenCalled();+ expect(h.viewport.getZoom()).toBe(1);+ expect(h.detected.value).toBe(false);});- it('routes to the active tool onWheel when present', () => {- const onWheel = vi.fn();- const h = createHarness(toolWithId('view', onWheel));- const wheelZoom = vi.spyOn(h.viewport, 'wheelZoom');- h.handler(makeWheelEvent(-120));- expect(onWheel).toHaveBeenCalledTimes(1);- expect(wheelZoom).not.toHaveBeenCalled();+ it('zooms by the gesture scale from its start, around the pointer, and detects a trackpad in any mode', () => {+ const h = createHarness({ scrollInput: 'mouse' });+ h.viewport.zoomAtPoint(2, ANCHOR);+ const documentUnderPointer = h.viewport.screenToDocument(ANCHOR);+ expect(pinchGesture(h, 'gesturestart', 1)).toHaveBeenCalled();+ pinchGesture(h, 'gesturechange', 1.5);+ expect(pinchGesture(h, 'gesturechange', 0.5)).toHaveBeenCalled();+ expect(h.viewport.getZoom()).toBeCloseTo(1, 10);+ const after = h.viewport.screenToDocument(ANCHOR);+ expect(after.x).toBeCloseTo(documentUnderPointer.x, 10);+ expect(after.y).toBeCloseTo(documentUnderPointer.y, 10);+ expect(h.detected.value).toBe(true);});});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/wheel.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/wheel.tsindex cd0508b861..97c090eb4d 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/wheel.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/wheel.ts@@ -1,57 +1,136 @@/**- * Plain wheel routes to the tool or cursor-centered zoom. Ctrl+wheel sizes brush/eraser and is otherwise swallowed.- * Injected dependencies keep routing testable without DOM setup.+ * Mouse wheel: plain wheel zooms around the cursor, resting on snap points; ctrl+wheel sizes brush/eraser and is+ * otherwise swallowed. Trackpad: plain wheel pans on both axes for every tool; ctrl+wheel, how browsers deliver a+ * pinch, zooms continuously around the cursor. `scrollInput` picks one, or `auto` judges each event (`wheelDevice.ts`);+ * a two-axis event or a pinch proves a trackpad.*/+import type { ScalarStore, ScrollInput } from '@workbench/canvas-engine/engineStores';+import type { ControlKeyState } from '@workbench/canvas-engine/input/pointerPipeline';+import type { WheelSample } from '@workbench/canvas-engine/input/wheelDevice';import type { InvalidatePayload } from '@workbench/canvas-engine/render/scheduler';-import type { Tool, ToolContext } from '@workbench/canvas-engine/tools/tool';-import type { PointerModifiers, Vec2 } from '@workbench/canvas-engine/types';+import type { Tool } from '@workbench/canvas-engine/tools/tool';+import type { Vec2 } from '@workbench/canvas-engine/types';import type { Viewport } from '@workbench/canvas-engine/viewport';+import { createWheelDeviceClassifier } from '@workbench/canvas-engine/input/wheelDevice';+export interface WheelHandlerDeps {viewport: Viewport;invalidate(payload: InvalidatePayload): void;getInputElement(): HTMLElement | null;getActiveTool(): Tool | undefined;- getToolContext(): ToolContext;/** Steps the active brush/eraser diameter by one notch (`+1` grow, `-1` shrink). */stepActiveBrushSize(direction: 1 | -1): void;/** Inverts ctrl+wheel brush sizing (default false: wheel-up grows); a user preference read fresh per event. */getInvertBrushSizeScroll(): boolean;+ getScrollInput(): ScrollInput;+ /** The physical Control key; a pinch's ctrl+wheel arrives with it `up` or, right after window focus, `unknown`. */+ getControlKeyState(): ControlKeyState;+ /** A wheel without ctrlKey shows Control up, so a pinch that follows a scroll right after focus is known as one. */+ onWheelWithoutControl(): void;+ /** Set on trackpad proof; gates `auto` routing of smooth scrolling. */+ trackpadDetected: Pick<ScalarStore<boolean>, 'get' | 'set'>;+ /** A pointer gesture is under way: iPadOS also sends pinch gesture events for touches, mid-stroke. */+ isGestureActive(): boolean;+}++export interface WheelInputHandlers {+ onWheel(event: WheelEvent): void;+ /** Safari sends a trackpad pinch as these instead of ctrl+wheel; unhandled, it magnifies the page. */+ onPinchGestureStart(event: Event): void;+ onPinchGestureChange(event: Event): void;+}++/** Safari's non-standard `GestureEvent`, absent from lib.dom; `scale` is relative to the gesture's start. */+interface SafariGestureEvent extends Event {+ readonly scale: number;+ readonly clientX: number;+ readonly clientY: number;}-const modifiersOf = (event: WheelEvent): PointerModifiers => ({- alt: event.altKey,- ctrl: event.ctrlKey,- meta: event.metaKey,- shift: event.shiftKey,-});+/** Browser pinch steps are a few pixels each; matches the image map's pinch gain. */+const PINCH_ZOOM_GAIN = 0.01;+/** Bounds a ctrl+mouse-wheel notch (~100px, e^1 unbounded) while leaving pinch steps untouched. */+const MAX_PINCH_ZOOM_STEP = 1.25;-export const createWheelHandler = (deps: WheelHandlerDeps): ((event: WheelEvent) => void) => {- return (event: WheelEvent): void => {- event.preventDefault();+const pinchZoomFactor = (deltaY: number): number =>+ Math.min(MAX_PINCH_ZOOM_STEP, Math.max(1 / MAX_PINCH_ZOOM_STEP, Math.exp(-deltaY * PINCH_ZOOM_GAIN)));+export const createWheelInput = (deps: WheelHandlerDeps): WheelInputHandlers => {+ const classify = createWheelDeviceClassifier();+ // Null while the pinch belongs to a touch that is already drawing.+ let gestureStartZoom: number | null = null;++ const screenAnchor = (event: { clientX: number; clientY: number }): Vec2 => {const rect = deps.getInputElement()?.getBoundingClientRect();- const screenAnchor: Vec2 = { x: event.clientX - (rect?.left ?? 0), y: event.clientY - (rect?.top ?? 0) };+ return { x: event.clientX - (rect?.left ?? 0), y: event.clientY - (rect?.top ?? 0) };+ };- const tool = deps.getActiveTool();+ const routesAsTrackpad = (sample: WheelSample): boolean => {+ const scrollInput = deps.getScrollInput();+ if (scrollInput !== 'auto') {+ return scrollInput === 'trackpad';+ }+ // A sideways-only wheel has nothing to zoom by.+ if (sample.deltaY === 0 && sample.deltaX !== 0) {+ return true;+ }+ if (sample.kind === 'notched') {+ return false;+ }+ if (sample.twoAxis || sample.pinch) {+ deps.trackpadDetected.set(true);+ }+ // Until a trackpad shows itself, smooth scrolling may be a high-resolution mouse wheel, which zooms.+ return deps.trackpadDetected.get();+ };- // Ctrl+wheel: brush/eraser size step, else reserved (pinch-zoom) — swallowed.- if (event.ctrlKey) {- if (tool && (tool.id === 'brush' || tool.id === 'eraser')) {- // Default: wheel-up (deltaY < 0) grows. The inversion preference flips it.- const grow = event.deltaY < 0;- const stepUp = grow !== deps.getInvertBrushSizeScroll();- deps.stepActiveBrushSize(stepUp ? 1 : -1);+ return {+ onPinchGestureChange: (event) => {+ event.preventDefault();+ if (gestureStartZoom === null) {+ return;}- return;- }+ const gesture = event as SafariGestureEvent;+ deps.trackpadDetected.set(true);+ deps.viewport.zoomAtPoint(gestureStartZoom * gesture.scale, screenAnchor(gesture));+ deps.invalidate({ view: true });+ },+ onPinchGestureStart: (event) => {+ event.preventDefault();+ gestureStartZoom = deps.isGestureActive() ? null : deps.viewport.getZoom();+ },+ onWheel: (event) => {+ event.preventDefault();+ if (!event.ctrlKey) {+ deps.onWheelWithoutControl();+ }+ const sample = classify(event, deps.viewport.getViewportSize(), deps.getControlKeyState());+ const anchor = screenAnchor(event);- if (tool?.onWheel) {- tool.onWheel(deps.getToolContext(), event.deltaY, screenAnchor, modifiersOf(event));- return;- }- deps.viewport.wheelZoom(event.deltaY, screenAnchor);- deps.invalidate({ view: true });+ if (routesAsTrackpad(sample)) {+ if (event.ctrlKey) {+ deps.viewport.zoomAtPoint(deps.viewport.getZoom() * pinchZoomFactor(sample.deltaY), anchor);+ } else {+ // Content follows the fingers, as native scrolling moves a page.+ deps.viewport.panBy({ x: -sample.deltaX, y: -sample.deltaY });+ }+ deps.invalidate({ view: true });+ return;+ }++ if (event.ctrlKey) {+ const tool = deps.getActiveTool();+ if ((tool?.id === 'brush' || tool?.id === 'eraser') && sample.deltaY !== 0) {+ const grow = sample.deltaY < 0;+ deps.stepActiveBrushSize(grow !== deps.getInvertBrushSizeScroll() ? 1 : -1);+ }+ return;+ }++ deps.viewport.wheelZoom(sample.deltaY, anchor);+ deps.invalidate({ view: true });+ },};};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/wheelDevice.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/wheelDevice.test.tsnew file mode 100644index 0000000000..a60fc6bbc7--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/wheelDevice.test.ts@@ -0,0 +1,146 @@+import type { WheelEventShape } from '@workbench/canvas-engine/input/wheelDevice';++import { createWheelDeviceClassifier } from '@workbench/canvas-engine/input/wheelDevice';+import { describe, expect, it } from 'vitest';++const VIEWPORT = { height: 600, width: 800 };++const wheel = (deltaY: number, init: Partial<WheelEventShape> = {}): WheelEventShape => ({+ ctrlKey: false,+ deltaMode: 0,+ deltaX: 0,+ deltaY,+ timeStamp: 0,+ ...init,+});++describe('wheel device classifier', () => {+ it.each<[string, WheelEventShape, 'notched' | 'smooth']>([+ ['a Chromium notch', wheel(100, { wheelDeltaY: -120 }), 'notched'],+ ['a Firefox line-mode notch', wheel(3, { deltaMode: 1 }), 'notched'],+ ['a macOS non-precise wheel notch', wheel(4.000244140625 * 3, { wheelDeltaY: -36 }), 'notched'],+ ['a Chromium notch on Wayland', wheel(150, { wheelDeltaY: -180 }), 'notched'],+ ['a small trackpad delta', wheel(3, { wheelDeltaY: -9 }), 'smooth'],+ ['a Chromium pinch step, stamped as one tick', wheel(-2.4, { wheelDeltaY: 120 }), 'smooth'],+ ['a two-axis trackpad delta', wheel(6, { deltaX: 1.5, wheelDeltaY: -18 }), 'smooth'],+ ])('reads %s', (_name, event, kind) => {+ expect(createWheelDeviceClassifier()(event, VIEWPORT, 'down').kind).toBe(kind);+ });++ it('reads a large first pinch step as smooth, but still a notch-sized one as a notch', () => {+ const pinch = { ctrlKey: true, wheelDeltaY: 120 };+ expect(createWheelDeviceClassifier()(wheel(-30, pinch), VIEWPORT, 'up')).toMatchObject({+ kind: 'smooth',+ pinch: true,+ });+ expect(createWheelDeviceClassifier()(wheel(-100, pinch), VIEWPORT, 'up')).toMatchObject({+ kind: 'notched',+ pinch: false,+ });+ });++ it('reads no pinch, with Control unknown, without ctrl or without Chromium’s whole-tick stamp', () => {+ const pinch = (event: WheelEventShape) => createWheelDeviceClassifier()(event, VIEWPORT, 'unknown').pinch;+ expect(pinch(wheel(-2.4, { wheelDeltaY: 120 }))).toBe(false);+ expect(pinch(wheel(-4, { ctrlKey: true, wheelDeltaY: 12 }))).toBe(false);+ });++ it('reads deltaMode before the deltas, as Firefox reports a line-mode wheel in pixels otherwise', () => {+ let modeRead = false;+ const firefoxWheel: WheelEventShape = {+ get deltaMode() {+ modeRead = true;+ return 1;+ },+ ctrlKey: false,+ deltaX: 0,+ get deltaY() {+ return modeRead ? 3 : 57;+ },+ timeStamp: 0,+ };+ expect(createWheelDeviceClassifier()(firefoxWheel, VIEWPORT, 'down')).toMatchObject({+ deltaY: 48,+ kind: 'notched',+ });+ });++ it('normalizes lines to 16px and pages to the viewport size', () => {+ const classify = createWheelDeviceClassifier();+ expect(classify(wheel(3, { deltaMode: 1, deltaX: -1 }), VIEWPORT, 'down')).toMatchObject({+ deltaX: -16,+ deltaY: 48,+ });+ expect(classify(wheel(1, { deltaMode: 2, deltaX: 0.5 }), VIEWPORT, 'down')).toMatchObject({+ deltaX: 400,+ deltaY: 600,+ });+ });++ it('keeps a trackpad stream smooth through a notch-looking delta, and re-judges after a 200ms pause', () => {+ const classify = createWheelDeviceClassifier();+ expect(classify(wheel(3, { timeStamp: 0 }), VIEWPORT, 'down').kind).toBe('smooth');+ expect(classify(wheel(60, { timeStamp: 16, wheelDeltaY: -120 }), VIEWPORT, 'down').kind).toBe('smooth');+ expect(classify(wheel(60, { timeStamp: 216, wheelDeltaY: -120 }), VIEWPORT, 'down').kind).toBe('smooth');+ expect(classify(wheel(60, { timeStamp: 420, wheelDeltaY: -120 }), VIEWPORT, 'down').kind).toBe('notched');+ });++ it.each<[string, [number, number][], ('notched' | 'smooth')[]]>([+ [+ 'a flick that starts at 50px or more',+ [+ [60, -180],+ [50, -150],+ [30, -90],+ [12, -36],+ [5, -15],+ ],+ ['notched', 'notched', 'smooth', 'smooth', 'smooth'],+ ],+ [+ 'a flick that starts with a whole tick',+ [+ [40, -120],+ [20, -60],+ [8, -24],+ ],+ ['notched', 'smooth', 'smooth'],+ ],+ ])(+ 'turns a notched stream smooth on the first vertical event that is not notch-shaped: %s',+ (_name, events, kinds) => {+ const classify = createWheelDeviceClassifier();+ const read = events.map(+ ([deltaY, wheelDeltaY], index) =>+ classify(wheel(deltaY, { timeStamp: index * 16, wheelDeltaY }), VIEWPORT, 'down').kind+ );+ expect(read).toEqual(kinds);+ }+ );++ it('judges a stream by its vertical events only, so a tilt click before or inside a spin leaves it notched', () => {+ const classify = createWheelDeviceClassifier();+ const tilt = (timeStamp: number) => classify(wheel(0, { deltaX: 30, timeStamp }), VIEWPORT, 'down');+ const notch = (timeStamp: number) => classify(wheel(150, { timeStamp, wheelDeltaY: -180 }), VIEWPORT, 'down').kind;+ tilt(0);+ expect([notch(16), notch(66)]).toEqual(['notched', 'notched']);+ tilt(100);+ expect(notch(150)).toBe('notched');+ });++ it('keeps a trackpad stream open through a sideways-only swipe', () => {+ const classify = createWheelDeviceClassifier();+ classify(wheel(3, { timeStamp: 0 }), VIEWPORT, 'down');+ for (const timeStamp of [150, 300]) {+ classify(wheel(0, { deltaX: 20, timeStamp }), VIEWPORT, 'down');+ }+ expect(classify(wheel(60, { timeStamp: 316, wheelDeltaY: -180 }), VIEWPORT, 'down').kind).toBe('smooth');+ });++ it('turns a notched stream smooth on a two-axis event', () => {+ const classify = createWheelDeviceClassifier();+ expect(classify(wheel(100, { wheelDeltaY: -120 }), VIEWPORT, 'down').kind).toBe('notched');+ expect(classify(wheel(4, { deltaX: 2, timeStamp: 16 }), VIEWPORT, 'down').kind).toBe('smooth');+ expect(classify(wheel(4, { timeStamp: 32 }), VIEWPORT, 'down').kind).toBe('smooth');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/wheelDevice.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/wheelDevice.tsnew file mode 100644index 0000000000..c18a13883c--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/wheelDevice.ts@@ -0,0 +1,99 @@+/**+ * Tells a notched mouse wheel from smooth scrolling per wheel event. Notch signatures: line or page `deltaMode`+ * (Firefox); a vertical pixel delta that is a multiple of 4.000244140625 (macOS non-precise wheel in Chromium and+ * Safari, as in MapLibre); a legacy `wheelDeltaY` multiple of 120 with a delta of 25px or more (Chromium, Safari;+ * skipped for a pinch); a delta of 50px or more (Chromium on Wayland reports a notch as 150px, wheelDelta 180).+ * Trackpads start with small deltas and often move on both axes at once, which no wheel does. Events at most 200ms+ * apart form a stream, judged by its first vertical one: a smooth stream stays smooth through a flick's large delta+ * unless a line-mode or macOS-notch event says otherwise; a notched one turns smooth on a two-axis event or on any+ * vertical event that is not notch-shaped. A pinch is a smooth ctrl+wheel with Control known up or, while its state+ * is unknown, one carrying Chromium's pinch stamp: a whole-tick `wheelDeltaY` on a delta under 25px.+ */++import type { ControlKeyState } from '@workbench/canvas-engine/input/pointerPipeline';+import type { Size } from '@workbench/canvas-engine/viewport';++export type WheelDeviceKind = 'notched' | 'smooth';++/** The fields read, with Chromium/Safari's legacy `wheelDeltaY`, which lib.dom omits. */+export interface WheelEventShape {+ readonly ctrlKey: boolean;+ readonly deltaMode: number;+ readonly deltaX: number;+ readonly deltaY: number;+ readonly timeStamp: number;+ readonly wheelDeltaY?: number;+}++export interface WheelSample {+ kind: WheelDeviceKind;+ /** Deltas in CSS pixels. */+ deltaX: number;+ deltaY: number;+ /** Moved on both axes at once: only a trackpad does that. */+ twoAxis: boolean;+ /** A trackpad pinch: a smooth ctrl+wheel that a held Control key does not explain. */+ pinch: boolean;+}++const DOM_DELTA_PIXEL = 0;+const DOM_DELTA_LINE = 1;+const DOM_DELTA_PAGE = 2;+const WHEEL_LINE_PX = 16;+const MAC_NOTCH_PX = 4.000244140625;+const LEGACY_NOTCH = 120;+const LEGACY_NOTCH_MIN_PX = 25;+const NOTCH_MIN_PX = 50;+const WHEEL_STREAM_GAP_MS = 200;++/** `controlKey`: the physical Control key, which tells a pinch's ctrl+wheel from a held Control. */+export const createWheelDeviceClassifier = (): ((+ event: WheelEventShape,+ viewportSize: Size,+ controlKey: ControlKeyState+) => WheelSample) => {+ let streamKind: WheelDeviceKind = 'smooth';+ let lastTimeStamp = Number.NEGATIVE_INFINITY;++ return (event, viewportSize, controlKey) => {+ // Firefox reports a line-mode wheel in pixels once a delta is read before `deltaMode`.+ const mode = event.deltaMode;+ const rawX = event.deltaX;+ const rawY = event.deltaY;+ const wheelDeltaY = event.wheelDeltaY ?? 0;+ const scaleX = mode === DOM_DELTA_PAGE ? viewportSize.width : mode === DOM_DELTA_LINE ? WHEEL_LINE_PX : 1;+ const scaleY = mode === DOM_DELTA_PAGE ? viewportSize.height : mode === DOM_DELTA_LINE ? WHEEL_LINE_PX : 1;+ const size = Math.abs(rawY);+ const twoAxis = rawX !== 0 && rawY !== 0;+ const vertical = rawX === 0 && rawY !== 0;+ const macNotch = vertical && rawY % MAC_NOTCH_PX === 0;+ const wholeTick = wheelDeltaY !== 0 && wheelDeltaY % LEGACY_NOTCH === 0;+ const pinchStamp = mode === DOM_DELTA_PIXEL && vertical && !macNotch && wholeTick && size < LEGACY_NOTCH_MIN_PX;+ const pinchCandidate = event.ctrlKey && (controlKey === 'up' || (controlKey === 'unknown' && pinchStamp));+ const legacyNotch = !pinchCandidate && wholeTick && size >= LEGACY_NOTCH_MIN_PX;+ const notchShaped = legacyNotch || size >= NOTCH_MIN_PX;+ const sameStream = event.timeStamp - lastTimeStamp <= WHEEL_STREAM_GAP_MS;++ if (mode === DOM_DELTA_LINE || mode === DOM_DELTA_PAGE) {+ streamKind = 'notched';+ } else if (twoAxis) {+ streamKind = 'smooth';+ } else if (macNotch) {+ streamKind = 'notched';+ } else if (vertical && !(sameStream && streamKind === 'smooth')) {+ streamKind = notchShaped ? 'notched' : 'smooth';+ }+ // A sideways-only or empty event, as a tilt click around a spin, extends a stream but never opens one.+ if (rawY !== 0 || sameStream) {+ lastTimeStamp = event.timeStamp;+ }++ return {+ deltaX: rawX * scaleX,+ deltaY: rawY * scaleY,+ kind: streamKind,+ pinch: pinchCandidate && streamKind === 'smooth',+ twoAxis,+ };+ };+};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.tsindex 18aa9dd861..bfb05eaadc 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts@@ -20,7 +20,7 @@ import type { SamInteractionState, SamVisualInput } from '@workbench/canvas-engiimport type { FloatingSelection, FloatLiftResult } from '@workbench/canvas-engine/selection/floatingSelection';import type { SelectionCommit } from '@workbench/canvas-engine/selection/selectionState';import type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';-import type { PlacedSurface, PointerInput, PointerModifiers, Rect, ToolId, Vec2 } from '@workbench/canvas-engine/types';+import type { PlacedSurface, PointerInput, Rect, ToolId, Vec2 } from '@workbench/canvas-engine/types';import type { Viewport } from '@workbench/canvas-engine/viewport';/** Before/after images sized to `dirtyRect`, for exact undo/redo and persistence. */@@ -163,9 +163,6 @@ export interface Tool {onModifierKey?(ctx: ToolContext, code: 'Space' | 'Alt' | 'Shift', pressed: boolean): boolean;/** Drop or reconcile an unfinished gesture when its document target changes. Never dispatch from this hook. */onDocumentChanged?(ctx: ToolContext): void;-- /** Wheel over the canvas; `screenAnchor` is the CSS-pixel cursor position. */- onWheel?(ctx: ToolContext, deltaY: number, screenAnchor: { x: number; y: number }, modifiers: PointerModifiers): void;cursor?(ctx: ToolContext): string;/** The pointer pipeline must not turn this tool's alt-hold into the temporary color picker. */readonly usesAltKey?: boolean;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/viewTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/viewTool.tsindex 91a41b18ba..9163ded56e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/viewTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/viewTool.ts@@ -1,6 +1,6 @@/** Per-engine view tool: pans and zooms the viewport without document dispatch; also the temporary Space tool. */-import type { PointerInput, PointerModifiers, Vec2 } from '@workbench/canvas-engine/types';+import type { PointerInput, Vec2 } from '@workbench/canvas-engine/types';import type { Tool, ToolContext } from './tool';@@ -41,9 +41,5 @@ export const createViewTool = (): Tool => {onPointerDown: (_ctx, input) => begin(input),onPointerMove: move,onPointerUp: end,- onWheel: (ctx: ToolContext, deltaY: number, screenAnchor: Vec2, _modifiers: PointerModifiers) => {- ctx.viewport.wheelZoom(deltaY, screenAnchor);- ctx.invalidate({ view: true });- },};};diff --git a/invokeai/frontend/webv2/src/workbench/settings/projectSettings.ts b/invokeai/frontend/webv2/src/workbench/settings/projectSettings.tsindex 2d2e45f1c2..d4415c8a76 100644--- a/invokeai/frontend/webv2/src/workbench/settings/projectSettings.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/projectSettings.ts@@ -57,6 +57,7 @@ export const getLayeredSettings = (): LayeredSettingsTable =>invertBrushSizeScroll: typedBoolean(false),outputOnlyMaskedRegions: typedBoolean(true),ruleOfThirds: typedBoolean(false),+ scrollInput: oneOf('auto', ['mouse', 'trackpad']),showBbox: typedBoolean(true),showCheckerboard: typedBoolean(true),showGrid: typedBoolean(false),diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasScrollInputFeed.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasScrollInputFeed.browser.test.tsxnew file mode 100644index 0000000000..4190b8bca2--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasScrollInputFeed.browser.test.tsx@@ -0,0 +1,73 @@+/* oxlint-disable react-perf/jsx-no-new-object-as-prop */+import type * as WorkbenchContextModule from '@workbench/WorkbenchContext';++import { createEngineStores } from '@workbench/canvas-engine/engineStores';+import { createWorkbenchStore } from '@workbench/workbenchStore';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, describe, expect, it, vi } from 'vitest';++const harness = vi.hoisted(() => ({ store: null as ReturnType<typeof createWorkbenchStore> | null }));++vi.mock('@workbench/WorkbenchContext', async (importOriginal) => ({+ ...(await importOriginal<typeof WorkbenchContextModule>()),+ useWorkbenchQueries: () => harness.store!.queries,+ useWorkbenchSubscription: () => harness.store!.subscribe,+}));++import { CanvasScrollInputFeed } from './CanvasScrollInputFeed';++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const STORAGE_KEY = 'invokeai:v7:webv2:canvas-trackpad-detected';++let root: Root | null = null;+let host: HTMLDivElement | null = null;++afterEach(async () => {+ await act(() => root?.unmount());+ host?.remove();+ root = null;+ host = null;+ harness.store = null;+ localStorage.removeItem(STORAGE_KEY);+});++const mount = async () => {+ const store = createWorkbenchStore();+ harness.store = store;+ const stores = createEngineStores();+ const engine = {+ interaction: {+ get: (key: 'scrollInput' | 'trackpadDetected') => stores[key].get(),+ set: (key: 'scrollInput' | 'trackpadDetected', value: never) => stores[key].set(value),+ subscribe: (key: 'scrollInput' | 'trackpadDetected', listener: () => void) => stores[key].subscribe(listener),+ },+ } as never;+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ await act(() => root!.render(<CanvasScrollInputFeed engine={engine} projectId={store.getState().activeProjectId} />));+ return { store, stores };+};++describe('CanvasScrollInputFeed', () => {+ it('feeds the project’s scroll input to the engine', async () => {+ const { store, stores } = await mount();+ expect(stores.scrollInput.get()).toBe('auto');+ await act(() => store.commands.widgets.patchValues('canvas', { scrollInput: 'trackpad' }));+ expect(stores.scrollInput.get()).toBe('trackpad');+ });++ it('persists a detected trackpad for this browser and restores it on the next mount', async () => {+ const first = await mount();+ expect(first.stores.trackpadDetected.get()).toBe(false);+ first.stores.trackpadDetected.set(true);+ expect(localStorage.getItem(STORAGE_KEY)).toBe('true');+ await act(() => root?.unmount());+ host?.remove();++ const second = await mount();+ expect(second.stores.trackpadDetected.get()).toBe(true);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasScrollInputFeed.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasScrollInputFeed.tsxnew file mode 100644index 0000000000..ef91468271--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasScrollInputFeed.tsx@@ -0,0 +1,69 @@+import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';++import { useMountEffect } from '@platform/react/useMountEffect';+import { getResolvedProjectWidgetValues } from '@workbench/widgetState';+import { useWorkbenchQueries, useWorkbenchSubscription } from '@workbench/WorkbenchContext';++import { readCanvasScrollInput } from './canvasSettings';++// Per browser, not per account or project: the pointing device belongs to the machine.+const TRACKPAD_DETECTED_KEY = 'invokeai:v7:webv2:canvas-trackpad-detected';++const readTrackpadDetected = (): boolean => {+ try {+ return globalThis.localStorage?.getItem(TRACKPAD_DETECTED_KEY) === 'true';+ } catch {+ return false;+ }+};++const persistTrackpadDetected = (): void => {+ try {+ globalThis.localStorage?.setItem(TRACKPAD_DETECTED_KEY, 'true');+ } catch {+ // Without storage the next session detects the trackpad again.+ }+};++/** Feeds the scroll input setting to the engine and keeps the engine's trackpad detection across sessions. */+export const CanvasScrollInputFeed = ({+ engine,+ projectId,+}: {+ engine: Pick<CanvasEngineHandle, 'interaction'>;+ projectId: string;+}) => {+ const queries = useWorkbenchQueries();+ const subscribe = useWorkbenchSubscription();+ useMountEffect(() => {+ const { interaction } = engine;+ let read: unknown = null;+ const feed = (): void => {+ const project = queries.getProject(projectId);+ if (!project) {+ return;+ }+ // Resolved values keep their identity while the project's pins and the account defaults keep theirs.+ const values = getResolvedProjectWidgetValues(project, 'canvas', queries.getSnapshot().scopedDefaults);+ if (values !== read) {+ read = values;+ interaction.set('scrollInput', readCanvasScrollInput(values));+ }+ };+ feed();+ if (readTrackpadDetected()) {+ interaction.set('trackpadDetected', true);+ }+ const unsubscribeDetected = interaction.subscribe('trackpadDetected', () => {+ if (interaction.get('trackpadDetected')) {+ persistTrackpadDetected();+ }+ });+ const unsubscribeWorkbench = subscribe(feed);+ return () => {+ unsubscribeWorkbench();+ unsubscribeDetected();+ };+ });+ return null;+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsxindex 9df68688e3..c8be75b860 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx@@ -54,6 +54,7 @@ import { CANVAS_ONLY_HOTKEYS, executeCanvasHotkeyCommand } from './canvasHotkeyCimport { findCanvasImageDropDestination, resolveCanvasImageDrop, type CanvasImageDropData } from './canvasImageDnd';import { CanvasImageDropOverlay } from './CanvasImageDropOverlay';import { CanvasSaveToGallerySubmenu } from './CanvasSaveToGallerySubmenu';+import { CanvasScrollInputFeed } from './CanvasScrollInputFeed';import {CANVAS_SETTINGS,CANVAS_SHOW_PROGRESS_KEY,@@ -674,6 +675,9 @@ export const CanvasWidgetView = ({ runtime, instance }: WidgetViewProps) => {) : null}<CanvasColorFeed engine={engine} />{engine ? <CanvasFrameLockFeed key={`${projectId}:frame-lock`} engine={engine} projectId={projectId} /> : null}+ {engine ? (+ <CanvasScrollInputFeed key={`${projectId}:scroll-input`} engine={engine} projectId={projectId} />+ ) : null}{engine ? <CanvasEditRefusalNotices key={`${projectId}:edit-refusals`} engine={engine} /> : null}{engine ? (<CanvasStagedRegionsFeed key={`${projectId}:staged-regions`} engine={engine} projectId={projectId} />diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSettings.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSettings.test.tsindex 12d68a8dc7..14547028ac 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSettings.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSettings.test.ts@@ -15,6 +15,7 @@ import {CANVAS_SNAP_TO_GRID_KEY,canvasSettingsEqual,readCanvasBooleanSetting,+ readCanvasScrollInput,resolveCanvasSettings,} from './canvasSettings';@@ -86,6 +87,12 @@ describe('canvasSettings persistence mapping', () => {).toBe(false);});+ it('reads the scroll input, falling back to auto-detection for anything unknown', () => {+ expect(readCanvasScrollInput(resolvedValues({ scrollInput: 'trackpad' }))).toBe('trackpad');+ expect(readCanvasScrollInput(resolvedValues({ scrollInput: true }))).toBe('auto');+ expect(readCanvasScrollInput(undefined)).toBe('auto');+ });+it('maps every setting to a unique persisted key', () => {const keys = CANVAS_SETTINGS.map((s) => s.key);expect(new Set(keys).size).toBe(keys.length);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSettings.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSettings.tsindex f5585b8572..682e32467f 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSettings.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSettings.ts@@ -1,6 +1,7 @@/** Per-project canvas preferences, outside undo history; engine-backed ones feed stores one way. */import type { ResolvedValues } from '@platform/core/resolvedValues';+import type { ScrollInput } from '@workbench/canvas-engine/api';import { CANVAS_COMPOSITING_KEYS, DEFAULT_CANVAS_COMPOSITING } from './invoke/canvasCompositing';@@ -119,6 +120,18 @@ export const CANVAS_SETTINGS: readonly CanvasBooleanSetting[] = [},];+/** Feeds the engine's `scrollInput` store; a select, so it stays outside `CANVAS_SETTINGS`. */+export const CANVAS_SCROLL_INPUT_KEY = 'scrollInput';+export const CANVAS_SCROLL_INPUTS = ['auto', 'mouse', 'trackpad'] as const satisfies readonly ScrollInput[];++export const isCanvasScrollInput = (value: unknown): value is ScrollInput =>+ (CANVAS_SCROLL_INPUTS as readonly unknown[]).includes(value);++export const readCanvasScrollInput = (values: ResolvedValues | undefined): ScrollInput => {+ const raw = values?.[CANVAS_SCROLL_INPUT_KEY];+ return isCanvasScrollInput(raw) ? raw : 'auto';+};+/** Resolved settings, keyed by persisted setting key (default-applied). */export type ResolvedCanvasSettings = Record<string, boolean>;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/settingsBindings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/settingsBindings.tsxindex 5826968f04..a6470dde50 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/settingsBindings.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/settingsBindings.tsx@@ -2,32 +2,44 @@ import type { ResolvedValues } from '@platform/core/resolvedValues';import type { SettingFieldProps } from '@platform/ui/settings/contracts';import { SettingControl } from '@platform/ui/settings/SettingControl';-import { useLayeredSetting } from '@workbench/settings/useLayeredSetting';+import { readBuiltIn, useLayeredSetting } from '@workbench/settings/useLayeredSetting';import { useCallback } from 'react';-import { CANVAS_SETTINGS, readCanvasBooleanSetting } from './canvasSettings';+import {+ CANVAS_SCROLL_INPUT_KEY,+ CANVAS_SETTINGS,+ isCanvasScrollInput,+ readCanvasBooleanSetting,+ readCanvasScrollInput,+} from './canvasSettings';export const Field = ({ field, surface, target }: SettingFieldProps) => {+ const isScrollInput = field.id === CANVAS_SCROLL_INPUT_KEY;const definition = CANVAS_SETTINGS.find((setting) => setting.key === field.id);const read = useCallback(- (values: ResolvedValues) => (definition ? readCanvasBooleanSetting(values, definition) : false),- [definition]+ (values: ResolvedValues): boolean | string =>+ isScrollInput ? readCanvasScrollInput(values) : definition ? readCanvasBooleanSetting(values, definition) : false,+ [definition, isScrollInput]);- const { disabled, layer, set, value } = useLayeredSetting(+ const { disabled, layer, set, value } = useLayeredSetting<boolean | string>('canvas',field.id,target,read,- definition?.defaultValue ?? false,+ readBuiltIn(read),field);const onChange = useCallback((next: boolean | string | number) => {- if (definition && typeof next === 'boolean') {+ if (isScrollInput) {+ if (isCanvasScrollInput(next)) {+ set(next);+ }+ } else if (definition && typeof next === 'boolean') {set(next);}},- [definition, set]+ [definition, isScrollInput, set]);return (<SettingControldiff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/settingsContribution.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/settingsContribution.tsindex c785b09364..9ba9367d08 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/settingsContribution.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/settingsContribution.ts@@ -1,18 +1,33 @@-import type { SettingsContribution } from '@platform/ui/settings/contracts';+import type { SettingDefinition, SettingsContribution } from '@platform/ui/settings/contracts';-import { CANVAS_SETTINGS } from './canvasSettings';+import { CANVAS_SCROLL_INPUT_KEY, CANVAS_SCROLL_INPUTS, CANVAS_SETTINGS } from './canvasSettings';export const canvasSettingsContribution: SettingsContribution = {id: 'canvas',label: (t) => t('widgets.labels.canvas'),- fields: CANVAS_SETTINGS.map((setting) => ({- group: (t) => t(`widgets.canvas.settings.sections.${setting.section}`),- id: setting.key,- kind: 'boolean',- label: (t) => t(setting.labelKey),- scope: 'project',- keywords: setting.key === 'showCheckerboard' ? 'transparency background' : undefined,- })),- quick: CANVAS_SETTINGS.map((setting) => setting.key),+ fields: [+ {+ description: (t) => t('widgets.canvas.settings.scrollInputDescription'),+ group: (t) => t('widgets.canvas.settings.sections.behavior'),+ id: CANVAS_SCROLL_INPUT_KEY,+ keywords: 'trackpad touchpad mouse wheel pinch zoom pan',+ kind: 'select',+ label: (t) => t('widgets.canvas.settings.scrollInput'),+ options: CANVAS_SCROLL_INPUTS.map((value) => ({+ label: (t) => t(`widgets.canvas.settings.scrollInputOptions.${value}`),+ value,+ })),+ scope: 'project',+ },+ ...CANVAS_SETTINGS.map((setting): SettingDefinition => ({+ group: (t) => t(`widgets.canvas.settings.sections.${setting.section}`),+ id: setting.key,+ kind: 'boolean',+ label: (t) => t(setting.labelKey),+ scope: 'project',+ keywords: setting.key === 'showCheckerboard' ? 'transparency background' : undefined,+ })),+ ],+ quick: [CANVAS_SCROLL_INPUT_KEY, ...CANVAS_SETTINGS.map((setting) => setting.key)],load: () => import('./settingsBindings'),};