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): clear selected masks with shift c
joshistoast50c0f7fa4ecb
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex b851f0ff20..e5649e1d23 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -934,6 +934,7 @@"previousEntity": "Previous canvas entity","redo": "Redo canvas edit","reorderLayer": "Reorder layer",+ "resetSelected": "Clear selected mask","selectAll": "Select all","selectBboxTool": "Select generation frame tool","selectBrushTool": "Select brush tool",diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.test.tsindex fcec69f895..06f191dca9 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.test.ts@@ -513,6 +513,24 @@ describe('createBitmapStore', () => {h.store.dispose();});+ it('discardLayer cancels pending and in-flight persistence for one cleared layer', async () => {+ const deferred = createDeferred<CanvasImageUploadResult>();+ const uploadImage = vi.fn(() => deferred.promise);+ const h = createHarness({ uploadImage });++ h.store.markLayerDirty(LAYER);+ const barrier = h.store.flushPendingUploads();+ await drainUntil(() => uploadImage.mock.calls.length >= 1);++ h.store.discardLayer(LAYER);+ deferred.resolve({ height: 10, imageName: 'stale-mask', width: 10 });+ await barrier;+ await vi.advanceTimersByTimeAsync(3000);++ expect(h.dispatch).not.toHaveBeenCalled();+ h.store.dispose();+ });+it('does not flush after dispose', async () => {const h = createHarness();h.store.markLayerDirty(LAYER);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.tsindex 305830ae59..b3eba856f0 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/bitmapStore.ts@@ -123,6 +123,8 @@ export interface BitmapStoreDeps {export interface BitmapStore {/** Marks a layer dirty and (re)arms its debounce timer. Called on each committed stroke. */markLayerDirty(layerId: string): void;+ /** Cancels pending persistence and invalidates an in-flight result for one layer. */+ discardLayer(layerId: string): void;/** Flushes every dirty layer immediately and resolves once all in-flight uploads settle. */flushPendingUploads(): Promise<void>;/**@@ -204,6 +206,8 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {const hashToImage = new Map<string, CanvasImageUploadResult>();/** Layer id → the image name most recently dispatched by this store (self-echo guard). */const lastApplied = new Map<string, string>();+ /** Per-layer generation used to invalidate an upload already in flight when its pixels are discarded. */+ const layerGenerations = new Map<string, number>();let disposed = false;const clearTimer = (layerId: string): void => {@@ -261,6 +265,7 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {/** Encodes → hashes → dedupes/uploads → swaps the layer's ref, once. */const flushLayer = async (layerId: string): Promise<void> => {+ const generationAtEntry = layerGenerations.get(layerId) ?? 0;const placed = deps.getLayerSurface(layerId);if (!placed) {// Layer or its cache is gone (or empty); nothing to persist.@@ -325,6 +330,9 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {if (disposed) {return;}+ if ((layerGenerations.get(layerId) ?? 0) !== generationAtEntry) {+ return;+ }// Re-check the source right before dispatching: `encodeSurface`/`hashBlob`/// `uploadImage` above all awaited, so a source-type change (rasterize →// undo) landing DURING that window would slip past the entry-time@@ -416,6 +424,14 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {scheduleFlush(layerId);};+ const discardLayer = (layerId: string): void => {+ layerGenerations.set(layerId, (layerGenerations.get(layerId) ?? 0) + 1);+ dirty.delete(layerId);+ dirtyReason.delete(layerId);+ lastApplied.delete(layerId);+ clearTimer(layerId);+ };+/** Safety net against a genuine infinite loop; real barrier calls settle in a handful of rounds. */const MAX_BARRIER_ITERATIONS = 10_000;@@ -457,6 +473,9 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {};const reset = (): void => {+ for (const layerId of inFlight.keys()) {+ layerGenerations.set(layerId, (layerGenerations.get(layerId) ?? 0) + 1);+ }// Cancel pending debounced flushes and drop dirty state for the OLD document.for (const handle of debounceTimers.values()) {timers.clearTimeout(handle);@@ -480,7 +499,8 @@ export const createBitmapStore = (deps: BitmapStoreDeps): BitmapStore => {inFlight.clear();hashToImage.clear();lastApplied.clear();+ layerGenerations.clear();};- return { dispose, flushPendingUploads, isSelfEcho, markLayerDirty, reset };+ return { discardLayer, dispose, flushPendingUploads, isSelfEcho, markLayerDirty, reset };};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.mask.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.mask.test.tsindex fd7114b0d9..8d642b6edf 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.mask.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.mask.test.ts@@ -392,3 +392,82 @@ describe('mask invert', () => {engine.dispose();});});++describe('mask clear', () => {+ it('clears a live unflushed inpaint mask and restores it through undo', () => {+ const { engine, overlay } = setupEngine(maskDoc());+ engine.setTool('brush');+ overlay.fire('pointerdown', pointerAt(20, 20));+ overlay.fire('pointermove', pointerAt(50, 50));+ overlay.fire('pointerup', pointerAt(50, 50, 0));++ expect(engine.clearMask('mask1')).toBe(true);+ expect(engine.clearMask('mask1')).toBe(false);+ expect(engine.stores.canUndo.get()).toBe(true);++ engine.undo();+ expect(engine.stores.canRedo.get()).toBe(true);+ engine.redo();+ expect(engine.clearMask('mask1')).toBe(false);+ engine.undo();+ expect(engine.clearMask('mask1')).toBe(true);+ engine.dispose();+ });++ it('clears a regional-guidance mask', () => {+ const doc = maskDoc();+ doc.layers[0] = {+ autoNegative: false,+ blendMode: 'normal',+ id: 'mask1',+ isEnabled: true,+ isLocked: false,+ mask: { bitmap: null, fill: { color: '#e07575', style: 'diagonal' } },+ name: 'Region 1',+ negativePrompt: null,+ opacity: 1,+ positivePrompt: null,+ referenceImages: [],+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'regional_guidance',+ };+ const { engine, overlay } = setupEngine(doc);+ engine.setTool('brush');+ overlay.fire('pointerdown', pointerAt(20, 20));+ overlay.fire('pointermove', pointerAt(50, 50));+ overlay.fire('pointerup', pointerAt(50, 50, 0));++ expect(engine.clearMask('mask1')).toBe(true);+ engine.dispose();+ });++ it('refuses missing, non-mask, locked, and empty layers', () => {+ const locked = maskDoc();+ locked.layers[0]!.isLocked = true;+ const { engine } = setupEngine(locked);++ expect(engine.clearMask('missing')).toBe(false);+ expect(engine.clearMask('mask1')).toBe(false);+ engine.dispose();++ const raster = maskDoc();+ raster.layers[0] = {+ blendMode: 'normal',+ id: 'mask1',+ isEnabled: true,+ isLocked: false,+ name: 'Raster 1',+ opacity: 1,+ source: { bitmap: null, type: 'paint' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'raster',+ };+ const { engine: rasterEngine } = setupEngine(raster);+ expect(rasterEngine.clearMask('mask1')).toBe(false);+ rasterEngine.dispose();++ const { engine: emptyEngine } = setupEngine(maskDoc());+ expect(emptyEngine.clearMask('mask1')).toBe(false);+ emptyEngine.dispose();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.tsindex 3b480c677e..2acaab2f96 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts@@ -961,6 +961,7 @@ const createSpyBitmapStore = (): BitmapStore & {markLayerDirty: Mock<(layerId: string) => void>;reset: Mock<() => void>;} => ({+ discardLayer: vi.fn(),dispose: vi.fn(),flushPendingUploads: vi.fn(() => Promise.resolve()),isSelfEcho: () => false,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex ab493abef3..ccff56162a 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -429,6 +429,8 @@ export interface CanvasEngine {deselect(): void;/** Inverts the selection within the document (`mod+shift+i`). */invertSelection(): void;+ /** Clears an inpaint/regional mask as one undoable edit, preserving its non-pixel settings. */+ clearMask(layerId: string): boolean;/*** Inverts a mask layer's alpha in place over `content ∪ bbox`, as one undoable* edit persisted through the normal dirty path. A no-op (returns `false`)@@ -3390,6 +3392,59 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {const fillSelection = (): void => runMaskedSelectionEdit('fill');const eraseSelection = (): void => runMaskedSelectionEdit('erase');+ /** Clears a mask's live pixels and persisted bitmap while retaining prompts, fill, and modifiers. */+ const clearMask = (layerId: string): boolean => {+ if (pipeline.isGestureActive()) {+ return false;+ }+ const doc = mirror.getDocument();+ if (!doc) {+ return false;+ }+ const layer = doc.layers.find((candidate) => candidate.id === layerId);+ if (!layer || !isMaskLayer(layer) || layer.isLocked || !isLayerCacheReadyForOp(layer, doc)) {+ return false;+ }+ const entry = layerCache.get(layerId);+ if (!entry || isEmpty(entry.rect)) {+ return false;+ }+ const before = entry.surface.ctx.getImageData(0, 0, entry.rect.width, entry.rect.height);+ endNudgeBurst();+ const rect = { ...entry.rect };+ const emptyRect = { height: 0, width: 0, x: 0, y: 0 };+ const dispatchEmptyMask = (offset: { x: number; y: number }): void => {+ store.dispatch({+ config: { layerType: layer.type, mask: { bitmap: null, offset } },+ id: layerId,+ type: 'updateCanvasLayerConfig',+ });+ };+ const applyClear = (): void => {+ bitmapStore.discardLayer(layerId);+ dispatchEmptyMask({ x: 0, y: 0 });+ layerCache.delete(layerId);+ adjustedSurfaceCache.delete(layerId);+ const empty = layerCache.getOrCreateRect(layerId, emptyRect);+ empty.stale = false;+ notifyLayerPainted(layerId);+ };+ const applyRestore = (): void => {+ bitmapStore.discardLayer(layerId);+ dispatchEmptyMask({ x: rect.x, y: rect.y });+ restoreLayerCache(layerId, rect, before);+ };++ applyClear();+ history.push({+ bytes: before.data.byteLength + 256,+ label: 'Clear mask',+ redo: applyClear,+ undo: applyRestore,+ });+ return true;+ };+/*** Inverts a mask layer's alpha in place, over the domain* `content ∪ liveCacheRect ∪ bbox` (the same bounded-domain decision the@@ -3598,6 +3653,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {booleanMergeRasterLayers,clearCaches,clearHistory,+ clearMask,contextMenuLayerIdAt,logDebugInfo,attach,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.test.tsindex c4332fe3ad..068066f8a6 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.test.ts@@ -41,12 +41,19 @@ const makePointerEvent = (init: FakePointerInit = {}): PointerEvent => {return self as unknown as PointerEvent;};-const makeKeyEvent = (init: { code?: string; key?: string; repeat?: boolean; target?: unknown }): KeyboardEvent =>+const makeKeyEvent = (init: {+ code?: string;+ key?: string;+ repeat?: boolean;+ shiftKey?: boolean;+ target?: unknown;+}): KeyboardEvent =>({code: init.code ?? '',key: init.key ?? '',preventDefault: vi.fn(),repeat: init.repeat ?? false,+ shiftKey: init.shiftKey ?? false,target: init.target ?? null,}) as unknown as KeyboardEvent;@@ -425,6 +432,16 @@ describe('pointer pipeline: temporary modifier tools', () => {expect(h.setTool.mock.calls.slice(-2)).toEqual([['brush', { temporary: true }], ['bbox']]);});+ it('leaves Shift+C to the registered clear-mask hotkey', () => {+ const h = createHarness({ tools: ['view', 'brush', 'bbox'] });+ h.pipeline.onPointerEnter();++ h.pipeline.onKeyDown(makeKeyEvent({ code: 'KeyC', key: 'C', shiftKey: true }));+ h.pipeline.onKeyUp(makeKeyEvent({ code: 'KeyC', key: 'C', shiftKey: true }));++ expect(h.setTool).not.toHaveBeenCalled();+ });+it('holding C restores the prior tool on release without sticky-selecting bbox', () => {vi.useFakeTimers();const h = createHarness({ tools: ['view', 'brush', 'bbox'] });diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.tsindex 54dc872bd3..282dd3f77e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.ts@@ -104,7 +104,8 @@ const toPointerType = (type: string): PointerInput['pointerType'] =>type === 'pen' ? 'pen' : type === 'touch' ? 'touch' : 'mouse';const isAltKey = (event: KeyboardEvent): boolean => event.code === 'AltLeft' || event.code === 'AltRight';-const isBboxKey = (event: KeyboardEvent): boolean => event.code === 'KeyC';+const isBboxKey = (event: KeyboardEvent): boolean =>+ event.code === 'KeyC' && !event.altKey && !event.ctrlKey && !event.metaKey && !event.shiftKey;/*** True when the key event targets an editable element (text input, textarea, ordiff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsxindex e07e0acfff..eeb9aae234 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx@@ -272,6 +272,10 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {const { forward, inverse } = deleteLayerActions(selectedLayer, selectedIndex);engine.commitStructural(t('widgets.canvas.commands.deleteLayer'), forward, inverse);}+ } else if (commandId === 'canvas.resetSelected') {+ if (engine && selectedLayer) {+ engine.clearMask(selectedLayer.id);+ }} else if (commandId === 'canvas.undo') {// Canvas undo/redo is engine-scoped: it drives the engine-owned pixel/// structural history, NOT project-level (reducer) undo. When the canvas@@ -338,6 +342,7 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {['canvas.prevEntity', t('widgets.canvas.commands.previousEntity'), ['alt+[']],['canvas.nextEntity', t('widgets.canvas.commands.nextEntity'), ['alt+]']],['canvas.deleteSelected', t('widgets.canvas.commands.deleteSelected'), ['delete', 'backspace']],+ ['canvas.resetSelected', t('widgets.canvas.commands.resetSelected'), ['shift+c']],['canvas.undo', t('widgets.canvas.commands.undo'), ['mod+z']],['canvas.redo', t('widgets.canvas.commands.redo'), ['mod+shift+z', 'mod+y']],// Tool selection and brush/eraser size step. `allowInEditable: false` below