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): edit control layers through selections

joshistoast40550006574c
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 5771db5dc2..57184617bb 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
@@ -2157,6 +2157,8 @@ const createControlPaintHarness = (overrides: ControlPaintHarnessOverrides) => {
};
};
+const createControlSelectionHarness = createControlPaintHarness;
+
/** A minimal in-memory bitmap store: records dirty-marks, never touches the network. */
const createSpyBitmapStore = (): BitmapStore & {
markLayerDirty: Mock<(layerId: string) => void>;
@@ -12381,6 +12383,228 @@ describe('engine selection: fill / erase', () => {
return { bitmapStore, engine };
};
+ it('fills an empty selected paint control without adding a raster layer', () => {
+ const h = createControlSelectionHarness({ source: { bitmap: null, type: 'paint' } });
+ h.engine.selectAll();
+ h.engine.fillSelection();
+ expect(h.engine.getDocument()!.layers).toHaveLength(1);
+ expect(h.engine.getDocument()!.layers[0]).toMatchObject({ id: 'control', type: 'control' });
+ expect(h.engine.stores.canUndo.get()).toBe(true);
+ h.engine.dispose();
+ });
+
+ it('erases an existing selected paint control without adding a raster layer', async () => {
+ const h = createControlSelectionHarness({
+ source: { bitmap: { height: 10, imageName: 'paint-bitmap', width: 10 }, type: 'paint' },
+ });
+ await h.publishInitialCache();
+ h.engine.selectAll();
+ h.engine.eraseSelection();
+ expect(h.engine.getDocument()!.layers).toHaveLength(1);
+ expect(h.engine.getDocument()!.layers[0]).toMatchObject({ id: 'control', type: 'control' });
+ expect(h.engine.stores.canUndo.get()).toBe(true);
+ h.engine.dispose();
+ });
+
+ it.each(['fill', 'erase'] as const)('materializes an image control and %ss it as one undo step', async (kind) => {
+ const h = createControlSelectionHarness({
+ source: { image: { height: 10, imageName: 'control-image', width: 10 }, type: 'image' },
+ transform: { rotation: 0, scaleX: 2, scaleY: 2, x: 5, y: 6 },
+ });
+ await h.publishInitialCache();
+ const before = structuredClone(h.engine.getDocument()!.layers[0]);
+ h.engine.selectAll();
+ if (kind === 'fill') {
+ h.engine.fillSelection();
+ } else {
+ h.engine.eraseSelection();
+ }
+ const after = structuredClone(h.engine.getDocument()!.layers[0]);
+ expect(after).toMatchObject({ id: 'control', source: { type: 'paint' }, type: 'control' });
+ h.engine.undo();
+ expect(h.engine.getDocument()!.layers[0]).toEqual(before);
+ h.engine.redo();
+ expect(h.engine.getDocument()!.layers[0]).toEqual(after);
+ h.engine.dispose();
+ });
+
+ it('does not materialize an image control when Erase has no overlapping pixels', async () => {
+ const h = createControlSelectionHarness({
+ source: { image: { height: 10, imageName: 'control-image', width: 10 }, type: 'image' },
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 50, y: 50 },
+ });
+ await h.publishInitialCache();
+ const before = structuredClone(h.engine.getDocument());
+ h.engine.setTool('lasso');
+ h.overlay.fire('pointerdown', pointerAt(0, 0));
+ h.overlay.fire('pointermove', pointerAt(10, 0));
+ h.overlay.fire('pointermove', pointerAt(10, 10));
+ h.overlay.fire('pointermove', pointerAt(0, 10));
+ h.overlay.fire('pointerup', pointerAt(0, 0, { buttons: 0 }));
+ h.engine.eraseSelection();
+ expect(h.engine.getDocument()).toEqual(before);
+ expect(h.engine.stores.canUndo.get()).toBe(false);
+ expect(h.bitmapStore.suspendLayer).not.toHaveBeenCalled();
+ h.engine.dispose();
+ });
+
+ it.each([
+ ['locked', { isLocked: true }],
+ ['disabled', { isEnabled: false }],
+ ] as const)('selection editing leaves a %s control unchanged', (_scenario, patch) => {
+ const h = createControlSelectionHarness({ source: { bitmap: null, type: 'paint' }, ...patch });
+ const before = structuredClone(h.engine.getDocument());
+ h.engine.selectAll();
+ h.engine.fillSelection();
+ expect(h.engine.getDocument()).toEqual(before);
+ expect(h.engine.stores.canUndo.get()).toBe(false);
+ expect(h.bitmapStore.markLayerDirty).not.toHaveBeenCalled();
+ h.engine.dispose();
+ });
+
+ it('selection editing leaves a not-ready image control unchanged', () => {
+ const h = createControlSelectionHarness({
+ source: { image: { height: 10, imageName: 'pending-image', width: 10 }, type: 'image' },
+ });
+ const before = structuredClone(h.engine.getDocument());
+ h.engine.selectAll();
+ h.engine.fillSelection();
+ expect(h.engine.getDocument()).toEqual(before);
+ expect(h.engine.stores.canUndo.get()).toBe(false);
+ expect(h.bitmapStore.markLayerDirty).not.toHaveBeenCalled();
+ h.engine.dispose();
+ });
+
+ it('rolls back a direct control selection edit when masked compositing fails', async () => {
+ const h = createControlSelectionHarness({
+ source: { bitmap: { height: 10, imageName: 'paint-bitmap', width: 10 }, type: 'paint' },
+ });
+ await h.publishInitialCache();
+ const beforeDocument = structuredClone(h.engine.getDocument());
+ const beforeCache = await snapshotLayerCache(h.engine, 'control');
+ const originalCtx = beforeCache.surface.ctx;
+ let capturedBefore: ImageData | null = null;
+ const failingCtx = new Proxy(originalCtx, {
+ get(target, property, receiver) {
+ const value = Reflect.get(target, property, receiver);
+ if (property === 'getImageData' && typeof value === 'function') {
+ return (...args: unknown[]) => {
+ const result = Reflect.apply(value, target, args) as ImageData;
+ capturedBefore = result;
+ return result;
+ };
+ }
+ if (property === 'drawImage' && typeof value === 'function') {
+ return (...args: unknown[]) => {
+ Reflect.apply(value, target, args);
+ throw new Error('selection compositing failed');
+ };
+ }
+ return value;
+ },
+ });
+ Object.defineProperty(beforeCache.surface, 'ctx', { configurable: true, value: failingCtx });
+ h.engine.setTool('lasso');
+ h.overlay.fire('pointerdown', pointerAt(0, 0));
+ h.overlay.fire('pointermove', pointerAt(5, 0));
+ h.overlay.fire('pointermove', pointerAt(5, 5));
+ h.overlay.fire('pointermove', pointerAt(0, 5));
+ h.overlay.fire('pointerup', pointerAt(0, 0, { buttons: 0 }));
+
+ expect(() => h.engine.fillSelection()).toThrow('selection compositing failed');
+
+ expect(h.engine.getDocument()).toEqual(beforeDocument);
+ expect(h.engine.stores.canUndo.get()).toBe(false);
+ expect(h.bitmapStore.markLayerDirty).not.toHaveBeenCalled();
+ expect(
+ (beforeCache.surface as StubRasterSurface).callLog.filter((entry) => entry.op === 'putImageData').at(-1)?.args[0]
+ ).toBe(capturedBefore);
+
+ Object.defineProperty(beforeCache.surface, 'ctx', { configurable: true, value: originalCtx });
+ h.engine.fillSelection();
+ expect(h.engine.stores.canUndo.get()).toBe(true);
+ h.engine.dispose();
+ });
+
+ it('rolls back a materialized control selection edit when masked compositing fails', async () => {
+ const h = createControlSelectionHarness({
+ source: { image: { height: 10, imageName: 'control-image', width: 10 }, type: 'image' },
+ transform: { rotation: 0, scaleX: 2, scaleY: 2, x: 5, y: 6 },
+ });
+ await h.publishInitialCache();
+ const beforeDocument = structuredClone(h.engine.getDocument());
+ const beforeCache = await snapshotLayerCache(h.engine, 'control');
+ const createSurface = h.backend.createSurface.bind(h.backend);
+ vi.spyOn(h.backend, 'createSurface').mockImplementation((width, height) => {
+ const surface = createSurface(width, height);
+ const originalCtx = surface.ctx;
+ const failingCtx = new Proxy(originalCtx, {
+ get(target, property, receiver) {
+ const value = Reflect.get(target, property, receiver);
+ if (property !== 'drawImage' || typeof value !== 'function') {
+ return value;
+ }
+ return (...args: unknown[]) => {
+ const result = Reflect.apply(value, target, args);
+ if (target.globalCompositeOperation === 'destination-out') {
+ throw new Error('selection compositing failed');
+ }
+ return result;
+ };
+ },
+ });
+ Object.defineProperty(surface, 'ctx', { configurable: true, value: failingCtx });
+ return surface;
+ });
+ h.engine.selectAll();
+
+ expect(() => h.engine.eraseSelection()).toThrow('selection compositing failed');
+
+ expect(h.engine.getDocument()).toEqual(beforeDocument);
+ expect(h.engine.stores.canUndo.get()).toBe(false);
+ expect(h.bitmapStore.markLayerDirty).not.toHaveBeenCalled();
+ expect(h.bitmapStore.releaseSuspendedLayer).toHaveBeenCalledOnce();
+ const restored = await h.engine.exportLayerPixels('control', { includeDisabled: true });
+ expect(restored.status).toBe('ok');
+ if (restored.status === 'ok') {
+ expect(restored.surface).toBe(beforeCache.surface);
+ expect(restored.rect).toEqual(beforeCache.rect);
+ expect(restored.guard.cacheVersion).toBe(beforeCache.version);
+ }
+
+ vi.mocked(h.backend.createSurface).mockRestore();
+ h.engine.eraseSelection();
+ expect(h.engine.stores.canUndo.get()).toBe(true);
+ h.engine.dispose();
+ });
+
+ it('preserves transaction-owned rollback when a materialized control selection commit fails', async () => {
+ const h = createControlSelectionHarness({
+ source: { image: { height: 10, imageName: 'control-image', width: 10 }, type: 'image' },
+ transform: { rotation: 0, scaleX: 2, scaleY: 2, x: 5, y: 6 },
+ });
+ await h.publishInitialCache();
+ const beforeDocument = structuredClone(h.engine.getDocument());
+ const beforeCache = await snapshotLayerCache(h.engine, 'control');
+ h.engine.selectAll();
+ historyPreparationFaults.layerSnapshot = true;
+
+ expect(() => h.engine.fillSelection()).toThrow('layer snapshot preparation failed');
+
+ expect(h.engine.getDocument()).toEqual(beforeDocument);
+ expect(h.engine.stores.canUndo.get()).toBe(false);
+ expect(h.bitmapStore.markLayerDirty).not.toHaveBeenCalled();
+ expect(h.bitmapStore.releaseSuspendedLayer).toHaveBeenCalledOnce();
+ const restored = await h.engine.exportLayerPixels('control', { includeDisabled: true });
+ expect(restored.status).toBe('ok');
+ if (restored.status === 'ok') {
+ expect(restored.surface).toBe(beforeCache.surface);
+ expect(restored.rect).toEqual(beforeCache.rect);
+ expect(restored.guard.cacheVersion).toBe(beforeCache.version);
+ }
+ h.engine.dispose();
+ });
+
it('fillSelection on the selected paint layer records one undoable edit + persists', () => {
const { bitmapStore, engine } = makeEngine(paintDoc());
engine.selectAll();
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index 6fdf88fdf4..4a1b5a2d9e 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -316,6 +316,10 @@ interface RasterizationJob {
export type LayerThumbnailRequestResult = 'ready' | 'stale' | 'error' | 'missing' | 'unsupported';
+type SelectionPixelTarget =
+ | { kind: 'raster'; layerId: string; transparencyLocked: boolean }
+ | { kind: 'control'; transaction: ControlPixelEditTransaction; transparencyLocked: false };
+
/** Structural equality for JSON-safe canvas contracts (including synthetic mask paint sources). */
const isDeeplyEqual = (left: unknown, right: unknown): boolean => {
if (Object.is(left, right)) {
@@ -6475,19 +6479,25 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
}
};
- /** Resolves the selected paint layer eligible for a masked fill/erase, or `null`. */
- const selectionPaintTarget = (): { layerId: string; transparencyLocked: boolean } | null => {
+ /** Resolves the selected pixel-edit target for a masked fill/erase, or `null`. */
+ const selectionPixelTarget = (): SelectionPixelTarget | null => {
const doc = mirror.getDocument();
if (!doc || !doc.selectedLayerId) {
return null;
}
const layer = doc.layers.find((candidate) => candidate.id === doc.selectedLayerId);
- // Paint layers only (image-source layers are a no-op this phase — rasterize
- // comes with the next task); locked/hidden targets are refused.
- if (!layer || layer.type !== 'raster' || layer.source.type !== 'paint' || layer.isLocked || !layer.isEnabled) {
- return null;
+ if (layer?.type === 'raster' && layer.source.type === 'paint' && !layer.isLocked && layer.isEnabled) {
+ return {
+ kind: 'raster',
+ layerId: layer.id,
+ transparencyLocked: layer.isTransparencyLocked === true,
+ };
+ }
+ if (layer?.type === 'control') {
+ const transaction = beginControlPixelEdit(layer.id);
+ return transaction ? { kind: 'control', transaction, transparencyLocked: false } : null;
}
- return { layerId: layer.id, transparencyLocked: layer.isTransparencyLocked === true };
+ return null;
};
/**
@@ -6514,77 +6524,187 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
if (!doc || !placedMask || !bounds) {
return;
}
- const target = selectionPaintTarget();
+ const selRect = roundOut(bounds);
+ const selectedLayer = doc.layers.find((candidate) => candidate.id === doc.selectedLayerId);
+ if (
+ kind === 'erase' &&
+ selectedLayer?.type === 'control' &&
+ !intersect(selRect, roundOut(getSourceBounds(selectedLayer, doc)))
+ ) {
+ return;
+ }
+ const target = selectionPixelTarget();
if (!target) {
return;
}
+ const cancelControlEdit = (): void => {
+ if (target.kind === 'control') {
+ target.transaction.cancel();
+ }
+ };
// Transparency lock (mirrors the brush/eraser tool policy, paintTool.ts): an
// ERASE is refused outright (it would delete locked alpha), and a FILL is
// constrained to existing pixels via `source-atop` — colour lands only on
// already-opaque areas, never into transparent space.
if (kind === 'erase' && target.transparencyLocked) {
+ cancelControlEdit();
return;
}
- const selRect = roundOut(bounds);
- let rect: Rect | null;
- let entry: ReturnType<LayerCacheStore['getOrCreateRect']>;
- if (kind === 'fill' && !target.transparencyLocked) {
- // Grow the cache to the selection bounds so a fill in empty space appears.
- rect = selRect;
- entry = layerCache.growToRect(target.layerId, selRect);
- } else {
- // Erase, OR a transparency-locked fill: both only affect EXISTING pixels, so
- // clamp to the current content extent (never grow into empty space).
- const existing = layerCache.get(target.layerId);
- if (!existing || isEmpty(existing.rect)) {
+ const layerId = target.kind === 'control' ? target.transaction.layerId : target.layerId;
+ let before: ImageData | null = null;
+ let editOrigin: { x: number; y: number } | null = null;
+ let editRect: Rect | null = null;
+ let editSurface: RasterSurface | null = null;
+ let controlCommitStarted = false;
+ let controlGrowthSnapshot:
+ | {
+ hasPublishedPixels: boolean;
+ lastUsed: number;
+ pixels: ImageData | null;
+ rect: Rect;
+ stale: boolean;
+ surface: RasterSurface;
+ version: number;
+ }
+ | null
+ | undefined;
+ try {
+ if (target.kind === 'control' && kind === 'fill') {
+ const existing = layerCache.get(layerId);
+ const needsGrowth =
+ !existing ||
+ isEmpty(existing.rect) ||
+ selRect.x < existing.rect.x ||
+ selRect.y < existing.rect.y ||
+ selRect.x + selRect.width > existing.rect.x + existing.rect.width ||
+ selRect.y + selRect.height > existing.rect.y + existing.rect.height;
+ if (needsGrowth) {
+ controlGrowthSnapshot = existing
+ ? {
+ hasPublishedPixels: existing.hasPublishedPixels,
+ lastUsed: existing.lastUsed,
+ pixels: isEmpty(existing.rect)
+ ? null
+ : existing.surface.ctx.getImageData(0, 0, existing.rect.width, existing.rect.height),
+ rect: { ...existing.rect },
+ stale: existing.stale,
+ surface: existing.surface,
+ version: existing.version,
+ }
+ : null;
+ }
+ }
+
+ let rect: Rect | null;
+ let entry: ReturnType<LayerCacheStore['getOrCreateRect']>;
+ if (kind === 'fill' && !target.transparencyLocked) {
+ // Grow the cache to the selection bounds so a fill in empty space appears.
+ rect = selRect;
+ entry = layerCache.growToRect(layerId, selRect);
+ } else {
+ // Erase, OR a transparency-locked fill: both only affect EXISTING pixels, so
+ // clamp to the current content extent (never grow into empty space).
+ const existing = layerCache.get(layerId);
+ if (!existing || isEmpty(existing.rect)) {
+ cancelControlEdit();
+ return;
+ }
+ rect = intersect(selRect, existing.rect);
+ entry = existing;
+ }
+ if (!rect || isEmpty(rect)) {
+ cancelControlEdit();
return;
}
- rect = intersect(selRect, existing.rect);
- entry = existing;
- }
- if (!rect || isEmpty(rect)) {
- return;
- }
- endNudgeBurst();
- const surface = entry.surface;
- const origin = { x: entry.rect.x, y: entry.rect.y };
- const before = surface.ctx.getImageData(rect.x - origin.x, rect.y - origin.y, rect.width, rect.height);
- if (kind === 'fill') {
- fillMaskedRegion({
- backend,
- color: stores.brushOptions.get().color,
- // Transparency lock: colour only on existing pixels (never fill holes).
- composite: target.transparencyLocked ? 'source-atop' : 'source-over',
- mask: placedMask.surface,
- maskOrigin: placedMask.rect,
- rect,
- target: surface,
- targetOrigin: origin,
- });
- } else {
- eraseMaskedRegion({
- backend,
- mask: placedMask.surface,
- maskOrigin: placedMask.rect,
- rect,
- target: surface,
- targetOrigin: origin,
- });
- }
- const after = surface.ctx.getImageData(rect.x - origin.x, rect.y - origin.y, rect.width, rect.height);
- notifyLayerPainted(target.layerId);
- bitmapStore.markLayerDirty(target.layerId);
- if (!history.isApplying()) {
- history.push(
- createImagePatchEntry({
- after,
- apply: applyImagePatch,
- before,
- label: kind === 'fill' ? 'Fill selection' : 'Erase selection',
- layerId: target.layerId,
+ endNudgeBurst();
+ const surface = entry.surface;
+ const origin = { x: entry.rect.x, y: entry.rect.y };
+ before = surface.ctx.getImageData(rect.x - origin.x, rect.y - origin.y, rect.width, rect.height);
+ editOrigin = origin;
+ editRect = rect;
+ editSurface = surface;
+ if (kind === 'fill') {
+ fillMaskedRegion({
+ backend,
+ color: stores.brushOptions.get().color,
+ // Transparency lock: colour only on existing pixels (never fill holes).
+ composite: target.transparencyLocked ? 'source-atop' : 'source-over',
+ mask: placedMask.surface,
+ maskOrigin: placedMask.rect,
rect,
- })
- );
+ target: surface,
+ targetOrigin: origin,
+ });
+ } else {
+ eraseMaskedRegion({
+ backend,
+ mask: placedMask.surface,
+ maskOrigin: placedMask.rect,
+ rect,
+ target: surface,
+ targetOrigin: origin,
+ });
+ }
+ const after = surface.ctx.getImageData(rect.x - origin.x, rect.y - origin.y, rect.width, rect.height);
+ const label = kind === 'fill' ? 'Fill selection' : 'Erase selection';
+ if (target.kind === 'control') {
+ controlCommitStarted = true;
+ target.transaction.commitPatch(label, { after, before, rect });
+ } else {
+ notifyLayerPainted(target.layerId);
+ bitmapStore.markLayerDirty(target.layerId);
+ if (!history.isApplying()) {
+ history.push(
+ createImagePatchEntry({
+ after,
+ apply: applyImagePatch,
+ before,
+ label,
+ layerId: target.layerId,
+ rect,
+ })
+ );
+ }
+ }
+ } catch (error) {
+ if (target.kind !== 'control') {
+ throw error;
+ }
+ if (controlCommitStarted) {
+ // The transaction owns commit-time rollback and closes itself before
+ // rethrowing; restoring its preview here would overwrite that rollback.
+ throw error;
+ }
+ try {
+ if (controlGrowthSnapshot !== undefined) {
+ if (controlGrowthSnapshot === null) {
+ layerCache.delete(layerId);
+ } else {
+ const current = layerCache.get(layerId);
+ if (current) {
+ controlGrowthSnapshot.surface.resize(controlGrowthSnapshot.rect.width, controlGrowthSnapshot.rect.height);
+ if (controlGrowthSnapshot.pixels) {
+ controlGrowthSnapshot.surface.ctx.putImageData(controlGrowthSnapshot.pixels, 0, 0);
+ }
+ current.hasPublishedPixels = controlGrowthSnapshot.hasPublishedPixels;
+ current.lastUsed = controlGrowthSnapshot.lastUsed;
+ current.rect = { ...controlGrowthSnapshot.rect };
+ current.stale = controlGrowthSnapshot.stale;
+ current.surface = controlGrowthSnapshot.surface;
+ current.version = controlGrowthSnapshot.version;
+ }
+ }
+ adjustedSurfaceCache.delete(layerId);
+ scheduler.invalidate({ layers: [layerId] });
+ } else if (before && editOrigin && editRect && editSurface) {
+ editSurface.ctx.putImageData(before, editRect.x - editOrigin.x, editRect.y - editOrigin.y);
+ adjustedSurfaceCache.delete(layerId);
+ scheduler.invalidate({ layers: [layerId] });
+ }
+ } finally {
+ target.transaction.cancel();
+ }
+ throw error;
}
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/LassoOptions.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/LassoOptions.test.tsx
new file mode 100644
index 0000000000..317a367f01
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/LassoOptions.test.tsx
@@ -0,0 +1,92 @@
+import type { CanvasEngine } from '@workbench/canvas-engine/engine';
+import type { CanvasLayerContract, Project } from '@workbench/types';
+import type { ReactNode } from 'react';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { system } from '@theme/system';
+import { createControlLayer, createEmptyPaintLayer } from '@workbench/widgets/layers/layerOps';
+import { createDraftProject } from '@workbench/workbenchState';
+import { renderToStaticMarkup } from 'react-dom/server';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { LassoOptions } from './LassoOptions';
+
+interface CapturedButton {
+ children?: ReactNode;
+ disabled?: boolean;
+}
+
+const { activeProject, buttons } = vi.hoisted(() => ({
+ activeProject: { current: null as Project | null },
+ buttons: new Map<string, CapturedButton>(),
+}));
+
+vi.mock('@workbench/components/ui', () => ({
+ Button: (props: CapturedButton) => {
+ buttons.set(String(props.children), props);
+ return <button disabled={props.disabled}>{props.children}</button>;
+ },
+}));
+vi.mock('@workbench/widgets/canvas/engineStoreHooks', () => ({
+ useCanvasHasSelection: () => true,
+ useLassoOptions: () => ({ mode: 'replace' }),
+}));
+vi.mock('@workbench/WorkbenchContext', () => ({
+ useActiveProjectSelector: (selector: (project: Project) => unknown) => selector(activeProject.current!),
+}));
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+const engine = {
+ deselect: vi.fn(),
+ eraseSelection: vi.fn(),
+ fillSelection: vi.fn(),
+ invertSelection: vi.fn(),
+ stores: { lassoOptions: { set: vi.fn() } },
+} as unknown as CanvasEngine;
+
+const renderLassoOptions = (layer: CanvasLayerContract): Map<string, CapturedButton> => {
+ const project = createDraftProject([]);
+ project.canvas.document = {
+ background: 'transparent',
+ bbox: { height: 100, width: 100, x: 0, y: 0 },
+ height: 100,
+ layers: [layer],
+ selectedLayerId: layer.id,
+ version: 2,
+ width: 100,
+ };
+ activeProject.current = project;
+ renderToStaticMarkup(
+ <ChakraProvider value={system}>
+ <LassoOptions engine={engine} />
+ </ChakraProvider>
+ );
+ return new Map(buttons);
+};
+
+beforeEach(() => {
+ buttons.clear();
+});
+
+describe('LassoOptions pixel target eligibility', () => {
+ const rasterPaint = createEmptyPaintLayer('Raster', 'raster');
+ const controlPaint = createControlLayer('Control', 'control');
+ const rasterImage: CanvasLayerContract = {
+ ...createEmptyPaintLayer('Raster image', 'raster-image'),
+ source: { image: { height: 10, imageName: 'raster-image', width: 10 }, type: 'image' },
+ };
+
+ it.each([
+ { disabled: false, layer: rasterPaint, scenario: 'raster paint' },
+ { disabled: false, layer: controlPaint, scenario: 'control paint' },
+ { disabled: true, layer: { ...controlPaint, isLocked: true }, scenario: 'locked control' },
+ { disabled: true, layer: { ...controlPaint, isEnabled: false }, scenario: 'disabled control' },
+ { disabled: true, layer: rasterImage, scenario: 'raster image' },
+ ])('sets Fill and Erase disabled=$disabled for $scenario', ({ disabled, layer }) => {
+ const rendered = renderLassoOptions(layer);
+ expect(rendered.get('widgets.canvas.toolOptions.fillSelection')?.disabled).toBe(disabled);
+ expect(rendered.get('widgets.canvas.toolOptions.eraseSelection')?.disabled).toBe(disabled);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/LassoOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/LassoOptions.tsx
index 4a26e5cbd7..1ad84802ac 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/LassoOptions.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/LassoOptions.tsx
@@ -2,6 +2,7 @@ import type { CanvasEngine } from '@workbench/canvas-engine/engine';
import type { SelectionOp } from '@workbench/canvas-engine/types';
import { HStack, Text } from '@chakra-ui/react';
+import { isLayerPixelEditEligible } from '@workbench/canvas-engine/editing/controlPixelEdit';
import { Button } from '@workbench/components/ui';
import { useCanvasHasSelection, useLassoOptions } from '@workbench/widgets/canvas/engineStoreHooks';
import { useActiveProjectSelector } from '@workbench/WorkbenchContext';
@@ -50,7 +51,7 @@ export const LassoOptions = ({ engine }: ToolOptionsComponentProps) => {
const layer = document.selectedLayerId
? document.layers.find((entry) => entry.id === document.selectedLayerId)
: undefined;
- return !!layer && layer.type === 'raster' && layer.source.type === 'paint' && !layer.isLocked && layer.isEnabled;
+ return isLayerPixelEditEligible(layer);
});
const onFill = useCallback(() => engine.fillSelection(), [engine]);