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.

fix(canvas): report unreadable layers and merge masks at full coverage

Josh Corbett993c4e8d5df9
diff --git a/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx b/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx
index 7d1c470f14..055c6fc7a0 100644
--- a/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx
+++ b/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx
@@ -36,7 +36,7 @@ The tool strip on the left edge of the canvas holds the drawing and editing tool
The Shape and Select buttons hold several tools. Click to use the current one, or press and hold (or right-click, or press **→** on) the button to choose another from a menu that lists each tool with its shortcut. To pick a color from the canvas, hold **Alt** with any painting tool and click. While you pick, a round **loupe** follows the pointer: it magnifies the pixels around it, boxes the pixel that will be picked in the center, and shows that pixel's RGB values. The pointer itself is hidden, so aim with the boxed pixel. You can drag to sample as you go; the color is set when you release, and **Escape** cancels the pick and restores the previous color. The picked color goes to what you are editing:
* the selected mask's tint, while **Mask tint** is chosen in the [Color](/users-guide/canvas/layers-panel/#color) tab;
-* the selected shape layer's fill when the foreground chip is active, or its stroke when the background chip is active;
+* the selected shape layer's fill when the foreground chip is active, or its stroke when the background chip is active. A pick never turns on a fill or stroke the shape doesn't have; it sets the active color instead;
* the selected text layer's color;
* otherwise the active foreground or background color.
@@ -67,7 +67,7 @@ In InvokeAI 6, the Lasso drew directly into an inpaint mask, and created one if
## Navigating the canvas
-* **Zoom** with the mouse wheel, which zooms around the pointer, or choose a level from the zoom menu in the header (25% to 500%). **Ctrl+1**, **Ctrl+2**, **Ctrl+3** and **Ctrl+4** zoom to 100%, 200%, 400% and 800% around the center of the view. Many browsers use these keys to switch tabs and do not pass them to the page; there, use the zoom menu instead.
+* **Zoom** with the mouse wheel, which zooms around the pointer, or choose a level from the zoom menu in the header (25% to 500%). **Ctrl+1**, **Ctrl+2**, **Ctrl+3** and **Ctrl+4** zoom to 100%, 200%, 400% and 800% around the center of the view. Many browsers use these keys to switch tabs and do not pass them to the page; there, choose **Zoom to 100%**, **Zoom to 200%**, **Zoom to 400%** or **Zoom to 800%** from the command palette (**Ctrl+K**), or assign other keys in **Settings → Hotkeys**.
* **Pan** with the View tool, by holding **Space**, or by dragging with the middle mouse button.
* **Fit to view** (header) fits the generation frame and all layers into the window.
@@ -76,8 +76,8 @@ In InvokeAI 6, the Lasso drew directly into an inpaint mask, and created one if
The buttons along the top of the canvas, from left to right:
* **Zoom level** and **Fit to view**.
-* **Fit frame to layers** (**Shift+N**) — resizes the generation frame to enclose all layers.
-* **Fit frame to masks** (**Shift+B**) — resizes the generation frame to enclose the inpaint masks, with a margin of the **Mask blur** (in the Generate panel's **Compositing** section) plus 8 pixels, so the blurred edge of the mask stays inside the frame. With the default blur of 16, the margin is 24 pixels.
+* **Fit frame to layers** (**Shift+N**) — resizes the generation frame to the area all layers cover. With **Snap to grid** on, the frame then shrinks inward to the model's grid, so it can trim up to one grid step less one pixel from each edge of the layers.
+* **Fit frame to masks** (**Shift+B**) — resizes the generation frame to enclose the inpaint masks, with a margin of the **Mask blur** (in the Generate panel's **Compositing** section) plus 8 pixels, so the blurred edge of the mask stays inside the frame. With the default blur of 16, the margin is 24 pixels. With **Snap to grid** on, the frame then grows outward to the model's grid, so the margin can be wider but never narrower.
* **Undo canvas edit** (**Ctrl+Z**) and **Redo canvas edit** (**Ctrl+Shift+Z** or **Ctrl+Y**).
* **Save Canvas to Gallery** — saves the visible canvas as an image on the board new results go to: the auto-add board, or the selected board when none is set (see [Choosing where new media goes](/users-guide/gallery/introduction/#choosing-where-new-media-goes)). Its arrow offers **Save Frame to Gallery**, which saves only what is inside the generation frame. A message names the board the image went to; its **Show in Gallery** button selects the image in the Gallery and keeps the Canvas in the center.
* **Clear canvas** (**Ctrl+Alt+N**, **Cmd+Option+N** on macOS) — after you confirm, clears all layers and starts a fresh canvas with an empty inpaint mask. This cannot be undone.
@@ -115,7 +115,7 @@ Choose **Transform** from a layer's menu, or press **Shift+T**, to scale and rot
Press **Enter** or click **Apply** to finish, or **Escape** or **Cancel** to undo the transform. The **Transform** tab of the Layers panel sets the position, scale and rotation numerically. A negative scale flips the layer.
-To crop a layer to the generation frame, choose **Crop layer to frame** from its menu. **Fit to frame** scales a layer to fit inside the frame. To crop every layer at once, use **Crop all layers to frame** in the [canvas menu](#the-canvas-menu).
+To crop a layer to the generation frame, choose **Crop layer to frame** from its menu; a layer entirely outside the frame is left alone. **Fit to frame** scales a layer to fit inside the frame. To crop every layer at once, use **Crop all layers to frame** in the [canvas menu](#the-canvas-menu).
## Filters and object selection
@@ -168,7 +168,7 @@ Right-click the canvas to open the menu of the selected layer, the same menu as
* **Save to Gallery** — **Save Canvas to Gallery** or **Save Frame to Gallery**.
* **Create From Frame** — copy what is inside the generation frame into a **New Global Reference Image**, **New Regional Reference Image**, **New Control Layer** or **New Raster Layer**.
-* **Crop all layers to frame** — crops every raster layer, control layer, inpaint mask and regional guidance layer to the generation frame, including hidden and disabled layers and layers inside groups, as one undoable step. Groups, layer order and visibility are unchanged. A layer entirely outside the frame is emptied rather than deleted. Locked layers, and layers in a locked group, are skipped. A notice says how many layers were cropped, counting only the ones that changed, and how many locked layers were skipped.
+* **Crop all layers to frame** — crops every raster layer, control layer, inpaint mask and regional guidance layer to the generation frame, including hidden and disabled layers and layers inside groups, as one undoable step. Groups, layer order and visibility are unchanged. A layer entirely outside the frame is emptied rather than deleted. Locked layers, and layers in a locked group, are skipped, and so are layers whose image could not be read, for example because it was deleted from the Gallery; the other layers are still cropped. A brush stroke still being saved is saved first. A notice says how many layers were cropped, counting only the ones that changed, and how many locked or unreadable layers were left as they were. When every layer is locked, or there are no layers, the item is unavailable; highlighting it shows why.
With no layer selected, the menu has only the Canvas section.
diff --git a/docs/src/content/docs/Users Guide/07.Canvas/03.layers-panel.mdx b/docs/src/content/docs/Users Guide/07.Canvas/03.layers-panel.mdx
index 486343a9a0..8710b8171c 100644
--- a/docs/src/content/docs/Users Guide/07.Canvas/03.layers-panel.mdx
+++ b/docs/src/content/docs/Users Guide/07.Canvas/03.layers-panel.mdx
@@ -30,7 +30,7 @@ The **Color** tab edits the two painting colors: the **Foreground color**, which
* **Pick a color from the canvas** — the eyedropper. You can also hold **Alt** on the canvas. A magnifying loupe shows the pixel under the pointer and its RGB values; see the [Canvas guide](/users-guide/canvas/canvas-guide/#tools).
* When an inpaint mask or regional guidance layer is selected, a third chip, **Mask tint**, edits the color of its overlay.
-Picking with **Alt** on the canvas writes to what you are editing: the mask tint while **Mask tint** is chosen, the selected shape layer's fill (foreground chip) or stroke (background chip), the selected text layer's color, and otherwise the active foreground or background color. A pick that changes a layer is one undoable step. The eyedropper button sets the mask tint while **Mask tint** is chosen, and otherwise the active foreground or background color.
+Picking with **Alt** on the canvas writes to what you are editing: the mask tint while **Mask tint** is chosen, the selected shape layer's fill (foreground chip) or stroke (background chip), the selected text layer's color, and otherwise the active foreground or background color. A pick never turns on a fill or stroke the shape does not have: on such a shape it sets the active foreground or background color instead. A pick that changes a layer is one undoable step. The eyedropper button sets the mask tint while **Mask tint** is chosen, and otherwise the active foreground or background color.
The canvas's tool keys, such as **B** for the Brush, and **[**, **]**, **X** and **D**, also work while the Layers panel or the Color tab has focus, except while you type in a field.
@@ -85,7 +85,8 @@ The icons at the top **Arrange** the layer (move it to the front, forward, backw
* **Rename layer** and **Fit to frame** (scale the layer to fit inside the generation frame).
* **Merge down** — combines the layer with the one below. Each layer's adjustments are baked into the merged pixels; undo restores both layers with their adjustments.
* **Copy to** — including **Copy layer to clipboard**, and copies to other layer types.
- * **Crop layer to frame** and **Save layer to board** (save it to the Gallery as an upload, in Uncategorized or a board you pick from its submenu).
+ * **Crop layer to frame** — keeps only the part of the layer inside the generation frame. It refuses, saying why, a layer that is locked or inside a locked group, a layer that lies entirely outside the frame (cropping would leave it empty), and a layer whose image could not be read, for example because it was deleted from the Gallery.
+ * **Save layer to board** — saves the layer to the Gallery as an upload, in Uncategorized or a board you pick from its submenu.
* **Disable layer**, **Lock layer**, **Bookmark for quick switch** and **Color label**. A bookmarked layer is where **Q** switches on the canvas; press **Q** again to return. The bookmark is temporary and is not saved in the project. It can reset when the canvas is released, for example after switching away from its project, and resets on reload.
* **Remove from group** — for a layer inside a group: moves it out, directly above the group. With several layers selected, it appears when they are all in the same group, and moves them together in their current order. The emptied group stays.
* **Delete layer**.
@@ -100,7 +101,7 @@ The icons at the top **Arrange** the layer (move it to the front, forward, backw
* **Inpaint masks:** **Add noise**, **Add denoise limit**, **Extract masked area** (copy the masked part of the image to a new layer), and **Hide layer**.
* **Regional guidance:** **Enable auto-negative**, **Add reference image**, and **Hide layer**.
-When several layers are selected, the menu also offers **Merge selected layers**. When only inpaint masks are selected, it offers **Merge masks** instead: the masks are combined into one new inpaint mask, named after the topmost one with "merged" added, which takes the topmost mask's fill color and style, noise and denoise limit. The new mask is placed where the topmost one was, even when the masks are in different groups, and replaces them. Merge masks needs two or more enabled, unlocked inpaint masks with content. One undo brings the original masks back.
+When several layers are selected, the menu also offers **Merge selected layers**. When only inpaint masks are selected, it offers **Merge masks** instead: the masks are combined into one new inpaint mask, named after the topmost one with "merged" added. It covers everywhere any of the masks did, at full strength whatever each mask's opacity, and takes the topmost mask's fill color and style. The new mask is placed where the topmost one was, even when the masks are in different groups, and replaces them. Merge masks needs two or more enabled, unlocked inpaint masks with content, whose noise and denoise limit settings match, since the new mask applies one setting to all of its area. When the item is unavailable, highlighting it shows why. One undo brings the original masks back.
## Properties
diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.json
index 80cc316b19..5a75048e86 100644
--- a/invokeai/frontend/webv2/performance/browser-baseline.json
+++ b/invokeai/frontend/webv2/performance/browser-baseline.json
@@ -1380,6 +1380,7 @@
"source:src/workbench/canvas-engine/color.ts",
"source:src/workbench/canvas-engine/contracts.ts",
"source:src/workbench/canvas-engine/controllers/booleanMergeController.ts",
+ "source:src/workbench/canvas-engine/controllers/colorSampleController.ts",
"source:src/workbench/canvas-engine/controllers/controlPixelController.ts",
"source:src/workbench/canvas-engine/controllers/copyLayerController.ts",
"source:src/workbench/canvas-engine/controllers/cropLayerController.ts",
@@ -1398,6 +1399,7 @@
"source:src/workbench/canvas-engine/controllers/mergeLayerController.ts",
"source:src/workbench/canvas-engine/controllers/mutationContext.ts",
"source:src/workbench/canvas-engine/controllers/newRasterLayerController.ts",
+ "source:src/workbench/canvas-engine/controllers/paintLineEndController.ts",
"source:src/workbench/canvas-engine/controllers/persistenceController.ts",
"source:src/workbench/canvas-engine/controllers/previewStateController.ts",
"source:src/workbench/canvas-engine/controllers/psdExportController.ts",
@@ -2493,6 +2495,7 @@
"source:src/workbench/canvas-engine/color.ts",
"source:src/workbench/canvas-engine/contracts.ts",
"source:src/workbench/canvas-engine/controllers/booleanMergeController.ts",
+ "source:src/workbench/canvas-engine/controllers/colorSampleController.ts",
"source:src/workbench/canvas-engine/controllers/controlPixelController.ts",
"source:src/workbench/canvas-engine/controllers/copyLayerController.ts",
"source:src/workbench/canvas-engine/controllers/cropLayerController.ts",
@@ -2511,6 +2514,7 @@
"source:src/workbench/canvas-engine/controllers/mergeLayerController.ts",
"source:src/workbench/canvas-engine/controllers/mutationContext.ts",
"source:src/workbench/canvas-engine/controllers/newRasterLayerController.ts",
+ "source:src/workbench/canvas-engine/controllers/paintLineEndController.ts",
"source:src/workbench/canvas-engine/controllers/persistenceController.ts",
"source:src/workbench/canvas-engine/controllers/previewStateController.ts",
"source:src/workbench/canvas-engine/controllers/psdExportController.ts",
@@ -2937,6 +2941,7 @@
"source:src/workbench/widgets/canvas/canvasImageDnd.ts",
"source:src/workbench/widgets/canvas/canvasInteractionLock.ts",
"source:src/workbench/widgets/canvas/canvasSettings.ts",
+ "source:src/workbench/widgets/canvas/canvasToolCommands.ts",
"source:src/workbench/widgets/canvas/checkerColors.ts",
"source:src/workbench/widgets/canvas/color-system/CanvasColorFeed.tsx",
"source:src/workbench/widgets/canvas/color-system/colorPair.ts",
@@ -3832,6 +3837,7 @@
"source:src/workbench/canvas-engine/color.ts",
"source:src/workbench/canvas-engine/contracts.ts",
"source:src/workbench/canvas-engine/controllers/booleanMergeController.ts",
+ "source:src/workbench/canvas-engine/controllers/colorSampleController.ts",
"source:src/workbench/canvas-engine/controllers/controlPixelController.ts",
"source:src/workbench/canvas-engine/controllers/copyLayerController.ts",
"source:src/workbench/canvas-engine/controllers/cropLayerController.ts",
@@ -3850,6 +3856,7 @@
"source:src/workbench/canvas-engine/controllers/mergeLayerController.ts",
"source:src/workbench/canvas-engine/controllers/mutationContext.ts",
"source:src/workbench/canvas-engine/controllers/newRasterLayerController.ts",
+ "source:src/workbench/canvas-engine/controllers/paintLineEndController.ts",
"source:src/workbench/canvas-engine/controllers/persistenceController.ts",
"source:src/workbench/canvas-engine/controllers/previewStateController.ts",
"source:src/workbench/canvas-engine/controllers/psdExportController.ts",
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 27a7f8dbe9..8de12bc2e3 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -3425,13 +3425,18 @@
"createError": "Couldn't create from the frame",
"createFromBbox": "Create From Frame",
"createdFromBbox": "Added {{destination}} from the frame",
+ "cropAllAllLocked": "Every layer is locked. Unlock a layer to crop it.",
"cropAllLayersToBbox": "Crop all layers to frame",
+ "cropAllNoLayers": "There are no layers to crop.",
+ "cropAllNoneCropped": "No layer was cropped",
"cropAllNothing": "Every layer already fits the frame",
"cropAllNothingUnlocked": "Every unlocked layer already fits the frame",
+ "cropAllUnreadable_one": "{{count}} layer could not be read and was left as it is.",
+ "cropAllUnreadable_other": "{{count}} layers could not be read and were left as they are.",
"croppedAllLayers_one": "Cropped {{count}} layer to the frame",
"croppedAllLayers_other": "Cropped {{count}} layers to the frame",
- "croppedAllLayersSkipped_one": "{{count}} locked layer skipped",
- "croppedAllLayersSkipped_other": "{{count}} locked layers skipped",
+ "croppedAllLayersSkipped_one": "{{count}} locked layer skipped.",
+ "croppedAllLayersSkipped_other": "{{count}} locked layers skipped.",
"empty": "This region has no visible raster content.",
"newControlLayer": "New Control Layer",
"newGlobalReferenceImage": "New Global Reference Image",
@@ -3446,7 +3451,8 @@
"saveError": "Couldn't save to gallery",
"saveToGallery": "Save to Gallery",
"saved": "Saved to gallery",
- "stale": "The canvas changed while saving. Try again."
+ "stale": "The canvas changed while saving. Try again.",
+ "unreadable": "A layer's image could not be read (it may have been deleted or damaged). Disable or delete that layer, then try again."
},
"controls": {
"clearCanvas": "Clear canvas",
@@ -3890,6 +3896,7 @@
"cropBusy": "Finish the current canvas action before cropping this layer.",
"cropFailed": "The layer could not be cropped.",
"cropLayerToBbox": "Crop layer to frame",
+ "cropOutsideFrame": "This layer lies entirely outside the frame, so cropping it would leave it empty. Nothing was changed.",
"cropUnsupported": "This layer cannot be cropped.",
"cropped": "Layer cropped to frame.",
"cutaway": "Cutaway with layer below",
@@ -3949,6 +3956,7 @@
"toggleVisibility": "Enable/disable",
"transform": "Transform",
"unsupported": "This action is not supported for this layer.",
+ "unreadable": "A layer's image could not be read (it may have been deleted or damaged), so nothing was changed.",
"unlock": "Unlock layer",
"unlockSelected": "Unlock selected",
"group": "Group layers",
@@ -3975,9 +3983,13 @@
"addNoise": "Add noise",
"addRegenerateRegion": "Add regenerate region",
"addRegenerateRegionDescription": "Regenerate where this layer has content, as a live inpaint mask.",
+ "canvasNotReady": "The canvas is still starting. Try again in a moment.",
+ "interactionLocked": "Unavailable while the canvas is generating, has staged results, or is applying an edit.",
"mergeMasks": "Merge masks",
"mergeMasksIneligible": "Merge masks needs two or more enabled, unlocked inpaint masks with content.",
+ "mergeMasksSettingsDiffer": "The masks have different noise or denoise settings. Match them to merge.",
"removeFromGroup": "Remove from group",
+ "removeFromGroupLocked": "Unlock the layer and the groups that contain it first.",
"transformIneligible": "Transform works on enabled raster and control layers with content."
},
"control": {
@@ -4159,6 +4171,7 @@
"sourceAdjustmentOverBudget": "Not enough canvas memory to apply this layer’s Clarity, Texture or Dehaze before filtering it. Delete layers you no longer need, then try again.",
"sourceAdjustmentTooLarge": "Clarity, Texture and Dehaze can’t run on this layer: its content is larger than 16.8 megapixels (4096 × 4096 px). Disable or remove them, or crop the layer, then try again.",
"sourceOverBudget": "Not enough memory is free to read this layer for the filter.",
+ "sourceUnreadable": "The layer's image could not be read, so it cannot be filtered.",
"statusCommitting": "Applying filter…",
"statusError": "Filter needs attention.",
"stale": "The layer changed while filtering. Preview it again.",
@@ -4183,6 +4196,7 @@
"errorQueue": "Select Object processing failed on the backend.",
"errorReconcile": "The completed Select Object result could not be retrieved.",
"errorUnknown": "Select Object could not finish.",
+ "errorUnreadable": "The layer's image could not be read.",
"errorUpload": "The layer source could not be uploaded for Select Object.",
"exclude": "Exclude",
"excludeCount": "Exclude {{count}}",
@@ -4243,6 +4257,7 @@
"noBindings": "The active workflow has no compatible image input and output.",
"notReady": "The active workflow is not ready with this layer input.",
"overBudget": "The workflow result is too large to apply undoably, so the layer was not changed.",
+ "unreadable": "The layer's image could not be read, so the workflow did not run.",
"output": "Workflow image output",
"replace": "Replace layer",
"replaceSuccess": "Replaced the layer with the workflow result.",
@@ -4347,6 +4362,7 @@
"exportNotReady": "Layers are still loading — try exporting again in a moment",
"exportOverBudget": "Not enough raster memory is available to export this PSD",
"exportStale": "The canvas changed during export — try again",
+ "exportUnreadable": "A layer's image could not be read, so nothing was exported. Delete or replace that layer, then export again",
"exportAborted": "PSD export was canceled",
"exportFailed": "PSD export failed",
"exportPsd": "Export to PSD",
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
index ce2d24114e..c742c9a9cb 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
@@ -69,13 +69,16 @@ Current extracted ownership includes:
- `HistoryController`: engine-owned history, guarded async replay with failure reporting, inactive byte trimming.
- `PersistenceController`: dirty-bitmap flush barriers and disposal.
- `EditingController`: selection state and exclusive edit-lease lifecycle.
+- `TransformEditingController` (under `EditingController`): transform sessions, previews, parameter commits and paint bakes, plus `layers.beginTransform` and the wait of a session requested before its layer's pixels persist. It alone decides when that wait opens a session or ends; `engine.ts` routes it document changes, tool switches, Escape, replays, document replacement and final upload failures.
+- `ColorSampleController`: one-shot color requests and the workbench color router, and which of them receives each pick.
+- `PaintLineEndController`: where the last brush or eraser stroke ended on each layer, followed through the layer's changes (see "Input ownership and frame scheduling").
- `InteractionController`: public tool commands and their disposal boundary.
- `LayerController`: guarded layer mutations and thumbnail capability ports.
-- `RasterExportController`: guarded layer rasterization, transformed copies, encoding, reservations, pin leases.
+- `RasterExportController`: guarded layer rasterization, transformed copies, encoding, reservations, pin leases. A rasterization that failed (an image that is gone or does not decode) reports `unreadable`, never `not-ready`: waiting cannot fix it, so every consumer (crop, merges, boolean merges, copies, conversion, extraction, duplicate, filter, Select Object, Run Workflow, snapshots for generation and PSD) refuses with that reason instead of asking the user to retry. The rasterizer remembers the failure per cache entry, keyed by cache version, document generation and source, and a retry of the same source that fails again raises no second error notice. Two questions read that record. `hasFailed` (a failure is recorded for the layer's current key) drives the readiness gates that never rasterize themselves (Merge Down, boolean merges, extraction): they answer `unreadable` for as long as it holds. `isBackingOff` (that failure's retry backoff, 3 s doubling per repeated failure up to 60 s, is still running) drives the compositor, which skips the layer meanwhile instead of reading its image every frame; the backoff's end invalidates the layer, so a displayed layer retries on its own. A layer nobody redraws (off screen, disabled) is retried by a readiness gate that finds the backoff over, in the background while it still answers `unreadable`. Explicit operations (crop, export, merges) always try again. A retry that fails again restarts the backoff without a second notice; a success or any change to the layer clears the failure.
- `PsdExportController`: immutable PSD planning, snapshot capture, reservation, execution, cancellation.
- `StagedResultController`: guarded staged-candidate acceptance and its history entry.
- `PixelEditController`, `SelectionImageController`, `LayerMutationController`: atomic pixel/document publication at their respective boundaries. Pixel editor materializes control layers and raster-image layers in place before destructive edits (brush and eraser alike), keeping conversion plus pixels in one undoable transaction.
-- `CropLayerController`: crops one layer, or every leaf of every stack, to the frame; crop-all is one entry. Locked leaves (own or ancestor lock) are skipped, and counted when their content reaches past the frame, so the result can say how many were skipped even when nothing was cropped; a leaf already inside the frame, empty or unsupported is left alone; a leaf wholly outside is emptied in place, so ids, order, groups and flags never change. It reads one leaf at a time through a read lease, copies the cropped pixels into a surface under their own raster reservation and releases the lease before the next leaf, so the peak is the cropped set plus one export; it refuses `stale` when the stacks, frame or any pixel guard moved meanwhile, admits one history entry for every before and after snapshot, and publishes one `replaceCanvasLayers` (same-id, same-type leaves, refused whole when any entry is invalid). `MergeLayerController` merges selected leaves into a new one through one pipeline parameterized by eligibility, result stack, result leaf and label: merge-selected flattens a contiguous raster run into a paint layer, merge-masks unions any inpaint masks' coverage (each at its opacity) into a mask configured like the topmost source.
+- `CropLayerController`: crops one layer, or every leaf of every stack, to the frame; crop-all is one entry. Both paths share one eligibility rule: a leaf locked by itself or an ancestor, or with a source the export cannot bake, is never cropped. A single crop refuses such a leaf, an `unreadable` one, and one wholly outside the frame (`outside-frame`: the explicit crop would empty it). Crop all first crosses the paint-upload barrier (`flushPendingPixels`, not waiting for held pixels), so an acknowledgement replacing a just-painted leaf cannot land mid-read and refuse it as `stale`. It skips locked and `unreadable` leaves and counts each when its contract's content reaches past the frame (`skippedLocked`, `skippedUnreadable`), so the result can say what was left alone even when nothing was cropped, and one leaf that cannot be read never blocks the rest; a leaf already inside the frame, empty or unsupported is left alone; a leaf wholly outside is emptied in place, so ids, order, groups and flags never change. It reads one leaf at a time through a read lease, copies the cropped pixels into a surface under their own raster reservation and releases the lease before the next leaf, so the peak is the cropped set plus one export; it refuses `stale` when the stacks, frame or any pixel guard moved meanwhile, admits one history entry for every before and after snapshot, and publishes one `replaceCanvasLayers` (same-id, same-type leaves, refused whole when any entry is invalid). `MergeLayerController` merges selected leaves into a new one through one pipeline parameterized by eligibility, result stack, result leaf and label: merge-selected flattens a contiguous raster run into a paint layer, merge-masks unions any inpaint masks' coverage (each at full alpha, since a mask's opacity only tints it on screen) into a mask configured like the topmost source.
- `MaskResultController`, `FilterResultController`, `GeneratedResultController`: guarded application-result adoption through narrow host ports.
Controller-local tests instantiate these boundaries with fakes. Integration tests in `engine.test.ts` cover composition, document routing, cross-controller invariants.
@@ -84,7 +87,7 @@ Controller-local tests instantiate these boundaries with fakes. Integration test
`CanvasDocumentCapability.captureSnapshot()` returns `CanvasDocumentSnapshot` or `null`. Snapshot holds structured clone of exact `CanvasStateContractV3` and engine's `documentGeneration`. Engine privately ties it to the reducer canvas identity it was captured from, so caller cannot manufacture a current snapshot by copying fields.
-`CanvasExportCapability.captureRasterSnapshot(snapshot, layerIds, options)` requests exactly the required layer caches, temporarily pins them, reserves detached-surface capacity, copies their pixels into independent surfaces. Returns typed `ok`, `stale`, `aborted`, `not-ready`, or `over-budget` result. Freshness checked before and after every async rasterization boundary and once after all copies are detached.
+`CanvasExportCapability.captureRasterSnapshot(snapshot, layerIds, options)` requests exactly the required layer caches, temporarily pins them, reserves detached-surface capacity, copies their pixels into independent surfaces. Returns typed `ok`, `stale`, `aborted`, `not-ready`, `unreadable`, or `over-budget` result. Freshness checked before and after every async rasterization boundary and once after all copies are detached.
`ok` result holds a `CanvasRasterSnapshot`: cloned canvas contract, its document generation, map of detached layer surfaces, idempotent `release()`. Snapshot is caller-owned. Its surfaces do not read live caches and stay valid while engine cools down; cooldown releases generation-scoped reservations but does not invalidate detached snapshots. Caller must release snapshot in `finally`. Engine disposal releases any snapshots still outstanding.
@@ -209,13 +212,13 @@ Each leaf bakes its own stack exactly (spatial entries included), layer-local, b
Controller keeps 30,000-pixel side cap and also derives a pixel-area limit from currently available reserved bytes. Accounts for flattened composite plus each transformed layer surface, budgets eight bytes per required pixel, reserves full execution allocation before creating PSD surfaces. Final freshness check happens before that reservation; once execution starts it uses only frozen pixels. Capture and execution reservations release in `finally`; cancellation aborts before next allocation or side effect.
-Capability returns `exported`, `nothing`, `too-large`, `not-ready`, `over-budget`, `stale`, `aborted`, or an `AdjustmentRefusal`. Layers widget awaits the promise and maps every non-success result to a user-visible notice.
+Capability returns `exported`, `nothing`, `too-large`, `not-ready`, `unreadable`, `over-budget`, `stale`, `aborted`, or an `AdjustmentRefusal`. Layers widget awaits the promise and maps every non-success result to a user-visible notice.
## Input ownership and frame scheduling
Pointer pipeline (`input/pointerPipeline.ts`) owns gesture capture and temporary holds (Space → view, Alt → picker, C → bbox). Keyboard ownership is explicit. Widget passes its focusable keyboard root and a `resolveKeyOwner` judge to `surface.attach`; the judge names the workbench region that owns a keydown (`surface`, a `companion` widget acting on this canvas's layers, or `elsewhere`) and is asked only on keydown, after the pipeline's own refusals, so the engine imports nothing from Workbench focus and pointer paths never pay for it. No key acts over an editable field, a control reached by keyboard (pipeline records on `focusin` whether focus arrived by pointer: Chromium marks focused element `:focus-visible` at any keydown, so arrival is the only reliable signal), an open dialog, menu or listbox, or beneath a modal. Past those refusals: Enter applies a session only from the `surface` with focus on its root or nowhere, never on a control; the Escape ladder and C act from the `surface` or a `companion`; Space and Alt stay pointer-led, acting over the hovered canvas whatever the owner and otherwise only from the `surface`. Without a judge (tests, detached engines) focus alone decides: the root or no focus is the surface, and a control the pointer last clicked counts as a companion. Owned Space keydown is prevented, so a clicked control does not activate. An owned Alt keydown is prevented, and so is the release of an Alt the pipeline claimed, because Firefox and Windows otherwise activate the menu bar; that holds for a tool that reads Alt as a gesture modifier too (Marquee, Lasso), which keeps the key and only gets no picker hold, since pointer events still carry `altKey`. Every other release is observed, never consumed. Alt from the surface while the pointer is elsewhere arms a pending hold that the next `pointerenter` with Alt still held, or a `pointerdown` with Alt, begins before the press is routed, so a pen landing without hover samples on contact; release, tool switch, blur, reset and detach clear it. Genuine tool switch first cancels the gesture through outgoing tool and ends any hold, restoring held tool, so the switch leaves the tool the user was really on and a later key release restores nothing.
-A pick previews each sampled color to the one-shot request or the workbench router (`setColorSampleRouter`), then commits the last preview once on release or cancels it once when the press ends any other way (Escape, a tool change, a cancelled pointer); a declined preview falls back to the brush color. The sink that took a pick's first preview gets its commit or cancel, so a request armed or settled mid-pick never sends the router a stray phase, nor the reverse. Brush and eraser share an engine-lifetime map of where the last committed stroke ended on each layer: a Shift press on a layer with a remembered end draws a straight segment from it as part of the one stroke, and the map survives tool switches but forgets on replay, document replacement and the layer's removal. `layers.beginTransform` selects a leaf, switches to transform and opens its session even when transform is already active, cancelling a session on another layer; it refuses a locked or ineligible leaf, a running gesture, a live float or locked edits without changing selection or tool. A leaf whose only content is a stroke persistence has not acknowledged yet (a new paint layer's first upload) has no persisted extent to frame, so the request waits in the `pendingTransformLayerId` interaction store and the session opens when the bitmap lands, while the leaf is still selected, transform is the tool the user is on (a Space, Alt or C hold over it counts) and no other session opened. The wait ends without a session on a genuine tool switch, a selection change, the leaf's removal, Escape, a document replacement, or an upload of that leaf failing with no retry to follow (retried failures keep the wait), which also reports a `not-ready` refusal through `tools.onEditRefused`.
+`ColorSampleController` routes picks. A pick previews each sampled color to the one-shot request or the workbench router (`setColorSampleRouter`), then commits the last preview once on release or cancels it once when the press ends any other way (Escape, a tool change, a cancelled pointer); a declined preview falls back to the brush color. The sink that took a pick's first preview gets its commit or cancel, so a request armed or settled mid-pick never sends the router a stray phase, nor the reverse. Brush and eraser share an engine-lifetime memory (`PaintLineEndController`) of where the last committed stroke ended on each layer, kept in that layer's local space: a Shift press on a layer with a remembered end draws a straight segment from it, placed through the layer's current transform, as part of the one stroke. The engine routes every layer change to it. A change of transform alone (move, nudge, Fit to frame, a transform parameter) carries the end with the layer; a change that rewrites content and transform together (crop, conversion, a baked float or result) keeps its document position and re-expresses it in the new local space; an applied Transform on a paint layer, which redraws only the pixels, rebases it from the session's transform. It survives tool switches but forgets on replay, document replacement, the layer's removal and a transform it cannot invert. `layers.beginTransform` (`TransformEditingController.request`) selects a leaf, switches to transform and opens its session even when transform is already active, cancelling a session on another layer; it refuses a locked or ineligible leaf, a running gesture, a live float or locked edits without changing selection or tool. A leaf whose only content is a stroke persistence has not acknowledged yet (a new paint layer's first upload) has no persisted extent to frame, so the request waits in the `pendingTransformLayerId` interaction store and the session opens when the bitmap lands, while the leaf is still selected, transform is the tool the user is on (a Space, Alt or C hold over it counts) and no other session opened. The wait ends without a session on a genuine tool switch, a selection change, the leaf's removal, Escape, a history replay, a document replacement, disposal, or an upload of that leaf failing with no retry to follow (retried failures keep the wait), which also reports a `not-ready` refusal through `tools.onEditRefused`.
`RenderScheduler.beforeNextFrame(task)` runs tasks once before next frame takes its flags, so their invalidations join that frame. Tools reach it through required `ToolContext.scheduleFrame`; detached engine runs the task immediately because it produces no frames. Brush strokes append samples and decimate them incrementally per event, render accumulated stroke at most once per presented frame, render synchronously on commit.
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/applicationHost.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/applicationHost.ts
index 72fecad528..918f7a619f 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/applicationHost.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/applicationHost.ts
@@ -48,7 +48,7 @@ export interface CanvasApplicationHost {
options?: ExportLayerPixelsOptions
): Promise<
| { status: 'ok'; surface: RasterSurface; rect: Rect; guard: LayerExportGuard; release(): void }
- | { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'over-budget' }
+ | { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'unreadable' | 'over-budget' }
| AdjustmentRefusal
>;
getCompositeExecutorDeps(): CanvasCompositeExecutorDeps;
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
index af4af734cd..c2bcebb9ea 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
@@ -270,6 +270,7 @@ export type PsdExportResult =
| 'nothing'
| 'too-large'
| 'over-budget'
+ | 'unreadable'
| SubsetOf<CanvasTransactionOutcome, 'not-ready' | 'stale' | 'aborted'>;
export interface CanvasPsdExportCapability {
@@ -377,7 +378,8 @@ export type ExportBakedLayerBlobResult =
| SubsetOf<CanvasTransactionOutcome, 'not-ready' | 'aborted'>
| 'disabled'
| 'empty'
- | 'over-budget';
+ | 'over-budget'
+ | 'unreadable';
}
| AdjustmentRefusal;
@@ -550,7 +552,13 @@ export interface FilterPreviewInput {
export type DuplicateLayersResult =
| { readonly status: 'duplicated'; readonly duplicateIds: readonly string[]; readonly selectedLayerId: string }
- | { readonly status: SubsetOf<CanvasTransactionOutcome, 'busy' | 'not-ready' | 'stale'> | 'nothing' | 'over-budget' };
+ | {
+ readonly status:
+ | SubsetOf<CanvasTransactionOutcome, 'busy' | 'not-ready' | 'stale'>
+ | 'nothing'
+ | 'over-budget'
+ | 'unreadable';
+ };
/**
* Layer pixel operations report a distinct outcome: refused before anything changed (`busy`, `not-ready`,
* `over-budget` when the edit could never be undone), nothing to do, or `failed` when the document refused it.
@@ -637,8 +645,6 @@ export interface CanvasEngineLayerCapability extends CanvasLayerCapability {
*/
beginTransform(layerId: string): BeginTransformResult;
booleanMergeRasterLayers(upperLayerId: string, operation: BooleanRasterOperation): Promise<BooleanRasterResult>;
- /** Whether `mergeInpaintMasks` would accept these ids; pure, for menu enablement. */
- canMergeInpaintMasks(layerIds: readonly string[]): boolean;
cancelTextEdit(): void;
cancelTransform(): void;
clearMask(layerId: string): MaskEditResult;
@@ -797,6 +803,8 @@ export {
areSelectedRasterLayersContiguous,
canMergeSelectedRasters,
canMergeVisibleRasters,
+ inpaintMaskMergeEligibility,
+ type InpaintMaskMergeEligibility,
} from './document/mergeVisible';
export { documentToExportLocalSamPoint } from './samCoordinates';
export { bboxEquals, constrainBboxToRatio, roundBbox } from './tools/bboxHitTest';
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/booleanMergeController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/booleanMergeController.ts
index 85bddcbf1c..f670115f66 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/booleanMergeController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/booleanMergeController.ts
@@ -16,7 +16,9 @@ import {
layerOperationStatus,
paintLayerAt,
publishAddedRasterLayer,
+ readinessOfAll,
rgbaBytes,
+ type LayerCacheReadiness,
type LayerStepContext,
type LayerEditRefusal,
} from './editSteps';
@@ -27,13 +29,14 @@ export type BooleanRasterResult =
| 'missing'
| 'unsupported'
| 'empty'
+ | 'unreadable'
| 'failed'
| LayerEditRefusal
| AdjustmentRefusal;
type ExportResult =
| { status: 'ok'; surface: RasterSurface; rect: Rect; guard: LayerExportGuard; release(): void }
- | { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'over-budget' }
+ | { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'unreadable' | 'over-budget' }
| AdjustmentRefusal;
export interface BooleanMergeControllerOptions {
@@ -49,7 +52,7 @@ export interface BooleanMergeControllerOptions {
| 'isPermitCurrent'
>;
readonly backend: RasterBackend;
- readonly isCacheReady: (layer: CanvasLayerContract, document: CanvasDocumentContractV3) => boolean;
+ readonly cacheReadiness: (layer: CanvasLayerContract, document: CanvasDocumentContractV3) => LayerCacheReadiness;
readonly exportBaked: (layerId: string) => Promise<ExportResult>;
readonly isGuardCurrent: (guard: LayerExportGuard) => boolean;
}
@@ -86,8 +89,12 @@ export class BooleanMergeController {
}
const upper = getDocumentLayer(document, eligibility.upperId)!;
const below = getDocumentLayer(document, eligibility.lowerId)!;
- if (!this.deps.isCacheReady(upper, document) || !this.deps.isCacheReady(below, document)) {
- return 'not-ready';
+ const readiness = readinessOfAll([
+ this.deps.cacheReadiness(upper, document),
+ this.deps.cacheReadiness(below, document),
+ ]);
+ if (readiness !== 'ready') {
+ return readiness;
}
const owned: Extract<ExportResult, { status: 'ok' }>[] = [];
const acquire = async (layerId: string): Promise<ExportResult> => {
@@ -116,6 +123,9 @@ export class BooleanMergeController {
if (upperPixels.status === 'over-budget' || belowPixels.status === 'over-budget') {
return 'over-budget';
}
+ if (upperPixels.status === 'unreadable' || belowPixels.status === 'unreadable') {
+ return 'unreadable';
+ }
if (upperPixels.status === 'not-ready' || belowPixels.status === 'not-ready') {
return 'not-ready';
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/colorSampleController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/colorSampleController.test.ts
new file mode 100644
index 0000000000..4ebf5a6ab7
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/colorSampleController.test.ts
@@ -0,0 +1,163 @@
+import type { ColorSamplePhase } from '@workbench/canvas-engine/capabilities';
+import type { ToolId } from '@workbench/canvas-engine/types';
+
+import { describe, expect, it } from 'vitest';
+
+import { ColorSampleController } from './colorSampleController';
+
+/** The controller over a recorded tool; `heldPick` is a press the held tool ends when a request arrives. */
+const createHarness = (initialTool: ToolId = 'brush') => {
+ const tool = { current: initialTool };
+ const routed: [string, ColorSamplePhase][] = [];
+ const heldPick = { active: false };
+ const controller: ColorSampleController = new ColorSampleController({
+ // Ending a held picker cancels its pick, as the pointer pipeline does.
+ endHeldTool: () => {
+ if (heldPick.active) {
+ heldPick.active = false;
+ controller.route('#000000', 'cancel');
+ }
+ },
+ getActiveToolId: () => tool.current,
+ setTool: (toolId) => {
+ tool.current = toolId;
+ },
+ });
+ controller.setRouter((hex, phase) => {
+ routed.push([hex, phase]);
+ return true;
+ });
+ const request = () => {
+ const result: { hex?: string | null } = {};
+ void controller.requestSample().then((hex) => {
+ result.hex = hex;
+ });
+ return result;
+ };
+ return { controller, heldPick, request, routed, tool };
+};
+
+const settled = () => Promise.resolve();
+
+describe('ColorSampleController', () => {
+ it('arms the picker and settles a request on the release commit, returning to the previous tool', async () => {
+ const h = createHarness('brush');
+ const result = h.request();
+ expect(h.tool.current).toBe('colorPicker');
+
+ expect(h.controller.route('#111111', 'preview')).toBe(true);
+ expect(h.controller.route('#222222', 'preview')).toBe(true);
+ await settled();
+ expect(result.hex).toBeUndefined();
+
+ expect(h.controller.route('#222222', 'commit')).toBe(true);
+ await settled();
+ expect(result.hex).toBe('#222222');
+ expect(h.tool.current).toBe('brush');
+ expect(h.routed).toEqual([]);
+ });
+
+ it('keeps a request armed through a cancelled pick and settles it from the next one', async () => {
+ const h = createHarness();
+ const result = h.request();
+ h.controller.route('#111111', 'preview');
+ h.controller.route('#111111', 'cancel');
+ await settled();
+ expect(result.hex).toBeUndefined();
+
+ h.controller.route('#333333', 'preview');
+ h.controller.route('#333333', 'commit');
+ await settled();
+ expect(result.hex).toBe('#333333');
+ });
+
+ it('sends a pick’s commit or cancel only to the sink that took its first preview', async () => {
+ const h = createHarness('colorPicker');
+ // A standing pick is under way when a request arrives: ending the held picker cancels the router's pick, once.
+ h.controller.route('#111111', 'preview');
+ h.heldPick.active = true;
+ const first = h.request();
+ expect(h.routed).toEqual([
+ ['#111111', 'preview'],
+ ['#000000', 'cancel'],
+ ]);
+ h.controller.route('#444444', 'preview');
+ h.controller.route('#444444', 'commit');
+ await settled();
+ expect(first.hex).toBe('#444444');
+
+ // A request settled by Escape mid-pick keeps that pick's cancel away from the router.
+ const second = h.request();
+ h.controller.route('#555555', 'preview');
+ expect(h.controller.onEscape()).toBe(true);
+ expect(h.controller.route('#555555', 'cancel')).toBe(true);
+ await settled();
+ expect(second.hex).toBeNull();
+ expect(h.routed).toHaveLength(2);
+
+ // The other way round: a pick the router took keeps its commit when a request arms mid-pick.
+ h.controller.route('#666666', 'preview');
+ const third = h.request();
+ h.controller.route('#666666', 'commit');
+ await settled();
+ expect(third.hex).toBeUndefined();
+ expect(h.routed.at(-1)).toEqual(['#666666', 'commit']);
+ });
+
+ it('declines a pick with no request and no router, so the picker falls back to the brush color', () => {
+ const h = createHarness();
+ const remove = h.controller.setRouter(() => true);
+ remove();
+ // The harness router was replaced, so removing the newer one leaves none.
+ expect(h.controller.route('#111111', 'preview')).toBe(false);
+ });
+
+ it('removes a router only while it is still the installed one', () => {
+ const h = createHarness();
+ const routedByLater: ColorSamplePhase[] = [];
+ const removeEarlier = h.controller.setRouter(() => true);
+ h.controller.setRouter((_hex, phase) => {
+ routedByLater.push(phase);
+ return true;
+ });
+ removeEarlier();
+
+ expect(h.controller.route('#111111', 'preview')).toBe(true);
+ expect(routedByLater).toEqual(['preview']);
+ });
+
+ it('settles with null, keeping the requested tool, on a switch off the picker; a newer request supersedes', async () => {
+ const h = createHarness('brush');
+ const first = h.request();
+ const second = h.request();
+ await settled();
+ expect(first.hex).toBeNull();
+
+ h.controller.onToolChange('colorPicker');
+ await settled();
+ expect(second.hex).toBeUndefined();
+ h.controller.onToolChange('move');
+ await settled();
+ expect(second.hex).toBeNull();
+ // The switch the caller requested wins; the controller restores nothing.
+ expect(h.tool.current).toBe('colorPicker');
+ });
+
+ it('leaves Escape to the next handler when nothing is armed', () => {
+ expect(createHarness().controller.onEscape()).toBe(false);
+ });
+
+ it('settles an armed request on dispose, idempotently, and answers later requests with null', async () => {
+ const h = createHarness();
+ const armed = h.request();
+ h.controller.dispose();
+ h.controller.dispose();
+ await settled();
+ expect(armed.hex).toBeNull();
+
+ const late = h.request();
+ await settled();
+ expect(late.hex).toBeNull();
+ expect(h.controller.route('#111111', 'preview')).toBe(false);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/colorSampleController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/colorSampleController.ts
new file mode 100644
index 0000000000..b54290a8b5
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/colorSampleController.ts
@@ -0,0 +1,109 @@
+import type { ColorSamplePhase } from '@workbench/canvas-engine/capabilities';
+import type { ToolId } from '@workbench/canvas-engine/types';
+
+export interface ColorSampleControllerOptions {
+ /** The tool the user is on; a settled request returns to it. */
+ readonly getActiveToolId: () => ToolId;
+ /** Switches tools directly; the controller settles its own request around the switch. */
+ readonly setTool: (toolId: ToolId) => void;
+ /** Ends a held temporary tool, so a request records the tool the user was really on. */
+ readonly endHeldTool: () => void;
+}
+
+type ColorSampleRouter = (hex: string, phase: ColorSamplePhase) => boolean;
+
+/**
+ * Routes eyedropper picks. A one-shot request takes a pick's previews and settles on its release commit, after
+ * structural edits are allowed; Escape, a tool change and disposal settle it with null. Unclaimed picks go to the
+ * workbench router while one is installed. A pick belongs to the sink that took its first preview: its commit or
+ * cancel goes there alone, so a request armed or settled mid-pick never strays into the router, nor the reverse.
+ */
+export class ColorSampleController {
+ private request: { previousToolId: ToolId; resolve: (hex: string | null) => void } | null = null;
+ private router: ColorSampleRouter | null = null;
+ // Which sink took the current pick's first preview; null between picks.
+ private pickSink: 'request' | 'router' | null = null;
+ private disposed = false;
+
+ constructor(private readonly deps: ColorSampleControllerOptions) {}
+
+ /** Arms the color picker and resolves the picked hex on release, or null when cancelled. */
+ requestSample(): Promise<string | null> {
+ // A second request supersedes the first; the earlier caller gets a cancel.
+ this.settle(null, false);
+ if (this.disposed) {
+ return Promise.resolve(null);
+ }
+ this.deps.endHeldTool();
+ return new Promise<string | null>((resolve) => {
+ this.request = { previousToolId: this.deps.getActiveToolId(), resolve };
+ this.deps.setTool('colorPicker');
+ });
+ }
+
+ /** Takes one sample of a pick; returns whether a sink consumed it, else the picker falls back to the brush. */
+ route(hex: string, phase: ColorSamplePhase): boolean {
+ if (phase === 'preview') {
+ this.pickSink ??= this.request ? 'request' : 'router';
+ }
+ const sink = this.pickSink;
+ if (phase !== 'preview') {
+ this.pickSink = null;
+ }
+ if (sink === 'request') {
+ if (phase === 'commit') {
+ this.settle(hex, true);
+ }
+ return true;
+ }
+ return sink === 'router' ? (this.router?.(hex, phase) ?? false) : false;
+ }
+
+ /** Installs the workbench router; the returned cleanup removes it only while it is still the installed one. */
+ setRouter(router: ColorSampleRouter): () => void {
+ this.router = router;
+ return () => {
+ if (this.router === router) {
+ this.router = null;
+ }
+ };
+ }
+
+ /** Any move off the eyedropper abandons the sample the caller is awaiting; the requested switch wins. */
+ onToolChange(toolId: ToolId): void {
+ if (toolId !== 'colorPicker') {
+ this.settle(null, false);
+ }
+ }
+
+ /** An armed request is the most recent thing the user opted into, so Escape takes it back first. */
+ onEscape(): boolean {
+ if (!this.request) {
+ return false;
+ }
+ this.settle(null, true);
+ return true;
+ }
+
+ private settle(hex: string | null, restoreTool: boolean): void {
+ const request = this.request;
+ if (!request) {
+ return;
+ }
+ this.request = null;
+ request.resolve(hex);
+ if (restoreTool) {
+ this.deps.setTool(request.previousToolId);
+ }
+ }
+
+ dispose(): void {
+ if (this.disposed) {
+ return;
+ }
+ this.disposed = true;
+ this.settle(null, false);
+ this.router = null;
+ this.pickSink = null;
+ }
+}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/copyLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/copyLayerController.ts
index db1dcd484a..5049b01ce2 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/copyLayerController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/copyLayerController.ts
@@ -25,7 +25,7 @@ import {
type ExportResult =
| { status: 'ok'; surface: RasterSurface; rect: Rect; guard: LayerExportGuard; release(): void }
- | { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'over-budget' }
+ | { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'unreadable' | 'over-budget' }
| AdjustmentRefusal;
/** The stack a baked copy lands in: a raster paint layer, or a control layer with a default adapter. */
@@ -33,7 +33,14 @@ export type CopyLayerTarget = 'raster' | 'control';
export type CopyLayerResult =
| { status: 'copied'; layerId: string }
- | { status: LayerEditRefusal | SubsetOf<CanvasCommandRefusal, 'missing' | 'unsupported'> | 'empty' | 'failed' }
+ | {
+ status:
+ | LayerEditRefusal
+ | SubsetOf<CanvasCommandRefusal, 'missing' | 'unsupported'>
+ | 'empty'
+ | 'unreadable'
+ | 'failed';
+ }
| AdjustmentRefusal;
export interface CopyLayerControllerOptions {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.test.ts
index ffb07eaaac..82a8da9b2c 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.test.ts
@@ -2,6 +2,7 @@ import type {
CanvasAdjustmentsContract,
CanvasDocumentContractV3,
CanvasLayerContract,
+ CanvasNodeContract,
} from '@workbench/canvas-engine/contracts';
import type { AdjustmentRefusal } from '@workbench/canvas-engine/render/exactAdjustments';
import type { Rect } from '@workbench/canvas-engine/types';
@@ -33,19 +34,23 @@ const layer: CanvasLayerContract = {
const CACHE_RECT: Rect = { height: 50, width: 50, x: -10, y: -10 };
const BBOX: Rect = { height: 20, width: 20, x: 0, y: 0 };
-const createHarness = (historyBytes?: number) => {
+const createHarness = (
+ historyBytes?: number,
+ options: { readonly nodes?: CanvasNodeContract[]; readonly unreadable?: boolean } = {}
+) => {
const document: CanvasDocumentContractV3 = {
background: 'transparent',
bbox: BBOX,
height: 100,
selectedLayerId: 'paint',
- stacks: stacksFrom([layer]),
+ stacks: stacksFrom(options.nodes ?? [layer]),
version: 3,
width: 100,
};
const h = createLayerOperationHarness(document, { historyBytes });
h.layers.getOrCreateRect('paint', CACHE_RECT);
const discardPersisted = vi.fn();
+ const exported: string[] = [];
const controller = new CropLayerController({
backend: h.backend,
captureCache: (target) => {
@@ -57,6 +62,10 @@ const createHarness = (historyBytes?: number) => {
ctx: h.ctx,
discardPersisted,
exportBaked: (layerId) => {
+ exported.push(layerId);
+ if (options.unreadable) {
+ return Promise.resolve({ status: 'unreadable' as const });
+ }
const entry = h.layers.get(layerId)!;
const current = getDocumentLayer(h.document(), layerId)!;
return Promise.resolve({
@@ -67,10 +76,11 @@ const createHarness = (historyBytes?: number) => {
surface: entry.surface,
});
},
+ flushPendingPixels: () => Promise.resolve(),
isGuardCurrent: () => true,
isSupportedSource: () => true,
});
- return { ...h, controller, discardPersisted, original: getDocumentLayer(h.document(), 'paint')! };
+ return { ...h, controller, discardPersisted, exported, original: getDocumentLayer(h.document(), 'paint')! };
};
describe('CropLayerController', () => {
@@ -100,6 +110,31 @@ describe('CropLayerController', () => {
expect(h.layers.get('paint')?.rect).toEqual(CACHE_RECT);
});
+ it('refuses a layer under a locked group, as crop all skips it, without reading it', async () => {
+ const h = createHarness(undefined, { nodes: [groupContract('G', [layer], { isLocked: true })] });
+
+ await expect(h.controller.crop('paint')).resolves.toEqual({ status: 'locked' });
+ expect(h.exported).toEqual([]);
+ expect(h.dispatched).toEqual([]);
+ });
+
+ it('says a layer that could not be read is unreadable, not still loading', async () => {
+ const h = createHarness(undefined, { unreadable: true });
+
+ await expect(h.controller.crop('paint')).resolves.toEqual({ status: 'unreadable' });
+ expect(h.dispatched).toEqual([]);
+ expect(h.history.canUndo()).toBe(false);
+ });
+
+ it('refuses to empty a layer that lies wholly outside the frame', async () => {
+ const h = createHarness();
+ h.layers.delete('paint');
+ h.layers.getOrCreateRect('paint', { height: 10, width: 10, x: 60, y: 60 });
+
+ await expect(h.controller.crop('paint')).resolves.toEqual({ status: 'outside-frame' });
+ expect(h.dispatched).toEqual([]);
+ });
+
it('leaves the step on the undo stack when its replay is refused', async () => {
const h = createHarness();
await h.controller.crop('paint');
@@ -148,6 +183,10 @@ const createCropAllHarness = (
onExport?: (layerId: string) => void;
/** Refuses the owner's bake; its raw export still succeeds. */
refusal?: AdjustmentRefusal;
+ /** Leaves added on top whose pixels cannot be read. */
+ unreadable?: readonly CanvasLayerContract[];
+ /** Settles pending paint uploads; resolves at once by default. */
+ flushPendingPixels?: () => Promise<void>;
} = {}
) => {
const raster = (id: string) =>
@@ -162,6 +201,7 @@ const createCropAllHarness = (
height: 100,
selectedLayerId: 'raster',
stacks: stacksFrom([
+ ...(options.unreadable ?? []),
raster('inside'),
raster('raster'),
lockedPaint('locked'),
@@ -202,6 +242,9 @@ const createCropAllHarness = (
const read = exportOptions?.applyAdjustments === false ? `${layerId}:raw` : layerId;
exported.push(read);
options.onExport?.(layerId);
+ if (options.unreadable?.some((leaf) => leaf.id === layerId)) {
+ return Promise.resolve({ status: 'unreadable' as const });
+ }
if (options.refusal?.ownerId === layerId && read === layerId) {
return Promise.resolve(options.refusal);
}
@@ -219,6 +262,7 @@ const createCropAllHarness = (
surface: entry.surface,
});
},
+ flushPendingPixels: options.flushPendingPixels ?? (() => Promise.resolve()),
isGuardCurrent: () => guard.current,
isSupportedSource: () => true,
});
@@ -257,7 +301,12 @@ describe('CropLayerController: crop all layers', () => {
};
const h = createCropAllHarness({ adjusted: ['inside'], refusal });
- await expect(h.controller.cropAll()).resolves.toEqual({ cropped: 4, skippedLocked: 2, status: 'cropped' });
+ await expect(h.controller.cropAll()).resolves.toEqual({
+ cropped: 4,
+ skippedLocked: 2,
+ skippedUnreadable: 0,
+ status: 'cropped',
+ });
expect(h.exported).toEqual(['mask', 'region', 'control', 'inside:raw', 'raster']);
expect(getDocumentLayer(h.document(), 'inside')).toBe(getDocumentLayer(h.original, 'inside'));
expect(h.layers.get('raster')?.rect).toEqual(FRAME);
@@ -267,7 +316,12 @@ describe('CropLayerController: crop all layers', () => {
it('bakes an adjusted leaf it must crop, after releasing its raw read', async () => {
const h = createCropAllHarness({ adjusted: ['raster'] });
- await expect(h.controller.cropAll()).resolves.toEqual({ cropped: 4, skippedLocked: 2, status: 'cropped' });
+ await expect(h.controller.cropAll()).resolves.toEqual({
+ cropped: 4,
+ skippedLocked: 2,
+ skippedUnreadable: 0,
+ status: 'cropped',
+ });
expect(h.exported).toEqual(['mask', 'region', 'control', 'inside', 'raster:raw', 'raster']);
// The raw read is released before the bake reserves, so the peak stays one export.
const croppedRegion = bytes({ height: 10, width: 5, x: 0, y: 0 });
@@ -281,7 +335,12 @@ describe('CropLayerController: crop all layers', () => {
it('crops every unlocked leaf that reaches past the frame in one entry, and replays it as one', async () => {
const h = createCropAllHarness();
- await expect(h.controller.cropAll()).resolves.toEqual({ cropped: 4, skippedLocked: 2, status: 'cropped' });
+ await expect(h.controller.cropAll()).resolves.toEqual({
+ cropped: 4,
+ skippedLocked: 2,
+ skippedUnreadable: 0,
+ status: 'cropped',
+ });
// Hidden, disabled and grouped leaves crop too; locked ones are never read, and only those reaching past the
// frame count as skipped.
@@ -338,6 +397,44 @@ describe('CropLayerController: crop all layers', () => {
expect(h.layers.get('raster')?.rect).toEqual(FRAME);
});
+ it('skips leaves whose pixels cannot be read and crops the rest, counting those that reach past the frame', async () => {
+ /** An image layer whose decode failed; its contract still says where its content lies. */
+ const unreadableImage = (id: string, x: number) =>
+ layerContract(id, 'raster', {
+ source: { image: { height: 10, imageName: `${id}.png`, width: 10 }, type: 'image' },
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x, y: 0 },
+ } as Partial<CanvasLayerContract>);
+ const h = createCropAllHarness({ unreadable: [unreadableImage('gone', 15), unreadableImage('goneInside', 5)] });
+
+ await expect(h.controller.cropAll()).resolves.toEqual({
+ cropped: 4,
+ skippedLocked: 2,
+ skippedUnreadable: 1,
+ status: 'cropped',
+ });
+ expect(h.exported).toEqual(['mask', 'region', 'control', 'gone', 'goneInside', 'inside', 'raster']);
+ expect(getDocumentLayer(h.document(), 'gone')).toBe(getDocumentLayer(h.original, 'gone'));
+ expect(getDocumentLayer(h.document(), 'raster')).not.toBe(getDocumentLayer(h.original, 'raster'));
+ expect(h.history.entries().past).toEqual(['Crop all layers to frame']);
+ });
+
+ it('settles pending paint uploads before it reads any leaf', async () => {
+ let settle!: () => void;
+ const h = createCropAllHarness({
+ flushPendingPixels: () =>
+ new Promise<void>((resolve) => {
+ settle = resolve;
+ }),
+ });
+
+ const crop = h.controller.cropAll();
+ await Promise.resolve();
+ expect(h.exported).toEqual([]);
+ settle();
+
+ await expect(crop).resolves.toMatchObject({ cropped: 4, status: 'cropped' });
+ });
+
it('reports nothing when every unlocked leaf already fits the frame', async () => {
const h = createCropAllHarness();
for (const id of ['raster', 'control', 'mask', 'region']) {
@@ -345,7 +442,11 @@ describe('CropLayerController: crop all layers', () => {
h.layers.getOrCreateRect(id, CACHE_RECTS.inside!);
}
- await expect(h.controller.cropAll()).resolves.toEqual({ skippedLocked: 2, status: 'nothing' });
+ await expect(h.controller.cropAll()).resolves.toEqual({
+ skippedLocked: 2,
+ skippedUnreadable: 0,
+ status: 'nothing',
+ });
expect(h.dispatched).toEqual([]);
expect(h.history.canUndo()).toBe(false);
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.ts
index fdb0ed2150..9540bd4a90 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.ts
@@ -4,11 +4,12 @@ import type {
CanvasLayerContract,
CanvasLayerSourceContract,
} from '@workbench/canvas-engine/contracts';
+import type { SemanticLeaf } from '@workbench/canvas-engine/document-model/semanticLeaf';
import type { AdjustmentRefusal } from '@workbench/canvas-engine/render/exactAdjustments';
import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';
import type { Rect } from '@workbench/canvas-engine/types';
-import { compileDocumentLeaves } from '@workbench/canvas-engine/document-model/documentModel';
+import { compileDocumentLeaves, lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';
import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';
import { getSourceContentRect, renderableSourceOf } from '@workbench/canvas-engine/document/sources';
import { collectHistoryMediaRefs, HISTORY_ENTRY_OVERHEAD_BYTES } from '@workbench/canvas-engine/history/history';
@@ -28,25 +29,31 @@ import {
type LayerPixels,
} from './editSteps';
+/**
+ * `locked`: the layer or a group above it is locked. `outside-frame`: the layer lies wholly outside the frame, so the
+ * crop would empty it (crop all does that; an explicit crop of one layer refuses). `unreadable`: its pixels could not
+ * be read (an image that is gone or does not decode).
+ */
export type CropLayerResult =
| { status: 'cropped' }
- | { status: 'missing' | 'locked' | 'unsupported' | 'empty' | LayerEditRefusal }
+ | { status: 'missing' | 'locked' | 'unsupported' | 'empty' | 'outside-frame' | 'unreadable' | LayerEditRefusal }
| { status: 'failed'; message: string }
| AdjustmentRefusal;
/**
- * `skippedLocked` counts locked leaves (own or ancestor lock) whose content reaches past the frame. `nothing` when
- * every unlocked leaf already fits; every refusal leaves document, pixels and history alone.
+ * `skippedLocked` counts locked leaves (own or ancestor lock) and `skippedUnreadable` leaves whose pixels could not be
+ * read, each only when its content reaches past the frame; both are left as they are. `nothing` when every other leaf
+ * already fits; every refusal leaves document, pixels and history alone.
*/
export type CropAllLayersResult =
- | { status: 'cropped'; cropped: number; skippedLocked: number }
- | { status: 'nothing'; skippedLocked: number }
+ | { status: 'cropped'; cropped: number; skippedLocked: number; skippedUnreadable: number }
+ | { status: 'nothing'; skippedLocked: number; skippedUnreadable: number }
| { status: 'stale' | 'failed' | LayerEditRefusal }
| AdjustmentRefusal;
type ExportResult =
| { status: 'ok'; surface: RasterSurface; rect: Rect; guard: LayerExportGuard; release(): void }
- | { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'over-budget' }
+ | { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'unreadable' | 'over-budget' }
| AdjustmentRefusal;
export interface CropLayerControllerOptions {
@@ -75,10 +82,30 @@ export interface CropLayerControllerOptions {
admit?: (rect: Rect) => boolean
) => LayerPixels | null | 'not-ready' | 'over-budget';
readonly discardPersisted: (layerId: string) => void;
+ /**
+ * Settles paint uploads already owed (the persistence barrier canvas invocation crosses), so an acknowledgement
+ * replacing a layer's contract cannot land while crop all reads every leaf and refuse it as `stale`.
+ */
+ readonly flushPendingPixels: () => Promise<void>;
}
const failedCrop: CropLayerResult = { message: 'The crop could not be applied.', status: 'failed' };
+/**
+ * Whether a crop may change `leaf`, asked by single crop and crop all alike: never when it or a group above it is
+ * locked, and only for a source the export can bake.
+ */
+const cropEligibility = (
+ leaf: SemanticLeaf,
+ isSupportedSource: (source: CanvasLayerSourceContract) => boolean
+): 'eligible' | 'locked' | 'unsupported' => {
+ if (leaf.effectiveLocked) {
+ return 'locked';
+ }
+ const source = renderableSourceOf(leaf.layer);
+ return source && isSupportedSource(source) ? 'eligible' : 'unsupported';
+};
+
/**
* The contract of `layer` cropped to `rect`: its baked pixels now sit at `rect` in a paint source (or mask bitmap) with
* an identity transform, so transform, raster adjustments and control filter no longer apply. The bitmap is
@@ -110,6 +137,13 @@ const cropPixels = (backend: RasterBackend, exported: RasterSurface, exportedRec
return cropped;
};
+/** What crop all makes of one leaf's export. */
+type CropExport =
+ | Extract<ExportResult, { status: 'ok' }>
+ | { status: 'skip' }
+ | { status: 'unreadable' }
+ | CropAllLayersResult;
+
/** One leaf's crop: its contract and pixels before and after. */
interface LayerCrop {
readonly before: CanvasLayerContract;
@@ -137,16 +171,13 @@ export class CropLayerController {
return { status: 'busy' };
}
const document = ctx.getDocument();
- const layer = getDocumentLayer(document, layerId);
- if (!document || !layer) {
+ const leaf = document ? lookupDocumentLeaf(document, layerId) : null;
+ if (!document || !leaf) {
return { status: 'missing' };
}
- if (layer.isLocked) {
- return { status: 'locked' };
- }
- const source = renderableSourceOf(layer);
- if (!source || !this.deps.isSupportedSource(source)) {
- return { status: 'unsupported' };
+ const eligibility = cropEligibility(leaf, this.deps.isSupportedSource);
+ if (eligibility !== 'eligible') {
+ return { status: eligibility };
}
try {
const exported = await this.deps.exportBaked(layerId);
@@ -161,23 +192,25 @@ export class CropLayerController {
return { status: 'busy' };
}
const liveDocument = ctx.getDocument();
- const liveLayer = getDocumentLayer(liveDocument, layerId);
- if (!liveDocument || !liveLayer) {
+ const liveLeaf = liveDocument ? lookupDocumentLeaf(liveDocument, layerId) : null;
+ if (!liveDocument || !liveLeaf) {
return { status: 'missing' };
}
- if (liveLayer.isLocked) {
+ const liveEligibility = cropEligibility(liveLeaf, this.deps.isSupportedSource);
+ if (liveEligibility === 'locked') {
return { status: 'locked' };
}
if (!this.deps.isGuardCurrent(exported.guard)) {
return { status: 'not-ready' };
}
- const liveSource = renderableSourceOf(liveLayer);
- if (!liveSource || !this.deps.isSupportedSource(liveSource)) {
+ if (liveEligibility === 'unsupported') {
return { status: 'unsupported' };
}
+ const liveLayer = liveLeaf.layer;
const overlap = intersect(exported.rect, roundOut(liveDocument.bbox));
+ // Crop all empties such a layer in place; asked for this one layer, emptying it is never what was meant.
if (!overlap || isEmpty(overlap)) {
- return { status: 'empty' };
+ return { status: 'outside-frame' };
}
const cropRect = roundOut(overlap);
const txn = ctx.begin({ historyBytes: rgbaBytes(cropRect) + HISTORY_ENTRY_OVERHEAD_BYTES });
@@ -233,9 +266,10 @@ export class CropLayerController {
/**
* Crops every leaf of every stack to the frame as one history entry. Locked leaves (their own lock or an ancestor's)
- * are skipped; leaves already inside the frame, empty ones and unsupported sources are left alone; a leaf entirely
- * outside the frame is emptied in place, so ids, order, groups and flags never change. Each leaf's export is
- * released as soon as its cropped pixels are copied, so the peak is the cropped set plus one export.
+ * and leaves whose pixels cannot be read are skipped; leaves already inside the frame, empty ones and unsupported
+ * sources are left alone; a leaf entirely outside the frame is emptied in place, so ids, order, groups and flags
+ * never change. Pending paint uploads settle first. Each leaf's export is released as soon as its cropped pixels
+ * are copied, so the peak is the cropped set plus one export.
*/
async cropAll(): Promise<CropAllLayersResult> {
const { ctx } = this.deps;
@@ -243,36 +277,51 @@ export class CropLayerController {
if (this.disposed || !permit) {
return { status: 'busy' };
}
+ try {
+ await this.deps.flushPendingPixels();
+ } catch {
+ // A layer whose upload failed or is held still crops from its live pixels; the guards below still fence it.
+ }
+ if (this.disposed || !ctx.isPermitCurrent(permit)) {
+ return { status: 'busy' };
+ }
const document = ctx.getDocument();
if (!document) {
- return { skippedLocked: 0, status: 'nothing' };
+ return { skippedLocked: 0, skippedUnreadable: 0, status: 'nothing' };
}
const frame = roundOut(document.bbox);
+ /** Whether cropping would change `leaf`, judged from its contract: content reaching past the frame. */
+ const reachesPastFrame = (leaf: SemanticLeaf): boolean => {
+ const content = getSourceContentRect(leaf.layer, document);
+ return !isEmpty(content) && cropRectFor(transformBounds(leaf.worldTransform, content), frame) !== null;
+ };
let skippedLocked = 0;
- const candidates: CanvasLayerContract[] = [];
+ let skippedUnreadable = 0;
+ const candidates: SemanticLeaf[] = [];
for (const leaf of compileDocumentLeaves(document)) {
- const source = renderableSourceOf(leaf.layer);
- if (!source || !this.deps.isSupportedSource(source)) {
- continue;
- }
- if (!leaf.effectiveLocked) {
- candidates.push(leaf.layer);
- continue;
- }
- // A locked leaf counts only when cropping would have changed it: content reaching past the frame.
- const content = getSourceContentRect(leaf.layer, document);
- if (!isEmpty(content) && cropRectFor(transformBounds(leaf.worldTransform, content), frame)) {
+ const eligibility = cropEligibility(leaf, this.deps.isSupportedSource);
+ if (eligibility === 'eligible') {
+ candidates.push(leaf);
+ } else if (eligibility === 'locked' && reachesPastFrame(leaf)) {
skippedLocked += 1;
}
}
const guards: LayerExportGuard[] = [];
const cropped: CroppedLeaf[] = [];
try {
- for (const layer of candidates) {
+ for (const leaf of candidates) {
+ const { layer } = leaf;
const exported = await this.exportForCrop(layer, frame);
if (exported.status === 'skip') {
continue;
}
+ if (exported.status === 'unreadable') {
+ // Waiting cannot make it readable; one such layer must not hold every other layer back.
+ if (reachesPastFrame(leaf)) {
+ skippedUnreadable += 1;
+ }
+ continue;
+ }
if (exported.status !== 'ok') {
return exported;
}
@@ -312,9 +361,9 @@ export class CropLayerController {
return { status: 'stale' };
}
if (cropped.length === 0) {
- return { skippedLocked, status: 'nothing' };
+ return { skippedLocked, skippedUnreadable, status: 'nothing' };
}
- return this.publishAll(liveDocument, cropped, skippedLocked);
+ return this.publishAll(liveDocument, cropped, { skippedLocked, skippedUnreadable });
} catch {
return { status: 'failed' };
} finally {
@@ -325,21 +374,19 @@ export class CropLayerController {
}
/**
- * A leaf's baked pixels for crop all, or `skip` when it has nothing to crop. A leaf with its own adjustment stack is
+ * A leaf's baked pixels for crop all, `skip` when it has nothing to crop, or `unreadable`. A leaf with its own adjustment stack is
* first exported raw: adjustments never move pixels, so the raw rect is the baked one, and a leaf already inside the
* frame never runs its stack (a spatial job that could refuse the whole crop). Its guard still joins the staleness
* check, as every read leaf's does.
*/
- private async exportForCrop(
- layer: CanvasLayerContract,
- frame: Rect
- ): Promise<Extract<ExportResult, { status: 'ok' }> | { status: 'skip' } | CropAllLayersResult> {
- const settle = (
- exported: ExportResult
- ): Extract<ExportResult, { status: 'ok' }> | { status: 'skip' } | CropAllLayersResult => {
+ private async exportForCrop(layer: CanvasLayerContract, frame: Rect): Promise<CropExport> {
+ const settle = (exported: ExportResult): CropExport => {
if (exported.status === 'ok' || exported.status === 'adjustment-refused') {
return exported;
}
+ if (exported.status === 'unreadable') {
+ return { status: 'unreadable' };
+ }
if (exported.status === 'missing') {
return { status: 'stale' };
}
@@ -363,7 +410,7 @@ export class CropLayerController {
private publishAll(
document: CanvasDocumentContractV3,
cropped: readonly CroppedLeaf[],
- skippedLocked: number
+ skipped: { readonly skippedLocked: number; readonly skippedUnreadable: number }
): CropAllLayersResult {
const { ctx } = this.deps;
const afterBytes = cropped.reduce((sum, leaf) => sum + rgbaBytes(leaf.pixels.rect), 0);
@@ -408,7 +455,7 @@ export class CropLayerController {
undo: replay('before'),
});
const status = layerOperationStatus(result);
- return status === 'committed' ? { cropped: crops.length, skippedLocked, status: 'cropped' } : { status };
+ return status === 'committed' ? { cropped: crops.length, ...skipped, status: 'cropped' } : { status };
} finally {
txn.end();
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editSteps.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editSteps.ts
index 2c5b3be64b..e9fb4399a8 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editSteps.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editSteps.ts
@@ -34,6 +34,16 @@ export const rgbaBytes = (rect: Rect): number => Math.max(0, rect.width) * Math.
// ---- Publication outcomes ----------------------------------------------------------------------------------
+/**
+ * Whether a layer operation can read a layer's cache now: `not-ready` while its pixels load (waiting helps),
+ * `unreadable` once rasterizing its current source failed (waiting does not; the operation refuses and says so).
+ */
+export type LayerCacheReadiness = 'ready' | 'not-ready' | 'unreadable';
+
+/** Layers read together: one that cannot be read refuses the set even while others still load. */
+export const readinessOfAll = (readiness: readonly LayerCacheReadiness[]): LayerCacheReadiness =>
+ readiness.includes('unreadable') ? 'unreadable' : readiness.includes('not-ready') ? 'not-ready' : 'ready';
+
/** A refused admission as callers report it; a gesture in progress reads as contention. */
export type LayerEditRefusal = SubsetOf<CanvasTransactionOutcome, 'busy' | 'not-ready' | 'over-budget'>;
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.test.ts
index c5d333baf3..510e38c398 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.test.ts
@@ -41,12 +41,20 @@ const createTransformOptions = () => ({
canEdit: () => true,
commitStructural: vi.fn(),
ctx: {} as never,
+ enterTool: vi.fn(),
getCache: () => null,
getDocument: () => null,
+ getUserToolId: () => 'brush' as const,
+ hasFloatingSelection: () => false,
invalidate: vi.fn(),
isGestureActive: () => false,
+ isInteractionLocked: () => false,
+ peekCacheRect: () => undefined,
+ pending: { get: () => null, set: vi.fn() },
reportRefusal: vi.fn(),
+ rebaseLineEnd: vi.fn(),
restoreCache: vi.fn(),
+ select: vi.fn(),
session: { get: () => null, set: vi.fn() },
setOverride: vi.fn(),
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/extractMaskedAreaController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/extractMaskedAreaController.ts
index 940f034280..07d99b3edc 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/extractMaskedAreaController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/extractMaskedAreaController.ts
@@ -41,21 +41,30 @@ import {
layerOperationStatus,
paintLayerAt,
publishAddedRasterLayer,
+ readinessOfAll,
rgbaBytes,
+ type LayerCacheReadiness,
type LayerStepContext,
type LayerEditRefusal,
} from './editSteps';
export type ExtractMaskedAreaResult =
| { status: 'extracted'; layerId: string }
- | { status: LayerEditRefusal | SubsetOf<CanvasCommandRefusal, 'missing' | 'unsupported'> | 'empty' | 'failed' }
+ | {
+ status:
+ | LayerEditRefusal
+ | SubsetOf<CanvasCommandRefusal, 'missing' | 'unsupported'>
+ | 'empty'
+ | 'unreadable'
+ | 'failed';
+ }
| AdjustmentRefusal;
type OwnedExport = Extract<ExportResult, { status: 'ok' }>;
type ExportResult =
| { status: 'ok'; surface: RasterSurface; rect: Rect; guard: LayerExportGuard; release(): void }
- | { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'over-budget' }
+ | { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'unreadable' | 'over-budget' }
| AdjustmentRefusal;
export interface ExtractMaskedAreaControllerOptions {
@@ -72,7 +81,7 @@ export interface ExtractMaskedAreaControllerOptions {
>;
readonly backend: RasterBackend;
readonly layers: LayerCacheStore;
- readonly isCacheReady: (layer: CanvasLayerContract, document: CanvasDocumentContractV3) => boolean;
+ readonly cacheReadiness: (layer: CanvasLayerContract, document: CanvasDocumentContractV3) => LayerCacheReadiness;
readonly hasExportableContent: (layerId: string) => boolean;
readonly exportBaked: (layerId: string, includeDisabled?: boolean) => Promise<ExportResult>;
readonly rasterize: (layerId: string) => Promise<ExportResult>;
@@ -138,11 +147,9 @@ export class ExtractMaskedAreaController {
if (contributors.length === 0) {
return { status: 'empty' };
}
- if (
- !this.deps.isCacheReady(mask, document) ||
- contributors.some((layer) => !this.deps.isCacheReady(layer, document))
- ) {
- return { status: 'not-ready' };
+ const readiness = readinessOfAll([mask, ...contributors].map((layer) => this.deps.cacheReadiness(layer, document)));
+ if (readiness !== 'ready') {
+ return { status: readiness };
}
const owned: Extract<ExportResult, { status: 'ok' }>[] = [];
const acquire = async (resultPromise: Promise<ExportResult>): Promise<ExportResult> => {
@@ -168,8 +175,10 @@ export class ExtractMaskedAreaController {
return { status: 'busy' };
}
const statuses = [maskPixels, ...contributorPixels].map((pixels) => pixels.status);
- if (statuses.includes('over-budget') || statuses.includes('not-ready')) {
- return { status: statuses.includes('over-budget') ? 'over-budget' : 'not-ready' };
+ for (const status of ['over-budget', 'unreadable', 'not-ready'] as const) {
+ if (statuses.includes(status)) {
+ return { status };
+ }
}
if (maskPixels.status !== 'ok' || statuses.some((status) => status !== 'ok')) {
return { status: 'empty' };
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 9205d03d0e..f09b7f051d 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
@@ -54,7 +54,7 @@ describe('LayerController', () => {
ctx: {} as never,
exportBaked: vi.fn(),
hasExportableContent: () => false,
- isCacheReady: () => true,
+ cacheReadiness: () => 'ready' as const,
layers: {} as never,
needsPixelPersistence: () => false,
peekAdjustedSurface: () => null,
@@ -64,7 +64,7 @@ describe('LayerController', () => {
backend: {} as never,
ctx: {} as never,
exportBaked: vi.fn(),
- isCacheReady: () => true,
+ cacheReadiness: () => 'ready' as const,
isGuardCurrent: () => true,
};
const extractMaskedArea = {
@@ -76,7 +76,7 @@ describe('LayerController', () => {
getAdjustedSurface: vi.fn(),
getMaskPattern: () => null,
hasExportableContent: () => false,
- isCacheReady: () => true,
+ cacheReadiness: () => 'ready' as const,
isGuardCurrent: () => true,
layers: {} as never,
rasterize: vi.fn(),
@@ -87,6 +87,7 @@ describe('LayerController', () => {
ctx: {} as never,
discardPersisted: vi.fn(),
exportBaked: vi.fn(),
+ flushPendingPixels: () => Promise.resolve(),
isGuardCurrent: () => true,
isSupportedSource: () => true,
};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts
index 80cb3a35f4..c32e280f62 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts
@@ -42,12 +42,13 @@ export type ConvertLayerToControlResult =
| 'converted'
| SubsetOf<CanvasCommandRefusal, 'missing' | 'locked' | 'unsupported'>
| LayerEditRefusal
+ | 'unreadable'
| 'failed'
| AdjustmentRefusal;
type BakedExportResult =
| { status: 'ok'; surface: RasterSurface; rect: Rect; guard: LayerExportGuard; release(): void }
- | { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'over-budget' }
+ | { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'unreadable' | 'over-budget' }
| AdjustmentRefusal;
export type DuplicateLayerRasterPlan =
@@ -64,7 +65,7 @@ export type DuplicateLayerRasterPlan =
type DuplicateRasterPreparationResult =
| { readonly status: 'ready'; readonly layer: CanvasLayerContract }
- | { readonly status: 'not-ready' | 'over-budget' };
+ | { readonly status: 'not-ready' | 'unreadable' | 'over-budget' };
export interface LayerMutationControllerOptions {
readonly ctx: Pick<
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.browser.test.ts
index fbe7bee362..4906bb1eeb 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.browser.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.browser.test.ts
@@ -123,7 +123,7 @@ const mergeScene = (scene: Scene, displayed: boolean, service?: SpatialAdjustmen
ctx: h.ctx,
exportBaked: () => Promise.reject(new Error('merge down reads live caches')),
hasExportableContent: (layerId) => (h.layers.get(layerId)?.rect.width ?? 0) > 0,
- isCacheReady: () => true,
+ cacheReadiness: () => 'ready',
layers: h.layers,
needsPixelPersistence: () => false,
peekAdjustedSurface: (contract, entry) =>
@@ -233,10 +233,10 @@ const coverage = (rect: Rect, alpha: number): RasterSurface => {
};
describe('MergeLayerController in Chromium: merge masks', () => {
- it('unions coverage source-over, each mask at its own opacity', async () => {
- // The top mask is half-covered at full opacity; the one below is fully covered at half opacity.
+ it('unions coverage source-over, ignoring each mask’s display opacity', async () => {
+ // The top mask is half-covered at full opacity; the one below is fully covered but shown at 40 % opacity.
const sources: Record<string, { alpha: number; opacity: number; rect: Rect }> = {
- below: { alpha: 255, opacity: 0.5, rect: { height: 10, width: 10, x: 5, y: 0 } },
+ below: { alpha: 255, opacity: 0.4, rect: { height: 10, width: 10, x: 5, y: 0 } },
top: { alpha: 128, opacity: 1, rect: { height: 10, width: 10, x: 0, y: 0 } },
};
const document: CanvasDocumentContractV3 = {
@@ -278,7 +278,7 @@ describe('MergeLayerController in Chromium: merge masks', () => {
surface: coverage(sources[layerId]!.rect, sources[layerId]!.alpha),
}),
hasExportableContent: () => true,
- isCacheReady: () => true,
+ cacheReadiness: () => 'ready',
layers: h.layers,
needsPixelPersistence: () => true,
peekAdjustedSurface: () => null,
@@ -289,9 +289,10 @@ describe('MergeLayerController in Chromium: merge masks', () => {
const merged = created.find((surface) => surface.width === 15 && surface.height === 10)!;
const alphaAt = (x: number): number => merged.ctx.getImageData(x, 5, 1, 1).data[3]!;
- // Top only: its own coverage. Below only: half of full coverage. Both: 128 over 128 = 128 + 128 * (1 - 128/255).
+ // Top only: its own partial coverage. Below only: full coverage, which generation reads as masked (alpha > 127)
+ // however faintly the mask was shown. Both: full coverage under the top's.
expect(alphaAt(2)).toBeCloseTo(128, -0.5);
- expect(alphaAt(12)).toBeCloseTo(128, -0.5);
- expect(alphaAt(7)).toBeCloseTo(128 + 128 * (1 - 128 / 255), -0.5);
+ expect(alphaAt(12)).toBe(255);
+ expect(alphaAt(7)).toBe(255);
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.test.ts
index b44d069b2a..1a66fc0b18 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.test.ts
@@ -72,7 +72,7 @@ const createHarness = (
ctx: h.ctx,
exportBaked: () => Promise.reject(new Error('merge down reads live caches')),
hasExportableContent: (layerId) => (h.layers.get(layerId)?.rect.width ?? 0) > 0,
- isCacheReady: () => true,
+ cacheReadiness: () => 'ready',
layers: h.layers,
needsPixelPersistence: () => true,
peekAdjustedSurface: () => displayed,
@@ -295,7 +295,7 @@ describe('MergeLayerController: merge visible with a spatial group stack', () =>
}
),
hasExportableContent: () => true,
- isCacheReady: () => true,
+ cacheReadiness: () => 'ready',
layers: h.layers,
needsPixelPersistence: () => false,
peekAdjustedSurface: () => null,
@@ -357,11 +357,17 @@ describe('MergeLayerController: merge masks', () => {
top: { height: 10, width: 10, x: 0, y: 0 },
};
- const createMaskHarness = (options: { historyBytes?: number; onExport?: () => void } = {}) => {
- const top = layerContract('top', 'inpaint_mask', {
+ const createMaskHarness = (
+ options: { bottomNoiseLevel?: number; historyBytes?: number; onExport?: () => void } = {}
+ ) => {
+ // Generation settings every source shares, so the merge may carry them over the whole union.
+ const settings = (noiseLevel = 0.2) => ({
denoise: { isEnabled: true, limit: 0.4 },
+ noise: { isEnabled: true, level: noiseLevel },
+ });
+ const top = layerContract('top', 'inpaint_mask', {
+ ...settings(),
mask: { bitmap: null, fill: { color: '#123456', style: 'grid' } },
- noise: { isEnabled: true, level: 0.2 },
opacity: 0.5,
} as Partial<CanvasLayerContract>);
const document: CanvasDocumentContractV3 = {
@@ -371,8 +377,11 @@ describe('MergeLayerController: merge masks', () => {
selectedLayerId: 'middle',
stacks: stacksFrom([
groupContract('first', [layerContract('other', 'inpaint_mask'), top]),
- groupContract('second', [layerContract('middle', 'inpaint_mask')]),
- layerContract('bottom', 'inpaint_mask'),
+ groupContract('second', [layerContract('middle', 'inpaint_mask', settings() as Partial<CanvasLayerContract>)]),
+ layerContract('bottom', 'inpaint_mask', {
+ ...settings(options.bottomNoiseLevel),
+ mask: { bitmap: null, fill: { color: '#abcdef', style: 'solid' } },
+ } as Partial<CanvasLayerContract>),
]),
version: 3,
width: 100,
@@ -398,7 +407,7 @@ describe('MergeLayerController: merge masks', () => {
});
},
hasExportableContent: (layerId) => (h.layers.get(layerId)?.rect.width ?? 0) > 0,
- isCacheReady: () => true,
+ cacheReadiness: () => 'ready',
layers: h.layers,
needsPixelPersistence: () => true,
peekAdjustedSurface: () => null,
@@ -410,7 +419,7 @@ describe('MergeLayerController: merge masks', () => {
const structure = (document: CanvasDocumentContractV3) =>
[...getDocumentIndex(document).byId.values()].map((entry) => [entry.node.id, entry.parentId, entry.siblingIndex]);
- it('unions masks from different groups into one mask above the topmost, configured like it, as one step', async () => {
+ it('unions masks from different groups into one mask above the topmost, with its fill, as one step', async () => {
const h = createMaskHarness();
const result = await h.controller.mergeInpaintMasks(['bottom', 'top', 'middle']);
@@ -462,6 +471,14 @@ describe('MergeLayerController: merge masks', () => {
expect(h.dispatched).toEqual([]);
});
+ it('refuses masks whose noise or denoise settings differ without reading pixels', async () => {
+ const h = createMaskHarness({ bottomNoiseLevel: 0.7, onExport: () => expect.fail('read pixels') });
+
+ await expect(h.controller.mergeInpaintMasks(['top', 'bottom'])).resolves.toEqual({ status: 'settings-differ' });
+ expect(h.dispatched).toEqual([]);
+ expect(h.history.canUndo()).toBe(false);
+ });
+
it('refuses a merge it could never undo with nothing changed', async () => {
const h = createMaskHarness({ historyBytes: 1024 });
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts
index 781b3ffeb1..1d65edcbcd 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts
@@ -27,6 +27,7 @@ import {
canMergeInpaintMasks,
canMergeSelectedRasters,
getMergeVisibleRasterLeaves,
+ inpaintMaskMergeEligibility,
} from '@workbench/canvas-engine/document/mergeVisible';
import { collectHistoryMediaRefs, HISTORY_ENTRY_OVERHEAD_BYTES } from '@workbench/canvas-engine/history/history';
import { isEmpty, roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';
@@ -59,19 +60,25 @@ import {
layerOperationStatus,
paintLayerAt,
publishAddedRasterLayer,
+ readinessOfAll,
rgbaBytes,
withReplayReservation,
+ type LayerCacheReadiness,
type LayerEditRefusal,
replaceLayerStep,
type LayerPixels,
} from './editSteps';
-export type MergeVisibleResult = 'merged' | LayerEditRefusal | 'nothing' | 'failed' | AdjustmentRefusal;
+/** `unreadable`: a contributor's pixels could not be read (its image is gone or does not decode). */
+export type MergeVisibleResult = 'merged' | LayerEditRefusal | 'nothing' | 'unreadable' | 'failed' | AdjustmentRefusal;
-/** Every refusal leaves document, pixels and history alone. */
+/**
+ * Every refusal leaves document, pixels and history alone. `settings-differ`: the masks are otherwise eligible, but
+ * their enabled noise or denoise settings differ.
+ */
export type MergeInpaintMasksResult =
| { status: 'merged'; layerId: string }
- | { status: 'ineligible' | 'missing' | 'failed' | LayerEditRefusal }
+ | { status: 'ineligible' | 'settings-differ' | 'missing' | 'unreadable' | 'failed' | LayerEditRefusal }
| AdjustmentRefusal;
/**
@@ -83,6 +90,8 @@ interface SelectedMergeSpec {
readonly label: string;
readonly stack: LayerStackKind;
canMerge(document: CanvasDocumentContractV3, selectedIds: ReadonlySet<string>): boolean;
+ /** The alpha a contributor composites at. */
+ contributorAlpha(contributor: CanvasLayerContract): number;
/** The merged leaf placing pixels at `rect`, from the contributors top first. */
createResult(id: string, contributors: readonly CanvasLayerContract[], rect: Rect): CanvasLayerContract;
}
@@ -96,7 +105,7 @@ const IDENTITY_TRANSFORM = { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 };
/**
* One inpaint mask carrying the union of the sources' coverage at `rect`, named after and configured like the topmost
- * source: its fill, noise and denoise.
+ * source: its fill, and the noise and denoise every source shares.
*/
const mergedMaskLayer = (id: string, contributors: readonly CanvasLayerContract[], rect: Rect): CanvasLayerContract => {
const top = contributors[0]!;
@@ -122,19 +131,20 @@ export type MergeDownResult =
| 'merged'
| SubsetOf<CanvasCommandRefusal, 'missing' | 'unsupported'>
| LayerEditRefusal
+ | 'unreadable'
| 'failed'
| AdjustmentRefusal;
type ExportResult =
| { status: 'ok'; surface: RasterSurface; rect: Rect; guard: LayerExportGuard; release(): void }
- | { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'over-budget' }
+ | { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'unreadable' | 'over-budget' }
| AdjustmentRefusal;
export interface MergeLayerControllerOptions {
readonly backend: RasterBackend;
readonly ctx: CanvasMutationContext;
readonly layers: LayerCacheStore;
- readonly isCacheReady: (layer: CanvasLayerContract, document: CanvasDocumentContractV3) => boolean;
+ readonly cacheReadiness: (layer: CanvasLayerContract, document: CanvasDocumentContractV3) => LayerCacheReadiness;
readonly hasExportableContent: (layerId: string) => boolean;
readonly exportBaked: (layerId: string) => Promise<ExportResult>;
readonly needsPixelPersistence: (layer: CanvasLayerContract) => boolean;
@@ -182,12 +192,14 @@ export class MergeLayerController {
const belowCache = this.deps.layers.get(below.id);
const upperHasContent = this.deps.hasExportableContent(upper.id);
const belowHasContent = this.deps.hasExportableContent(below.id);
- if (
- (upperHasContent && !upperCache) ||
- (belowHasContent && !belowCache) ||
- !this.deps.isCacheReady(upper, document) ||
- !this.deps.isCacheReady(below, document)
- ) {
+ const readiness = readinessOfAll([
+ this.deps.cacheReadiness(upper, document),
+ this.deps.cacheReadiness(below, document),
+ ]);
+ if (readiness !== 'ready') {
+ return readiness;
+ }
+ if ((upperHasContent && !upperCache) || (belowHasContent && !belowCache)) {
return 'not-ready';
}
const matrix = mergeDownMatrix(below.transform, upper.transform);
@@ -412,6 +424,9 @@ export class MergeLayerController {
if (exports.some((result) => result.status === 'over-budget')) {
return 'over-budget';
}
+ if (exports.some((result) => result.status === 'unreadable')) {
+ return 'unreadable';
+ }
if (exports.some((result) => result.status !== 'ok')) {
return 'not-ready';
}
@@ -556,6 +571,7 @@ export class MergeLayerController {
const result = await this.mergeSelectedInto(layerIds, {
canMerge: (document, selectedIds) =>
canMergeSelectedRasters(document, compileDocumentLeaves(document), selectedIds, this.deps.hasExportableContent),
+ contributorAlpha: (contributor) => contributor.opacity,
createResult: (id, contributors, rect) => paintLayerAt(id, `${contributors[0]!.name} merged`, rect),
label: 'Merge selected layers',
stack: 'raster',
@@ -569,9 +585,21 @@ export class MergeLayerController {
if (document && layerIds.some((id) => !getDocumentNode(document, id))) {
return { status: 'missing' };
}
+ if (
+ document &&
+ inpaintMaskMergeEligibility(
+ compileDocumentLeaves(document),
+ new Set(layerIds),
+ this.deps.hasExportableContent
+ ) === 'settings-differ'
+ ) {
+ return { status: 'settings-differ' };
+ }
const result = await this.mergeSelectedInto(layerIds, {
canMerge: (candidate, selectedIds) =>
canMergeInpaintMasks(compileDocumentLeaves(candidate), selectedIds, this.deps.hasExportableContent),
+ // Opacity only tints a mask on screen; generation reads its coverage alone, so it never thins merged coverage.
+ contributorAlpha: () => 1,
createResult: mergedMaskLayer,
label: 'Merge masks',
stack: 'inpaint_mask',
@@ -583,8 +611,8 @@ export class MergeLayerController {
}
/**
- * Composites the selected leaves bottom-up (source-over, each at its opacity) into a new leaf above the topmost and
- * removes them, as one undo step that restores every source in place with its raw pixels.
+ * Composites the selected leaves bottom-up (source-over, each at the spec's alpha) into a new leaf above the topmost
+ * and removes them, as one undo step that restores every source in place with its raw pixels.
*/
private async mergeSelectedInto(layerIds: readonly string[], spec: SelectedMergeSpec): Promise<SelectedMergeResult> {
const { ctx } = this.deps;
@@ -626,6 +654,9 @@ export class MergeLayerController {
if (exports.some((result) => result.status === 'over-budget')) {
return { status: 'over-budget' };
}
+ if (exports.some((result) => result.status === 'unreadable')) {
+ return { status: 'unreadable' };
+ }
if (exports.some((result) => result.status !== 'ok')) {
return { status: 'not-ready' };
}
@@ -699,7 +730,7 @@ export class MergeLayerController {
for (let index = successful.length - 1; index >= 0; index -= 1) {
const exported = successful[index]!;
const contributor = contributors[index]!;
- context.globalAlpha = contributor.opacity;
+ context.globalAlpha = spec.contributorAlpha(contributor);
context.globalCompositeOperation = 'source-over';
context.drawImage(exported.surface.canvas, exported.rect.x - rect.x, exported.rect.y - rect.y);
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/paintLineEndController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/paintLineEndController.test.ts
new file mode 100644
index 0000000000..f11df60508
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/paintLineEndController.test.ts
@@ -0,0 +1,65 @@
+import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';
+
+import { layerContract } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
+import { describe, expect, it } from 'vitest';
+
+import { PaintLineEndController } from './paintLineEndController';
+
+const paint = (x: number, offsetX: number, overrides: Partial<CanvasLayerContract> = {}): CanvasLayerContract =>
+ layerContract('paint', 'raster', {
+ source: { bitmap: null, offset: { x: offsetX, y: 0 }, type: 'paint' },
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x, y: 0 },
+ ...overrides,
+ } as Partial<CanvasLayerContract>);
+
+const createHarness = (initial: CanvasLayerContract) => {
+ let layer: CanvasLayerContract | null = initial;
+ const ends = new PaintLineEndController({ getLayer: () => layer });
+ const change = (next: CanvasLayerContract | null) => {
+ layer = next;
+ ends.onLayerChanged('paint');
+ };
+ return { change, ends };
+};
+
+describe('PaintLineEndController', () => {
+ it('carries the stroke end with a layer that only moves', () => {
+ const h = createHarness(paint(0, 0));
+ h.ends.set('paint', { x: 60, y: 10 });
+
+ h.change(paint(100, 0));
+
+ expect(h.ends.get('paint')).toEqual({ x: 60, y: 10 });
+ });
+
+ it('keeps the document point when content and transform are rewritten together, as a crop does', () => {
+ const h = createHarness(paint(100, 0));
+ h.ends.set('paint', { x: 60, y: 10 });
+
+ // Cropped: the pixels stay where they were, now at an identity transform.
+ h.change(paint(0, 100));
+
+ expect(h.ends.get('paint')).toEqual({ x: 160, y: 10 });
+ });
+
+ it('follows pixels redrawn from a Transform session into a new local space', () => {
+ const h = createHarness(paint(0, 0));
+ h.ends.set('paint', { x: 60, y: 10 });
+
+ h.ends.rebase('paint', { rotation: 0, scaleX: 2, scaleY: 2, x: 100, y: 0 });
+
+ expect(h.ends.get('paint')).toEqual({ x: 220, y: 20 });
+ });
+
+ it('forgets the end of a removed layer and one a degenerate transform cannot hold', () => {
+ const removed = createHarness(paint(0, 0));
+ removed.ends.set('paint', { x: 1, y: 1 });
+ removed.change(null);
+ expect(removed.ends.get('paint')).toBeUndefined();
+
+ const flattened = createHarness(paint(0, 0));
+ flattened.ends.set('paint', { x: 1, y: 1 });
+ flattened.change(paint(0, 5, { transform: { rotation: 0, scaleX: 0, scaleY: 1, x: 0, y: 0 } }));
+ expect(flattened.ends.get('paint')).toBeUndefined();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/paintLineEndController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/paintLineEndController.ts
new file mode 100644
index 0000000000..4d4814e61d
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/paintLineEndController.ts
@@ -0,0 +1,110 @@
+import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';
+import type { PaintLineEnds } from '@workbench/canvas-engine/tools/tool';
+import type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';
+import type { Vec2 } from '@workbench/canvas-engine/types';
+
+import { areJsonValuesStructurallyEqual } from '@platform/core/json';
+import { renderableSourceOf } from '@workbench/canvas-engine/document/sources';
+import { applyToPoint, invert, multiply } from '@workbench/canvas-engine/math/mat2d';
+import { layerTransformMatrix } from '@workbench/canvas-engine/transform/transformMath';
+
+export interface PaintLineEndControllerOptions {
+ /** The layer as the document holds it now, or null when it is gone. */
+ readonly getLayer: (layerId: string) => CanvasLayerContract | null;
+}
+
+interface LineEnd {
+ /** Layer-local, in the space of `layer.transform`. */
+ readonly point: Vec2;
+ /** The contract last seen for the layer, which `point` is relative to. */
+ readonly layer: CanvasLayerContract;
+}
+
+const sameTransform = (a: LayerTransform, b: LayerTransform): boolean =>
+ a.x === b.x && a.y === b.y && a.rotation === b.rotation && a.scaleX === b.scaleX && a.scaleY === b.scaleY;
+
+/**
+ * Where the last committed brush or eraser stroke ended on each layer, for Shift-click straight lines. Points are kept
+ * layer-local, so a change of transform alone (a move, nudge, Fit to frame or transform parameter) carries them with
+ * the layer. A change that rewrites the layer's content and transform together (crop, conversion, a baked float or
+ * result) keeps the point where the content stays in the document, mapping it from the previous transform into the
+ * new one. An applied Transform on a paint layer rewrites only its pixels, so it says where they went with
+ * {@link rebase}. A point the new transform cannot hold is forgotten.
+ */
+export class PaintLineEndController implements PaintLineEnds {
+ private readonly ends = new Map<string, LineEnd>();
+
+ constructor(private readonly deps: PaintLineEndControllerOptions) {}
+
+ get(layerId: string): Vec2 | undefined {
+ // Catches up with a change no layer event reported (a layer moved between stacks reports a reorder).
+ this.onLayerChanged(layerId);
+ return this.ends.get(layerId)?.point;
+ }
+
+ set(layerId: string, point: Vec2): void {
+ const layer = this.deps.getLayer(layerId);
+ if (layer) {
+ this.ends.set(layerId, { layer, point: { ...point } });
+ }
+ }
+
+ /** Follows one document change of `layerId`. */
+ onLayerChanged(layerId: string): void {
+ const end = this.ends.get(layerId);
+ if (!end) {
+ return;
+ }
+ const layer = this.deps.getLayer(layerId);
+ if (!layer) {
+ this.ends.delete(layerId);
+ return;
+ }
+ if (layer === end.layer) {
+ return;
+ }
+ const rebaked =
+ !sameTransform(layer.transform, end.layer.transform) &&
+ (layer.type !== end.layer.type ||
+ !areJsonValuesStructurallyEqual(renderableSourceOf(layer), renderableSourceOf(end.layer)));
+ if (!rebaked) {
+ this.ends.set(layerId, { layer, point: end.point });
+ return;
+ }
+ this.map(layerId, end.point, end.layer.transform, layer);
+ }
+
+ /**
+ * The layer's pixels were redrawn through `from`, the transform they were shown at, into its current local space
+ * (an applied Transform on a paint layer); the point follows them.
+ */
+ rebase(layerId: string, from: LayerTransform): void {
+ this.onLayerChanged(layerId);
+ const end = this.ends.get(layerId);
+ if (end) {
+ this.map(layerId, end.point, from, end.layer);
+ }
+ }
+
+ /** Stores `point`, local to `from`, as the same document point local to `layer`'s transform. */
+ private map(layerId: string, point: Vec2, from: LayerTransform, layer: CanvasLayerContract): void {
+ const toLocal = invert(layerTransformMatrix(layer.transform));
+ if (!toLocal) {
+ this.ends.delete(layerId);
+ return;
+ }
+ this.ends.set(layerId, { layer, point: applyToPoint(multiply(toLocal, layerTransformMatrix(from)), point) });
+ }
+
+ delete(layerId: string): void {
+ this.ends.delete(layerId);
+ }
+
+ clear(): void {
+ this.ends.clear();
+ }
+
+ dispose(): void {
+ this.ends.clear();
+ }
+}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.ts
index f07356c0bb..cc2e055383 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.ts
@@ -27,9 +27,16 @@ import {
type SpatialRunner,
} from '@workbench/canvas-engine/render/exactAdjustments';
+/**
+ * `not-ready`: the pixels are still loading or moved while they were read, so trying again can succeed. `unreadable`:
+ * rasterizing the layer's current source failed (an image that is gone or does not decode), so trying again cannot
+ * succeed until the source changes.
+ */
export type ExportLayerPixelsResult =
| ({ status: 'ok' } & RasterReadLease)
- | { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'over-budget' | 'aborted' }
+ | {
+ status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'unreadable' | 'over-budget' | 'aborted';
+ }
| AdjustmentRefusal;
export interface RasterExportControllerOptions {
@@ -206,7 +213,7 @@ export class RasterExportController {
try {
const rasterized = await this.options.getOrStartRasterization(layer, document, options.signal);
if (rasterized !== 'published') {
- return { status: rasterized === 'aborted' ? 'aborted' : 'not-ready' };
+ return { status: rasterized === 'aborted' ? 'aborted' : rasterized === 'error' ? 'unreadable' : 'not-ready' };
}
const currentDocument = this.options.getDocument();
const currentLayer = currentDocument ? lookupDocumentLayer(currentDocument, layerId) : null;
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.test.ts
index 0f49ad5bab..fca5eba3bc 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.test.ts
@@ -1,6 +1,7 @@
import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';
import type { TransformSession } from '@workbench/canvas-engine/engineStores';
import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';
+import type { ToolId } from '@workbench/canvas-engine/types';
import { createCanvasMutationContext } from '@workbench/canvas-engine/controllers/mutationContext';
import { documentFrom, layerContract } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
@@ -16,19 +17,26 @@ import { TransformEditingController } from './transformEditingController';
const MOVED = { rotation: 0, scaleX: 1, scaleY: 1, x: 12, y: 4 };
-/** The controller over a real reducer, mutation context and history. */
+/**
+ * The controller over a real reducer, mutation context and history. The first layer is selected and has a 4×4 cache;
+ * `state` holds what the engine would otherwise decide (the tool, locks, a float, a gesture).
+ */
const createHarness = (
- layer: CanvasLayerContract,
+ layers: CanvasLayerContract | CanvasLayerContract[],
options: { byteBudget?: number; commitStatus?: 'committed' | 'busy' } = {}
) => {
+ const [layer] = Array.isArray(layers) ? layers : [layers];
+ if (!layer) {
+ throw new Error('expected a layer');
+ }
let project = applyCanvasProjectMutation(createInitialWorkbenchState().projects[0]!, {
- document: documentFrom([layer], layer.id),
+ document: documentFrom(Array.isArray(layers) ? layers : [layers], layer.id),
type: 'replaceCanvasDocument',
});
const history = createHistory({ byteBudget: options.byteBudget });
const backend = createTestStubRasterBackend();
- const layers = createLayerCacheStore(backend);
- layers.getOrCreateRect(layer.id, { height: 4, width: 4, x: 0, y: 0 });
+ const caches = createLayerCacheStore(backend);
+ caches.getOrCreateRect(layer.id, { height: 4, width: 4, x: 0, y: 0 });
const dispatch = (action: CanvasProjectMutation): boolean => {
project = applyCanvasProjectMutation(project, action);
return true;
@@ -58,23 +66,44 @@ const createHarness = (
subscribeReducer: () => () => undefined,
});
let session: TransformSession | null = null;
+ let pending: string | null = null;
+ const state = {
+ canEdit: true,
+ floating: false,
+ gesture: false,
+ interactionLocked: false,
+ tool: 'brush' as ToolId,
+ };
const calls = {
commitStructural: vi.fn(() => ({ status: options.commitStatus ?? ('committed' as const) })),
+ enterTool: vi.fn(() => {
+ state.tool = 'transform';
+ }),
+ rebaseLineEnd: vi.fn(),
reportRefusal: vi.fn(),
restoreCache: vi.fn(),
+ select: vi.fn((layerId: string) => dispatch({ id: layerId, type: 'setCanvasSelectedLayer' })),
setOverride: vi.fn(),
};
const controller = new TransformEditingController({
backend,
- canEdit: () => true,
+ canEdit: () => state.canEdit,
commitStructural: calls.commitStructural,
ctx,
- getCache: (layerId) => layers.get(layerId) ?? null,
+ enterTool: calls.enterTool,
+ getCache: (layerId) => caches.get(layerId) ?? null,
getDocument: () => project.canvas.document,
+ getUserToolId: () => state.tool,
+ hasFloatingSelection: () => state.floating,
invalidate: vi.fn(),
- isGestureActive: () => false,
+ isGestureActive: () => state.gesture,
+ isInteractionLocked: () => state.interactionLocked,
+ peekCacheRect: (layerId) => caches.peek(layerId)?.rect,
+ pending: { get: () => pending, set: (value) => (pending = value) },
reportRefusal: calls.reportRefusal,
+ rebaseLineEnd: calls.rebaseLineEnd,
restoreCache: calls.restoreCache,
+ select: calls.select,
session: { get: () => session, set: (value) => (session = value) },
setOverride: calls.setOverride,
});
@@ -82,13 +111,18 @@ const createHarness = (
calls,
controller,
dispatch,
+ document: () => project.canvas.document,
history,
layer: () => getDocumentLayer(project.canvas.document, layer.id),
+ pending: () => pending,
rasterFits,
session: () => session,
+ state,
};
};
+type HarnessState = ReturnType<typeof createHarness>['state'];
+
const shape = layerContract('shape', 'raster', {
source: { fill: '#fff', height: 10, kind: 'rect', stroke: null, strokeWidth: 0, type: 'shape', width: 10 },
} as Partial<CanvasLayerContract>);
@@ -185,3 +219,176 @@ describe('TransformEditingController', () => {
expect(h.calls.restoreCache).toHaveBeenCalledOnce();
});
});
+
+describe('TransformEditingController.request', () => {
+ const persistedPaint = (id: string) =>
+ layerContract(id, 'raster', {
+ source: { bitmap: { height: 4, imageName: `${id}.png`, width: 4 }, type: 'paint' },
+ } as Partial<CanvasLayerContract>);
+ const a = persistedPaint('a');
+ const b = persistedPaint('b');
+
+ it('selects the layer, enters the tool and opens its session', () => {
+ const h = createHarness([a, b]);
+
+ expect(h.controller.request('b')).toBe('started');
+ expect(h.document()?.selectedLayerId).toBe('b');
+ expect(h.calls.enterTool).toHaveBeenCalledOnce();
+ expect(h.session()?.layerId).toBe('b');
+ expect(h.pending()).toBeNull();
+ });
+
+ it('cancels a session on another layer, dropping its preview, before opening one on the target', () => {
+ const h = createHarness([a, b]);
+ h.controller.begin('a');
+ h.controller.update(MOVED);
+
+ expect(h.controller.request('b')).toBe('started');
+ expect(h.calls.setOverride).toHaveBeenCalledWith('a', null);
+ expect(h.session()).toMatchObject({ layerId: 'b', transform: { scaleX: 1, x: 0, y: 0 } });
+ // The abandoned preview on `a` never landed.
+ expect(getDocumentLayer(h.document(), 'a')?.transform.x).toBe(0);
+ });
+
+ it.each([
+ ['a locked leaf', { ...b, isLocked: true }, 'locked'],
+ ['a mask', layerContract('b', 'inpaint_mask'), 'ineligible'],
+ ['a missing leaf', null, 'missing'],
+ ] as const)('refuses %s without selecting or switching tools', (_, target, status) => {
+ const h = createHarness(target ? [a, target] : [a]);
+
+ expect(h.controller.request('b')).toBe(status);
+ expect(h.calls.select).not.toHaveBeenCalled();
+ expect(h.calls.enterTool).not.toHaveBeenCalled();
+ expect(h.session()).toBeNull();
+ expect(h.pending()).toBeNull();
+ });
+
+ it.each([
+ ['interaction is locked', (s: HarnessState) => (s.interactionLocked = true)],
+ ['a gesture runs', (s: HarnessState) => (s.gesture = true)],
+ ['a float is live', (s: HarnessState) => (s.floating = true)],
+ ['document edits are locked', (s: HarnessState) => (s.canEdit = false)],
+ ])('refuses as busy while %s, leaving the selection and tool unchanged', (_, lock) => {
+ const h = createHarness([a, b]);
+ lock(h.state);
+
+ expect(h.controller.request('b')).toBe('busy');
+ expect(h.calls.select).not.toHaveBeenCalled();
+ expect(h.calls.enterTool).not.toHaveBeenCalled();
+ expect(h.session()).toBeNull();
+ });
+
+ it('refuses as busy once disposed', () => {
+ const h = createHarness([a, b]);
+ h.controller.dispose();
+ h.controller.dispose();
+
+ expect(h.controller.request('b')).toBe('busy');
+ expect(h.calls.select).not.toHaveBeenCalled();
+ });
+});
+
+describe('TransformEditingController pending transform', () => {
+ /** A paint layer whose only pixels are a stroke persistence has not acknowledged yet. */
+ const unpersisted = layerContract('stroke', 'raster');
+ const other = layerContract('other', 'raster', {
+ source: { bitmap: { height: 4, imageName: 'other.png', width: 4 }, type: 'paint' },
+ } as Partial<CanvasLayerContract>);
+
+ const requestUnpersisted = () => {
+ const h = createHarness([unpersisted, other]);
+ expect(h.controller.request('stroke')).toBe('started');
+ expect(h.session()).toBeNull();
+ expect(h.pending()).toBe('stroke');
+ const persist = () => {
+ h.dispatch({
+ id: 'stroke',
+ source: { bitmap: { height: 4, imageName: 'stroke.png', width: 4 }, type: 'paint' },
+ type: 'updateCanvasLayerSource',
+ });
+ h.controller.onDocumentChanged();
+ };
+ return { ...h, persist };
+ };
+
+ it('opens the session once the pixels are persisted, and not before', () => {
+ const h = requestUnpersisted();
+ h.controller.onDocumentChanged();
+ expect(h.pending()).toBe('stroke');
+
+ h.persist();
+ expect(h.session()?.layerId).toBe('stroke');
+ expect(h.pending()).toBeNull();
+ });
+
+ it('keeps waiting through a switch to the transform tool itself', () => {
+ const h = requestUnpersisted();
+ h.controller.onToolSwitch('transform');
+ h.persist();
+ expect(h.session()?.layerId).toBe('stroke');
+ });
+
+ it.each([
+ ['a tool switch', (h: ReturnType<typeof requestUnpersisted>) => h.controller.onToolSwitch('brush')],
+ ['Escape', (h: ReturnType<typeof requestUnpersisted>) => expect(h.controller.onEscape()).toBe(true)],
+ ['a history replay', (h: ReturnType<typeof requestUnpersisted>) => h.controller.onReplay()],
+ ['a document replacement', (h: ReturnType<typeof requestUnpersisted>) => h.controller.onDocumentReplaced()],
+ [
+ 'a selection change',
+ (h: ReturnType<typeof requestUnpersisted>) => {
+ h.dispatch({ id: 'other', type: 'setCanvasSelectedLayer' });
+ h.controller.onDocumentChanged();
+ h.dispatch({ id: 'stroke', type: 'setCanvasSelectedLayer' });
+ },
+ ],
+ [
+ 'leaving transform for a tool the user is on',
+ (h: ReturnType<typeof requestUnpersisted>) => {
+ h.state.tool = 'brush';
+ h.controller.onDocumentChanged();
+ h.state.tool = 'transform';
+ },
+ ],
+ [
+ 'another session opening',
+ (h: ReturnType<typeof requestUnpersisted>) => {
+ h.controller.begin('other');
+ h.controller.onDocumentChanged();
+ h.controller.cancel();
+ },
+ ],
+ ['disposal', (h: ReturnType<typeof requestUnpersisted>) => h.controller.dispose()],
+ ])('stops waiting on %s, silently', (_, end) => {
+ const h = requestUnpersisted();
+ end(h);
+ expect(h.pending()).toBeNull();
+
+ h.persist();
+ expect(h.session()).toBeNull();
+ expect(h.calls.reportRefusal).not.toHaveBeenCalled();
+ });
+
+ it('stops waiting when the layer is removed', () => {
+ const h = requestUnpersisted();
+ h.dispatch({ ids: ['stroke'], type: 'removeCanvasLayers' });
+ h.controller.onDocumentChanged();
+ expect(h.pending()).toBeNull();
+ });
+
+ it('leaves Escape to the next handler when nothing waits', () => {
+ const h = createHarness([other]);
+ expect(h.controller.onEscape()).toBe(false);
+ });
+
+ it('reports not-ready when the waiting layer’s upload fails with no retry to follow', () => {
+ const h = requestUnpersisted();
+ h.controller.onUploadFailed('other');
+ expect(h.pending()).toBe('stroke');
+ expect(h.calls.reportRefusal).not.toHaveBeenCalled();
+
+ h.controller.onUploadFailed('stroke');
+ expect(h.pending()).toBeNull();
+ expect(h.calls.reportRefusal).toHaveBeenCalledExactlyOnceWith('not-ready');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.ts
index 3708e9ef7a..672254d10a 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.ts
@@ -1,11 +1,15 @@
-import type { CanvasEditRefusal, StructuralCommitResult } from '@workbench/canvas-engine/capabilities';
+import type {
+ BeginTransformResult,
+ CanvasEditRefusal,
+ StructuralCommitResult,
+} from '@workbench/canvas-engine/capabilities';
import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';
import type { TransformSession } from '@workbench/canvas-engine/engineStores';
import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';
import type { LayerCacheEntry } from '@workbench/canvas-engine/render/layerCache';
import type { RasterBackend } from '@workbench/canvas-engine/render/raster';
import type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';
-import type { Rect } from '@workbench/canvas-engine/types';
+import type { Rect, ToolId } from '@workbench/canvas-engine/types';
import { lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';
import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';
@@ -14,6 +18,7 @@ import { isRenderableLayer } from '@workbench/canvas-engine/document/sources';
import { HISTORY_ENTRY_OVERHEAD_BYTES, NO_HELD_ASSET_REFS } from '@workbench/canvas-engine/history/history';
import { isEmpty, roundOut, transformBounds } from '@workbench/canvas-engine/math/rect';
import { hittableLayerSize } from '@workbench/canvas-engine/tools/moveHitTest';
+import { isTransformEligible } from '@workbench/canvas-engine/tools/transformTool';
import { bakeMatrix } from '@workbench/canvas-engine/transform/transformMath';
import type { CanvasMutationContext, EditStep } from './mutationContext';
@@ -22,13 +27,19 @@ import { rgbaBytes, withReplayReservation } from './editSteps';
export interface TransformEditingControllerOptions {
readonly session: { get(): TransformSession | null; set(value: TransformSession | null): void };
+ /** A requested session waiting for its layer's pixels to persist; see {@link TransformEditingController.request}. */
+ readonly pending: { get(): string | null; set(value: string | null): void };
readonly backend: RasterBackend;
readonly ctx: Pick<CanvasMutationContext, 'applyStep' | 'begin' | 'reserveRaster'>;
readonly getDocument: () => CanvasDocumentContractV3 | null;
readonly getCache: (layerId: string) => LayerCacheEntry | null;
+ /** The live cache extent, read without touching residency order. */
+ readonly peekCacheRect: (layerId: string) => Rect | undefined;
readonly setOverride: (layerId: string, transform: LayerTransform | null) => void;
/** Installs whole-layer pixels at a layer-local rect, marking them painted and dirty. */
readonly restoreCache: (layerId: string, rect: Rect, pixels: ImageData) => void;
+ /** A paint layer's pixels were redrawn from `from`, the session's transform, into its new local space. */
+ readonly rebaseLineEnd: (layerId: string, from: LayerTransform) => void;
readonly commitStructural: (
label: string,
forward: CanvasProjectMutation,
@@ -37,6 +48,14 @@ export interface TransformEditingControllerOptions {
readonly reportRefusal: (refusal: CanvasEditRefusal) => void;
readonly canEdit: () => boolean;
readonly isGestureActive: () => boolean;
+ readonly isInteractionLocked: () => boolean;
+ readonly hasFloatingSelection: () => boolean;
+ /** The tool the user is on: a Space, Alt or C hold only lends the surface to another tool. */
+ readonly getUserToolId: () => ToolId;
+ /** Selects `layerId`; selecting cancels a session on another layer. */
+ readonly select: (layerId: string) => void;
+ /** Switches to the transform tool, which opens a session on an eligible selection. */
+ readonly enterTool: () => void;
readonly invalidate: (payload: { layers: string[]; overlay: true }) => void;
}
@@ -52,7 +71,10 @@ const unchanged = (left: LayerTransform, right: LayerTransform): boolean =>
left.scaleY === right.scaleY &&
left.rotation === right.rotation;
-/** Owns transform session state, previews, param commits, and paint bakes. */
+/**
+ * Owns transform session state, previews, param commits, paint bakes, and the wait of a session requested on pixels
+ * persistence has not acknowledged yet.
+ */
export class TransformEditingController {
private disposed = false;
@@ -82,6 +104,110 @@ export class TransformEditingController {
this.deps.invalidate({ layers: [layerId], overlay: true });
}
+ /**
+ * Opens a session on `layerId` now, whatever tool is active: selects it, enters the tool and opens the session
+ * even when transform is already active, cancelling a session on another layer. Every refusal is decided before
+ * the selection or tool changes. A leaf whose only content is a stroke persistence has not acknowledged yet (a new
+ * paint layer's first upload) has no persisted extent to frame, so the request waits in `pending` and the session
+ * opens once the bitmap lands.
+ */
+ request(layerId: string): BeginTransformResult {
+ const document = this.deps.getDocument();
+ const leaf = lookupDocumentLeaf(document, layerId);
+ if (this.disposed || !document || !leaf) {
+ return this.disposed ? 'busy' : 'missing';
+ }
+ if (leaf.effectiveLocked) {
+ return 'locked';
+ }
+ const persisted = isTransformEligible(leaf.layer, document);
+ if (!persisted && !isTransformEligible(leaf.layer, document, this.deps.peekCacheRect(layerId))) {
+ return 'ineligible';
+ }
+ if (
+ this.deps.isInteractionLocked() ||
+ this.deps.isGestureActive() ||
+ this.deps.hasFloatingSelection() ||
+ !this.deps.canEdit()
+ ) {
+ return 'busy';
+ }
+ if (document.selectedLayerId !== layerId) {
+ this.deps.select(layerId);
+ }
+ this.deps.enterTool();
+ if (this.deps.session.get()?.layerId !== layerId) {
+ this.cancel();
+ if (persisted) {
+ this.begin(layerId);
+ }
+ if (this.deps.session.get()?.layerId !== layerId) {
+ this.deps.pending.set(layerId);
+ }
+ }
+ return 'started';
+ }
+
+ /**
+ * Every document change settles a wait: the session opens once the layer's pixels are persisted, if it is still
+ * the selection, transform is the tool the user is on and no session opened meanwhile; otherwise the wait ends.
+ */
+ onDocumentChanged(): void {
+ const layerId = this.deps.pending.get();
+ if (layerId === null) {
+ return;
+ }
+ const document = this.deps.getDocument();
+ const layer = getDocumentLayer(document, layerId);
+ if (
+ !document ||
+ !layer ||
+ document.selectedLayerId !== layerId ||
+ this.deps.getUserToolId() !== 'transform' ||
+ this.deps.session.get() !== null
+ ) {
+ this.deps.pending.set(null);
+ } else if (isTransformEligible(layer, document)) {
+ this.deps.pending.set(null);
+ this.begin(layerId);
+ }
+ }
+
+ /** A genuine switch to another tool ends the wait; temporary holds never reach here. */
+ onToolSwitch(to: ToolId): void {
+ if (to !== 'transform') {
+ this.deps.pending.set(null);
+ }
+ }
+
+ /** Escape ends a wait once no session is open; returns whether it did. */
+ onEscape(): boolean {
+ if (this.deps.pending.get() === null) {
+ return false;
+ }
+ this.deps.pending.set(null);
+ return true;
+ }
+
+ /** A replay lands on a document the request never saw, so the wait ends. */
+ onReplay(): void {
+ this.deps.pending.set(null);
+ }
+
+ /** A replaced document drops the session and the wait without restoring anything. */
+ onDocumentReplaced(): void {
+ this.deps.session.set(null);
+ this.deps.pending.set(null);
+ }
+
+ /** Pixels that could not be persisted, with no retry to follow, will not open a session; say so. */
+ onUploadFailed(layerId: string): void {
+ if (this.deps.pending.get() === layerId) {
+ this.deps.pending.set(null);
+ this.deps.reportRefusal('not-ready');
+ }
+ }
+
update(transform: LayerTransform): void {
const session = this.deps.session.get();
if (this.disposed || !session) {
@@ -199,6 +325,9 @@ export class TransformEditingController {
redo: () => this.replay(forward, afterRect),
undo: () => this.replay(backward, beforeRect),
});
+ if (result.status === 'committed') {
+ this.deps.rebaseLineEnd(layer.id, session.transform);
+ }
this.settle(result.status);
} finally {
txn.end();
@@ -223,6 +352,7 @@ export class TransformEditingController {
return;
}
this.cancel();
+ this.deps.pending.set(null);
this.disposed = true;
}
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeVisible.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeVisible.test.ts
index fbf8f8fbe7..a7f8c540eb 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeVisible.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeVisible.test.ts
@@ -14,10 +14,11 @@ import {
canMergeSelectedRasters,
canMergeVisibleRasters,
getMergeVisibleRasterLayers,
+ inpaintMaskMergeEligibility,
} from './mergeVisible';
const raster = (id: string, overrides: Partial<CanvasLayerContract> = {}) => layerContract(id, 'raster', overrides);
-const mask = (id: string) => layerContract(id, 'inpaint_mask');
+const mask = (id: string, overrides: Partial<CanvasLayerContract> = {}) => layerContract(id, 'inpaint_mask', overrides);
const gradientRaster = (id: string): CanvasLayerContract =>
raster(id, {
source: {
@@ -126,8 +127,18 @@ describe('merge-masks eligibility', () => {
layerContract('region', 'regional_guidance'),
mask('empty'),
raster('raster'),
+ mask('noisy', { noise: { isEnabled: true, level: 0.3 } } as Partial<CanvasLayerContract>),
+ mask('noisyToo', {
+ mask: { bitmap: null, fill: { color: '#00ff00', style: 'grid' } },
+ noise: { isEnabled: true, level: 0.3 },
+ } as Partial<CanvasLayerContract>),
+ mask('noisier', { noise: { isEnabled: true, level: 0.6 } } as Partial<CanvasLayerContract>),
+ mask('quietNoise', { noise: { isEnabled: false, level: 0.6 } } as Partial<CanvasLayerContract>),
+ mask('limited', { denoise: { isEnabled: true, limit: 0.4 } } as Partial<CanvasLayerContract>),
+ mask('unlimited', { denoise: { isEnabled: false, limit: 0.4 } } as Partial<CanvasLayerContract>),
];
const can = (ids: string[]) => canMergeInpaintMasks(leavesOf(nodes), new Set(ids), hasContent);
+ const eligibility = (ids: string[]) => inpaintMaskMergeEligibility(leavesOf(nodes), new Set(ids), hasContent);
it('accepts two or more contributing, unlocked masks with pixels in any groups', () => {
expect(can(['top', 'inA', 'inB'])).toBe(true);
@@ -146,5 +157,25 @@ describe('merge-masks eligibility', () => {
['a mask without pixels', ['top', 'empty']],
])('refuses a selection holding %s', (_, ids) => {
expect(can(ids)).toBe(false);
+ expect(eligibility(ids)).toBe('ineligible');
+ });
+
+ it('accepts masks whose enabled noise and denoise match, whatever their fill or disabled modifiers', () => {
+ expect(can(['noisy', 'noisyToo'])).toBe(true);
+ expect(can(['top', 'quietNoise', 'unlimited'])).toBe(true);
+ });
+
+ it.each([
+ ['noise levels', ['noisy', 'noisier']],
+ ['enabled and absent noise', ['top', 'noisy']],
+ ['enabled and disabled noise', ['noisier', 'quietNoise']],
+ ['enabled and disabled denoise limits', ['limited', 'unlimited']],
+ ])('refuses different %s as a settings mismatch', (_, ids) => {
+ expect(can(ids)).toBe(false);
+ expect(eligibility(ids)).toBe('settings-differ');
+ });
+
+ it('names an ineligible mask before a settings mismatch', () => {
+ expect(eligibility(['noisy', 'noisier', 'locked'])).toBe('ineligible');
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeVisible.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeVisible.ts
index c1396442cb..a648336189 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeVisible.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeVisible.ts
@@ -1,4 +1,8 @@
-import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';
+import type {
+ CanvasDocumentContractV3,
+ CanvasInpaintMaskLayerContract,
+ CanvasLayerContract,
+} from '@workbench/canvas-engine/contracts';
import type { SemanticLeaf } from '@workbench/canvas-engine/document-model/semanticLeaf';
import { getDocumentIndex } from './documentIndex';
@@ -82,18 +86,30 @@ export const canMergeSelectedRasters = (
hasContent(leaf.id)
);
+/**
+ * What generation applies across an inpaint mask's area besides its coverage: the enabled noise level and denoise
+ * limit (a disabled modifier keeps its tuned value out of generation). Fill and opacity are display-only.
+ */
+const maskGenerationSettings = (layer: CanvasInpaintMaskLayerContract): string =>
+ `${layer.noise?.isEnabled ? layer.noise.level : '-'}|${layer.denoise?.isEnabled ? layer.denoise.limit : '-'}`;
+
/**
* Whether merge-masks can take the exact selection: two or more inpaint masks, each contributing, unlocked and holding
- * pixels, wherever they sit in the stack. Regional guidance never merges this way.
+ * pixels, wherever they sit in the stack (`ineligible` otherwise), whose generation settings agree, since the merged
+ * mask carries one set over the whole union (`settings-differ`, reported only for an otherwise eligible selection).
+ * Regional guidance never merges this way.
*/
-export const canMergeInpaintMasks = (
+export type InpaintMaskMergeEligibility = 'eligible' | 'ineligible' | 'settings-differ';
+
+export const inpaintMaskMergeEligibility = (
leaves: readonly SemanticLeaf[],
selectedLayerIds: ReadonlySet<string>,
hasContent: HasMergeVisibleContent
-): boolean => {
+): InpaintMaskMergeEligibility => {
if (selectedLayerIds.size < 2) {
- return false;
+ return 'ineligible';
}
+ const settings = new Set<string>();
let found = 0;
for (const leaf of leaves) {
if (!selectedLayerIds.has(leaf.id)) {
@@ -105,10 +121,20 @@ export const canMergeInpaintMasks = (
leaf.effectiveLocked ||
!hasContent(leaf.id)
) {
- return false;
+ return 'ineligible';
}
+ settings.add(maskGenerationSettings(leaf.layer));
found += 1;
}
// A selected group or a missing id is not a mask leaf.
- return found === selectedLayerIds.size;
+ if (found !== selectedLayerIds.size) {
+ return 'ineligible';
+ }
+ return settings.size === 1 ? 'eligible' : 'settings-differ';
};
+
+export const canMergeInpaintMasks = (
+ leaves: readonly SemanticLeaf[],
+ selectedLayerIds: ReadonlySet<string>,
+ hasContent: HasMergeVisibleContent
+): boolean => inpaintMaskMergeEligibility(leaves, selectedLayerIds, hasContent) === 'eligible';
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 2687dfa21e..0fb3632177 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
@@ -60,6 +60,7 @@ import type { StrokeCommittedEvent } from './tools/tool';
import { createBitmapStore } from './document/bitmapStore';
import { mergeDownMatrix } from './document/mergeDown';
import { createCanvasEngine as createCoreCanvasEngine } from './engine';
+import { RASTERIZATION_RETRY_BASE_MS } from './layerRasterizer';
interface EngineStore {
dispatch(action: EngineTestAction): void;
@@ -753,6 +754,113 @@ describe('createCanvasEngine', () => {
engine.lifecycle.dispose();
});
+ it('retries a layer whose image failed only once its backoff ends, and shows it once the image loads', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+ try {
+ const raf = createControllableRaf();
+ vi.stubGlobal('requestAnimationFrame', raf.requestFrame);
+ vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);
+ const document = { ...makeDoc(), stacks: stacksFrom([rasterLayer('flaky')]), selectedLayerId: 'flaky' };
+ const { projectId, store } = createReducerBackedStore(document);
+ let available = false;
+ const imageResolver = vi.fn(() =>
+ available ? Promise.resolve(new Blob()) : Promise.reject(new Error('backend restarting'))
+ );
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ bitmapStore: createSpyBitmapStore(),
+ imageResolver,
+ projectId,
+ reportError: vi.fn(),
+ store,
+ });
+ engine.surface.attach(createInputCanvas().element, createInputCanvas().element);
+ // The shared helper waits on a timer, which these fake timers hold.
+ const settle = async () => {
+ for (let tick = 0; tick < 50; tick += 1) {
+ await Promise.resolve();
+ }
+ };
+ const renderFrames = async () => {
+ for (let frame = 0; frame < 3; frame += 1) {
+ engine.viewport.getViewport().zoomAtPoint(1 + frame / 10, { x: 0, y: 0 });
+ raf.flush();
+ await settle();
+ }
+ };
+
+ await renderFrames();
+ expect(imageResolver).toHaveBeenCalledOnce();
+ expect(engine.stores.thumbnailStatus.get('flaky')).toBe('error');
+
+ // Frames inside the backoff never read the image again.
+ vi.advanceTimersByTime(RASTERIZATION_RETRY_BASE_MS - 1);
+ await renderFrames();
+ expect(imageResolver).toHaveBeenCalledOnce();
+
+ // Its end invalidates the layer by itself, and the next frame reads the image, which now loads.
+ available = true;
+ vi.advanceTimersByTime(1);
+ raf.flush();
+ await settle();
+ expect(imageResolver).toHaveBeenCalledTimes(2);
+ expect(engine.stores.thumbnailStatus.get('flaky')).toBe('ready');
+ await renderFrames();
+ expect(imageResolver).toHaveBeenCalledTimes(2);
+ engine.lifecycle.dispose();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('keeps Merge down unreadable past the backoff for a layer nobody redraws, and merges once its image loads', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+ try {
+ const document = { ...makeDoc(), stacks: stacksFrom([rasterLayer('upper'), rasterLayer('flaky')]) };
+ const { projectId, store } = createReducerBackedStore(document);
+ let available = false;
+ const imageResolver = vi.fn((imageName: string) =>
+ imageName !== 'flaky' || available
+ ? Promise.resolve(new Blob())
+ : Promise.reject(new Error('backend restarting'))
+ );
+ const reportError = vi.fn();
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ bitmapStore: createSpyBitmapStore(),
+ imageResolver,
+ projectId,
+ reportError,
+ store,
+ });
+ const settle = async () => {
+ for (let tick = 0; tick < 50; tick += 1) {
+ await Promise.resolve();
+ }
+ };
+ // No surface is attached, so nothing redraws either layer.
+ expect((await engine.exports.exportLayerPixels('upper')).status).toBe('ok');
+ expect((await engine.exports.exportLayerPixels('flaky')).status).toBe('unreadable');
+ expect(await engine.layers.mergeLayerDown('upper')).toBe('unreadable');
+
+ vi.advanceTimersByTime(RASTERIZATION_RETRY_BASE_MS);
+ // Past the backoff it still cannot be read, and asking tries the image again in the background.
+ expect(await engine.layers.mergeLayerDown('upper')).toBe('unreadable');
+ await settle();
+ expect(imageResolver.mock.calls.filter(([name]) => name === 'flaky')).toHaveLength(2);
+ expect(reportError.mock.calls).toHaveLength(1);
+
+ available = true;
+ vi.advanceTimersByTime(RASTERIZATION_RETRY_BASE_MS * 2);
+ expect(await engine.layers.mergeLayerDown('upper')).toBe('unreadable');
+ await settle();
+ expect(await engine.layers.mergeLayerDown('upper')).toBe('merged');
+ engine.lifecycle.dispose();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('settles a claimed color sample on release, after the sampling gesture ends', async () => {
const raf = createControllableRaf();
vi.stubGlobal('requestAnimationFrame', raf.requestFrame);
@@ -834,7 +942,7 @@ describe('createCanvasEngine', () => {
engine.lifecycle.dispose();
});
- it('sends a pick’s commit or cancel only to the sink that took its first preview', async () => {
+ it('sends a pick’s commit or cancel only to the sink that took its first preview, through real pointer events', async () => {
const raf = createControllableRaf();
vi.stubGlobal('requestAnimationFrame', raf.requestFrame);
vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);
@@ -987,7 +1095,7 @@ describe('createCanvasEngine', () => {
engine.lifecycle.dispose();
});
- it('returns typed not-ready when asynchronous raster cache preparation fails', async () => {
+ it('returns typed unreadable when asynchronous raster cache preparation fails', async () => {
const { store } = createReactiveStore(makeDoc());
const engine = createCanvasEngine({
backend: createTestStubRasterBackend(),
@@ -999,7 +1107,7 @@ describe('createCanvasEngine', () => {
const documentSnapshot = engine.document.captureSnapshot();
await expect(engine.exports.captureRasterSnapshot(documentSnapshot!, ['a'])).resolves.toEqual({
- status: 'not-ready',
+ status: 'unreadable',
});
engine.lifecycle.dispose();
});
@@ -1237,6 +1345,22 @@ describe('createCanvasEngine', () => {
engine.lifecycle.dispose();
});
+ it('refuses a composite export with a layer whose image cannot be read as unreadable', async () => {
+ const { store } = createReactiveStore(makeDoc());
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ imageResolver: () => Promise.reject(new Error('image deleted')),
+ projectId: 'p1',
+ reportError: vi.fn(),
+ store,
+ });
+
+ await expect(engine.exports.exportRasterComposite({ bounds: 'content' })).resolves.toEqual({
+ status: 'unreadable',
+ });
+ engine.lifecycle.dispose();
+ });
+
it('uploads per-generation composites through the intermediate seam, not the durable one', async () => {
// Generation composites have no document references and must be reclaimable; only layer-owned pixels require
// durable uploads.
@@ -1600,7 +1724,7 @@ describe('createCanvasEngine', () => {
store,
});
- expect(await engine.exports.exportLayerPixels('shape')).toEqual({ status: 'not-ready' });
+ expect(await engine.exports.exportLayerPixels('shape')).toEqual({ status: 'unreadable' });
expect((await engine.exports.exportLayerPixels('shape')).status).toBe('ok');
engine.lifecycle.dispose();
});
@@ -2235,7 +2359,12 @@ describe('createCanvasEngine', () => {
});
const before = structuredClone(engine.document.getDocument()!);
- expect(await engine.layers.cropAllLayersToBbox()).toEqual({ cropped: 3, skippedLocked: 1, status: 'cropped' });
+ expect(await engine.layers.cropAllLayersToBbox()).toEqual({
+ cropped: 3,
+ skippedLocked: 1,
+ skippedUnreadable: 0,
+ status: 'cropped',
+ });
const cropped = structuredClone(engine.document.getDocument()!);
expect(getDocumentLayer(cropped, 'a')).toMatchObject({ source: { bitmap: null, offset: { x: 8, y: 5 } } });
expect(getDocumentLayer(cropped, 'outside')).toMatchObject({ isEnabled: false, source: { bitmap: null } });
@@ -2254,7 +2383,47 @@ describe('createCanvasEngine', () => {
engine.lifecycle.dispose();
});
- it('cropLayerToBbox returns empty without mutation when the layer and bbox do not overlap', async () => {
+ it('cropAllLayersToBbox crops around a layer whose image cannot be read, and reports the read failure once', async () => {
+ const document = {
+ ...makeDoc(),
+ bbox: { height: 8, width: 8, x: 0, y: 0 },
+ stacks: stacksFrom([rasterLayer('broken'), rasterLayer('a')]),
+ };
+ const { projectId, store } = createReducerBackedStore(document);
+ const reportError = vi.fn();
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ bitmapStore: createSpyBitmapStore(),
+ imageResolver: (imageName) =>
+ imageName === 'broken' ? Promise.reject(new Error('image deleted')) : Promise.resolve(new Blob()),
+ projectId,
+ reportError,
+ store,
+ });
+ const broken = getDocumentLayer(engine.document.getDocument()!, 'broken');
+
+ expect(await engine.layers.cropAllLayersToBbox()).toEqual({
+ cropped: 1,
+ skippedLocked: 0,
+ skippedUnreadable: 1,
+ status: 'cropped',
+ });
+ expect(getDocumentLayer(engine.document.getDocument()!, 'broken')).toBe(broken);
+ expect(getDocumentLayer(engine.document.getDocument()!, 'a')).toMatchObject({ source: { type: 'paint' } });
+ // Asking again reads the image again, but the same failure raises no second notice.
+ expect(await engine.layers.cropAllLayersToBbox()).toEqual({
+ skippedLocked: 0,
+ skippedUnreadable: 1,
+ status: 'nothing',
+ });
+ const readFailures = reportError.mock.calls.filter(
+ ([report]) => (report as { message: string }).message === 'Layer thumbnail rasterization failed'
+ );
+ expect(readFailures).toHaveLength(1);
+ engine.lifecycle.dispose();
+ });
+
+ it('cropLayerToBbox refuses without mutation a layer that lies wholly outside the frame', async () => {
const document = { ...makeDoc(), bbox: { height: 5, width: 5, x: 50, y: 50 } };
const { projectId, store } = createReducerBackedStore(document);
const bitmapStore = createSpyBitmapStore();
@@ -2267,14 +2436,14 @@ describe('createCanvasEngine', () => {
});
const before = engine.document.getDocument();
- expect(await engine.layers.cropLayerToBbox('a')).toEqual({ status: 'empty' });
+ expect(await engine.layers.cropLayerToBbox('a')).toEqual({ status: 'outside-frame' });
expect(engine.document.getDocument()).toBe(before);
expect(engine.stores.canUndo.get()).toBe(false);
expect(bitmapStore.markLayerDirty).not.toHaveBeenCalled();
engine.lifecycle.dispose();
});
- it('cropLayerToBbox reports missing, locked, unsupported, and not-ready layers explicitly', async () => {
+ it('cropLayerToBbox reports missing, locked, unsupported, and unreadable layers explicitly', async () => {
// A polygon without enough points to fill has no raster to crop.
const polygon: CanvasLayerSourceContract = {
fill: '#000',
@@ -2289,7 +2458,7 @@ describe('createCanvasEngine', () => {
const layers = [
{ ...rasterLayer('locked'), isLocked: true },
{ ...rasterLayer('polygon'), source: polygon },
- rasterLayer('pending'),
+ rasterLayer('unreadable'),
];
const document = { ...makeDoc(), stacks: stacksFrom(layers) };
const { projectId, store } = createReducerBackedStore(document);
@@ -2303,7 +2472,7 @@ describe('createCanvasEngine', () => {
expect(await engine.layers.cropLayerToBbox('missing')).toEqual({ status: 'missing' });
expect(await engine.layers.cropLayerToBbox('locked')).toEqual({ status: 'locked' });
expect(await engine.layers.cropLayerToBbox('polygon')).toEqual({ status: 'unsupported' });
- expect(await engine.layers.cropLayerToBbox('pending')).toEqual({ status: 'not-ready' });
+ expect(await engine.layers.cropLayerToBbox('unreadable')).toEqual({ status: 'unreadable' });
engine.lifecycle.dispose();
});
@@ -3381,6 +3550,109 @@ describe('engine-owned pixel editing', () => {
h.engine.lifecycle.dispose();
});
+ it('starts a Shift-click line from the last stroke end on a layer nudged 100 px since', async () => {
+ const h = createRasterImageEraserHarness({ adjustments: [], blendMode: 'normal', opacity: 1 });
+ await h.publishInitialCache();
+ let xs: number[] = [];
+ vi.stubGlobal(
+ 'Path2D',
+ class RecordingPath2D {
+ closePath() {}
+ lineTo(x: number) {
+ xs.push(x);
+ }
+ moveTo(x: number) {
+ xs.push(x);
+ }
+ quadraticCurveTo(_cx: number, _cy: number, x: number) {
+ xs.push(x);
+ }
+ }
+ );
+ const strokeSpan = (x: number, shiftKey: boolean): number => {
+ xs = [];
+ h.overlay.fire('pointerdown', { ...pointerAt(x, 20), shiftKey });
+ h.overlay.fire('pointerup', { ...pointerAt(x, 20, { buttons: 0 }), shiftKey });
+ return Math.max(...xs) - Math.min(...xs);
+ };
+
+ h.engine.tools.setTool('brush');
+ const dab = strokeSpan(12, false);
+ expect(h.engine.layers.nudgeSelectedLayer(100, 0).status).toBe('committed');
+ // The stroke ended at x=12 on the layer, which now sits at x=112: the line runs 30 px, not 130.
+ const line = strokeSpan(142, true);
+ expect(line).toBeGreaterThan(dab + 25);
+ expect(line).toBeLessThan(dab + 35);
+ h.engine.lifecycle.dispose();
+ });
+
+ it.each([
+ [
+ 'cropped',
+ async (h: ReturnType<typeof createPixelEditHarness>) => {
+ expect(h.engine.layers.nudgeSelectedLayer(30, 0).status).toBe('committed');
+ expect(await h.engine.layers.cropLayerToBbox('paint')).toEqual({ status: 'cropped' });
+ },
+ ],
+ [
+ 'transformed and applied',
+ (h: ReturnType<typeof createPixelEditHarness>) => {
+ expect(h.engine.layers.beginTransform('paint')).toBe('started');
+ expect(h.engine.stores.transformSession.get()?.layerId).toBe('paint');
+ h.engine.layers.updateTransformSession({ rotation: 0, scaleX: 1, scaleY: 1, x: 30, y: 0 });
+ h.engine.layers.applyTransform();
+ expect(h.engine.stores.transformSession.get()).toBeNull();
+ expect(h.engine.history.getEntries().past.at(-1)).toBe('Transform layer');
+ },
+ ],
+ ])('starts a Shift-click line where the last stroke ended once its paint layer is %s', async (_label, edit) => {
+ const h = createPixelEditHarness({
+ blendMode: 'normal',
+ id: 'paint',
+ isEnabled: true,
+ isLocked: false,
+ name: 'Paint',
+ opacity: 1,
+ source: { bitmap: { height: 10, imageName: 'paint-bitmap', width: 20 }, offset: { x: 5, y: 15 }, type: 'paint' },
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
+ type: 'raster',
+ });
+ await h.publishInitialCache();
+ let xs: number[] = [];
+ vi.stubGlobal(
+ 'Path2D',
+ class RecordingPath2D {
+ closePath() {}
+ lineTo(x: number) {
+ xs.push(x);
+ }
+ moveTo(x: number) {
+ xs.push(x);
+ }
+ quadraticCurveTo(_cx: number, _cy: number, x: number) {
+ xs.push(x);
+ }
+ }
+ );
+ const strokeSpan = (x: number, shiftKey: boolean): number => {
+ xs = [];
+ h.overlay.fire('pointerdown', { ...pointerAt(x, 20), shiftKey });
+ h.overlay.fire('pointerup', { ...pointerAt(x, 20, { buttons: 0 }), shiftKey });
+ return Math.max(...xs) - Math.min(...xs);
+ };
+
+ h.engine.tools.setTool('brush');
+ const dab = strokeSpan(12, false);
+ await edit(h);
+ // Both edits rebuild the layer at an identity transform with the stroke's pixels 30 px to the right, at x=42.
+ expect(getDocumentLeaves(h.engine.document.getDocument()!)[0]?.transform).toMatchObject({ x: 0, y: 0 });
+ h.engine.tools.setTool('brush');
+ const line = strokeSpan(72, true);
+ expect(line).toBeGreaterThan(dab + 25);
+ expect(line).toBeLessThan(dab + 35);
+ h.engine.lifecycle.dispose();
+ });
+
it('persists and releases a materialized image erase when a thumbnail observer throws', async () => {
const h = createRasterImageEraserHarness();
await h.publishInitialCache();
@@ -7605,6 +7877,69 @@ describe('structural raster publication failure atomicity', () => {
await expectLayerCacheExact(engine, source.id, croppedCache);
engine.lifecycle.dispose();
});
+
+ it('crop all right after a stroke waits for its upload, so the acknowledgement cannot make it stale', async () => {
+ const painted: CanvasRasterLayerContractV2 = {
+ ...(rasterLayer('painted') as CanvasRasterLayerContractV2),
+ source: { bitmap: { height: 10, imageName: 'painted-before', width: 10 }, offset: { x: 0, y: 0 }, type: 'paint' },
+ };
+ const document: CanvasDocumentContractV3 = {
+ ...makeDoc(),
+ bbox: { height: 7, width: 6, x: 2, y: 3 },
+ stacks: stacksFrom([painted, rasterLayer('slow')]),
+ };
+ const reducer = createReducerBackedStore(document);
+ const upload = createDeferred<{ height: number; imageName: string; width: number }>();
+ const uploadImage = vi.fn(() => upload.promise);
+ let placed: { offset: { x: number; y: number }; surface: RasterSurface } | null = null;
+ const bitmapStore = createBitmapStore({
+ debounceMs: 1500,
+ dispatch: createTestMutationPort(reducer.store, reducer.projectId).dispatch,
+ encodeSurface: (surface) =>
+ Promise.resolve(new Blob([`${surface.width}x${surface.height}`], { type: 'image/png' })),
+ getLayerSource: (layerId) => {
+ const layer = getDocumentLeaves(
+ reducer.store.getState().projects.find((project) => project.id === reducer.projectId)?.canvas.document
+ ).find((candidate) => candidate.id === layerId);
+ return layer?.type === 'raster' ? layer.source : null;
+ },
+ getLayerSurface: () => placed,
+ hashBlob: (blob) => blob.text(),
+ maxUploadAttempts: 1,
+ retryDelaysMs: [],
+ sleep: () => Promise.resolve(),
+ uploadImage,
+ });
+ // The second layer's image is still decoding, so crop all is mid-read when the acknowledgement could land.
+ const slowImage = createDeferred<Blob>();
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ bitmapStore,
+ imageResolver: (imageName) => (imageName === 'slow' ? slowImage.promise : Promise.resolve(new Blob())),
+ projectId: reducer.projectId,
+ store: reducer.store,
+ });
+ const before = await snapshotLayerCache(engine, painted.id);
+ placed = { offset: { x: before.rect.x, y: before.rect.y }, surface: before.surface };
+ // A stroke marks the layer dirty and its debounced upload starts.
+ bitmapStore.markLayerDirty(painted.id);
+ void bitmapStore.flushPendingUploads();
+ for (let tick = 0; tick < 50 && uploadImage.mock.calls.length === 0; tick += 1) {
+ await Promise.resolve();
+ }
+ expect(uploadImage).toHaveBeenCalledOnce();
+
+ const crop = engine.layers.cropAllLayersToBbox();
+ upload.resolve({ height: 10, imageName: 'painted-after', width: 10 });
+ for (let tick = 0; tick < 50; tick += 1) {
+ await Promise.resolve();
+ }
+ slowImage.resolve(new Blob());
+
+ await expect(crop).resolves.toEqual({ cropped: 2, skippedLocked: 0, skippedUnreadable: 0, status: 'cropped' });
+ expect(engine.history.getEntries().past).toEqual(['Crop all layers to frame']);
+ engine.lifecycle.dispose();
+ });
});
describe('mergeVisibleRasterLayers', () => {
@@ -15893,6 +16228,21 @@ describe('beginTransform', () => {
return { dispatch, engine };
};
+ it('refuses as busy while interaction is locked, leaving the selection and tool unchanged', () => {
+ const { dispatch, engine } = setup([rasterLayer('a'), rasterLayer('b')], 'a');
+ engine.tools.setInteractionLocked(true);
+ // The lock itself parks the surface on the view tool.
+ const lockedTool = engine.stores.activeTool.get();
+ dispatch.mockClear();
+
+ expect(engine.layers.beginTransform('b')).toBe('busy');
+ expect(dispatch).not.toHaveBeenCalled();
+ expect(engine.document.getDocument()?.selectedLayerId).toBe('a');
+ expect(engine.stores.activeTool.get()).toBe(lockedTool);
+ expect(engine.stores.transformSession.get()).toBeNull();
+ engine.lifecycle.dispose();
+ });
+
it('selects the layer and opens its session now, even with transform already active and no session', () => {
const { engine } = setup([rasterLayer('a'), rasterLayer('b')], null);
engine.tools.setTool('transform');
@@ -15905,39 +16255,11 @@ describe('beginTransform', () => {
engine.lifecycle.dispose();
});
- it('cancels a session on another layer, dropping its preview, before opening one on the target', () => {
- const { dispatch, engine } = setup([rasterLayer('a'), rasterLayer('b')], 'a');
- engine.tools.setTool('transform');
- engine.layers.updateTransformSession({ rotation: 0, scaleX: 2, scaleY: 2, x: 5, y: 6 });
- dispatch.mockClear();
-
- expect(engine.layers.beginTransform('b')).toBe('started');
- expect(engine.stores.transformSession.get()).toMatchObject({
- layerId: 'b',
- transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
- });
- // Only the selection changed: the abandoned preview on `a` never landed.
- expect(dispatch.mock.calls.map(([action]) => action.type)).toEqual(['setCanvasSelectedLayer']);
- expect(getDocumentLayer(engine.document.getDocument(), 'a')?.transform.scaleX).toBe(1);
- engine.lifecycle.dispose();
- });
-
- it.each([
- ['locked', [{ ...rasterLayer('b'), isLocked: true }], 'locked'],
- ['a mask', [thumbnailMaskLayer('b', 'inpaint_mask')], 'ineligible'],
- ['missing', [rasterLayer('a')], 'missing'],
- ] as const)('refuses %s without selecting or switching tools', (_, layers, status) => {
- const { dispatch, engine } = setup([rasterLayer('a'), ...layers.filter((layer) => layer.id !== 'a')], 'a');
-
- expect(engine.layers.beginTransform('b')).toBe(status);
- expect(dispatch).not.toHaveBeenCalled();
- expect(engine.stores.activeTool.get()).not.toBe('transform');
- expect(engine.stores.transformSession.get()).toBeNull();
- engine.lifecycle.dispose();
- });
-
- /** Paints a stroke onto a new layer, then asks for its transform before persistence acknowledges the pixels. */
- const strokeThenTransform = (options: { uploadImage?: () => Promise<never> } = {}) => {
+ /**
+ * Paints a stroke onto a new layer (or an empty paint layer that already exists), then asks for its transform
+ * before persistence acknowledges the pixels.
+ */
+ const strokeThenTransform = (options: { existingLayer?: boolean; uploadImage?: () => Promise<never> } = {}) => {
const raf = createControllableRaf();
vi.stubGlobal('requestAnimationFrame', raf.requestFrame);
vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);
@@ -15956,10 +16278,14 @@ describe('beginTransform', () => {
windowListeners.set(type, listener)
);
vi.stubGlobal('removeEventListener', (type: string) => windowListeners.delete(type));
+ const existing: CanvasLayerContract = {
+ ...(rasterLayer('paint') as CanvasRasterLayerContractV2),
+ source: { bitmap: null, type: 'paint' },
+ };
const { dispatch, projectId, store } = createReducerBackedStore({
...makeDoc(),
- selectedLayerId: null,
- stacks: stacksFrom([]),
+ selectedLayerId: options.existingLayer ? existing.id : null,
+ stacks: stacksFrom(options.existingLayer ? [existing] : []),
});
const engine = createCanvasEngine({
backend: createTestStubRasterBackend(),
@@ -16033,6 +16359,17 @@ describe('beginTransform', () => {
h.engine.lifecycle.dispose();
});
+ it('stops waiting on an undo, whose replay lands on a document the request never saw', async () => {
+ // The layer survives the undo, still selected under transform, so only the replay itself ends the wait.
+ const h = strokeThenTransform({ existingLayer: true });
+ expect(h.layerId).toBe('paint');
+ await h.engine.history.undo();
+ expect(h.engine.interaction.get('pendingTransformLayerId')).toBeNull();
+ h.persist();
+ expect(h.sessionLayerId()).toBeNull();
+ h.engine.lifecycle.dispose();
+ });
+
it('keeps waiting through retried upload failures, and stops with a refusal once no retry follows', async () => {
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
try {
@@ -16079,43 +16416,6 @@ describe('beginTransform', () => {
vi.useRealTimers();
}
});
-
- it('refuses as busy while interaction is locked, leaving the selection and tool unchanged', () => {
- const { dispatch, engine } = setup([rasterLayer('a'), rasterLayer('b')], 'a');
- engine.tools.setInteractionLocked(true);
- // The lock itself parks the surface on the view tool.
- const lockedTool = engine.stores.activeTool.get();
- dispatch.mockClear();
-
- expect(engine.layers.beginTransform('b')).toBe('busy');
- expect(dispatch).not.toHaveBeenCalled();
- expect(engine.document.getDocument()?.selectedLayerId).toBe('a');
- expect(engine.stores.activeTool.get()).toBe(lockedTool);
- expect(engine.stores.transformSession.get()).toBeNull();
- engine.lifecycle.dispose();
- });
-
- it('refuses as busy while document edits are locked, leaving the selection and tool unchanged', () => {
- const { dispatch, engine } = setup([rasterLayer('a'), rasterLayer('b')], 'a');
- engine.tools.setTool('brush');
- engine.stores.documentEditingLocked.set(true);
- dispatch.mockClear();
-
- expect(engine.layers.beginTransform('b')).toBe('busy');
- expect(dispatch).not.toHaveBeenCalled();
- expect(engine.stores.activeTool.get()).toBe('brush');
- expect(engine.stores.transformSession.get()).toBeNull();
- engine.lifecycle.dispose();
- });
-
- it('refuses as busy once disposed, without touching the selection', () => {
- const { dispatch, engine } = setup([rasterLayer('a'), rasterLayer('b')], 'a');
- engine.lifecycle.dispose();
- dispatch.mockClear();
-
- expect(engine.layers.beginTransform('b')).toBe('busy');
- expect(dispatch).not.toHaveBeenCalled();
- });
});
describe('transform session', () => {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index 5081695955..5b5772edd8 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -1,5 +1,4 @@
import type {
- BeginTransformResult,
CanvasEditRefusal,
CanvasHistoryReplayStatus,
CanvasHistoryCapability,
@@ -20,7 +19,6 @@ import type {
CanvasSurfaceAttachOptions,
CanvasSurfaceCapability,
CanvasViewportCapability,
- ColorSamplePhase,
BooleanRasterOperation,
BooleanRasterResult,
CopyLayerResult,
@@ -85,6 +83,7 @@ import type {
CanvasLayerContract,
CanvasLayerSourceContract,
} from '@workbench/canvas-engine/contracts';
+import type { LayerCacheReadiness } from '@workbench/canvas-engine/controllers/editSteps';
import type { CreatePath2D } from '@workbench/canvas-engine/freehand';
import type { ColorSampleProviders, ColorSampler } from '@workbench/canvas-engine/render/colorSample';
import type { AdjustmentRefusal } from '@workbench/canvas-engine/render/exactAdjustments';
@@ -100,6 +99,7 @@ import type { CanvasProjectMutationPort } from '@workbench/canvasProjectMutation
import { createItemId } from '@platform/browser/randomUuid';
import { areJsonValuesStructurallyEqual } from '@platform/core/json';
+import { ColorSampleController } from '@workbench/canvas-engine/controllers/colorSampleController';
import { PixelEditController } from '@workbench/canvas-engine/controllers/controlPixelController';
import { EditingController } from '@workbench/canvas-engine/controllers/editingController';
import { FilterResultController } from '@workbench/canvas-engine/controllers/filterResultController';
@@ -117,6 +117,7 @@ import {
createCanvasMutationContext,
type CanvasMutationContext,
} from '@workbench/canvas-engine/controllers/mutationContext';
+import { PaintLineEndController } from '@workbench/canvas-engine/controllers/paintLineEndController';
import { PersistenceController } from '@workbench/canvas-engine/controllers/persistenceController';
import { PsdExportController } from '@workbench/canvas-engine/controllers/psdExportController';
import { RasterController } from '@workbench/canvas-engine/controllers/rasterController';
@@ -131,7 +132,6 @@ import { createCanvasDiagnostics } from '@workbench/canvas-engine/diagnostics';
import {
compileDocumentLeaves,
createDocumentModel,
- lookupDocumentLeaf,
type CanvasDocumentModel,
} from '@workbench/canvas-engine/document-model/documentModel';
import {
@@ -169,7 +169,10 @@ import { createMaskPatternTile } from '@workbench/canvas-engine/render/maskFill'
import { colorLoupePixels, renderOverlay } from '@workbench/canvas-engine/render/overlayRenderer';
import { trimPaintCacheToAlpha } from '@workbench/canvas-engine/render/paintCacheTrim';
import { createDomRasterBackend, type RasterBackend, type RasterSurface } from '@workbench/canvas-engine/render/raster';
-import { RasterCompositeOverBudgetError } from '@workbench/canvas-engine/render/rasterComposite';
+import {
+ RasterCompositeOverBudgetError,
+ RasterCompositeUnreadableError,
+} from '@workbench/canvas-engine/render/rasterComposite';
import { rasterizeSource, type ImageResolver, type RasterizeDeps } from '@workbench/canvas-engine/render/rasterizers';
import { fitThumbnailSize, getLayerThumbnailDisplayKey } from '@workbench/canvas-engine/render/thumbnail';
import { documentDeltaToLocal, liftSelectedPixels } from '@workbench/canvas-engine/selection/floatingSelection';
@@ -188,7 +191,7 @@ import { stepBrushSize } from '@workbench/canvas-engine/tools/paintConstants';
import { createSamTool } from '@workbench/canvas-engine/tools/samTool';
import { createShapeTool } from '@workbench/canvas-engine/tools/shapeTool';
import { createTextTool } from '@workbench/canvas-engine/tools/textTool';
-import { createTransformTool, isTransformEligible } from '@workbench/canvas-engine/tools/transformTool';
+import { createTransformTool } from '@workbench/canvas-engine/tools/transformTool';
import { FULL_DAMAGE } from '@workbench/canvas-engine/types';
import { createViewport, type Viewport } from '@workbench/canvas-engine/viewport';
@@ -199,7 +202,6 @@ import type { StrokeCommittedEvent, Tool, ToolContext } from './tools/tool';
import { createBitmapStore, type BitmapStore } from './document/bitmapStore';
import { createDocumentMirror, type DocumentMirror } from './document/documentMirror';
import { decideLayerChange, nextThumbnailDisplayToken } from './document/layerChangeDecision';
-import { canMergeInpaintMasks as canMergeInpaintMasksIn } from './document/mergeVisible';
import { getSourceBounds, getSourceContentRect, isRenderableLayer, renderableSourceOf } from './document/sources';
import { collectCanvasFontReferences, replaceCanvasFontReferences } from './fontReferences';
import { createLayerExportGuards, isSupportedExportSource } from './layerExportGuards';
@@ -645,7 +647,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
onError: (error, layerId, info) => {
// A retry may still land the pixels; only a failure no retry follows ends the wait.
if (!info.willRetry) {
- failPendingTransform(layerId);
+ editingController.transform.onUploadFailed(layerId);
}
reportError(
info.willRetry ? 'Bitmap persistence failed' : 'Bitmap persistence suspended',
@@ -665,6 +667,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
// undoable until it commits.
beforeReplay: () => {
paintLineEnds.clear();
+ editingController.transform.onReplay();
floatingSelection.cancel();
structuralController.endPreview();
},
@@ -1013,12 +1016,20 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
canEdit: () => canEditDocument(),
commitStructural: (label, forward, inverse) => commitStructural(label, forward, inverse),
ctx: mutationContext,
+ enterTool: () => setTool('transform'),
getCache: (layerId) => layerCache.get(layerId) ?? null,
getDocument: () => mirror.getDocument(),
+ getUserToolId: () => pipeline.heldRestoreToolId() ?? interactionController.getActiveToolId(),
+ hasFloatingSelection: () => floatingSelection.has(),
invalidate: (payload) => scheduler.invalidate(payload),
isGestureActive: () => pipeline.isGestureActive(),
+ isInteractionLocked: () => interactionLocked,
+ peekCacheRect: (layerId) => layerCache.peek(layerId)?.rect,
+ pending: stores.pendingTransformLayerId,
reportRefusal: reportEditRefusal,
+ rebaseLineEnd: (layerId, from) => paintLineEnds.rebase(layerId, from),
restoreCache: restoreLayerCache,
+ select: (layerId) => dispatchCanvasMutation({ id: layerId, type: 'setCanvasSelectedLayer' }),
session: stores.transformSession,
setOverride: (layerId, transform) => {
if (transform) {
@@ -1083,57 +1094,16 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
}
}
- /**
- * One-shot color claims take a pick's previews and settle on its release commit, after structural edits are
- * allowed. Escape, tool change and teardown resolve null.
- */
- let pendingColorSample: {
- previousToolId: ToolId;
- resolve: (hex: string | null) => void;
- } | null = null;
- // Where unclaimed eyedropper samples land while a workbench is attached.
- let colorSampleRouter: ((hex: string, phase: ColorSamplePhase) => boolean) | null = null;
- // Which sink took the current pick's first preview; null between picks.
- let colorPickSink: 'request' | 'router' | null = null;
- // Shift-click line starts: where the last brush or eraser stroke ended on each layer. Engine-lifetime memory,
- // kept across tool switches and forgotten on replay, document replacement and layer removal.
- const paintLineEnds = new Map<string, Vec2>();
- /**
- * A transform requested on pixels persistence has not acknowledged yet (a stroke's first upload) waits in
- * `pendingTransformLayerId`: sessions size their frame from the persisted source, so the session opens once the
- * bitmap lands, if the layer is still the selection under the transform tool (or a hold over it) with no session
- * open. Otherwise the wait ends there; a genuine tool switch, Escape, document replacement and a failed upload of
- * that layer end it too.
- */
- const openDeferredTransform = (): void => {
- const layerId = stores.pendingTransformLayerId.get();
- if (layerId === null) {
- return;
- }
- const document = mirror.getDocument();
- const layer = getDocumentLayer(document, layerId);
- // A Space, Alt or C hold only lends the surface to another tool; the user is still on transform.
- const toolId = pipeline.heldRestoreToolId() ?? interactionController.getActiveToolId();
- if (
- !document ||
- !layer ||
- document.selectedLayerId !== layerId ||
- toolId !== 'transform' ||
- stores.transformSession.get() !== null
- ) {
- stores.pendingTransformLayerId.set(null);
- } else if (isTransformEligible(layer, document)) {
- stores.pendingTransformLayerId.set(null);
- beginTransformSession(layerId);
- }
- };
- /** A pending transform whose pixels could not be persisted will not open; say so instead of waiting silently. */
- const failPendingTransform = (layerId: string): void => {
- if (stores.pendingTransformLayerId.get() === layerId) {
- stores.pendingTransformLayerId.set(null);
- reportEditRefusal('not-ready');
- }
- };
+ const colorSamples = new ColorSampleController({
+ endHeldTool: () => pipeline.endForToolSwitch(),
+ getActiveToolId: () => interactionController.getActiveToolId(),
+ setTool: (toolId) => interactionController.setTool(toolId),
+ });
+ // Shift-click line starts, shared by brush and eraser for the engine's lifetime; forgotten on replay and document
+ // replacement, and followed through every change of their layer.
+ const paintLineEnds = new PaintLineEndController({
+ getLayer: (layerId) => getDocumentLayer(mirror.getDocument(), layerId),
+ });
const toolContext: ToolContext = {
applyTransform: () => applyTransform(),
@@ -1192,24 +1162,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
openTextEdit: (layerId) => openTextEdit(layerId),
paintLineEnds,
sampleProviders: colorSampleProviders,
- resolveColorSample: (hex, phase) => {
- // A pick belongs to whichever sink took its first preview; its commit or cancel goes there alone, so a
- // request armed or settled mid-pick never strays into the router, nor the router's pick into the request.
- if (phase === 'preview') {
- colorPickSink ??= pendingColorSample ? 'request' : 'router';
- }
- const sink = colorPickSink;
- if (phase !== 'preview') {
- colorPickSink = null;
- }
- if (sink === 'request') {
- if (phase === 'commit' && pendingColorSample) {
- settleColorSample(hex, true);
- }
- return true;
- }
- return sink === 'router' ? (colorSampleRouter?.(hex, phase) ?? false) : false;
- },
+ resolveColorSample: (hex, phase) => colorSamples.route(hex, phase),
setLayerTransformOverride: (layerId, override) => {
if (override) {
transformOverrides.set(layerId, override);
@@ -1311,7 +1264,12 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
projectId,
});
- const { getOrStartLayerRasterization } = createLayerRasterizer({
+ const {
+ dispose: disposeLayerRasterizer,
+ getOrStartLayerRasterization,
+ hasFailed: hasFailedRasterization,
+ isBackingOff: isRasterizationBackingOff,
+ } = createLayerRasterizer({
createSurface: (width, height) => backend.createSurface(width, height),
fontLoader,
getDocument: () => mirror.getDocument(),
@@ -1412,7 +1370,10 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
const prepareLayerRasterCache = async (layerId: string) => {
const result = await rasterizeLayerPixels(layerId, { includeDisabled: true });
if (result.status !== 'ok') {
- return { status: result.status === 'over-budget' ? ('over-budget' as const) : ('not-ready' as const) };
+ return {
+ status:
+ result.status === 'over-budget' || result.status === 'unreadable' ? result.status : ('not-ready' as const),
+ };
}
const layer = result.guard.layer;
result.release();
@@ -1434,7 +1395,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
const exportBakedLayerBlob = rasterExportController.blob.bind(rasterExportController);
type StructuralExportLayerPixelsResult =
| Extract<ExportLayerPixelsResult, { status: 'ok' }>
- | { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'over-budget' }
+ | { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'unreadable' | 'over-budget' }
| AdjustmentRefusal;
const normalizeStructuralExport = async (
result: Promise<ExportLayerPixelsResult>
@@ -1479,6 +1440,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
if (result.status === 'over-budget') {
throw new RasterCompositeOverBudgetError();
}
+ if (result.status === 'unreadable') {
+ throw new RasterCompositeUnreadableError(layerId);
+ }
throw new Error(`Cannot rasterize layer ${layerId} for export: ${result.status}.`);
};
@@ -1565,7 +1529,13 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
previews: renderController.previews,
raster: rasterController,
hasStagedCandidates,
- rasterizeLayer: (layer, doc) => void getOrStartLayerRasterization(layer, doc),
+ // A source that just failed waits out its retry backoff (or a change to it) rather than failing again every frame;
+ // the backoff's end invalidates the layer, so the display retries on its own.
+ rasterizeLayer: (layer, doc) => {
+ if (!isRasterizationBackingOff(layer)) {
+ void getOrStartLayerRasterization(layer, doc);
+ }
+ },
stores,
transformOverrides,
viewport,
@@ -1623,7 +1593,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
let lastSelectedLayerId: string | null = null;
const mirror: DocumentMirror = createDocumentMirror(mutationPort, {
onDocumentChanged: () => {
- openDeferredTransform();
+ editingController.transform.onDocumentChanged();
stores.documentEpoch.set(stores.documentEpoch.get() + 1);
},
// Bbox changes need only overlay redraw unless a bbox-relative staged preview must move in the composite.
@@ -1645,8 +1615,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
cleanup.run(() => stores.bboxPreview.set(null));
cleanup.run(() => history.clear());
paintLineEnds.clear();
- cleanup.run(() => stores.transformSession.set(null));
- cleanup.run(() => stores.pendingTransformLayerId.set(null));
+ cleanup.run(() => editingController.transform.onDocumentReplaced());
cleanup.run(() => transformOverrides.clear());
// A text-edit session likewise belongs to the outgoing document; drop it.
cleanup.run(() => stores.textEditSession.set(null));
@@ -1723,6 +1692,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
const session = stores.transformSession.get();
const textSession = stores.textEditSession.get();
for (const id of ids) {
+ paintLineEnds.onLayerChanged(id);
const decision = decideLayerChange({
currentThumbnailKey: rasterController.getThumbnailKey(id),
currentThumbnailVersion: stores.thumbnailVersion.get(id),
@@ -1733,7 +1703,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
sourceChanged: sourceChanged.has(id),
});
if (decision.kind === 'removed') {
- paintLineEnds.delete(id);
rasterController.deleteThumbnailKey(id);
cleanup.run(() => dropLayer(id));
// Removed preview layers must drop decoded pixels and advance decode tokens so late results or restored
@@ -1936,10 +1905,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
// finished the move.
if (!switchOptions?.temporary) {
floatingSelection.commit();
- // A genuine switch away also ends a transform still waiting on its pixels.
- if (to !== 'transform') {
- stores.pendingTransformLayerId.set(null);
- }
+ editingController.transform.onToolSwitch(to);
}
for (const listener of toolChangeListeners) {
listener({ from, temporary: switchOptions?.temporary === true, to });
@@ -1954,53 +1920,18 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
stepBrushSize: stepActiveBrushSize,
updateCursor,
});
- /**
- * Settle a pending sample, optionally restoring the previous tool. Tool-switch callers skip restoration so their
- * requested switch wins.
- */
- const settleColorSample = (hex: string | null, restoreTool: boolean): void => {
- const pending = pendingColorSample;
- if (!pending) {
- return;
- }
- pendingColorSample = null;
- pending.resolve(hex);
- if (restoreTool) {
- interactionController.setTool(pending.previousToolId);
- }
- };
-
const setTool = (toolId: ToolId, options?: { temporary?: boolean }): void => {
- // Any move off the eyedropper abandons the sample the caller is awaiting.
- if (toolId !== 'colorPicker') {
- settleColorSample(null, false);
- }
+ colorSamples.onToolChange(toolId);
interactionController.setTool(toolId, options);
};
- /** Samples the document composite and resolves hex on release, after the gesture, or null on cancellation. */
- const requestColorSample = (): Promise<string | null> => {
- // A second request supersedes the first; the earlier caller gets a cancel.
- settleColorSample(null, false);
- // End any held temporary tool first, so the request records the tool the user was really on.
- pipeline.endForToolSwitch();
-
- return new Promise<string | null>((resolve) => {
- pendingColorSample = { previousToolId: interactionController.getActiveToolId(), resolve };
- interactionController.setTool('colorPicker');
- });
- };
-
/**
* After gesture cancellation, Escape cancels defocused text editing, then transform, then selection. Focused
* portals handle Escape themselves. If a gesture consumed Escape, preserve committed selection. Shared with
* pipeline wiring and node tests.
*/
const handleEscapePriority = ({ gestureWasActive }: { gestureWasActive: boolean }): void => {
- // An armed eyedropper is the most recent thing the user opted into, so it
- // is the first thing Escape takes back.
- if (pendingColorSample) {
- settleColorSample(null, true);
+ if (colorSamples.onEscape()) {
return;
}
if (stores.textEditSession.get()) {
@@ -2011,8 +1942,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
cancelTransform();
return;
}
- if (stores.pendingTransformLayerId.get() !== null) {
- stores.pendingTransformLayerId.set(null);
+ if (editingController.transform.onEscape()) {
return;
}
if (floatingSelection.has()) {
@@ -2231,6 +2161,23 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
const entry = layerCache.get(layer.id);
return !!entry && !entry.stale && !isCurrentRasterizationJob(layer);
};
+ /**
+ * `unreadable` while a failure is recorded for the layer's current source. Once its backoff has ended this also
+ * tries the image again in the background (a layer off screen or disabled is never redrawn to do so), so an image
+ * that became available recovers; a retry that fails again only restarts the backoff.
+ */
+ const layerCacheReadinessForOp = (layer: CanvasLayerContract, doc: CanvasDocumentContractV3): LayerCacheReadiness => {
+ if (isLayerCacheReadyForOp(layer, doc)) {
+ return 'ready';
+ }
+ if (isCurrentRasterizationJob(layer) || !hasFailedRasterization(layer)) {
+ return 'not-ready';
+ }
+ if (!isRasterizationBackingOff(layer)) {
+ scheduleLayerRasterization([layer.id]);
+ }
+ return 'unreadable';
+ };
const prepareGeneratedPaintCache = (layerId: string, rect: Rect, pixels: RasterSurface) =>
layerCache.prepareReplacement(layerId, rect, pixels);
@@ -2471,13 +2418,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
const mergeSelectedRasterLayers = (layerIds: readonly string[]): Promise<MergeVisibleResult> =>
layerController.merge.mergeSelected(layerIds);
const mergeVisibleRasterLayers = (): Promise<MergeVisibleResult> => layerController.merge.mergeVisible();
- const canMergeInpaintMasks = (layerIds: readonly string[]): boolean => {
- const document = mirror.getDocument();
- return (
- document !== null &&
- canMergeInpaintMasksIn(compileDocumentLeaves(document), new Set(layerIds), hasExportableLayerContent)
- );
- };
const mergeInpaintMasks = (layerIds: readonly string[]): Promise<MergeInpaintMasksResult> =>
layerController.merge.mergeInpaintMasks(layerIds);
const cropAllLayersToBbox = (): Promise<CropAllLayersResult> => layerController.crop.cropAll();
@@ -2514,42 +2454,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
// paint; Cancel drops previews. Tools and public UI share the session API.
const beginTransformSession = (layerId: string): void => editingController.transform.begin(layerId);
- /** Opens a session on `layerId` now, whatever tool is active; the context menu and shortcut use it. */
- const beginTransform = (layerId: string): BeginTransformResult => {
- const document = mirror.getDocument();
- const leaf = lookupDocumentLeaf(document, layerId);
- if (disposed || !document || !leaf) {
- return disposed ? 'busy' : 'missing';
- }
- if (leaf.effectiveLocked) {
- return 'locked';
- }
- const persisted = isTransformEligible(leaf.layer, document);
- if (!persisted && !isTransformEligible(leaf.layer, document, layerCache.peek(layerId)?.rect)) {
- return 'ineligible';
- }
- if (interactionLocked || pipeline.isGestureActive() || floatingSelection.has() || !canEditDocument()) {
- return 'busy';
- }
- // Selecting cancels a session on another layer (see `onSelectionChanged`); entering the tool opens one on the
- // selection, and an already active tool is opened explicitly.
- if (document.selectedLayerId !== layerId) {
- dispatchCanvasMutation({ id: layerId, type: 'setCanvasSelectedLayer' });
- }
- setTool('transform');
- if (stores.transformSession.get()?.layerId !== layerId) {
- cancelTransform();
- if (persisted) {
- beginTransformSession(layerId);
- }
- // Every refusal is decided above, before the selection or tool changes. A layer whose pixels persistence
- // has not acknowledged yet (a stroke's first upload) opens its session once the bitmap lands.
- if (stores.transformSession.get()?.layerId !== layerId) {
- stores.pendingTransformLayerId.set(layerId);
- }
- }
- return 'started';
- };
const updateTransformSession = (transform: LayerTransform): void => editingController.transform.update(transform);
// A framed float is the session — Apply banks it, Cancel abandons it. Only
// with no float in flight do these reach the layer transform session.
@@ -2658,7 +2562,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
return;
}
disposed = true;
- paintLineEnds.clear();
+ paintLineEnds.dispose();
+ disposeLayerRasterizer();
releaseActiveSnapshots();
rasterController.memory.releaseGeneration(lifecycleGeneration);
lifecycleGeneration += 1;
@@ -2682,7 +2587,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
cleanup.run(() => stores.textEditSession.set(null));
cleanup.run(() => antsAnimator.stop());
// No render loop left to sample with; release any awaited eyedropper.
- cleanup.run(() => settleColorSample(null, false));
+ cleanup.run(() => colorSamples.dispose());
cleanup.run(() => activeTool()?.onDeactivate?.(toolContext));
cleanup.run(unsubscribeViewport);
cleanup.run(unsubscribeBrushOptions);
@@ -2853,7 +2758,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
backend,
ctx: mutationContext,
exportBaked: (layerId) => exportBakedLayerPixelsForStructural(layerId),
- isCacheReady: isLayerCacheReadyForOp,
+ cacheReadiness: layerCacheReadinessForOp,
isGuardCurrent: isLayerExportGuardCurrent,
},
crop: {
@@ -2863,6 +2768,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
discardPersisted: (layerId) => bitmapStore.discardLayer(layerId),
exportBaked: (layerId, options) =>
exportBakedLayerPixelsForStructural(layerId, { ...options, includeDisabled: true }),
+ // Held pixels belong to an open edit; crop all must not wait for that edit to end.
+ flushPendingPixels: () => persistenceController.flush({ waitForHeldPixels: false }),
isGuardCurrent: isLayerExportGuardCurrent,
isSupportedSource: isSupportedExportSource,
},
@@ -2879,7 +2786,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
ctx: mutationContext,
exportBaked: (layerId, includeDisabled) => exportBakedLayerPixelsForStructural(layerId, { includeDisabled }),
hasExportableContent: hasExportableLayerContent,
- isCacheReady: isLayerCacheReadyForOp,
+ cacheReadiness: layerCacheReadinessForOp,
isGuardCurrent: isLayerExportGuardCurrent,
layers: layerCache,
peekAdjustedCacheSurface: (layerId, surface, adjustments) =>
@@ -2910,7 +2817,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
ctx: mutationContext,
exportBaked: (layerId) => exportBakedLayerPixelsForStructural(layerId),
hasExportableContent: hasExportableLayerContent,
- isCacheReady: isLayerCacheReadyForOp,
+ cacheReadiness: layerCacheReadinessForOp,
layers: layerCache,
needsPixelPersistence: layerNeedsPixelPersistence,
peekAdjustedSurface: (layer, entry) => rasterController.peekAdjustedSurface(layer, entry),
@@ -3010,24 +2917,15 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
handleEscapePriority,
onEditRefused,
onStrokeCommitted,
- requestColorSample,
- setColorSampleRouter: (router) => {
- colorSampleRouter = router;
- return () => {
- // Compare-and-clear: a later installer must not be evicted by an earlier one's cleanup.
- if (colorSampleRouter === router) {
- colorSampleRouter = null;
- }
- };
- },
+ requestColorSample: () => colorSamples.requestSample(),
+ setColorSampleRouter: (router) => colorSamples.setRouter(router),
setInteractionLocked,
};
const layersCapability: CanvasEngineLayerCapability = {
...layerController.layers,
applyTransform,
- beginTransform,
+ beginTransform: (layerId) => editingController.transform.request(layerId),
booleanMergeRasterLayers,
- canMergeInpaintMasks,
cancelTextEdit,
cancelTransform,
clearMask,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.ts
index da754b1d60..4fd3e1d96b 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.ts
@@ -13,6 +13,7 @@ import {
getBaseRasterContentBounds,
planBaseRasterComposite,
RasterCompositeOverBudgetError,
+ RasterCompositeUnreadableError,
renderRasterComposite,
type RenderRasterCompositeDeps,
} from '@workbench/canvas-engine/render/rasterComposite';
@@ -21,7 +22,7 @@ export type RasterCompositeExportRequest = { bounds: 'content' } | { bounds: 're
export type RasterCompositeExportResult =
| { status: 'ok'; blob: Blob; rect: Rect }
- | { status: 'empty' | 'stale' | 'not-ready' | 'over-budget' }
+ | { status: 'empty' | 'stale' | 'not-ready' | 'unreadable' | 'over-budget' }
| AdjustmentRefusal;
export interface RasterCompositeExportSnapshot {
@@ -75,6 +76,9 @@ export const exportRasterComposite = async (
if (error instanceof RasterCompositeOverBudgetError) {
return { status: 'over-budget' };
}
+ if (error instanceof RasterCompositeUnreadableError) {
+ return { status: 'unreadable' };
+ }
if (error instanceof AdjustmentRefusedError) {
return adjustmentRefusal(document, error.ownerId, error.reason);
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.test.ts
index 76d2ca1dbe..415f0c3459 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.test.ts
@@ -6,7 +6,7 @@ import type { RasterSurface } from '@workbench/canvas-engine/render/raster';
import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { createLayerRasterizer, type CreateLayerRasterizerDeps } from './layerRasterizer';
+import { createLayerRasterizer, type CreateLayerRasterizerDeps, RASTERIZATION_RETRY_BASE_MS } from './layerRasterizer';
const surface = (width = 4, height = 4): RasterSurface =>
({
@@ -123,6 +123,7 @@ const makeHarness = (overrides: Partial<CreateLayerRasterizerDeps> = {}): Harnes
layerCache: {
get: vi.fn(() => entry),
getOrCreateRect: vi.fn(() => entry),
+ peek: vi.fn(() => entry),
publishRasterized: vi.fn((_layerId: string, _rect: unknown, _pixels: unknown, family?: string) => {
entry.renderedFontFamily = family;
return { ...entry, version: entry.version + 1 };
@@ -277,6 +278,66 @@ describe('failure', () => {
);
});
+ it('reports a source that keeps failing once, and remembers the failure until the layer changes', async () => {
+ const rasterizer = createLayerRasterizer(harness.deps);
+ (harness.entry as { stale: boolean }).stale = true;
+ harness.rasterize.mockRejectedValue(new Error('decode failed'));
+ const layer = rasterLayer();
+
+ await expect(rasterizer.getOrStartLayerRasterization(layer, harness.document.value)).resolves.toBe('error');
+ await expect(rasterizer.getOrStartLayerRasterization(layer, harness.document.value)).resolves.toBe('error');
+ expect(harness.rasterize).toHaveBeenCalledTimes(2);
+ expect(harness.spies.reportError).toHaveBeenCalledOnce();
+ expect(rasterizer.hasFailed(layer)).toBe(true);
+
+ // Another image is another failure, worth its own notice.
+ const replaced = rasterLayer({ source: { image: { height: 4, imageName: 'b.png', width: 4 }, type: 'image' } });
+ harness.document.value = documentOf([replaced]);
+ expect(rasterizer.hasFailed(replaced)).toBe(false);
+ await expect(rasterizer.getOrStartLayerRasterization(replaced, harness.document.value)).resolves.toBe('error');
+ expect(harness.spies.reportError).toHaveBeenCalledTimes(2);
+ });
+
+ it('lets a failed source retry after a backoff that doubles per failure, reporting it once', async () => {
+ const timers: { callback: () => void; delayMs: number }[] = [];
+ const rasterizer = createLayerRasterizer({
+ ...harness.deps,
+ setTimer: (callback, delayMs) => {
+ timers.push({ callback, delayMs });
+ return () => undefined;
+ },
+ });
+ (harness.entry as { stale: boolean }).stale = true;
+ harness.rasterize.mockRejectedValue(new Error('backend restarting'));
+ const layer = rasterLayer();
+
+ await rasterizer.getOrStartLayerRasterization(layer, harness.document.value);
+ expect(rasterizer.isBackingOff(layer)).toBe(true);
+ timers.at(-1)!.callback();
+ // The backoff's end lets the display try again, and says so; the failure itself is still on record.
+ expect(rasterizer.isBackingOff(layer)).toBe(false);
+ expect(rasterizer.hasFailed(layer)).toBe(true);
+ expect(harness.spies.invalidateLayerRender).toHaveBeenCalledWith('layer-1');
+
+ await rasterizer.getOrStartLayerRasterization(layer, harness.document.value);
+ expect(timers.map(({ delayMs }) => delayMs)).toEqual([
+ RASTERIZATION_RETRY_BASE_MS,
+ RASTERIZATION_RETRY_BASE_MS * 2,
+ ]);
+ expect(harness.spies.reportError).toHaveBeenCalledOnce();
+ });
+
+ it('forgets a failure once a retry publishes', async () => {
+ const rasterizer = createLayerRasterizer(harness.deps);
+ (harness.entry as { stale: boolean }).stale = true;
+ harness.rasterize.mockRejectedValueOnce(new Error('network blip'));
+ const layer = rasterLayer();
+
+ await expect(rasterizer.getOrStartLayerRasterization(layer, harness.document.value)).resolves.toBe('error');
+ await expect(rasterizer.getOrStartLayerRasterization(layer, harness.document.value)).resolves.toBe('published');
+ expect(rasterizer.hasFailed(layer)).toBe(false);
+ });
+
it('still reports error when diagnostics itself throws', async () => {
harness.rasterize.mockRejectedValue(new Error('decode failed'));
harness.spies.reportError.mockImplementation(() => {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.ts
index 394271e514..121ff1a252 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/layerRasterizer.ts
@@ -5,7 +5,7 @@ import type {
} from '@workbench/canvas-engine/contracts';
import type { RasterizationJob } from '@workbench/canvas-engine/controllers/rasterController';
import type { FontLoader } from '@workbench/canvas-engine/render/fontLoader';
-import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';
+import type { LayerCacheEntry, LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';
import type { RasterSurface } from '@workbench/canvas-engine/render/raster';
import type { RasterizeResult } from '@workbench/canvas-engine/render/rasterizers';
@@ -47,8 +47,14 @@ export interface CreateLayerRasterizerDeps {
readonly invalidateLayerCache: (layerId: string) => void;
readonly invalidateLayerRender: (layerId: string) => void;
readonly reportError: (message: 'Layer thumbnail rasterization failed', layerId: string, error: unknown) => void;
+ /** Runs `callback` after `delayMs`, returning a cancel; defaults to the global timer. */
+ readonly setTimer?: (callback: () => void, delayMs: number) => () => void;
}
+/** The first wait before a failed source may rasterize again for display, doubling per repeated failure up to the cap. */
+export const RASTERIZATION_RETRY_BASE_MS = 3_000;
+export const RASTERIZATION_RETRY_MAX_MS = 60_000;
+
export interface LayerRasterizer {
/**
* Starts or joins rasterization for the same source, cache version and document generation; repeated frame
@@ -59,6 +65,30 @@ export interface LayerRasterizer {
document: CanvasDocumentContractV3,
signal?: AbortSignal
): Promise<LayerRasterizationOutcome>;
+ /**
+ * Whether the last rasterization of `layer`'s current source, cache version and document generation failed, so its
+ * stale cache cannot become ready by waiting. A success or any change to the layer clears it.
+ */
+ hasFailed(layer: CanvasLayerContract): boolean;
+ /**
+ * Whether {@link hasFailed} and the failure's retry backoff is still running. The backoff starts at
+ * {@link RASTERIZATION_RETRY_BASE_MS} and doubles per repeated failure up to {@link RASTERIZATION_RETRY_MAX_MS}; its
+ * end invalidates the layer's render, so a displayed layer retries on its own.
+ */
+ isBackingOff(layer: CanvasLayerContract): boolean;
+ /** Cancels pending retry timers. */
+ dispose(): void;
+}
+
+/** What a failed rasterization read; a later failure of the same key is the same failure. */
+interface RasterizationFailure {
+ readonly version: number;
+ readonly documentGeneration: number;
+ readonly source: CanvasLayerSourceContract;
+ /** Consecutive failures of this key. */
+ readonly attempts: number;
+ /** Ends the backoff early; null once it ended. */
+ cancelRetry: (() => void) | null;
}
/**
@@ -69,6 +99,32 @@ export interface LayerRasterizer {
*/
export const createLayerRasterizer = (deps: CreateLayerRasterizerDeps): LayerRasterizer => {
const { jobs, layerCache } = deps;
+ const setTimer =
+ deps.setTimer ??
+ ((callback: () => void, delayMs: number) => {
+ const handle = setTimeout(callback, delayMs);
+ return () => clearTimeout(handle);
+ });
+ // Keyed by cache entry so an evicted or deleted layer's record goes with it.
+ const failures = new WeakMap<LayerCacheEntry, RasterizationFailure>();
+ const backoffs = new Set<RasterizationFailure>();
+ const endBackoff = (failure: RasterizationFailure | undefined): void => {
+ failure?.cancelRetry?.();
+ if (failure) {
+ failure.cancelRetry = null;
+ backoffs.delete(failure);
+ }
+ };
+ const isSameFailure = (
+ failure: RasterizationFailure | undefined,
+ version: number,
+ documentGeneration: number,
+ source: CanvasLayerSourceContract | null
+ ): boolean =>
+ !!failure &&
+ failure.version === version &&
+ failure.documentGeneration === documentGeneration &&
+ areJsonValuesStructurallyEqual(failure.source, source);
const getOrStartLayerRasterization = (
layer: CanvasLayerContract,
@@ -166,6 +222,8 @@ export const createLayerRasterizer = (deps: CreateLayerRasterizerDeps): LayerRas
return 'stale';
}
+ endBackoff(failures.get(currentEntry));
+ failures.delete(currentEntry);
const publishedEntry = layerCache.publishRasterized(layer.id, result.rect, result.surface, renderedFontFamily);
deps.thumbnails.setVersion(layer.id, publishedEntry.version);
deps.thumbnails.setStatus(layer.id, 'ready');
@@ -189,10 +247,31 @@ export const createLayerRasterizer = (deps: CreateLayerRasterizerDeps): LayerRas
return 'stale';
}
deps.thumbnails.setStatus(layer.id, 'error');
- try {
- deps.reportError('Layer thumbnail rasterization failed', layer.id, error);
- } catch {
- // Diagnostics must not turn a handled thumbnail failure into a rejection.
+ // Retrying the same source fails the same way; only its first failure is worth a notice.
+ const failedEntry = layerCache.peek(layer.id);
+ const previous = failedEntry ? failures.get(failedEntry) : undefined;
+ const repeated = !!failedEntry && isSameFailure(previous, version, documentGeneration, source);
+ endBackoff(previous);
+ if (failedEntry && !deps.isDisposed()) {
+ const attempts = repeated ? previous!.attempts + 1 : 1;
+ const failure: RasterizationFailure = { attempts, cancelRetry: null, documentGeneration, source, version };
+ failure.cancelRetry = setTimer(
+ () => {
+ failure.cancelRetry = null;
+ backoffs.delete(failure);
+ deps.invalidateLayerRender(layer.id);
+ },
+ Math.min(RASTERIZATION_RETRY_BASE_MS * 2 ** (attempts - 1), RASTERIZATION_RETRY_MAX_MS)
+ );
+ backoffs.add(failure);
+ failures.set(failedEntry, failure);
+ }
+ if (!repeated) {
+ try {
+ deps.reportError('Layer thumbnail rasterization failed', layer.id, error);
+ } catch {
+ // Diagnostics must not turn a handled thumbnail failure into a rejection.
+ }
}
return 'error';
} finally {
@@ -203,5 +282,23 @@ export const createLayerRasterizer = (deps: CreateLayerRasterizerDeps): LayerRas
return promise;
};
- return { getOrStartLayerRasterization };
+ /** The failure recorded for `layer`'s current key, while its cache still waits for pixels. */
+ const currentFailure = (layer: CanvasLayerContract): RasterizationFailure | undefined => {
+ const entry = layerCache.peek(layer.id);
+ const failure = entry ? failures.get(entry) : undefined;
+ return entry?.stale &&
+ isSameFailure(failure, entry.version, jobs.getDocumentGeneration(), renderableSourceOf(layer))
+ ? failure
+ : undefined;
+ };
+ const hasFailed = (layer: CanvasLayerContract): boolean => !!currentFailure(layer);
+ const isBackingOff = (layer: CanvasLayerContract): boolean => !!currentFailure(layer)?.cancelRetry;
+
+ const dispose = (): void => {
+ for (const failure of backoffs) {
+ endBackoff(failure);
+ }
+ };
+
+ return { dispose, getOrStartLayerRasterization, hasFailed, isBackingOff };
};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.ts
index ade1fc6137..edd517ce4c 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.ts
@@ -154,7 +154,11 @@ export const createRasterSnapshotCapture = (deps: CreateRasterSnapshotCaptureDep
if (liveResult.status !== 'ok') {
return {
status:
- liveResult.status === 'aborted' || liveResult.status === 'over-budget' ? liveResult.status : 'not-ready',
+ liveResult.status === 'aborted' ||
+ liveResult.status === 'over-budget' ||
+ liveResult.status === 'unreadable'
+ ? liveResult.status
+ : 'not-ready',
};
}
const live = liveResult;
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterTransactions.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterTransactions.ts
index 9f528f4746..fc18d1ebbc 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterTransactions.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterTransactions.ts
@@ -29,9 +29,10 @@ export interface CanvasRasterSnapshot {
release(): void;
}
+/** `unreadable`: a required layer's pixels could not be read (its image is gone or does not decode). */
export type CaptureRasterSnapshotResult =
| { status: 'ok'; snapshot: CanvasRasterSnapshot }
- | { status: 'stale' | 'aborted' | 'not-ready' | 'over-budget' };
+ | { status: 'stale' | 'aborted' | 'not-ready' | 'unreadable' | 'over-budget' };
export interface CanvasCompositeExecutorDeps {
backend: {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.ts
index 975f07c3cf..38e7823925 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.ts
@@ -108,6 +108,14 @@ export class RasterCompositeOverBudgetError extends Error {
}
}
+/** Thrown when a contributor's pixels cannot be read (its image is gone or does not decode); export maps it to `unreadable`. */
+export class RasterCompositeUnreadableError extends Error {
+ constructor(readonly layerId: string) {
+ super(`The pixels of layer ${layerId} could not be read.`);
+ this.name = 'RasterCompositeUnreadableError';
+ }
+}
+
const defaultReadImageData = (surface: RasterSurface, rect: Rect): ImageData =>
surface.ctx.getImageData(rect.x, rect.y, rect.width, rect.height);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts
index 6bac3fcd0e..23061a1bb7 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts
@@ -930,6 +930,27 @@ describe('Shift-click straight lines', () => {
expect(h.paintLineEnds.get('paint1')).toEqual({ x: 60, y: 10 });
});
+ it('keeps the line start on the layer when the layer moves', () => {
+ const layer = paintLayer('paint1');
+ const h = lineHarness([layer], 'paint1');
+ const brush = createBrushTool();
+ down(brush, h.ctx, pointer(10, 10));
+ up(brush, h.ctx, pointer(10, 10));
+ h.span();
+
+ // Nudge the layer 100 px right: its last stroke end now sits at document x=110.
+ const nudged = makeDoc([{ ...layer, transform: { ...layer.transform, x: 100 } }], 'paint1');
+ const ctx: ToolContext = { ...h.ctx, getDocument: () => nudged };
+ down(brush, ctx, pointer(160, 10, { shift: true }));
+ up(brush, ctx, pointer(160, 10, { shift: true }));
+
+ // 50 px from x=110 to x=160 plus the brush radius at each end, not 150 px from where the end used to be.
+ const span = h.span();
+ expect(span).toBeGreaterThanOrEqual(50);
+ expect(span).toBeLessThan(60);
+ expect(h.paintLineEnds.get('paint1')).toEqual({ x: 60, y: 10 });
+ });
+
it('paints a dab on a Shift press without a remembered point, or on a layer with none', () => {
const h = lineHarness([paintLayer('paint1'), paintLayer('paint2')], 'paint2');
h.paintLineEnds.set('paint1', { x: 10, y: 10 });
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts
index a07e086ec0..080f359b52 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts
@@ -1,18 +1,19 @@
/**
* Shared brush/eraser gesture resolves or creates a target, drives a StrokeSession and commits/cancels. Only
* gesture-start layer creation dispatches here; moves never dispatch. Fill/erase differ by blend and option
- * source. A Shift press on a layer with a remembered stroke end draws a straight segment from it.
+ * source. A Shift press on a layer with a remembered stroke end draws a straight segment from it; the end is kept
+ * layer-local, so moving or transforming the layer carries it.
*/
import type { CanvasLayerContract, CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';
import type { CanvasNodeInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';
-import type { PointerInput } from '@workbench/canvas-engine/types';
+import type { Mat2d, PointerInput } from '@workbench/canvas-engine/types';
import { lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';
import { getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';
import { isLeafPaintable, isLayerTransparencyLocked } from '@workbench/canvas-engine/document/layerEligibility';
import { isMaskLayer } from '@workbench/canvas-engine/document/sources';
-import { fromTRS, invert } from '@workbench/canvas-engine/math/mat2d';
+import { applyToPoint, fromTRS, invert } from '@workbench/canvas-engine/math/mat2d';
import type { StrokeEdit, Tool, ToolContext } from './tool';
@@ -77,6 +78,12 @@ const editTarget = (
...extra,
});
+/** The target layer's document matrix; null is identity (a new or materialized layer). */
+const targetMatrix = ({ transform }: PaintTarget): Mat2d | null =>
+ transform
+ ? fromTRS({ x: transform.x, y: transform.y }, transform.rotation, transform.scaleX, transform.scaleY)
+ : null;
+
/** Resolves (or auto-creates) the paint target for a gesture, or `null` to no-op. */
const resolveTarget = (ctx: ToolContext, tool: PaintToolSpec['id']): PaintTarget | null => {
const doc = ctx.getDocument();
@@ -268,14 +275,7 @@ export const createPaintTool = (spec: PaintToolSpec): Tool => {
return;
}
const composite = resolvedTarget.transparencyLocked && spec.id === 'brush' ? 'source-atop' : spec.composite;
- const layerTransform = resolvedTarget.transform
- ? fromTRS(
- { x: resolvedTarget.transform.x, y: resolvedTarget.transform.y },
- resolvedTarget.transform.rotation,
- resolvedTarget.transform.scaleX,
- resolvedTarget.transform.scaleY
- )
- : null;
+ const layerTransform = targetMatrix(resolvedTarget);
if (layerTransform && !invert(layerTransform)) {
// A zero-scale layer has no paintable geometry to invert into.
resolvedTarget.cancel();
@@ -309,9 +309,10 @@ export const createPaintTool = (spec: PaintToolSpec): Tool => {
thinning: spec.thinning(ctx),
tool: spec.id,
});
- // Shift continues from the layer's last stroke end: both points take the press pressure, so the segment
- // renders as a line rather than collapsing to a tap.
- const lineStart = input.modifiers.shift ? ctx.paintLineEnds?.get(target.layerId) : undefined;
+ // Shift continues from the layer's last stroke end, placed through the layer's current transform: both points
+ // take the press pressure, so the segment renders as a line rather than collapsing to a tap.
+ const localStart = input.modifiers.shift ? ctx.paintLineEnds?.get(target.layerId) : undefined;
+ const lineStart = localStart && layerTransform ? applyToPoint(layerTransform, localStart) : localStart;
session.addPoints(lineStart ? [{ ...input, documentPoint: lineStart }, input] : [input]);
} catch {
abortSession();
@@ -342,7 +343,13 @@ export const createPaintTool = (spec: PaintToolSpec): Tool => {
}
endSession();
if (published) {
- ctx.paintLineEnds?.set(activeTarget.layerId, { ...input.documentPoint });
+ // Kept layer-local, in the space the stroke painted; the press already refused a non-invertible matrix.
+ const matrix = targetMatrix(activeTarget);
+ const toLocal = matrix ? invert(matrix) : null;
+ ctx.paintLineEnds?.set(
+ activeTarget.layerId,
+ toLocal ? applyToPoint(toLocal, input.documentPoint) : { ...input.documentPoint }
+ );
} else {
activeTarget.cancel();
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts
index ba8992bac0..89f5fd3585 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts
@@ -77,7 +77,7 @@ export interface LayerTransformOverride {
rotation?: number;
}
-/** Where the last committed brush or eraser stroke ended, per layer id, in document space. */
+/** Where the last committed brush or eraser stroke ended, per layer id, in that layer's local space. */
export interface PaintLineEnds {
get(layerId: string): Vec2 | undefined;
set(layerId: string, point: Vec2): void;
@@ -151,8 +151,9 @@ export interface ToolContext {
/** Compositor providers that make sampling WYSIWYG; absent ⇒ raw cached pixels. */
sampleProviders?: Pick<CompositeOptions, 'adjustedSurface' | 'derivedSurfaces' | 'groupSurface'>;
/**
- * Where the last committed brush or eraser stroke ended on each layer, in document space; shared by both tools for
- * Shift-click lines. The engine owns it and forgets entries on replay, document replacement and layer removal.
+ * Where the last committed brush or eraser stroke ended on each layer, layer-local so moving or transforming the
+ * layer carries it; shared by both tools for Shift-click lines. The engine owns it and forgets entries on replay,
+ * document replacement and layer removal.
*/
paintLineEnds?: PaintLineEnds;
/**
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.ts
index 2b1245c0a5..1994a1784e 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.ts
@@ -28,7 +28,7 @@ export type CreateFromBboxDestination = 'global-reference' | CreateFromBboxLayer
export type CreateFromBboxResult =
| { status: 'created'; destination: CreateFromBboxLayerDestination; layerIds: string[] }
| { status: 'uploaded'; image: CanvasImageUploadResult }
- | { status: 'empty' | 'stale' | 'not-ready' | 'over-budget' }
+ | { status: 'empty' | 'stale' | 'not-ready' | 'unreadable' | 'over-budget' }
| AdjustmentRefusal
| { status: 'blocked' | 'stale-document' | 'stale-project' };
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBboxNotice.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBboxNotice.test.ts
index 4bd383497e..a366bde858 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBboxNotice.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBboxNotice.test.ts
@@ -20,6 +20,7 @@ describe('getCreateFromBboxNotice', () => {
['stale', 'info', 'widgets.canvas.contextMenu.stale'],
['not-ready', 'info', 'widgets.canvas.contextMenu.notReady'],
['over-budget', 'info', 'widgets.canvas.contextMenu.notReady'],
+ ['unreadable', 'error', 'widgets.canvas.contextMenu.unreadable'],
['blocked', 'info', 'widgets.canvas.import.blocked'],
['stale-document', 'error', 'widgets.canvas.import.staleDocument'],
['stale-project', 'error', 'widgets.canvas.import.staleProject'],
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBboxNotice.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBboxNotice.ts
index dd9349b2e1..4dd3fcc339 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBboxNotice.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBboxNotice.ts
@@ -14,7 +14,8 @@ export type CreateFromBboxNotice =
| 'widgets.canvas.contextMenu.createdFromBbox'
| 'widgets.canvas.contextMenu.empty'
| 'widgets.canvas.contextMenu.notReady'
- | 'widgets.canvas.contextMenu.stale';
+ | 'widgets.canvas.contextMenu.stale'
+ | 'widgets.canvas.contextMenu.unreadable';
/** `destination` is itself a translation key naming the created entity. */
options?: CanvasImportNotice['options'] | { destination: string };
}
@@ -47,6 +48,8 @@ export const getCreateFromBboxNotice = (
case 'not-ready':
case 'over-budget':
return { kind: 'info', titleKey: 'widgets.canvas.contextMenu.notReady' };
+ case 'unreadable':
+ return { kind: 'error', titleKey: 'widgets.canvas.contextMenu.unreadable' };
case 'adjustment-refused':
return { kind: 'error', refusal: result };
case 'blocked':
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/exportCanvasComposite.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/exportCanvasComposite.ts
index f2f5bbf91b..ef50c45d51 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/exportCanvasComposite.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/exportCanvasComposite.ts
@@ -10,7 +10,7 @@ export type CanvasCompositeRegion = 'canvas' | 'bbox';
export type ExportCanvasCompositeResult =
| { status: 'ok'; blob: Blob; rect: Rect }
- | { status: 'empty' | 'stale' | 'not-ready' | 'over-budget' }
+ | { status: 'empty' | 'stale' | 'not-ready' | 'unreadable' | 'over-budget' }
| AdjustmentRefusal;
export type CanvasCompositeExportEngine = {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/filterOperationSession.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/filterOperationSession.ts
index e10ac2f322..35265e4e97 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/filterOperationSession.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/filterOperationSession.ts
@@ -184,9 +184,11 @@ export const createFilterOperationSession = (
? `source-adjustment-${exported.reason}`
: exported.status === 'over-budget'
? 'source-over-budget'
- : exported.status === 'aborted'
- ? 'not-ready'
- : exported.status;
+ : exported.status === 'unreadable'
+ ? 'source-unreadable'
+ : exported.status === 'aborted'
+ ? 'not-ready'
+ : exported.status;
throw new Error(`The filter source is ${exported.status}.`);
}
try {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.ts
index d1778beddd..229fdf9021 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.ts
@@ -128,7 +128,7 @@ export interface GenerationComposites {
export type ComposeForGenerationResult =
| { status: 'ok'; composites: GenerationComposites; dedupeCommit: GenerationCompositeDedupeCommit }
- | { status: 'no-document' | 'stale' | 'aborted' | 'not-ready' | 'over-budget' }
+ | { status: 'no-document' | 'stale' | 'aborted' | 'not-ready' | 'unreadable' | 'over-budget' }
| AdjustmentRefusal;
/**
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/layerImageResult.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/layerImageResult.ts
index 957f1a8ba4..8b848a3a07 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/layerImageResult.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/layerImageResult.ts
@@ -18,7 +18,9 @@ export interface SelectObjectReadyResult {
export type SelectObjectRunResult =
| SelectObjectReadyResult
- | { status: 'aborted' | 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'over-budget' }
+ | {
+ status: 'aborted' | 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'unreadable' | 'over-budget';
+ }
| AdjustmentRefusal
| { status: 'invalid-input' }
| { status: 'dimension-mismatch'; message: string }
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/operationTypes.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/operationTypes.ts
index d31988fcbf..642d538c76 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/operationTypes.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/operationTypes.ts
@@ -25,6 +25,8 @@ export type SamSessionErrorCode =
| 'output-dimension'
| 'decode'
| 'locked'
+ /** The layer's image could not be read (it is gone or does not decode). */
+ | 'unreadable'
| 'unknown';
export interface SamSessionError {
code: SamSessionErrorCode;
@@ -77,6 +79,8 @@ export type FilterSessionErrorCode =
| 'disabled'
| 'empty'
| 'source-over-budget'
+ /** The layer's image could not be read (it is gone or does not decode). */
+ | 'source-unreadable'
/** The layer's Clarity, Texture or Dehaze could not run on the source, so it was not filtered without them. */
| 'source-adjustment-too-large'
| 'source-adjustment-over-budget'
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.ts
index c7cd7e5cba..ee3049534a 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.ts
@@ -28,7 +28,7 @@ export type CanvasGallerySaveRegion = CanvasCompositeRegion;
export type SaveCanvasToGalleryResult =
/** `boardId` is where the image went: a board id, or `none` for Uncategorized. */
| { status: 'saved'; boardId: string; imageName: string }
- | { status: 'empty' | 'stale' | 'not-ready' | 'over-budget' }
+ | { status: 'empty' | 'stale' | 'not-ready' | 'unreadable' | 'over-budget' }
| AdjustmentRefusal;
const buildCanvasSaveMetadata = (project: Project, rect: Rect): Record<string, unknown> => {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/selectObjectSession.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/selectObjectSession.ts
index 55fbe3031b..e70977f547 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/selectObjectSession.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/selectObjectSession.ts
@@ -136,6 +136,9 @@ const getPreparedSourceError = (
if (result.status === 'adjustment-refused') {
return { code: `adjustment-${result.reason}` };
}
+ if (result.status === 'unreadable') {
+ return { code: 'unreadable' };
+ }
return { code: 'not-ready' };
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasCropAllLayersMenuItem.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasCropAllLayersMenuItem.browser.test.tsx
new file mode 100644
index 0000000000..34aeab38b4
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasCropAllLayersMenuItem.browser.test.tsx
@@ -0,0 +1,118 @@
+/* oxlint-disable react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */
+import type { CanvasNodeContract } from '@workbench/canvas-engine/api';
+import type { Project } from '@workbench/projectContracts';
+import type * as WorkbenchContextModule from '@workbench/WorkbenchContext';
+
+import { ChakraProvider, Menu } from '@chakra-ui/react';
+import { system } from '@theme/system';
+import {
+ groupContract,
+ layerContract,
+ stacksFrom,
+} from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
+import { createInitialWorkbenchState } from '@workbench/workbenchState';
+import { createInstance } from 'i18next';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
+import { page, userEvent } from 'vitest/browser';
+
+const harness = vi.hoisted(() => ({ project: null as Project | null }));
+
+vi.mock('@workbench/WorkbenchContext', async (importOriginal) => ({
+ ...(await importOriginal<typeof WorkbenchContextModule>()),
+ useActiveProjectSelector: (selector: (project: Project) => unknown) => selector(harness.project!),
+}));
+vi.mock('@workbench/useNotify', () => ({ useNotify: () => ({ error: vi.fn(), info: vi.fn(), success: vi.fn() }) }));
+
+import { CanvasCropAllLayersMenuItem } from './CanvasCropAllLayersMenuItem';
+
+const i18n = createInstance();
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+beforeAll(async () => {
+ const translation = await fetch('/locales/en.json').then((response) => response.json());
+ await i18n.use(initReactI18next).init({ initAsync: false, lng: 'en', resources: { en: { translation } } });
+});
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+/** Opens a menu holding only the item, over a project whose canvas holds `nodes`. */
+const renderItem = async (nodes: CanvasNodeContract[], interactionLocked: boolean) => {
+ const base = createInitialWorkbenchState().projects[0]!;
+ harness.project = {
+ ...base,
+ canvas: { ...base.canvas, document: { ...base.canvas.document, stacks: stacksFrom(nodes) } },
+ };
+ const layers = { cropAllLayersToBbox: vi.fn(() => Promise.resolve({ status: 'busy' as const })) };
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ await act(() => {
+ root?.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <Menu.Root>
+ <Menu.Trigger>Canvas</Menu.Trigger>
+ <Menu.Positioner>
+ <Menu.Content>
+ <CanvasCropAllLayersMenuItem interactionLocked={interactionLocked} layers={layers} />
+ </Menu.Content>
+ </Menu.Positioner>
+ </Menu.Root>
+ </ChakraProvider>
+ </I18nextProvider>
+ );
+ });
+ await act(() => userEvent.click(page.getByRole('button', { name: 'Canvas' })));
+ const item = document.querySelector<HTMLElement>('[data-value="crop-all-layers-to-bbox"]')!;
+ await act(() => userEvent.keyboard('{ArrowDown}'));
+ await vi.waitFor(() => expect(item.hasAttribute('data-highlighted')).toBe(true));
+ return { item, layers };
+};
+
+const reasonOf = (item: HTMLElement): string | null | undefined =>
+ document.getElementById(item.getAttribute('aria-describedby') ?? '')?.textContent;
+
+describe('Crop all layers menu item', () => {
+ it.each([
+ [
+ 'every layer is locked, by itself or by its group',
+ [
+ layerContract('locked', 'raster', { isLocked: true }),
+ groupContract('G', [layerContract('inside', 'control')], { isLocked: true }),
+ ],
+ false,
+ 'Every layer is locked. Unlock a layer to crop it.',
+ ],
+ [
+ 'the canvas is busy',
+ [layerContract('free', 'raster')],
+ true,
+ 'Unavailable while the canvas is generating, has staged results, or is applying an edit.',
+ ],
+ ])('stays reachable and says why it cannot run when %s', async (_case, nodes, interactionLocked, reason) => {
+ const { item, layers } = await renderItem(nodes, interactionLocked);
+
+ expect(item).toHaveAttribute('aria-disabled', 'true');
+ expect(reasonOf(item)).toBe(reason);
+ await act(() => userEvent.keyboard('{Enter}'));
+ expect(layers.cropAllLayersToBbox).not.toHaveBeenCalled();
+ });
+
+ it('crops when an unlocked layer exists and the canvas is free', async () => {
+ const { item, layers } = await renderItem([layerContract('free', 'raster')], false);
+
+ expect(item).not.toHaveAttribute('aria-disabled');
+ await act(() => userEvent.keyboard('{Enter}'));
+ expect(layers.cropAllLayersToBbox).toHaveBeenCalledOnce();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasCropAllLayersMenuItem.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasCropAllLayersMenuItem.tsx
index f192dfa7fc..915c97e0c6 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasCropAllLayersMenuItem.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasCropAllLayersMenuItem.tsx
@@ -7,26 +7,33 @@ import { CropIcon } from 'lucide-react';
import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
-import { cropAllLayersToFrame, hasCroppableLayers } from './canvasContextMenu';
+import { cropAllLayersToFrame, getCropAllUnavailableReasonKey } from './canvasContextMenu';
-/** Canvas-menu action that crops every unlocked layer to the frame as one undo step and reports the count. */
+/**
+ * Canvas-menu action that crops every unlocked layer to the frame as one undo step and reports the count. While it
+ * cannot run it stays reachable by keyboard and says why.
+ */
export const CanvasCropAllLayersMenuItem = ({
- disabled,
+ interactionLocked,
layers,
}: {
- disabled: boolean;
+ /** The canvas is generating, has staged results, or is applying an edit. */
+ interactionLocked: boolean;
layers: Pick<CanvasEngineLayerCapability, 'cropAllLayersToBbox'>;
}) => {
const { t } = useTranslation();
const notify = useNotify();
- const hasCroppable = useActiveProjectSelector((project) => hasCroppableLayers(project.canvas.document));
+ const documentReasonKey = useActiveProjectSelector((project) =>
+ getCropAllUnavailableReasonKey(project.canvas.document)
+ );
+ const reasonKey = interactionLocked ? 'widgets.layers.actions.interactionLocked' : documentReasonKey;
const onSelect = useCallback(() => void cropAllLayersToFrame(layers, notify, t), [layers, notify, t]);
return (
<MenuActionItem
- disabled={disabled || !hasCroppable}
icon={CropIcon}
label={t('widgets.canvas.contextMenu.cropAllLayersToBbox')}
+ unavailableReason={reasonKey ? t(reasonKey) : undefined}
value="crop-all-layers-to-bbox"
onSelect={onSelect}
/>
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
index f82bbb9139..3b3ce1c630 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
@@ -41,12 +41,7 @@ import { CanvasCreateFromBboxSubmenu } from './CanvasCreateFromBboxSubmenu';
import { CanvasCropAllLayersMenuItem } from './CanvasCropAllLayersMenuItem';
import { CanvasEditRefusalNotices } from './CanvasEditRefusalNotices';
import { CanvasGlobalContextMenu } from './CanvasGlobalContextMenu';
-import {
- CANVAS_COMPANION_HOTKEYS,
- CANVAS_ONLY_HOTKEYS,
- executeCanvasHotkeyCommand,
- reportTransformRefusal,
-} from './canvasHotkeyCommands';
+import { CANVAS_ONLY_HOTKEYS, executeCanvasHotkeyCommand } from './canvasHotkeyCommands';
import { resolveCanvasImageDrop } from './canvasImageDnd';
import { CanvasImageDropOverlay } from './CanvasImageDropOverlay';
import { createCanvasInteractionLockReader, getCanvasInteractionCapabilities } from './canvasInteractionLock';
@@ -59,6 +54,7 @@ import {
} from './canvasSettings';
import { CanvasSurface } from './CanvasSurface';
import { CanvasSurfaceContextLayout } from './CanvasSurfaceContextLayout';
+import { CANVAS_COMPANION_HOTKEYS, reportTransformRefusal } from './canvasToolCommands';
import { resolveCheckerColors } from './checkerColors';
import { CanvasColorFeed } from './color-system/CanvasColorFeed';
import { useActiveColorCommands } from './color-system/useActiveColors';
@@ -497,16 +493,16 @@ export const CanvasWidgetView = ({ runtime, instance }: WidgetViewProps) => {
() => <CanvasCreateFromBboxSubmenu disabled={isCompositeMenuDisabled} onCreate={createFromBbox} />,
[createFromBbox, isCompositeMenuDisabled]
);
- const isCropAllDisabled = isInteractionLocked || interactionCapabilities.isDocumentEditingLocked;
+ const isCropAllLocked = isInteractionLocked || interactionCapabilities.isDocumentEditingLocked;
const compositeSubmenus = useMemo(
() => (
<>
{saveToGallerySubmenu}
{createFromBboxSubmenu}
- {engine ? <CanvasCropAllLayersMenuItem disabled={isCropAllDisabled} layers={engine.layers} /> : null}
+ {engine ? <CanvasCropAllLayersMenuItem interactionLocked={isCropAllLocked} layers={engine.layers} /> : null}
</>
),
- [createFromBboxSubmenu, engine, isCropAllDisabled, saveToGallerySubmenu]
+ [createFromBboxSubmenu, engine, isCropAllLocked, saveToGallerySubmenu]
);
const canvasSurface = useMemo(
() => (engine ? <CanvasSurface engine={engine} instanceId={instance.id} /> : null),
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.test.ts
index d8227bd1e1..1869b2c3f3 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.test.ts
@@ -11,7 +11,7 @@ import { describe, expect, it, vi } from 'vitest';
import {
cropAllLayersToFrame,
- hasCroppableLayers,
+ getCropAllUnavailableReasonKey,
resolveCanvasContextMenu,
resolveCanvasContextMenuBranch,
} from './canvasContextMenu';
@@ -89,29 +89,31 @@ describe('resolveCanvasContextMenu', () => {
});
});
-describe('hasCroppableLayers', () => {
+describe('getCropAllUnavailableReasonKey', () => {
const documentWith = (nodes: CanvasNodeContract[]): CanvasDocumentContractV3 => ({
...createEmptyCanvasDocument(),
stacks: stacksFrom(nodes),
});
it('finds a croppable leaf in any stack, hidden or disabled ones included', () => {
- expect(hasCroppableLayers(documentWith([layerContract('mask', 'inpaint_mask', { isEnabled: false })]))).toBe(true);
- expect(hasCroppableLayers(documentWith([groupContract('G', [layerContract('region', 'regional_guidance')])]))).toBe(
- true
- );
+ expect(
+ getCropAllUnavailableReasonKey(documentWith([layerContract('mask', 'inpaint_mask', { isEnabled: false })]))
+ ).toBeNull();
+ expect(
+ getCropAllUnavailableReasonKey(documentWith([groupContract('G', [layerContract('region', 'regional_guidance')])]))
+ ).toBeNull();
});
- it('has nothing to crop when every leaf is locked by itself or by a group above it', () => {
- expect(hasCroppableLayers(documentWith([]))).toBe(false);
+ it('says why there is nothing to crop: no layers, or every leaf locked by itself or a group above it', () => {
+ expect(getCropAllUnavailableReasonKey(documentWith([]))).toBe('widgets.canvas.contextMenu.cropAllNoLayers');
expect(
- hasCroppableLayers(
+ getCropAllUnavailableReasonKey(
documentWith([
layerContract('locked', 'raster', { isLocked: true }),
groupContract('G', [layerContract('inside', 'control')], { isLocked: true }),
])
)
- ).toBe(false);
+ ).toBe('widgets.canvas.contextMenu.cropAllAllLocked');
});
});
@@ -129,22 +131,43 @@ describe('cropAllLayersToFrame', () => {
};
it.each([
- [{ cropped: 1, skippedLocked: 0 }, ['Cropped 1 layer to the frame', undefined]],
- [{ cropped: 4, skippedLocked: 1 }, ['Cropped 4 layers to the frame', '1 locked layer skipped']],
- [{ cropped: 2, skippedLocked: 3 }, ['Cropped 2 layers to the frame', '3 locked layers skipped']],
- ])('reports %o as cropped, with the locked layers it skipped', async (counts, expected) => {
+ [{ cropped: 1, skippedLocked: 0, skippedUnreadable: 0 }, ['Cropped 1 layer to the frame', undefined]],
+ [
+ { cropped: 4, skippedLocked: 1, skippedUnreadable: 0 },
+ ['Cropped 4 layers to the frame', '1 locked layer skipped.'],
+ ],
+ [
+ { cropped: 2, skippedLocked: 3, skippedUnreadable: 0 },
+ ['Cropped 2 layers to the frame', '3 locked layers skipped.'],
+ ],
+ [
+ { cropped: 2, skippedLocked: 1, skippedUnreadable: 2 },
+ [
+ 'Cropped 2 layers to the frame',
+ '1 locked layer skipped. 2 layers could not be read and were left as they are.',
+ ],
+ ],
+ ])('reports %o as cropped, with the layers it left as they were', async (counts, expected) => {
expect(await notices({ status: 'cropped', ...counts })).toEqual({ error: [], info: [], success: [expected] });
});
it('says nothing needed cropping, and that only unlocked layers were checked when some were skipped', async () => {
- expect((await notices({ skippedLocked: 0, status: 'nothing' })).info).toEqual([
+ expect((await notices({ skippedLocked: 0, skippedUnreadable: 0, status: 'nothing' })).info).toEqual([
['Every layer already fits the frame', undefined],
]);
- expect((await notices({ skippedLocked: 2, status: 'nothing' })).info).toEqual([
- ['Every unlocked layer already fits the frame', '2 locked layers skipped'],
+ expect((await notices({ skippedLocked: 2, skippedUnreadable: 0, status: 'nothing' })).info).toEqual([
+ ['Every unlocked layer already fits the frame', '2 locked layers skipped.'],
]);
});
+ it('reports a crop that left only unreadable layers uncropped as a failure, never as still loading', async () => {
+ expect(await notices({ skippedLocked: 0, skippedUnreadable: 1, status: 'nothing' })).toEqual({
+ error: [['No layer was cropped', '1 layer could not be read and was left as it is.']],
+ info: [],
+ success: [],
+ });
+ });
+
it('names the layer whose adjustments prevented the crop', async () => {
const result = await notices({
ownerId: 'haze',
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.ts
index c5573ba4fd..bdc3eb7c01 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.ts
@@ -59,15 +59,24 @@ export const resolveCanvasContextMenu = ({
};
};
-/** Whether Crop all layers to frame has a leaf to act on: one not locked by itself or a group above it. */
-export const hasCroppableLayers = (document: CanvasDocumentContractV3): boolean => {
+/**
+ * Why Crop all layers to frame cannot run on `document`, or null when it has a leaf to act on: one not locked by
+ * itself or a group above it.
+ */
+export const getCropAllUnavailableReasonKey = (document: CanvasDocumentContractV3): string | null => {
const { byId, leaves } = getDocumentIndex(document);
- return leaves.some((leaf) => !leaf.isLocked && !byId.get(leaf.id)?.ancestorsLocked);
+ if (leaves.length === 0) {
+ return 'widgets.canvas.contextMenu.cropAllNoLayers';
+ }
+ return leaves.some((leaf) => !leaf.isLocked && !byId.get(leaf.id)?.ancestorsLocked)
+ ? null
+ : 'widgets.canvas.contextMenu.cropAllAllLocked';
};
/**
* Crops every unlocked layer to the frame as one undo step and says what happened: how many layers it cropped, how
- * many locked ones it skipped, or that nothing needed cropping. The canvas menu and the command share it.
+ * many locked or unreadable ones it left as they were, or that nothing needed cropping. The canvas menu and the
+ * command share it.
*/
export const cropAllLayersToFrame = async (
layers: Pick<CanvasEngineLayerCapability, 'cropAllLayersToBbox'>,
@@ -84,12 +93,19 @@ export const cropAllLayersToFrame = async (
switch (result.status) {
case 'cropped':
case 'nothing': {
+ const { skippedLocked, skippedUnreadable } = result;
const skipped =
- result.skippedLocked > 0
- ? t('widgets.canvas.contextMenu.croppedAllLayersSkipped', { count: result.skippedLocked })
- : undefined;
+ [
+ skippedLocked > 0 ? t('widgets.canvas.contextMenu.croppedAllLayersSkipped', { count: skippedLocked }) : '',
+ skippedUnreadable > 0 ? t('widgets.canvas.contextMenu.cropAllUnreadable', { count: skippedUnreadable }) : '',
+ ]
+ .filter(Boolean)
+ .join(' ') || undefined;
if (result.status === 'cropped') {
notify.success(t('widgets.canvas.contextMenu.croppedAllLayers', { count: result.cropped }), skipped);
+ } else if (skippedUnreadable > 0) {
+ // Those layers needed cropping and could not be read: nothing the user asked for happened.
+ notify.error(t('widgets.canvas.contextMenu.cropAllNoneCropped'), skipped);
} else {
notify.info(
t(
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts
index 6d57e1e9ed..31cbc7062a 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts
@@ -18,14 +18,8 @@ import { createControlLayer } from '@workbench/widgets/layers/layerOps';
import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest';
import { CANVAS_HEADER_HOTKEYS } from './canvasHeaderCommands';
-import {
- CANVAS_COMPANION_HOTKEYS,
- CANVAS_ONLY_HOTKEYS,
- executeCanvasHotkeyCommand,
- executeCanvasToolCommand,
- reportTransformRefusal,
- type CanvasHotkeyContext,
-} from './canvasHotkeyCommands';
+import { CANVAS_ONLY_HOTKEYS, executeCanvasHotkeyCommand, type CanvasHotkeyContext } from './canvasHotkeyCommands';
+import { CANVAS_COMPANION_HOTKEYS, executeCanvasToolCommand, reportTransformRefusal } from './canvasToolCommands';
const rasterLayer = (id: string, overrides: Partial<CanvasLayerContract> = {}): CanvasLayerContract =>
({
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
index db6b696b48..1664cf798a 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
@@ -1,5 +1,4 @@
import type {
- BeginTransformResult,
AdjustmentRefusal,
CanvasDocumentContractV3,
CanvasEngine,
@@ -7,7 +6,6 @@ import type {
StructuralCommitResult,
} from '@workbench/canvas-engine/api';
import type { CanvasProjectMutationDispatch } from '@workbench/useCanvasProjectMutationDispatch';
-import type { TFunction } from 'i18next';
import {
compileDocumentLeaves,
@@ -17,9 +15,15 @@ import {
isOverlayStack,
} from '@workbench/canvas-engine/api';
import { publishLayerPanelSelection } from '@workbench/layerPanelState';
+import {
+ CANVAS_HISTORY_HOTKEYS,
+ executeCanvasToolCommand,
+ isCanvasToolCommand,
+ type CanvasToolCommandContext,
+ type HotkeyTableEntry,
+} from '@workbench/widgets/canvas/canvasToolCommands';
import {
commitPreparedEdit,
- reportLayerOperation,
type LayerOperationRefusal,
type PreparedCommitOutcome,
} from '@workbench/widgets/canvas/useStructuralCommit';
@@ -33,37 +37,6 @@ import {
} from '@workbench/widgets/layers/layerGroupCommands';
import { canMergeLayerDown } from '@workbench/widgets/layers/layerOps';
-type HotkeyTableEntry = readonly [id: string, titleKey: string, defaultKeys: readonly string[]];
-
-/**
- * Canvas keys that also act while a companion widget (Layers, with its Color pane) holds focus: tools, the
- * transform session, brush size and the color pair. The Canvas and the companion both register from this table.
- */
-export const CANVAS_COMPANION_HOTKEYS = [
- ['canvas.tool.view', 'widgets.canvas.commands.selectViewTool', ['h']],
- ['canvas.tool.move', 'widgets.canvas.commands.selectMoveTool', ['v']],
- ['canvas.transformSelected', 'widgets.canvas.commands.selectTransformTool', ['shift+t']],
- ['canvas.tool.bbox', 'widgets.canvas.commands.selectBboxTool', []],
- ['canvas.tool.brush', 'widgets.canvas.commands.selectBrushTool', ['b']],
- ['canvas.tool.eraser', 'widgets.canvas.commands.selectEraserTool', ['e']],
- ['canvas.tool.lasso', 'widgets.canvas.commands.selectLassoTool', ['l']],
- ['canvas.tool.marquee', 'widgets.canvas.commands.selectMarqueeTool', ['u']],
- ['canvas.tool.shape', 'widgets.canvas.commands.selectShapeTool', ['r']],
- ['canvas.tool.text', 'widgets.canvas.commands.selectTextTool', ['t']],
- ['canvas.tool.gradient', 'widgets.canvas.commands.selectGradientTool', ['g']],
- ['canvas.brushSizeDown', 'widgets.canvas.commands.decreaseBrushSize', ['[']],
- ['canvas.brushSizeUp', 'widgets.canvas.commands.increaseBrushSize', [']']],
- // The active color pair: X swaps, D resets to black/white.
- ['canvas.toggleFillColor', 'widgets.canvas.commands.swapColors', ['x']],
- ['canvas.setFillColorsToDefault', 'widgets.canvas.commands.resetColors', ['d']],
-] as const satisfies readonly HotkeyTableEntry[];
-
-/** Canvas history, which the Canvas and its companion widgets both bind. */
-export const CANVAS_HISTORY_HOTKEYS = [
- ['canvas.undo', 'widgets.canvas.commands.undo', ['mod+z']],
- ['canvas.redo', 'widgets.canvas.commands.redo', ['mod+shift+z', 'mod+y']],
-] as const satisfies readonly HotkeyTableEntry[];
-
/** Keys that act only while the Canvas itself holds focus; rows and fields own them elsewhere. */
export const CANVAS_ONLY_HOTKEYS = [
...CANVAS_HISTORY_HOTKEYS,
@@ -104,139 +77,6 @@ export const CANVAS_ONLY_HOTKEYS = [
['canvas.cropAllLayersToFrame', 'widgets.canvas.contextMenu.cropAllLayersToBbox', []],
] as const satisfies readonly HotkeyTableEntry[];
-export type CanvasToolCommandId = (typeof CANVAS_COMPANION_HOTKEYS)[number][0];
-
-const CANVAS_TOOL_COMMAND_IDS: ReadonlySet<string> = new Set(CANVAS_COMPANION_HOTKEYS.map(([id]) => id));
-
-export const isCanvasToolCommand = (commandId: string): commandId is CanvasToolCommandId =>
- CANVAS_TOOL_COMMAND_IDS.has(commandId);
-
-export type TransformRefusal = Exclude<BeginTransformResult, 'started'>;
-
-/** Explains a refused `beginTransform`; a layer Transform cannot act on gets Transform's own reason. */
-export const reportTransformRefusal = (
- refusal: TransformRefusal,
- reportError: (title: string, message: string) => void,
- t: TFunction
-): void => {
- if (refusal === 'ineligible') {
- reportError(t('widgets.layers.actions.actionFailed'), t('widgets.layers.actions.transformIneligible'));
- } else {
- reportLayerOperation(refusal, reportError, t);
- }
-};
-
-/** What the companion keys need; the Canvas and the Layers widget each build it from their own state. */
-export interface CanvasToolCommandContext {
- readonly engine: Pick<CanvasEngine, 'interaction' | 'layers' | 'tools'> | null;
- readonly isInteractionLocked: boolean;
- /** The selected leaf that Transform opens on; null when nothing or a group is selected. */
- readonly selectedLayerId: string | null;
- /** Swaps the project foreground/background pair — a preference, never a document edit. */
- readonly swapActiveColors: () => void;
- /** Resets the pair to the black-on-white default. */
- readonly resetActiveColors: () => void;
- readonly reportTransformRefusal: (refusal: TransformRefusal) => void;
-}
-
-/**
- * Runs one companion key. The color pair is a preference, not a document edit, so X/D stay live while the surface
- * is interaction-locked; of the rest only the view tool works then.
- */
-export const executeCanvasToolCommand = (commandId: CanvasToolCommandId, ctx: CanvasToolCommandContext): void => {
- const { engine } = ctx;
- if (commandId === 'canvas.toggleFillColor') {
- ctx.swapActiveColors();
- return;
- }
- if (commandId === 'canvas.setFillColorsToDefault') {
- ctx.resetActiveColors();
- return;
- }
- if (ctx.isInteractionLocked && commandId !== 'canvas.tool.view') {
- return;
- }
- if (!engine) {
- return;
- }
- switch (commandId) {
- case 'canvas.tool.view':
- engine.tools.setTool('view');
- return;
- case 'canvas.tool.move':
- engine.tools.setTool('move');
- return;
- case 'canvas.transformSelected': {
- // A selected leaf opens its session at once, even with Transform already active; otherwise only the tool
- // changes. Apply/Cancel (Enter/Escape) are handled engine-side.
- if (ctx.selectedLayerId === null) {
- engine.tools.setTool('transform');
- return;
- }
- const result = engine.layers.beginTransform(ctx.selectedLayerId);
- // A key pressed mid-gesture is dropped quietly; the gesture already says why.
- if (result !== 'started' && result !== 'busy') {
- ctx.reportTransformRefusal(result);
- }
- return;
- }
- case 'canvas.tool.bbox':
- engine.tools.setTool('bbox');
- return;
- case 'canvas.tool.brush':
- engine.tools.setTool('brush');
- return;
- case 'canvas.tool.eraser':
- engine.tools.setTool('eraser');
- return;
- case 'canvas.tool.lasso':
- // Repeating the active tool shortcut cycles its shape.
- if (engine.interaction.get('activeTool') === 'lasso') {
- const lasso = engine.interaction.get('lassoOptions');
- engine.interaction.set('lassoOptions', {
- ...lasso,
- shape: lasso.shape === 'freehand' ? 'polygon' : 'freehand',
- });
- } else {
- engine.tools.setTool('lasso');
- }
- return;
- case 'canvas.tool.marquee':
- if (engine.interaction.get('activeTool') === 'marquee') {
- const marquee = engine.interaction.get('marqueeOptions');
- engine.interaction.set('marqueeOptions', {
- ...marquee,
- kind: marquee.kind === 'rect' ? 'ellipse' : 'rect',
- });
- } else {
- engine.tools.setTool('marquee');
- }
- return;
- case 'canvas.tool.shape':
- if (engine.interaction.get('activeTool') === 'shape') {
- // Repeat presses cycle the kind, like the marquee hotkey.
- const shape = engine.interaction.get('shapeOptions');
- const order = ['rect', 'ellipse', 'triangle', 'star', 'polygon', 'freehand'] as const;
- const next = order[(order.indexOf(shape.kind) + 1) % order.length]!;
- engine.interaction.set('shapeOptions', { ...shape, kind: next });
- } else {
- engine.tools.setTool('shape');
- }
- return;
- case 'canvas.tool.text':
- engine.tools.setTool('text');
- return;
- case 'canvas.tool.gradient':
- engine.tools.setTool('gradient');
- return;
- case 'canvas.brushSizeDown':
- engine.tools.stepBrushSize(-1);
- return;
- case 'canvas.brushSizeUp':
- engine.tools.stepBrushSize(1);
- }
-};
-
/** Command id → document-space nudge delta (shift variants are ×10). */
const NUDGE_DELTAS: Record<string, { dx: number; dy: number }> = {
'canvas.nudgeDown': { dx: 0, dy: 1 },
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasToolCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasToolCommands.ts
new file mode 100644
index 0000000000..56af262fa7
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasToolCommands.ts
@@ -0,0 +1,170 @@
+import type { BeginTransformResult, CanvasEngine } from '@workbench/canvas-engine/api';
+import type { TFunction } from 'i18next';
+
+import { reportLayerOperation } from '@workbench/widgets/canvas/useStructuralCommit';
+
+/** One hotkey row: its command id, title key and default keys. */
+export type HotkeyTableEntry = readonly [id: string, titleKey: string, defaultKeys: readonly string[]];
+
+/**
+ * Canvas keys that also act while a companion widget (Layers, with its Color pane) holds focus: tools, the
+ * transform session, brush size and the color pair. The Canvas and the companion both register from this table;
+ * companions import this module alone, without the Canvas's full dispatcher (`canvasHotkeyCommands.ts`).
+ */
+export const CANVAS_COMPANION_HOTKEYS = [
+ ['canvas.tool.view', 'widgets.canvas.commands.selectViewTool', ['h']],
+ ['canvas.tool.move', 'widgets.canvas.commands.selectMoveTool', ['v']],
+ ['canvas.transformSelected', 'widgets.canvas.commands.selectTransformTool', ['shift+t']],
+ ['canvas.tool.bbox', 'widgets.canvas.commands.selectBboxTool', []],
+ ['canvas.tool.brush', 'widgets.canvas.commands.selectBrushTool', ['b']],
+ ['canvas.tool.eraser', 'widgets.canvas.commands.selectEraserTool', ['e']],
+ ['canvas.tool.lasso', 'widgets.canvas.commands.selectLassoTool', ['l']],
+ ['canvas.tool.marquee', 'widgets.canvas.commands.selectMarqueeTool', ['u']],
+ ['canvas.tool.shape', 'widgets.canvas.commands.selectShapeTool', ['r']],
+ ['canvas.tool.text', 'widgets.canvas.commands.selectTextTool', ['t']],
+ ['canvas.tool.gradient', 'widgets.canvas.commands.selectGradientTool', ['g']],
+ ['canvas.brushSizeDown', 'widgets.canvas.commands.decreaseBrushSize', ['[']],
+ ['canvas.brushSizeUp', 'widgets.canvas.commands.increaseBrushSize', [']']],
+ // The active color pair: X swaps, D resets to black/white.
+ ['canvas.toggleFillColor', 'widgets.canvas.commands.swapColors', ['x']],
+ ['canvas.setFillColorsToDefault', 'widgets.canvas.commands.resetColors', ['d']],
+] as const satisfies readonly HotkeyTableEntry[];
+
+/** Canvas history, which the Canvas and its companion widgets both bind. */
+export const CANVAS_HISTORY_HOTKEYS = [
+ ['canvas.undo', 'widgets.canvas.commands.undo', ['mod+z']],
+ ['canvas.redo', 'widgets.canvas.commands.redo', ['mod+shift+z', 'mod+y']],
+] as const satisfies readonly HotkeyTableEntry[];
+
+export type CanvasToolCommandId = (typeof CANVAS_COMPANION_HOTKEYS)[number][0];
+
+const CANVAS_TOOL_COMMAND_IDS: ReadonlySet<string> = new Set(CANVAS_COMPANION_HOTKEYS.map(([id]) => id));
+
+export const isCanvasToolCommand = (commandId: string): commandId is CanvasToolCommandId =>
+ CANVAS_TOOL_COMMAND_IDS.has(commandId);
+
+export type TransformRefusal = Exclude<BeginTransformResult, 'started'>;
+
+/** Explains a refused `beginTransform`; a layer Transform cannot act on gets Transform's own reason. */
+export const reportTransformRefusal = (
+ refusal: TransformRefusal,
+ reportError: (title: string, message: string) => void,
+ t: TFunction
+): void => {
+ if (refusal === 'ineligible') {
+ reportError(t('widgets.layers.actions.actionFailed'), t('widgets.layers.actions.transformIneligible'));
+ } else {
+ reportLayerOperation(refusal, reportError, t);
+ }
+};
+
+/** What the companion keys need; the Canvas and the Layers widget each build it from their own state. */
+export interface CanvasToolCommandContext {
+ readonly engine: Pick<CanvasEngine, 'interaction' | 'layers' | 'tools'> | null;
+ readonly isInteractionLocked: boolean;
+ /** The selected leaf that Transform opens on; null when nothing or a group is selected. */
+ readonly selectedLayerId: string | null;
+ /** Swaps the project foreground/background pair — a preference, never a document edit. */
+ readonly swapActiveColors: () => void;
+ /** Resets the pair to the black-on-white default. */
+ readonly resetActiveColors: () => void;
+ readonly reportTransformRefusal: (refusal: TransformRefusal) => void;
+}
+
+/**
+ * Runs one companion key. The color pair is a preference, not a document edit, so X/D stay live while the surface
+ * is interaction-locked; of the rest only the view tool works then.
+ */
+export const executeCanvasToolCommand = (commandId: CanvasToolCommandId, ctx: CanvasToolCommandContext): void => {
+ const { engine } = ctx;
+ if (commandId === 'canvas.toggleFillColor') {
+ ctx.swapActiveColors();
+ return;
+ }
+ if (commandId === 'canvas.setFillColorsToDefault') {
+ ctx.resetActiveColors();
+ return;
+ }
+ if (ctx.isInteractionLocked && commandId !== 'canvas.tool.view') {
+ return;
+ }
+ if (!engine) {
+ return;
+ }
+ switch (commandId) {
+ case 'canvas.tool.view':
+ engine.tools.setTool('view');
+ return;
+ case 'canvas.tool.move':
+ engine.tools.setTool('move');
+ return;
+ case 'canvas.transformSelected': {
+ // A selected leaf opens its session at once, even with Transform already active; otherwise only the tool
+ // changes. Apply/Cancel (Enter/Escape) are handled engine-side.
+ if (ctx.selectedLayerId === null) {
+ engine.tools.setTool('transform');
+ return;
+ }
+ const result = engine.layers.beginTransform(ctx.selectedLayerId);
+ // A key pressed mid-gesture is dropped quietly; the gesture already says why.
+ if (result !== 'started' && result !== 'busy') {
+ ctx.reportTransformRefusal(result);
+ }
+ return;
+ }
+ case 'canvas.tool.bbox':
+ engine.tools.setTool('bbox');
+ return;
+ case 'canvas.tool.brush':
+ engine.tools.setTool('brush');
+ return;
+ case 'canvas.tool.eraser':
+ engine.tools.setTool('eraser');
+ return;
+ case 'canvas.tool.lasso':
+ // Repeating the active tool shortcut cycles its shape.
+ if (engine.interaction.get('activeTool') === 'lasso') {
+ const lasso = engine.interaction.get('lassoOptions');
+ engine.interaction.set('lassoOptions', {
+ ...lasso,
+ shape: lasso.shape === 'freehand' ? 'polygon' : 'freehand',
+ });
+ } else {
+ engine.tools.setTool('lasso');
+ }
+ return;
+ case 'canvas.tool.marquee':
+ if (engine.interaction.get('activeTool') === 'marquee') {
+ const marquee = engine.interaction.get('marqueeOptions');
+ engine.interaction.set('marqueeOptions', {
+ ...marquee,
+ kind: marquee.kind === 'rect' ? 'ellipse' : 'rect',
+ });
+ } else {
+ engine.tools.setTool('marquee');
+ }
+ return;
+ case 'canvas.tool.shape':
+ if (engine.interaction.get('activeTool') === 'shape') {
+ // Repeat presses cycle the kind, like the marquee hotkey.
+ const shape = engine.interaction.get('shapeOptions');
+ const order = ['rect', 'ellipse', 'triangle', 'star', 'polygon', 'freehand'] as const;
+ const next = order[(order.indexOf(shape.kind) + 1) % order.length]!;
+ engine.interaction.set('shapeOptions', { ...shape, kind: next });
+ } else {
+ engine.tools.setTool('shape');
+ }
+ return;
+ case 'canvas.tool.text':
+ engine.tools.setTool('text');
+ return;
+ case 'canvas.tool.gradient':
+ engine.tools.setTool('gradient');
+ return;
+ case 'canvas.brushSizeDown':
+ engine.tools.stepBrushSize(-1);
+ return;
+ case 'canvas.brushSizeUp':
+ engine.tools.stepBrushSize(1);
+ }
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts
index ced828a3c9..3dd32eae35 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts
@@ -360,7 +360,9 @@ export const runCanvasInvocation = async (deps: RunCanvasInvocationDeps): Promis
? 'The canvas changed while generation was being prepared. Please invoke again.'
: composed.status === 'adjustment-refused'
? ADJUSTMENT_REFUSAL_NOTICES[composed.reason](composed.ownerName)
- : `The canvas could not be captured for generation (${composed.status}).`
+ : composed.status === 'unreadable'
+ ? "A layer's image could not be read (it may have been deleted or damaged). Disable or delete that layer, then invoke again."
+ : `The canvas could not be captured for generation (${composed.status}).`
);
return;
}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.test.tsx
index dfe0a67d84..27f7ea04b5 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.test.tsx
@@ -160,6 +160,7 @@ describe('getFilterErrorTranslationKey', () => {
'source-adjustment-over-budget': true,
'source-adjustment-too-large': true,
'source-over-budget': true,
+ 'source-unreadable': true,
stale: true,
unsupported: true,
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.tsx
index 7597784272..279dc73fa2 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.tsx
@@ -88,6 +88,7 @@ const FILTER_ERROR_TRANSLATION_KEYS: Record<FilterSessionErrorCode, string> = {
'source-adjustment-over-budget': 'widgets.layers.rasterFilter.sourceAdjustmentOverBudget',
'source-adjustment-too-large': 'widgets.layers.rasterFilter.sourceAdjustmentTooLarge',
'source-over-budget': 'widgets.layers.rasterFilter.sourceOverBudget',
+ 'source-unreadable': 'widgets.layers.rasterFilter.sourceUnreadable',
stale: 'widgets.layers.rasterFilter.stale',
unsupported: 'widgets.layers.rasterFilter.unsupported',
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.tsx
index 1e6f80469f..2619160d20 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.tsx
@@ -87,6 +87,7 @@ const SAM_ERROR_TRANSLATION_KEYS: Record<SamSessionErrorCode, string> = {
queue: 'widgets.layers.selectObject.errorQueue',
reconcile: 'widgets.layers.selectObject.errorReconcile',
unknown: 'widgets.layers.selectObject.errorUnknown',
+ unreadable: 'widgets.layers.selectObject.errorUnreadable',
upload: 'widgets.layers.selectObject.errorUpload',
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.browser.test.tsx
index 22eb49b7c1..7aa1085a4a 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.browser.test.tsx
@@ -16,6 +16,8 @@ import { useCanvasGallerySave } from './useCanvasGallerySave';
const mocks = vi.hoisted(() => ({
activeProjectId: 'project-1',
findGalleryItem: vi.fn(),
+ notifyError: vi.fn(),
+ notifyInfo: vi.fn(),
reportError: vi.fn(),
saveCanvasToGallery: vi.fn<(options: { region: CanvasGallerySaveRegion }) => Promise<unknown>>(),
}));
@@ -31,7 +33,9 @@ vi.mock('@workbench/WorkbenchContext', () => ({
}),
}));
vi.mock('@workbench/image-actions/useFindGalleryItem', () => ({ useFindGalleryItem: () => mocks.findGalleryItem }));
-vi.mock('@workbench/useNotify', () => ({ useNotify: () => ({ error: vi.fn(), info: vi.fn(), success: vi.fn() }) }));
+vi.mock('@workbench/useNotify', () => ({
+ useNotify: () => ({ error: mocks.notifyError, info: mocks.notifyInfo, success: vi.fn() }),
+}));
vi.mock('@features/gallery/queries', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
// The auto-add board, B, as the Gallery's board listing names it.
@@ -134,6 +138,19 @@ describe('useCanvasGallerySave across surfaces', () => {
await act(() => menu.current!.save('canvas'));
expect(mocks.saveCanvasToGallery).toHaveBeenCalledTimes(2);
});
+ it('says a layer could not be read rather than that the canvas is still preparing', async () => {
+ mocks.saveCanvasToGallery.mockResolvedValueOnce({ status: 'unreadable' });
+
+ await act(() => header.current!.save('canvas'));
+
+ expect(mocks.notifyError).toHaveBeenCalledWith(
+ 'widgets.canvas.contextMenu.saveError',
+ 'widgets.canvas.contextMenu.unreadable'
+ );
+ expect(mocks.notifyInfo).not.toHaveBeenCalled();
+ expect(mocks.reportError).not.toHaveBeenCalled();
+ });
+
it.each([
[
'refuses the board (403)',
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.ts
index 7fff4fbafd..b0f5acb1ec 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.ts
@@ -90,6 +90,8 @@ export const useCanvasGallerySave = (
notify.info(t('widgets.canvas.contextMenu.stale'));
} else if (result.status === 'adjustment-refused') {
notify.error(t('widgets.canvas.contextMenu.saveError'), describeAdjustmentRefusal(result, t));
+ } else if (result.status === 'unreadable') {
+ notify.error(t('widgets.canvas.contextMenu.saveError'), t('widgets.canvas.contextMenu.unreadable'));
} else {
notify.info(t('widgets.canvas.contextMenu.notReady'));
}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.ts
index 70a6a55fba..09d2fe82ee 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.ts
@@ -29,6 +29,7 @@ export type LayerOperationRefusal =
| 'not-ready'
| 'over-budget'
| 'stale'
+ | 'unreadable'
| 'unsupported';
const LAYER_OPERATION_KEYS: Record<LayerOperationRefusal, string> = {
@@ -40,6 +41,7 @@ const LAYER_OPERATION_KEYS: Record<LayerOperationRefusal, string> = {
'not-ready': 'widgets.layers.actions.notReady',
'over-budget': 'widgets.layers.actions.overBudget',
stale: 'widgets.layers.actions.stale',
+ unreadable: 'widgets.layers.actions.unreadable',
unsupported: 'widgets.layers.actions.unsupported',
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.browser.test.tsx
new file mode 100644
index 0000000000..98d3be391c
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.browser.test.tsx
@@ -0,0 +1,242 @@
+/* oxlint-disable react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */
+import type { CanvasLayerContract, CanvasNodeContract } from '@workbench/canvas-engine/api';
+import type { CanvasEngine } from '@workbench/canvas-operations/createCanvasEngine';
+import type { Project } from '@workbench/projectContracts';
+import type * as WorkbenchContextModule from '@workbench/WorkbenchContext';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { system } from '@theme/system';
+import { getDocumentIndex, getDocumentLeaves } from '@workbench/canvas-engine/api';
+import {
+ groupContract,
+ layerContract,
+ stacksFrom,
+} from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
+import { createCanvasEngine } from '@workbench/canvas-operations/createCanvasEngine';
+import { createCanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';
+import { clearLayerPanelStates, publishLayerPanelSelection } from '@workbench/layerPanelState';
+import { createInitialWorkbenchState } from '@workbench/workbenchState';
+import { createWorkbenchStore } from '@workbench/workbenchStore';
+import { createInstance } from 'i18next';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
+import { page, userEvent } from 'vitest/browser';
+
+/** The menu reads the real store and drives a real engine over real decoded pixels. */
+const harness = vi.hoisted(() => ({
+ engine: null as CanvasEngine | null,
+ store: null as ReturnType<typeof createWorkbenchStore> | null,
+}));
+const activeProject = () => harness.store!.getState().projects[0]!;
+
+vi.mock('@workbench/WorkbenchContext', async (importOriginal) => ({
+ ...(await importOriginal<typeof WorkbenchContextModule>()),
+ useActiveProjectId: () => activeProject().id,
+ useActiveProjectSelector: (selector: (project: Project) => unknown) => selector(activeProject()),
+ useOptionalWorkbenchCommands: () => harness.store!.commands,
+ useWorkbenchCommands: () => harness.store!.commands,
+}));
+
+import { CanvasLayerContextMenu } from './LayerContextMenu';
+
+const i18n = createInstance();
+let root: Root | null = null;
+let host: HTMLDivElement | null = null;
+let pixels: Blob;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+beforeAll(async () => {
+ const translation = await fetch('/locales/en.json').then((response) => response.json());
+ await i18n.use(initReactI18next).init({ initAsync: false, lng: 'en', resources: { en: { translation } } });
+ const canvas = new OffscreenCanvas(16, 16);
+ const context = canvas.getContext('2d')!;
+ context.fillStyle = '#fff';
+ context.fillRect(0, 0, 16, 16);
+ pixels = await canvas.convertToBlob({ type: 'image/png' });
+});
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ harness.engine?.lifecycle.dispose();
+ Object.assign(harness, { engine: null, store: null });
+ clearLayerPanelStates();
+ root = null;
+ host = null;
+});
+
+const image = (name: string) => ({ height: 16, imageName: `${name}.png`, width: 16 });
+const imageLayer = (id: string): CanvasLayerContract =>
+ layerContract(id, 'raster', {
+ name: id,
+ source: { image: image(id), type: 'image' },
+ } as Partial<CanvasLayerContract>);
+const maskLayer = (id: string, overrides: Partial<CanvasLayerContract> = {}): CanvasLayerContract =>
+ layerContract(id, 'inpaint_mask', {
+ mask: { bitmap: image(id), fill: { color: '#e45050', style: 'solid' }, offset: { x: 0, y: 0 } },
+ name: id,
+ ...overrides,
+ } as Partial<CanvasLayerContract>);
+
+/**
+ * Renders the Layers panel's layer menu over a real engine for `nodes`, with `selectedIds` selected in the panel (the
+ * first as primary), returning a way to open it on a layer. Images named in `unreadable` fail to load.
+ */
+const renderMenu = async (
+ nodes: CanvasNodeContract[],
+ selectedIds: readonly string[] = [],
+ unreadable: readonly string[] = []
+) => {
+ const initial = createInitialWorkbenchState();
+ const base = initial.projects[0]!;
+ const store = createWorkbenchStore({
+ ...initial,
+ projects: [
+ {
+ ...base,
+ canvas: {
+ ...base.canvas,
+ document: { ...base.canvas.document, selectedLayerId: selectedIds[0] ?? null, stacks: stacksFrom(nodes) },
+ },
+ },
+ ],
+ });
+ const projectId = store.getState().activeProjectId;
+ harness.store = store;
+ publishLayerPanelSelection({ primaryId: selectedIds[0] ?? null, projectId, selectedIds });
+ const engine = createCanvasEngine({
+ ensureProjectOnServer: () => Promise.resolve(),
+ imageResolver: (imageName) =>
+ unreadable.includes(imageName) ? Promise.reject(new Error('image deleted')) : Promise.resolve(pixels),
+ mutationPort: createCanvasProjectMutationPort(store, projectId),
+ projectId,
+ reportError: () => undefined,
+ });
+ harness.engine = engine;
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ const queryClient = new QueryClient();
+ const render = (layerId: string | null) =>
+ act(() =>
+ root!.render(
+ <QueryClientProvider client={queryClient}>
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <CanvasLayerContextMenu
+ engine={engine}
+ target={layerId ? { layerId, x: 40, y: 40 } : null}
+ onClose={() => void render(null)}
+ />
+ </ChakraProvider>
+ </I18nextProvider>
+ </QueryClientProvider>
+ )
+ );
+ await render(null);
+ const openMenu = async (layerId: string) => {
+ await render(layerId);
+ await expect.element(page.getByRole('menu')).toBeVisible();
+ };
+ const document_ = () => store.getState().projects[0]!.canvas.document;
+ const notices = () => store.getState().notifications.map(({ message, title }) => [title, message]);
+ return { document: document_, engine, notices, openMenu };
+};
+
+const item = (name: string) => page.getByRole('menuitem', { exact: true, name });
+
+describe('Layers context menu over a real engine', () => {
+ it('opens a transform session on the chosen layer while the Transform tool is already active', async () => {
+ const { engine, openMenu } = await renderMenu([imageLayer('top'), imageLayer('art')]);
+ engine.tools.setTool('transform');
+ expect(engine.stores.transformSession.get()).toBeNull();
+
+ await openMenu('art');
+ await act(() => item('Transform').click());
+
+ await vi.waitFor(() => expect(engine.stores.transformSession.get()?.layerId).toBe('art'));
+ expect(engine.document.getDocument()?.selectedLayerId).toBe('art');
+ });
+
+ it('merges two selected masks into one', async () => {
+ const { document, engine, openMenu } = await renderMenu([maskLayer('m1'), maskLayer('m2')], ['m1', 'm2']);
+ await vi.waitFor(() => expect(['m1', 'm2'].every((id) => engine.exports.hasExportableLayerContent(id))).toBe(true));
+
+ await openMenu('m1');
+ await act(() => item('Merge masks').click());
+
+ await vi.waitFor(() =>
+ expect(getDocumentLeaves(document()).map((layer) => [layer.type, layer.name])).toEqual([
+ ['inpaint_mask', 'm1 merged'],
+ ])
+ );
+ expect(engine.history.getEntries().past).toEqual(['Merge masks']);
+ });
+
+ it('removes a layer from its group as one undo step', async () => {
+ const { document, engine, openMenu } = await renderMenu([
+ groupContract('G', [imageLayer('child'), imageLayer('sibling')]),
+ ]);
+ const parentOf = (id: string) => getDocumentIndex(document()).byId.get(id)?.parentId;
+
+ await openMenu('child');
+ await act(() => item('Remove from group').click());
+
+ await vi.waitFor(() => expect(parentOf('child')).toBeNull());
+ expect(engine.history.getEntries().past).toHaveLength(1);
+ await act(() => engine.history.undo());
+ expect(parentOf('child')).toBe('G');
+ expect(engine.history.getEntries().past).toHaveLength(0);
+ });
+
+ it.each([
+ ['Crop layer to frame', ['gone'], []],
+ ['Merge selected layers', ['gone', 'kept'], ['kept']],
+ ] as const)(
+ 'says %s could not read a missing image, never that it is still loading',
+ async (label, ids, readable) => {
+ const { document, notices, openMenu } = await renderMenu(
+ ids.map(imageLayer),
+ ids,
+ ids.filter((id) => !(readable as readonly string[]).includes(id)).map((id) => `${id}.png`)
+ );
+ const before = document();
+
+ await openMenu('gone');
+ await act(() => item(label).click());
+
+ await vi.waitFor(() =>
+ expect(notices()).toContainEqual([
+ 'Layer action failed',
+ "A layer's image could not be read (it may have been deleted or damaged), so nothing was changed.",
+ ])
+ );
+ expect(notices().flat()).not.toContain('The layer content is still loading. Try again shortly.');
+ expect(document().stacks).toBe(before.stacks);
+ }
+ );
+
+ it('keeps an unavailable Merge masks reachable by keyboard and says why', async () => {
+ const { engine, openMenu } = await renderMenu(
+ [maskLayer('m1'), maskLayer('m2', { noise: { isEnabled: true, level: 0.5 } } as Partial<CanvasLayerContract>)],
+ ['m1', 'm2']
+ );
+ const reason = 'The masks have different noise or denoise settings. Match them to merge.';
+
+ await openMenu('m1');
+ const merge = document.querySelector<HTMLElement>('[role="menuitem"][data-value="merge-masks"]')!;
+ expect(merge).toHaveAttribute('aria-disabled', 'true');
+ for (let step = 0; step < 30 && !merge.hasAttribute('data-highlighted'); step += 1) {
+ await userEvent.keyboard('{ArrowDown}');
+ }
+ expect(merge).toHaveAttribute('data-highlighted');
+ await expect.element(page.getByRole('tooltip')).toHaveTextContent(reason);
+ expect(document.getElementById(merge.getAttribute('aria-describedby')!)).toHaveTextContent(reason);
+
+ await userEvent.keyboard('{Enter}');
+ expect(getDocumentLeaves(engine.document.getDocument()!).map((layer) => layer.id)).toEqual(['m1', 'm2']);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
index 356a4e76b2..114dc91b2c 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
@@ -26,6 +26,7 @@ import {
getDocumentIndex,
getDocumentLayer,
getSourceContentRect,
+ inpaintMaskMergeEligibility,
isAdjustmentRefusal,
isGroupNode,
isHideableLayer,
@@ -40,8 +41,8 @@ import { ShortcutKeycaps } from '@workbench/hotkeys/keyGlyphs';
import { formatHotkeyForPlatform } from '@workbench/hotkeys/keys';
import { publishLayerPanelSelection, readLayerPanelState, useLayerPanelState } from '@workbench/layerPanelState';
import { useNotify } from '@workbench/useNotify';
-import { reportTransformRefusal } from '@workbench/widgets/canvas/canvasHotkeyCommands';
import { isCanvasInteractionLocked } from '@workbench/widgets/canvas/canvasInteractionLock';
+import { reportTransformRefusal } from '@workbench/widgets/canvas/canvasToolCommands';
import {
useCanvasDocumentEditingLocked,
useCanvasEngineRead,
@@ -165,6 +166,7 @@ type LayerActionErrorStatus =
| 'missing'
| 'not-ready'
| 'over-budget'
+ | 'unreadable'
| 'unsupported';
const LAYER_ACTION_ERROR_KEYS: Record<LayerActionErrorStatus, string> = {
@@ -177,6 +179,7 @@ const LAYER_ACTION_ERROR_KEYS: Record<LayerActionErrorStatus, string> = {
missing: 'widgets.layers.actions.missing',
'not-ready': 'widgets.layers.actions.notReady',
'over-budget': 'widgets.layers.actions.overBudget',
+ unreadable: 'widgets.layers.actions.unreadable',
unsupported: 'widgets.layers.actions.unsupported',
};
@@ -308,10 +311,14 @@ const LayerMenu = ({
)
);
});
- const canMergeMasks = useCanvasEngineRead(
- engine,
- () => !!engine && targets.length > 1 && engine.layers.canMergeInpaintMasks(targets)
- );
+ const mergeMasksEligibility = useCanvasEngineRead(engine, () => {
+ const model = engine?.document.model() ?? null;
+ return engine && model
+ ? inpaintMaskMergeEligibility(model.compileLeaves(), new Set(targets), (layerId) =>
+ engine.exports.hasExportableLayerContent(layerId)
+ )
+ : 'ineligible';
+ });
const canRemoveTargetsFromGroup = useCanvasEngineRead(engine, () =>
canRemoveFromGroup(engine?.document.model() ?? null, targets)
);
@@ -326,7 +333,6 @@ const LayerMenu = ({
() => ({
canDeleteSelection,
canGroupSelection: canGroup,
- canMergeMasks,
canMergeSelection: canMerge,
canRemoveFromGroup: canRemoveTargetsFromGroup,
hiddenByAncestor,
@@ -338,6 +344,7 @@ const LayerMenu = ({
hasWorkflowBindings: workflowAvailability.hasWorkflowBindings,
interactionLocked,
layer,
+ mergeMasksEligibility,
modelBase: base,
selectedIds,
}),
@@ -348,13 +355,13 @@ const LayerMenu = ({
canDeleteSelection,
canGroup,
canMerge,
- canMergeMasks,
canRemoveTargetsFromGroup,
document,
engine,
hasSupportedContent,
interactionLocked,
layer,
+ mergeMasksEligibility,
selectedIds,
workflowAvailability.canRunWorkflow,
workflowAvailability.hasWorkflowBindings,
@@ -438,6 +445,8 @@ const LayerMenu = ({
reportLayerOperation(result, notify.error, t);
} else if (result.status === 'ineligible') {
notify.error(t('widgets.layers.actions.actionFailed'), t('widgets.layers.actions.mergeMasksIneligible'));
+ } else if (result.status === 'settings-differ') {
+ notify.error(t('widgets.layers.actions.actionFailed'), t('widgets.layers.actions.mergeMasksSettingsDiffer'));
} else if (result.status !== 'merged') {
reportLayerOperation(result.status, notify.error, t);
}
@@ -452,6 +461,8 @@ const LayerMenu = ({
notify.error(t('widgets.layers.actions.actionFailed'), describeAdjustmentRefusal(result, t));
} else if (result === 'not-ready') {
notify.error(t('widgets.layers.actions.actionFailed'), t('widgets.layers.groupActions.mergeNotReady'));
+ } else if (result === 'unreadable') {
+ notify.error(t('widgets.layers.actions.actionFailed'), t('widgets.layers.actions.unreadable'));
} else if (result === 'over-budget') {
notify.error(t('widgets.layers.actions.actionFailed'), t('widgets.layers.groupActions.mergeOverBudget'));
} else if (result === 'failed') {
@@ -715,8 +726,11 @@ const LayerMenu = ({
case 'locked':
case 'empty':
case 'not-ready':
+ case 'unreadable':
case 'over-budget':
throw makeStatusError(result.status);
+ case 'outside-frame':
+ throw new Error(t('widgets.layers.actions.cropOutsideFrame'));
case 'adjustment-refused':
throw makeStatusError(result);
case 'busy':
@@ -1381,11 +1395,16 @@ const LayerMenuSubmenu = ({
type LayerMenuTranslate = (key: string, options: { count?: number; defaultValue: string }) => string;
-/** Copying a layer needs the clipboard, which a plain-HTTP origin lacks; the item says so instead of failing. */
+/**
+ * Why the item cannot run: the registry's reason for a disabled action, or, since copying a layer needs the clipboard,
+ * which a plain-HTTP origin lacks, that. The item stays reachable by keyboard and says so instead of failing.
+ */
const getUnavailableReason = (action: LayerContextAction, t: LayerMenuTranslate): string | undefined =>
action.id === 'copy-to-clipboard' && !canCopyImage()
? t('common.copyUnavailable', { defaultValue: 'Copying needs HTTPS or localhost' })
- : undefined;
+ : action.unavailableReasonKey
+ ? t(action.unavailableReasonKey, { defaultValue: '' }) || undefined
+ : undefined;
const LayerMenuIconActionItem = ({
action,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx
index bcd2342084..e1a6259808 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx
@@ -514,7 +514,13 @@ export const LayersTree = ({
void copyLayerToClipboard(key, { exportLayer: currentEngine.exports.exportBakedLayerBlob }).then(
(status) => {
if (status !== 'ok') {
- copyFailed(isAdjustmentRefusal(status) ? describeAdjustmentRefusal(status, t) : undefined);
+ copyFailed(
+ isAdjustmentRefusal(status)
+ ? describeAdjustmentRefusal(status, t)
+ : status === 'unreadable'
+ ? t('widgets.layers.actions.unreadable')
+ : undefined
+ );
}
},
() => copyFailed()
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.tsx
index 9f2fdcb228..e486dfcf50 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.tsx
@@ -178,6 +178,7 @@ const FAILURE_KEYS: Record<
'not-ready': 'widgets.layers.runWorkflow.notReady',
'over-budget': 'widgets.layers.runWorkflow.overBudget',
stale: 'widgets.layers.runWorkflow.stale',
+ unreadable: 'widgets.layers.runWorkflow.unreadable',
unsupported: 'widgets.layers.runWorkflow.unsupported',
};
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 9fcdb780c0..adccdeaebb 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts
@@ -85,7 +85,7 @@ const makeState = (
interactionLocked: false,
canGroupSelection: true,
canDeleteSelection: true,
- canMergeMasks: true,
+ mergeMasksEligibility: 'eligible',
canMergeSelection: true,
canRemoveFromGroup: true,
layer,
@@ -205,6 +205,10 @@ describe('layer context action registry', () => {
'widgets.layers.actions.cropUnsupported',
'widgets.layers.actions.cropped',
'widgets.layers.actions.mergeMasksIneligible',
+ 'widgets.layers.actions.mergeMasksSettingsDiffer',
+ 'widgets.layers.actions.canvasNotReady',
+ 'widgets.layers.actions.interactionLocked',
+ 'widgets.layers.actions.removeFromGroupLocked',
'widgets.layers.actions.transformIneligible',
'widgets.layers.rasterFilter.busy',
'widgets.layers.rasterFilter.cancel',
@@ -989,15 +993,32 @@ describe('remove-from-group', () => {
it("is enabled by the model's answer and routes to its effect", () => {
const document = makeDocument(grouped);
+ const enabled = byId(getLayerContextActions(makeState(r1, { document })), 'remove-from-group');
+ expect(enabled).toMatchObject({ isDisabled: false, unavailableReasonKey: undefined });
const refused = getLayerContextActions(makeState(r1, { canRemoveFromGroup: false, document }));
expect(byId(refused, 'remove-from-group').isDisabled).toBe(true);
- const locked = getLayerContextActions(makeState(r1, { document, interactionLocked: true }));
- expect(byId(locked, 'remove-from-group').isDisabled).toBe(true);
const runtime = makeRuntimeContext(r1, { document });
void getLayerContextActionDefinition('remove-from-group').handler(runtime);
expect(runtime.effects.removeFromGroup).toHaveBeenCalledOnce();
});
+
+ it('says why it is disabled in each state that disables it', () => {
+ const reason = (layer: CanvasLayerContract, nodes: CanvasNodeContract[], state: Partial<LayerContextActionState>) =>
+ byId(getLayerContextActions(makeState(layer, { document: makeDocument(nodes), ...state })), 'remove-from-group')
+ .unavailableReasonKey;
+ const lockedLayer = { ...r1, isLocked: true };
+ const refused = { canRemoveFromGroup: false };
+
+ expect(reason(r1, grouped, { ...refused, hasEngine: false })).toBe('widgets.layers.actions.canvasNotReady');
+ expect(reason(lockedLayer, [groupContract('G', [lockedLayer])], refused)).toBe(
+ 'widgets.layers.actions.removeFromGroupLocked'
+ );
+ // A lock on any group above the layer refuses the move just the same.
+ const nested = [groupContract('Outer', [groupContract('G', [r1])], { isLocked: true })];
+ expect(reason(r1, nested, refused)).toBe('widgets.layers.actions.removeFromGroupLocked');
+ expect(reason(r1, grouped, { interactionLocked: true })).toBe('widgets.layers.actions.interactionLocked');
+ });
});
describe('merge-masks', () => {
@@ -1018,14 +1039,38 @@ describe('merge-masks', () => {
it("is enabled by the engine's eligibility and routes to its effect", () => {
const state = { document: makeDocument(layers), selectedIds: ['m1', 'm2'] };
- expect(byId(getLayerContextActions(makeState(m1, state)), 'merge-masks').isDisabled).toBe(false);
- expect(byId(getLayerContextActions(makeState(m1, state)), 'merge-masks').descriptionKey).toBeUndefined();
- const ineligible = getLayerContextActions(makeState(m1, { ...state, canMergeMasks: false }));
- expect(byId(ineligible, 'merge-masks').isDisabled).toBe(true);
- expect(byId(ineligible, 'merge-masks').descriptionKey).toBe('widgets.layers.actions.mergeMasksIneligible');
+ expect(byId(getLayerContextActions(makeState(m1, state)), 'merge-masks')).toMatchObject({
+ isDisabled: false,
+ unavailableReasonKey: undefined,
+ });
+ const ineligible = getLayerContextActions(makeState(m1, { ...state, mergeMasksEligibility: 'ineligible' }));
+ expect(byId(ineligible, 'merge-masks')).toMatchObject({
+ descriptionKey: undefined,
+ isDisabled: true,
+ unavailableReasonKey: 'widgets.layers.actions.mergeMasksIneligible',
+ });
const runtime = makeRuntimeContext(m1, state);
void getLayerContextActionDefinition('merge-masks').handler(runtime);
expect(runtime.effects.mergeMasks).toHaveBeenCalledOnce();
});
+
+ it('tells a settings mismatch, a canvas still starting and a busy canvas apart from other ineligibility', () => {
+ const reason = (nodes: CanvasNodeContract[], state: Partial<LayerContextActionState>) =>
+ byId(
+ getLayerContextActions(makeState(m1, { document: makeDocument(nodes), selectedIds: ['m1', 'm2'], ...state })),
+ 'merge-masks'
+ ).unavailableReasonKey;
+
+ expect(reason([m1, m2], { mergeMasksEligibility: 'settings-differ' })).toBe(
+ 'widgets.layers.actions.mergeMasksSettingsDiffer'
+ );
+ expect(reason([m1, m2], { mergeMasksEligibility: 'ineligible' })).toBe(
+ 'widgets.layers.actions.mergeMasksIneligible'
+ );
+ expect(reason([m1, m2], { hasEngine: false, mergeMasksEligibility: 'ineligible' })).toBe(
+ 'widgets.layers.actions.canvasNotReady'
+ );
+ expect(reason([m1, m2], { interactionLocked: true })).toBe('widgets.layers.actions.interactionLocked');
+ });
});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts
index c8f0321c09..e4fba2c525 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts
@@ -4,6 +4,7 @@ import type {
CanvasColorLabel,
CanvasDocumentContractV3,
CanvasLayerContract,
+ InpaintMaskMergeEligibility,
LayerStackMoveKind,
} from '@workbench/canvas-engine/api';
import type { LucideIcon } from 'lucide-react';
@@ -144,8 +145,8 @@ export interface LayerContextActionState {
canDeleteSelection: boolean;
/** Whether the whole multi-selection can merge into one raster, asked the same way. */
canMergeSelection: boolean;
- /** Whether the engine would merge `actionTargets` into one inpaint mask. */
- canMergeMasks: boolean;
+ /** Whether merge masks would take `actionTargets`, and if not, whether only their generation settings differ. */
+ mergeMasksEligibility: InpaintMaskMergeEligibility;
/** The model's answer for lifting `actionTargets` out of their group. */
canRemoveFromGroup: boolean;
/** A group above the layer hides it on the canvas; the layer's own flag cannot override that. */
@@ -216,10 +217,10 @@ interface LayerContextActionDefinitionBase {
tone?: 'danger';
/** A raw hotkey string (e.g. `mod+]`) shown as a trailing hint on the item. */
hint?: string;
- /** A second line under the label explaining what the action does. */
+ /** A second line under the label explaining what the action does, shown whether or not it is enabled. */
descriptionKey?: string;
- /** A second line that depends on the context, such as why the action is unavailable; wins over `descriptionKey`. */
- getDescriptionKey?(context: LayerContextActionState): string | undefined;
+ /** Why the disabled action cannot run here; asked only when `isEnabled` is false. */
+ getUnavailableReasonKey?(context: LayerContextActionState): string | undefined;
isVisible(context: LayerContextActionState): boolean;
isEnabled(context: LayerContextActionState): boolean;
handler(context: LayerContextActionRuntimeContext): void | Promise<void>;
@@ -255,6 +256,8 @@ export interface LayerContextAction {
hint?: string;
descriptionKey?: string;
isDisabled: boolean;
+ /** Set only on a disabled action whose reason is known; the menu keeps such an item reachable and says why. */
+ unavailableReasonKey?: string;
handler(context: LayerContextActionRuntimeContext): void | Promise<void>;
}
@@ -328,6 +331,16 @@ const isLayerFrozen = (context: LayerContextActionState): boolean =>
context.layer.isLocked || (layerEntry(context)?.ancestorsLocked ?? false);
const isLayerMutable = (context: LayerContextActionState): boolean =>
isInteractionFree(context) && !isLayerFrozen(context);
+const CANVAS_NOT_READY_REASON = 'widgets.layers.actions.canvasNotReady';
+const INTERACTION_LOCKED_REASON = 'widgets.layers.actions.interactionLocked';
+/** Any target locked, by itself or by a group above it: the model refuses to move it out. */
+const isAnyTargetFrozen = (context: LayerContextActionState): boolean => {
+ const index = getDocumentIndex(context.document);
+ return actionTargets(context).some((id) => {
+ const entry = index.byId.get(id);
+ return !!entry && (entry.node.isLocked || entry.ancestorsLocked);
+ });
+};
const hasReadablePixels = (context: LayerContextActionState): boolean =>
context.hasEngine && context.hasSupportedContent && !context.interactionLocked;
const hasMutablePixels = (context: LayerContextActionState): boolean =>
@@ -486,6 +499,14 @@ export const LAYER_CONTEXT_ACTION_DEFINITIONS: readonly LayerContextActionDefini
},
{
defaultLabel: 'Remove from group',
+ getUnavailableReasonKey: (context) =>
+ !context.hasEngine
+ ? CANVAS_NOT_READY_REASON
+ : isAnyTargetFrozen(context)
+ ? 'widgets.layers.actions.removeFromGroupLocked'
+ : context.interactionLocked
+ ? INTERACTION_LOCKED_REASON
+ : undefined,
handler: ({ effects }) => effects.removeFromGroup(),
icon: UngroupIcon,
id: 'remove-from-group',
@@ -709,12 +730,18 @@ export const LAYER_CONTEXT_ACTION_DEFINITIONS: readonly LayerContextActionDefini
},
{
defaultLabel: 'Merge masks',
- // The engine's eligibility has several reasons; name them rather than leave the item silently disabled.
- getDescriptionKey: (context) => (context.canMergeMasks ? undefined : 'widgets.layers.actions.mergeMasksIneligible'),
+ getUnavailableReasonKey: (context) =>
+ !context.hasEngine
+ ? CANVAS_NOT_READY_REASON
+ : context.mergeMasksEligibility === 'settings-differ'
+ ? 'widgets.layers.actions.mergeMasksSettingsDiffer'
+ : context.mergeMasksEligibility === 'ineligible'
+ ? 'widgets.layers.actions.mergeMasksIneligible'
+ : INTERACTION_LOCKED_REASON,
handler: ({ effects }) => effects.mergeMasks(),
icon: MergeIcon,
id: 'merge-masks',
- isEnabled: (context) => isInteractionFree(context) && context.canMergeMasks,
+ isEnabled: (context) => isInteractionFree(context) && context.mergeMasksEligibility === 'eligible',
isVisible: (context) => isMultiTarget(context) && allTargetsInpaintMasks(context),
labelKey: 'widgets.layers.actions.mergeMasks',
order: 1,
@@ -1086,20 +1113,24 @@ export const getLayerContextActionDefinition = (id: LayerContextActionId): Layer
export const getLayerContextActions = (context: LayerContextActionState): LayerContextAction[] =>
LAYER_CONTEXT_ACTION_DEFINITIONS.filter(
(definition) => definition.supportedLayerTypes.includes(context.layer.type) && definition.isVisible(context)
- ).map((definition) => ({
- defaultLabel: definition.getDefaultLabel?.(context) ?? definition.defaultLabel,
- descriptionKey: definition.getDescriptionKey?.(context) ?? definition.descriptionKey,
- handler: definition.handler,
- hint: definition.hint,
- icon: definition.getIcon?.(context) ?? definition.icon,
- iconColor: definition.iconColor,
- id: definition.id,
- isDisabled: !definition.isEnabled(context),
- labelCount: definition.getLabelCount?.(context),
- labelKey: definition.getLabelKey?.(context) ?? definition.labelKey,
- order: definition.order,
- picker: definition.picker,
- section: definition.section,
- submenu: definition.submenu,
- tone: definition.tone,
- }));
+ ).map((definition) => {
+ const isDisabled = !definition.isEnabled(context);
+ return {
+ defaultLabel: definition.getDefaultLabel?.(context) ?? definition.defaultLabel,
+ descriptionKey: definition.descriptionKey,
+ handler: definition.handler,
+ hint: definition.hint,
+ icon: definition.getIcon?.(context) ?? definition.icon,
+ iconColor: definition.iconColor,
+ id: definition.id,
+ isDisabled,
+ labelCount: definition.getLabelCount?.(context),
+ labelKey: definition.getLabelKey?.(context) ?? definition.labelKey,
+ order: definition.order,
+ picker: definition.picker,
+ section: definition.section,
+ submenu: definition.submenu,
+ tone: definition.tone,
+ unavailableReasonKey: isDisabled ? definition.getUnavailableReasonKey?.(context) : undefined,
+ };
+ });
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts
index f4357b559b..b5b286ca53 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts
@@ -51,7 +51,7 @@ const actionsFor = (layer: CanvasLayerContract, layers: readonly CanvasLayerCont
selectedIds: [layer.id],
canGroupSelection: true,
canDeleteSelection: true,
- canMergeMasks: true,
+ mergeMasksEligibility: 'eligible',
canMergeSelection: true,
canRemoveFromGroup: true,
layer,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/psdExportNotice.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/psdExportNotice.ts
index e07dd3104f..87505e742e 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/psdExportNotice.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/psdExportNotice.ts
@@ -6,6 +6,7 @@ export type PsdExportNoticeKey =
| 'widgets.layers.groupActions.exportNothing'
| 'widgets.layers.groupActions.exportOverBudget'
| 'widgets.layers.groupActions.exportStale'
+ | 'widgets.layers.groupActions.exportUnreadable'
| 'widgets.layers.groupActions.exportAborted';
/** The notice for a non-refusal result; an `AdjustmentRefusal` is worded by `describeAdjustmentRefusal`. */
@@ -25,6 +26,8 @@ export const getPsdExportNoticeKey = (
return 'widgets.layers.groupActions.exportOverBudget';
case 'stale':
return 'widgets.layers.groupActions.exportStale';
+ case 'unreadable':
+ return 'widgets.layers.groupActions.exportUnreadable';
case 'aborted':
return 'widgets.layers.groupActions.exportAborted';
}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/runLayerWorkflow.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/runLayerWorkflow.ts
index 2bb1ec4877..d5851b9a0a 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/runLayerWorkflow.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/runLayerWorkflow.ts
@@ -42,6 +42,7 @@ export type RunLayerWorkflowResult =
| 'unsupported'
| 'empty'
| 'not-ready'
+ | 'unreadable'
| 'over-budget'
| 'locked'
| 'stale'
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/useCanvasCompanionHotkeys.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/useCanvasCompanionHotkeys.ts
index 13eb879327..e07e6c0208 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/useCanvasCompanionHotkeys.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/useCanvasCompanionHotkeys.ts
@@ -2,14 +2,14 @@ import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';
import type { WidgetCommandApi, WidgetHotkeyApi } from '@workbench/widgetContracts';
import { useNotify } from '@workbench/useNotify';
+import { isCanvasInteractionLocked } from '@workbench/widgets/canvas/canvasInteractionLock';
import {
CANVAS_COMPANION_HOTKEYS,
CANVAS_HISTORY_HOTKEYS,
executeCanvasToolCommand,
reportTransformRefusal,
type CanvasToolCommandId,
-} from '@workbench/widgets/canvas/canvasHotkeyCommands';
-import { isCanvasInteractionLocked } from '@workbench/widgets/canvas/canvasInteractionLock';
+} from '@workbench/widgets/canvas/canvasToolCommands';
import { useActiveColorCommands } from '@workbench/widgets/canvas/color-system/useActiveColors';
import { useWorkbenchQueries } from '@workbench/WorkbenchContext';
import { useEffect, useEffectEvent } from 'react';
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/useLayerStackActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/useLayerStackActions.ts
index 5f2fa825fa..3ab9d3c3ac 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/useLayerStackActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/useLayerStackActions.ts
@@ -119,6 +119,12 @@ export const useLayerStackActions = (
});
} else if (result === 'not-ready') {
toaster.create({ title: t('widgets.layers.groupActions.mergeNotReady'), type: 'warning' });
+ } else if (result === 'unreadable') {
+ toaster.create({
+ description: t('widgets.layers.actions.unreadable'),
+ title: t('widgets.layers.actions.actionFailed'),
+ type: 'error',
+ });
} else if (result === 'over-budget') {
toaster.create({ title: t('widgets.layers.groupActions.mergeOverBudget'), type: 'warning' });
} else if (result === 'failed') {
diff --git a/invokeai/frontend/webv2/vite.config.mts b/invokeai/frontend/webv2/vite.config.mts
index 1893d377e5..1ca8b92578 100644
--- a/invokeai/frontend/webv2/vite.config.mts
+++ b/invokeai/frontend/webv2/vite.config.mts
@@ -271,8 +271,8 @@ const CANVAS_LAYER_SHARED_MODULES = [
'/workbench/canvas-operations/useCanvasEngine.ts',
'/workbench/canvasProjectMutationPort.ts',
'/workbench/useCanvasProjectMutationDispatch.ts',
- '/workbench/widgets/canvas/canvasHotkeyCommands.ts',
'/workbench/widgets/canvas/canvasInteractionLock.ts',
+ '/workbench/widgets/canvas/canvasToolCommands.ts',
'/workbench/widgets/canvas/color-system/colorPair.ts',
'/workbench/widgets/canvas/color-system/maskTintTarget.ts',
'/workbench/widgets/canvas/color-system/useActiveColors.ts',