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(canvas): extract masked canvas areas

joshistoast5c0fbda21e00
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index b50d10f9ab..4ddb627ab9 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -1137,6 +1137,7 @@
"delete": "Delete layer",
"duplicate": "Duplicate layer",
"exclude": "Exclude layer below",
+ "extractMaskedArea": "Extract masked area",
"hide": "Hide layer",
"intersect": "Intersect with layer below",
"lock": "Lock layer",
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 54efd63ad5..ba5c682fdc 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
@@ -1960,6 +1960,131 @@ describe('boolean raster operations', () => {
});
});
+describe('extract masked canvas area', () => {
+ const maskedDoc = (): CanvasDocumentContractV2 => {
+ const doc = twoPaintDoc();
+ return {
+ ...doc,
+ layers: [
+ {
+ ...maskLayer('mask'),
+ mask: {
+ bitmap: { height: 20, imageName: 'mask-bitmap', width: 20 },
+ fill: { color: '#e07575', style: 'diagonal' },
+ offset: { x: 15, y: 25 },
+ },
+ },
+ ...doc.layers,
+ ],
+ selectedLayerId: 'mask',
+ };
+ };
+
+ const setup = () => {
+ const raf = createControllableRaf();
+ vi.stubGlobal('requestAnimationFrame', raf.requestFrame);
+ vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);
+ const { projectId, store } = createReducerBackedStore(maskedDoc());
+ const base = createTestStubRasterBackend();
+ const surfaces: StubRasterSurface[] = [];
+ const backend = {
+ ...base,
+ createSurface: (width: number, height: number): StubRasterSurface => {
+ const surface = base.createSurface(width, height);
+ surfaces.push(surface);
+ return surface;
+ },
+ };
+ const engine = createCanvasEngine({
+ backend,
+ imageResolver: () => Promise.resolve(new Blob()),
+ projectId,
+ store,
+ });
+ const screen = createFakeCanvas();
+ const overlay = createFakeCanvas();
+ engine.attach(screen.element, overlay.element);
+ return { engine, raf, surfaces };
+ };
+
+ it('composites visible raster content through mask alpha and inserts one undoable raster layer', async () => {
+ const { engine, raf, surfaces } = setup();
+ raf.flush();
+ await flushMicrotasks();
+ raf.flush();
+
+ const result = await engine.extractMaskedArea('mask');
+ expect(result.status).toBe('extracted');
+ if (result.status !== 'extracted') {
+ throw new Error('expected an extracted layer');
+ }
+
+ const extractedPixels = surfaces.find((surface) =>
+ surface.callLog.some(
+ (entry) =>
+ entry.op === 'set' && entry.args[0] === 'globalCompositeOperation' && entry.args[1] === 'destination-in'
+ )
+ );
+ expect(extractedPixels).toMatchObject({ height: 20, width: 20 });
+ expect(extractedPixels!.callLog.filter((entry) => entry.op === 'drawImage').length).toBeGreaterThanOrEqual(3);
+
+ const extracted = engine.getDocument()!.layers.find((layer) => layer.id === result.layerId);
+ expect(extracted).toMatchObject({
+ isEnabled: true,
+ source: { bitmap: null, offset: { x: 15, y: 25 }, type: 'paint' },
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
+ type: 'raster',
+ });
+ expect(engine.getDocument()!.layers.find((layer) => layer.id === 'mask')).toEqual(maskedDoc().layers[0]);
+ expect(engine.getDocument()!.layers.find((layer) => layer.id === 'upper')?.isEnabled).toBe(true);
+ expect(engine.getDocument()!.layers.find((layer) => layer.id === 'below')?.isEnabled).toBe(true);
+
+ engine.undo();
+ expect(engine.getDocument()!.layers.some((layer) => layer.id === result.layerId)).toBe(false);
+ engine.redo();
+ expect(engine.getDocument()!.layers.some((layer) => layer.id === result.layerId)).toBe(true);
+ engine.dispose();
+ });
+
+ it('refuses extraction until the mask and contributor caches are ready', async () => {
+ const { engine, raf } = setup();
+ raf.flush();
+
+ expect(await engine.extractMaskedArea('mask')).toEqual({ status: 'not-ready' });
+ expect(engine.getDocument()!.layers.map((layer) => layer.id)).toEqual(['mask', 'upper', 'below']);
+ engine.dispose();
+ });
+
+ it('rejects missing, unsupported, and empty masks without changing the document', async () => {
+ const doc = maskedDoc();
+ const { projectId, store } = createReducerBackedStore(doc);
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ imageResolver: () => Promise.resolve(new Blob()),
+ projectId,
+ store,
+ });
+
+ expect(await engine.extractMaskedArea('missing')).toEqual({ status: 'missing' });
+ expect(await engine.extractMaskedArea('upper')).toEqual({ status: 'unsupported' });
+ expect(await engine.extractMaskedArea('mask')).toEqual({ status: 'not-ready' });
+ expect(engine.getDocument()!.layers).toEqual(doc.layers);
+ engine.dispose();
+
+ const emptyDoc = maskedDoc();
+ emptyDoc.layers[0] = maskLayer('mask');
+ const emptyHarness = createReducerBackedStore(emptyDoc);
+ const emptyEngine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ imageResolver: () => Promise.resolve(new Blob()),
+ projectId: emptyHarness.projectId,
+ store: emptyHarness.store,
+ });
+ expect(await emptyEngine.extractMaskedArea('mask')).toEqual({ status: 'empty' });
+ emptyEngine.dispose();
+ });
+});
+
// ---- mergeVisibleRasterLayers: whole-fold pre-flight + interleave-safe fold ----
/**
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index 1d41372edb..02f67d0cee 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -134,6 +134,10 @@ export type MergeVisibleResult = 'merged' | 'not-ready' | 'nothing';
export type BooleanRasterOperation = 'intersect' | 'cutout' | 'cutaway' | 'exclude';
export type BooleanRasterResult = 'merged' | 'missing' | 'unsupported' | 'not-ready' | 'busy' | 'empty';
+export type ExtractMaskedAreaResult =
+ | { status: 'extracted'; layerId: string }
+ | { status: 'missing' | 'unsupported' | 'not-ready' | 'busy' | 'empty' };
+
/**
* Result of {@link CanvasEngine.exportRasterLayersToPsd}: `'exported'` on
* success, `'nothing'` when there are no raster layers with content, `'too-large'`
@@ -277,6 +281,8 @@ export interface CanvasEngine {
* The complete change is one engine-history entry.
*/
booleanMergeRasterLayers(upperLayerId: string, operation: BooleanRasterOperation): Promise<BooleanRasterResult>;
+ /** Extracts the enabled raster/control composite through one inpaint mask. */
+ extractMaskedArea(maskLayerId: string): Promise<ExtractMaskedAreaResult>;
/**
* Folds ALL visible mergeable raster layers together (the raster group-header
* "merge visible" action; legacy `mergeVisibleOfType`). Plans runs via the pure
@@ -2141,6 +2147,91 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
return 'merged';
};
+ const extractMaskedArea = async (maskLayerId: string): Promise<ExtractMaskedAreaResult> => {
+ if (pipeline.isGestureActive()) {
+ return { status: 'busy' };
+ }
+ endNudgeBurst();
+ const doc = mirror.getDocument();
+ if (!doc) {
+ return { status: 'missing' };
+ }
+ const maskIndex = doc.layers.findIndex((layer) => layer.id === maskLayerId);
+ if (maskIndex < 0) {
+ return { status: 'missing' };
+ }
+ const maskLayer = doc.layers[maskIndex];
+ if (!maskLayer || maskLayer.type !== 'inpaint_mask') {
+ return { status: 'unsupported' };
+ }
+ if (isEmpty(getSourceContentRect(maskLayer, doc))) {
+ return { status: 'empty' };
+ }
+ const contributors = doc.layers.filter(
+ (layer) => layer.isEnabled && (layer.type === 'raster' || layer.type === 'control')
+ );
+ if (contributors.length === 0) {
+ return { status: 'empty' };
+ }
+ if (!isLayerCacheReadyForOp(maskLayer, doc) || contributors.some((layer) => !isLayerCacheReadyForOp(layer, doc))) {
+ return { status: 'not-ready' };
+ }
+
+ const maskPixels = await exportBakedLayerPixels(maskLayerId, { includeDisabled: true });
+ if (maskPixels.status !== 'ok') {
+ return { status: maskPixels.status === 'not-ready' ? 'not-ready' : 'empty' };
+ }
+ const resultRect = maskPixels.rect;
+ if (isEmpty(resultRect)) {
+ return { status: 'empty' };
+ }
+
+ const resultPixels = backend.createSurface(resultRect.width, resultRect.height);
+ const compositeDoc: CanvasDocumentContractV2 = { ...doc, layers: contributors };
+ compositeDocument(
+ resultPixels,
+ compositeDoc,
+ layerCache,
+ { a: 1, b: 0, c: 0, d: 1, e: -resultRect.x, f: -resultRect.y },
+ {
+ adjustedSurface: getAdjustedSurface,
+ backend,
+ maskPatternTile: getMaskPatternTile,
+ }
+ );
+ const ctx = resultPixels.ctx;
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
+ ctx.globalAlpha = 1;
+ ctx.globalCompositeOperation = 'destination-in';
+ ctx.drawImage(maskPixels.surface.canvas, 0, 0);
+
+ const resultId = createLayerId();
+ const resultLayer: CanvasLayerContract = {
+ blendMode: 'normal',
+ id: resultId,
+ isEnabled: true,
+ isLocked: false,
+ name: `${maskLayer.name} extraction`,
+ opacity: 1,
+ source: { bitmap: null, offset: { x: resultRect.x, y: resultRect.y }, type: 'paint' },
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
+ type: 'raster',
+ };
+ const apply = (): void => {
+ store.dispatch({ index: maskIndex, layer: resultLayer, type: 'addCanvasLayer' });
+ seedGeneratedPaintCache(resultId, resultRect, resultPixels);
+ };
+
+ apply();
+ history.push({
+ bytes: resultRect.width * resultRect.height * 4 + 256,
+ label: 'Extract masked area',
+ redo: apply,
+ undo: () => store.dispatch({ ids: [resultId], type: 'removeCanvasLayers' }),
+ });
+ return { layerId: resultId, status: 'extracted' };
+ };
+
const mergeLayerDown = (upperLayerId: string): boolean => {
// No-op mid-gesture (a mod+e mashed during a paint drag): merging writes
// pixels and dispatches a structural collapse under the open stroke session.
@@ -3423,6 +3514,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
dispose,
drawLayerThumbnail,
eraseSelection,
+ extractMaskedArea,
exportRasterLayersToPsd,
exportBakedLayerBlob,
exportBakedLayerPixels,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
index 8400d6492b..3134bf6670 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
@@ -380,6 +380,10 @@ const LayerMenu = ({
void engine?.cropLayerToBbox(layer.id);
}, [engine, layer.id]);
+ const handleExtractMaskedArea = useCallback(() => {
+ void engine?.extractMaskedArea(layer.id);
+ }, [engine, layer.id]);
+
const handleBooleanRaster = useCallback(
(operation: 'intersect' | 'cutout' | 'cutaway' | 'exclude') => {
void engine?.booleanMergeRasterLayers(layer.id, operation);
@@ -491,6 +495,9 @@ const LayerMenu = ({
case 'crop-to-bbox':
handleCropToBbox();
break;
+ case 'extract-masked-area':
+ handleExtractMaskedArea();
+ break;
case 'intersect':
case 'cutout':
case 'cutaway':
@@ -555,6 +562,7 @@ const LayerMenu = ({
handleCropToBbox,
handleDelete,
handleDuplicate,
+ handleExtractMaskedArea,
handleFitToBbox,
handleLayerConfigAction,
handleMerge,
@@ -752,6 +760,7 @@ const LAYER_ACTION_ICONS: Record<LayerContextActionId, LucideIcon> = {
delete: Trash2Icon,
duplicate: CopyIcon,
exclude: MergeIcon,
+ 'extract-masked-area': CropIcon,
'fit-to-bbox': ImageIcon,
'inpaint-denoise-limit': SlidersHorizontalIcon,
'inpaint-noise': SlidersHorizontalIcon,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts
index 5f4f598b2b..e0e99bdfea 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts
@@ -97,9 +97,18 @@ describe('getLayerContextActions', () => {
expect(idsFor(layer)).toContain('inpaint-denoise-limit');
expect(idsFor(layer)).toContain('copy-to-regional-guidance');
+ expect(idsFor(layer)).toContain('extract-masked-area');
expect(idsFor(layer)).not.toContain('inpaint-noise');
});
+ it('exposes masked extraction only for inpaint masks and disables it without an engine', () => {
+ const mask = createInpaintMaskLayer('Mask', 'mask');
+ const withoutEngine = getLayerContextActions({ hasEngine: false, index: 0, layer: mask, layers: [mask] });
+
+ expect(withoutEngine.find((action) => action.id === 'extract-masked-area')?.isDisabled).toBe(true);
+ expect(idsFor(paintLayer('raster'))).not.toContain('extract-masked-area');
+ });
+
it('copies regional guidance to an inpaint mask without offering unsupported conversions', () => {
const layer = createRegionalGuidanceLayer('Region', 0, 'region');
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts
index 5f7e9483b1..8982ff3a01 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts
@@ -15,6 +15,7 @@ export type LayerContextActionId =
| 'save-to-assets'
| 'copy-to-clipboard'
| 'crop-to-bbox'
+ | 'extract-masked-area'
| 'intersect'
| 'cutout'
| 'cutaway'
@@ -147,6 +148,14 @@ export const LAYER_CONTEXT_ACTION_DEFINITIONS: readonly LayerContextActionDefini
isDisabled: (ctx) => !ctx.hasEngine || ctx.layer.isLocked,
labelKey: 'widgets.layers.actions.cropLayerToBbox',
},
+ {
+ defaultLabel: 'Extract masked area',
+ group: 'edit',
+ id: 'extract-masked-area',
+ isDisabled: (ctx) => !ctx.hasEngine,
+ isVisible: (ctx) => ctx.layer.type === 'inpaint_mask',
+ labelKey: 'widgets.layers.actions.extractMaskedArea',
+ },
{
defaultLabel: 'Intersect with layer below',
group: 'edit',