Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(canvas): add crop layer to bbox
joshistoastf174719bddd3
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.tsindex eb431e73e6..ee824013d3 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts@@ -384,6 +384,93 @@ describe('createCanvasEngine', () => {engine.dispose();});+ it('cropLayerToBbox replaces a raster/control source with bbox-sized paint pixels at identity', async () => {+ const doc = { ...makeDoc(), bbox: { height: 7, width: 6, x: 2, y: 3 } };+ const { store } = createFakeStore(doc);+ const dispatch = store.dispatch as Mock;+ const base = createTestStubRasterBackend();+ const surfaces: StubRasterSurface[] = [];+ const engine = createCanvasEngine({+ backend: {+ ...base,+ createSurface: (width, height) => {+ const surface = base.createSurface(width, height);+ surfaces.push(surface);+ return surface;+ },+ },+ imageResolver: () => Promise.resolve(new Blob()),+ projectId: 'p1',+ store,+ });++ expect(await engine.cropLayerToBbox('a')).toBe(true);++ expect(dispatch.mock.calls.map((call) => call[0])).toEqual(+ expect.arrayContaining([+ { id: 'a', source: { bitmap: null, offset: { x: 2, y: 3 }, type: 'paint' }, type: 'updateCanvasLayerSource' },+ {+ id: 'a',+ patch: { transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 } },+ type: 'updateCanvasLayer',+ },+ ])+ );+ const cropped = surfaces.find((surface) => surface.width === 6 && surface.height === 7);+ expect(cropped?.callLog.some((entry) => entry.op === 'drawImage')).toBe(true);+ engine.dispose();+ });++ it('cropLayerToBbox replaces a mask bitmap while preserving mask fill', async () => {+ const layer: CanvasInpaintMaskLayerContract = {+ ...maskLayer('mask'),+ mask: { bitmap: { height: 10, imageName: 'mask-img', width: 10 }, fill: { color: '#e07575', style: 'diagonal' } },+ };+ const doc = { ...makeDoc(), bbox: { height: 7, width: 6, x: 2, y: 3 }, layers: [layer] };+ const { store } = createFakeStore(doc);+ const dispatch = store.dispatch as Mock;+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId: 'p1',+ store,+ });++ expect(await engine.cropLayerToBbox('mask')).toBe(true);++ expect(dispatch.mock.calls.map((call) => call[0])).toEqual(+ expect.arrayContaining([+ {+ config: { layerType: 'inpaint_mask', mask: { bitmap: null, offset: { x: 2, y: 3 } } },+ id: 'mask',+ type: 'updateCanvasLayerConfig',+ },+ {+ id: 'mask',+ patch: { transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 } },+ type: 'updateCanvasLayer',+ },+ ])+ );+ engine.dispose();+ });++ it('cropLayerToBbox refuses locked layers', async () => {+ const doc = { ...makeDoc(), layers: [{ ...rasterLayer('a'), isLocked: true }] };+ const { store } = createFakeStore(doc);+ const dispatch = store.dispatch as Mock;+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId: 'p1',+ store,+ });++ expect(await engine.cropLayerToBbox('a')).toBe(false);+ expect(dispatch).not.toHaveBeenCalled();+ engine.dispose();+ });+it('setTool switches the active tool and updates the store', () => {const { engine } = createEngine();const listener = vi.fn();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex 7f95410ea4..14d5df41db 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -313,6 +313,12 @@ export interface CanvasEngine {): Promise<ExportBakedLayerPixelsResult>;/** Encodes {@link exportBakedLayerPixels} as a PNG blob for save/copy/upload actions. */exportBakedLayerBlob(layerId: string, options?: ExportBakedLayerPixelsOptions): Promise<ExportBakedLayerBlobResult>;+ /**+ * Destructively crops a layer to the current bbox: bakes transform/adjustments+ * into bbox-sized paint/mask pixels, resets transform to identity, and persists+ * through the normal bitmap-store path. A no-op for locked/missing/unsupported layers.+ */+ cropLayerToBbox(layerId: string): Promise<boolean>;/*** Rasterizes a parametric (shape/gradient/text) layer to a paint layer: bakes its* current appearance into a content-sized paint bitmap (persisted through the@@ -1151,6 +1157,70 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {return { blob: await backend.encodeSurface(result.surface, 'image/png'), rect: result.rect, status: 'ok' };};+ const cropLayerToBbox = async (layerId: string): Promise<boolean> => {+ if (pipeline.isGestureActive()) {+ return false;+ }+ endNudgeBurst();+ const doc = mirror.getDocument();+ const layer = doc?.layers.find((candidate) => candidate.id === layerId);+ if (!doc || !layer || layer.isLocked) {+ return false;+ }+ const cropRect = roundOut(doc.bbox);+ if (isEmpty(cropRect)) {+ return false;+ }++ const baked = await exportBakedLayerPixels(layerId, { includeDisabled: true });+ if (baked.status !== 'ok') {+ return false;+ }++ const cropped = backend.createSurface(cropRect.width, cropRect.height);+ const cctx = cropped.ctx;+ cctx.setTransform(1, 0, 0, 1, 0, 0);+ cctx.clearRect(0, 0, cropRect.width, cropRect.height);+ cctx.drawImage(baked.surface.canvas, baked.rect.x - cropRect.x, baked.rect.y - cropRect.y);++ const identity = { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 };+ if (layer.type === 'raster' || layer.type === 'control') {+ store.dispatch({+ id: layerId,+ source: { bitmap: null, offset: { x: cropRect.x, y: cropRect.y }, type: 'paint' },+ type: 'updateCanvasLayerSource',+ });+ if (layer.type === 'raster' && layer.adjustments) {+ store.dispatch({+ config: { adjustments: undefined, layerType: 'raster' },+ id: layerId,+ type: 'updateCanvasLayerConfig',+ });+ } else if (layer.type === 'control' && layer.filter) {+ store.dispatch({+ config: { filter: undefined, layerType: 'control' },+ id: layerId,+ type: 'updateCanvasLayerConfig',+ });+ }+ } else {+ store.dispatch({+ config: { layerType: layer.type, mask: { bitmap: null, offset: { x: cropRect.x, y: cropRect.y } } },+ id: layerId,+ type: 'updateCanvasLayerConfig',+ });+ }+ store.dispatch({ id: layerId, patch: { transform: identity }, type: 'updateCanvasLayer' });++ layerCache.delete(layerId);+ const target = layerCache.getOrCreateRect(layerId, cropRect);+ target.surface.ctx.drawImage(cropped.canvas, 0, 0);+ target.stale = false;+ notifyLayerPainted(layerId);+ bitmapStore.markLayerDirty(layerId);+ return true;+ };+/*** Rasterizes a single layer on demand and returns its cache surface plus the* content rect (layer-local origin/size) those pixels occupy, for the@@ -3186,6 +3256,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {commitOpenTextSession,commitStructural,commitTextEdit,+ cropLayerToBbox,deselect,detach,dispose,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsxindex 7df6c5e8c0..fc386524e7 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx@@ -18,6 +18,7 @@ import {ArrowUpIcon,ArrowUpToLineIcon,CopyIcon,+ CropIcon,EyeIcon,EyeOffIcon,ImageIcon,@@ -331,6 +332,10 @@ const LayerMenu = ({await copyBlobToClipboard(result.blob);}, [engine, layer.id]);+ const handleCropToBbox = useCallback(() => {+ void engine?.cropLayerToBbox(layer.id);+ }, [engine, layer.id]);+const handleLayerConfigAction = useCallback((id: LayerContextActionId) => {if (id === 'control-transparency-effect' && layer.type === 'control') {@@ -392,6 +397,9 @@ const LayerMenu = ({case 'copy-to-clipboard':void handleCopyToClipboard();break;+ case 'crop-to-bbox':+ handleCropToBbox();+ break;case 'rasterize':handleRasterize();break;@@ -422,6 +430,7 @@ const LayerMenu = ({handleConvertToControl,handleConvertToRaster,handleCopyToClipboard,+ handleCropToBbox,handleDelete,handleDuplicate,handleFitToBbox,@@ -607,6 +616,7 @@ const LAYER_ACTION_GROUPS: readonly LayerContextAction['group'][] = [const LAYER_ACTION_ICONS: Record<LayerContextActionId, LucideIcon> = {'control-transparency-effect': SlidersHorizontalIcon,'copy-to-clipboard': CopyIcon,+ 'crop-to-bbox': CropIcon,'convert-to-control': SlidersHorizontalIcon,'convert-to-raster': ImageIcon,delete: Trash2Icon,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.tsindex ae170a6efa..5ae891867e 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts@@ -29,6 +29,7 @@ describe('getLayerContextActions', () => {'fit-to-bbox','save-to-assets','copy-to-clipboard',+ 'crop-to-bbox','merge-down','delete',])@@ -83,6 +84,14 @@ describe('getLayerContextActions', () => {expect(actions.find((action) => action.id === 'transform')?.isDisabled).toBe(true);expect(actions.find((action) => action.id === 'save-to-assets')?.isDisabled).toBe(true);expect(actions.find((action) => action.id === 'copy-to-clipboard')?.isDisabled).toBe(true);+ expect(actions.find((action) => action.id === 'crop-to-bbox')?.isDisabled).toBe(true);expect(actions.find((action) => action.id === 'merge-down')?.isDisabled).toBe(true);});++ it('disables crop-to-bbox for locked layers', () => {+ const layer = paintLayer('raster', { isLocked: true });+ const actions = getLayerContextActions({ hasEngine: true, index: 0, layer, layers: [layer] });++ expect(actions.find((action) => action.id === 'crop-to-bbox')?.isDisabled).toBe(true);+ });});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.tsindex a40727275f..63d59cffff 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts@@ -14,6 +14,7 @@ export type LayerContextActionId =| 'fit-to-bbox'| 'save-to-assets'| 'copy-to-clipboard'+ | 'crop-to-bbox'| 'rasterize'| 'convert-to-control'| 'convert-to-raster'@@ -125,6 +126,13 @@ export const LAYER_CONTEXT_ACTION_DEFINITIONS: readonly LayerContextActionDefiniisDisabled: (ctx) => !ctx.hasEngine,labelKey: 'widgets.layers.actions.copyLayerToClipboard',},+ {+ defaultLabel: 'Crop layer to bbox',+ group: 'edit',+ id: 'crop-to-bbox',+ isDisabled: (ctx) => !ctx.hasEngine || ctx.layer.isLocked,+ labelKey: 'widgets.layers.actions.cropLayerToBbox',+ },{defaultLabel: 'Rasterize',group: 'convert',