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(webv2): float selected pixels for move
joshistoastc679984f4761
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.test.tsindex 5d48d6db22..f6267355fa 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.test.ts@@ -62,6 +62,19 @@ const createSelectionPixelOptions = () => ({notifyPainted: vi.fn(),});+const createFloatingSelectionOptions = () => ({+ applyImagePatch: vi.fn(),+ backend: {} as never,+ canEdit: () => true,+ endBurst: vi.fn(),+ getDocument: () => null,+ history: {} as never,+ invalidateLayer: vi.fn(),+ layers: {} as never,+ markDirty: vi.fn(),+ notifyPainted: vi.fn(),+});+const createSelectionImageOptions = () => ({capturePermit: () => null,decodeImage: vi.fn(),@@ -76,6 +89,7 @@ describe('EditingController', () => {const selection = createSelection();const createSelectionState = vi.fn((_deps: SelectionStateDeps) => selection);const controller = new EditingController({+ floatingSelection: createFloatingSelectionOptions(),getDocument: () => null,selection: {} as SelectionStateDeps,selectionPixels: createSelectionPixelOptions(),@@ -98,6 +112,7 @@ describe('EditingController', () => {it('disposes selection and leases idempotently and cannot reactivate afterward', () => {const selection = createSelection();const controller = new EditingController({+ floatingSelection: createFloatingSelectionOptions(),getDocument: () => null,selection: {} as SelectionStateDeps,selectionPixels: createSelectionPixelOptions(),diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.tsindex 0689b4ceb3..f05ee81030 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.ts@@ -8,6 +8,7 @@ import { createCanvasEditGate } from '@workbench/canvas-engine/editGate';import { roundOut, union } from '@workbench/canvas-engine/math/rect';import { createSelectionState } from '@workbench/canvas-engine/selection/selectionState';+import { FloatingSelectionController, type FloatingSelectionControllerOptions } from './floatingSelectionController';import { SelectionImageController, type SelectionImageControllerOptions } from './selectionImageController';import { SelectionPixelController, type SelectionPixelControllerOptions } from './selectionPixelController';import { TextEditingController, type TextEditingControllerOptions } from './textEditingController';@@ -22,6 +23,7 @@ export interface EditingControllerOptions<Permit = unknown, Owner = symbol> {readonly transform: TransformEditingControllerOptions;readonly selectionPixels: Omit<SelectionPixelControllerOptions, 'selection'>;readonly selectionImage: Omit<SelectionImageControllerOptions<Permit, Owner>, 'selection'>;+ readonly floatingSelection: Omit<FloatingSelectionControllerOptions, 'selection'>;}/** Owns transient editing state whose lifetime follows one engine instance. */@@ -32,6 +34,7 @@ export class EditingController<Permit = unknown, Owner = symbol> {readonly transform: TransformEditingController;readonly selectionPixels: SelectionPixelController;readonly selectionImage: SelectionImageController<Permit, Owner>;+ readonly floatingSelection: FloatingSelectionController;private readonly editGate: CanvasEditGateController;private readonly getDocument: () => CanvasDocumentContractV2 | null;private disposed = false;@@ -48,6 +51,10 @@ export class EditingController<Permit = unknown, Owner = symbol> {...options.selectionImage,selection: this.selection,});+ this.floatingSelection = new FloatingSelectionController({+ ...options.floatingSelection,+ selection: this.selection,+ });}activate(): void {@@ -122,6 +129,9 @@ export class EditingController<Permit = unknown, Owner = symbol> {this.transform.dispose();this.selectionPixels.dispose();this.selectionImage.dispose();+ // Before the selection: disposing a live float puts its pixels back, and+ // that read still needs the selection's mask to be intact.+ this.floatingSelection.dispose();this.selection.dispose();}}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.test.tsnew file mode 100644index 0000000000..7f4119d3b9--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.test.ts@@ -0,0 +1,317 @@+import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { SelectionState } from '@workbench/canvas-engine/selection/selectionState';+import type { PlacedSurface, Rect } from '@workbench/canvas-engine/types';++import { createHistory } from '@workbench/canvas-engine/history/history';+import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';+import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { FloatingSelectionController } from './floatingSelectionController';++const paintLayer = (id: string, transform: Partial<CanvasLayerContract['transform']> = {}): CanvasLayerContract => ({+ blendMode: 'normal',+ id,+ isEnabled: true,+ isLocked: false,+ name: id,+ opacity: 1,+ source: { bitmap: null, offset: { x: 0, y: 0 }, type: 'paint' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0, ...transform },+ type: 'raster',+});++const makeDoc = (layers: CanvasLayerContract[]): CanvasDocumentContractV2 => ({+ background: 'transparent',+ bbox: { height: 100, width: 100, x: 0, y: 0 },+ height: 100,+ layers,+ selectedLayerId: layers[0]?.id ?? null,+ version: 2,+ width: 100,+});++const createHarness = (options: { layer?: CanvasLayerContract; maskRect?: Rect; cacheRect?: Rect } = {}) => {+ const backend = createTestStubRasterBackend();+ const layers = createLayerCacheStore(backend);+ const history = createHistory();+ const layer = options.layer ?? paintLayer('a');+ let document: CanvasDocumentContractV2 | null = makeDoc([layer]);++ const maskRect = options.maskRect ?? { height: 30, width: 30, x: 20, y: 20 };+ const maskSurface: PlacedSurface = {+ rect: maskRect,+ surface: backend.createSurface(maskRect.width, maskRect.height),+ };+ const replaceMask = vi.fn();+ const selection = {+ antsPaths: () => [],+ bounds: () => maskRect,+ clear: vi.fn(),+ commit: vi.fn(),+ containsPoint: () => true,+ dispose: vi.fn(),+ hasSelection: () => true,+ invert: vi.fn(),+ mask: () => maskSurface,+ replaceMask,+ selectAll: vi.fn(),+ } as SelectionState;++ // Seed a cache so there is something to lift out of.+ layers.getOrCreateRect(layer.id, options.cacheRect ?? { height: 100, width: 100, x: 0, y: 0 });++ const calls = {+ applyImagePatch: vi.fn(),+ endBurst: vi.fn(),+ invalidateLayer: vi.fn(),+ markDirty: vi.fn(),+ notifyPainted: vi.fn(),+ };++ const controller = new FloatingSelectionController({+ applyImagePatch: calls.applyImagePatch,+ backend,+ canEdit: () => true,+ endBurst: calls.endBurst,+ getDocument: () => document,+ history,+ invalidateLayer: calls.invalidateLayer,+ layers,+ markDirty: calls.markDirty,+ notifyPainted: calls.notifyPainted,+ selection,+ });++ return {+ backend,+ calls,+ controller,+ history,+ layer,+ layers,+ replaceMask,+ removeLayer: () => {+ document = makeDoc([]);+ },+ };+};++/** Moves the float by a layer-local delta. */+const move = (controller: FloatingSelectionController, x: number, y: number): void =>+ controller.setTransform({ rotation: 0, scaleX: 1, scaleY: 1, x, y });++describe('FloatingSelectionController: lift', () => {+ it('lifts the selection region and reports a live float', () => {+ const h = createHarness();+ expect(h.controller.lift('a')).toBe(true);+ expect(h.controller.has()).toBe(true);+ expect(h.controller.get()?.layerId).toBe('a');+ expect(h.controller.get()?.pixels.rect).toEqual({ height: 30, width: 30, x: 20, y: 20 });+ // Identity until something drags it.+ expect(h.controller.get()?.transform).toEqual({ rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 });+ });++ it('recomposites the hole but never marks the layer dirty', () => {+ // Persisting mid-float would upload a holed bitmap the user never asked for.+ const h = createHarness();+ h.controller.lift('a');+ expect(h.calls.notifyPainted).toHaveBeenCalledWith('a');+ expect(h.calls.markDirty).not.toHaveBeenCalled();+ });++ it('pushes no history entry — only a commit is undoable', () => {+ const h = createHarness();+ h.controller.lift('a');+ expect(h.history.canUndo()).toBe(false);+ });++ it('closes any coalescing burst before touching pixels', () => {+ const h = createHarness();+ h.controller.lift('a');+ expect(h.calls.endBurst).toHaveBeenCalled();+ });++ it('refuses a second lift while a float is live', () => {+ const h = createHarness();+ expect(h.controller.lift('a')).toBe(true);+ expect(h.controller.lift('a')).toBe(false);+ });++ it('refuses a locked layer', () => {+ const h = createHarness({ layer: { ...paintLayer('a'), isLocked: true } });+ expect(h.controller.lift('a')).toBe(false);+ expect(h.controller.has()).toBe(false);+ });++ it('refuses a hidden layer', () => {+ const h = createHarness({ layer: { ...paintLayer('a'), isEnabled: false } });+ expect(h.controller.lift('a')).toBe(false);+ });++ it('refuses an unknown layer', () => {+ const h = createHarness();+ expect(h.controller.lift('nope')).toBe(false);+ });++ it('refuses when the selection misses the layer content', () => {+ const h = createHarness({ cacheRect: { height: 10, width: 10, x: 0, y: 0 } });+ expect(h.controller.lift('a')).toBe(false);+ });+});++describe('FloatingSelectionController: commit', () => {+ it('pushes exactly one undoable entry for the whole move, however many drags', () => {+ const h = createHarness();+ h.controller.lift('a');+ move(h.controller, 5, 0);+ move(h.controller, 12, 3);+ move(h.controller, 40, 10);+ h.controller.commit();++ expect(h.controller.has()).toBe(false);+ expect(h.history.canUndo()).toBe(true);+ h.history.undo();+ expect(h.history.canUndo()).toBe(false);+ });++ it('spans both the hole and the landing region so one undo restores both', () => {+ const h = createHarness();+ h.controller.lift('a');+ move(h.controller, 40, 0);+ h.controller.commit();++ // The commit writes the cache directly; `applyImagePatch` is the history+ // entry's replay bridge, so it first runs on undo.+ expect(h.calls.applyImagePatch).not.toHaveBeenCalled();+ h.history.undo();++ const [layerId, rect] = h.calls.applyImagePatch.mock.calls[0] as [string, Rect];+ expect(layerId).toBe('a');+ // The hole at x ∈ [20,50) unioned with the landing region at x ∈ [60,90).+ expect(rect.x).toBe(20);+ expect(rect.x + rect.width).toBe(90);+ });++ it('marks the layer dirty so the baked pixels persist', () => {+ const h = createHarness();+ h.controller.lift('a');+ move(h.controller, 40, 0);+ h.controller.commit();+ expect(h.calls.markDirty).toHaveBeenCalledWith('a');+ });++ it('carries the selection mask along so the ants land on the moved pixels', () => {+ const h = createHarness();+ h.controller.lift('a');+ move(h.controller, 40, 10);+ h.controller.commit();++ expect(h.replaceMask).toHaveBeenCalledTimes(1);+ const moved = h.replaceMask.mock.calls[0]![0] as PlacedSurface;+ expect(moved.rect).toEqual({ height: 30, width: 30, x: 60, y: 30 });+ });++ it('scales a layer-local move into document space for the mask', () => {+ // On a 2× layer, a 20px local move is a 40px document move.+ const h = createHarness({ layer: paintLayer('a', { scaleX: 2, scaleY: 2 }) });+ h.controller.lift('a');+ move(h.controller, 20, 0);+ h.controller.commit();++ const moved = h.replaceMask.mock.calls[0]![0] as PlacedSurface;+ expect(moved.rect.x).toBe(60);+ });++ it('treats an unmoved float as a cancel — nothing changed, so nothing is undoable', () => {+ const h = createHarness();+ h.controller.lift('a');+ h.controller.commit();++ expect(h.controller.has()).toBe(false);+ expect(h.history.canUndo()).toBe(false);+ expect(h.replaceMask).not.toHaveBeenCalled();+ });++ it('drops the float without committing when its layer has gone', () => {+ const h = createHarness();+ h.controller.lift('a');+ move(h.controller, 40, 0);+ h.removeLayer();+ h.controller.commit();++ expect(h.controller.has()).toBe(false);+ expect(h.history.canUndo()).toBe(false);+ });++ it('is a no-op with no float', () => {+ const h = createHarness();+ h.controller.commit();+ expect(h.history.canUndo()).toBe(false);+ });+});++describe('FloatingSelectionController: cancel', () => {+ it('drops the float and pushes no history', () => {+ const h = createHarness();+ h.controller.lift('a');+ move(h.controller, 40, 0);+ h.controller.cancel();++ expect(h.controller.has()).toBe(false);+ expect(h.history.canUndo()).toBe(false);+ });++ it('restores the pixels without marking dirty (the layer never changed)', () => {+ const h = createHarness();+ h.controller.lift('a');+ h.controller.cancel();++ expect(h.calls.markDirty).not.toHaveBeenCalled();+ expect(h.calls.notifyPainted).toHaveBeenCalledTimes(2);+ });++ it('leaves the selection where it was', () => {+ const h = createHarness();+ h.controller.lift('a');+ move(h.controller, 40, 0);+ h.controller.cancel();+ expect(h.replaceMask).not.toHaveBeenCalled();+ });++ it('is a no-op with no float', () => {+ const h = createHarness();+ h.controller.cancel();+ expect(h.calls.notifyPainted).not.toHaveBeenCalled();+ });+});++describe('FloatingSelectionController: dispose', () => {+ let harness: ReturnType<typeof createHarness>;++ beforeEach(() => {+ harness = createHarness();+ });++ it('puts a live float back rather than dropping its pixels on the floor', () => {+ harness.controller.lift('a');+ move(harness.controller, 40, 0);+ harness.controller.dispose();++ expect(harness.controller.has()).toBe(false);+ expect(harness.history.canUndo()).toBe(false);+ // The restore pass ran.+ expect(harness.calls.notifyPainted).toHaveBeenCalledTimes(2);+ });++ it('refuses further lifts once disposed', () => {+ harness.controller.dispose();+ expect(harness.controller.lift('a')).toBe(false);+ });++ it('is idempotent', () => {+ harness.controller.dispose();+ harness.controller.dispose();+ expect(harness.controller.has()).toBe(false);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.tsnew file mode 100644index 0000000000..ff3a999797--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.ts@@ -0,0 +1,282 @@+import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { History } from '@workbench/canvas-engine/history/history';+import type { ImagePatchApply } from '@workbench/canvas-engine/history/imagePatch';+import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';+import type { RasterBackend } from '@workbench/canvas-engine/render/raster';+import type { FloatingSelection } from '@workbench/canvas-engine/selection/floatingSelection';+import type { SelectionState } from '@workbench/canvas-engine/selection/selectionState';+import type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';+import type { Rect } from '@workbench/canvas-engine/types';++import { isLayerPixelEditEligible } from '@workbench/canvas-engine/editing/controlPixelEdit';+import { createImagePatchEntry } from '@workbench/canvas-engine/history/imagePatch';+import { isEmpty, roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';+import {+ floatDocumentMatrix,+ liftSelectedPixels,+ transformPlacedMask,+} from '@workbench/canvas-engine/selection/floatingSelection';+import { eraseMaskedRegion } from '@workbench/canvas-engine/selection/selectionOps';+import { layerMatrix } from '@workbench/canvas-engine/tools/moveHitTest';+import { bakeMatrix, IDENTITY_TRANSFORM } from '@workbench/canvas-engine/transform/transformMath';++export interface FloatingSelectionControllerOptions {+ readonly backend: RasterBackend;+ readonly layers: LayerCacheStore;+ readonly selection: SelectionState;+ readonly history: History;+ readonly applyImagePatch: ImagePatchApply;+ readonly getDocument: () => CanvasDocumentContractV2 | null;+ readonly canEdit: () => boolean;+ readonly endBurst: () => void;+ readonly notifyPainted: (layerId: string) => void;+ readonly markDirty: (layerId: string) => void;+ readonly invalidateLayer: (layerId: string) => void;+}++const isIdentity = (transform: LayerTransform): boolean =>+ transform.x === 0 &&+ transform.y === 0 &&+ transform.scaleX === 1 &&+ transform.scaleY === 1 &&+ transform.rotation === 0;++/**+ * Owns the floating-selection lifecycle: cutting selected pixels off a layer,+ * holding them in flight, and either baking them back as ONE undo entry or+ * putting them back untouched.+ *+ * **The lift is deliberately not a history entry.** Only `commit` pushes, with+ * `before` = the pre-lift pixels and `after` = the post-bake pixels over the+ * union of the hole and the landing region. So one undo restores the layer+ * exactly, no matter how many drags happened in between — and a cancelled float+ * leaves the history untouched rather than adding a pair of entries that undo+ * each other.+ *+ * The cache is mutated on lift (the hole) but deliberately NOT marked dirty:+ * persisting a holed bitmap mid-drag would upload a state the user never asked+ * for, and a slow network could land it after the commit. Only `commit` marks+ * dirty.+ */+export class FloatingSelectionController {+ private float: FloatingSelection | null = null;+ private disposed = false;++ constructor(private readonly deps: FloatingSelectionControllerOptions) {}++ get(): FloatingSelection | null {+ return this.float;+ }++ has(): boolean {+ return this.float !== null;+ }++ /** The float's layer, or `null` — resolved fresh so a deleted layer reads as absent. */+ private layerOf(float: FloatingSelection): CanvasLayerContract | null {+ const document = this.deps.getDocument();+ return document?.layers.find((layer) => layer.id === float.layerId) ?? null;+ }++ /**+ * Cuts the selection's pixels out of `layerId` into a new float. Returns false+ * when there is nothing to lift (no selection, an ineligible layer, or no+ * overlap between the two).+ */+ lift(layerId: string): boolean {+ if (this.disposed || this.float || !this.deps.canEdit()) {+ return false;+ }+ const document = this.deps.getDocument();+ const layer = document?.layers.find((candidate) => candidate.id === layerId);+ if (!document || !layer || !isLayerPixelEditEligible(layer)) {+ return false;+ }+ const mask = this.deps.selection.mask();+ const entry = this.deps.layers.get(layerId);+ if (!mask || !entry || isEmpty(entry.rect)) {+ return false;+ }++ const lifted = liftSelectedPixels({+ backend: this.deps.backend,+ cache: { rect: entry.rect, surface: entry.surface },+ layerMatrix: layerMatrix(layer.transform),+ mask,+ });+ if (!lifted) {+ return false;+ }++ // Close any coalescing burst before mutating pixels, so a pending nudge does+ // not absorb this edit.+ this.deps.endBurst();+ const region = lifted.pixels.rect;+ const before = entry.surface.ctx.getImageData(+ region.x - entry.rect.x,+ region.y - entry.rect.y,+ region.width,+ region.height+ );++ eraseMaskedRegion({+ backend: this.deps.backend,+ mask: lifted.localMask.surface,+ maskOrigin: lifted.localMask.rect,+ rect: region,+ target: entry.surface,+ targetOrigin: entry.rect,+ });++ this.float = {+ before: { data: before, rect: region },+ layerId,+ mask: { rect: mask.rect, surface: mask.surface },+ pixels: lifted.pixels,+ transform: { ...IDENTITY_TRANSFORM },+ };+ // Bump the cache version so the hole composites, WITHOUT marking dirty.+ this.deps.notifyPainted(layerId);+ this.deps.invalidateLayer(layerId);+ return true;+ }++ /** Updates the float's live (layer-local) transform. */+ setTransform(transform: LayerTransform): void {+ if (!this.float) {+ return;+ }+ this.float.transform = { ...transform };+ this.deps.invalidateLayer(this.float.layerId);+ }++ /**+ * Bakes the float back into its layer as one undoable entry, and carries the+ * selection outline along with it. A float whose transform never moved is+ * still put back (it was cut out), but without a history entry — nothing+ * changed.+ */+ commit(): void {+ const float = this.float;+ if (this.disposed || !float) {+ return;+ }+ const layer = this.layerOf(float);+ if (!layer) {+ // The layer went away under the float; the pixels have nowhere to land.+ this.float = null;+ return;+ }+ if (isIdentity(float.transform)) {+ this.cancel();+ return;+ }++ const matrix = bakeMatrix(float.transform);+ const landing = roundOut(transformBounds(matrix, float.pixels.rect));+ // The patch spans both the hole left behind and where the pixels land, so a+ // single undo restores both halves of the move.+ const patchRect = union(float.before.rect, landing);++ this.deps.endBurst();+ const entry = this.deps.layers.growToRect(float.layerId, patchRect);++ // Reconstruct the pre-lift pixels over the patch: the live cache is correct+ // everywhere except the hole, which `before` refills exactly.+ const scratch = this.deps.backend.createSurface(patchRect.width, patchRect.height);+ const sctx = scratch.ctx;+ sctx.setTransform(1, 0, 0, 1, 0, 0);+ sctx.globalCompositeOperation = 'source-over';+ sctx.globalAlpha = 1;+ sctx.drawImage(entry.surface.canvas, entry.rect.x - patchRect.x, entry.rect.y - patchRect.y);+ sctx.putImageData(float.before.data, float.before.rect.x - patchRect.x, float.before.rect.y - patchRect.y);+ const before = sctx.getImageData(0, 0, patchRect.width, patchRect.height);++ // Land the float through its transform, in layer-local space.+ const ctx = entry.surface.ctx;+ ctx.save();+ ctx.globalCompositeOperation = 'source-over';+ ctx.globalAlpha = 1;+ ctx.imageSmoothingEnabled = true;+ ctx.setTransform(matrix.a, matrix.b, matrix.c, matrix.d, matrix.e - entry.rect.x, matrix.f - entry.rect.y);+ ctx.drawImage(float.pixels.surface.canvas, float.pixels.rect.x, float.pixels.rect.y);+ ctx.restore();+ ctx.setTransform(1, 0, 0, 1, 0, 0);++ const after = ctx.getImageData(+ patchRect.x - entry.rect.x,+ patchRect.y - entry.rect.y,+ patchRect.width,+ patchRect.height+ );++ this.float = null;+ this.deps.notifyPainted(float.layerId);+ this.deps.markDirty(float.layerId);+ this.deps.invalidateLayer(float.layerId);++ if (!this.deps.history.isApplying()) {+ this.deps.history.push(+ createImagePatchEntry({+ after,+ apply: this.deps.applyImagePatch,+ before,+ label: 'Move selection',+ layerId: float.layerId,+ rect: patchRect,+ })+ );+ }++ this.moveSelectionWithFloat(layer, matrix, float);+ }++ /**+ * Re-places the document-space selection mask by the float's motion, so the+ * marching ants end up around the pixels' new home rather than their old one.+ */+ private moveSelectionWithFloat(+ layer: CanvasLayerContract,+ floatMatrix: ReturnType<typeof bakeMatrix>,+ float: FloatingSelection+ ): void {+ const documentMatrix = floatDocumentMatrix(layerMatrix(layer.transform), floatMatrix);+ if (!documentMatrix) {+ return;+ }+ const moved = transformPlacedMask(this.deps.backend, float.mask, documentMatrix);+ if (moved) {+ this.deps.selection.replaceMask(moved);+ }+ }++ /** Puts the lifted pixels back untouched and drops the float. Pushes no history. */+ cancel(): void {+ const float = this.float;+ if (!float) {+ return;+ }+ this.float = null;+ if (!this.layerOf(float)) {+ return;+ }+ const restoreRect: Rect = float.before.rect;+ if (isEmpty(restoreRect)) {+ return;+ }+ const entry = this.deps.layers.growToRect(float.layerId, restoreRect);+ entry.surface.ctx.putImageData(float.before.data, restoreRect.x - entry.rect.x, restoreRect.y - entry.rect.y);+ this.deps.notifyPainted(float.layerId);+ this.deps.invalidateLayer(float.layerId);+ }++ dispose(): void {+ if (this.disposed) {+ return;+ }+ // A live float holds pixels that exist nowhere else; put them back rather+ // than dropping them on the floor.+ this.cancel();+ this.disposed = true;+ }+}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex c623d45b1c..8b34907540 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -90,7 +90,7 @@ import type { LayerCacheEntry, LayerCacheStore } from '@workbench/canvas-engine/import type { OverlayCursor } from '@workbench/canvas-engine/render/overlayRenderer';import type { RenderScheduler } from '@workbench/canvas-engine/render/scheduler';import type { SamVisualInput } from '@workbench/canvas-engine/samInteraction';-import type { Rect, RenderFlags, ToolId, Vec2 } from '@workbench/canvas-engine/types';+import type { Mat2d, Rect, RenderFlags, ToolId, Vec2 } from '@workbench/canvas-engine/types';import type { CanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';@@ -141,6 +141,7 @@ import { createWheelHandler } from '@workbench/canvas-engine/input/wheel';import { fromTRS } from '@workbench/canvas-engine/math/mat2d';import { isEmpty, roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';import {+ type CompositeOptions,compositeDocument,createCheckerboardTile,shouldSmoothAtZoom,@@ -154,6 +155,7 @@ import { rasterizeSource, type ImageResolver, type RasterizeDeps } from '@workbeimport { textFontString } from '@workbench/canvas-engine/render/rasterizers/textRasterizer';import { enforceSurfaceBudget } from '@workbench/canvas-engine/render/surfaceBudget';import { getLayerThumbnailDisplayKey } from '@workbench/canvas-engine/render/thumbnail';+import { documentDeltaToLocal, floatDocumentMatrix } from '@workbench/canvas-engine/selection/floatingSelection';import { ANTS_STEP_PX, createAntsAnimator, type AntsAnimator } from '@workbench/canvas-engine/selection/marchingAnts';import { createBboxTool } from '@workbench/canvas-engine/tools/bboxTool';import { createBrushTool } from '@workbench/canvas-engine/tools/brushTool';@@ -162,14 +164,18 @@ import { createEraserTool } from '@workbench/canvas-engine/tools/eraserTool';import { createGradientTool } from '@workbench/canvas-engine/tools/gradientTool';import { createLassoTool } from '@workbench/canvas-engine/tools/lassoTool';import { createMarqueeTool } from '@workbench/canvas-engine/tools/marqueeTool';-import { hittableLayerRect, layerOutlineCorners } from '@workbench/canvas-engine/tools/moveHitTest';+import { hittableLayerRect, layerMatrix, layerOutlineCorners } from '@workbench/canvas-engine/tools/moveHitTest';import { createMoveTool } from '@workbench/canvas-engine/tools/moveTool';import { stepBrushSize } from '@workbench/canvas-engine/tools/paintConstants';import { createSamTool } from '@workbench/canvas-engine/tools/samTool';import { createShapeTool } from '@workbench/canvas-engine/tools/shapeTool';import { createTextTool } from '@workbench/canvas-engine/tools/textTool';import { createTransformTool } from '@workbench/canvas-engine/tools/transformTool';-import { type LayerTransform, transformOverlayGeometry } from '@workbench/canvas-engine/transform/transformMath';+import {+ bakeMatrix,+ type LayerTransform,+ transformOverlayGeometry,+} from '@workbench/canvas-engine/transform/transformMath';import { createViewport, MAX_DPR, type Viewport } from '@workbench/canvas-engine/viewport';import type { HistoryEntry } from './history/history';@@ -884,6 +890,18 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC};const editingController = new EditingController({+ floatingSelection: {+ applyImagePatch,+ backend,+ canEdit: () => canEditDocument(),+ endBurst: () => endNudgeBurst(),+ getDocument: () => mirror.getDocument(),+ history,+ invalidateLayer: (layerId) => scheduler.invalidate({ layers: [layerId] }),+ layers: layerCache,+ markDirty: (layerId) => bitmapStore.markLayerDirty(layerId),+ notifyPainted: notifyLayerPainted,+ },getDocument: () => mirror.getDocument(),selection: {backend,@@ -958,6 +976,35 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC},});const selection = editingController.selection;+ const floatingSelection = editingController.floatingSelection;++ /**+ * The float's render inputs for the current frame: the compositor's+ * layer-local placement, and the document-space matrix the ants ride through+ * so the outline tracks the pixels in flight.+ */+ const floatingSelectionRender = (+ doc: CanvasDocumentContractV2 | null+ ): { composite: NonNullable<CompositeOptions['floatingSelection']>; ants: Mat2d } | null => {+ const float = floatingSelection.get();+ const layer = float && doc ? doc.layers.find((candidate) => candidate.id === float.layerId) : undefined;+ if (!float || !layer) {+ return null;+ }+ const matrix = bakeMatrix(float.transform);+ const ants = floatDocumentMatrix(layerMatrix(layer.transform), matrix);+ return ants+ ? {+ ants,+ composite: {+ layerId: float.layerId,+ matrix,+ rect: float.pixels.rect,+ surface: float.pixels.surface,+ },+ }+ : null;+ };const antsAnimator: AntsAnimator = createAntsAnimator({cancelFrame: (handle) => globalThis.cancelAnimationFrame(handle),@@ -987,8 +1034,23 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCbeginTransformSession: (layerId) => beginTransformSession(layerId),cancelTextEdit: () => cancelTextEdit(),cancelTransform: () => cancelTransform(),- commitSelection: (commit) => selection.commit(commit),+ cancelFloatingSelection: () => floatingSelection.cancel(),+ commitFloatingSelection: () => floatingSelection.commit(),+ commitSelection: (commit) => {+ // A new selection supersedes the float's own; land the pixels first so the+ // committed op applies to the document the user can see.+ floatingSelection.commit();+ selection.commit(commit);+ },commitStructural: (label, forward, inverse) => commitStructural(label, forward, inverse),+ documentDeltaToLayerLocal: (layerId, delta) => {+ const layer = mirror.getDocument()?.layers.find((candidate) => candidate.id === layerId);+ return layer ? documentDeltaToLocal(layerMatrix(layer.transform), delta) : delta;+ },+ getFloatingSelection: () => floatingSelection.get(),+ isPointInSelection: (point) => selection.containsPoint(point),+ liftFloatingSelection: (layerId) => floatingSelection.lift(layerId),+ setFloatingTransform: (transform) => floatingSelection.setTransform(transform),createLayerId,createPath2D: createPath2DImpl,dispatch: (action) => dispatchCanvasMutation(action),@@ -1686,6 +1748,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst stagedPreview = renderController.previews.getStaged();const samPreview = renderController.previews.getSam();const filterPreviews = renderController.previews.filterSnapshot();+ // Resolved once: the composite draws the float's pixels, the overlay rides+ // the ants through the matching document-space transform.+ const floatRender = floatingSelectionRender(doc);if (needsComposite) {const stagedPlacement = stagedPreview?.placement;const isolatedGuard = samPreview?.isolated ? samPreview.guard : null;@@ -1736,6 +1801,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC? new Map(Array.from(filterPreviews, ([id, preview]) => [id, preview])): null,clipRect: isolatedGuard && samPreview ? samPreview.rect : null,+ // Pixels in flight, drawn directly above the layer they were cut from.+ floatingSelection: isolatedGuard ? null : (floatRender?.composite ?? null),// Feed the cached checkerboard tile only while the toggle is ON; passing// `null` renders transparent documents without a checkerboard.checkerboardTile: stores.checkerboard.get() ? getCheckerboardTile() : null,@@ -1813,7 +1880,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC// ants animator's overlay-only ticks.gradientPreview: stores.gradientPreview.get(),lassoPreview: stores.lassoPreview.get(),- marchingAnts: selection.hasSelection() ? { paths: selection.antsPaths(), phase: antsPhase } : null,+ marchingAnts: selection.hasSelection()+ ? { matrix: floatRender?.ants ?? null, paths: selection.antsPaths(), phase: antsPhase }+ : null,marqueePreview: stores.marqueePreview.get(),samInput: samSession?.input.type === 'visual' ? samSession.input : null,samPreview: samPreview ? { opacity: 0.45, rect: samPreview.rect, surface: samPreview.data } : null,@@ -1894,6 +1963,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCcleanup.run(clearAllFilterPreviews);// The selection is document-scoped interaction state: a swap drops it (and// any in-progress lasso preview), stopping the ants loop via onChange.+ // A float belongs to the outgoing document's layer. Cancel (not commit):+ // the layer it would bake into is about to be replaced.+ cleanup.run(() => floatingSelection.cancel());cleanup.run(() => selection.clear());cleanup.run(() => stores.lassoPreview.set(null));cleanup.run(() => stores.marqueePreview.set(null));@@ -1940,6 +2012,13 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC},onLayersChanged: (ids, sourceChangedIds) => {const cleanup = createCleanupAccumulator();+ const floatLayerId = floatingSelection.get()?.layerId;+ if (floatLayerId && ids.includes(floatLayerId)) {+ // The float's layer was replaced or removed. Drop the float rather than+ // baking pixels into a layer whose content just changed underneath them;+ // `cancel` is a no-op restore when the layer is already gone.+ cleanup.run(() => floatingSelection.cancel());+ }if (controlPixelController?.isOpenFor(ids)) {cleanup.run(() => pipeline.cancelActiveGesture());cleanup.run(cancelOpenControlPixelEdit);@@ -2061,6 +2140,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC*/onSelectionChanged: (selectedLayerId) => {const cleanup = createCleanupAccumulator();+ // A float belongs to exactly one layer; selecting another banks it rather+ // than leaving pixels in flight over a layer the user is no longer on.+ cleanup.run(() => floatingSelection.commit());const session = stores.transformSession.get();if (session && session.layerId !== selectedLayerId) {// The open session belongs to the layer that was just deselected; drop@@ -2172,6 +2254,13 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst interactionController = new InteractionController({beforeSwitch: (from, to, switchOptions) => {+ // A REAL tool switch banks a float — the pixels are already cut, and+ // carrying them into an unrelated tool would strand them. A temporary+ // modifier-hold switch (space → view to pan) must not: the user has not+ // finished the move.+ if (!switchOptions?.temporary) {+ floatingSelection.commit();+ }for (const listener of toolChangeListeners) {listener({ from, temporary: switchOptions?.temporary === true, to });}@@ -2207,6 +2296,13 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCcancelTransform();return;}+ if (floatingSelection.has()) {+ // Escape ABANDONS a float: the lifted pixels go back where they came from+ // and the selection stays, so the move can simply be redrawn. Committing+ // instead is what Enter / deselect / a tool switch do.+ floatingSelection.cancel();+ return;+ }if (applicationEscapeHandler?.(gestureWasActive)) {return;}@@ -2696,12 +2792,30 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC* an empty canvas; any renderable layer beyond it is unioned in. The closest* coherent analogue of legacy's bounded canvas for the complement in `invert`.*/- const selectAll = (): void => editingController.selectAll();- const deselect = (): void => editingController.deselect();- const invertSelection = (): void => editingController.invertSelection();+ // Every selection-level operation banks a live float first: the pixels are+ // already cut, and the op that follows must see the document the user does.+ // (Escape is the one path that abandons instead — see `handleEscapePriority`.)+ const selectAll = (): void => {+ floatingSelection.commit();+ editingController.selectAll();+ };+ const deselect = (): void => {+ floatingSelection.commit();+ editingController.deselect();+ };+ const invertSelection = (): void => {+ floatingSelection.commit();+ editingController.invertSelection();+ };- const fillSelection = (): void => editingController.selectionPixels.run('fill');- const eraseSelection = (): void => editingController.selectionPixels.run('erase');+ const fillSelection = (): void => {+ floatingSelection.commit();+ editingController.selectionPixels.run('fill');+ };+ const eraseSelection = (): void => {+ floatingSelection.commit();+ editingController.selectionPixels.run('erase');+ };const clearMask = (layerId: string): boolean => layerController.mask.clear(layerId);const dispose = (): void => {@@ -2822,8 +2936,17 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC!stores.textEditSession.get() &&mirror.getDocument() !== null;- const undo = (): void => historyController.undo();- const redo = (): void => historyController.redo();+ // A live float holds pixels that no history entry knows about, so replaying an+ // entry over them would write into a layer with a hole in it. Put them back+ // first; the float is not itself undoable until it commits.+ const undo = (): void => {+ floatingSelection.cancel();+ historyController.undo();+ };+ const redo = (): void => {+ floatingSelection.cancel();+ historyController.redo();+ };const setBboxGrid = (size: number): void => stores.bboxGrid.set(size > 0 ? size : 1);const getViewport = (): Viewport => viewport;const getCompositeExecutorDeps = (): CanvasCompositeExecutorDeps => ({diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.test.tsindex 821e84ca44..3732fa48a7 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.test.ts@@ -622,3 +622,71 @@ describe('shouldSmoothAtZoom', () => {expect(shouldSmoothAtZoom(20)).toBe(false);});});++describe('compositeDocument — floating selection', () => {+ const floatOf = (backend: ReturnType<typeof createTestStubRasterBackend>, layerId: string) => ({+ layerId,+ matrix: identity(),+ rect: { height: 8, width: 8, x: 0, y: 0 },+ surface: backend.createSurface(8, 8),+ });++ it('draws the float immediately above its own layer and below the next one up', () => {+ const backend = createTestStubRasterBackend();+ const caches = createLayerCacheStore(backend);+ const top = rasterLayer('top');+ const bottom = rasterLayer('bottom');+ const topCache = caches.getOrCreate('top', 10, 10);+ const bottomCache = caches.getOrCreate('bottom', 10, 10);+ const float = floatOf(backend, 'bottom');++ const target = backend.createSurface(200, 200);+ compositeDocument(target, makeDoc([top, bottom]), caches, VIEW, { floatingSelection: float });++ const drawn = target.callLog.filter((e) => e.op === 'drawImage').map((e) => e.args[0]);+ expect(drawn).toEqual([bottomCache.surface.canvas, float.surface.canvas, topCache.surface.canvas]);+ });++ it('inherits its layer opacity and blend mode', () => {+ const backend = createTestStubRasterBackend();+ const caches = createLayerCacheStore(backend);+ caches.getOrCreate('a', 10, 10);+ const float = floatOf(backend, 'a');++ const target = backend.createSurface(200, 200);+ const doc = makeDoc([rasterLayer('a', { blendMode: 'multiply' as CanvasBlendMode, opacity: 0.5 })]);+ compositeDocument(target, doc, caches, VIEW, { floatingSelection: float });++ // Twice: once for the layer's own cache, once for the float over it.+ expect(findSet(target.callLog, 'globalAlpha').filter((value) => value === 0.5)).toHaveLength(2);+ expect(findSet(target.callLog, 'globalCompositeOperation').filter((value) => value === 'multiply')).toHaveLength(2);+ });++ it('still draws a float whose source layer has been emptied by the cut', () => {+ // The lift can take everything a layer held; the detached pixels must not+ // vanish with it.+ const backend = createTestStubRasterBackend();+ const caches = createLayerCacheStore(backend);+ caches.getOrCreateRect('a', { height: 0, width: 0, x: 0, y: 0 });+ const float = floatOf(backend, 'a');++ const target = backend.createSurface(200, 200);+ compositeDocument(target, makeDoc([rasterLayer('a')]), caches, VIEW, { floatingSelection: float });++ const drawn = target.callLog.filter((e) => e.op === 'drawImage').map((e) => e.args[0]);+ expect(drawn).toEqual([float.surface.canvas]);+ });++ it('ignores a float whose layer id matches nothing in the document', () => {+ const backend = createTestStubRasterBackend();+ const caches = createLayerCacheStore(backend);+ const cache = caches.getOrCreate('a', 10, 10);+ const float = floatOf(backend, 'gone');++ const target = backend.createSurface(200, 200);+ compositeDocument(target, makeDoc([rasterLayer('a')]), caches, VIEW, { floatingSelection: float });++ const drawn = target.callLog.filter((e) => e.op === 'drawImage').map((e) => e.args[0]);+ expect(drawn).toEqual([cache.surface.canvas]);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.tsindex 213295e6b7..d378fd9e67 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts@@ -159,6 +159,15 @@ export interface CompositeOptions {adjustedSurface?: ((layer: CanvasLayerContract, entry: LayerCacheEntry) => RasterSurface | null) | null;/** Shared memoized surfaces for mask and control display effects. */derivedSurfaces?: DerivedSurfaceCache | null;+ /**+ * A live floating selection: pixels cut out of `layerId` and held in flight.+ * They are drawn immediately ABOVE their own layer (the hole they left is+ * already in that layer's cache), inheriting its opacity and blend mode, so+ * the z-order is right by construction. `surface`/`rect` are LAYER-LOCAL, and+ * `matrix` is the float's layer-local transform — both are composed with the+ * layer's own matrix at draw time. `null`/absent ⇒ nothing in flight.+ */+ floatingSelection?: { layerId: string; surface: RasterSurface; rect: Rect; matrix: Mat2d } | null;/** Optional deterministic render counters; omitted in the normal zero-overhead path. */diagnostics?: CanvasDiagnostics | null;}@@ -374,6 +383,26 @@ const drawCachedLayer = (ctx.restore();};+/**+ * Draws the floating selection over the layer it was cut from. Its pixels are+ * layer-local, so they go through the layer's (possibly overridden) matrix and+ * then the float's own — never resampled into document space and back.+ */+const drawFloatingSelection = (+ ctx: Ctx,+ layer: CanvasLayerContract,+ view: Mat2d,+ opts: CompositeOptions,+ float: NonNullable<CompositeOptions['floatingSelection']>+): void => {+ ctx.save();+ ctx.globalAlpha = layer.opacity;+ ctx.globalCompositeOperation = blendToComposite(layer.blendMode);+ setTransformFromMat(ctx, multiply(multiply(view, getEffectiveLayerMatrix(layer, opts)), float.matrix));+ ctx.drawImage(float.surface.canvas, float.rect.x, float.rect.y);+ ctx.restore();+};+/*** Composites `doc` onto `target`, using `caches` for each layer's pixels and* `view` as the document→screen transform.@@ -431,17 +460,25 @@ export const compositeDocument = (continue;}opts.diagnostics?.increment('layersConsidered');+ const float = opts.floatingSelection?.layerId === layer.id ? opts.floatingSelection : null;const entry = caches.get(layer.id);// Skip layers with no cache or an empty content rect (a brand-new / cleared- // paint / mask layer holds no pixels — nothing to draw).+ // paint / mask layer holds no pixels — nothing to draw). A float still draws:+ // its pixels are detached, so an emptied source layer must not hide them.if (!entry || entry.rect.width <= 0 || entry.rect.height <= 0) {+ if (float) {+ drawFloatingSelection(ctx, layer, view, opts, float);+ }continue;}- if (isDefinitelyOffscreen(layer, entry, view, target, opts)) {+ if (isDefinitelyOffscreen(layer, entry, view, target, opts) && !float) {opts.diagnostics?.increment('layersCulled');continue;}drawCachedLayer(ctx, layer, entry, view, opts);+ if (float) {+ drawFloatingSelection(ctx, layer, view, opts, float);+ }opts.diagnostics?.increment('layersDrawn');}};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/floatingSelection.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/floatingSelection.test.tsnew file mode 100644index 0000000000..181c00ede5--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/floatingSelection.test.ts@@ -0,0 +1,203 @@+import type { PlacedSurface, Rect } from '@workbench/canvas-engine/types';++import { fromTRS, identity } from '@workbench/canvas-engine/math/mat2d';+import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';+import { describe, expect, it } from 'vitest';++import {+ documentDeltaToLocal,+ floatDocumentMatrix,+ liftSelectedPixels,+ transformPlacedMask,+} from './floatingSelection';++const backend = createTestStubRasterBackend();++const placed = (rect: Rect): PlacedSurface => ({+ rect,+ surface: backend.createSurface(Math.max(0, rect.width), Math.max(0, rect.height)),+});++/** A layer matrix from the usual transform fields. */+const matrixOf = (t: { x?: number; y?: number; rotation?: number; scaleX?: number; scaleY?: number }) =>+ fromTRS({ x: t.x ?? 0, y: t.y ?? 0 }, t.rotation ?? 0, t.scaleX ?? 1, t.scaleY ?? t.scaleX ?? 1);++/** Rounds a matrix's components so exact trig comparisons stay readable. */+const rounded = (value: number): number => Math.round(value * 1e6) / 1e6;++describe('documentDeltaToLocal', () => {+ it('passes a delta through an identity layer unchanged', () => {+ expect(documentDeltaToLocal(identity(), { x: 10, y: -4 })).toEqual({ x: 10, y: -4 });+ });++ it('ignores the layer translation — a delta is a vector, not a point', () => {+ expect(documentDeltaToLocal(matrixOf({ x: 500, y: -300 }), { x: 10, y: -4 })).toEqual({ x: 10, y: -4 });+ });++ it('divides by the layer scale', () => {+ const local = documentDeltaToLocal(matrixOf({ scaleX: 2 }), { x: 10, y: 8 });+ expect(rounded(local.x)).toBe(5);+ expect(rounded(local.y)).toBe(4);+ });++ it('un-rotates by the layer rotation', () => {+ // The layer is rotated a quarter turn, so dragging right in document space+ // must move the pixels "up" in the layer's own frame.+ const local = documentDeltaToLocal(matrixOf({ rotation: Math.PI / 2 }), { x: 10, y: 0 });+ expect(rounded(local.x)).toBe(0);+ expect(rounded(local.y)).toBe(-10);+ });+});++describe('floatDocumentMatrix', () => {+ it('is the float transform itself under an identity layer', () => {+ const float = matrixOf({ x: 7, y: -3 });+ expect(floatDocumentMatrix(identity(), float)).toEqual(float);+ });++ it('leaves a translate unchanged under a translated layer (translations commute)', () => {+ const result = floatDocumentMatrix(matrixOf({ x: 100, y: 40 }), matrixOf({ x: 7, y: -3 }));+ expect(rounded(result!.e)).toBe(7);+ expect(rounded(result!.f)).toBe(-3);+ });++ it('scales a local translate up by the layer scale', () => {+ // 5 layer-local px on a 2× layer is 10 document px.+ const result = floatDocumentMatrix(matrixOf({ scaleX: 2 }), matrixOf({ x: 5, y: 0 }));+ expect(rounded(result!.e)).toBe(10);+ expect(rounded(result!.f)).toBe(0);+ });++ it('rotates a local translate into the document frame', () => {+ const result = floatDocumentMatrix(matrixOf({ rotation: Math.PI / 2 }), matrixOf({ x: 10, y: 0 }));+ expect(rounded(result!.e)).toBe(0);+ expect(rounded(result!.f)).toBe(10);+ });+});++describe('liftSelectedPixels', () => {+ const cache = () => placed({ height: 100, width: 100, x: 0, y: 0 });++ it('cuts the selection ∩ content region under an identity layer', () => {+ const lifted = liftSelectedPixels({+ backend,+ cache: cache(),+ layerMatrix: identity(),+ mask: placed({ height: 30, width: 30, x: 20, y: 20 }),+ });+ expect(lifted?.pixels.rect).toEqual({ height: 30, width: 30, x: 20, y: 20 });+ // The stencil covers exactly the same region, so the cut and the copy agree.+ expect(lifted?.localMask.rect).toEqual(lifted?.pixels.rect);+ });++ it('clips the region to what the layer actually holds', () => {+ const lifted = liftSelectedPixels({+ backend,+ cache: cache(),+ layerMatrix: identity(),+ mask: placed({ height: 50, width: 50, x: 80, y: 80 }),+ });+ // The selection runs off the layer's right/bottom edge.+ expect(lifted?.pixels.rect).toEqual({ height: 20, width: 20, x: 80, y: 80 });+ });++ it('maps the document-space mask into layer-local space through the layer translation', () => {+ const lifted = liftSelectedPixels({+ backend,+ cache: cache(),+ layerMatrix: matrixOf({ x: 10, y: 5 }),+ mask: placed({ height: 30, width: 30, x: 20, y: 20 }),+ });+ // Document (20,20) sits at layer-local (10,15) once the layer's own offset is undone.+ expect(lifted?.pixels.rect).toEqual({ height: 30, width: 30, x: 10, y: 15 });+ });++ it('maps through the layer scale', () => {+ const lifted = liftSelectedPixels({+ backend,+ cache: cache(),+ layerMatrix: matrixOf({ scaleX: 2 }),+ mask: placed({ height: 40, width: 40, x: 20, y: 20 }),+ });+ expect(lifted?.pixels.rect).toEqual({ height: 20, width: 20, x: 10, y: 10 });+ });++ it('maps through a layer rotation', () => {+ const lifted = liftSelectedPixels({+ backend,+ cache: placed({ height: 200, width: 200, x: -100, y: -100 }),+ layerMatrix: matrixOf({ rotation: Math.PI / 2 }),+ mask: placed({ height: 20, width: 10, x: 30, y: 40 }),+ });+ // A quarter turn swaps the axes: document x becomes local -y and vice versa,+ // so document [30,40]×[40,60] lands on local [40,60]×[-40,-30]. The region is+ // rounded OUTWARD, so trig landing a hair off an integer may widen it by a+ // pixel — harmless, since the stencil's alpha is zero out there.+ const rect = lifted!.pixels.rect;+ expect(rect.x).toBe(40);+ expect(rect.width).toBe(20);+ expect(rect.y).toBeGreaterThanOrEqual(-41);+ expect(rect.y).toBeLessThanOrEqual(-40);+ expect(rect.y + rect.height).toBeGreaterThanOrEqual(-30);+ expect(rect.y + rect.height).toBeLessThanOrEqual(-29);+ });++ it('returns null when the selection misses the layer entirely', () => {+ expect(+ liftSelectedPixels({+ backend,+ cache: cache(),+ layerMatrix: identity(),+ mask: placed({ height: 10, width: 10, x: 500, y: 500 }),+ })+ ).toBeNull();+ });++ it('returns null for an empty cache', () => {+ expect(+ liftSelectedPixels({+ backend,+ cache: placed({ height: 0, width: 0, x: 0, y: 0 }),+ layerMatrix: identity(),+ mask: placed({ height: 30, width: 30, x: 20, y: 20 }),+ })+ ).toBeNull();+ });++ it('returns null for a non-invertible layer matrix (a collapsed scale)', () => {+ expect(+ liftSelectedPixels({+ backend,+ cache: cache(),+ layerMatrix: matrixOf({ scaleX: 0 }),+ mask: placed({ height: 30, width: 30, x: 20, y: 20 }),+ })+ ).toBeNull();+ });+});++describe('transformPlacedMask', () => {+ it('re-places the mask rect through the matrix', () => {+ const moved = transformPlacedMask(+ backend,+ placed({ height: 30, width: 30, x: 20, y: 20 }),+ matrixOf({ x: 5, y: 7 })+ );+ expect(moved?.rect).toEqual({ height: 30, width: 30, x: 25, y: 27 });+ });++ it('grows the rect outward for a scale', () => {+ const moved = transformPlacedMask(+ backend,+ placed({ height: 30, width: 30, x: 20, y: 20 }),+ matrixOf({ scaleX: 2 })+ );+ expect(moved?.rect).toEqual({ height: 60, width: 60, x: 40, y: 40 });+ });++ it('returns null when the transform collapses the mask', () => {+ expect(+ transformPlacedMask(backend, placed({ height: 30, width: 30, x: 20, y: 20 }), matrixOf({ scaleX: 0 }))+ ).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/floatingSelection.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/floatingSelection.tsnew file mode 100644index 0000000000..f42923f9d0--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/floatingSelection.ts@@ -0,0 +1,191 @@+/**+ * The floating selection: pixels lifted out of a layer and held in flight.+ *+ * Dragging inside the marching ants cuts the selected pixels off the layer into+ * a transient float that follows the pointer, leaving a hole behind. The float+ * stays live — re-draggable, transformable — until it is committed (baked back+ * into the same layer as ONE undo entry) or cancelled (the hole refilled). This+ * module owns the geometry and the pixel extraction; `FloatingSelectionController`+ * owns the lifecycle, history, and persistence around it.+ *+ * ## Coordinate spaces+ *+ * The distinction that makes this work: **the selection mask is in DOCUMENT+ * space, the layer cache is in LAYER-LOCAL space.** They coincide only when the+ * layer's transform is the identity — which the existing `selectionOps` fill and+ * erase happen to assume. A float cannot assume it: it lands back in the layer+ * cache, so it must be exact under rotation and scale.+ *+ * So the float keeps its pixels and its live transform in **layer-local** space:+ *+ * - The lift maps the mask into layer-local through the inverse layer matrix,+ * which resamples the MASK (cheap, and only its coverage matters) rather than+ * the content.+ * - The lifted content is never resampled — a plain blit out and, for a pure+ * translate at whole pixels, a plain blit back.+ * - The move tool converts its document-space pointer delta into layer-local+ * before applying it (see {@link documentDeltaToLocal}).+ *+ * Zero React, zero import-time side effects.+ */++import type { RasterBackend } from '@workbench/canvas-engine/render/raster';+import type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';+import type { Mat2d, PlacedSurface, Rect, Vec2 } from '@workbench/canvas-engine/types';++import { applyToPoint, invert, multiply } from '@workbench/canvas-engine/math/mat2d';+import { intersect, isEmpty, roundOut, transformBounds } from '@workbench/canvas-engine/math/rect';++/** A live floating selection. */+export interface FloatingSelection {+ /** The layer the pixels were cut from, and the only layer they can bake into. */+ readonly layerId: string;+ /** The lifted pixels, placed at their lift-time rect in LAYER-LOCAL space. */+ readonly pixels: PlacedSurface;+ /** The layer cache's pre-lift pixels over the cut region, for cancel and the undo entry. */+ readonly before: { rect: Rect; data: ImageData };+ /** The selection mask at lift time, in DOCUMENT space — the ants follow it through the float's transform. */+ readonly mask: PlacedSurface;+ /** The float's live transform, in LAYER-LOCAL space. Identity at lift. */+ transform: LayerTransform;+}++/** Inputs to {@link liftSelectedPixels}. */+export interface LiftSelectedPixelsParams {+ backend: RasterBackend;+ /** The layer's cache surface and its layer-local content rect. */+ cache: PlacedSurface;+ /** The selection mask (alpha inside) and its document-space rect. */+ mask: PlacedSurface;+ /** The layer's local→document matrix. */+ layerMatrix: Mat2d;+}++/** What a lift produces, all in LAYER-LOCAL space. */+export interface LiftedPixels {+ /** The masked copy of the layer's content, sized to the cut region. */+ pixels: PlacedSurface;+ /**+ * The selection mask projected into layer-local space over the same region —+ * the stencil the caller punches the hole with, so the cut and the copy agree+ * to the pixel.+ */+ localMask: PlacedSurface;+}++/**+ * Converts a DOCUMENT-space delta into the layer's LOCAL space. Only the linear+ * part of the layer matrix applies — a delta is a vector, not a point, so the+ * translation must not be added.+ */+export const documentDeltaToLocal = (layerMatrix: Mat2d, delta: Vec2): Vec2 => {+ const inverse = invert(layerMatrix);+ if (!inverse) {+ return { x: 0, y: 0 };+ }+ const origin = applyToPoint(inverse, { x: 0, y: 0 });+ const moved = applyToPoint(inverse, delta);+ return { x: moved.x - origin.x, y: moved.y - origin.y };+};++/**+ * The float's transform expressed in DOCUMENT space: `L · F · L⁻¹`, where `L` is+ * the layer matrix and `F` the float's layer-local transform. Used to carry the+ * document-space selection mask along with the float on commit, so the marching+ * ants end up around the moved pixels.+ */+export const floatDocumentMatrix = (layerMatrix: Mat2d, floatMatrix: Mat2d): Mat2d | null => {+ const inverse = invert(layerMatrix);+ return inverse ? multiply(multiply(layerMatrix, floatMatrix), inverse) : null;+};++/**+ * Draws a document-space placed surface into a fresh surface covering `region`+ * in LAYER-LOCAL space, projecting through `inverseLayerMatrix`.+ */+const projectIntoLocal = (+ backend: RasterBackend,+ source: PlacedSurface,+ inverseLayerMatrix: Mat2d,+ region: Rect+): PlacedSurface => {+ const surface = backend.createSurface(region.width, region.height);+ const ctx = surface.ctx;+ ctx.setTransform(1, 0, 0, 1, 0, 0);+ ctx.globalCompositeOperation = 'source-over';+ ctx.globalAlpha = 1;+ // document → layer-local → region-local, so the source's own document-space+ // origin can be passed straight to `drawImage`.+ const toRegion = multiply({ a: 1, b: 0, c: 0, d: 1, e: -region.x, f: -region.y }, inverseLayerMatrix);+ ctx.setTransform(toRegion.a, toRegion.b, toRegion.c, toRegion.d, toRegion.e, toRegion.f);+ ctx.drawImage(source.surface.canvas, source.rect.x, source.rect.y);+ ctx.setTransform(1, 0, 0, 1, 0, 0);+ return { rect: region, surface };+};++/**+ * Copies the layer's content within the selection into a detached surface, and+ * returns the layer-local stencil that produced it. Returns `null` when the+ * selection does not overlap the layer's content — there would be nothing to+ * float.+ *+ * This does NOT modify the cache: punching the hole is the caller's step, done+ * with the returned `localMask` so the two agree exactly.+ */+export const liftSelectedPixels = ({+ backend,+ cache,+ layerMatrix,+ mask,+}: LiftSelectedPixelsParams): LiftedPixels | null => {+ const inverseLayerMatrix = invert(layerMatrix);+ if (!inverseLayerMatrix || isEmpty(cache.rect) || isEmpty(mask.rect)) {+ return null;+ }+ // The selection's extent in layer-local space, clipped to what the layer holds.+ const maskLocalBounds = roundOut(transformBounds(inverseLayerMatrix, mask.rect));+ const region = intersect(maskLocalBounds, cache.rect);+ if (!region || isEmpty(region)) {+ return null;+ }++ const localMask = projectIntoLocal(backend, mask, inverseLayerMatrix, region);++ const surface = backend.createSurface(region.width, region.height);+ const ctx = surface.ctx;+ ctx.setTransform(1, 0, 0, 1, 0, 0);+ ctx.globalCompositeOperation = 'source-over';+ ctx.globalAlpha = 1;+ ctx.drawImage(cache.surface.canvas, cache.rect.x - region.x, cache.rect.y - region.y);+ // Keep only what the selection covers.+ ctx.globalCompositeOperation = 'destination-in';+ ctx.drawImage(localMask.surface.canvas, 0, 0);+ ctx.globalCompositeOperation = 'source-over';++ return { localMask, pixels: { rect: region, surface } };+};++/**+ * Re-places a document-space mask through `matrix`, returning a fresh placed+ * surface — how the selection outline follows a committed float.+ */+export const transformPlacedMask = (+ backend: RasterBackend,+ mask: PlacedSurface,+ matrix: Mat2d+): PlacedSurface | null => {+ const rect = roundOut(transformBounds(matrix, mask.rect));+ if (isEmpty(rect)) {+ return null;+ }+ const surface = backend.createSurface(rect.width, rect.height);+ const ctx = surface.ctx;+ ctx.setTransform(1, 0, 0, 1, 0, 0);+ ctx.globalCompositeOperation = 'source-over';+ ctx.globalAlpha = 1;+ const placed = multiply({ a: 1, b: 0, c: 0, d: 1, e: -rect.x, f: -rect.y }, matrix);+ ctx.setTransform(placed.a, placed.b, placed.c, placed.d, placed.e, placed.f);+ ctx.drawImage(mask.surface.canvas, mask.rect.x, mask.rect.y);+ ctx.setTransform(1, 0, 0, 1, 0, 0);+ return { rect, surface };+};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/marchingAnts.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/marchingAnts.tsindex 7870d286f4..85db45a713 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/marchingAnts.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/marchingAnts.ts@@ -27,7 +27,7 @@import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Mat2d } from '@workbench/canvas-engine/types';-import { getScale } from '@workbench/canvas-engine/math/mat2d';+import { getScale, multiply } from '@workbench/canvas-engine/math/mat2d';/** Dash length in screen pixels; the offset advances by {@link ANTS_STEP_PX} per tick. */export const ANTS_DASH_PX = 4;@@ -45,6 +45,13 @@ export interface MarchingAntsRender {paths: readonly Path2D[];/** Animated dash offset in screen pixels. */phase: number;+ /**+ * An extra DOCUMENT-space transform to draw the outlines through, or absent+ * for none. A live floating selection sets it so the ants track the pixels in+ * flight without rebuilding the paths every frame; on commit the selection is+ * re-placed for real and this goes back to absent.+ */+ matrix?: Mat2d | null;}/**@@ -55,13 +62,16 @@ export const drawMarchingAnts = (ctx: RasterSurface['ctx'], view: Mat2d, render:if (render.paths.length === 0) {return;}+ const transform = render.matrix ? multiply(view, render.matrix) : view;+ // Line width and dash stay screen-constant, so they follow the VIEW scale+ // only — a float scaled up must not thicken its own outline.const scale = getScale(view) || 1;const dash = ANTS_DASH_PX / scale;const lineWidth = ANTS_LINE_WIDTH_PX / scale;const offset = render.phase / scale;ctx.save();- ctx.setTransform(view.a, view.b, view.c, view.d, view.e, view.f);+ ctx.setTransform(transform.a, transform.b, transform.c, transform.d, transform.e, transform.f);ctx.lineWidth = lineWidth;// Dark base run: a continuous dashed outline.diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.tsindex 55a19998c7..ae0f5e6a9f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.ts@@ -1,5 +1,7 @@import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { FloatingSelection } from '@workbench/canvas-engine/selection/floatingSelection';import type { Tool, ToolContext } from '@workbench/canvas-engine/tools/tool';+import type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';import type { PointerInput } from '@workbench/canvas-engine/types';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';@@ -79,32 +81,75 @@ interface Harness {dispatched: CanvasProjectMutation[];commits: StructuralCommit[];overrides: { layerId: string; override: { x: number; y: number } | null }[];+ /** The fake floating selection this harness hands the tool, if any. */+ float: { current: FloatingSelection | null };+ lifts: string[];+ commitFloat: ReturnType<typeof vi.fn>;+ transforms: LayerTransform[];}-const createHarness = (doc: CanvasDocumentContractV2): Harness => {+interface HarnessOptions {+ /** Whether a live selection contains every point (the ants are "under" the cursor). */+ selectionContainsPoint?: boolean;+ /** Whether a lift succeeds when the tool asks for one. */+ canLift?: boolean;+ /** A float that is already in flight before the gesture starts. */+ existingFloat?: boolean;+}++const IDENTITY: LayerTransform = { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 };++/** A minimal stand-in for a lifted float — only the fields the move tool reads. */+const fakeFloat = (layerId: string): FloatingSelection =>+ ({ layerId, transform: { ...IDENTITY } }) as FloatingSelection;++const createHarness = (doc: CanvasDocumentContractV2, options: HarnessOptions = {}): Harness => {const dispatched: CanvasProjectMutation[] = [];const commits: StructuralCommit[] = [];const overrides: { layerId: string; override: { x: number; y: number } | null }[] = [];+ const transforms: LayerTransform[] = [];+ const lifts: string[] = [];+ const float: { current: FloatingSelection | null } = {+ current: options.existingFloat ? fakeFloat(doc.selectedLayerId ?? 'a') : null,+ };+ const commitFloat = vi.fn();const ctx: ToolContext = {backend: null as never,+ commitFloatingSelection: commitFloat,commitStructural: (label, forward, inverse) => commits.push({ forward, inverse, label }),createLayerId: () => 'x',createPath2D: (d) => ({ d }) as unknown as Path2D,dispatch: (action) => dispatched.push(action),emitStrokeCommitted: vi.fn(),getDocument: () => doc,+ getFloatingSelection: () => float.current,invalidate: vi.fn(),- // A real (empty) layer cache so the move tool's live-cache-rect hit-test seam- // resolves; no test here relies on cached content, so entries stay absent.+ isPointInSelection: () => options.selectionContainsPoint === true,+ // A real (empty) layer cache so the tool's cache seam resolves; no test here+ // relies on cached content, so entries stay absent.layers: createLayerCacheStore(createTestStubRasterBackend()),+ liftFloatingSelection: (layerId) => {+ if (options.canLift === false) {+ return false;+ }+ lifts.push(layerId);+ float.current = fakeFloat(layerId);+ return true;+ },notifyLayerPainted: vi.fn(),+ setFloatingTransform: (transform) => {+ transforms.push(transform);+ if (float.current) {+ float.current.transform = transform;+ }+ },setLayerTransformOverride: (layerId, override) => overrides.push({ layerId, override }),setOverlayCursor: vi.fn(),stores: createEngineStores(),updateCursor: vi.fn(),viewport: null as never,};- return { commits, ctx, dispatched, overrides };+ return { commitFloat, commits, ctx, dispatched, float, lifts, overrides, transforms };};const down = (t: Tool, ctx: ToolContext, i: PointerInput): void => t.onPointerDown?.(ctx, i);@@ -330,3 +375,132 @@ describe('move tool: cancel', () => {expect(h.commits).toHaveLength(0);});});++describe('move tool: dragging a floating selection', () => {+ const doc = () => makeDoc([imageLayer('a', { x: 0, y: 0, width: 50, height: 50 })], 'a');++ it('lifts the selected pixels when the press lands inside the ants', () => {+ const h = createHarness(doc(), { selectionContainsPoint: true });+ const tool = createMoveTool();++ down(tool, h.ctx, pointer(10, 10));+ move(tool, h.ctx, pointer(30, 25));+ up(tool, h.ctx, pointer(30, 25));++ expect(h.lifts).toEqual(['a']);+ // The float moved, and the LAYER did not.+ expect(h.transforms.at(-1)).toMatchObject({ x: 20, y: 15 });+ expect(h.commits).toHaveLength(0);+ expect(h.overrides).toHaveLength(0);+ });++ it('moves the layer when the press lands outside the ants', () => {+ const h = createHarness(doc(), { selectionContainsPoint: false });+ const tool = createMoveTool();++ down(tool, h.ctx, pointer(10, 10));+ move(tool, h.ctx, pointer(30, 25));+ up(tool, h.ctx, pointer(30, 25));++ expect(h.lifts).toHaveLength(0);+ expect(h.commits).toHaveLength(1);+ expect(h.commits[0]!.forward).toMatchObject({ id: 'a' });+ });++ it('moves the layer when there is no selection at all', () => {+ const h = createHarness(doc());+ const tool = createMoveTool();++ down(tool, h.ctx, pointer(10, 10));+ move(tool, h.ctx, pointer(30, 25));+ up(tool, h.ctx, pointer(30, 25));++ expect(h.lifts).toHaveLength(0);+ expect(h.commits).toHaveLength(1);+ });++ it('drags an existing float even when the press is outside the ants', () => {+ // Once pixels are in flight they stay grabbable — the ants have moved with+ // them, and re-targeting the layer mid-move would be a trap.+ const h = createHarness(doc(), { existingFloat: true, selectionContainsPoint: false });+ const tool = createMoveTool();++ down(tool, h.ctx, pointer(10, 10));+ move(tool, h.ctx, pointer(40, 10));+ up(tool, h.ctx, pointer(40, 10));++ expect(h.lifts).toHaveLength(0);+ expect(h.transforms.at(-1)).toMatchObject({ x: 30, y: 0 });+ expect(h.commits).toHaveLength(0);+ });++ it('accumulates across drags, each starting from the float current position', () => {+ const h = createHarness(doc(), { selectionContainsPoint: true });+ const tool = createMoveTool();++ down(tool, h.ctx, pointer(10, 10));+ move(tool, h.ctx, pointer(30, 10));+ up(tool, h.ctx, pointer(30, 10));+ expect(h.transforms.at(-1)).toMatchObject({ x: 20, y: 0 });++ down(tool, h.ctx, pointer(30, 10));+ move(tool, h.ctx, pointer(45, 10));+ up(tool, h.ctx, pointer(45, 10));+ expect(h.transforms.at(-1)).toMatchObject({ x: 35, y: 0 });+ });++ it('falls back to moving the layer when the lift finds nothing to take', () => {+ const h = createHarness(doc(), { canLift: false, selectionContainsPoint: true });+ const tool = createMoveTool();++ down(tool, h.ctx, pointer(10, 10));+ move(tool, h.ctx, pointer(30, 25));+ up(tool, h.ctx, pointer(30, 25));++ expect(h.commits).toHaveLength(1);+ });++ it('constrains a float drag to the dominant axis under shift', () => {+ const h = createHarness(doc(), { selectionContainsPoint: true });+ const tool = createMoveTool();++ down(tool, h.ctx, pointer(10, 10));+ move(tool, h.ctx, pointer(40, 15, { shift: true }));+ up(tool, h.ctx, pointer(40, 15, { shift: true }));++ expect(h.transforms.at(-1)).toMatchObject({ x: 30, y: 0 });+ });++ it('reverts only the current drag on pointercancel, keeping the float', () => {+ const h = createHarness(doc(), { existingFloat: true });+ const tool = createMoveTool();+ h.float.current!.transform = { rotation: 0, scaleX: 1, scaleY: 1, x: 12, y: 4 };++ down(tool, h.ctx, pointer(10, 10));+ move(tool, h.ctx, pointer(40, 10));+ cancel(tool, h.ctx);++ expect(h.transforms.at(-1)).toEqual({ rotation: 0, scaleX: 1, scaleY: 1, x: 12, y: 4 });+ expect(h.float.current).not.toBeNull();+ });++ it('banks the float on Enter', () => {+ const h = createHarness(doc(), { existingFloat: true });+ const tool = createMoveTool();++ tool.onKeyCommand?.(h.ctx, 'apply');++ expect(h.commitFloat).toHaveBeenCalledTimes(1);+ });++ it('ignores Enter mid-drag, so a held pointer is never torn out from under', () => {+ const h = createHarness(doc(), { existingFloat: true });+ const tool = createMoveTool();++ down(tool, h.ctx, pointer(10, 10));+ move(tool, h.ctx, pointer(40, 10));+ tool.onKeyCommand?.(h.ctx, 'apply');++ expect(h.commitFloat).not.toHaveBeenCalled();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.tsindex 1d5ff8dec1..6439e2fafa 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.ts@@ -1,5 +1,5 @@/**- * The move tool: drag to move the SELECTED layer.+ * The move tool: drag to move the SELECTED layer, or the selected PIXELS.** Interaction contract:* - **The layers panel is the sole authority on which layer is active.** The move@@ -9,19 +9,30 @@* it — an editor where the pointer silently re-targets is the behaviour this* contract exists to prevent.* - **Click** (press+release under the drag threshold): a no-op.- * - **Drag**: moves the document's `selectedLayerId`, when that layer is enabled- * and unlocked. Hidden/locked layers are never dragged, and a press over empty- * space still drags the selected layer (the grab point is irrelevant).- * `shift` constrains motion to the dominant axis. Pointer-move only sets a- * transient transform override (live preview) — it never dispatches.- * - **Commit** (pointer-up after a real move): one `commitStructural` with the- * new/old transform x/y. A zero-delta drag commits nothing.- * - **Cancel** (Esc / pointercancel): drops the override, no dispatch.+ * - **Drag inside a live selection** — or with a float already in flight —+ * moves the selected PIXELS: the first such drag cuts them out of the selected+ * layer into a floating selection that follows the pointer, leaving a hole.+ * The float stays live across further drags until it is committed (Enter,+ * deselect, tool switch — one undo entry for the whole move) or cancelled+ * (Escape). This is the Photoshop feel: ants present and the press inside them+ * moves pixels; otherwise the press moves the layer.+ * - **Drag anywhere else**: moves the document's `selectedLayerId`, when that+ * layer is enabled and unlocked. Hidden/locked layers are never dragged, and a+ * press over empty space still drags the selected layer (the grab point is+ * irrelevant). Pointer-move only sets a transient transform override (live+ * preview) — it never dispatches.+ * - **`shift`** constrains motion to the dominant axis, for both modes.+ * - **Commit** (pointer-up after a real layer move): one `commitStructural` with+ * the new/old transform x/y. A zero-delta drag commits nothing. Moving a float+ * commits nothing here — the float's own commit does that later.+ * - **Cancel** (Esc / pointercancel): drops the layer override or reverts the+ * float to where this drag started. Neither dispatches.** Zero React, zero import-time side effects.*/import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';import type { PointerInput, Vec2 } from '@workbench/canvas-engine/types';import type { Tool, ToolContext } from './tool';@@ -42,13 +53,16 @@ export const constrainDelta = (dx: number, dy: number, shift: boolean): Vec2 =>return Math.abs(dx) >= Math.abs(dy) ? { x: dx, y: 0 } : { x: 0, y: dy };};+/** Which thing this gesture moves. */+type DragMode =+ | { kind: 'layer'; targetId: string; origin: { x: number; y: number } }+ | { kind: 'float'; layerId: string; origin: LayerTransform }+ | { kind: 'none' };+interface GestureState {startDoc: Vec2;startScreen: Vec2;- /** The layer being dragged (null when the selected layer isn't movable). */- targetId: string | null;- /** The drag target's original transform x/y. */- origin: { x: number; y: number } | null;+ mode: DragMode;moved: boolean;}@@ -57,8 +71,8 @@ export const createMoveTool = (): Tool => {let state: GestureState | null = null;const clearOverride = (ctx: ToolContext): void => {- if (state?.targetId) {- ctx.setLayerTransformOverride(state.targetId, null);+ if (state?.mode.kind === 'layer') {+ ctx.setLayerTransformOverride(state.mode.targetId, null);}};@@ -70,23 +84,63 @@ export const createMoveTool = (): Tool => {* The drag target is the document's selected layer, and nothing else — the* press point plays no part in choosing it.*/- const resolveDragTarget = (ctx: ToolContext): CanvasLayerContract | null => {+ const selectedDraggableLayer = (ctx: ToolContext): CanvasLayerContract | null => {const doc = ctx.getDocument();const selectedId = doc?.selectedLayerId;const selected = doc && selectedId ? doc.layers.find((layer) => layer.id === selectedId) : undefined;return selected && isDraggable(selected) ? selected : null;};- const previewAt = (ctx: ToolContext, input: PointerInput): void => {- if (!state || !state.targetId || !state.origin) {- return;+ /**+ * Resolves what a press at `point` drags. Pixels win over the layer when a+ * float is already in flight, or when a live selection contains the press.+ */+ const resolveMode = (ctx: ToolContext, point: Vec2): DragMode => {+ const existing = ctx.getFloatingSelection?.() ?? null;+ if (existing) {+ return { kind: 'float', layerId: existing.layerId, origin: { ...existing.transform } };+ }+ const layer = selectedDraggableLayer(ctx);+ if (!layer) {+ return { kind: 'none' };+ }+ if (ctx.isPointInSelection?.(point) && ctx.liftFloatingSelection?.(layer.id)) {+ const lifted = ctx.getFloatingSelection?.();+ if (lifted) {+ return { kind: 'float', layerId: lifted.layerId, origin: { ...lifted.transform } };+ }}- const delta = constrainDelta(- input.documentPoint.x - state.startDoc.x,- input.documentPoint.y - state.startDoc.y,+ return { kind: 'layer', origin: { x: layer.transform.x, y: layer.transform.y }, targetId: layer.id };+ };++ /** The constrained document-space delta from the gesture start to `input`. */+ const deltaFor = (current: GestureState, input: PointerInput): Vec2 =>+ constrainDelta(+ input.documentPoint.x - current.startDoc.x,+ input.documentPoint.y - current.startDoc.y,input.modifiers.shift);- ctx.setLayerTransformOverride(state.targetId, { x: state.origin.x + delta.x, y: state.origin.y + delta.y });++ const applyDelta = (ctx: ToolContext, current: GestureState, input: PointerInput): void => {+ const delta = deltaFor(current, input);+ if (current.mode.kind === 'layer') {+ ctx.setLayerTransformOverride(current.mode.targetId, {+ x: current.mode.origin.x + delta.x,+ y: current.mode.origin.y + delta.y,+ });+ return;+ }+ if (current.mode.kind === 'float') {+ // The float's transform is LAYER-LOCAL, so a document-space pointer delta+ // has to be mapped through the layer's inverse matrix first — otherwise a+ // rotated or scaled layer would drag the pixels off at an angle.+ const local = ctx.documentDeltaToLayerLocal?.(current.mode.layerId, delta) ?? delta;+ ctx.setFloatingTransform?.({+ ...current.mode.origin,+ x: current.mode.origin.x + local.x,+ y: current.mode.origin.y + local.y,+ });+ }};return {@@ -96,26 +150,32 @@ export const createMoveTool = (): Tool => {clearOverride(ctx);endGesture();},+ onKeyCommand: (ctx, command) => {+ // Enter banks a float in place. Escape's abandon runs on the engine's own+ // ladder (it must work whichever tool is active), so it is not handled here.+ if (command === 'apply' && !state) {+ ctx.commitFloatingSelection?.();+ }+ },onPointerCancel: (ctx) => {+ if (state?.mode.kind === 'float') {+ // Revert just this drag; the float itself survives (Escape's own+ // float-cancel is a separate, engine-level step).+ ctx.setFloatingTransform?.(state.mode.origin);+ }clearOverride(ctx);ctx.invalidate({ overlay: true });endGesture();},onPointerDown: (ctx, input) => {- if (state || (input.buttons & PRIMARY_BUTTON) === 0) {- return;- }- const doc = ctx.getDocument();- if (!doc) {+ if (state || (input.buttons & PRIMARY_BUTTON) === 0 || !ctx.getDocument()) {return;}- const dragTarget = resolveDragTarget(ctx);state = {+ mode: resolveMode(ctx, input.documentPoint),moved: false,- origin: dragTarget ? { x: dragTarget.transform.x, y: dragTarget.transform.y } : null,startDoc: input.documentPoint,startScreen: input.screenPoint,- targetId: dragTarget?.id ?? null,};},onPointerMove: (ctx, input) => {@@ -130,7 +190,7 @@ export const createMoveTool = (): Tool => {}state.moved = true;}- previewAt(ctx, input);+ applyDelta(ctx, state, input);},onPointerUp: (ctx, input) => {if (!state) {@@ -143,36 +203,34 @@ export const createMoveTool = (): Tool => {// A click never re-targets the layer selection — that is the panel's job.return;}-- if (!current.targetId || !current.origin) {+ if (current.mode.kind === 'none') {// No movable layer is selected — nothing to commit.return;}+ if (current.mode.kind === 'float') {+ // The float keeps the drag; it bakes later, as one entry for the whole+ // move however many drags it took.+ applyDelta(ctx, current, input);+ return;+ }- const delta = constrainDelta(- input.documentPoint.x - current.startDoc.x,- input.documentPoint.y - current.startDoc.y,- input.modifiers.shift- );- const next = { x: current.origin.x + delta.x, y: current.origin.y + delta.y };+ const delta = deltaFor(current, input);+ const origin = current.mode.origin;+ const next = { x: origin.x + delta.x, y: origin.y + delta.y };- if (next.x === current.origin.x && next.y === current.origin.y) {+ if (next.x === origin.x && next.y === origin.y) {// Zero-delta drag: drop the preview, commit nothing.- ctx.setLayerTransformOverride(current.targetId, null);+ ctx.setLayerTransformOverride(current.mode.targetId, null);return;}ctx.commitStructural('Move layer',- { id: current.targetId, patch: { transform: { x: next.x, y: next.y } }, type: 'updateCanvasLayer' },- {- id: current.targetId,- patch: { transform: { x: current.origin.x, y: current.origin.y } },- type: 'updateCanvasLayer',- }+ { id: current.mode.targetId, patch: { transform: { x: next.x, y: next.y } }, type: 'updateCanvasLayer' },+ { id: current.mode.targetId, patch: { transform: { x: origin.x, y: origin.y } }, type: 'updateCanvasLayer' });// The committed transform now flows through the mirror; drop the preview.- ctx.setLayerTransformOverride(current.targetId, null);+ ctx.setLayerTransformOverride(current.mode.targetId, null);},};};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.tsindex 61701964a4..9925bee8b3 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts@@ -21,6 +21,7 @@ import type { OverlayCursor } from '@workbench/canvas-engine/render/overlayRendeimport type { RasterBackend } from '@workbench/canvas-engine/render/raster';import type { InvalidatePayload } from '@workbench/canvas-engine/render/scheduler';import type { SamInteractionState, SamVisualInput } from '@workbench/canvas-engine/samInteraction';+import type { FloatingSelection } 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';@@ -176,6 +177,27 @@ export interface ToolContext {getSelectionMask?(): PlacedSurface | null;/** Updates visual SAM input for the active engine-owned Select Object session. */updateSamInput?(input: SamVisualInput): void;+ /**+ * Cuts the current selection's pixels out of `layerId` into a floating+ * selection, returning whether anything was lifted. Absent in minimal test+ * harnesses.+ */+ liftFloatingSelection?(layerId: string): boolean;+ /** The live floating selection, or `null`. */+ getFloatingSelection?(): FloatingSelection | null;+ /** Sets the float's live transform (LAYER-LOCAL space). */+ setFloatingTransform?(transform: LayerTransform): void;+ /** Bakes the float back into its layer as one undoable entry. */+ commitFloatingSelection?(): void;+ /** Puts the float's pixels back untouched, pushing no history. */+ cancelFloatingSelection?(): void;+ /**+ * Converts a DOCUMENT-space delta into `layerId`'s LOCAL space, so a pointer+ * drag moves a float correctly under a rotated/scaled layer.+ */+ documentDeltaToLayerLocal?(layerId: string, delta: Vec2): Vec2;+ /** True if `point` (document space) falls inside the live selection. */+ isPointInSelection?(point: Vec2): boolean;}/**