Skip to content

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

fix(canvas): admit floating selections from lift to landing

Josh Corbett9130407a3a40
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
index dc5f3cde12..134111c133 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
@@ -154,7 +154,11 @@ Invalidate only the affected effect when parameters change. Delete every derived
## Edits, history and replay
-Every recorded document and pixel edit goes through one protocol, `CanvasMutationContext.begin`, and is admitted before it mutates anything. Admission reserves the undo entry's bytes in `History` without clearing redo or evicting older steps, so an edit whose entry could never be kept is refused as `over-budget` while the document, pixels and history are untouched. Two kinds of edit are admitted before they change anything but publish afterwards: live strokes paint as they are admitted (see below), and a floating selection is admitted when it lands. Selection-mask changes (`selection/selectionHistory.ts`) admit their step right after applying, because the new mask's size is only known then, and roll back to the exact prior selection when it cannot be kept. The resulting `EditTransaction` also reserves raster memory for its preparation (`reserveRaster`), holds leases and pins until `end()`, and publishes once: `publish(label, step, entry)` applies an `EditStep` — an optional document mutation with its postcondition and rollback, prepared pixels to install, and ancillary notifications — verifies the reducer and mirror, records the entry, then routes a user edit and notifies. A step that is rejected or fails its postconditions records nothing; a failed postcondition dispatches the step's rollback and reports when the reducer or mirror could not return. Transactions refuse while the permit is stale, a gesture runs (unless the edit belongs to that gesture), a replay runs, or the engine is disposed. Coalescing (nudges) names the entry it replaces by its `HistoryEntryToken` and is refused once anything else became the newest step.
+Every recorded document and pixel edit goes through one protocol, `CanvasMutationContext.begin`, and is admitted before it mutates anything. Admission reserves the undo entry's bytes in `History` without clearing redo or evicting older steps, so an edit whose entry could never be kept is refused as `over-budget` while the document, pixels and history are untouched. Two kinds of edit are admitted before they change anything but publish afterwards: live strokes paint as they are admitted (see below), and a floating selection holds its admission from lift to landing. Selection-mask changes (`selection/selectionHistory.ts`) admit their step right after applying, because the new mask's size is only known then, and roll back to the exact prior selection when it cannot be kept. The resulting `EditTransaction` also reserves raster memory for its preparation (`reserveRaster`), holds leases and pins until `end()`, and publishes once: `publish(label, step, entry)` applies an `EditStep` — an optional document mutation with its postcondition and rollback, prepared pixels to install, and ancillary notifications — verifies the reducer and mirror, records the entry, then routes a user edit and notifies. A step that is rejected or fails its postconditions records nothing; a failed postcondition dispatches the step's rollback and reports when the reducer or mirror could not return. Transactions refuse while the permit is stale, a gesture runs (unless the edit belongs to that gesture), a replay runs, or the engine is disposed. Coalescing (nudges) names the entry it replaces by its `HistoryEntryToken` and is refused once anything else became the newest step.
+
+Layer controllers build their steps from `controllers/editSteps.ts`: byte accounting, replay reservations (a replay whose preparation memory does not fit throws `REPLAY_RASTER_REFUSAL` and stays in place), the steps that add, replace and remove layers with their prepared pixels, and new paint layers. It also names how a publication that did not land is reported: ordinary layer operations (merge, crop, copy, rasterize, insert) report a reducer refusal or failed postcondition as `failed` (`layerOperationStatus`), while guarded result operations (generated, filter, mask and staged results, mask edits, duplicate) report it as `stale` (`guardedResultRefusal`), because their target moved on after the guard was taken.
+
+A floating selection (`FloatingSelectionController`) computes its commit footprint from geometry before it copies or cuts anything: before and after pixels over the union of the hole and the landing, the selection alpha before and after, and the entry overhead. It is admitted for that footprint as part of the drag that lifts it, and keeps the transaction until it lands or is dropped. Every move, scale or rotation grows the admission to the footprint at the new transform, from geometry alone; a transform that does not fit keeps the last accepted one and reports `over-budget` once per float, so an accepted transform always fits its undo entry while the permit stays current; the admission never shrinks, so a live float holds its largest accepted footprint until it lands or is dropped. A refused lift is reported and moves nothing (`lift` returns `refused`), including content whose cache is not rebuilt yet; only a lift with nothing to take (`unavailable`) lets the Move tool fall back to moving the layer. The cut layer's persistence is suspended while the float lives. Commit lands the pixels and the moved selection as one entry under the retained admission, renewed once when its permit went stale (an operation locked and released the document meanwhile); a commit that cannot be admitted or published puts the pre-lift pixels and selection back. Cancellation refills the hole before persistence resumes, and a hole that cannot be refilled keeps the layer suspended rather than uploading it. Every terminal path ends the transaction: commit, cancel, Escape, undo/redo, the layer's deletion or replacement, document replacement, cooldown (which banks the float before the flush), disposal, and exceptions while cutting or landing.
Live pixel edits (brush, eraser, shapes, pixel transactions on control and image layers) are admitted before their first pixel changes and grow their admission before the stroke's before/after footprint does; a refused growth restores the layer's pixels and extent and the engine reports the refusal through `tools.onEditRefused`, which the canvas widget turns into a notice. Widget previews of structural edits run in one owned `StructuralPreviewSession` (`useStructuralPreview`), which coalesces live dispatches to one per frame and records the gesture as a single step; a refused commit or a cancel restores the baseline, even while edits are locked.
@@ -188,7 +192,7 @@ The pointer pipeline (`input/pointerPipeline.ts`) owns gesture capture and the t
## Lifecycle
-Lifecycle states are `active`, `cooling`, `cool`, and `disposed`. Losing the final registry reference immediately detaches input/render targets, cancels background PSD work and rasterization, releases the old generation's reservations, and starts a dirty-pixel flush. Successful, still-current flushes release every derived and group surface and each base cache that no read lease pins and no session holds, then trim history. Failed flushes retain dirty pixels and remain retryable; the registry retains the engine and retries after another grace period, disposing it only after a `cooled` result. Reacquisition increments the lifecycle generation so late flush or grace-period work cannot clean up or dispose a live engine. Operation-owned reservations and pins survive these generation transitions until their owning operation settles.
+Lifecycle states are `active`, `cooling`, `cool`, and `disposed`. Losing the final registry reference immediately banks a live floating selection, detaches input/render targets, cancels background PSD work and rasterization, releases the old generation's reservations, and starts a dirty-pixel flush. Successful, still-current flushes release every derived and group surface and each base cache that no read lease pins and no session holds, then trim history. Failed flushes retain dirty pixels and remain retryable; the registry retains the engine and retries after another grace period, disposing it only after a `cooled` result. Reacquisition increments the lifecycle generation so late flush or grace-period work cannot clean up or dispose a live engine. Operation-owned reservations and pins survive these generation transitions until their owning operation settles.
Operations that write an open project's document elsewhere (close, export, duplicate) first cross its engine's paint barrier through the open-project handle and the Workbench's `LiveCanvasEngines` registry; close crosses it again after the push so pixels painted meanwhile are not lost. These barriers do not wait on an edit that holds dirty pixels (a session, gesture or suspension): they fail fast and ask the user to finish or cancel it, and if unsaved pixels cannot be persisted the project stays open with its engine state intact. Rename keeps its tolerant flush. Invocation waits for short-lived holds. Disposal cancels outstanding work and releases every resource category: caches, decoded bitmaps, reservations, pins and outstanding snapshots.
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.ts
index 7b677629a2..c5d333baf3 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
@@ -73,7 +73,6 @@ const createSelectionPixelOptions = () => ({
const createFloatingSelectionOptions = () => ({
applyImagePatch: vi.fn(),
backend: {} as never,
- canEdit: () => true,
ctx: {} as never,
getDocument: () => null,
invalidateLayer: vi.fn(),
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.ts
index ab3ac281b9..49bb8049cf 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.ts
@@ -110,6 +110,12 @@ export class EditingController {
cooldown(): void {
if (!this.disposed) {
+ // Leaving the canvas banks a float like a tool switch, so the flush that follows persists it.
+ try {
+ this.floatingSelection.commit();
+ } catch {
+ // A float that cannot land has been put back; cooldown proceeds regardless.
+ }
this.editGate.cooldown();
}
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.browser.test.ts
new file mode 100644
index 0000000000..54c99a12f7
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.browser.test.ts
@@ -0,0 +1,185 @@
+import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';
+import type { Rect } from '@workbench/canvas-engine/types';
+
+import { createCanvasMutationContext } from '@workbench/canvas-engine/controllers/mutationContext';
+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
+import { createHistory } from '@workbench/canvas-engine/history/history';
+import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';
+import { createDomRasterBackend } from '@workbench/canvas-engine/render/raster';
+import { createSelectionState } from '@workbench/canvas-engine/selection/selectionState';
+import { describe, expect, it, vi } from 'vitest';
+
+import { FloatingSelectionController } from './floatingSelectionController';
+
+const LAYER: CanvasLayerContract = {
+ blendMode: 'normal',
+ id: 'a',
+ isEnabled: true,
+ isLocked: false,
+ name: 'a',
+ opacity: 1,
+ source: { bitmap: null, offset: { x: 0, y: 0 }, type: 'paint' },
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
+ type: 'raster',
+};
+
+const DOCUMENT: CanvasDocumentContractV3 = {
+ background: 'transparent',
+ bbox: { height: 100, width: 100, x: 0, y: 0 },
+ height: 100,
+ selectedLayerId: 'a',
+ stacks: stacksFrom([LAYER]),
+ version: 3,
+ width: 100,
+};
+
+/** Every view reads this fixed area, so caches of different extents compare pixel for pixel. */
+const VIEW: Rect = { height: 40, width: 80, x: 0, y: 0 };
+
+const createHarness = (byteBudget = 64 * 1024 * 1024) => {
+ const backend = createDomRasterBackend();
+ const layers = createLayerCacheStore(backend);
+ const history = createHistory({ byteBudget });
+ const selection = createSelectionState({
+ backend,
+ createPath2D: (d) => new Path2D(d),
+ getDocumentSize: () => ({ height: 100, width: 100 }),
+ onChange: () => undefined,
+ });
+
+ // Distinct opaque pixels everywhere, so any misplaced copy shows.
+ const entry = layers.getOrCreateRect('a', { height: 40, width: 40, x: 0, y: 0 });
+ const seed = entry.surface.ctx.createImageData(40, 40);
+ for (let index = 0; index < 40 * 40; index += 1) {
+ seed.data.set([index % 40, Math.floor(index / 40), 200, 255], index * 4);
+ }
+ entry.surface.ctx.putImageData(seed, 0, 0);
+
+ const mask = backend.createSurface(10, 10);
+ mask.ctx.fillStyle = '#fff';
+ mask.ctx.fillRect(0, 0, 10, 10);
+ selection.replaceMask({ rect: { height: 10, width: 10, x: 10, y: 10 }, surface: mask });
+
+ const ctx = createCanvasMutationContext({
+ commitEdit: vi.fn(),
+ createLayerId: () => 'unused',
+ dispatch: () => true,
+ editOwner: Symbol('owner'),
+ editingLocked: { get: () => false, subscribe: () => () => undefined },
+ getDocument: () => DOCUMENT,
+ getReducerDocument: () => DOCUMENT,
+ history,
+ installPrepared: () => undefined,
+ isGestureActive: () => false,
+ isGuardCurrent: () => true,
+ preparePixels: () => {
+ throw new Error('unused');
+ },
+ projectId: 'p',
+ refreshMirror: () => undefined,
+ reserveRaster: () => ({ lease: { release: () => undefined }, status: 'ok' }),
+ subscribeReducer: () => () => undefined,
+ });
+ const reportRefusal = vi.fn();
+ const controller = new FloatingSelectionController({
+ applyImagePatch: (layerId, rect, pixels) => {
+ const target = layers.growToRect(layerId, rect);
+ target.surface.ctx.putImageData(pixels, rect.x - target.rect.x, rect.y - target.rect.y);
+ return Promise.resolve();
+ },
+ backend,
+ ctx,
+ getDocument: () => DOCUMENT,
+ invalidateLayer: () => undefined,
+ layers,
+ markDirty: () => undefined,
+ notifyPainted: () => undefined,
+ onChange: () => undefined,
+ reportRefusal,
+ selection,
+ suspendPersistence: () => () => undefined,
+ });
+
+ /** The layer's pixels over {@link VIEW}, transparent where the cache does not reach. */
+ const pixels = (): number[] => {
+ const view = backend.createSurface(VIEW.width, VIEW.height);
+ const cache = layers.get('a')!;
+ view.ctx.drawImage(cache.surface.canvas, cache.rect.x - VIEW.x, cache.rect.y - VIEW.y);
+ return [...view.ctx.getImageData(0, 0, VIEW.width, VIEW.height).data];
+ };
+ const pixelAt = (x: number, y: number): number[] =>
+ pixels().slice((y * VIEW.width + x) * 4, (y * VIEW.width + x) * 4 + 4);
+ const selected = () => {
+ const snapshot = selection.snapshot();
+ return { alpha: snapshot.alpha ? [...snapshot.alpha] : null, rect: snapshot.rect };
+ };
+
+ return { controller, history, pixelAt, pixels, reportRefusal, selected };
+};
+
+describe('FloatingSelectionController in a real raster backend', () => {
+ it('restores exact pixels and selection on undo, and the landed ones on redo', async () => {
+ const h = createHarness();
+ const originalPixels = h.pixels();
+ const originalSelection = h.selected();
+
+ expect(h.controller.lift('a')).toBe('lifted');
+ expect(h.controller.setTransform({ rotation: 0, scaleX: 1, scaleY: 1, x: 35, y: 0 })).toBe(true);
+ h.controller.commit();
+
+ // The hole is clear and the pixels landed past the original cache edge.
+ expect(h.pixelAt(12, 12)).toEqual([0, 0, 0, 0]);
+ expect(h.pixelAt(47, 12)).toEqual([12, 12, 200, 255]);
+ expect(h.selected().rect).toEqual({ height: 10, width: 10, x: 45, y: 10 });
+ const landedPixels = h.pixels();
+ const landedSelection = h.selected();
+
+ expect(await h.history.undo()).toEqual({ status: 'applied' });
+ expect(h.pixels()).toEqual(originalPixels);
+ expect(h.selected()).toEqual(originalSelection);
+
+ expect(await h.history.redo()).toEqual({ status: 'applied' });
+ expect(h.pixels()).toEqual(landedPixels);
+ expect(h.selected()).toEqual(landedSelection);
+ });
+
+ it('restores exact pixels on cancel, recording nothing', () => {
+ const h = createHarness();
+ const originalPixels = h.pixels();
+
+ h.controller.lift('a');
+ h.controller.setTransform({ rotation: 0, scaleX: 1, scaleY: 1, x: 20, y: 5 });
+ h.controller.cancel();
+
+ expect(h.pixels()).toEqual(originalPixels);
+ expect(h.history.canUndo()).toBe(false);
+ });
+
+ it('commits an enlarged, rotated float with every other byte of the budget taken', () => {
+ const budget = 1024 * 1024;
+ const h = createHarness(budget);
+ h.controller.lift('a');
+ expect(h.controller.setTransform({ rotation: Math.PI / 6, scaleX: 1.5, scaleY: 2, x: 12, y: 3 })).toBe(true);
+
+ // Take the largest edit that still fits beside the float's admission.
+ let low = 0;
+ let high = budget;
+ while (low < high) {
+ const mid = Math.ceil((low + high) / 2);
+ const probe = h.history.admit(mid);
+ probe?.release();
+ if (probe) {
+ low = mid;
+ } else {
+ high = mid - 1;
+ }
+ }
+ const rest = h.history.admit(low)!;
+
+ h.controller.commit();
+
+ expect(h.history.entries().past).toEqual(['Move selection']);
+ expect(h.reportRefusal).not.toHaveBeenCalled();
+ rest.release();
+ });
+});
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.ts
index 67026022ce..ed787cb3fa 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.test.ts
@@ -4,7 +4,7 @@ import type { PlacedSurface, Rect } from '@workbench/canvas-engine/types';
import { createCanvasMutationContext } from '@workbench/canvas-engine/controllers/mutationContext';
import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
-import { createHistory } from '@workbench/canvas-engine/history/history';
+import { createHistory, HISTORY_BYTE_BUDGET } 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';
@@ -34,7 +34,7 @@ const makeDoc = (layers: CanvasLayerContract[]): CanvasDocumentContractV3 => ({
});
const createHarness = (
- options: { layer?: CanvasLayerContract; maskRect?: Rect; cacheRect?: Rect; byteBudget?: number } = {}
+ options: { layer?: CanvasLayerContract; maskRect?: Rect; cacheRect?: Rect | null; byteBudget?: number } = {}
) => {
const backend = createTestStubRasterBackend();
const layers = createLayerCacheStore(backend);
@@ -65,7 +65,9 @@ const createHarness = (
} 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 });
+ if (options.cacheRect !== null) {
+ layers.getOrCreateRect(layer.id, options.cacheRect ?? { height: 100, width: 100, x: 0, y: 0 });
+ }
const releasePersistence = vi.fn();
const calls = {
@@ -78,12 +80,20 @@ const createHarness = (
reportRefusal: vi.fn(),
suspendPersistence: vi.fn(() => releasePersistence),
};
+ let locked = false;
+ const lockListeners = new Set<() => void>();
const ctx = createCanvasMutationContext({
commitEdit: vi.fn(),
createLayerId: () => 'unused',
dispatch: () => true,
editOwner: Symbol('owner'),
- editingLocked: { get: () => false, subscribe: () => () => undefined },
+ editingLocked: {
+ get: () => locked,
+ subscribe: (listener) => {
+ lockListeners.add(listener);
+ return () => lockListeners.delete(listener);
+ },
+ },
getDocument: () => document,
getReducerDocument: () => document,
history,
@@ -102,7 +112,6 @@ const createHarness = (
const controller = new FloatingSelectionController({
applyImagePatch: calls.applyImagePatch,
backend,
- canEdit: () => true,
ctx,
getDocument: () => document,
invalidateLayer: calls.invalidateLayer,
@@ -115,6 +124,7 @@ const createHarness = (
suspendPersistence: calls.suspendPersistence,
});
+ const budget = options.byteBudget ?? HISTORY_BYTE_BUDGET;
return {
backend,
calls,
@@ -124,6 +134,27 @@ const createHarness = (
layers,
replaceMask,
selection,
+ /** History bytes the float holds, probed through admission: the largest edit that still fits is the rest. */
+ heldBytes: (): number => {
+ let low = 0;
+ let high = budget;
+ while (low < high) {
+ const mid = Math.ceil((low + high) / 2);
+ const admission = history.admit(mid);
+ admission?.release();
+ if (admission) {
+ low = mid;
+ } else {
+ high = mid - 1;
+ }
+ }
+ return budget - low;
+ },
+ disposeContext: () => ctx.dispose(),
+ setLocked: (value: boolean) => {
+ locked = value;
+ lockListeners.forEach((listener) => listener());
+ },
removeLayer: () => {
document = makeDoc([]);
},
@@ -131,13 +162,19 @@ const createHarness = (
};
/** Moves the float by a layer-local delta. */
-const move = (controller: FloatingSelectionController, x: number, y: number): void =>
+const move = (controller: FloatingSelectionController, x: number, y: number): boolean =>
controller.setTransform({ rotation: 0, scaleX: 1, scaleY: 1, x, y });
+// Commit bytes for the default 30×30 lift at (20, 20) on an identity layer: before and after RGBA over the
+// hole∪landing union, the 30×30 selection alpha before and after, and the entry overhead.
+const commitBytes = (patchWidth: number, patchHeight: number, movedMaskPixels = 900): number =>
+ patchWidth * patchHeight * 8 + 900 + movedMaskPixels + 256;
+const LIFT_BYTES = commitBytes(30, 30);
+
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.lift('a')).toBe('lifted');
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 });
@@ -145,6 +182,12 @@ describe('FloatingSelectionController: lift', () => {
expect(h.controller.get()?.transform).toEqual({ rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 });
});
+ it('holds history admission for an unmoved commit from the moment it lifts', () => {
+ const h = createHarness();
+ h.controller.lift('a');
+ expect(h.heldBytes()).toBe(LIFT_BYTES);
+ });
+
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();
@@ -178,31 +221,180 @@ describe('FloatingSelectionController: lift', () => {
expect(cancelled.calls.releasePersistence).toHaveBeenCalledOnce();
});
- it('refuses a second lift while a float is live', () => {
+ it('refuses a lift whose commit could never be recorded before copying or cutting anything', () => {
+ const h = createHarness({ byteBudget: LIFT_BYTES - 1 });
+ const surface = h.layers.get('a')!.surface as unknown as { callLog: unknown[] };
+ const drawnBefore = surface.callLog.length;
+
+ expect(h.controller.lift('a')).toBe('refused');
+
+ expect(h.controller.has()).toBe(false);
+ expect(h.calls.reportRefusal).toHaveBeenCalledExactlyOnceWith('over-budget');
+ expect(surface.callLog).toHaveLength(drawnBefore);
+ expect(h.calls.suspendPersistence).not.toHaveBeenCalled();
+ expect(h.calls.notifyPainted).not.toHaveBeenCalled();
+ expect(h.heldBytes()).toBe(0);
+ });
+
+ it('refuses and reports a lift while editing is locked, admitting and cutting nothing', () => {
const h = createHarness();
- expect(h.controller.lift('a')).toBe(true);
- expect(h.controller.lift('a')).toBe(false);
+ h.setLocked(true);
+
+ expect(h.controller.lift('a')).toBe('refused');
+
+ expect(h.calls.reportRefusal).toHaveBeenCalledExactlyOnceWith('busy');
+ expect(h.calls.suspendPersistence).not.toHaveBeenCalled();
+ expect(h.heldBytes()).toBe(0);
+ });
+
+ it('refuses a lift from content whose cache is not rebuilt yet, so the layer is not moved instead', () => {
+ const h = createHarness({
+ cacheRect: null,
+ layer: {
+ ...(paintLayer('a') as Extract<CanvasLayerContract, { type: 'raster' }>),
+ source: { bitmap: { height: 100, imageName: 'paint', width: 100 }, offset: { x: 0, y: 0 }, type: 'paint' },
+ },
+ });
+
+ expect(h.controller.lift('a')).toBe('refused');
+ expect(h.calls.reportRefusal).toHaveBeenCalledExactlyOnceWith('not-ready');
+ expect(h.heldBytes()).toBe(0);
+
+ expect(createHarness({ cacheRect: null }).controller.lift('a')).toBe('unavailable');
+ });
+
+ it('lifts when the budget covers exactly the unmoved commit', () => {
+ const h = createHarness({ byteBudget: LIFT_BYTES });
+ expect(h.controller.lift('a')).toBe('lifted');
});
- it('refuses a locked layer', () => {
- const h = createHarness({ layer: { ...paintLayer('a'), isLocked: true } });
- expect(h.controller.lift('a')).toBe(false);
+ it('reports a second lift while a float is live as unavailable', () => {
+ const h = createHarness();
+ expect(h.controller.lift('a')).toBe('lifted');
+ expect(h.controller.lift('a')).toBe('unavailable');
+ });
+
+ it.each([
+ ['a locked layer', { layer: { ...paintLayer('a'), isLocked: true } }, 'a'],
+ ['a hidden layer', { layer: { ...paintLayer('a'), isEnabled: false } }, 'a'],
+ ['an unknown layer', {}, 'nope'],
+ ['a selection that misses the layer content', { cacheRect: { height: 10, width: 10, x: 0, y: 0 } }, 'a'],
+ ])('has nothing to lift from %s, admitting nothing', (_, options, layerId) => {
+ const h = createHarness(options);
+ expect(h.controller.lift(layerId)).toBe('unavailable');
expect(h.controller.has()).toBe(false);
+ expect(h.calls.reportRefusal).not.toHaveBeenCalled();
+ expect(h.heldBytes()).toBe(0);
});
- it('refuses a hidden layer', () => {
- const h = createHarness({ layer: { ...paintLayer('a'), isEnabled: false } });
- expect(h.controller.lift('a')).toBe(false);
+ it('restores the cut, lets the layer persist and returns its admission when the cut throws', () => {
+ const h = createHarness();
+ const createSurface = h.backend.createSurface.bind(h.backend);
+ vi.spyOn(h.backend, 'createSurface').mockImplementation((width, height) => {
+ if (h.calls.suspendPersistence.mock.calls.length > 0) {
+ throw new Error('allocation failed');
+ }
+ return createSurface(width, height);
+ });
+
+ expect(() => h.controller.lift('a')).toThrow('allocation failed');
+
+ expect(h.controller.has()).toBe(false);
+ const ops = (h.layers.get('a')!.surface as unknown as { callLog: { op: string }[] }).callLog.map((call) => call.op);
+ expect(ops.at(-1)).toBe('putImageData');
+ expect(h.calls.releasePersistence).toHaveBeenCalledOnce();
+ expect(h.heldBytes()).toBe(0);
});
+});
- it('refuses an unknown layer', () => {
+describe('FloatingSelectionController: movement admission', () => {
+ it('grows the admission to cover a commit at each accepted transform, from geometry alone', () => {
const h = createHarness();
- expect(h.controller.lift('nope')).toBe(false);
+ h.controller.lift('a');
+ const surface = h.layers.get('a')!.surface as unknown as { callLog: unknown[] };
+ const drawn = surface.callLog.length;
+
+ expect(move(h.controller, 40, 0)).toBe(true);
+ // Hole x ∈ [20,50) ∪ landing x ∈ [60,90) spans 70×30.
+ expect(h.heldBytes()).toBe(commitBytes(70, 30));
+ expect(surface.callLog).toHaveLength(drawn);
+ expect(h.selection.snapshot).not.toHaveBeenCalled();
});
- 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);
+ it('never shrinks the admission when a later drag comes back', () => {
+ const h = createHarness();
+ h.controller.lift('a');
+ move(h.controller, 40, 0);
+ move(h.controller, 5, 0);
+ move(h.controller, 0, 10);
+ expect(h.heldBytes()).toBe(commitBytes(70, 30));
+ });
+
+ it('covers an enlarged float and its enlarged selection', () => {
+ const h = createHarness();
+ h.controller.lift('a');
+ h.controller.setTransform({ rotation: 0, scaleX: 2, scaleY: 2, x: 0, y: 0 });
+ // Scaled about the layer origin, the 60×60 landing at (40, 40) and the hole span (20, 20)–(100, 100).
+ expect(h.heldBytes()).toBe(commitBytes(80, 80, 60 * 60));
+ });
+
+ it('covers a rotated float, so its commit fits with no budget to spare', () => {
+ const budget = 200_000;
+ const h = createHarness({ byteBudget: budget });
+ h.controller.lift('a');
+ expect(h.controller.setTransform({ rotation: Math.PI / 4, scaleX: 1, scaleY: 1, x: 0, y: 0 })).toBe(true);
+ // A 30×30 square turned 45° needs a landing at least 43 px across.
+ expect(h.heldBytes()).toBeGreaterThan(commitBytes(43, 43));
+ const rest = h.history.admit(budget - h.heldBytes())!;
+
+ h.controller.commit();
+
+ expect(h.history.entries().past).toEqual(['Move selection']);
+ rest.release();
+ });
+
+ it('keeps the last accepted transform and reports once when a move outgrows the budget', () => {
+ const h = createHarness({ byteBudget: commitBytes(40, 30) });
+ h.controller.lift('a');
+
+ expect(move(h.controller, 5, 0)).toBe(true);
+ expect(move(h.controller, 40, 0)).toBe(false);
+ expect(move(h.controller, 60, 0)).toBe(false);
+ expect(h.controller.get()?.transform).toMatchObject({ x: 5, y: 0 });
+ expect(h.calls.reportRefusal).toHaveBeenCalledExactlyOnceWith('over-budget');
+
+ // Movement within the admission still works after a refusal.
+ expect(move(h.controller, 10, 0)).toBe(true);
+ expect(h.controller.get()?.transform).toMatchObject({ x: 10, y: 0 });
+ expect(h.calls.reportRefusal).toHaveBeenCalledOnce();
+ });
+
+ it('commits an accepted transform even when other edits took all the remaining budget', () => {
+ const budget = commitBytes(70, 30) + 10_000;
+ const h = createHarness({ byteBudget: budget });
+ h.controller.lift('a');
+ move(h.controller, 40, 0);
+ const rest = h.history.admit(budget - h.heldBytes());
+ expect(rest).not.toBeNull();
+
+ h.controller.commit();
+
+ expect(h.history.entries().past).toEqual(['Move selection']);
+ expect(h.calls.reportRefusal).not.toHaveBeenCalled();
+ rest!.release();
+ });
+
+ it('records one entry for repeated drags and returns the admission once it lands', () => {
+ const h = createHarness();
+ h.controller.lift('a');
+ for (const x of [5, 15, 40, 12, 30]) {
+ move(h.controller, x, 0);
+ }
+ h.controller.commit();
+ expect(h.history.entries().past).toEqual(['Move selection']);
+ expect(h.heldBytes()).toBe(0);
+ // The entry retains the final 60×30 patch twice plus its overhead (the stub selection has no alpha).
+ expect(h.history.byteSize()).toBe(60 * 30 * 8 + 256);
});
});
@@ -312,19 +504,106 @@ describe('FloatingSelectionController: commit', () => {
expect(h.selection.restore).toHaveBeenLastCalledWith(after);
});
- it('puts the pixels back and reports a move too large to undo, recording nothing', () => {
- // The 100×30 patch alone exceeds the whole budget.
- const h = createHarness({ byteBudget: 1000 });
+ it('renews an admission whose permit went stale, so a lock that came and went keeps the move', () => {
+ const h = createHarness();
h.controller.lift('a');
move(h.controller, 40, 0);
+ h.setLocked(true);
+ h.setLocked(false);
+
h.controller.commit();
+ expect(h.history.entries().past).toEqual(['Move selection']);
+ expect(h.calls.reportRefusal).not.toHaveBeenCalled();
+ expect(h.heldBytes()).toBe(0);
+ });
+
+ it('renews a float holding more than half the budget without counting it twice', () => {
+ const h = createHarness({ byteBudget: commitBytes(70, 30) + 1000 });
+ h.controller.lift('a');
+ move(h.controller, 40, 0);
+ h.setLocked(true);
+ h.setLocked(false);
+
+ h.controller.commit();
+
+ expect(h.history.entries().past).toEqual(['Move selection']);
+ expect(h.calls.reportRefusal).not.toHaveBeenCalled();
+ });
+
+ it('puts the pixels, extent and ants back when landing fails midway', () => {
+ const h = createHarness();
+ const before = { alpha: null, bounds: null, commits: [], rect: null, selected: true };
+ (h.selection.snapshot as ReturnType<typeof vi.fn>).mockReturnValueOnce(before);
+ h.replaceMask.mockImplementation(() => {
+ throw new Error('mask allocation failed');
+ });
+ h.controller.lift('a');
+ move(h.controller, 90, 0);
+
+ expect(() => h.controller.commit()).toThrow('mask allocation failed');
+
+ expect(h.layers.get('a')!.rect).toEqual({ height: 100, width: 100, x: 0, y: 0 });
+ expect(h.selection.restore).toHaveBeenLastCalledWith(before);
expect(h.controller.has()).toBe(false);
expect(h.history.canUndo()).toBe(false);
- expect(h.calls.reportRefusal).toHaveBeenCalledWith('over-budget');
+ expect(h.calls.markDirty).not.toHaveBeenCalled();
+ expect(h.calls.releasePersistence).toHaveBeenCalledOnce();
+ expect(h.heldBytes()).toBe(0);
+ });
+
+ it('puts everything back and reports when the selection outgrew the admission by commit time', () => {
+ const budget = commitBytes(160, 30) + 10_000;
+ const h = createHarness({ byteBudget: budget });
+ const before = { alpha: null, bounds: null, commits: [], rect: null, selected: true };
+ const outgrown = { ...before, alpha: new Uint8ClampedArray(20_000) };
+ (h.selection.snapshot as ReturnType<typeof vi.fn>).mockReturnValueOnce(before).mockReturnValueOnce(outgrown);
+ h.controller.lift('a');
+ move(h.controller, 90, 0);
+ const rest = h.history.admit(budget - h.heldBytes())!;
+
+ h.controller.commit();
+
+ expect(h.calls.reportRefusal).toHaveBeenCalledExactlyOnceWith('over-budget');
+ expect(h.layers.get('a')!.rect).toEqual({ height: 100, width: 100, x: 0, y: 0 });
+ expect(h.selection.restore).toHaveBeenLastCalledWith(before);
+ expect(h.history.canUndo()).toBe(false);
+ expect(h.calls.releasePersistence).toHaveBeenCalledOnce();
+ rest.release();
+ expect(h.heldBytes()).toBe(0);
+ });
+
+ it('puts the pixels back and reports a commit that can no longer be admitted', () => {
+ const h = createHarness();
+ h.controller.lift('a');
+ move(h.controller, 40, 0);
+ h.setLocked(true);
+
+ h.controller.commit();
+
+ expect(h.controller.has()).toBe(false);
+ expect(h.history.canUndo()).toBe(false);
+ expect(h.calls.reportRefusal).toHaveBeenCalledExactlyOnceWith('busy');
expect(h.calls.markDirty).not.toHaveBeenCalled();
expect(h.replaceMask).not.toHaveBeenCalled();
expect(h.calls.releasePersistence).toHaveBeenCalledOnce();
+ expect(h.heldBytes()).toBe(0);
+ });
+
+ it('puts the pixels back and returns its admission when landing throws', () => {
+ const h = createHarness();
+ h.controller.lift('a');
+ move(h.controller, 40, 0);
+ vi.spyOn(h.backend, 'createSurface').mockImplementation(() => {
+ throw new Error('allocation failed');
+ });
+
+ expect(() => h.controller.commit()).toThrow('allocation failed');
+
+ expect(h.controller.has()).toBe(false);
+ expect(h.history.canUndo()).toBe(false);
+ expect(h.calls.releasePersistence).toHaveBeenCalledOnce();
+ expect(h.heldBytes()).toBe(0);
});
it('keeps the step and the ants in place when its pixels cannot be restored', async () => {
@@ -417,6 +696,53 @@ describe('FloatingSelectionController: cancel', () => {
expect(h.calls.notifyPainted).toHaveBeenCalledTimes(2);
});
+ it('refills the hole before the layer may persist again, then returns the admission', () => {
+ const h = createHarness();
+ h.controller.lift('a');
+ move(h.controller, 40, 0);
+ const surface = h.layers.get('a')!.surface as unknown as { callLog: { op: string }[] };
+ let refilledAtRelease = false;
+ h.calls.releasePersistence.mockImplementation(() => {
+ refilledAtRelease = surface.callLog.at(-1)?.op === 'putImageData';
+ });
+
+ h.controller.cancel();
+
+ expect(refilledAtRelease).toBe(true);
+ expect(h.heldBytes()).toBe(0);
+ });
+
+ it('keeps the layer suspended when the hole cannot be refilled, still returning the admission', () => {
+ const h = createHarness();
+ h.controller.lift('a');
+ vi.spyOn(h.layers, 'growToRect').mockImplementation(() => {
+ throw new Error('allocation failed');
+ });
+
+ expect(() => h.controller.cancel()).toThrow('allocation failed');
+
+ expect(h.controller.has()).toBe(false);
+ expect(h.calls.releasePersistence).not.toHaveBeenCalled();
+ expect(h.heldBytes()).toBe(0);
+ });
+
+ it('returns the admission of a float whose layer was deleted', () => {
+ const cancelled = createHarness();
+ cancelled.controller.lift('a');
+ cancelled.removeLayer();
+ cancelled.controller.cancel();
+ expect(cancelled.heldBytes()).toBe(0);
+ expect(cancelled.calls.releasePersistence).toHaveBeenCalledOnce();
+
+ const committed = createHarness();
+ committed.controller.lift('a');
+ move(committed.controller, 40, 0);
+ committed.removeLayer();
+ committed.controller.commit();
+ expect(committed.heldBytes()).toBe(0);
+ expect(committed.history.canUndo()).toBe(false);
+ });
+
it('leaves the selection where it was', () => {
const h = createHarness();
h.controller.lift('a');
@@ -448,11 +774,13 @@ describe('FloatingSelectionController: dispose', () => {
expect(harness.history.canUndo()).toBe(false);
// The restore pass ran.
expect(harness.calls.notifyPainted).toHaveBeenCalledTimes(2);
+ expect(harness.calls.releasePersistence).toHaveBeenCalledOnce();
+ expect(harness.heldBytes()).toBe(0);
});
- it('refuses further lifts once disposed', () => {
+ it('has nothing to lift once disposed', () => {
harness.controller.dispose();
- expect(harness.controller.lift('a')).toBe(false);
+ expect(harness.controller.lift('a')).toBe('unavailable');
});
it('is idempotent', () => {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.ts
index 451fefff4d..79eb42854d 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.ts
@@ -3,19 +3,22 @@ import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/c
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 { FloatingSelection, FloatLiftResult } 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 { lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';
import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';
+import { getSourceContentRect, renderableSourceOf } from '@workbench/canvas-engine/document/sources';
import { isLeafPixelEditEligible } from '@workbench/canvas-engine/editing/controlPixelEdit';
+import { HISTORY_ENTRY_OVERHEAD_BYTES } from '@workbench/canvas-engine/history/history';
import { createImagePatchEntry } from '@workbench/canvas-engine/history/imagePatch';
import { isEmpty, roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';
import { renderLayerDisplayEffect } from '@workbench/canvas-engine/render/layerDisplayEffect';
import {
floatDocumentMatrix,
+ liftRegion,
liftSelectedPixels,
transformPlacedMask,
} from '@workbench/canvas-engine/selection/floatingSelection';
@@ -23,7 +26,9 @@ import { eraseMaskedRegion } from '@workbench/canvas-engine/selection/selectionO
import { layerMatrix } from '@workbench/canvas-engine/tools/moveHitTest';
import { bakeMatrix, IDENTITY_TRANSFORM } from '@workbench/canvas-engine/transform/transformMath';
-import type { CanvasMutationContext } from './mutationContext';
+import type { CanvasMutationContext, EditPublishResult, EditTransaction } from './mutationContext';
+
+import { rgbaBytes } from './editSteps';
export interface FloatingSelectionControllerOptions {
readonly backend: RasterBackend;
@@ -35,7 +40,6 @@ export interface FloatingSelectionControllerOptions {
readonly suspendPersistence: (layerId: string) => () => void;
readonly reportRefusal: (refusal: CanvasEditRefusal) => void;
readonly getDocument: () => CanvasDocumentContractV3 | null;
- readonly canEdit: () => boolean;
readonly notifyPainted: (layerId: string) => void;
readonly markDirty: (layerId: string) => void;
readonly invalidateLayer: (layerId: string) => void;
@@ -50,14 +54,42 @@ const isIdentity = (transform: LayerTransform): boolean =>
transform.scaleY === 1 &&
transform.rotation === 0;
+const pixelCount = (rect: Rect): number => (isEmpty(rect) ? 0 : rect.width * rect.height);
+
/**
- * Lifts pixels without history or dirtying, suspending the layer's persistence so the temporary hole never uploads.
- * Commit is admitted before it lands anything and records pre-lift and post-bake pixels across the hole/landing union
- * as one undo entry; a commit that cannot be recorded puts the pixels back instead. Cancellation restores pixels
- * without history.
+ * Undo bytes a commit at `transform` records, from geometry alone: pre-lift and landed pixels over the union of the
+ * hole and the landing, the selection alpha before and after, and the entry overhead.
+ */
+const commitHistoryBytes = (
+ region: Rect,
+ maskRect: Rect,
+ layerTransform: LayerTransform,
+ transform: LayerTransform
+): number => {
+ const matrix = bakeMatrix(transform);
+ const patch = union(region, roundOut(transformBounds(matrix, region)));
+ const documentMatrix = floatDocumentMatrix(layerMatrix(layerTransform), matrix);
+ const movedMask = documentMatrix ? roundOut(transformBounds(documentMatrix, maskRect)) : maskRect;
+ return rgbaBytes(patch) * 2 + pixelCount(maskRect) + pixelCount(movedMask) + HISTORY_ENTRY_OVERHEAD_BYTES;
+};
+
+type PublishedStatus = EditPublishResult['status'];
+const isRefusal = (status: PublishedStatus): status is CanvasEditRefusal =>
+ status === 'busy' || status === 'gesture-active' || status === 'not-ready' || status === 'over-budget';
+
+/**
+ * A float is admitted before it cuts anything and keeps that admission until it lands or is dropped; each transform
+ * grows it to cover the commit there, so an accepted transform always fits its undo entry. The cut layer's
+ * persistence is suspended meanwhile, so the hole never uploads. Commit records pre-lift and post-bake pixels across
+ * the hole/landing union with both selections as one undo entry; a commit that cannot be recorded puts the pixels
+ * back instead. Cancellation restores pixels without history.
*/
export class FloatingSelectionController {
private float: FloatingSelection | null = null;
+ /** The float's admission, held from lift until the float lands or is dropped. */
+ private txn: EditTransaction | null = null;
+ private admittedBytes = 0;
+ private refusalReported = false;
private releasePersistence: (() => void) | null = null;
private disposed = false;
@@ -77,83 +109,143 @@ export class FloatingSelectionController {
return getDocumentLayer(document, float.layerId) ?? null;
}
- /** Lifts selected pixels; returns false for absent selection, ineligible layers or no overlap. */
- lift(layerId: string): boolean {
- if (this.disposed || this.float || !this.deps.canEdit()) {
- return false;
+ /**
+ * Lifts selected pixels once the edit is admitted. `unavailable` means there is nothing to lift (no selection,
+ * an ineligible layer, no overlap); `refused` means the edit was refused and the refusal reported.
+ */
+ lift(layerId: string): FloatLiftResult {
+ if (this.disposed || this.float) {
+ return 'unavailable';
}
const document = this.deps.getDocument();
const leaf = lookupDocumentLeaf(document, layerId);
const layer = leaf?.layer;
if (!document || !layer || !isLeafPixelEditEligible(leaf)) {
- return false;
+ return 'unavailable';
}
const mask = this.deps.selection.mask();
+ if (!mask) {
+ return 'unavailable';
+ }
const entry = this.deps.layers.get(layerId);
- if (!mask || !entry || isEmpty(entry.rect)) {
- return false;
+ if (!entry) {
+ // Pixels the cache has not rebuilt yet are still the layer's; moving the whole layer instead would surprise.
+ if (renderableSourceOf(layer) && !isEmpty(getSourceContentRect(layer, document))) {
+ this.deps.reportRefusal('not-ready');
+ return 'refused';
+ }
+ return 'unavailable';
}
-
- const lifted = liftSelectedPixels({
- backend: this.deps.backend,
- cache: { rect: entry.rect, surface: entry.surface },
- layerMatrix: layerMatrix(layer.transform),
- mask,
- });
- if (!lifted) {
- return false;
+ const matrix = layerMatrix(layer.transform);
+ const region = liftRegion(entry.rect, matrix, mask.rect);
+ if (!region) {
+ return 'unavailable';
}
- this.releasePersistence = this.deps.suspendPersistence(layerId);
- 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,
- });
+ const historyBytes = commitHistoryBytes(region, mask.rect, layer.transform, IDENTITY_TRANSFORM);
+ // The lift belongs to the drag that starts it.
+ const txn = this.deps.ctx.begin({ gesture: true, historyBytes });
+ if (!('publish' in txn)) {
+ this.deps.reportRefusal(txn.status);
+ return 'refused';
+ }
- this.float = {
- before: { data: before, rect: region },
+ let before: ImageData | null = null;
+ let releasePersistence: (() => void) | null = null;
+ try {
+ const lifted = liftSelectedPixels({
+ backend: this.deps.backend,
+ cache: { rect: entry.rect, surface: entry.surface },
+ layerMatrix: matrix,
+ mask,
+ });
+ if (!lifted) {
+ txn.end();
+ return 'unavailable';
+ }
// Bake darkness dropout once so the float matches the rendered control map.
- display: renderLayerDisplayEffect(this.deps.backend, layer, lifted.pixels.surface),
- layerId,
- mask: { rect: mask.rect, surface: mask.surface },
- pixels: lifted.pixels,
- transform: { ...IDENTITY_TRANSFORM },
- };
+ const display = renderLayerDisplayEffect(this.deps.backend, layer, lifted.pixels.surface);
+ before = entry.surface.ctx.getImageData(
+ region.x - entry.rect.x,
+ region.y - entry.rect.y,
+ region.width,
+ region.height
+ );
+ releasePersistence = this.deps.suspendPersistence(layerId);
+ 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 },
+ display,
+ layerId,
+ mask: { rect: mask.rect, surface: mask.surface },
+ pixels: lifted.pixels,
+ transform: { ...IDENTITY_TRANSFORM },
+ };
+ } catch (error) {
+ try {
+ if (before && releasePersistence) {
+ entry.surface.ctx.putImageData(before, region.x - entry.rect.x, region.y - entry.rect.y);
+ releasePersistence();
+ }
+ } finally {
+ txn.end();
+ }
+ throw error;
+ }
+ this.txn = txn;
+ this.admittedBytes = historyBytes;
+ this.refusalReported = false;
+ this.releasePersistence = releasePersistence;
// Bump the cache version so the hole composites, WITHOUT marking dirty.
this.deps.notifyPainted(layerId);
this.deps.invalidateLayer(layerId);
this.deps.onChange();
- return true;
+ return 'lifted';
}
- /** Updates the float's live (layer-local) transform. */
- setTransform(transform: LayerTransform): void {
- if (!this.float) {
- return;
+ /**
+ * Accepts the float's live (layer-local) transform once the admission covers a commit there. A transform that
+ * would not fit keeps the last accepted one and reports the refusal once per float.
+ */
+ setTransform(transform: LayerTransform): boolean {
+ const float = this.float;
+ const txn = this.txn;
+ if (!float || !txn) {
+ return false;
+ }
+ const layer = this.layerOf(float);
+ if (layer) {
+ const required = commitHistoryBytes(float.pixels.rect, float.mask.rect, layer.transform, transform);
+ if (required > this.admittedBytes) {
+ if (!txn.growHistory(required - this.admittedBytes)) {
+ if (!this.refusalReported) {
+ this.refusalReported = true;
+ this.deps.reportRefusal('over-budget');
+ }
+ return false;
+ }
+ this.admittedBytes = required;
+ }
}
- this.float.transform = { ...transform };
- this.deps.invalidateLayer(this.float.layerId);
+ float.transform = { ...transform };
+ this.deps.invalidateLayer(float.layerId);
+ return true;
}
/**
- * Bakes pixels and moves the selection in one undo entry. An unmoved float restores its cut pixels without
- * adding history.
+ * Bakes pixels and moves the selection in one undo entry under the float's admission. An unmoved float restores
+ * its cut pixels without adding history.
*/
commit(): void {
const float = this.float;
- if (this.disposed || !float) {
+ if (!float || !this.txn) {
return;
}
const layer = this.layerOf(float);
@@ -166,136 +258,161 @@ export class FloatingSelectionController {
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);
- const selectionBefore = this.deps.selection.snapshot();
- const selectionBytes = (selectionBefore.alpha?.byteLength ?? 0) * 2;
- // Banking a float is part of whatever the user moved on to, even mid-gesture.
- const txn = this.deps.ctx.begin({
- gesture: true,
- historyBytes: patchRect.width * patchRect.height * 8 + selectionBytes,
- });
- if (!('publish' in txn)) {
- this.cancel();
- this.deps.reportRefusal(txn.status);
+ const txn = this.currentTransaction();
+ if (!txn) {
return;
}
try {
- this.land(float, layer, matrix, patchRect, selectionBefore, txn);
- } finally {
- txn.end();
+ this.land(float, layer, txn);
+ } catch (error) {
+ this.cancel();
+ throw error;
}
}
- private land(
- float: FloatingSelection,
- layer: CanvasLayerContract,
- matrix: ReturnType<typeof bakeMatrix>,
- patchRect: Rect,
- selectionBefore: ReturnType<SelectionState['snapshot']>,
- txn: Extract<ReturnType<CanvasMutationContext['begin']>, { publish: unknown }>
- ): void {
+ /**
+ * The retained admission, renewed once when its permit went stale (an operation locked and released the document
+ * meanwhile). A float that can no longer be admitted is put back and the refusal reported.
+ */
+ private currentTransaction(): EditTransaction | null {
+ const retained = this.txn!;
+ if (retained.isCurrent()) {
+ return retained;
+ }
+ // Hand the capacity back first; holding both would need the float's bytes twice.
+ retained.end();
+ const renewed = this.deps.ctx.begin({ gesture: true, historyBytes: this.admittedBytes });
+ if (!('publish' in renewed)) {
+ this.cancel();
+ this.deps.reportRefusal(renewed.status);
+ return null;
+ }
+ this.txn = renewed;
+ return renewed;
+ }
+
+ private land(float: FloatingSelection, layer: CanvasLayerContract, txn: EditTransaction): void {
+ const matrix = bakeMatrix(float.transform);
+ // 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, roundOut(transformBounds(matrix, float.pixels.rect)));
+ const selectionBefore = this.deps.selection.snapshot();
const existing = this.deps.layers.get(float.layerId);
const originalRect = existing ? { ...existing.rect } : null;
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);
+ let before: ImageData | null = null;
+ let committed = false;
+ try {
+ // 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);
+ 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);
+ // 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
- );
+ const after = ctx.getImageData(
+ patchRect.x - entry.rect.x,
+ patchRect.y - entry.rect.y,
+ patchRect.width,
+ patchRect.height
+ );
- // The ants travel with the pixels inside the same step, so one undo puts
- // both back; the raw selection records nothing of its own here.
- this.moveSelectionWithFloat(layer, matrix, float);
- const selectionAfter = this.deps.selection.snapshot();
+ // The ants travel with the pixels inside the same step, so one undo puts
+ // both back; the raw selection records nothing of its own here.
+ this.moveSelectionWithFloat(layer, matrix, float);
+ const selectionAfter = this.deps.selection.snapshot();
- const patch = createImagePatchEntry({
- after,
- apply: this.deps.applyImagePatch,
- before,
- label: 'Move selection',
- layerId: float.layerId,
- rect: patchRect,
- });
- const result = txn.publish(
- patch.label,
- {
- notify: () => {
- this.deps.notifyPainted(float.layerId);
- this.deps.markDirty(float.layerId);
- this.deps.invalidateLayer(float.layerId);
- },
- },
- {
- bytes: patch.bytes + (selectionBefore.alpha?.byteLength ?? 0) + (selectionAfter.alpha?.byteLength ?? 0),
- heldAssetRefs: patch.heldAssetRefs,
- redo: async () => {
- await patch.redo();
- this.deps.selection.restore(selectionAfter);
+ const patch = createImagePatchEntry({
+ after,
+ apply: this.deps.applyImagePatch,
+ before,
+ label: 'Move selection',
+ layerId: float.layerId,
+ rect: patchRect,
+ });
+ const result = txn.publish(
+ patch.label,
+ {
+ notify: () => {
+ this.deps.notifyPainted(float.layerId);
+ this.deps.markDirty(float.layerId);
+ this.deps.invalidateLayer(float.layerId);
+ },
},
- undo: async () => {
- await patch.undo();
- this.deps.selection.restore(selectionBefore);
+ {
+ bytes:
+ patch.bytes +
+ (selectionBefore.alpha?.byteLength ?? 0) +
+ (selectionAfter.alpha?.byteLength ?? 0) +
+ HISTORY_ENTRY_OVERHEAD_BYTES,
+ heldAssetRefs: patch.heldAssetRefs,
+ redo: async () => {
+ await patch.redo();
+ this.deps.selection.restore(selectionAfter);
+ },
+ undo: async () => {
+ await patch.undo();
+ this.deps.selection.restore(selectionBefore);
+ },
},
- },
- { origin: 'system' }
- );
- if (result.status !== 'committed') {
- // Nothing was recorded: return the layer and the ants to their pre-lift state.
- const live = this.deps.layers.get(float.layerId);
- live?.surface.ctx.putImageData(before, patchRect.x - live.rect.x, patchRect.y - live.rect.y);
- if (originalRect) {
- this.deps.layers.shrinkToRect(float.layerId, originalRect);
- } else {
- this.deps.layers.delete(float.layerId);
+ { origin: 'system' }
+ );
+ committed = result.status === 'committed';
+ if (isRefusal(result.status)) {
+ this.deps.reportRefusal(result.status);
}
- this.deps.selection.restore(selectionBefore);
- this.deps.notifyPainted(float.layerId);
- this.deps.invalidateLayer(float.layerId);
- if (result.status === 'over-budget') {
- this.deps.reportRefusal('over-budget');
+ } finally {
+ if (!committed) {
+ // Nothing was recorded: return the layer and the ants to their pre-lift state.
+ const live = this.deps.layers.get(float.layerId);
+ if (live && before) {
+ live.surface.ctx.putImageData(before, patchRect.x - live.rect.x, patchRect.y - live.rect.y);
+ }
+ if (originalRect) {
+ this.deps.layers.shrinkToRect(float.layerId, originalRect);
+ } else {
+ this.deps.layers.delete(float.layerId);
+ }
+ this.deps.selection.restore(selectionBefore);
+ this.deps.notifyPainted(float.layerId);
+ this.deps.invalidateLayer(float.layerId);
}
}
this.settle();
}
- /** Drops the float and lets its layer persist again. */
+ /** Drops the float, lets its layer persist again and returns its unused admission. */
private settle(): void {
- this.float = null;
+ const txn = this.txn;
const release = this.releasePersistence;
+ this.float = null;
+ this.txn = null;
+ this.admittedBytes = 0;
this.releasePersistence = null;
try {
release?.();
} finally {
- this.deps.onChange();
+ try {
+ txn?.end();
+ } finally {
+ this.deps.onChange();
+ }
}
}
@@ -320,22 +437,32 @@ export class FloatingSelectionController {
if (!float) {
return;
}
- const restoreRect: Rect = float.before.rect;
- if (this.layerOf(float) && !isEmpty(restoreRect)) {
- 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);
+ let restored = true;
+ try {
+ const restoreRect: Rect = float.before.rect;
+ if (this.layerOf(float) && !isEmpty(restoreRect)) {
+ restored = false;
+ 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);
+ restored = true;
+ this.deps.notifyPainted(float.layerId);
+ this.deps.invalidateLayer(float.layerId);
+ }
+ } finally {
+ if (!restored) {
+ // A hole that could not be refilled must never persist; the layer stays suspended.
+ this.releasePersistence = null;
+ }
+ this.settle();
}
- this.settle();
}
dispose(): void {
if (this.disposed) {
return;
}
+ this.disposed = true;
// Restore the float's uniquely held pixels before disposal.
this.cancel();
- this.disposed = true;
}
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.ts
index 5f82a236f7..c02cf110e6 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.ts
@@ -167,8 +167,8 @@ export class TransformEditingController {
const beforeRect = { ...cache.rect };
const matrix = bakeMatrix(session.transform);
const afterRect = roundOut(transformBounds(matrix, beforeRect));
- const beforeBytes = beforeRect.width * beforeRect.height * 4;
- const afterBytes = afterRect.width * afterRect.height * 4;
+ const beforeBytes = rgbaBytes(beforeRect);
+ const afterBytes = rgbaBytes(afterRect);
const txn = this.deps.ctx.begin({ historyBytes: beforeBytes + afterBytes + HISTORY_ENTRY_OVERHEAD_BYTES });
if (!('publish' in txn)) {
this.settle(txn.status);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
index 4d66bf9b2c..2a612deb54 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
@@ -18612,3 +18612,79 @@ describe('refused strokes', () => {
engine.lifecycle.dispose();
});
});
+
+describe('floating selection lifecycle', () => {
+ const liftFloat = () => {
+ const raf = createControllableRaf();
+ vi.stubGlobal('requestAnimationFrame', raf.requestFrame);
+ vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);
+ vi.stubGlobal(
+ 'Path2D',
+ class FakePath2D {
+ closePath() {}
+ lineTo() {}
+ moveTo() {}
+ quadraticCurveTo() {}
+ }
+ );
+ const reactive = createReactiveStore(paintDoc());
+ const bitmapStore = createSpyBitmapStore();
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ bitmapStore,
+ imageResolver: () => Promise.resolve(new Blob()),
+ projectId: 'p1',
+ store: reactive.store,
+ });
+ const overlay = createInputCanvas();
+ engine.surface.attach(createInputCanvas().element, overlay.element);
+ engine.tools.setTool('brush');
+ overlay.fire('pointerdown', pointerAt(20, 20));
+ overlay.fire('pointermove', pointerAt(40, 40));
+ overlay.fire('pointerup', pointerAt(40, 40, { buttons: 0 }));
+ engine.selection.selectAll();
+ engine.tools.setTool('move');
+ overlay.fire('pointerdown', pointerAt(30, 30));
+ overlay.fire('pointermove', pointerAt(45, 35));
+ overlay.fire('pointerup', pointerAt(45, 35, { buttons: 0 }));
+ expect(engine.stores.hasFloatingSelection.get()).toBe(true);
+ expect(bitmapStore.suspendLayer).toHaveBeenCalledWith('paint1');
+ bitmapStore.markLayerDirty.mockClear();
+ return { bitmapStore, engine, ...reactive };
+ };
+
+ it('banks a float on cooldown, so the flush that follows persists the landed pixels', async () => {
+ const { bitmapStore, engine } = liftFloat();
+
+ const cooled = engine.lifecycle.beginCooldown();
+
+ expect(engine.stores.hasFloatingSelection.get()).toBe(false);
+ expect(engine.history.getEntries().past.at(-1)).toBe('Move selection');
+ expect(bitmapStore.markLayerDirty).toHaveBeenCalledWith('paint1');
+ expect(bitmapStore.releaseSuspendedLayer).toHaveBeenCalledOnce();
+ await expect(cooled).resolves.toBe('cooled');
+ engine.lifecycle.dispose();
+ });
+
+ it('drops a float without recording it when the document is replaced', () => {
+ const { bitmapStore, engine, setDocument } = liftFloat();
+
+ setDocument({ ...paintDoc(), height: 200, width: 200 }, 1);
+
+ expect(engine.stores.hasFloatingSelection.get()).toBe(false);
+ expect(engine.history.getEntries().past).not.toContain('Move selection');
+ expect(bitmapStore.releaseSuspendedLayer).toHaveBeenCalledOnce();
+ engine.lifecycle.dispose();
+ });
+
+ it('drops a float without recording it when its layer is deleted', () => {
+ const { bitmapStore, engine, setDocument } = liftFloat();
+
+ setDocument({ ...paintDoc(), selectedLayerId: null, stacks: stacksFrom([]) });
+
+ expect(engine.stores.hasFloatingSelection.get()).toBe(false);
+ expect(engine.history.getEntries().past).not.toContain('Move selection');
+ expect(bitmapStore.releaseSuspendedLayer).toHaveBeenCalledOnce();
+ engine.lifecycle.dispose();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index 15f5f4fc78..e570f6c054 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -811,7 +811,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
floatingSelection: {
applyImagePatch,
backend,
- canEdit: () => canEditDocument(),
ctx: mutationContext,
getDocument: () => mirror.getDocument(),
invalidateLayer: (layerId) => scheduler.invalidate({ layers: [layerId] }),
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/floatingSelection.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/floatingSelection.ts
index bdea4307a9..aee4ef144c 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/floatingSelection.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/floatingSelection.ts
@@ -31,6 +31,9 @@ export interface FloatingSelection {
transform: LayerTransform;
}
+/** A lift took the pixels, was refused admission (and reported it), or found nothing it could lift. */
+export type FloatLiftResult = 'lifted' | 'refused' | 'unavailable';
+
/** Inputs to {@link liftSelectedPixels}. */
export interface LiftSelectedPixelsParams {
backend: RasterBackend;
@@ -101,9 +104,19 @@ const projectIntoLocal = (
return { rect: region, surface };
};
+/** The layer-local region a lift takes: the selection's local extent clipped to the layer content, or null. */
+export const liftRegion = (cacheRect: Rect, layerMatrix: Mat2d, maskRect: Rect): Rect | null => {
+ const inverseLayerMatrix = invert(layerMatrix);
+ if (!inverseLayerMatrix || isEmpty(cacheRect) || isEmpty(maskRect)) {
+ return null;
+ }
+ const region = intersect(roundOut(transformBounds(inverseLayerMatrix, maskRect)), cacheRect);
+ return region && !isEmpty(region) ? region : null;
+};
+
/**
- * Copies selected layer content and returns its exact local stencil, or null without overlap. Does not mutate
- * cache; callers cut with the same stencil.
+ * Copies selected layer content over {@link liftRegion} and returns its exact local stencil, or null without
+ * overlap. Does not mutate cache; callers cut with the same stencil.
*/
export const liftSelectedPixels = ({
backend,
@@ -111,14 +124,9 @@ export const liftSelectedPixels = ({
layerMatrix,
mask,
}: LiftSelectedPixelsParams): LiftedPixels | null => {
+ const region = liftRegion(cache.rect, layerMatrix, mask.rect);
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)) {
+ if (!region || !inverseLayerMatrix) {
return null;
}
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.ts
index 479a9e2fc8..22d5b5ef34 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,5 @@
import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';
-import type { FloatingSelection } from '@workbench/canvas-engine/selection/floatingSelection';
+import type { FloatingSelection, FloatLiftResult } 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';
@@ -99,8 +99,8 @@ interface HarnessOptions {
selectedLayerIds?: readonly string[];
/** 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;
+ /** What a lift returns when the tool asks for one; defaults to lifting. */
+ lift?: FloatLiftResult;
/** A float that is already in flight before the gesture starts. */
existingFloat?: boolean;
/** Tests default snapping off to isolate raw deltas; snapping cases opt in. Product default is on. */
@@ -150,12 +150,12 @@ const createHarness = (doc: CanvasDocumentContractV3, options: HarnessOptions =
isPointInSelection: () => options.selectionContainsPoint === true,
layers: createLayerCacheStore(createTestStubRasterBackend()),
liftFloatingSelection: (layerId) => {
- if (options.canLift === false) {
- return false;
- }
+ const result = options.lift ?? 'lifted';
lifts.push(layerId);
- float.current = fakeFloat(layerId);
- return true;
+ if (result === 'lifted') {
+ float.current = fakeFloat(layerId);
+ }
+ return result;
},
notifyLayerPainted: vi.fn(),
setFloatingTransform: (transform) => {
@@ -510,7 +510,6 @@ describe('move tool: grid snapping', () => {
it('does not snap a floating selection (its transform is layer-local)', () => {
const h = createHarness(snapDoc(), {
bboxGrid: 8,
- canLift: true,
selectionContainsPoint: true,
snapToGrid: true,
});
@@ -638,7 +637,7 @@ describe('move tool: dragging a floating selection', () => {
});
it('falls back to moving the layer when the lift finds nothing to take', () => {
- const h = createHarness(doc(), { canLift: false, selectionContainsPoint: true });
+ const h = createHarness(doc(), { lift: 'unavailable', selectionContainsPoint: true });
const tool = createMoveTool();
down(tool, h.ctx, pointer(10, 10));
@@ -648,6 +647,21 @@ describe('move tool: dragging a floating selection', () => {
expect(h.commits).toHaveLength(1);
});
+ it('moves nothing when the lift is refused, never the whole layer', () => {
+ const h = createHarness(doc(), { lift: 'refused', selectionContainsPoint: true });
+ const tool = createMoveTool();
+
+ down(tool, h.ctx, pointer(10, 10));
+ move(tool, h.ctx, pointer(30, 25));
+ move(tool, h.ctx, pointer(40, 30));
+ up(tool, h.ctx, pointer(40, 30));
+
+ expect(h.lifts).toEqual(['a']);
+ expect(h.commits).toHaveLength(0);
+ expect(h.overrides).toHaveLength(0);
+ expect(h.transforms).toHaveLength(0);
+ });
+
it('constrains a float drag to the dominant axis under shift', () => {
const h = createHarness(doc(), { selectionContainsPoint: true });
const tool = createMoveTool();
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.ts
index f10c9bf13c..4e8a38de7c 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.ts
@@ -123,15 +123,17 @@ export const createMoveTool = (): Tool => {
: layerDrag;
};
- /** A click must leave the layer whole, so the pixels are cut only when the drag starts. */
+ /**
+ * A click must leave the layer whole, so the pixels are cut only when the drag starts. Only a selection with
+ * nothing to lift falls back to moving the layer; a refused lift moves nothing.
+ */
const liftOnDrag = (ctx: ToolContext, mode: Extract<DragMode, { kind: 'lift' }>): DragMode => {
- if (ctx.liftFloatingSelection?.(mode.layerId)) {
- const lifted = ctx.getFloatingSelection?.();
- if (lifted) {
- return { kind: 'float', layerId: lifted.layerId, origin: { ...lifted.transform } };
- }
+ const result = ctx.liftFloatingSelection?.(mode.layerId) ?? 'unavailable';
+ if (result === 'unavailable') {
+ return mode.fallback;
}
- return mode.fallback;
+ const lifted = result === 'lifted' ? ctx.getFloatingSelection?.() : null;
+ return lifted ? { kind: 'float', layerId: lifted.layerId, origin: { ...lifted.transform } } : { kind: 'none' };
};
/** The constrained document-space delta from the gesture start to `input`. */
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts
index b64028f5f2..57474b9d29 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts
@@ -17,7 +17,7 @@ import type { OverlayCursor } from '@workbench/canvas-engine/render/overlayRende
import 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 { 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';
@@ -166,11 +166,11 @@ export interface ToolContext {
getStrokeClipRect?(): Rect | null;
/** Updates visual SAM input for the active engine-owned Select Object session. */
updateSamInput?(input: SamVisualInput): void;
- /** Optional lift of selected layer pixels into a float; returns whether any were lifted. */
- liftFloatingSelection?(layerId: string): boolean;
+ /** Optional lift of selected layer pixels into a float; a refused lift has already been reported. */
+ liftFloatingSelection?(layerId: string): FloatLiftResult;
/** The live floating selection, or `null`. */
getFloatingSelection?(): FloatingSelection | null;
- /** Sets the float's live transform (LAYER-LOCAL space). */
+ /** Sets the float's live transform (LAYER-LOCAL space); one its undo budget cannot cover keeps the last. */
setFloatingTransform?(transform: LayerTransform): void;
/** Bakes the float back into its layer as one undoable entry. */
commitFloatingSelection?(): void;