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.

feat(webv2): add selection clipboard ops and layer-via-copy

joshistoast8119b7f1d703
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 3e103e76e9..a6a91a2cb3 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -1179,7 +1179,13 @@
"canvas": {
"acceptToLayer": "Accept to Layer",
"candidateCount": "{{current}} of {{total}}",
+ "clipboard": {
+ "copyFailed": "Could not copy the selection to the clipboard",
+ "pasteFailed": "Could not paste an image from the clipboard"
+ },
"commands": {
+ "copySelection": "Copy selection",
+ "cutSelection": "Cut selection",
"decreaseBrushSize": "Decrease brush/eraser size",
"deleteLayer": "Delete layer",
"deleteSelected": "Delete selected canvas item",
@@ -1202,6 +1208,7 @@
"nudgeRightLarge": "Nudge layer right 10px",
"nudgeUp": "Nudge layer up",
"nudgeUpLarge": "Nudge layer up 10px",
+ "pasteImage": "Paste image",
"previousEntity": "Previous canvas entity",
"redo": "Redo canvas edit",
"reorderLayer": "Reorder layer",
@@ -1340,6 +1347,7 @@
"lassoPolygon": "Polygon",
"lassoPolygonHint": "Click to place points. Double-click, Enter, or click the first point to close.",
"lassoShape": "Lasso mode",
+ "liftSelectionToLayer": "New layer",
"lockAspect": "Lock aspect ratio",
"marqueeHint": "Drag to select a region. Shift constrains, Alt draws from centre.",
"marqueeKind": "Marquee shape",
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
index 3b1df2f41a..74c09f828a 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
@@ -9,6 +9,7 @@ import type { StrokeCommittedEvent } from '@workbench/canvas-engine/tools/tool';
import type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';
import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
+import type { NewRasterLayerResult } from './controllers/newRasterLayerController';
import type { CanvasEditGate } from './editGate';
import type {
BboxToolOptions,
@@ -190,6 +191,17 @@ export interface CanvasSelectionCapability {
getSelectionBounds(): Rect | null;
getSelectionMaskRect(): Rect | null;
invertSelection(): void;
+ /**
+ * Encodes the selection's pixels on the active layer as a PNG, or `null` when
+ * there is nothing to copy. The engine deliberately stops at the blob: writing
+ * to the system clipboard is a widget-layer concern (`canvas-engine` may not
+ * reach `workbench/widgets`).
+ */
+ exportSelectionBlob(): Promise<Blob | null>;
+ /** Inserts decoded pixels as a new raster layer above the active one. */
+ pasteImage(pixels: ImageData, center?: Vec2): NewRasterLayerResult;
+ /** Copies the selection's pixels into a new layer above the active one, leaving the source intact. */
+ liftSelectionToLayer(): NewRasterLayerResult;
replaceSelectionFromImage(
guard: LayerExportGuard,
image: CanvasImageRef,
@@ -199,6 +211,8 @@ export interface CanvasSelectionCapability {
selectAll(): void;
}
+export type { NewRasterLayerResult };
+
export type ReplaceSelectionFromImageResult =
| { status: 'selected' }
| { status: 'aborted' | 'missing' | 'locked' | 'stale' | 'unsupported' | 'busy' }
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.test.ts
index 0c2546c6bf..60c3928cde 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.test.ts
@@ -141,6 +141,22 @@ describe('LayerController', () => {
isPermitCurrent: () => true,
preparePixels: vi.fn(),
};
+ const newRasterLayer = {
+ backend: {} as never,
+ capturePermit: () => null,
+ createLayerId: () => 'new',
+ dispatchPrepared: vi.fn(),
+ endBurst: vi.fn(),
+ getDocument: () => null,
+ getReducerDocument: () => null,
+ history: {} as never,
+ installPrepared: vi.fn(),
+ isGestureActive: () => false,
+ isPermitCurrent: () => true,
+ layers: {} as never,
+ preparePixels: vi.fn(),
+ selection: {} as never,
+ };
it('exposes only declared layer and preview ports', async () => {
const forward: CanvasProjectMutation = { id: 'layer', type: 'setCanvasSelectedLayer' };
const inverse: CanvasProjectMutation = { id: null, type: 'setCanvasSelectedLayer' };
@@ -149,6 +165,7 @@ describe('LayerController', () => {
mask,
booleanMerge,
extractMaskedArea,
+ newRasterLayer,
crop,
copy,
merge,
@@ -170,6 +187,7 @@ describe('LayerController', () => {
mask,
booleanMerge,
extractMaskedArea,
+ newRasterLayer,
crop,
copy,
merge,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.ts
index f53e6d2ab5..bae210d218 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.ts
@@ -9,6 +9,7 @@ import { CropLayerController, type CropLayerControllerOptions } from './cropLaye
import { ExtractMaskedAreaController, type ExtractMaskedAreaControllerOptions } from './extractMaskedAreaController';
import { MaskLayerController } from './maskLayerController';
import { MergeLayerController, type MergeLayerControllerOptions } from './mergeLayerController';
+import { NewRasterLayerController, type NewRasterLayerControllerOptions } from './newRasterLayerController';
import { RasterizeLayerController, type RasterizeLayerControllerOptions } from './rasterizeLayerController';
import { ThumbnailController, type ThumbnailControllerOptions } from './thumbnailController';
@@ -26,6 +27,7 @@ export type LayerControllerDeps = Omit<
extractMaskedArea: ExtractMaskedAreaControllerOptions;
crop: CropLayerControllerOptions;
copy: CopyLayerControllerOptions;
+ newRasterLayer: NewRasterLayerControllerOptions;
};
/** Public layer-operation boundary. Implementations are injected by the composition root. */
@@ -41,6 +43,7 @@ export class LayerController {
readonly extractMaskedArea: ExtractMaskedAreaController;
readonly crop: CropLayerController;
readonly copy: CopyLayerController;
+ readonly newRasterLayer: NewRasterLayerController;
private disposed = false;
constructor(deps: LayerControllerDeps) {
@@ -53,6 +56,7 @@ export class LayerController {
this.extractMaskedArea = new ExtractMaskedAreaController(deps.extractMaskedArea);
this.crop = new CropLayerController(deps.crop);
this.copy = new CopyLayerController(deps.copy);
+ this.newRasterLayer = new NewRasterLayerController(deps.newRasterLayer);
this.layers = {
applyStructuralPreview: (action) => (this.disposed ? false : this.structural.preview(action)),
canCommitStructural: () => this.structural.canCommit(),
@@ -79,5 +83,6 @@ export class LayerController {
this.extractMaskedArea.dispose();
this.crop.dispose();
this.copy.dispose();
+ this.newRasterLayer.dispose();
}
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.test.ts
new file mode 100644
index 0000000000..bf7a05f57b
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.test.ts
@@ -0,0 +1,278 @@
+import type {
+ CanvasDocumentContractV2,
+ CanvasLayerContract,
+ CanvasRasterLayerContractV2,
+} from '@workbench/canvas-engine/contracts';
+import type { SelectionState } from '@workbench/canvas-engine/selection/selectionState';
+import type { PlacedSurface, Rect } from '@workbench/canvas-engine/types';
+import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
+
+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 { describe, expect, it, vi } from 'vitest';
+
+import { NewRasterLayerController } from './newRasterLayerController';
+
+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[], selectedLayerId: string | null): CanvasDocumentContractV2 => ({
+ background: 'transparent',
+ bbox: { height: 100, width: 100, x: 0, y: 0 },
+ height: 100,
+ layers,
+ selectedLayerId,
+ version: 2,
+ width: 100,
+});
+
+/** The created layer, narrowed to the raster variant the controller always makes. */
+const createdRaster = (document: CanvasDocumentContractV2 | null, id: string): CanvasRasterLayerContractV2 => {
+ const layer = document?.layers.find((candidate) => candidate.id === id);
+ if (!layer || layer.type !== 'raster') {
+ throw new Error(`expected a raster layer ${id}`);
+ }
+ return layer;
+};
+
+const imageData = (width: number, height: number): ImageData =>
+ ({ colorSpace: 'srgb', data: new Uint8ClampedArray(width * height * 4), height, width }) as ImageData;
+
+interface HarnessOptions {
+ layers?: CanvasLayerContract[];
+ selectedLayerId?: string | null;
+ maskRect?: Rect | null;
+ cacheRect?: Rect;
+ permit?: object | null;
+ gestureActive?: boolean;
+}
+
+const createHarness = (options: HarnessOptions = {}) => {
+ const backend = createTestStubRasterBackend();
+ const layerCache = createLayerCacheStore(backend);
+ const history = createHistory();
+ const layers = options.layers ?? [paintLayer('a')];
+ const selectedLayerId = options.selectedLayerId === undefined ? (layers[0]?.id ?? null) : options.selectedLayerId;
+ let document: CanvasDocumentContractV2 | null = makeDoc(layers, selectedLayerId);
+
+ const maskRect = options.maskRect === undefined ? { height: 30, width: 30, x: 20, y: 20 } : options.maskRect;
+ const mask: PlacedSurface | null = maskRect
+ ? { rect: maskRect, surface: backend.createSurface(maskRect.width, maskRect.height) }
+ : null;
+ const selection = { mask: () => mask } as SelectionState;
+
+ if (selectedLayerId) {
+ layerCache.getOrCreateRect(selectedLayerId, options.cacheRect ?? { height: 100, width: 100, x: 0, y: 0 });
+ }
+
+ const dispatched: CanvasProjectMutation[] = [];
+ const installed = vi.fn();
+ let nextId = 0;
+
+ const controller = new NewRasterLayerController({
+ backend,
+ capturePermit: () => (options.permit === undefined ? {} : options.permit),
+ createLayerId: () => `new-${(nextId += 1)}`,
+ dispatchPrepared: (action) => {
+ dispatched.push(action);
+ // Mirror the reducer: apply the stack mutation to the local document so
+ // the controller's postconditions and later reads see the new layer.
+ if (action.type === 'applyCanvasLayerStackMutation' && document) {
+ let next = document.layers;
+ if (action.removeIds) {
+ next = next.filter((layer) => !action.removeIds!.includes(layer.id));
+ }
+ if (action.add) {
+ next = [...next.slice(0, action.add.index), ...action.add.layers, ...next.slice(action.add.index)];
+ }
+ document = { ...document, layers: next, selectedLayerId: action.selectedLayerId ?? null };
+ }
+ },
+ endBurst: vi.fn(),
+ getDocument: () => document,
+ getReducerDocument: () => document,
+ history,
+ installPrepared: installed,
+ isGestureActive: () => options.gestureActive === true,
+ isPermitCurrent: () => true,
+ layers: layerCache,
+ preparePixels: (layerId, rect) => ({ layerId, rect }) as never,
+ selection,
+ });
+
+ return {
+ backend,
+ controller,
+ dispatched,
+ document: () => document,
+ history,
+ installed,
+ layerCache,
+ };
+};
+
+describe('NewRasterLayerController: insert', () => {
+ it('inserts a paint layer above the active one and selects it', () => {
+ const h = createHarness({ layers: [paintLayer('top'), paintLayer('bottom')], selectedLayerId: 'bottom' });
+ const surface = h.backend.createSurface(10, 10);
+
+ const result = h.controller.insert({ height: 10, width: 10, x: 5, y: 5 }, surface, 'New', 'Insert');
+
+ expect(result).toEqual({ layerId: 'new-1', status: 'created' });
+ // Index 0 is top-most, so "above bottom" is bottom's own index.
+ expect(h.document()!.layers.map((layer) => layer.id)).toEqual(['top', 'new-1', 'bottom']);
+ expect(h.document()!.selectedLayerId).toBe('new-1');
+ expect(h.installed).toHaveBeenCalledTimes(1);
+ });
+
+ it('places the pixels via the source offset, leaving the transform identity', () => {
+ const h = createHarness();
+ const surface = h.backend.createSurface(10, 10);
+
+ h.controller.insert({ height: 10, width: 10, x: 40, y: 60 }, surface, 'New', 'Insert');
+
+ const created = createdRaster(h.document(), 'new-1');
+ expect(created.transform).toEqual({ rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 });
+ expect(created.source).toMatchObject({ offset: { x: 40, y: 60 }, type: 'paint' });
+ });
+
+ it('undo removes the layer and restores the previous selection', () => {
+ const h = createHarness({ layers: [paintLayer('a')], selectedLayerId: 'a' });
+ const surface = h.backend.createSurface(10, 10);
+
+ h.controller.insert({ height: 10, width: 10, x: 0, y: 0 }, surface, 'New', 'Insert');
+ expect(h.history.canUndo()).toBe(true);
+
+ h.history.undo();
+ expect(h.document()!.layers.map((layer) => layer.id)).toEqual(['a']);
+ expect(h.document()!.selectedLayerId).toBe('a');
+ });
+
+ it('redo re-inserts the same layer', () => {
+ const h = createHarness();
+ const surface = h.backend.createSurface(10, 10);
+
+ h.controller.insert({ height: 10, width: 10, x: 0, y: 0 }, surface, 'New', 'Insert');
+ h.history.undo();
+ h.history.redo();
+
+ expect(h.document()!.layers.some((layer) => layer.id === 'new-1')).toBe(true);
+ expect(h.document()!.selectedLayerId).toBe('new-1');
+ });
+
+ it('refuses an empty rect', () => {
+ const h = createHarness();
+ const surface = h.backend.createSurface(0, 0);
+ expect(h.controller.insert({ height: 0, width: 0, x: 0, y: 0 }, surface, 'New', 'Insert')).toEqual({
+ status: 'empty',
+ });
+ });
+
+ it('refuses while the document edit lease is unavailable', () => {
+ const h = createHarness({ permit: null });
+ const surface = h.backend.createSurface(10, 10);
+ expect(h.controller.insert({ height: 10, width: 10, x: 0, y: 0 }, surface, 'New', 'Insert')).toEqual({
+ status: 'busy',
+ });
+ });
+
+ it('refuses mid-gesture', () => {
+ const h = createHarness({ gestureActive: true });
+ const surface = h.backend.createSurface(10, 10);
+ expect(h.controller.insert({ height: 10, width: 10, x: 0, y: 0 }, surface, 'New', 'Insert')).toEqual({
+ status: 'busy',
+ });
+ });
+
+ it('refuses once disposed', () => {
+ const h = createHarness();
+ const surface = h.backend.createSurface(10, 10);
+ h.controller.dispose();
+ expect(h.controller.insert({ height: 10, width: 10, x: 0, y: 0 }, surface, 'New', 'Insert')).toEqual({
+ status: 'busy',
+ });
+ });
+});
+
+describe('NewRasterLayerController: pasteImage', () => {
+ it('centres the pasted pixels on the given point', () => {
+ const h = createHarness();
+
+ h.controller.pasteImage(imageData(20, 10), 'Pasted', 'Paste', { x: 50, y: 50 });
+
+ const created = createdRaster(h.document(), 'new-1');
+ expect(created.source).toMatchObject({ offset: { x: 40, y: 45 } });
+ });
+
+ it('places at the origin with no centre given', () => {
+ const h = createHarness();
+
+ h.controller.pasteImage(imageData(20, 10), 'Pasted', 'Paste');
+
+ const created = createdRaster(h.document(), 'new-1');
+ expect(created.source).toMatchObject({ offset: { x: 0, y: 0 } });
+ });
+
+ it('refuses zero-sized pixels', () => {
+ const h = createHarness();
+ expect(h.controller.pasteImage(imageData(0, 0), 'Pasted', 'Paste')).toEqual({ status: 'empty' });
+ });
+});
+
+describe('NewRasterLayerController: liftSelectionToLayer', () => {
+ it('creates a layer covering the selection ∩ content region', () => {
+ const h = createHarness();
+
+ const result = h.controller.liftSelectionToLayer('Selection', 'Layer via copy');
+
+ expect(result).toEqual({ layerId: 'new-1', status: 'created' });
+ const created = createdRaster(h.document(), 'new-1');
+ expect(created.source).toMatchObject({ offset: { x: 20, y: 20 } });
+ });
+
+ it('leaves the source layer untouched — it is a copy, not a cut', () => {
+ const h = createHarness();
+ const before = h.layerCache.get('a')!.version;
+
+ h.controller.liftSelectionToLayer('Selection', 'Layer via copy');
+
+ expect(h.layerCache.get('a')!.version).toBe(before);
+ });
+
+ it('bakes the source layer transform into the new layer placement', () => {
+ // The copy comes out layer-local; a new layer lives in document space, so a
+ // translated source must shift where the pixels land.
+ const h = createHarness({ layers: [paintLayer('a', { x: 10, y: 5 })] });
+
+ h.controller.liftSelectionToLayer('Selection', 'Layer via copy');
+
+ const created = createdRaster(h.document(), 'new-1');
+ expect(created.source).toMatchObject({ offset: { x: 20, y: 20 } });
+ expect(created.transform).toMatchObject({ x: 0, y: 0 });
+ });
+
+ it('refuses with no selection', () => {
+ const h = createHarness({ maskRect: null });
+ expect(h.controller.liftSelectionToLayer('Selection', 'Layer via copy')).toEqual({ status: 'empty' });
+ });
+
+ it('refuses with no selected layer', () => {
+ const h = createHarness({ selectedLayerId: null });
+ expect(h.controller.liftSelectionToLayer('Selection', 'Layer via copy')).toEqual({ status: 'empty' });
+ });
+
+ it('refuses when the selection misses the layer content', () => {
+ const h = createHarness({ cacheRect: { height: 5, width: 5, x: 0, y: 0 } });
+ expect(h.controller.liftSelectionToLayer('Selection', 'Layer via copy')).toEqual({ status: 'empty' });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.ts
new file mode 100644
index 0000000000..091b2e4e20
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.ts
@@ -0,0 +1,200 @@
+import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';
+import type { History } from '@workbench/canvas-engine/history/history';
+import type { LayerCacheStore, PreparedLayerCacheReplacement } from '@workbench/canvas-engine/render/layerCache';
+import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';
+import type { SelectionState } from '@workbench/canvas-engine/selection/selectionState';
+import type { Rect, Vec2 } from '@workbench/canvas-engine/types';
+import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
+
+import { isEmpty, roundOut, transformBounds } from '@workbench/canvas-engine/math/rect';
+import { liftSelectedPixels } from '@workbench/canvas-engine/selection/floatingSelection';
+import { layerMatrix } from '@workbench/canvas-engine/tools/moveHitTest';
+
+export type NewRasterLayerResult = { status: 'created'; layerId: string } | { status: 'busy' | 'empty' | 'missing' };
+
+export interface NewRasterLayerControllerOptions {
+ readonly backend: RasterBackend;
+ readonly layers: LayerCacheStore;
+ readonly selection: SelectionState;
+ readonly history: History;
+ readonly getDocument: () => CanvasDocumentContractV2 | null;
+ readonly getReducerDocument: () => CanvasDocumentContractV2 | null;
+ readonly capturePermit: () => object | null;
+ readonly isPermitCurrent: (permit: object) => boolean;
+ readonly isGestureActive: () => boolean;
+ readonly endBurst: () => void;
+ readonly createLayerId: () => string;
+ readonly preparePixels: (layerId: string, rect: Rect, pixels: RasterSurface) => PreparedLayerCacheReplacement;
+ readonly installPrepared: (prepared: PreparedLayerCacheReplacement) => void;
+ readonly dispatchPrepared: (
+ action: CanvasProjectMutation,
+ expectedReducer: () => boolean,
+ expectedMirror: () => boolean
+ ) => void;
+}
+
+/**
+ * Creates raster layers out of loose pixels, undoably.
+ *
+ * Two callers want the same thing — Paste (pixels from the system clipboard)
+ * and Layer via Copy (the selection's pixels lifted off the active layer) — so
+ * they share one guarded insert rather than growing two near-identical
+ * controllers. The transactional shape follows `ExtractMaskedAreaController`:
+ * capture a permit, build the layer, `dispatchPrepared` with reducer AND mirror
+ * postconditions, install the prepared cache, then push a failure-atomic history
+ * entry whose redo re-runs the exact same apply.
+ *
+ * The new layer is inserted directly above the active one, which is where the
+ * user is looking, and becomes the selection.
+ */
+export class NewRasterLayerController {
+ private disposed = false;
+
+ constructor(private readonly deps: NewRasterLayerControllerOptions) {}
+
+ /**
+ * Inserts `pixels` as a new paint layer covering `rect` (document space).
+ * `pixels` is consumed as-is — the caller owns getting it into document space.
+ */
+ insert(rect: Rect, pixels: RasterSurface, name: string, label: string): NewRasterLayerResult {
+ const permit = this.deps.capturePermit();
+ if (this.disposed || !permit || this.deps.isGestureActive()) {
+ return { status: 'busy' };
+ }
+ const document = this.deps.getDocument();
+ if (!document) {
+ return { status: 'missing' };
+ }
+ if (isEmpty(rect)) {
+ return { status: 'empty' };
+ }
+ this.deps.endBurst();
+
+ const layerId = this.deps.createLayerId();
+ // Pixels are placed by the layer SOURCE offset, not the transform, so the
+ // layer's own transform stays identity — the same shape a paint layer takes
+ // after a stroke, which keeps every later edit (move, transform, float) on
+ // the ordinary path.
+ const layer: CanvasLayerContract = {
+ blendMode: 'normal',
+ id: layerId,
+ isEnabled: true,
+ isLocked: false,
+ name,
+ opacity: 1,
+ source: { bitmap: null, offset: { x: rect.x, y: rect.y }, type: 'paint' },
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
+ type: 'raster',
+ };
+
+ // Above the active layer: index 0 is top-most, so "above" is one index lower.
+ const activeIndex = document.layers.findIndex((candidate) => candidate.id === document.selectedLayerId);
+ const insertIndex = activeIndex >= 0 ? activeIndex : 0;
+ const previousSelectedLayerId = document.selectedLayerId;
+
+ const apply = (): void => {
+ const prepared = this.deps.preparePixels(layerId, rect, pixels);
+ this.deps.dispatchPrepared(
+ {
+ add: { index: insertIndex, layers: [layer] },
+ enabledUpdates: [],
+ selectedLayerId: layerId,
+ type: 'applyCanvasLayerStackMutation',
+ },
+ () =>
+ this.deps.getReducerDocument()?.selectedLayerId === layerId &&
+ this.deps.getReducerDocument()?.layers.some((candidate) => candidate === layer) === true,
+ () =>
+ this.deps.getDocument()?.selectedLayerId === layerId &&
+ this.deps.getDocument()?.layers.some((candidate) => candidate === layer) === true
+ );
+ this.deps.installPrepared(prepared);
+ };
+
+ if (!this.deps.isPermitCurrent(permit)) {
+ return { status: 'busy' };
+ }
+ apply();
+ this.deps.history.push({
+ bytes: rect.width * rect.height * 4 + 256,
+ label,
+ redo: apply,
+ replayFailureAtomic: true,
+ undo: () =>
+ this.deps.dispatchPrepared(
+ {
+ enabledUpdates: [],
+ removeIds: [layerId],
+ selectedLayerId: previousSelectedLayerId,
+ type: 'applyCanvasLayerStackMutation',
+ },
+ () =>
+ this.deps.getReducerDocument()?.selectedLayerId === previousSelectedLayerId &&
+ this.deps.getReducerDocument()?.layers.some((candidate) => candidate.id === layerId) === false,
+ () =>
+ this.deps.getDocument()?.selectedLayerId === previousSelectedLayerId &&
+ this.deps.getDocument()?.layers.some((candidate) => candidate.id === layerId) === false
+ ),
+ });
+ return { layerId, status: 'created' };
+ }
+
+ /**
+ * Copies the selection's pixels off the active layer into a new layer above
+ * it, leaving the source untouched (Photoshop's "Layer via Copy").
+ */
+ liftSelectionToLayer(name: string, label: string): NewRasterLayerResult {
+ const document = this.deps.getDocument();
+ const layer = document?.layers.find((candidate) => candidate.id === document.selectedLayerId);
+ const mask = this.deps.selection.mask();
+ const entry = layer ? this.deps.layers.get(layer.id) : undefined;
+ if (!document || !layer || !mask || !entry || isEmpty(entry.rect)) {
+ return { status: 'empty' };
+ }
+ const matrix = layerMatrix(layer.transform);
+ const lifted = liftSelectedPixels({
+ backend: this.deps.backend,
+ cache: { rect: entry.rect, surface: entry.surface },
+ layerMatrix: matrix,
+ mask,
+ });
+ if (!lifted) {
+ return { status: 'empty' };
+ }
+ // The copy comes out in LAYER-LOCAL space; a new layer is placed in document
+ // space, so bake the source layer's transform into the pixels on the way out.
+ const documentRect = roundOut(transformBounds(matrix, lifted.pixels.rect));
+ if (isEmpty(documentRect)) {
+ return { status: 'empty' };
+ }
+ const surface = this.deps.backend.createSurface(documentRect.width, documentRect.height);
+ const ctx = surface.ctx;
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
+ ctx.globalCompositeOperation = 'source-over';
+ ctx.globalAlpha = 1;
+ ctx.imageSmoothingEnabled = true;
+ ctx.setTransform(matrix.a, matrix.b, matrix.c, matrix.d, matrix.e - documentRect.x, matrix.f - documentRect.y);
+ ctx.drawImage(lifted.pixels.surface.canvas, lifted.pixels.rect.x, lifted.pixels.rect.y);
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
+
+ return this.insert(documentRect, surface, name, label);
+ }
+
+ /** Inserts decoded clipboard pixels as a new layer, centred on `center` when given. */
+ pasteImage(pixels: ImageData, name: string, label: string, center?: Vec2): NewRasterLayerResult {
+ if (pixels.width <= 0 || pixels.height <= 0) {
+ return { status: 'empty' };
+ }
+ const origin = center
+ ? { x: Math.round(center.x - pixels.width / 2), y: Math.round(center.y - pixels.height / 2) }
+ : { x: 0, y: 0 };
+ const surface = this.deps.backend.createSurface(pixels.width, pixels.height);
+ surface.ctx.setTransform(1, 0, 0, 1, 0, 0);
+ surface.ctx.putImageData(pixels, 0, 0);
+ return this.insert({ height: pixels.height, width: pixels.width, x: origin.x, y: origin.y }, surface, name, label);
+ }
+
+ dispose(): void {
+ this.disposed = true;
+ }
+}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index df64121b40..02f9f913bd 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -44,6 +44,7 @@ import type {
ExportBakedLayerPixelsOptions,
ExportLayerPixelsOptions,
LayerExportGuard,
+ NewRasterLayerResult,
PsdExportResult,
StagedPreviewInput,
StagedPreviewPlacement,
@@ -155,7 +156,11 @@ import { rasterizeSource, type ImageResolver, type RasterizeDeps } from '@workbe
import { 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 {
+ documentDeltaToLocal,
+ floatDocumentMatrix,
+ liftSelectedPixels,
+} 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';
@@ -2851,6 +2856,44 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
editingController.selectionPixels.run('erase');
};
+ /**
+ * The selection's pixels on the active layer, encoded as a PNG. Reuses the
+ * float's own masked-copy step (it never mutates the source — the cut is a
+ * separate call), so Copy and a lift always take exactly the same pixels.
+ */
+ const exportSelectionBlob = (): Promise<Blob | null> => {
+ floatingSelection.commit();
+ const doc = mirror.getDocument();
+ const layer = doc?.layers.find((candidate) => candidate.id === doc.selectedLayerId);
+ const mask = selection.mask();
+ const entry = layer ? layerCache.get(layer.id) : undefined;
+ if (!doc || !layer || !mask || !entry || isEmpty(entry.rect)) {
+ return Promise.resolve(null);
+ }
+ const lifted = liftSelectedPixels({
+ backend,
+ cache: { rect: entry.rect, surface: entry.surface },
+ layerMatrix: layerMatrix(layer.transform),
+ mask,
+ });
+ return lifted ? backend.encodeSurface(lifted.pixels.surface) : Promise.resolve(null);
+ };
+
+ const pasteImage = (pixels: ImageData, center?: Vec2): NewRasterLayerResult => {
+ floatingSelection.commit();
+ const doc = mirror.getDocument();
+ // Centred on the generation frame by default — the part of an unbounded
+ // canvas the user is actually composing in.
+ const target =
+ center ?? (doc ? { x: doc.bbox.x + doc.bbox.width / 2, y: doc.bbox.y + doc.bbox.height / 2 } : undefined);
+ return layerController.newRasterLayer.pasteImage(pixels, 'Pasted', 'Paste', target);
+ };
+
+ const liftSelectionToLayer = (): NewRasterLayerResult => {
+ floatingSelection.commit();
+ return layerController.newRasterLayer.liftSelectionToLayer('Selection', 'Layer via copy');
+ };
+
const clearMask = (layerId: string): boolean => layerController.mask.clear(layerId);
const dispose = (): void => {
if (disposed) {
@@ -3117,6 +3160,22 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
rasterize: (layerId) => rasterizeLayerPixelsForStructural(layerId),
},
commitGeneratedImageResult,
+ newRasterLayer: {
+ backend,
+ capturePermit: () => captureDocumentEditPermit(),
+ createLayerId,
+ dispatchPrepared: dispatchPreparedMutation,
+ endBurst: () => endNudgeBurst(),
+ getDocument: () => mirror.getDocument(),
+ getReducerDocument,
+ history,
+ installPrepared: (prepared) => installGeneratedPaintCache(prepared),
+ isGestureActive: () => pipeline.isGestureActive(),
+ isPermitCurrent: (permit) => isDocumentEditPermitCurrent(permit as DocumentEditPermit),
+ layers: layerCache,
+ preparePixels: prepareGeneratedPaintCache,
+ selection: editingController.selection,
+ },
mask: {
applyImagePatch,
canEdit: () => canEditDocument(),
@@ -3405,8 +3464,11 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
eraseSelection,
fillSelection,
getSelectionBounds: () => selection.bounds(),
+ exportSelectionBlob,
getSelectionMaskRect: () => selection.mask()?.rect ?? null,
invertSelection,
+ liftSelectionToLayer,
+ pasteImage,
replaceSelectionFromImage,
selectAll,
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
index 8e90d770b9..4abe925d3d 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
@@ -27,6 +27,7 @@ import { useTranslation } from 'react-i18next';
import { gridSizeForModelBase } from './bboxGrid';
import { CanvasBottomControls } from './CanvasBottomControls';
import { CanvasBottomOverlay } from './CanvasBottomOverlay';
+import { copyBlobToClipboard, decodeImageBlob, readClipboardImage } from './canvasClipboard';
import {
resolveCanvasContextMenu,
resolveCanvasContextMenuBranch,
@@ -232,6 +233,56 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {
[canvasCommands, engine, notifications, queries, t]
);
+ /**
+ * Copies the selection's pixels to the system clipboard, optionally cutting
+ * them. The engine produces the blob; the clipboard write is a widget concern
+ * (`canvas-engine` may not reach `workbench/widgets`).
+ */
+ const copySelection = useEffectEvent((cut: boolean) => {
+ const mountedEngine = engine;
+ if (!mountedEngine) {
+ return;
+ }
+ void (async () => {
+ try {
+ const blob = await mountedEngine.selection.exportSelectionBlob();
+ if (!blob) {
+ return;
+ }
+ await copyBlobToClipboard(blob);
+ if (cut) {
+ // Only after the write succeeds — a failed copy must not destroy pixels.
+ mountedEngine.selection.eraseSelection();
+ }
+ } catch {
+ notifications.add({ kind: 'error', title: t('widgets.canvas.clipboard.copyFailed') });
+ }
+ })();
+ });
+
+ /** Pastes an image off the system clipboard as a new layer over the bbox. */
+ const pasteFromClipboard = useEffectEvent(() => {
+ const mountedEngine = engine;
+ if (!mountedEngine) {
+ return;
+ }
+ void (async () => {
+ const blob = await readClipboardImage();
+ if (!blob) {
+ return;
+ }
+ const pixels = await decodeImageBlob(blob);
+ if (!pixels) {
+ notifications.add({ kind: 'error', title: t('widgets.canvas.clipboard.pasteFailed') });
+ return;
+ }
+ const result = mountedEngine.selection.pasteImage(pixels);
+ if (result.status !== 'created') {
+ notifications.add({ kind: 'error', title: t('widgets.canvas.clipboard.pasteFailed') });
+ }
+ })();
+ });
+
useDndMonitor({ onDragEnd: handleCanvasImageDrop });
useLayoutEffect(() => {
@@ -369,11 +420,18 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {
}
if (commandId === 'canvas.deleteSelected') {
- // Staged images take priority; otherwise delete the selected layer (undoable).
- if (engine && selectedLayer && selectedIndex >= 0) {
+ // With a live pixel selection, Delete clears the selected PIXELS — the
+ // Photoshop meaning. Only with no selection does it delete the layer.
+ if (engine?.interaction.get('hasSelection')) {
+ engine.selection.eraseSelection();
+ } else if (engine && selectedLayer && selectedIndex >= 0) {
const { forward, inverse } = deleteLayerActions(selectedLayer, selectedIndex);
engine.layers.commitStructural(t('widgets.canvas.commands.deleteLayer'), forward, inverse);
}
+ } else if (commandId === 'canvas.copySelection' || commandId === 'canvas.cutSelection') {
+ copySelection(commandId === 'canvas.cutSelection');
+ } else if (commandId === 'canvas.pasteImage') {
+ pasteFromClipboard();
} else if (commandId === 'canvas.resetSelected') {
if (engine && selectedLayer) {
engine.layers.clearMask(selectedLayer.id);
@@ -444,7 +502,11 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {
} else if (commandId === 'canvas.brushSizeUp') {
engine?.tools.stepBrushSize(1);
} else if (commandId === 'canvas.duplicateLayer') {
- if (engine && selectedLayer) {
+ // With a live pixel selection, mod+J is "layer via copy" — it lifts just
+ // the selected pixels. With none, it duplicates the whole layer.
+ if (engine?.interaction.get('hasSelection')) {
+ engine.selection.liftSelectionToLayer();
+ } else if (engine && selectedLayer) {
const { forward, inverse } = duplicateLayerActions(selectedLayer.id, createLayerId());
engine.layers.commitStructural(t('widgets.canvas.commands.duplicateLayer'), forward, inverse);
}
@@ -482,6 +544,9 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {
['canvas.tool.eraser', t('widgets.canvas.commands.selectEraserTool'), ['e']],
['canvas.tool.lasso', t('widgets.canvas.commands.selectLassoTool'), ['l']],
['canvas.tool.marquee', t('widgets.canvas.commands.selectMarqueeTool'), ['u']],
+ ['canvas.copySelection', t('widgets.canvas.commands.copySelection'), ['mod+c']],
+ ['canvas.cutSelection', t('widgets.canvas.commands.cutSelection'), ['mod+x']],
+ ['canvas.pasteImage', t('widgets.canvas.commands.pasteImage'), ['mod+v']],
['canvas.tool.shape', t('widgets.canvas.commands.selectShapeTool'), ['r']],
['canvas.tool.text', t('widgets.canvas.commands.selectTextTool'), ['t']],
['canvas.tool.gradient', t('widgets.canvas.commands.selectGradientTool'), ['g']],
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasClipboard.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasClipboard.test.ts
new file mode 100644
index 0000000000..989e717e21
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasClipboard.test.ts
@@ -0,0 +1,119 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { decodeImageBlob, readClipboardImage } from './canvasClipboard';
+
+const blob = (type: string): Blob => ({ type }) as Blob;
+
+/** A ClipboardItem stand-in exposing just what the reader touches. */
+const item = (types: string[], payload: Record<string, Blob> = {}): ClipboardItem =>
+ ({
+ getType: (type: string) => Promise.resolve(payload[type] ?? blob(type)),
+ types,
+ }) as unknown as ClipboardItem;
+
+describe('readClipboardImage', () => {
+ it('returns null when the clipboard API is unavailable', async () => {
+ await expect(readClipboardImage({ clipboard: undefined })).resolves.toBeNull();
+ });
+
+ it('returns null when permission is refused rather than throwing', async () => {
+ // A paste that cannot read the clipboard is an ordinary outcome — a
+ // defocused document refuses too — so it must not surface as an error.
+ const clipboard = { read: () => Promise.reject(new Error('NotAllowedError')) };
+ await expect(readClipboardImage({ clipboard })).resolves.toBeNull();
+ });
+
+ it('returns null when the clipboard holds no image', async () => {
+ const clipboard = { read: () => Promise.resolve([item(['text/plain'])]) };
+ await expect(readClipboardImage({ clipboard })).resolves.toBeNull();
+ });
+
+ it('reads a PNG off the clipboard', async () => {
+ const png = blob('image/png');
+ const clipboard = { read: () => Promise.resolve([item(['image/png'], { 'image/png': png })]) };
+ await expect(readClipboardImage({ clipboard })).resolves.toBe(png);
+ });
+
+ it('prefers PNG over lossy types when several are offered', async () => {
+ const png = blob('image/png');
+ const jpeg = blob('image/jpeg');
+ const clipboard = {
+ read: () => Promise.resolve([item(['image/jpeg', 'image/png'], { 'image/jpeg': jpeg, 'image/png': png })]),
+ };
+ await expect(readClipboardImage({ clipboard })).resolves.toBe(png);
+ });
+
+ it('falls back to a lossy type when PNG is absent', async () => {
+ const jpeg = blob('image/jpeg');
+ const clipboard = { read: () => Promise.resolve([item(['image/jpeg'], { 'image/jpeg': jpeg })]) };
+ await expect(readClipboardImage({ clipboard })).resolves.toBe(jpeg);
+ });
+
+ it('scans past a non-image item to a later image', async () => {
+ const png = blob('image/png');
+ const clipboard = {
+ read: () => Promise.resolve([item(['text/plain']), item(['image/png'], { 'image/png': png })]),
+ };
+ await expect(readClipboardImage({ clipboard })).resolves.toBe(png);
+ });
+});
+
+describe('decodeImageBlob', () => {
+ const imageData = { data: new Uint8ClampedArray(4), height: 1, width: 1 } as ImageData;
+
+ const fakeCanvas = (pixels: ImageData | null = imageData) => {
+ const drawImage = vi.fn();
+ const canvas = {
+ getContext: () => (pixels ? { drawImage, getImageData: () => pixels } : null),
+ } as unknown as HTMLCanvasElement;
+ return { canvas, drawImage };
+ };
+
+ const bitmap = (width: number, height: number) => {
+ const close = vi.fn();
+ return { bitmap: { close, height, width } as unknown as ImageBitmap, close };
+ };
+
+ it('decodes a blob to ImageData', async () => {
+ const { bitmap: bmp } = bitmap(4, 3);
+ const { canvas, drawImage } = fakeCanvas();
+
+ await expect(
+ decodeImageBlob(blob('image/png'), {
+ createCanvas: () => canvas,
+ createImageBitmap: () => Promise.resolve(bmp),
+ })
+ ).resolves.toBe(imageData);
+ expect(drawImage).toHaveBeenCalledWith(bmp, 0, 0);
+ });
+
+ it('releases the decoded bitmap even when the draw path bails out', async () => {
+ const { bitmap: bmp, close } = bitmap(4, 3);
+ const { canvas } = fakeCanvas(null);
+
+ await expect(
+ decodeImageBlob(blob('image/png'), {
+ createCanvas: () => canvas,
+ createImageBitmap: () => Promise.resolve(bmp),
+ })
+ ).resolves.toBeNull();
+ expect(close).toHaveBeenCalled();
+ });
+
+ it('returns null for an undecodable blob', async () => {
+ await expect(
+ decodeImageBlob(blob('image/png'), { createImageBitmap: () => Promise.reject(new Error('bad')) })
+ ).resolves.toBeNull();
+ });
+
+ it('returns null for a zero-sized image', async () => {
+ const { bitmap: bmp } = bitmap(0, 0);
+ await expect(
+ decodeImageBlob(blob('image/png'), { createImageBitmap: () => Promise.resolve(bmp) })
+ ).resolves.toBeNull();
+ });
+
+ it('returns null when decoding is unavailable', async () => {
+ await expect(decodeImageBlob(blob('image/png'), { createImageBitmap: undefined })).resolves.toBeNull();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasClipboard.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasClipboard.ts
new file mode 100644
index 0000000000..b26c84c463
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasClipboard.ts
@@ -0,0 +1,92 @@
+/**
+ * System-clipboard access for canvas pixel selections.
+ *
+ * The engine deliberately stops at `Blob` / `ImageData` — `canvas-engine` may
+ * not reach `workbench/widgets`, and clipboard permissions are a DOM concern
+ * either way. This module is the widget-side bridge: it reads an image off the
+ * clipboard and decodes it to `ImageData` the engine can paste, and re-exports
+ * the existing write helper so a canvas caller has one place to import from.
+ *
+ * Every dependency is injectable so the whole path is testable without a real
+ * clipboard or canvas.
+ */
+
+export { copyBlobToClipboard } from '@workbench/widgets/layers/layerExportActions';
+
+type ClipboardReadLike = { read(): Promise<readonly ClipboardItem[]> };
+
+export interface ReadClipboardImageDeps {
+ clipboard?: ClipboardReadLike;
+}
+
+/** MIME types accepted from the clipboard, best first. */
+const IMAGE_TYPES = ['image/png', 'image/webp', 'image/jpeg'] as const;
+
+/**
+ * The first image on the clipboard, or `null` when it holds none. Returns
+ * `null` rather than throwing when the clipboard is unavailable or permission
+ * was refused — a paste that finds nothing is an ordinary outcome, not an error.
+ */
+export const readClipboardImage = async (deps: ReadClipboardImageDeps = {}): Promise<Blob | null> => {
+ const clipboard = deps.clipboard ?? (globalThis.navigator?.clipboard as ClipboardReadLike | undefined);
+ if (!clipboard?.read) {
+ return null;
+ }
+ let items: readonly ClipboardItem[];
+ try {
+ items = await clipboard.read();
+ } catch {
+ // Permission refused, or the document is not focused. Nothing to paste.
+ return null;
+ }
+ for (const item of items) {
+ const type = IMAGE_TYPES.find((candidate) => item.types.includes(candidate));
+ if (type) {
+ return item.getType(type);
+ }
+ }
+ return null;
+};
+
+export interface DecodeImageBlobDeps {
+ createImageBitmap?: (blob: Blob) => Promise<ImageBitmap>;
+ createCanvas?: (width: number, height: number) => HTMLCanvasElement | OffscreenCanvas;
+}
+
+const defaultCreateCanvas = (width: number, height: number): HTMLCanvasElement | OffscreenCanvas => {
+ if (typeof OffscreenCanvas !== 'undefined') {
+ return new OffscreenCanvas(width, height);
+ }
+ const canvas = globalThis.document.createElement('canvas');
+ canvas.width = width;
+ canvas.height = height;
+ return canvas;
+};
+
+/** Decodes an image blob to `ImageData`, or `null` when it cannot be decoded. */
+export const decodeImageBlob = async (blob: Blob, deps: DecodeImageBlobDeps = {}): Promise<ImageData | null> => {
+ const decode = deps.createImageBitmap ?? globalThis.createImageBitmap;
+ if (!decode) {
+ return null;
+ }
+ let bitmap: ImageBitmap;
+ try {
+ bitmap = await decode(blob);
+ } catch {
+ return null;
+ }
+ try {
+ if (bitmap.width <= 0 || bitmap.height <= 0) {
+ return null;
+ }
+ const canvas = (deps.createCanvas ?? defaultCreateCanvas)(bitmap.width, bitmap.height);
+ const ctx = canvas.getContext('2d') as CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D | null;
+ if (!ctx) {
+ return null;
+ }
+ ctx.drawImage(bitmap, 0, 0);
+ return ctx.getImageData(0, 0, bitmap.width, bitmap.height);
+ } finally {
+ bitmap.close?.();
+ }
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.tsx
index fba234cf5d..2805fc2676 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.tsx
@@ -75,6 +75,7 @@ export const SelectionOptionsRow = ({ engine, hintKey, mode, onModeChange }: Sel
const onErase = useCallback(() => engine.selection.eraseSelection(), [engine]);
const onInvert = useCallback(() => engine.selection.invertSelection(), [engine]);
const onDeselect = useCallback(() => engine.selection.deselect(), [engine]);
+ const onLiftToLayer = useCallback(() => engine.selection.liftSelectionToLayer(), [engine]);
const canEdit = hasSelection && canPaintTarget;
@@ -92,6 +93,9 @@ export const SelectionOptionsRow = ({ engine, hintKey, mode, onModeChange }: Sel
<Button disabled={!canEdit} size="xs" variant="ghost" onClick={onErase}>
{t('widgets.canvas.toolOptions.eraseSelection')}
</Button>
+ <Button disabled={!canEdit} size="xs" variant="ghost" onClick={onLiftToLayer}>
+ {t('widgets.canvas.toolOptions.liftSelectionToLayer')}
+ </Button>
<Button disabled={!hasSelection} size="xs" variant="ghost" onClick={onInvert}>
{t('widgets.canvas.toolOptions.invertSelection')}
</Button>