Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(canvas): correct Shape tool drawing and properties (#10151)
Josh Corbettec2a56bdff6b
diff --git a/docs/src/content/docs/Users Guide/07.Canvas/01.introduction.mdx b/docs/src/content/docs/Users Guide/07.Canvas/01.introduction.mdxindex bc5d589750..9d9edbe06d 100644--- a/docs/src/content/docs/Users Guide/07.Canvas/01.introduction.mdx+++ b/docs/src/content/docs/Users Guide/07.Canvas/01.introduction.mdx@@ -78,7 +78,7 @@ Inpainting regenerates part of an image and leaves the rest untouched: remove an1. **Add an inpaint mask**, or select the empty one a new canvas starts with, in the **Inpaint Masks** stack. (A new canvas opens with nothing selected and the Brush active, so a stroke there paints a new raster layer.)-2. **Paint the mask.** Choose the **Brush** (**B**) and paint over the area to regenerate, or draw it with the **Shape** tool (**R**). The mask shows as a tinted overlay. The **Eraser** (**E**) removes mask, and **[** and **]** change the brush size.+2. **Paint the mask.** Choose the **Brush** (**B**) and paint over the area to regenerate, or draw it with the **Shape** tool (**U**). The mask shows as a tinted overlay. The **Eraser** (**E**) removes mask, and **[** and **]** change the brush size.3. **Describe the result** in the Generate panel's prompt: describe the whole picture as it should look, or just what should appear in the masked area.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.mdxindex 0706085592..810c78fc7c 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 @@ A tool that cannot change the selected layer says so instead of doing nothing: t| **Marquee select** / **Lasso select** | **M** / **L** | Select an area of pixels. Press **M** again to switch between rectangle and ellipse, or **L** again for freehand and polygon. || **Color picker** | **I** | Pick a color from the canvas (see below). |-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 the Brush, Eraser, Shape, Gradient, Text or View tool and click, or press **I** for the Color picker tool. Move, Transform, the Generation frame and the selection tools use **Alt** themselves, so holding it there changes their drag instead. 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 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 the Brush, Eraser, Gradient, Text or View tool and click, or press **I** for the Color picker tool. Move, Transform, the Generation frame, Shape and the selection tools use **Alt** themselves, so holding it there changes their drag instead. 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. A pick never turns on a fill or stroke the shape doesn't have; it sets the active color instead;@@ -51,10 +51,10 @@ A pick that changes a layer is one undoable step. Gradient stops are not picked* **Eraser** — **Size**, **Opacity** and **Hardness**; and, under **Dynamics**, whether pen pressure affects the width. Pressure never changes how strongly the eraser erases.The Brush, Eraser, Shape and Text options are remembered for your account, so they are the same in every project and after a reload. Colors are the project's own.-* **Shape** — the **Kind** of shape; **Place on**, which draws on the **Selected layer** or on a **New layer** of its own; **Fill** and **Stroke**, each with a color; and the stroke **Width**. **Shift** constrains the proportions. For polygons, click to place points and double-click, press **Enter** or click the first point to close the shape. With an inpaint mask or regional guidance layer selected, the shape is added to the mask or region, which makes shapes a quick way to mark rectangular or geometric areas; the colors are ignored.+* **Shape** — settings for the next shape: its **Kind**, a row of buttons showing each shape (point at one for its name), and **Place on**, which draws on the **Selected layer** or on a **New layer** of its own. Only a paint layer, an inpaint mask or a regional guidance layer takes shape pixels. With anything else selected, or nothing selected, **Selected layer** is unavailable and **New layer** shows where the shape will go; a note below explains why. Your placement preference returns when you select a paint layer or mask. Under the tool's **Appearance** group, **Fill**, **Stroke** and stroke **Width** set the next shape's defaults. To edit an existing shape's appearance, use the **Layer** section below the tool options; those controls stay available with any tool active and each gesture is one undoable step. **Shift** constrains the proportions, **Alt** draws from the center, and **Shift+Alt** does both. **Ctrl** (**Cmd** on macOS) cuts the shape out of the selected paint layer or mask instead of drawing it, whatever **Place on** says: it erases like the Eraser and never adds a layer. With no paint layer or mask selected, a notice says so and nothing is drawn. For polygons, click to place points and double-click, press **Enter** or click the first point to close the shape; **Escape** drops the points without drawing anything. With an inpaint mask or regional guidance layer selected, the shape is added to the mask or region, which makes shapes a quick way to mark rectangular or geometric areas; the colors are ignored.* **Gradient** — **Kind** (Linear or Radial), **Angle**, and the color **Stops**, which can be added and removed or follow the foreground and background colors. Dragging creates a gradient layer the size of the generation frame, or repositions the selected gradient layer.* **Text** — the font **Family**, **Style** or **Weight**, **Size**, **Line height**, **Align** and **Fill** color. Click the canvas to start typing; **Ctrl+Enter** or clicking elsewhere finishes the text, and **Escape** cancels it. The text stays editable as a text layer.-* **Marquee select** and **Lasso select** — the **Shape** and the selection **Mode** (Replace, Add, Subtract or Intersect). **Shift** adds to the selection and **Alt** subtracts from it. The **Actions** fill or erase the selection, lift it to a **New layer**, **Invert** it, select everything, or **Deselect**.+* **Marquee select** and **Lasso select** — the **Shape** and the selection **Mode** (Replace, Add, Subtract or Intersect). **Shift** adds to the selection and **Alt** subtracts from it. A polygon lasso closes like a polygon shape, and **Escape** drops its points while keeping the current selection. The **Actions** fill or erase the selection, lift it to a **New layer**, **Invert** it, select everything, or **Deselect**.### Fonts@@ -241,5 +241,5 @@ The tool keys, **Shift+T**, **[** and **]**, and **X** and **D** also work after| **Shift+H** | Hide control, guidance and mask layers || **Shift+N** / **Shift+B** | Fit the generation frame to the layers / to the masks || **Ctrl+1** / **Ctrl+2** / **Ctrl+3** / **Ctrl+4** | Zoom to 100% / 200% / 400% / 800%, where the browser passes these keys to the page |-| **Enter** / **Escape** | Apply / cancel a transform, text or filter |+| **Enter** / **Escape** | Apply / cancel a transform, text, filter or polygon |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.mdxindex 007ec92087..6a286ae7fe 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@@ -27,7 +27,7 @@ The **Color** tab edits the two painting colors: the **Foreground color**, which* The color wheel, or a box picker via **Switch to box picker**, and the hex value, always shown. The format button next to it cycles through hex only, RGB, HSB and HSL, adding a field for each channel.* **Swap foreground and background colors** (**X**) and **Reset colors to black and white** (**D**).-* **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).+* **Pick a color from the canvas** — the eyedropper. You can also hold **Alt** on the canvas with the Brush, Eraser, Gradient, Text or View tool. 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 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.@@ -126,7 +126,8 @@ The Layer section is dimmed while Filter or Select Object is running.### Raster layer-* **Lock transparency** — paint only where the layer already has pixels, leaving transparent areas transparent, like Photoshop's "Lock transparent pixels". Use it to recolor a shape without spilling paint around it, or to refine a subject painted on a transparent layer without growing its outline. Brushes, shapes and pen input all respect the lock.+* **Lock transparency** — paint only where the layer already has pixels, leaving transparent areas transparent, like Photoshop's "Lock transparent pixels". Use it to recolor a shape without spilling paint around it, or to refine a subject painted on a transparent layer without growing its outline. Brushes, shapes and pen input all respect the lock, and the Eraser and a Shape cutout can't remove pixels while it's on.+* **Shape appearance** — with a shape layer selected, its **Fill**, **Stroke** and stroke **Width** appear under **Appearance**, whatever canvas tool is active. Each gesture is one undoable step and changes only the selected shape. The Shape tool's own **Appearance** group sets creation defaults separately.* **Filter** — start the Filter operation.The Brush and Eraser paint directly on a selected image layer, such as an accepted result or an added picture, rather than adding a new layer. The first stroke turns it into a paint layer, with its position, scale and adjustments applied to its pixels; one undo restores the original image layer.diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.jsonindex 92cae0f241..329f6adda5 100644--- a/invokeai/frontend/webv2/performance/browser-baseline.json+++ b/invokeai/frontend/webv2/performance/browser-baseline.json@@ -1558,6 +1558,7 @@"source:src/workbench/canvas-engine/tools/bboxTool.ts","source:src/workbench/canvas-engine/tools/brushTool.ts","source:src/workbench/canvas-engine/tools/colorPickerTool.ts",+ "source:src/workbench/canvas-engine/tools/dragRect.ts","source:src/workbench/canvas-engine/tools/eraserTool.ts","source:src/workbench/canvas-engine/tools/gradientTool.ts","source:src/workbench/canvas-engine/tools/gridSnap.ts",@@ -1570,6 +1571,7 @@"source:src/workbench/canvas-engine/tools/polylineSession.ts","source:src/workbench/canvas-engine/tools/samHitTest.ts","source:src/workbench/canvas-engine/tools/samTool.ts",+ "source:src/workbench/canvas-engine/tools/shapeTarget.ts","source:src/workbench/canvas-engine/tools/shapeTool.ts","source:src/workbench/canvas-engine/tools/strokeSession.ts","source:src/workbench/canvas-engine/tools/textTool.ts",@@ -2733,6 +2735,7 @@"source:src/workbench/canvas-engine/tools/bboxTool.ts","source:src/workbench/canvas-engine/tools/brushTool.ts","source:src/workbench/canvas-engine/tools/colorPickerTool.ts",+ "source:src/workbench/canvas-engine/tools/dragRect.ts","source:src/workbench/canvas-engine/tools/eraserTool.ts","source:src/workbench/canvas-engine/tools/gradientTool.ts","source:src/workbench/canvas-engine/tools/gridSnap.ts",@@ -2745,6 +2748,7 @@"source:src/workbench/canvas-engine/tools/polylineSession.ts","source:src/workbench/canvas-engine/tools/samHitTest.ts","source:src/workbench/canvas-engine/tools/samTool.ts",+ "source:src/workbench/canvas-engine/tools/shapeTarget.ts","source:src/workbench/canvas-engine/tools/shapeTool.ts","source:src/workbench/canvas-engine/tools/strokeSession.ts","source:src/workbench/canvas-engine/tools/textTool.ts",@@ -4143,6 +4147,7 @@"source:src/workbench/canvas-engine/tools/bboxTool.ts","source:src/workbench/canvas-engine/tools/brushTool.ts","source:src/workbench/canvas-engine/tools/colorPickerTool.ts",+ "source:src/workbench/canvas-engine/tools/dragRect.ts","source:src/workbench/canvas-engine/tools/eraserTool.ts","source:src/workbench/canvas-engine/tools/gradientTool.ts","source:src/workbench/canvas-engine/tools/gridSnap.ts",@@ -4155,6 +4160,7 @@"source:src/workbench/canvas-engine/tools/polylineSession.ts","source:src/workbench/canvas-engine/tools/samHitTest.ts","source:src/workbench/canvas-engine/tools/samTool.ts",+ "source:src/workbench/canvas-engine/tools/shapeTarget.ts","source:src/workbench/canvas-engine/tools/shapeTool.ts","source:src/workbench/canvas-engine/tools/strokeSession.ts","source:src/workbench/canvas-engine/tools/textTool.ts",diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 324f64955c..804b67e8bf 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -2915,6 +2915,7 @@"stroke": "Stroke","dynamics": "Dynamics","shape": "Shape",+ "appearance": "Appearance","gradient": "Gradient","stops": "Stops","font": "Font",@@ -4570,6 +4571,7 @@"shapeRect": "Rectangle","shapeStar": "Star","shapeTarget": "Place on",+ "shapeTargetFallbackHint": "Select a paint layer or mask.","shapeTargetNew": "New layer","shapeTargetSelected": "Selected layer","shapeTriangle": "Triangle",@@ -4644,9 +4646,11 @@"lockedMessage": "Unlock the layer to edit it.","lockedOfferMessage": "Unlock the layer to paint on it, or paint on a new layer above it.","alphaLocked": "“{{name}}” has its transparency locked",- "alphaLockedMessage": "The eraser can’t remove pixels while transparency is locked.",+ "alphaLockedMessage": "Unlock its transparency to remove pixels from it.","loading": "“{{name}}” is still loading","loadingMessage": "Its pixels are on their way. Try again in a moment.",+ "noCutoutTarget": "Nothing to cut the shape out of",+ "noCutoutTargetMessage": "Select a paint layer or mask to cut the shape out of it.","paintOnNewLayer": "Paint on a new layer"},"restorePoints": {@@ -7059,6 +7063,8 @@"subtractSelection": "Subtract (hold at completion)","draw": "Draw shape","constrain": "Constrain proportions",+ "drawFromCenter": "Draw from center",+ "cutOutShape": "Cut out of the selected layer","smaller": "Smaller brush","larger": "Larger brush","deselect": "Deselect",diff --git a/invokeai/frontend/webv2/src/platform/ui/SegmentedControl.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/SegmentedControl.browser.test.tsxnew file mode 100644index 0000000000..a4fab8aadd--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/ui/SegmentedControl.browser.test.tsx@@ -0,0 +1,100 @@+import { ChakraProvider } from '@chakra-ui/react';+import { system } from '@theme/system';+import { CircleIcon, SquareIcon, StarIcon } from 'lucide-react';+import { act, useCallback, useState } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { page, userEvent } from 'vitest/browser';++import { SegmentedControl, type SegmentedControlOption } from './SegmentedControl';++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const ICON_OPTIONS: readonly SegmentedControlOption[] = [+ { icon: SquareIcon, label: 'Square', value: 'square' },+ { disabled: true, icon: CircleIcon, label: 'Circle', value: 'circle' },+ { icon: StarIcon, label: 'Star', value: 'star' },+];++let host: HTMLDivElement | null = null;+let root: Root | null = null;++const mount = async (options: readonly SegmentedControlOption[], onChange = vi.fn()) => {+ const Harness = () => {+ const [value, setValue] = useState(options[0]!.value);+ const select = useCallback((next: string) => {+ onChange(next);+ setValue(next);+ }, []);+ return <SegmentedControl ariaLabel="Kind" options={options} value={value} onChange={select} />;+ };+ host = document.createElement('div');+ host.style.width = '160px';+ // Room on both sides, so the tip centres on its segment instead of shifting off the viewport edge.+ host.style.margin = '80px 200px';+ document.body.append(host);+ root = createRoot(host);+ await act(() =>+ root!.render(+ <ChakraProvider value={system}>+ <Harness />+ </ChakraProvider>+ )+ );+ return onChange;+};++afterEach(async () => {+ await act(() => root?.unmount());+ host?.remove();+ host = null;+ root = null;+});++describe('SegmentedControl icon options', () => {+ it('names each icon segment, shows its label as a tooltip on focus, and steps over disabled ones', async () => {+ const onChange = await mount(ICON_OPTIONS);+ const group = page.getByRole('radiogroup', { name: 'Kind' });+ const square = group.getByRole('radio', { exact: true, name: 'Square' });+ await expect.element(square).toBeChecked();+ // The label is only the accessible name: the segment shows the icon alone.+ expect(host!.querySelector('[data-part="item-text"]')!.getBoundingClientRect().width).toBeLessThanOrEqual(1);++ await userEvent.keyboard('{Tab}');+ await expect.element(square).toHaveFocus();+ const tooltip = page.getByRole('tooltip');+ await expect.element(tooltip).toHaveTextContent('Square');+ // Anchored to its own segment: the tip sits over Square, not at the page origin.+ const item = square.element().closest('[data-part="item"]')!;+ // The tip leaves the segment's own checked state in place.+ expect(item.getAttribute('data-state')).toBe('checked');+ const segment = item.getBoundingClientRect();+ await expect+ .poll(() => {+ const tip = tooltip.element().getBoundingClientRect();+ return Math.abs(tip.left + tip.width / 2 - (segment.left + segment.width / 2));+ })+ .toBeLessThan(4);++ await userEvent.keyboard('{ArrowRight}');++ expect(onChange).toHaveBeenLastCalledWith('star');+ await expect.element(group.getByRole('radio', { exact: true, name: 'Star' })).toBeChecked();+ await expect.element(group.getByRole('radio', { exact: true, name: 'Circle' })).toBeDisabled();+ await expect.element(page.getByRole('tooltip')).toHaveTextContent('Star');+ });++ it('keeps text segments as visible labels without tooltips', async () => {+ await mount([+ { label: 'Linear', value: 'linear' },+ { label: 'Radial', value: 'radial' },+ ]);+ const linear = page.getByRole('radio', { exact: true, name: 'Linear' });+ await expect.element(page.getByText('Linear')).toBeVisible();++ await userEvent.keyboard('{Tab}');++ await expect.element(linear).toHaveFocus();+ expect(document.querySelector('[role="tooltip"]')).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/platform/ui/SegmentedControl.tsx b/invokeai/frontend/webv2/src/platform/ui/SegmentedControl.tsxindex 90b36e66c6..96e4a47cef 100644--- a/invokeai/frontend/webv2/src/platform/ui/SegmentedControl.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/SegmentedControl.tsx@@ -1,11 +1,16 @@-import type { ReactNode } from 'react';+import type { ElementType, ReactNode } from 'react';-import { SegmentGroup } from '@chakra-ui/react';+import { chakra, Icon, SegmentGroup } from '@chakra-ui/react';import { useCallback } from 'react';+import { Tooltip } from './Tooltip';+export interface SegmentedControlOption {disabled?: boolean;+ /** Shown as the segment's text; with `icon`, the segment's accessible name and tooltip instead. */label: ReactNode;+ /** Makes the segment icon-only. */+ icon?: ElementType;value: string;}@@ -19,7 +24,7 @@ export interface SegmentedControlProps extends Omit<SegmentGroup.RootProps, 'onCvalue: string | null;}-/** The house segmented control: an `md` group of equal centered segments with `xs` labels. */+/** The house segmented control: an `md` group of equal centered segments with `xs` labels or tooltipped icons. */export const SegmentedControl = ({ariaLabel,disabled,@@ -55,10 +60,25 @@ export const SegmentedControl = ({flex={isFullWidth ? '1' : undefined}justifyContent={isFullWidth ? 'center' : undefined}minW={isFullWidth ? '0' : undefined}+ px={option.icon ? '0' : undefined}value={option.value}>- <SegmentGroup.ItemHiddenInput />- <SegmentGroup.ItemText fontSize="xs">{option.label}</SegmentGroup.ItemText>+ {option.icon ? (+ // The tip's trigger is inside the item, never the item itself: a trigger's data attributes would replace+ // the item's checked state. Focus on the radio inside it still reaches the trigger. Arrow keys check the+ // next radio with a click, which must not close its tip; a pointer press still does.+ <Tooltip closeOnClick={false} content={option.label}>+ <chakra.span alignItems="center" alignSelf="stretch" display="flex" flex="1" justifyContent="center">+ <SegmentGroup.ItemHiddenInput />+ <Icon as={option.icon} aria-hidden boxSize="3.5" />+ </chakra.span>+ </Tooltip>+ ) : (+ <SegmentGroup.ItemHiddenInput />+ )}+ <SegmentGroup.ItemText fontSize="xs" srOnly={option.icon ? true : undefined}>+ {option.label}+ </SegmentGroup.ItemText></SegmentGroup.Item>))}</SegmentGroup.Root>diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.mdindex fd39ea8ddd..6651730cdd 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md@@ -111,7 +111,7 @@ Nothing in the document freezes while a generation runs or its results wait for## Frame demand before allocation-Each frame is described once by a `CompositePreparation` (`render/compositor.ts`): leaves drawn bottom first, each leaf's effective matrix with transient transform overrides applied, isolated group scopes, each leaf's document-space bounds (persisted source bounds joined with any larger live cache rect, through that matrix). `compositeFrame` reuses the description until document identity, isolation or override contents change, and each leaf's bounds until its contract, matrix, live cache extent or document size does. Frame demand and screen composite read that one description; frame demand also keeps every filter-previewed layer resident, since its preview draws through layer's cache entry. Color sampler, overview and extraction prepare their own descriptions of committed document without transient overrides. The overview composites the same extent fit-to-view fits (the frame joined with every enabled renderable layer's bounds), translated so that extent fills its target, and returns that document-space rect so the Overview pane maps its outline and pointer through it. The screen description also carries which overlay stacks it shows: while a staged or progress preview is shown it hides the inpaint-mask and regional-guidance stacks and the regenerate-region tint, so the result reads untinted, whatever is selected. They show again, drawn above the preview, only while a pointer gesture edits the selected mask or region (or a group in those stacks; `isStagingHiddenStackSelected`), so the user never paints a mask blind. Whether a gesture edits is the active tool's `Tool.editsSelectedLayer` contract, asked once as the pointer pipeline reports the gesture starting (`onGestureChange`): a brush or eraser press that paints the selected leaf in place and is not refused up front; a box or freehand shape drag aimed at the selection whose leaf accepts its pixels. A tool that knows only later calls `ToolContext.beginSelectedLayerEdit`, which runs the same reveal decision mid-gesture: a move reveals once its drag crosses the drag threshold as a layer drag, so a click reveals nothing, nor does a drag that a locked or hidden layer refuses or that moves a float. A locked or hidden mask reveals nothing, and a selected group reveals only for a move, since the brush, eraser and shapes paint a new layer instead. Navigation, sampling, bbox, selection, transform, gradient and Select Object gestures, Space and Alt holds included, never reveal, and a polygon's vertex presses do not either, since they write nothing until it closes. Edits that no revealing gesture carries, such as undoing a mask stroke or closing a polygon, change nothing visible while the preview hides the stacks. So that a gesture can edit at once, while its stack is hidden the frame keeps a selected mask or region leaf resident when the screen would otherwise draw it and its bounds meet the viewport (the rule drawn leaves follow): it stays demanded (protected from eviction) and rasterizes when stale; a selected group needs nothing up front. Transform sessions and floating selections never open on masks or regions, so the transform tool has nothing to reveal. The staged preview always lands above the raster and control stacks and below masks and regions, so a shown mask draws over it. A candidate whose preview is toggled off hides nothing. Control layers, isolation targets and every non-screen composite are unaffected. The flag is derived per frame from that per-gesture decision and joins the description's reuse key; publishing or clearing the preview repaints in full, and while a preview is shown so do the reveal's start (the press, or a move's threshold crossing) and the gesture's end (release, cancel or reset); its other pointer moves repaint only their own damage. A progress frame decodes at its own (latent) size and the compositor scales it into its rect, so an upscale's large output rect costs no full-size decode.+Each frame is described once by a `CompositePreparation` (`render/compositor.ts`): leaves drawn bottom first, each leaf's effective matrix with transient transform overrides applied, isolated group scopes, each leaf's document-space bounds (persisted source bounds joined with any larger live cache rect, through that matrix). `compositeFrame` reuses the description until document identity, isolation or override contents change, and each leaf's bounds until its contract, matrix, live cache extent or document size does. Frame demand and screen composite read that one description; frame demand also keeps every filter-previewed layer resident, since its preview draws through layer's cache entry. Color sampler, overview and extraction prepare their own descriptions of committed document without transient overrides. The overview composites the same extent fit-to-view fits (the frame joined with every enabled renderable layer's bounds), translated so that extent fills its target, and returns that document-space rect so the Overview pane maps its outline and pointer through it. The screen description also carries which overlay stacks it shows: while a staged or progress preview is shown it hides the inpaint-mask and regional-guidance stacks and the regenerate-region tint, so the result reads untinted, whatever is selected. They show again, drawn above the preview, only while a pointer gesture edits the selected mask or region (or a group in those stacks; `isStagingHiddenStackSelected`), so the user never paints a mask blind. Whether a gesture edits is the active tool's `Tool.editsSelectedLayer` contract, asked once as the pointer pipeline reports the gesture starting (`onGestureChange`): a brush or eraser press that paints the selected leaf in place and is not refused up front; a box or freehand shape drag that draws into the selected leaf's pixels, or cuts out of them under the mod key whatever Place on says. A tool that knows only after it was asked calls `ToolContext.beginSelectedLayerEdit`, which runs the same reveal decision mid-gesture: the shape tool once its press shows the modifiers (the hook is asked before the press reaches the tool), or when the mod key turns a drag into a cutout; a move reveals once its drag crosses the drag threshold as a layer drag, so a click reveals nothing, nor does a drag that a locked or hidden layer refuses or that moves a float. A locked or hidden mask reveals nothing, and a selected group reveals only for a move, since the brush, eraser and shapes paint a new layer instead. Navigation, sampling, bbox, selection, transform, gradient and Select Object gestures, Space and Alt holds included, never reveal, and a polygon's vertex presses do not either, since they write nothing until it closes. Edits that no revealing gesture carries, such as undoing a mask stroke or closing a polygon, change nothing visible while the preview hides the stacks. So that a gesture can edit at once, while its stack is hidden the frame keeps a selected mask or region leaf resident when the screen would otherwise draw it and its bounds meet the viewport (the rule drawn leaves follow): it stays demanded (protected from eviction) and rasterizes when stale; a selected group needs nothing up front. Transform sessions and floating selections never open on masks or regions, so the transform tool has nothing to reveal. The staged preview always lands above the raster and control stacks and below masks and regions, so a shown mask draws over it. A candidate whose preview is toggled off hides nothing. Control layers, isolation targets and every non-screen composite are unaffected. The flag is derived per frame from that per-gesture decision and joins the description's reuse key; publishing or clearing the preview repaints in full, and while a preview is shown so do the reveal's start (the press, or a move's threshold crossing) and the gesture's end (release, cancel or reset); its other pointer moves repaint only their own damage. A progress frame decodes at its own (latent) size and the compositor scales it into its rect, so an upscale's large output rect costs no full-size decode.`calculateActiveFrameLayerIds` is the pure pre-allocation pass over that description: intersects each drawable leaf's bounds with document-space viewport. Explicitly isolated operation target is the one exception to normal document visibility: stays demanded and drawable when disabled or display-hidden, because user acts on that named layer directly.@@ -152,6 +152,8 @@ Staged results use a separate compressed-Blob cache instead of retaining a decod## Composition, damage and overlays+Shape rasterization and direct Shape-tool pixel edits share `render/rasterizers/shapeRasterizer.ts`. Fill uses the original silhouette; an outline is a centered stroke at twice its configured width, masked to that silhouette so the visible stroke lies inside the shape without changing fill coverage or the source extent. Both callers provide isolated transparent targets: the parametric rasterizer clears its target, and the Shape tool allocates scratch pixels before selection or mask compositing. With an outline, fill color covers that target first, then stroke color composites over it, and one opaque `destination-in` fill applies silhouette coverage. Applying coverage once prevents antialiased exterior pixels from exposing the fill color. The drawing helper restores caller transform, alpha and composite state; its final mask must never act on existing layer pixels. The tool preview traces the same silhouette.+Damage is explicit: `FrameDamage` is full repaint, no visible repaint, or layer-local regions. Scheduler widens to full on any invalidation without a region, a viewport change or a forced repaint. Compositor resolves regions through frame's matrices into one padded screen rect: regions entirely off target draw nothing; bounded repaint clips to the rect and culls every leaf, group scope and staged preview whose screen bounds miss it. Unknown layers or non-finite geometry repaint everything.Compositing always renders through canonical `RasterBackend`; no approximate backend-free path. Filter previews and floating selection of a grouped member compose inside group's isolated surface, under group's opacity, blend and adjustments, exactly as member's committed pixels would. Committed content composes with same semantics for display, sampling and export; previews and floats are display-only. Layer's own adjustments apply to its layer-local pixels before resampling: export draws display's memoized adjusted copy of a leased live cache when one is current and exact, never building one (a layer-sized copy would exceed the export's reservation), and otherwise adjusts only the layer region the output samples (plus one pixel of resampling margin). When a downscaled layer samples more pixels than output holds and its stack is position independent (color only), a detached copy of it is adjusted after resampling instead, keeping export work bounded by output size; composite reservations count each such scratch buffer at output size. A position-dependent stack (noise) never takes that shortcut: resampling must average its grain exactly as on screen, so its layer-local sampled region is adjusted and reserved even when larger than the output. Composite reservations plan that region from estimated content bounds; when a layer's rasterized pixels (measured text) sample more, rendering reserves the excess before allocating it and refuses as over-budget when it does not fit. World-space bakes (merges, boolean merges, crops, copies) and PSD always adjust the layer's own stack on a layer-local copy, or draw the display's exact adjusted copy, and then resample it. Merge Down bakes both layers' own stacks the same way before the upper layer resamples into the lower layer's space, so the merged layer carries no stack; its undo snapshots stay raw and undo restores both layers with their stacks. Control layers carry no stack, so a raster layer whose stack changes pixels reaches the control stack only baked: copy to control (`CopyLayerController`) and convert to control (`LayerMutationController.convertToControl`) draw the layer's exact baked export at an identity transform, conversion in place as one step whose undo restores the raster contract, its stack and its original cache; a layer whose stack changes nothing, or an empty layer with no pixels to bake, takes the plain contract clone of source and transform. Mask conversions read alpha alone, which no adjustment writes. Rasterize bakes a position-dependent or spatial stack (all of it) into the layer-local source render before the transform and drops it from the paint contract, since kept it would grain, or measure detail on, the baked pixel grid; a color-only stack stays on the contract. Thumbnails downscale the display's current adjusted copy when one exists.@@ -196,7 +198,7 @@ Layer controllers build their steps from `controllers/editSteps.ts`: byte accounFloating selection (`FloatingSelectionController`) computes its commit footprint from geometry before it copies or cuts anything: before and after pixels over union of hole and landing, selection alpha before and after, entry overhead. Admitted for that footprint as part of the drag that lifts it; keeps the transaction until it lands or is dropped. Every move, scale or rotation grows admission to the footprint at the new transform, from geometry alone; transform that does not fit keeps last accepted one and reports `over-budget` once per float, so an accepted transform always fits its undo entry while permit stays current; admission never shrinks, so a live float holds its largest accepted footprint until it lands or is dropped. Refused lift is reported and moves nothing (`lift` returns `refused`), including content whose cache is not rebuilt yet; only a lift with nothing to take (`unavailable`) lets Move tool fall back to moving the layer. Cut layer's persistence is suspended while float lives. Commit lands pixels and moved selection as one entry under retained admission, renewed once when its permit went stale (an operation locked and released the document meanwhile); commit that cannot be admitted or published puts pre-lift pixels and selection back. Cancellation refills hole before persistence resumes; hole that cannot be refilled keeps layer suspended rather than uploading it. Every terminal path ends the transaction: commit, cancel, Escape, undo/redo, layer's deletion or replacement, document replacement, cooldown (which banks the float before the flush), disposal, exceptions while cutting or landing.-Live pixel edits (brush, eraser, shapes on paint layers or as opaque mask coverage, pixel transactions on control and image layers) are admitted before their first pixel changes and grow their admission before the stroke's before/after footprint does; refused growth restores layer's pixels and extent and engine reports the refusal through `tools.onEditRefused`, which canvas widget turns into a notice. Tools report a press the selected layer cannot take there too, as a `CanvasLayerEditRefusal` naming the layer: hidden (disabled, itself or through a group), locked, transparency-locked under the eraser, or its durable pixels not in the cache yet (the press requests them and the next one can edit; nothing is drawn over missing pixels). The Brush never creates a layer above a locked or hidden image on its own; its refusal offers one. Brush, eraser and move cursors read not-allowed over such a selection; the engine refreshes the cursor on every document change. Widget previews of structural edits run in one owned `StructuralPreviewSession` (`useStructuralPreview`), which coalesces live dispatches to one per frame, captures the values its first preview of each field replaces (session's baseline) and records the gesture as a single step from it; refused commit or cancel restores that baseline, even while edits are locked. A commit from elsewhere, a history replay, a newer session or disposal ends an open session first, dropping pending previews and restoring baseline, so previewed values never land over a replayed document or inside another step: every engine edit starts from `CanvasMutationContext.getDocument()`, which ends it first (structural controller's commits and nudges, pixel and layer operations such as merge down and duplicate, result commits); widget-prepared edits (`commitPreparedEdit`, layers tree's child-row commands) end it before reading the model; `HistoryController` ends it (with any live float) before a replay that has a step to land, and a replay with nothing to land disturbs nothing; document replacement drops it without restoring, since the document it previewed on is gone. Widget's next preview starts a new session from changed document, and a commit after engine ended its session records from live values; its refusal as `missing` stays silent, since the document change that ended the gesture also unmounted the editor.+Live pixel edits (brush, eraser, shapes on paint layers or as opaque mask coverage, pixel transactions on control and image layers) are admitted before their first pixel changes and grow their admission before the stroke's before/after footprint does; refused growth restores layer's pixels and extent and engine reports the refusal through `tools.onEditRefused`, which canvas widget turns into a notice. Tools report a press the selected layer cannot take there too, as a `CanvasLayerEditRefusal` naming the layer: hidden (disabled, itself or through a group), locked, transparency-locked under the eraser or a shape cutout, or its durable pixels not in the cache yet (the press requests them and the next one can edit; nothing is drawn over missing pixels). A shape cutout (the platform's mod key: ⌘ on macOS, where Ctrl-click opens the context menu, Ctrl elsewhere) with no paint layer or mask selected reports a `CanvasShapeCutoutRefusal` and never adds a layer. The Shape tool reports at the press when the press already decides the target, and again at commit if the target changed meanwhile. The Brush never creates a layer above a locked or hidden image on its own; its refusal offers one. Brush, eraser, shape and move cursors read not-allowed over such a selection; the engine refreshes the cursor on every document change. Widget previews of structural edits run in one owned `StructuralPreviewSession` (`useStructuralPreview`), which coalesces live dispatches to one per frame, captures the values its first preview of each field replaces (session's baseline) and records the gesture as a single step from it; refused commit or cancel restores that baseline, even while edits are locked. A commit from elsewhere, a history replay, a newer session or disposal ends an open session first, dropping pending previews and restoring baseline, so previewed values never land over a replayed document or inside another step: every engine edit starts from `CanvasMutationContext.getDocument()`, which ends it first (structural controller's commits and nudges, pixel and layer operations such as merge down and duplicate, result commits); widget-prepared edits (`commitPreparedEdit`, layers tree's child-row commands) end it before reading the model; `HistoryController` ends it (with any live float) before a replay that has a step to land, and a replay with nothing to land disturbs nothing; document replacement drops it without restoring, since the document it previewed on is gone. Widget's next preview starts a new session from changed document, and a commit after engine ended its session records from live values; its refusal as `missing` stays silent, since the document change that ended the gesture also unmounted the editor.Undo and redo are async and failure-atomic: entry moves to the other stack only after its replay completes, replay that throws leaves it in place and is reported, and edits and new gestures are refused while one runs. Replays apply steps through same verified path (`applyStep`). Pixel replays land only on trustworthy pixels: evicted or stale cache is rasterized first under a read lease, and a layer that no longer exists moves the step as a no-op.@@ -289,7 +291,7 @@ Capability returns `exported`, `busy`, `nothing`, `too-large` (PSD format or ser## 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, Move and the Frame tool's grid bypass, Transform's scale about the centre), which keeps the key and only gets no picker hold, since pointer events still carry `altKey`; the Color picker tool (I) covers those tools. 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.+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`. Escape first cancels the pointer gesture, then the engine ladder runs, most local first: a color pick, a defocused text edit, a transform session or pending transform, a float, the open session of the tool the user is on (the held tool under a Space, Alt or C hold: a polygon between clicks), an application operation (Filter, Select Object), and only then the selection. A tool's `onKeyCommand('cancel')` reports whether it dropped a session; one that did, or a gesture the Escape cancelled, keeps the committed selection; 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, Move and the Frame tool's grid bypass, Transform's scale about the centre, Shape's draw from the centre), which keeps the key and only gets no picker hold, since pointer events still carry `altKey`; the Color picker tool (I) covers those tools. 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.`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`.@@ -311,7 +313,7 @@ Real-Canvas2D suite verifies transformed composition, clipping, alpha and blend## Adding functionality-- New tool: implement tool interface under `tools/`, keep durable state in `CanvasProjectMutation`, expose only required tool capability methods.+- New tool: implement tool interface under `tools/`, keep durable state in `CanvasProjectMutation`, expose only required tool capability methods. Commit structural edits on pointer-up or from a key command with no press held, never on pointer-down: the pipeline's gesture is active from press to release, and `commitStructural` refuses it as `gesture-active` (the Shape tool's click-closed polygon commits on the release of its closing press for this reason). Pixel edits begun through `beginStrokeEdit` belong to the gesture and may start on the press.- New derived effect: add stable effect kind/parameter key, construct through `DerivedSurfaceCache`, test warm hits, precise invalidation, stale source guards, culling, byte accounting.- New layer operation: pure pixel/document math in core, orchestration in a controller; accept narrow ports, use project-bound mutations, reserve background allocations, return status unions for expected no-op/stale cases.- New background raster workflow: capture document snapshot, plan required layers, reserve and pin before allocation, detach immutable surfaces, release every lease in `finally`, define whether edits after detachment are allowed.diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/api.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/api.tsindex 47e0e4c576..9ecf71472f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/api.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/api.ts@@ -15,3 +15,4 @@ export {restoreControlOriginal,} from './document/controlDerivation';export { createControlLayer, type CreateControlLayerInput, nextControlLayerName } from './document/layerFactories';+export { shapeDrawsOnLayer } from './tools/shapeTarget';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.tsindex 99b6dd9191..c7b9d3f2b1 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts@@ -432,15 +432,22 @@ export interface CanvasLayerEditRefusal {readonly canPaintNewLayer?: boolean;}+/** A shape cut out with the mod key found no selected paint layer or mask to erase its footprint from. */+export interface CanvasShapeCutoutRefusal {+ readonly status: 'cutout-no-target';+}+/*** Why the engine refused an edit the user started without a caller to report to (a stroke, a shape). An* `AdjustmentRefusal` names a layer whose spatial adjustments cannot run, so its pixels cannot be baked for painting;- * a `CanvasLayerEditRefusal` names a layer the active tool cannot edit.+ * a `CanvasLayerEditRefusal` names a layer the active tool cannot edit; a `CanvasShapeCutoutRefusal` has no layer to+ * name.*/export type CanvasEditRefusal =| SubsetOf<CanvasTransactionOutcome, 'busy' | 'gesture-active' | 'not-ready' | 'over-budget'>| AdjustmentRefusal- | CanvasLayerEditRefusal;+ | CanvasLayerEditRefusal+ | CanvasShapeCutoutRefusal;export type LayerThumbnailRequestResult =| 'ready'diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.tsindex b4fcd90544..7f5e5e3eb6 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts@@ -16157,11 +16157,61 @@ describe('masks while a result is staged', () => {h.engine.stores.shapeOptions.set({ ...h.engine.stores.shapeOptions.get(), target: 'new' });h.expectPressHidden();+ // A cutout edits the mask whatever Place on says: from a press with the mod key (Ctrl and ⌘ both held, so it is+ // the cutout key on any platform), or from the move that adds it mid-drag.+ const mod = { ctrlKey: true, metaKey: true };+ overlay.fire('pointerdown', { ...pointerAt(5, 5), ...mod });+ expect(frame()).toEqual({ ...MASKED, full: 1 });+ overlay.fire('pointerup', { ...pointerAt(15, 15, { buttons: 0 }), ...mod });+ expect(frame()).toEqual({ ...UNMASKED, full: 1 });+ overlay.fire('pointerdown', pointerAt(5, 5));+ expect(frame()).toMatchObject({ full: 0 });+ overlay.fire('pointermove', { ...pointerAt(15, 15), ...mod });+ expect(frame()).toEqual({ ...MASKED, full: 1 });+ overlay.fire('pointerup', { ...pointerAt(15, 15, { buttons: 0 }), ...mod });+ expect(frame()).toEqual({ ...UNMASKED, full: 1 });+h.engine.stores.shapeOptions.set({ ...h.engine.stores.shapeOptions.get(), kind: 'polygon', target: 'selected' });h.expectPressHidden();h.dispose();});+ it.each(['rect', 'freehand'] as const)(+ 'cuts the selected mask with a release-only modifier for %s without leaving masks above the preview',+ async (kind) => {+ const h = setup();+ const { frame, overlay } = h;+ h.select('m');+ h.useTool('shape');+ // Give the cutout mask pixels to erase, through the same tool interface.+ overlay.fire('pointerdown', pointerAt(0, 0));+ overlay.fire('pointermove', pointerAt(20, 20));+ overlay.fire('pointerup', pointerAt(20, 20, { buttons: 0 }));+ await h.showPreview();+ frame();+ h.engine.stores.shapeOptions.set({ ...h.engine.stores.shapeOptions.get(), kind, target: 'new' });+ const strokes: StrokeCommittedEvent[] = [];+ h.engine.tools.onStrokeCommitted((stroke) => strokes.push(stroke));++ overlay.fire('pointerdown', pointerAt(5, 5));+ expect(frame().drawn ?? []).not.toContain('m');+ overlay.fire('pointermove', pointerAt(15, 5));+ overlay.fire('pointermove', pointerAt(15, 15));+ expect(frame().drawn ?? []).not.toContain('m');+ // Release ends the gesture before the tool commits, so no mask-reveal gesture remains to announce.+ overlay.fire('pointerup', {+ ...pointerAt(kind === 'freehand' ? 5 : 15, 15, { buttons: 0 }),+ ctrlKey: true,+ metaKey: true,+ });++ expect(strokes).toHaveLength(1);+ expect(strokes[0]).toMatchObject({ layerId: 'm', tool: 'shape-cutout' });+ expect(frame()).toMatchObject(UNMASKED);+ h.dispose();+ }+ );+it.each([['a locked mask, which refuses every edit', [{ ...maskLayer('m'), isLocked: true }, rasterLayer('a')], 'm', false],[@@ -20504,8 +20554,17 @@ describe('edit feedback on the surface', () => {);vi.stubGlobal('removeEventListener', (type: string) => windowListeners.delete(type));const { dispatch, projectId, store } = createReducerBackedStore(document);+ const stubBackend = createTestStubRasterBackend();+ const surfaces: StubRasterSurface[] = [];const engine = createCanvasEngine({- backend: createTestStubRasterBackend(),+ backend: {+ ...stubBackend,+ createSurface: (width: number, height: number) => {+ const surface = stubBackend.createSurface(width, height);+ surfaces.push(surface);+ return surface;+ },+ },bitmapStore: createSpyBitmapStore(),imageResolver: () => Promise.resolve(new Blob()),projectId,@@ -20517,10 +20576,10 @@ describe('edit feedback on the surface', () => {engine.tools.onEditRefused((refusal) => refusals.push(refusal));const key = (type: 'keydown' | 'keyup', code: string) =>windowListeners.get(type)?.({ code, key: code, preventDefault: () => {}, target: null });- return { dispatch, engine, key, overlay, refusals };+ return { dispatch, engine, key, overlay, refusals, surfaces };};- it.each(['transform', 'bbox', 'move'] as const)(+ it.each(['transform', 'bbox', 'move', 'shape'] as const)('keeps %s when Alt is held before the drag, since Alt modifies its gesture',(tool) => {const h = attachEngine({ ...makeDoc(), selectedLayerId: 'a' });@@ -20559,4 +20618,212 @@ describe('edit feedback on the surface', () => {expect(h.engine.stores.cursor.get()).toBe('crosshair');h.engine.lifecycle.dispose();});++ describe('shape tool through the pointer pipeline', () => {+ const paintDoc = (): CanvasDocumentContractV3 => ({+ ...makeDoc(),+ selectedLayerId: 'paint',+ stacks: stacksFrom([+ { ...(rasterLayer('paint') as CanvasRasterLayerContractV2), source: { bitmap: null, type: 'paint' as const } },+ ]),+ });+ const maskDoc = (): CanvasDocumentContractV3 => ({+ ...makeDoc(),+ selectedLayerId: 'mask',+ stacks: stacksFrom([+ {+ blendMode: 'normal',+ id: 'mask',+ isEnabled: true,+ isLocked: false,+ mask: { bitmap: null, fill: { color: '#e07575', style: 'diagonal' } },+ name: 'Mask',+ opacity: 1,+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'inpaint_mask',+ },+ ]),+ });+ /** `mod` holds both Ctrl and ⌘, so the platform's cutout key is down whichever platform runs the test. */+ const at = (x: number, y: number, opts: { buttons?: number; mod?: boolean; timeStamp?: number } = {}) => ({+ ...pointerAt(x, y, { buttons: opts.buttons }),+ ctrlKey: opts.mod ?? false,+ metaKey: opts.mod ?? false,+ timeStamp: opts.timeStamp ?? 0,+ });+ const shapeEngine = (document: CanvasDocumentContractV3, kind: 'rect' | 'polygon') => {+ const h = attachEngine(document);+ const strokes: StrokeCommittedEvent[] = [];+ h.engine.tools.onStrokeCommitted((event) => strokes.push(event));+ h.engine.tools.setTool('shape');+ h.engine.stores.shapeOptions.set({ ...h.engine.stores.shapeOptions.get(), kind });+ h.overlay.fire('pointerenter', at(0, 0));+ const click = (x: number, y: number, opts: { mod?: boolean; timeStamp?: number } = {}) => {+ h.overlay.fire('pointerdown', at(x, y, opts));+ h.overlay.fire('pointerup', at(x, y, { ...opts, buttons: 0 }));+ };+ const drag = (from: number, to: number, opts: { mod?: boolean } = {}) => {+ h.overlay.fire('pointerdown', at(from, from));+ h.overlay.fire('pointermove', at(to, to));+ h.overlay.fire('pointerup', at(to, to, { ...opts, buttons: 0 }));+ };+ /** Places a triangle's three vertices at 10..50 × 10..40, a second apart so none reads as a double-click. */+ const placeTriangle = (start: number) => {+ click(10, 10, { timeStamp: start });+ click(50, 10, { timeStamp: start + 1000 });+ click(50, 40, { timeStamp: start + 2000 });+ };+ const leaves = () => getDocumentLeaves(h.engine.document.getDocument());+ return { ...h, click, drag, leaves, placeTriangle, strokes };+ };++ it('adds a polygon closed by a first-vertex click or a double-click as a new layer, one undo step each', async () => {+ const h = shapeEngine({ ...makeDoc(), stacks: stacksFrom([]) }, 'polygon');+ h.engine.stores.shapeOptions.set({ ...h.engine.stores.shapeOptions.get(), target: 'new' });++ h.placeTriangle(0);+ h.click(11, 11, { timeStamp: 3000 });+ expect(h.leaves()).toEqual([+ expect.objectContaining({ source: expect.objectContaining({ height: 30, kind: 'polygon', width: 40 }) }),+ ]);++ h.placeTriangle(4000);+ h.click(50, 40, { timeStamp: 6100 });+ expect(h.leaves()).toHaveLength(2);+ expect(h.refusals).toEqual([]);++ await h.engine.history.undo();+ await h.engine.history.undo();+ expect(h.leaves()).toHaveLength(0);+ h.engine.lifecycle.dispose();+ });++ it('draws a click-closed polygon onto the selected paint layer as one stroke', () => {+ const h = shapeEngine(paintDoc(), 'polygon');++ h.placeTriangle(0);+ h.click(10, 10, { timeStamp: 3000 });++ expect(h.leaves()).toHaveLength(1);+ expect(h.strokes).toEqual([expect.objectContaining({ layerId: 'paint', tool: 'shape' })]);+ expect(h.engine.stores.canUndo.get()).toBe(true);+ h.engine.lifecycle.dispose();+ });++ it.each([+ ['paint layer', paintDoc, 'paint'],+ ['mask', maskDoc, 'mask'],+ ] as const)(+ 'cuts a shape out of the selected %s with the mod key, and undo puts the pixels back',+ async (_l, doc, id) => {+ const h = shapeEngine(doc(), 'rect');+ h.drag(10, 60);+ h.drag(20, 40, { mod: true });++ expect(h.leaves()).toHaveLength(1);+ expect(h.strokes.map((stroke) => [stroke.layerId, stroke.tool])).toEqual([+ [id, 'shape'],+ [id, 'shape-cutout'],+ ]);+ const cutout = h.strokes[1]!;+ expect(cutout.dirtyRect).toEqual({ height: 20, width: 20, x: 20, y: 20 });++ await h.engine.history.undo();+ expect(h.engine.stores.canRedo.get()).toBe(true);+ // Undo writes the pixels the cutout removed back where it removed them: the cache starts at the first shape.+ expect(putImageDataCalls(h.surfaces)).toContainEqual({ image: cutout.beforeImageData, x: 10, y: 10 });+ expect(h.leaves()).toHaveLength(1);+ h.engine.lifecycle.dispose();+ }+ );++ it('says why a cutout did nothing when no paint layer or mask is selected, adding no layer', () => {+ const h = shapeEngine({ ...makeDoc(), stacks: stacksFrom([]) }, 'rect');+ h.drag(10, 60, { mod: true });++ expect(h.refusals).toEqual([{ status: 'cutout-no-target' }]);+ expect(h.leaves()).toHaveLength(0);+ expect(h.engine.stores.canUndo.get()).toBe(false);+ h.engine.lifecycle.dispose();+ });++ describe('Escape', () => {+ /** Shape or Lasso in polygon mode over an empty document with everything selected. */+ const polygonEngine = (tool: 'shape' | 'lasso') => {+ const h = shapeEngine({ ...makeDoc(), stacks: stacksFrom([]) }, 'polygon');+ h.engine.stores.lassoOptions.set({ ...h.engine.stores.lassoOptions.get(), shape: 'polygon' });+ h.engine.tools.setTool(tool);+ h.engine.selection.selectAll();+ const preview = () => h.engine.stores.lassoPreview.get();+ return { ...h, preview };+ };++ it.each(['shape', 'lasso'] as const)(+ 'drops a %s polygon between clicks, keeping the selection and adding nothing',+ (tool) => {+ const h = polygonEngine(tool);+ h.placeTriangle(0);+ expect(h.preview()).toMatchObject({ points: [{}, {}, {}] });++ h.key('keydown', 'Escape');+ expect(h.preview()).toBeNull();+ expect(h.engine.stores.hasSelection.get()).toBe(true);+ expect(h.leaves()).toHaveLength(0);++ // The next click starts a new polygon rather than extending the dropped one.+ h.click(70, 70, { timeStamp: 5000 });+ expect(h.preview()).toMatchObject({ points: [{ x: 70, y: 70 }] });+ h.engine.lifecycle.dispose();+ }+ );++ it.each(['shape', 'lasso'] as const)('drops a %s polygon once when Escape lands during a held press', (tool) => {+ const h = polygonEngine(tool);+ h.placeTriangle(0);+ h.overlay.fire('pointerdown', at(30, 60, { timeStamp: 3000 }));++ h.key('keydown', 'Escape');+ h.overlay.fire('pointerup', at(30, 60, { buttons: 0, timeStamp: 3000 }));+ expect(h.preview()).toBeNull();+ expect(h.engine.stores.hasSelection.get()).toBe(true);+ expect(h.leaves()).toHaveLength(0);+ h.engine.lifecycle.dispose();+ });++ it('drops the polygon of the tool a Space-held pan will return to', () => {+ const h = polygonEngine('shape');+ h.placeTriangle(0);+ h.key('keydown', 'Space');+ expect(h.engine.stores.activeTool.get()).toBe('view');++ h.key('keydown', 'Escape');+ h.key('keyup', 'Space');+ expect(h.engine.stores.activeTool.get()).toBe('shape');+ expect(h.preview()).toBeNull();+ expect(h.engine.stores.hasSelection.get()).toBe(true);+ h.engine.lifecycle.dispose();+ });++ it('still clears the selection when no tool session is open', () => {+ const h = polygonEngine('shape');+ h.key('keydown', 'Escape');+ expect(h.engine.stores.hasSelection.get()).toBe(false);+ h.engine.lifecycle.dispose();+ });+ });++ it('refreshes the cursor when Place on changes whether the selected layer would refuse the shape', () => {+ const locked = paintDoc();+ const h = shapeEngine(+ { ...locked, stacks: stacksFrom([{ ...getDocumentLeaves(locked)[0]!, isLocked: true }]) },+ 'rect'+ );+ h.engine.stores.shapeOptions.set({ ...h.engine.stores.shapeOptions.get(), target: 'new' });+ expect(h.engine.stores.cursor.get()).toBe('crosshair');++ h.engine.stores.shapeOptions.set({ ...h.engine.stores.shapeOptions.get(), target: 'selected' });+ expect(h.engine.stores.cursor.get()).toBe('not-allowed');+ h.engine.lifecycle.dispose();+ });+ });});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex 50df16bb20..84982651b0 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -1980,15 +1980,22 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCupdateCursor,});toolsReady = true;+ // The shape cursor reads Place on: not-allowed over a selected layer a shape drawn there would refuse.+ const unsubscribeShapeOptions = stores.shapeOptions.subscribe(() => {+ if (interactionController.getActiveToolId() === 'shape') {+ updateCursor();+ }+ });const setTool = (toolId: ToolId, options?: { temporary?: boolean }): void => {colorSamples.onToolChange(toolId);interactionController.setTool(toolId, options);};/**- * 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.+ * After gesture cancellation, Escape cancels defocused text editing, then transform, then a float, then the tool's+ * own open session (a polygon between clicks), then an application operation, then selection. Focused portals+ * handle Escape themselves. If a gesture or a tool session consumed Escape, preserve committed selection. Shared+ * with pipeline wiring and node tests.*/const handleEscapePriority = ({ gestureWasActive }: { gestureWasActive: boolean }): void => {if (colorSamples.onEscape()) {@@ -2011,6 +2018,11 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCfloatingSelection.cancel();return;}+ // The tool the user is really on: a Space-held pan mid-polygon keeps the polygon's session on the held tool.+ const sessionTool = tools.get(pipeline.heldRestoreToolId() ?? interactionController.getActiveToolId());+ if (sessionTool?.onKeyCommand?.(toolContext, 'cancel')) {+ return;+ }if (applicationEscapeHandler?.(gestureWasActive)) {return;}@@ -2687,6 +2699,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCcleanup.run(unsubscribeShowBbox);cleanup.run(unsubscribeBboxOverlay);cleanup.run(unsubscribeRuleOfThirds);+ cleanup.run(unsubscribeShapeOptions);cleanup.run(unsubscribeProjectPreviewLifecycle);cleanup.run(unsubscribeTextFontSources);cleanup.run(unsubscribeTextDefaultsFontSources);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.browser.test.tsindex 0603428a51..fe30c5a195 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.browser.test.ts@@ -44,7 +44,7 @@ const createInputHarness = () => {deactivations.push(id);}},- onKeyCommand: (_ctx, command) => events.push(`${id}:${command}`),+ onKeyCommand: (_ctx, command) => events.push(`${id}:${command}`) > 0,onPointerCancel: () => events.push(`${id}:cancel`),onPointerDown: () => events.push(`${id}:down`),onPointerMove: () => events.push(`${id}:move`),diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.test.tsindex 379dca6462..380cd88eee 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.test.ts@@ -663,7 +663,7 @@ describe('pointer pipeline: injected key owner', () => {const resolveKeyOwner = vi.fn((_event: KeyboardEvent) => owner);const h = createHarness({ handleEscape, resolveKeyOwner, tools: ['view', 'brush', 'bbox', 'colorPicker'] });const commands: string[] = [];- h.tool.onKeyCommand = (_ctx, command) => commands.push(command);+ h.tool.onKeyCommand = (_ctx, command) => commands.push(command) > 0;return { ...h, commands, handleEscape, resolveKeyOwner };};const BODY = { tagName: 'BODY' };@@ -748,7 +748,7 @@ describe('pointer pipeline: canvas keyboard ownership', () => {const applyHarness = () => {const h = createHarness();const commands: string[] = [];- h.tool.onKeyCommand = (_ctx, command) => commands.push(command);+ h.tool.onKeyCommand = (_ctx, command) => commands.push(command) > 0;return { ...h, commands };};@@ -771,7 +771,7 @@ describe('pointer pipeline: canvas keyboard ownership', () => {const handleEscape = vi.fn();const h = createHarness({ handleEscape });const commands: string[] = [];- h.tool.onKeyCommand = (_ctx, command) => commands.push(command);+ h.tool.onKeyCommand = (_ctx, command) => commands.push(command) > 0;h.pipeline.onPointerEnter();const body = { tagName: 'BODY' };const release = registerModalPresence();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.tsindex 3d33d37ec7..3b54db9a54 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.ts@@ -472,7 +472,7 @@ const drawRectShapePreview = (ctx: Ctx, state: OverlayState, preview: RectShapePctx.lineWidth = 1;ctx.setLineDash([...BBOX_DASH]);// The same path the rasterizer commits, so the outline is the shape it makes.- buildParametricShapePath(ctx, preview.kind, screen.x, screen.y, Math.abs(screen.width), Math.abs(screen.height), 0);+ buildParametricShapePath(ctx, preview.kind, screen.x, screen.y, Math.abs(screen.width), Math.abs(screen.height));ctx.stroke();ctx.setLineDash([]);ctx.restore();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/raster.testStub.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/raster.testStub.tsindex 5ddbfcf5c3..ab3af8fe4f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/raster.testStub.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/raster.testStub.ts@@ -55,13 +55,14 @@ const fontSizeFromShorthand = (font: unknown): number => {const createStubCtx = (callLog: RasterCallLogEntry[],- readbackAlpha: number+ readbackAlpha: number,+ canvas: RasterSurface['canvas']): OffscreenCanvasRenderingContext2D | CanvasRenderingContext2D => {const log = (op: string, args: unknown[]): void => {callLog.push({ args, op });};- const props: Record<string, unknown> = {};+ const props: Record<string, unknown> = { canvas };const methods: Record<string, (...args: unknown[]) => unknown> = {arc: (...args: unknown[]) => log('arc', args),@@ -147,13 +148,15 @@ class StubRasterSurfaceImpl implements StubRasterSurface {this.width = width;this.height = height;this.canvas = { height, width } as unknown as OffscreenCanvas | HTMLCanvasElement;- this.ctx = createStubCtx(this.callLog, readbackAlpha);+ this.ctx = createStubCtx(this.callLog, readbackAlpha, this.canvas);}resize(w: number, h: number): void {this.callLog.push({ args: [w, h], op: 'resize' });this.width = w;this.height = h;+ this.canvas.width = w;+ this.canvas.height = h;}/**@@ -164,6 +167,8 @@ class StubRasterSurfaceImpl implements StubRasterSurface {this.callLog.push({ args: [w, h, dx, dy], op: 'resizePreserving' });this.width = w;this.height = h;+ this.canvas.width = w;+ this.canvas.height = h;}}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/shapeRasterizer.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/shapeRasterizer.browser.test.tsnew file mode 100644index 0000000000..cbcd13e5f3--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/shapeRasterizer.browser.test.ts@@ -0,0 +1,306 @@+import type { CanvasLayerSourceContract } from '@workbench/canvas-engine/contracts';++import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';+import { createDomRasterBackend } from '@workbench/canvas-engine/render/raster';+import { describe, expect, it } from 'vitest';++import { drawShapeSource, rasterizeShapeSource } from './shapeRasterizer';++type ShapeSource = Extract<CanvasLayerSourceContract, { type: 'shape' }>;++const fixtures: readonly {+ name: string;+ source: ShapeSource;+ border: { x: number; y: number };+ interior: { x: number; y: number };+ outside: { x: number; y: number };+}[] = [+ {+ name: 'triangle',+ border: { x: 40, y: 8 },+ interior: { x: 40, y: 70 },+ outside: { x: 2, y: 10 },+ source: {+ fill: '#ff0000',+ height: 120,+ kind: 'triangle',+ stroke: '#ffffff',+ strokeWidth: 18,+ type: 'shape',+ width: 80,+ },+ },+ {+ name: 'concave polygon (a closed freehand shape)',+ border: { x: 2, y: 60 },+ interior: { x: 20, y: 75 },+ outside: { x: 60, y: 90 },+ source: {+ fill: '#ff0000',+ height: 120,+ kind: 'polygon',+ points: [+ { x: 0, y: 0 },+ { x: 120, y: 0 },+ { x: 120, y: 120 },+ { x: 80, y: 120 },+ { x: 70, y: 35 },+ { x: 50, y: 35 },+ { x: 40, y: 120 },+ { x: 0, y: 120 },+ ],+ stroke: '#ffffff',+ strokeWidth: 18,+ type: 'shape',+ width: 120,+ },+ },+ {+ name: 'rectangle',+ border: { x: 2, y: 50 },+ interior: { x: 60, y: 50 },+ outside: { x: -2, y: 50 },+ source: {+ fill: '#ff0000',+ height: 100,+ kind: 'rect',+ stroke: '#ffffff',+ strokeWidth: 18,+ type: 'shape',+ width: 120,+ },+ },+ {+ name: 'ellipse',+ border: { x: 60, y: 2 },+ interior: { x: 60, y: 50 },+ outside: { x: 2, y: 2 },+ source: {+ fill: '#ff0000',+ height: 100,+ kind: 'ellipse',+ stroke: '#ffffff',+ strokeWidth: 18,+ type: 'shape',+ width: 120,+ },+ },+ {+ name: 'star',+ border: { x: 80, y: 10 },+ interior: { x: 80, y: 80 },+ outside: { x: 10, y: 10 },+ source: {+ fill: '#ff0000',+ height: 160,+ kind: 'star',+ stroke: '#ffffff',+ strokeWidth: 18,+ type: 'shape',+ width: 160,+ },+ },+];++describe('shape borders in Chromium', () => {+ it.each([+ { name: 'triangle slope', source: fixtures[0]!.source, x: 38, y: 3 },+ { name: 'concave notch slope', source: fixtures[1]!.source, x: 74, y: 73 },+ ])('keeps the antialiased white outline free of red fill at the $name', ({ source, x, y }) => {+ const surface = createDomRasterBackend().createSurface(source.width + 32, source.height + 32);+ drawShapeSource(surface.ctx, source, 16, 16, source.width, source.height);+ // These pixels straddle the known outer silhouette, far from the outline's inner color transition.+ const pixel = Array.from(surface.ctx.getImageData(x + 16, y + 16, 1, 1).data);+ expect(pixel[3]).toBeGreaterThan(0);+ expect(pixel[3]).toBeLessThan(255);+ expect(pixel.slice(0, 3), `Exterior RGBA: ${JSON.stringify(pixel)}`).toEqual([255, 255, 255]);+ });++ it.each(fixtures)('keeps the thick white border outside the red fill for $name', ({ source }) => {+ const backend = createDomRasterBackend();+ const surface = backend.createSurface(source.width + 32, source.height + 32);+ drawShapeSource(surface.ctx, source, 16, 16, source.width, source.height);+ const { data, height, width } = surface.ctx.getImageData(0, 0, surface.width, surface.height);+ const exposedFill: { x: number; y: number }[] = [];+ let redPixels = 0;+ let whitePixels = 0;+ for (let y = 2; y < height - 2; y += 1) {+ for (let x = 2; x < width - 2; x += 1) {+ const index = (y * width + x) * 4;+ if (data[index + 3]! < 240) {+ continue;+ }+ if (data[index]! > 240 && data[index + 1]! > 240 && data[index + 2]! > 240) {+ whitePixels += 1;+ }+ if (data[index]! < 240 || data[index + 1]! > 16 || data[index + 2]! > 16) {+ continue;+ }+ redPixels += 1;+ // An 18px white border must separate solid red fill from transparency by more than antialiasing alone.+ if (+ [+ [-2, 0],+ [2, 0],+ [0, -2],+ [0, 2],+ ].some(([dx, dy]) => data[((y + dy!) * width + x + dx!) * 4 + 3]! < 16)+ ) {+ exposedFill.push({ x: x - 16, y: y - 16 });+ }+ }+ }+ expect(redPixels).toBeGreaterThan(0);+ expect(whitePixels).toBeGreaterThan(0);+ expect(exposedFill.slice(0, 8)).toEqual([]);+ });++ it.each(fixtures)(+ 'keeps opaque fill under translucent and transparent strokes for $name',+ ({ source, border, interior }) => {+ const backend = createDomRasterBackend();+ for (const [stroke, green] of [+ ['#ffffff80', 128],+ ['#ffffff00', 0],+ ] as const) {+ const surface = backend.createSurface(source.width + 32, source.height + 32);+ drawShapeSource(surface.ctx, { ...source, stroke }, 16, 16, source.width, source.height);+ const borderPixel = Array.from(surface.ctx.getImageData(border.x + 16, border.y + 16, 1, 1).data);+ expect(borderPixel).toEqual([255, green, green, 255]);+ expect(Array.from(surface.ctx.getImageData(interior.x + 16, interior.y + 16, 1, 1).data)).toEqual([+ 255, 0, 0, 255,+ ]);+ }+ }+ );++ it.each(fixtures)(+ 'contains stroke-only coverage within the original silhouette and extent for $name',+ ({ source, border, interior, outside }) => {+ const backend = createDomRasterBackend();+ const surface = backend.createSurface(source.width + 32, source.height + 32);+ drawShapeSource(surface.ctx, { ...source, fill: null }, 16, 16, source.width, source.height);+ expect(Array.from(surface.ctx.getImageData(border.x + 16, border.y + 16, 1, 1).data)).toEqual([+ 255, 255, 255, 255,+ ]);+ expect(surface.ctx.getImageData(interior.x + 16, interior.y + 16, 1, 1).data[3]).toBe(0);+ expect(surface.ctx.getImageData(outside.x + 16, outside.y + 16, 1, 1).data[3]).toBe(0);+ const { data, width, height } = surface.ctx.getImageData(0, 0, surface.width, surface.height);+ let outsideAlpha = 0;+ for (let y = 0; y < height; y += 1) {+ for (let x = 0; x < width; x += 1) {+ if (x < 16 || x >= source.width + 16 || y < 16 || y >= source.height + 16) {+ outsideAlpha += data[(y * width + x) * 4 + 3]!;+ }+ }+ }+ expect(outsideAlpha).toBe(0);+ }+ );++ it('uses the configured width inside the original rectangle edge', () => {+ const surface = createDomRasterBackend().createSurface(100, 100);+ drawShapeSource(+ surface.ctx,+ { fill: null, height: 60, kind: 'rect', stroke: '#ffffff', strokeWidth: 18, type: 'shape', width: 60 },+ 20,+ 20,+ 60,+ 60+ );+ expect(Array.from(surface.ctx.getImageData(37, 50, 1, 1).data)).toEqual([255, 255, 255, 255]);+ expect(surface.ctx.getImageData(38, 50, 1, 1).data[3]).toBe(0);+ expect(surface.ctx.getImageData(19, 50, 1, 1).data[3]).toBe(0);+ });++ it.each([+ ['#ffffff', [255, 255, 255, 255]],+ ['#ffffff80', [255, 170, 170, 192]],+ ] as const)('composites %s stroke independently over translucent fill', (stroke, borderPixel) => {+ const surface = createDomRasterBackend().createSurface(100, 100);+ drawShapeSource(+ surface.ctx,+ { fill: '#ff000080', height: 60, kind: 'rect', stroke, strokeWidth: 10, type: 'shape', width: 60 },+ 20,+ 20,+ 60,+ 60+ );+ expect(Array.from(surface.ctx.getImageData(22, 50, 1, 1).data)).toEqual(borderPixel);+ expect(Array.from(surface.ctx.getImageData(50, 50, 1, 1).data)).toEqual([255, 0, 0, 128]);+ });++ it('applies exterior coverage once with fractional placement and a nonuniform transform', () => {+ const surface = createDomRasterBackend().createSurface(160, 100);+ surface.ctx.setTransform(1.25, 0, 0, 0.75, 0.25, 0.25);+ drawShapeSource(+ surface.ctx,+ { fill: '#ff0000', height: 80, kind: 'rect', stroke: '#ffffff', strokeWidth: 10, type: 'shape', width: 80 },+ 16,+ 16,+ 80,+ 80+ );+ const pixel = Array.from(surface.ctx.getImageData(20, 12, 1, 1).data);+ expect(pixel[3]).toBeGreaterThan(0);+ expect(pixel[3]).toBeLessThan(255);+ expect(pixel.slice(0, 3)).toEqual([255, 255, 255]);+ expect(Array.from(surface.ctx.getImageData(70, 42, 1, 1).data)).toEqual([255, 0, 0, 255]);+ });++ it('clears a reused rasterization target after a stroked shape', async () => {+ const backend = createDomRasterBackend();+ const target = backend.createSurface(64, 64);+ const deps = {+ backend,+ documentSize: { width: 64, height: 64 },+ resolver: () => Promise.resolve(new Blob()),+ store: createLayerCacheStore(backend),+ };+ const source: ShapeSource = {+ fill: '#ff0000',+ height: 64,+ kind: 'rect',+ stroke: '#ffffff',+ strokeWidth: 10,+ type: 'shape',+ width: 64,+ };+ await rasterizeShapeSource(source, deps, target);+ expect(target.ctx.getImageData(0, 0, 1, 1).data[3]).toBe(255);+ const result = await rasterizeShapeSource(+ { ...source, kind: 'triangle', fill: '#00ff00', stroke: null },+ deps,+ target+ );+ expect(result.surface).toBe(target);+ expect(target.ctx.getImageData(0, 0, 1, 1).data[3]).toBe(0);+ expect(Array.from(target.ctx.getImageData(32, 40, 1, 1).data)).toEqual([0, 255, 0, 255]);+ });++ it('restores caller transform, alpha, composite mode and clip after drawing an outline', () => {+ const surface = createDomRasterBackend().createSurface(180, 180);+ const { ctx } = surface;+ ctx.beginPath();+ ctx.rect(0, 0, 150, 150);+ ctx.clip();+ ctx.setTransform(1, 0, 0, 1, 3, 2);+ ctx.globalAlpha = 0.5;+ ctx.globalCompositeOperation = 'xor';+ const { source } = fixtures[0]!;+ drawShapeSource(ctx, source, 16, 16, source.width, source.height);+ expect(ctx.globalAlpha).toBe(0.5);+ expect(ctx.globalCompositeOperation).toBe('xor');+ const { a, b, c, d, e, f } = ctx.getTransform();+ expect({ a, b, c, d, e, f }).toEqual({ a: 1, b: 0, c: 0, d: 1, e: 3, f: 2 });+ expect(ctx.getImageData(59, 88, 1, 1).data[3]).toBe(128);+ expect(Array.from(ctx.getImageData(59, 26, 1, 1).data)).toEqual([255, 170, 170, 192]);+ ctx.setTransform(1, 0, 0, 1, 0, 0);+ ctx.globalAlpha = 1;+ ctx.globalCompositeOperation = 'source-over';+ ctx.fillStyle = '#00ff00';+ ctx.fillRect(0, 0, 180, 180);+ expect(Array.from(ctx.getImageData(2, 2, 1, 1).data)).toEqual([0, 255, 0, 255]);+ expect(ctx.getImageData(160, 160, 1, 1).data[3]).toBe(0);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/shapeRasterizer.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/shapeRasterizer.test.tsindex 7f9651fa69..081d7c1b8e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/shapeRasterizer.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/shapeRasterizer.test.ts@@ -50,7 +50,7 @@ describe('rasterizeShapeSource — extent + sizing', () => {});describe('rasterizeShapeSource — polygon', () => {- it('traces the stored vertices, rescaled into the stroke inset box', async () => {+ it('traces the stored vertices for a clipped inside stroke', async () => {const deps = makeDeps();const surface = (await rasterizeShapeSource(@@ -70,11 +70,10 @@ describe('rasterizeShapeSource — polygon', () => {deps)).surface as StubRasterSurface;- // Inset 4px per side: the 60×40 box becomes 52×32 at (4, 4).- expect(surface.callLog.find((e) => e.op === 'moveTo')?.args).toEqual([4, 4]);+ expect(surface.callLog.find((e) => e.op === 'moveTo')?.args).toEqual([0, 0]);expect(surface.callLog.filter((e) => e.op === 'lineTo').map((e) => e.args)).toEqual([- [56, 4],- [30, 36],+ [60, 0],+ [30, 40],]);expect(ops(surface)).toContain('closePath');expect(ops(surface)).toContain('stroke');@@ -94,15 +93,14 @@ describe('rasterizeShapeSource — rect', () => {expect(ops(surface)).not.toContain('stroke');});- it('strokes with the stroke color + width, inset so it stays within the extent', async () => {+ it('masks a double-width centered stroke to the shape silhouette', async () => {const deps = makeDeps();const surface = (await rasterizeShapeSource(rect({ fill: null, stroke: '#0000ff', strokeWidth: 8 }), deps)).surface as StubRasterSurface;const log = surface.callLog;expect(log.some((e) => e.op === 'set' && e.args[0] === 'strokeStyle' && e.args[1] === '#0000ff')).toBe(true);- expect(log.some((e) => e.op === 'set' && e.args[0] === 'lineWidth' && e.args[1] === 8)).toBe(true);+ expect(log.some((e) => e.op === 'set' && e.args[0] === 'lineWidth' && e.args[1] === 16)).toBe(true);expect(ops(surface)).toContain('stroke');- expect(ops(surface)).not.toContain('fill');});it('draws both fill and stroke when both are set', async () => {@@ -152,7 +150,7 @@ describe('rasterizeShapeSource — triangle and star', () => {expect(log.filter((op) => op === 'lineTo')).toHaveLength(9);expect(log).toContain('closePath');expect(log).toContain('stroke');- expect((surface.ctx as unknown as { lineJoin: string }).lineJoin).toBe('round');+ expect(surface.callLog.some((e) => e.op === 'set' && e.args[0] === 'lineJoin' && e.args[1] === 'round')).toBe(true);});});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/shapeRasterizer.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/shapeRasterizer.tsindex cc12c0278b..f26f6a69de 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/shapeRasterizer.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/shapeRasterizer.ts@@ -1,6 +1,6 @@/**- * Parametric shapes rasterize at source width/height; compositing applies transforms. Inset strokes by half-width- * to contain outlines. Polygons with fewer than three vertices are refused.+ * Parametric shapes rasterize at source width/height; compositing applies transforms. Fill and inside-only strokes+ * share one silhouette mask, so acute and concave outlines contain the fill without color fringes.*/import type { CanvasLayerSourceContract, ParametricShapeKind } from '@workbench/canvas-engine/contracts';@@ -15,10 +15,7 @@ type Ctx = RasterSurface['ctx'];const STAR_INNER_RATIO = 0.382;const STAR_SPIKES = 5;-/**- * Shared raster/preview path inside an inset box, with round joins for sharp corners. Inset rescales the box- * rather than uniformly offsetting edges, so slanted thick outlines may drift slightly beyond the fill silhouette.- */+/** The original shape silhouette, shared by rasterized fill, its clipped outline and the tool preview. */export const buildParametricShapePath = (ctx: Ctx,kind: ParametricShapeKind | 'polygon',@@ -26,22 +23,15 @@ export const buildParametricShapePath = (y: number,width: number,height: number,- inset: number,points?: readonly { x: number; y: number }[]): void => {- const w = Math.max(0, width - inset * 2);- const h = Math.max(0, height - inset * 2);const cx = x + width / 2;const cy = y + height / 2;ctx.beginPath();if (kind === 'polygon') {- // Vertices are stored across the un-inset box; rescale them into the- // inset one (the same box rescale the other kinds get).- const sx = width > 0 ? w / width : 1;- const sy = height > 0 ? h / height : 1;(points ?? []).forEach((point, index) => {- const px = x + inset + point.x * sx;- const py = y + inset + point.y * sy;+ const px = x + point.x;+ const py = y + point.y;if (index === 0) {ctx.moveTo(px, py);} else {@@ -52,19 +42,19 @@ export const buildParametricShapePath = (return;}if (kind === 'ellipse') {- ctx.ellipse(cx, cy, w / 2, h / 2, 0, 0, Math.PI * 2);+ ctx.ellipse(cx, cy, width / 2, height / 2, 0, 0, Math.PI * 2);return;}if (kind === 'triangle') {- ctx.moveTo(cx, cy - h / 2);- ctx.lineTo(cx + w / 2, cy + h / 2);- ctx.lineTo(cx - w / 2, cy + h / 2);+ ctx.moveTo(cx, cy - height / 2);+ ctx.lineTo(cx + width / 2, cy + height / 2);+ ctx.lineTo(cx - width / 2, cy + height / 2);ctx.closePath();return;}if (kind === 'star') {- const rx = w / 2;- const ry = h / 2;+ const rx = width / 2;+ const ry = height / 2;for (let i = 0; i < STAR_SPIKES * 2; i += 1) {const radius = i % 2 === 0 ? 1 : STAR_INNER_RATIO;const angle = -Math.PI / 2 + (i * Math.PI) / STAR_SPIKES;@@ -79,10 +69,15 @@ export const buildParametricShapePath = (ctx.closePath();return;}- ctx.rect(x + inset, y + inset, w, h);+ ctx.rect(x, y, width, height);};-/** Shared fill-then-stroke drawing keeps shape rasterization and pixel placement consistent. */+/**+ * Draw into an isolated transparent target: the shape rasterizer clears it, and the Shape tool supplies fresh+ * scratch pixels. With an outline, compose the styles first and mask them to the silhouette once; clipping the+ * stroke over an already-antialiased fill would expose fill color along the exterior edge. The final mask clears+ * everything outside the shape, so this must never draw directly over existing layer pixels.+ */export const drawShapeSource = (ctx: Ctx,source: ShapeSource,@@ -91,22 +86,36 @@ export const drawShapeSource = (width: number,height: number): void => {- if (source.fill) {- ctx.fillStyle = source.fill;- buildParametricShapePath(ctx, source.kind, x, y, width, height, 0, source.points);- ctx.fill();+ const stroke = source.strokeWidth > 0 ? source.stroke : null;+ if (!source.fill && !stroke) {+ return;}- if (source.stroke && source.strokeWidth > 0) {- ctx.strokeStyle = source.stroke;- ctx.lineWidth = source.strokeWidth;- // Round joins keep sharp vertices within the half-stroke inset (a miter- // would spike past it); a rect keeps its miter — the 90° tip lands exactly- // on the extent corner, and rounding it would re-render every stored rect.+ ctx.save();+ ctx.globalCompositeOperation = 'source-over';+ buildParametricShapePath(ctx, source.kind, x, y, width, height, source.points);+ if (stroke) {+ if (source.fill) {+ // Cover the target, not the transformed shape bounds: the silhouette must be its only antialiased edge.+ ctx.save();+ ctx.setTransform(1, 0, 0, 1, 0, 0);+ ctx.fillStyle = source.fill;+ ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);+ ctx.restore();+ }+ ctx.strokeStyle = stroke;+ ctx.lineWidth = source.strokeWidth * 2;ctx.lineJoin = source.kind === 'rect' || source.kind === 'ellipse' ? 'miter' : 'round';- // Inset by half the stroke width so the (centered) stroke stays inside the extent.- buildParametricShapePath(ctx, source.kind, x, y, width, height, source.strokeWidth / 2, source.points);ctx.stroke();+ // Canvas strokes are centered; one mask keeps the inside half at the configured width and applies coverage once.+ ctx.globalCompositeOperation = 'destination-in';+ ctx.globalAlpha = 1;+ ctx.fillStyle = '#000000';+ ctx.fill();+ } else if (source.fill) {+ ctx.fillStyle = source.fill;+ ctx.fill();}+ ctx.restore();};export const rasterizeShapeSource = (diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.tsindex 484a4dcf03..062e9fe535 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.ts@@ -21,9 +21,15 @@ export interface CreateStrokeEditsDeps {readonly reportRefusal: (status: EditRefusal) => void;}+const STROKE_COMMIT_LABELS: Record<StrokeCommittedEvent['tool'], string> = {+ brush: 'Brush stroke',+ eraser: 'Eraser stroke',+ shape: 'Draw shape',+ 'shape-cutout': 'Cut out shape',+};+/** The history label for a committed pixel stroke. */-export const strokeCommitLabel = (tool: StrokeCommittedEvent['tool']): string =>- tool === 'eraser' ? 'Eraser stroke' : tool === 'shape' ? 'Draw shape' : 'Brush stroke';+export const strokeCommitLabel = (tool: StrokeCommittedEvent['tool']): string => STROKE_COMMIT_LABELS[tool];export interface StrokeEdits {/**diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/dragRect.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/dragRect.test.tsnew file mode 100644index 0000000000..239aad38cc--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/dragRect.test.ts@@ -0,0 +1,56 @@+import { describe, expect, it } from 'vitest';++import { dragRect } from './dragRect';++describe('dragRect', () => {+ const plain = { fromCenter: false, square: false };++ it('normalizes a drag in any direction', () => {+ expect(dragRect({ x: 10, y: 10 }, { x: 40, y: 30 }, plain)).toEqual({ height: 20, width: 30, x: 10, y: 10 });+ // Dragging up and to the left produces the same rect.+ expect(dragRect({ x: 40, y: 30 }, { x: 10, y: 10 }, plain)).toEqual({ height: 20, width: 30, x: 10, y: 10 });+ });++ it('constrains to a square under shift, keeping the drag direction', () => {+ expect(dragRect({ x: 0, y: 0 }, { x: 30, y: 10 }, { fromCenter: false, square: true })).toEqual({+ height: 30,+ width: 30,+ x: 0,+ y: 0,+ });+ // Up-left: the square grows away from the press point on both axes.+ expect(dragRect({ x: 50, y: 50 }, { x: 20, y: 40 }, { fromCenter: false, square: true })).toEqual({+ height: 30,+ width: 30,+ x: 20,+ y: 20,+ });+ });++ it('treats the press point as the centre under alt, doubling the extent', () => {+ expect(dragRect({ x: 50, y: 50 }, { x: 60, y: 70 }, { fromCenter: true, square: false })).toEqual({+ height: 40,+ width: 20,+ x: 40,+ y: 30,+ });+ });++ it('composes shift and alt into a square centred on the press point', () => {+ expect(dragRect({ x: 50, y: 50 }, { x: 60, y: 70 }, { fromCenter: true, square: true })).toEqual({+ height: 40,+ width: 40,+ x: 30,+ y: 30,+ });+ });++ it('rounds to whole pixels', () => {+ expect(dragRect({ x: 10.4, y: 10.6 }, { x: 20.4, y: 20.6 }, plain)).toEqual({+ height: 10,+ width: 10,+ x: 10,+ y: 11,+ });+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/dragRect.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/dragRect.tsnew file mode 100644index 0000000000..d18b5f30ef--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/dragRect.ts@@ -0,0 +1,37 @@+/** Rect drags shared by the marquee and shape tools: Shift squares the rect, Alt grows it from the press point. */++import type { Rect, Vec2 } from '@workbench/canvas-engine/types';++/** How the drag modifiers shape the rect. */+export interface DragRectConstraints {+ /** Equal width and height. */+ square: boolean;+ /** The press point is the rect's centre rather than a corner. */+ fromCenter: boolean;+}++/** The drag delta, optionally forced to equal magnitude on both axes (sign kept). */+const constrainedDelta = (start: Vec2, end: Vec2, square: boolean): Vec2 => {+ const dx = end.x - start.x;+ const dy = end.y - start.y;+ if (!square) {+ return { x: dx, y: dy };+ }+ const side = Math.max(Math.abs(dx), Math.abs(dy));+ return { x: (dx < 0 ? -1 : 1) * side, y: (dy < 0 ? -1 : 1) * side };+};++/** Normalized integer bounds of a drag; centered mode mirrors the constrained delta around the press point. */+export const dragRect = (start: Vec2, end: Vec2, constraints: DragRectConstraints): Rect => {+ const delta = constrainedDelta(start, end, constraints.square);+ const a = constraints.fromCenter ? { x: start.x - delta.x, y: start.y - delta.y } : start;+ const b = { x: start.x + delta.x, y: start.y + delta.y };+ const left = Math.round(Math.min(a.x, b.x));+ const top = Math.round(Math.min(a.y, b.y));+ return {+ height: Math.round(Math.max(a.y, b.y)) - top,+ width: Math.round(Math.max(a.x, b.x)) - left,+ x: left,+ y: top,+ };+};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.tsindex 125020788d..51b6bb2ca6 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.ts@@ -82,10 +82,12 @@ export const createGradientTool = (): Tool => {clearPreview(ctx);},onKeyCommand: (ctx, command) => {- if (command === 'cancel' && state) {- state = null;- clearPreview(ctx);+ if (command !== 'cancel' || !state) {+ return false;}+ state = null;+ clearPreview(ctx);+ return true;},onPointerCancel: (ctx) => {state = null;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.tsindex b38329e7a3..09ed9595c8 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.ts@@ -109,18 +109,21 @@ export const createLassoTool = (): Tool => {},onKeyCommand: (ctx, command) => {if (!session) {- return;+ return false;}if (command === 'cancel') {+ // Drops the outline only; the committed selection stays.reset();clearPreview(ctx);- return;+ return true;}- if (session.kind === 'polygon') {- // Enter closes the polygon. No modifiers are in play on a key command,- // so the persistent op mode applies.- closePolygon(ctx, session, { alt: false, shift: false });+ if (session.kind !== 'polygon') {+ return false;}+ // Enter closes the polygon. No modifiers are in play on a key command,+ // so the persistent op mode applies.+ closePolygon(ctx, session, { alt: false, shift: false });+ return true;},onPointerCancel: (ctx) => {reset();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/marqueeTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/marqueeTool.test.tsindex 5becc1d459..6391946b2f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/marqueeTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/marqueeTool.test.ts@@ -4,7 +4,7 @@ import type { PointerInput } from '@workbench/canvas-engine/types';import { createEngineStores } from '@workbench/canvas-engine/engineStores';import { ellipsePathData, rectPathData } from '@workbench/canvas-engine/selection/selectionPaths';-import { createMarqueeTool, marqueeRect } from '@workbench/canvas-engine/tools/marqueeTool';+import { createMarqueeTool } from '@workbench/canvas-engine/tools/marqueeTool';import { describe, expect, it, vi } from 'vitest';const pointer = (@@ -45,59 +45,6 @@ const drag = (tool: Tool, ctx: ToolContext, from: PointerInput, to: PointerInputup(tool, ctx, to);};-describe('marqueeRect', () => {- const plain = { fromCenter: false, square: false };-- it('normalizes a drag in any direction', () => {- expect(marqueeRect({ x: 10, y: 10 }, { x: 40, y: 30 }, plain)).toEqual({ height: 20, width: 30, x: 10, y: 10 });- // Dragging up and to the left produces the same rect.- expect(marqueeRect({ x: 40, y: 30 }, { x: 10, y: 10 }, plain)).toEqual({ height: 20, width: 30, x: 10, y: 10 });- });-- it('constrains to a square under shift, keeping the drag direction', () => {- expect(marqueeRect({ x: 0, y: 0 }, { x: 30, y: 10 }, { fromCenter: false, square: true })).toEqual({- height: 30,- width: 30,- x: 0,- y: 0,- });- // Up-left: the square grows away from the press point on both axes.- expect(marqueeRect({ x: 50, y: 50 }, { x: 20, y: 40 }, { fromCenter: false, square: true })).toEqual({- height: 30,- width: 30,- x: 20,- y: 20,- });- });-- it('treats the press point as the centre under alt, doubling the extent', () => {- expect(marqueeRect({ x: 50, y: 50 }, { x: 60, y: 70 }, { fromCenter: true, square: false })).toEqual({- height: 40,- width: 20,- x: 40,- y: 30,- });- });-- it('composes shift and alt into a square centred on the press point', () => {- expect(marqueeRect({ x: 50, y: 50 }, { x: 60, y: 70 }, { fromCenter: true, square: true })).toEqual({- height: 40,- width: 40,- x: 30,- y: 30,- });- });-- it('rounds to whole pixels', () => {- expect(marqueeRect({ x: 10.4, y: 10.6 }, { x: 20.4, y: 20.6 }, plain)).toEqual({- height: 10,- width: 10,- x: 10,- y: 11,- });- });-});-describe('marqueeTool: drag → commit', () => {it('commits a rect path with the persistent op mode', () => {const h = createHarness();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/marqueeTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/marqueeTool.tsindex d06f8be2ac..32df689d16 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/marqueeTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/marqueeTool.ts@@ -4,13 +4,15 @@* Degenerate/cancelled drags do not commit; engine selection history records accepted changes.*/-import type { Rect, Vec2 } from '@workbench/canvas-engine/types';+import type { Vec2 } from '@workbench/canvas-engine/types';import { selectionOpFor } from '@workbench/canvas-engine/selection/selectionOpMode';import { selectionShapePathData } from '@workbench/canvas-engine/selection/selectionPaths';import type { Tool, ToolContext } from './tool';+import { dragRect, type DragRectConstraints } from './dragRect';+/** Bit for the primary (usually left) mouse button in `PointerEvent.buttons`. */const PRIMARY_BUTTON = 1;@@ -30,42 +32,8 @@ interface GestureState {released: { shift: boolean; alt: boolean };}-/** How the drag modifiers shape the rect. */-export interface MarqueeConstraints {- /** Equal width and height (shift). */- square: boolean;- /** The press point is the rect's centre rather than a corner (alt). */- fromCenter: boolean;-}--/** The drag delta, optionally forced to equal magnitude on both axes (sign kept). */-const constrainedDelta = (start: Vec2, end: Vec2, square: boolean): Vec2 => {- const dx = end.x - start.x;- const dy = end.y - start.y;- if (!square) {- return { x: dx, y: dy };- }- const side = Math.max(Math.abs(dx), Math.abs(dy));- return { x: (dx < 0 ? -1 : 1) * side, y: (dy < 0 ? -1 : 1) * side };-};--/** Normalized integer marquee bounds; centered mode mirrors the constrained delta around the press point. */-export const marqueeRect = (start: Vec2, end: Vec2, constraints: MarqueeConstraints): Rect => {- const delta = constrainedDelta(start, end, constraints.square);- const a = constraints.fromCenter ? { x: start.x - delta.x, y: start.y - delta.y } : start;- const b = { x: start.x + delta.x, y: start.y + delta.y };- const left = Math.round(Math.min(a.x, b.x));- const top = Math.round(Math.min(a.y, b.y));- return {- height: Math.round(Math.max(a.y, b.y)) - top,- width: Math.round(Math.max(a.x, b.x)) - left,- x: left,- y: top,- };-};-/** The shaping constraints: a key still held since it chose the op at the press does not also shape. */-const constraintsFor = (modifiers: { shift: boolean; alt: boolean }, state: GestureState): MarqueeConstraints => {+const constraintsFor = (modifiers: { shift: boolean; alt: boolean }, state: GestureState): DragRectConstraints => {if (state.opModifiers.shift && !modifiers.shift) {state.released.shift = true;}@@ -100,10 +68,12 @@ export const createMarqueeTool = (): Tool => {clearPreview(ctx);},onKeyCommand: (ctx, command) => {- if (command === 'cancel' && state) {- end();- clearPreview(ctx);+ if (command !== 'cancel' || !state) {+ return false;}+ end();+ clearPreview(ctx);+ return true;},onPointerCancel: (ctx) => {end();@@ -133,7 +103,7 @@ export const createMarqueeTool = (): Tool => {}state.moved = true;}- const rect = marqueeRect(state.startDoc, input.documentPoint, constraintsFor(input.modifiers, state));+ const rect = dragRect(state.startDoc, input.documentPoint, constraintsFor(input.modifiers, state));ctx.stores.marqueePreview.set({ kind: ctx.stores.marqueeOptions.get().kind, rect });ctx.invalidate({ overlay: true });},@@ -148,7 +118,7 @@ export const createMarqueeTool = (): Tool => {if (!current.moved || !ctx.commitSelection) {return;}- const rect = marqueeRect(current.startDoc, input.documentPoint, constraintsFor(input.modifiers, current));+ const rect = dragRect(current.startDoc, input.documentPoint, constraintsFor(input.modifiers, current));if (rect.width < 1 || rect.height < 1) {// Degenerate drag: selecting nothing would silently wipe the selection// under `replace`, so treat it as a no-op instead.diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.tsindex 3b27097f30..e309ac35a7 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.ts@@ -214,9 +214,11 @@ export const createMoveTool = (): Tool => {},onKeyCommand: (ctx, command) => {// Enter commits the float; engine Escape abandons it regardless of active tool.- if (command === 'apply' && !state) {- ctx.commitFloatingSelection?.();+ if (command !== 'apply' || state || !ctx.getFloatingSelection?.()) {+ return false;}+ ctx.commitFloatingSelection?.();+ return true;},onPointerCancel: (ctx) => {if (state?.mode.kind === 'float') {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTarget.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTarget.tsnew file mode 100644index 0000000000..57b6581b30--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTarget.ts@@ -0,0 +1,23 @@+/**+ * Which layers take a finished shape as pixels. A leaf module, so the properties pane can ask without loading the+ * shape tool or its rasterizer.+ */++import type { CanvasLayerContract, CanvasLayerSourceContract } from '@workbench/canvas-engine/contracts';++import { maskAsPaintSource } from '@workbench/canvas-engine/document/sources';++/**+ * The paint pixels a shape draws into or cuts out of: a raster paint layer's source, or a mask's alpha viewed as+ * paint. Null for every other layer, which a drawn shape lands beside as a new shape layer instead.+ */+export const shapePaintSourceOf = (+ layer: CanvasLayerContract+): Extract<CanvasLayerSourceContract, { type: 'paint' }> | null =>+ layer.type === 'raster' && layer.source.type === 'paint' ? layer.source : maskAsPaintSource(layer);++/**+ * Whether the shape tool draws onto `layer` itself (as paint pixels or mask coverage) when it is the selected layer,+ * whatever its locks or visibility: those refuse the shape rather than redirect it.+ */+export const shapeDrawsOnLayer = (layer: CanvasLayerContract): boolean => shapePaintSourceOf(layer) !== null;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.browser.test.tsindex 702b7c76a8..67fd99e006 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.browser.test.ts@@ -14,18 +14,21 @@ import { describe, expect, it, vi } from 'vitest';import { createShapeTool } from './shapeTool';-const pointer = (x: number, y: number, timeStamp = 0): PointerInput => ({+const pointer = (x: number, y: number, timeStamp = 0, ctrl = false): PointerInput => ({buttons: 1,documentPoint: { x, y },- modifiers: { alt: false, ctrl: false, meta: false, shift: false },+ modifiers: { alt: false, ctrl, meta: false, shift: false },pointerType: 'mouse',pressure: 0.5,screenPoint: { x, y },timeStamp,});-/** Draws `kind` over document 20..80 × 20..60 (the polygon and freehand trace its right triangle). */-const draw = (tool: Tool, ctx: ToolContext, kind: ShapeToolKind): void => {+/**+ * Draws `kind` over document 20..80 × 20..60 (the polygon and freehand trace its right triangle). A cutout holds Ctrl+ * on the commit: the release, or the polygon's closing press on its first vertex.+ */+const draw = (tool: Tool, ctx: ToolContext, kind: ShapeToolKind, cutout = false): void => {if (kind === 'polygon') {for (const [x, y, t] of [[20, 20, 0],@@ -35,21 +38,33 @@ const draw = (tool: Tool, ctx: ToolContext, kind: ShapeToolKind): void => {tool.onPointerDown?.(ctx, pointer(x, y, t));tool.onPointerUp?.(ctx, pointer(x, y, t));}- tool.onKeyCommand?.(ctx, 'apply');+ tool.onPointerDown?.(ctx, pointer(20, 20, 3000, cutout));+ tool.onPointerUp?.(ctx, pointer(20, 20, 3000, cutout));return;}tool.onPointerDown?.(ctx, pointer(20, 20));for (const point of [pointer(80, 20), pointer(80, 60)]) {tool.onPointerMove?.(ctx, point, [point]);}- tool.onPointerUp?.(ctx, pointer(80, 60));+ tool.onPointerUp?.(ctx, pointer(80, 60, 0, cutout));};-const paintMask = (mask: CanvasLayerContract, kind: ShapeToolKind) => {+/** Draws (or with `cutout`, cuts) `kind` on the selected `layer`, whose cache starts as `prefill` when given. */+const drawOn = (+ layer: CanvasLayerContract,+ kind: ShapeToolKind,+ { cutout = false, prefill, strokeOnly = false }: { cutout?: boolean; prefill?: string; strokeOnly?: boolean } = {}+) => {const backend = createDomRasterBackend();const layers = createLayerCacheStore(backend);+ if (prefill) {+ const entry = layers.getOrCreateRect(layer.id, { height: 100, width: 100, x: 0, y: 0 });+ entry.stale = false;+ entry.surface.ctx.fillStyle = prefill;+ entry.surface.ctx.fillRect(0, 0, 100, 100);+ }const stores = createEngineStores();- stores.shapeOptions.set({ ...stores.shapeOptions.get(), kind });+ stores.shapeOptions.set({ ...stores.shapeOptions.get(), fillEnabled: !strokeOnly, kind, strokeEnabled: strokeOnly });// A translucent foreground must still paint full coverage.stores.colorPair.set({ background: '#000000', foreground: '#ff000040' });const strokeEdit = createRecordingStrokeEdit();@@ -65,7 +80,7 @@ const paintMask = (mask: CanvasLayerContract, kind: ShapeToolKind) => {createLayerId: () => 'created',createPath2D: (d) => new Path2D(d),dispatch: vi.fn(),- getDocument: () => documentFrom([mask], mask.id),+ getDocument: () => documentFrom([layer], layer.id),invalidate: vi.fn(),layers,notifyLayerPainted: vi.fn(),@@ -76,9 +91,10 @@ const paintMask = (mask: CanvasLayerContract, kind: ShapeToolKind) => {updateCursor: vi.fn(),viewport: { documentToScreen: (p: { x: number; y: number }) => p } as unknown as Viewport,};- draw(createShapeTool(), ctx, kind);- const entry = layers.get(mask.id);- /** The mask's alpha at a layer-local pixel, or 0 outside its cache. */+ // Off macOS, Ctrl is the cutout key.+ draw(createShapeTool({ isMacOs: false }), ctx, kind, cutout);+ const entry = layers.get(layer.id);+ /** The layer's alpha at a layer-local pixel, or 0 outside its cache. */const alphaAt = (x: number, y: number): number => {if (!entry || x < entry.rect.x || y < entry.rect.y) {return 0;@@ -93,7 +109,7 @@ describe('shape tool on a mask in Chromium', () => {it.each(['rect', 'ellipse', 'polygon', 'freehand'] as const)('covers a %s with opaque mask alpha inside the shape and nothing outside it',(kind) => {- const { addedLayers, alphaAt, strokeEdit } = paintMask(layerContract('mask', 'inpaint_mask'), kind);+ const { addedLayers, alphaAt, strokeEdit } = drawOn(layerContract('mask', 'inpaint_mask'), kind);expect(addedLayers).toHaveLength(0);expect(strokeEdit.record.commits).toHaveLength(1);@@ -109,11 +125,19 @@ describe('shape tool on a mask in Chromium', () => {});+ it('paints an inside stroke without filling the mask interior', () => {+ const { alphaAt, strokeEdit } = drawOn(layerContract('mask', 'inpaint_mask'), 'rect', { strokeOnly: true });+ expect(alphaAt(22, 40)).toBe(255);+ expect(alphaAt(50, 40)).toBe(0);+ expect(alphaAt(19, 40)).toBe(0);+ expect(strokeEdit.record.commits).toHaveLength(1);+ });+it('lands coverage under the cursor on a moved and scaled regional mask', () => {const mask = layerContract('region', 'regional_guidance', {transform: { rotation: 0, scaleX: 2, scaleY: 2, x: 10, y: 10 },});- const { alphaAt } = paintMask(mask, 'rect');+ const { alphaAt } = drawOn(mask, 'rect');// Document (72, 40) is local ((72 - 10) / 2, (40 - 10) / 2) = (31, 15).expect(alphaAt(31, 15)).toBe(255);@@ -121,3 +145,45 @@ describe('shape tool on a mask in Chromium', () => {expect(alphaAt(40, 15)).toBe(0);});});++describe('shape cutout in Chromium', () => {+ it.each([+ ['paint layer', 'raster', 'rect'],+ ['paint layer', 'raster', 'polygon'],+ ['mask', 'inpaint_mask', 'ellipse'],+ ['mask', 'regional_guidance', 'freehand'],+ ] as const)('clears a %s (%s) inside a %s and keeps every pixel outside it', (_label, type, kind) => {+ const { addedLayers, alphaAt, strokeEdit } = drawOn(layerContract('target', type), kind, {+ cutout: true,+ prefill: '#336699',+ });++ expect(addedLayers).toHaveLength(0);+ expect(strokeEdit.record.commits).toHaveLength(1);+ const event = strokeEdit.record.commits[0]!;+ expect(event.tool).toBe('shape-cutout');+ // The before image is the undo: the pixels the cutout removed, still opaque there.+ expect(event.beforeImageData.data[3]).toBe(255);+ expect(alphaAt(72, 40)).toBe(0);+ expect(alphaAt(90, 40)).toBe(255);+ expect(alphaAt(10, 10)).toBe(255);+ if (kind === 'polygon' || kind === 'freehand') {+ expect(alphaAt(25, 55)).toBe(255);+ } else {+ expect(alphaAt(50, 40)).toBe(0);+ }+ });++ it('cuts only the inside polygon outline and leaves its hollow interior intact', () => {+ const { alphaAt, strokeEdit } = drawOn(layerContract('paint', 'raster'), 'polygon', {+ cutout: true,+ prefill: '#336699',+ strokeOnly: true,+ });+ expect(alphaAt(76, 35)).toBe(0);+ expect(alphaAt(65, 30)).toBe(255);+ expect(alphaAt(25, 55)).toBe(255);+ expect(strokeEdit.record.commits).toHaveLength(1);+ expect(strokeEdit.record.commits[0]?.tool).toBe('shape-cutout');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.test.tsindex ad52cbf67d..f53ea42861 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.test.ts@@ -1,3 +1,4 @@+import type { CanvasEditRefusal } from '@workbench/canvas-engine/capabilities';import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { ShapeToolKind } from '@workbench/canvas-engine/engineStores';import type { Tool, ToolContext } from '@workbench/canvas-engine/tools/tool';@@ -17,7 +18,7 @@ import { createTestStubRasterBackend, type StubRasterSurface } from '@workbench/import { createRecordingStrokeEdit } from '@workbench/canvas-engine/tools/strokeEdit.testStub';import { describe, expect, it, vi } from 'vitest';-import { createShapeTool, polygonShapeFrom, rectFromDrag } from './shapeTool';+import { createShapeTool, polygonShapeFrom } from './shapeTool';const paintLayer = (over: Partial<CanvasLayerContract> = {}): CanvasLayerContract =>({@@ -51,11 +52,11 @@ const identityViewport = {const pointer = (x: number,y: number,- opts: { shift?: boolean; buttons?: number; timeStamp?: number } = {}+ opts: { shift?: boolean; alt?: boolean; ctrl?: boolean; meta?: boolean; buttons?: number; timeStamp?: number } = {}): PointerInput => ({buttons: opts.buttons ?? 1,documentPoint: { x, y },- modifiers: { alt: false, ctrl: false, meta: false, shift: opts.shift ?? false },+ modifiers: { alt: opts.alt ?? false, ctrl: opts.ctrl ?? false, meta: opts.meta ?? false, shift: opts.shift ?? false },pointerType: 'mouse',pressure: 0.5,screenPoint: { x, y },@@ -85,6 +86,7 @@ const createHarness = (doc: CanvasDocumentContractV3) => {},};const layers = createLayerCacheStore(backend);+ const refusals: CanvasEditRefusal[] = [];let idCounter = 0;const ctx: ToolContext = {scheduleFrame: () => () => undefined,@@ -102,6 +104,7 @@ const createHarness = (doc: CanvasDocumentContractV3) => {invalidate: vi.fn(),layers,notifyLayerPainted: vi.fn(),+ reportEditRefusal: (refusal) => refusals.push(refusal),setLayerTransformOverride: vi.fn(),setOverlayCursor: vi.fn(),stores,@@ -110,6 +113,7 @@ const createHarness = (doc: CanvasDocumentContractV3) => {};return {commits,+ refusals,ctx,dispatched,layers,@@ -129,28 +133,6 @@ const down = (t: Tool, ctx: ToolContext, i: PointerInput): void => t.onPointerDoconst move = (t: Tool, ctx: ToolContext, i: PointerInput): void => t.onPointerMove?.(ctx, i, [i]);const up = (t: Tool, ctx: ToolContext, i: PointerInput): void => t.onPointerUp?.(ctx, i);-describe('rectFromDrag', () => {- it('normalizes a drag to a positive integer rect', () => {- expect(rectFromDrag({ x: 50, y: 60 }, { x: 20, y: 100 }, false)).toEqual({- height: 40,- width: 30,- x: 20,- y: 60,- });- });-- it('constrains to a square using the larger dimension, preserving direction', () => {- expect(rectFromDrag({ x: 0, y: 0 }, { x: 30, y: 80 }, true)).toEqual({ height: 80, width: 80, x: 0, y: 0 });- // Dragging up-left: the square extends toward negative both axes.- expect(rectFromDrag({ x: 100, y: 100 }, { x: 70, y: 20 }, true)).toEqual({- height: 80,- width: 80,- x: 20,- y: 20,- });- });-});-describe('shape tool: creation', () => {it('previews on move then commits ONE addCanvasLayer on up', () => {const h = createHarness(makeDoc());@@ -234,6 +216,21 @@ describe('shape tool: creation', () => {}});+ it.each(['busy', 'not-ready', 'over-budget'] as const)(+ 'says why the release added no layer when the document refuses it as %s',+ (status) => {+ const h = createHarness(makeDoc());+ h.ctx.commitStructural = () => ({ status });+ const tool = createShapeTool();++ down(tool, h.ctx, pointer(10, 10));+ move(tool, h.ctx, pointer(70, 50));+ up(tool, h.ctx, pointer(70, 50));++ expect(h.refusals).toEqual([status]);+ }+ );+it('commits nothing for a zero-area drag', () => {const h = createHarness(makeDoc());const tool = createShapeTool();@@ -380,12 +377,110 @@ describe('shape tool: polygon and freehand kinds', () => {move(tool, h.ctx, pointer(13, 12));expect(h.stores.lassoPreview.get()).toMatchObject({ closeArmed: true, kind: 'polygon' });expect(tool.cursor?.(h.ctx)).toBe('pointer');- click(tool, h.ctx, 13, 12, 3000);+ // The closing press only arms the close: the commit waits for its release, outside the gesture.+ down(tool, h.ctx, pointer(13, 12, { timeStamp: 3000 }));+ expect(h.commits).toHaveLength(0);+ up(tool, h.ctx, pointer(13, 12, { timeStamp: 3000 }));expect(h.commits).toHaveLength(1);expect(h.stores.lassoPreview.get()).toBeNull();});+ it('closes on the release of a double-click, and a cancelled closing press closes nothing', () => {+ const h = createHarness(makeDoc());+ h.stores.shapeOptions.set({ ...h.stores.shapeOptions.get(), kind: 'polygon' });+ const tool = createShapeTool();++ click(tool, h.ctx, 10, 10, 0);+ click(tool, h.ctx, 50, 10, 1000);+ click(tool, h.ctx, 50, 40, 2000);+ down(tool, h.ctx, pointer(50, 40, { timeStamp: 2100 }));+ tool.onPointerCancel?.(h.ctx);+ up(tool, h.ctx, pointer(50, 40, { timeStamp: 2100 }));+ expect(h.commits).toHaveLength(0);+ expect(h.stores.lassoPreview.get()).toBeNull();++ click(tool, h.ctx, 10, 10, 3000);+ click(tool, h.ctx, 50, 10, 4000);+ click(tool, h.ctx, 50, 40, 5000);+ down(tool, h.ctx, pointer(50, 40, { timeStamp: 5100 }));+ expect(h.commits).toHaveLength(0);+ up(tool, h.ctx, pointer(50, 40, { timeStamp: 5100 }));+ expect(h.commits).toHaveLength(1);+ expect(h.commits[0]?.forward).toMatchObject({ layer: { source: { kind: 'polygon', width: 40 } } });+ });++ it('closes on the release when Enter comes during a held press', () => {+ const h = createHarness(makeDoc());+ h.stores.shapeOptions.set({ ...h.stores.shapeOptions.get(), kind: 'polygon' });+ const tool = createShapeTool();++ click(tool, h.ctx, 10, 10, 0);+ click(tool, h.ctx, 50, 10, 1000);+ down(tool, h.ctx, pointer(50, 40, { timeStamp: 2000 }));+ tool.onKeyCommand?.(h.ctx, 'apply');+ expect(h.commits).toHaveLength(0);+ up(tool, h.ctx, pointer(50, 40, { timeStamp: 2000 }));++ expect(h.commits).toHaveLength(1);+ expect(h.commits[0]?.forward).toMatchObject({ layer: { source: { height: 30, kind: 'polygon', width: 40 } } });+ });++ it('keeps the vertices when the closing press is refused, so the polygon can close once the layer is fixed', () => {+ let doc = makeDoc({ stacks: stacksFrom([paintLayer({ isLocked: true })]), selectedLayerId: 'paint-1' });+ const h = createHarness(doc);+ h.ctx.getDocument = () => doc;+ h.stores.shapeOptions.set({ ...h.stores.shapeOptions.get(), kind: 'polygon' });+ const tool = createShapeTool();+ doc = makeDoc({ stacks: stacksFrom([paintLayer()]), selectedLayerId: 'paint-1' });+ click(tool, h.ctx, 10, 10, 0);+ click(tool, h.ctx, 50, 10, 1000);+ click(tool, h.ctx, 50, 40, 2000);++ doc = makeDoc({ stacks: stacksFrom([paintLayer({ isLocked: true })]), selectedLayerId: 'paint-1' });+ click(tool, h.ctx, 10, 10, 3000);+ expect(h.refusals).toEqual([expect.objectContaining({ status: 'layer-locked' })]);+ expect(h.stores.lassoPreview.get()).toMatchObject({ points: [{}, {}, {}] });++ doc = makeDoc({ stacks: stacksFrom([paintLayer()]), selectedLayerId: 'paint-1' });+ click(tool, h.ctx, 10, 10, 4000);+ expect(h.strokeEdit.record.commits).toHaveLength(1);+ });++ it.each([+ ['Enter', false],+ ['Enter during a held press', true],+ ])('keeps the vertices when a close by %s is refused, closing once the layer is fixed', (_label, held) => {+ let doc = makeDoc({ stacks: stacksFrom([paintLayer()]), selectedLayerId: 'paint-1' });+ const h = createHarness(doc);+ h.ctx.getDocument = () => doc;+ h.stores.shapeOptions.set({ ...h.stores.shapeOptions.get(), kind: 'polygon' });+ const tool = createShapeTool();+ click(tool, h.ctx, 10, 10, 0);+ click(tool, h.ctx, 50, 10, 1000);+ click(tool, h.ctx, 50, 40, 2000);+ /** Enter, alone or between a later press and its release (that press placing a fourth vertex). */+ const enter = (timeStamp: number) => {+ if (held) {+ down(tool, h.ctx, pointer(30, 60, { timeStamp }));+ }+ tool.onKeyCommand?.(h.ctx, 'apply');+ if (held) {+ up(tool, h.ctx, pointer(30, 60, { timeStamp }));+ }+ };++ doc = makeDoc({ stacks: stacksFrom([paintLayer({ isLocked: true })]), selectedLayerId: 'paint-1' });+ enter(3000);+ expect(h.refusals).toEqual([expect.objectContaining({ status: 'layer-locked' })]);+ expect(h.stores.lassoPreview.get()).toMatchObject({ kind: 'polygon' });++ doc = makeDoc({ stacks: stacksFrom([paintLayer()]), selectedLayerId: 'paint-1' });+ tool.onKeyCommand?.(h.ctx, 'apply');+ expect(h.strokeEdit.record.commits).toHaveLength(1);+ expect(h.stores.lassoPreview.get()).toBeNull();+ });+it('drops an open polygon when the kind changes mid-session', () => {const h = createHarness(makeDoc());h.stores.shapeOptions.set({ ...h.stores.shapeOptions.get(), kind: 'polygon' });@@ -517,11 +612,31 @@ describe('shape tool: placement', () => {const tool = createShapeTool();down(tool, h.ctx, pointer(10, 10));+ // Said at the press, before anything is drawn; the refused press starts no preview.+ expect(h.refusals).toEqual([{ layerId: 'paint-1', layerName: 'Paint', status: 'layer-locked' }]);move(tool, h.ctx, pointer(70, 50));+ expect(h.previewOf()).toBeNull();up(tool, h.ctx, pointer(70, 50));expect(h.strokeEdit.record.commits).toHaveLength(0);expect(h.commits).toHaveLength(0);+ expect(h.refusals).toHaveLength(1);+ });++ it('says why the shape placed nothing when its layer is locked mid-drag', () => {+ let doc = makeDoc({ stacks: stacksFrom([paintLayer()]), selectedLayerId: 'paint-1' });+ const h = createHarness(doc);+ h.ctx.getDocument = () => doc;+ const tool = createShapeTool();++ down(tool, h.ctx, pointer(10, 10));+ move(tool, h.ctx, pointer(70, 50));+ doc = makeDoc({ stacks: stacksFrom([paintLayer({ isLocked: true })]), selectedLayerId: 'paint-1' });+ up(tool, h.ctx, pointer(70, 50));++ expect(h.refusals).toEqual([{ layerId: 'paint-1', layerName: 'Paint', status: 'layer-locked' }]);+ expect(h.strokeEdit.record.commits).toHaveLength(0);+ expect(h.commits).toHaveLength(0);});it('waits for a durable paint layer whose pixels are not cached yet', () => {@@ -531,12 +646,20 @@ describe('shape tool: placement', () => {const tool = createShapeTool();down(tool, h.ctx, pointer(10, 10));+ expect(h.ctx.requestLayerRasterization).toHaveBeenCalledWith('paint-1');+ expect(h.refusals).toEqual([{ layerId: 'paint-1', layerName: 'Paint', status: 'layer-loading' }]);move(tool, h.ctx, pointer(70, 50));up(tool, h.ctx, pointer(70, 50));- expect(h.ctx.requestLayerRasterization).toHaveBeenCalledWith('paint-1');expect(h.strokeEdit.record.commits).toHaveLength(0);expect(h.commits).toHaveLength(0);++ // Once the pixels are cached, the next press draws.+ h.layers.getOrCreateRect('paint-1', { height: 8, width: 8, x: 0, y: 0 }).stale = false;+ down(tool, h.ctx, pointer(10, 10));+ move(tool, h.ctx, pointer(70, 50));+ up(tool, h.ctx, pointer(70, 50));+ expect(h.strokeEdit.record.commits).toHaveLength(1);});it('falls back to a new shape layer when the selection is not a paint layer', () => {@@ -658,12 +781,18 @@ describe('shape tool: mask placement', () => {'a mask under a locked group',[groupContract('group-1', [layerContract('mask-1', 'regional_guidance')], { isLocked: true })],],- ])('refuses %s without spawning a layer', (_label, nodes) => {+ ])('refuses %s without spawning a layer', (label, nodes) => {const h = createHarness(makeDoc({ stacks: stacksFrom(nodes), selectedLayerId: 'mask-1' }));const tool = createShapeTool();drawKind(tool, h.ctx, 'rect');+ expect(h.refusals).toEqual([+ expect.objectContaining({+ layerId: 'mask-1',+ status: label.includes('disabled') ? 'layer-hidden' : 'layer-locked',+ }),+ ]);expect(h.strokeEdit.record.commits).toHaveLength(0);expect(h.commits).toHaveLength(0);expect(h.dispatched).toHaveLength(0);@@ -692,6 +821,7 @@ describe('shape tool: mask placement', () => {drawKind(tool, h.ctx, 'rect');expect(h.ctx.requestLayerRasterization).toHaveBeenCalledWith('mask-1');+ expect(h.refusals).toEqual([expect.objectContaining({ layerId: 'mask-1', status: 'layer-loading' })]);expect(h.strokeEdit.record.commits).toHaveLength(0);expect(h.commits).toHaveLength(0);});@@ -729,3 +859,235 @@ describe('shape tool: mask placement', () => {}});});++describe('shape tool: Alt draws from the center', () => {+ const dragWith = (modifiers: { alt?: boolean; shift?: boolean }) => {+ const h = createHarness(makeDoc());+ const tool = createShapeTool();+ down(tool, h.ctx, pointer(50, 50, modifiers));+ move(tool, h.ctx, pointer(60, 70, modifiers));+ const preview = h.previewOf();+ up(tool, h.ctx, pointer(60, 70, modifiers));+ return { forward: h.commits[0]?.forward, preview };+ };++ it('grows the box from the press point under Alt, previewing what it commits', () => {+ const { forward, preview } = dragWith({ alt: true });+ expect(preview?.rect).toEqual({ height: 40, width: 20, x: 40, y: 30 });+ expect(forward).toMatchObject({+ layer: { source: { height: 40, width: 20 }, transform: { x: 40, y: 30 } },+ type: 'addCanvasLayer',+ });+ });++ it('makes a square about the press point under Shift+Alt', () => {+ const { forward } = dragWith({ alt: true, shift: true });+ expect(forward).toMatchObject({ layer: { source: { height: 40, width: 40 }, transform: { x: 30, y: 30 } } });+ });++ it('reads Alt live: let go before the release, the box goes back to a corner drag', () => {+ const h = createHarness(makeDoc());+ const tool = createShapeTool();+ down(tool, h.ctx, pointer(50, 50, { alt: true }));+ move(tool, h.ctx, pointer(60, 70, { alt: true }));+ up(tool, h.ctx, pointer(60, 70));+ expect(h.commits[0]?.forward).toMatchObject({+ layer: { source: { height: 20, width: 10 }, transform: { x: 50, y: 50 } },+ });+ });++ it('leaves a freehand trace as drawn', () => {+ const h = createHarness(makeDoc());+ h.stores.shapeOptions.set({ ...h.stores.shapeOptions.get(), kind: 'freehand' });+ const tool = createShapeTool();+ down(tool, h.ctx, pointer(50, 50, { alt: true }));+ move(tool, h.ctx, pointer(80, 50, { alt: true }));+ up(tool, h.ctx, pointer(80, 80, { alt: true }));+ expect(h.commits[0]?.forward).toMatchObject({+ layer: { source: { height: 30, width: 30 }, transform: { x: 50, y: 50 } },+ });+ });+});++describe('shape tool: the mod key cuts the shape out', () => {+ /** Off macOS, so Ctrl is the mod key; the platform cases below cover ⌘. */+ const createTool = () => createShapeTool({ isMacOs: false });++ /** A selected layer with cached pixels over 0..100², so a cutout has something to erase. */+ const cutoutHarness = (layer: CanvasLayerContract, target: 'selected' | 'new' = 'selected') => {+ const h = createHarness(makeDoc({ stacks: stacksFrom([layer]), selectedLayerId: layer.id }));+ h.stores.shapeOptions.set({ ...h.stores.shapeOptions.get(), target });+ h.layers.getOrCreateRect(layer.id, { height: 100, width: 100, x: 0, y: 0 }).stale = false;+ return h;+ };++ /** The composite operations the tool set on the layer's own cache surface. */+ const layerComposites = (h: ReturnType<typeof createHarness>, layerId: string): unknown[] =>+ (h.layers.peek(layerId)!.surface as StubRasterSurface).callLog+ .filter((entry) => entry.op === 'set' && entry.args[0] === 'globalCompositeOperation')+ .map((entry) => entry.args[1]);++ it.each([+ ['Ctrl off macOS', false, { ctrl: true }],+ ['⌘ on macOS', true, { meta: true }],+ ])('erases from the selected paint layer with %s at the release, whatever Place on says', (_l, isMacOs, modifier) => {+ const h = cutoutHarness(paintLayer(), 'new');+ const tool = createShapeTool({ isMacOs });++ down(tool, h.ctx, pointer(10, 10));+ move(tool, h.ctx, pointer(70, 50));+ up(tool, h.ctx, pointer(70, 50, modifier));++ expect(h.commits).toHaveLength(0);+ expect(h.strokeEdit.record.commits).toHaveLength(1);+ expect(h.strokeEdit.record.commits[0]).toMatchObject({+ dirtyRect: { height: 40, width: 60, x: 10, y: 10 },+ layerId: 'paint-1',+ tool: 'shape-cutout',+ });+ expect(layerComposites(h, 'paint-1')).toContain('destination-out');+ // The footprint is opaque coverage, not the pair's colors.+ expect(h.assigned('fillStyle')).toContain('#ffffff');+ });++ it.each([+ ['Ctrl on macOS, which opens the context menu there', true, { ctrl: true }],+ ['⌘ off macOS', false, { meta: true }],+ ])('draws rather than cuts with %s', (_label, isMacOs, modifier) => {+ const h = cutoutHarness(paintLayer());+ const tool = createShapeTool({ isMacOs });++ down(tool, h.ctx, pointer(10, 10, modifier));+ move(tool, h.ctx, pointer(70, 50, modifier));+ up(tool, h.ctx, pointer(70, 50, modifier));++ expect(h.strokeEdit.record.commits[0]?.tool).toBe('shape');+ expect(tool.cursor?.(h.ctx)).toBe('crosshair');+ });++ it('erases mask coverage from a selected mask', () => {+ const h = cutoutHarness(layerContract('mask-1', 'inpaint_mask'));+ const tool = createTool();++ down(tool, h.ctx, pointer(10, 10, { ctrl: true }));+ move(tool, h.ctx, pointer(70, 50, { ctrl: true }));+ up(tool, h.ctx, pointer(70, 50, { ctrl: true }));++ expect(h.strokeEdit.record.commits[0]).toMatchObject({ layerId: 'mask-1', tool: 'shape-cutout' });+ expect(layerComposites(h, 'mask-1')).toContain('destination-out');+ expect(h.commits).toHaveLength(0);+ });++ it('erases only cached pixels, never growing the layer', () => {+ const h = createHarness(makeDoc({ stacks: stacksFrom([paintLayer()]), selectedLayerId: 'paint-1' }));+ h.layers.getOrCreateRect('paint-1', { height: 20, width: 20, x: 0, y: 0 }).stale = false;+ const tool = createTool();++ down(tool, h.ctx, pointer(10, 10));+ move(tool, h.ctx, pointer(70, 50));+ up(tool, h.ctx, pointer(70, 50, { ctrl: true }));+ expect(h.strokeEdit.record.commits[0]?.dirtyRect).toEqual({ height: 10, width: 10, x: 10, y: 10 });+ expect(h.layers.peek('paint-1')?.rect).toEqual({ height: 20, width: 20, x: 0, y: 0 });++ // A shape wholly past the pixels erases nothing and records nothing.+ down(tool, h.ctx, pointer(40, 40));+ move(tool, h.ctx, pointer(70, 70));+ up(tool, h.ctx, pointer(70, 70, { ctrl: true }));+ expect(h.strokeEdit.record.commits).toHaveLength(1);+ expect(h.refusals).toHaveLength(0);+ });++ it('clips the cutout to the selection and bbox like a shape drawn there', () => {+ const h = cutoutHarness(paintLayer());+ const selection = h.ctx.backend.createSurface(40, 40);+ h.ctx.getSelectionMask = () => ({ rect: { height: 40, width: 40, x: 0, y: 0 }, surface: selection });+ h.ctx.getStrokeClipRect = () => ({ height: 30, width: 30, x: 0, y: 0 });+ const tool = createTool();++ down(tool, h.ctx, pointer(10, 10));+ move(tool, h.ctx, pointer(70, 50));+ up(tool, h.ctx, pointer(70, 50, { ctrl: true }));++ expect(h.strokeEdit.record.commits[0]?.dirtyRect).toEqual({ height: 20, width: 20, x: 10, y: 10 });+ });++ it('cuts a click-closed polygon out under the modifiers of its closing press', () => {+ const h = cutoutHarness(paintLayer(), 'new');+ h.stores.shapeOptions.set({ ...h.stores.shapeOptions.get(), kind: 'polygon' });+ const tool = createTool();+ for (const [x, y, timeStamp] of [+ [10, 10, 0],+ [50, 10, 1000],+ [50, 40, 2000],+ ] as const) {+ down(tool, h.ctx, pointer(x, y, { timeStamp }));+ up(tool, h.ctx, pointer(x, y, { timeStamp }));+ }+ down(tool, h.ctx, pointer(10, 10, { ctrl: true, timeStamp: 3000 }));+ up(tool, h.ctx, pointer(10, 10, { timeStamp: 3000 }));++ expect(h.commits).toHaveLength(0);+ expect(h.strokeEdit.record.commits[0]).toMatchObject({ layerId: 'paint-1', tool: 'shape-cutout' });+ });++ it.each([+ ['nothing is selected', makeDoc()],+ [+ 'the selection is an image layer',+ makeDoc({+ stacks: stacksFrom([+ paintLayer({ id: 'image-1', source: { image: { height: 8, imageName: 'i', width: 8 }, type: 'image' } }),+ ]),+ selectedLayerId: 'image-1',+ }),+ ],+ ])('refuses, drawing nothing and adding no layer, when %s', (_label, doc) => {+ const h = createHarness(doc);+ const tool = createTool();++ // Known at the press: the refused press starts nothing.+ down(tool, h.ctx, pointer(10, 10, { ctrl: true }));+ expect(h.refusals).toEqual([{ status: 'cutout-no-target' }]);+ move(tool, h.ctx, pointer(70, 50, { ctrl: true }));+ up(tool, h.ctx, pointer(70, 50, { ctrl: true }));++ // Learned only at the release: the shape still places nothing.+ down(tool, h.ctx, pointer(10, 10));+ move(tool, h.ctx, pointer(70, 50));+ up(tool, h.ctx, pointer(70, 50, { ctrl: true }));++ expect(h.refusals).toEqual([{ status: 'cutout-no-target' }, { status: 'cutout-no-target' }]);+ expect(h.commits).toHaveLength(0);+ expect(h.strokeEdit.record.commits).toHaveLength(0);+ });++ it('refuses a transparency-locked paint layer like the eraser', () => {+ const h = cutoutHarness(paintLayer({ isTransparencyLocked: true } as Partial<CanvasLayerContract>));+ const tool = createTool();++ down(tool, h.ctx, pointer(10, 10));+ move(tool, h.ctx, pointer(70, 50));+ up(tool, h.ctx, pointer(70, 50, { ctrl: true }));++ expect(h.refusals).toEqual([{ layerId: 'paint-1', layerName: 'Paint', status: 'layer-alpha-locked' }]);+ expect(h.strokeEdit.record.commits).toHaveLength(0);+ });++ it('cues the cutout on the cursor while the mod key is held, and not-allowed when it would be refused', () => {+ const h = cutoutHarness(paintLayer());+ const tool = createTool();+ expect(tool.cursor?.(h.ctx)).toBe('crosshair');++ move(tool, h.ctx, pointer(10, 10, { ctrl: true }));+ expect(h.ctx.updateCursor).toHaveBeenCalledOnce();+ expect(tool.cursor?.(h.ctx)).toMatch(/^url\("data:image\/svg\+xml,.*, crosshair$/);++ move(tool, h.ctx, pointer(12, 10));+ expect(h.ctx.updateCursor).toHaveBeenCalledTimes(2);+ expect(tool.cursor?.(h.ctx)).toBe('crosshair');++ const empty = createHarness(makeDoc());+ move(tool, empty.ctx, pointer(10, 10, { ctrl: true }));+ expect(tool.cursor?.(empty.ctx)).toBe('not-allowed');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.tsindex e209e9c936..60746c3929 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.ts@@ -1,31 +1,41 @@/**- * Shapes use box drags, polygon clicks or closed freehand. Commit pixels to an eligible selected paint layer or- * mask (as opaque mask coverage) with selection/bbox clipping, otherwise create a parametric layer.- * Locked/disabled/unready paint or masks refuse. Shift constrains box aspect; previews/cancellation do not- * dispatch, and nonzero shapes produce one structural or stroke commit.+ * Shapes use box drags, polygon clicks or closed freehand. Place on = selected layer draws into a selected paint layer+ * or mask (as opaque mask coverage); any other selection, or Place on = new layer, adds a parametric shape layer.+ * Shift squares a box and Alt grows it from the press point, both read live on every move and the release, as the+ * marquee does; polygon and freehand ignore them. The platform's mod key (⌘ on macOS, where Ctrl-click opens the+ * context menu; Ctrl elsewhere) cuts the shape's opaque footprint out of the selected paint layer or mask instead,+ * whatever Place on says, and never adds a layer: the release decides for drags and traces, the closing press for a+ * click-closed polygon; Enter always draws. Pixel commits clip to the selection and bbox. Hidden, locked or loading+ * targets refuse with a notice (a cutout also refuses a transparency lock or a selection it cannot cut), at the+ * press when the press already knows, so nothing is drawn in vain; a refused polygon close, by click or Enter, keeps+ * its vertices. A new layer the document refuses (busy, not ready, over budget) is reported too.+ * Commits wait for the gesture to end, so a new layer is never refused mid-gesture: a drag or trace commits on+ * release, a polygon on Enter or on the release of the press that closes it. Escape (through the engine ladder) or a+ * cancelled press drops the session. A box or freehand gesture bound for the selected layer's pixels tells the engine+ * so as soon as its modifiers decide it, so a mask it edits shows above a staged preview; polygons never do. Previews+ * and cancellation do not dispatch, and a nonzero shape produces one structural or stroke commit.*/-import type {- CanvasLayerContract,- CanvasLayerSourceContract,- CanvasRasterLayerContractV2,-} from '@workbench/canvas-engine/contracts';+import type { CanvasLayerEditRefusal, CanvasShapeCutoutRefusal } from '@workbench/canvas-engine/capabilities';+import type { CanvasLayerSourceContract, CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';import type { SemanticLeaf } from '@workbench/canvas-engine/document-model/semanticLeaf';import type { ShapeToolOptions } from '@workbench/canvas-engine/engineStores';import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';-import type { PlacedSurface, Rect, Vec2 } from '@workbench/canvas-engine/types';+import type { PlacedSurface, PointerInput, PointerModifiers, Rect, Vec2 } from '@workbench/canvas-engine/types';import { lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';import { getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';-import { isLayerTransparencyLocked, isLeafPaintable } from '@workbench/canvas-engine/document/layerEligibility';-import { isMaskLayer, maskAsPaintSource } from '@workbench/canvas-engine/document/sources';+import { isLayerTransparencyLocked, leafEditRefusal } from '@workbench/canvas-engine/document/layerEligibility';+import { isMaskLayer } from '@workbench/canvas-engine/document/sources';import { polygonBounds } from '@workbench/canvas-engine/freehand';import { identity, invert, multiply, translate } from '@workbench/canvas-engine/math/mat2d';import { intersect, roundOut, transformBounds } from '@workbench/canvas-engine/math/rect';import { drawShapeSource } from '@workbench/canvas-engine/render/rasterizers/shapeRasterizer';+import { IS_MAC_OS } from '@workbench/hotkeys/keys';import type { Tool, ToolContext } from './tool';+import { dragRect, type DragRectConstraints } from './dragRect';import { layerMatrix } from './moveHitTest';import { MASK_PAINT_COLOR } from './paintConstants';import {@@ -40,6 +50,7 @@ import {type FreehandTrace,type PolylineSession,} from './polylineSession';+import { shapeDrawsOnLayer, shapePaintSourceOf } from './shapeTarget';type ShapeSource = Extract<CanvasLayerSourceContract, { type: 'shape' }>;@@ -49,27 +60,43 @@ const PRIMARY_BUTTON = 1;/** Screen-space distance (CSS px) the pointer must travel before a press becomes a drag. */export const SHAPE_DRAG_THRESHOLD_PX = 3;+/** Whether a finished shape adds its pixels (or a layer) or erases its footprint from the selected layer. */+type ShapeMode = 'draw' | 'cutout';++/** The platform's mod key cuts the shape out: ⌘ on macOS, where Ctrl-click opens the context menu; Ctrl elsewhere. */+const modeOf = (modifiers: PointerModifiers, isMacOs: boolean): ShapeMode =>+ (isMacOs ? modifiers.meta : modifiers.ctrl) ? 'cutout' : 'draw';++/** Shift squares a box drag and Alt centres it on the press point. */+const constraintsOf = (modifiers: PointerModifiers): DragRectConstraints => ({+ fromCenter: modifiers.alt,+ square: modifiers.shift,+});++/** Legacy's subtract cue: the crosshair with a minus badge, falling back to the plain crosshair. */+const CUTOUT_CURSOR_SVG = `<svg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'>+ <g fill='none' stroke-linecap='round'>+ <path d='M12 3v5M12 16v5M3 12h5M16 12h5' stroke='white' stroke-width='3'/>+ <path d='M12 3v5M12 16v5M3 12h5M16 12h5' stroke='black' stroke-width='1.5'/>+ <circle cx='6' cy='18' r='4.5' fill='white' stroke='black' stroke-width='1'/>+ <path d='M4 18h4' stroke='black' stroke-width='1.5'/>+ </g>+</svg>`;+type Session =- | { kind: 'drag'; startDoc: Vec2; startScreen: Vec2; moved: boolean }- | { kind: 'polyline'; session: PolylineSession }- | ({ kind: 'freehand' } & FreehandTrace);+ | { kind: 'drag'; startDoc: Vec2; startScreen: Vec2; moved: boolean; editsSelected: boolean }+ | {+ kind: 'polyline';+ session: PolylineSession;+ /** A press is down; a close it asks for waits for its release. */+ pressed: boolean;+ /** The close a press (or Enter during one) armed, committed on the release in this mode. */+ closing: ShapeMode | null;+ }+ | ({ kind: 'freehand'; editsSelected: boolean } & FreehandTrace);const distance = (a: Vec2, b: Vec2): number => Math.hypot(a.x - b.x, a.y - b.y);-/** The integer, normalized document rect for a drag from `start` to `end`, optionally square-constrained. */-export const rectFromDrag = (start: Vec2, end: Vec2, square: boolean): Rect => {- let dx = end.x - start.x;- let dy = end.y - start.y;- if (square) {- const side = Math.max(Math.abs(dx), Math.abs(dy));- dx = (dx < 0 ? -1 : 1) * side;- dy = (dy < 0 ? -1 : 1) * side;- }- const x = Math.round(Math.min(start.x, start.x + dx));- const y = Math.round(Math.min(start.y, start.y + dy));- return { height: Math.round(Math.abs(dy)), width: Math.round(Math.abs(dx)), x, y };-};-/** A shape to place: its source plus the document rect it covers. */interface PlacedShape {source: ShapeSource;@@ -103,19 +130,18 @@ export const polygonShapeFrom = (};};-/** Where a finished shape went: pixels, nothing to draw, refused by the paint layer or mask, or neither at all. */-type PixelPlacement = 'placed' | 'nothing' | 'refused' | 'unsupported';--/** The pixels a shape aimed at `layer` draws into: a paint layer's, or a mask's alpha; null for any other layer. */-const pixelTargetOf = (layer: CanvasLayerContract): Extract<CanvasLayerSourceContract, { type: 'paint' }> | null =>- layer.type === 'raster' && layer.source.type === 'paint' ? layer.source : maskAsPaintSource(layer);+/** Where a finished shape goes: a new shape layer, the selected leaf's pixels, or nowhere, with the reason. */+type ShapeTarget =+ | { kind: 'layer' }+ | { kind: 'pixels'; leaf: SemanticLeaf }+ | { kind: 'refused'; refusal: CanvasLayerEditRefusal | CanvasShapeCutoutRefusal };/** With fill off and no stroke to draw, a shape changes no pixel, so it records no step and uploads nothing. */const drawsNothing = (source: ShapeSource): boolean =>source.fill === null && (source.stroke === null || source.strokeWidth <= 0);-/** A mask takes the shape's footprint as coverage: each enabled part paints opaque, whatever its color. */-const maskCoverageOf = (source: ShapeSource): ShapeSource => ({+/** The shape's footprint as coverage: each enabled part paints opaque, whatever its color. */+const coverageOf = (source: ShapeSource): ShapeSource => ({...source,fill: source.fill === null ? null : MASK_PAINT_COLOR,stroke: source.stroke === null ? null : MASK_PAINT_COLOR,@@ -129,9 +155,43 @@ const sessionFitsKind = (session: Session, kind: ShapeToolOptions['kind']): bool? session.kind === 'freehand': session.kind === 'drag';-/** Creates a fresh shape tool with its own gesture state. */-export const createShapeTool = (): Tool => {+/**+ * Where a shape finished in `mode` would go now. A cutout needs a selected paint layer or mask; a drawn shape takes+ * one only when Place on asks for it. `loading: 'request'` also refuses a target whose durable pixels are not cached+ * yet (drawing then would lose them) and asks for them; `'skip'` predicts without side effects, for the cursor.+ */+const resolveTarget = (ctx: ToolContext, mode: ShapeMode, loading: 'request' | 'skip'): ShapeTarget => {+ const doc = ctx.getDocument();+ const leaf = doc?.selectedLayerId ? lookupDocumentLeaf(doc, doc.selectedLayerId) : null;+ if (!leaf || !shapeDrawsOnLayer(leaf.layer)) {+ return mode === 'cutout' ? { kind: 'refused', refusal: { status: 'cutout-no-target' } } : { kind: 'layer' };+ }+ if (mode === 'draw' && ctx.stores.shapeOptions.get().target !== 'selected') {+ return { kind: 'layer' };+ }+ const { layer } = leaf;+ let status: CanvasLayerEditRefusal['status'] | null = leafEditRefusal(leaf);+ if (!status && mode === 'cutout' && isLayerTransparencyLocked(layer)) {+ status = 'layer-alpha-locked';+ }+ if (!status && loading === 'request' && shapePaintSourceOf(layer)?.bitmap) {+ const existing = ctx.layers.get(layer.id);+ if (!existing || existing.stale) {+ ctx.requestLayerRasterization?.(layer.id);+ status = 'layer-loading';+ }+ }+ return status+ ? { kind: 'refused', refusal: { layerId: layer.id, layerName: layer.name, status } }+ : { kind: 'pixels', leaf };+};++/** Creates a fresh shape tool with its own gesture state; `isMacOs` picks the cutout key. */+export const createShapeTool = ({ isMacOs = IS_MAC_OS }: { isMacOs?: boolean } = {}): Tool => {let session: Session | null = null;+ /** The cutout key on the latest pointer event, which picks the cursor cue. */+ let cutoutHeld = false;+ const cutoutCursor = `url("data:image/svg+xml,${encodeURIComponent(CUTOUT_CURSOR_SVG)}") 12 12, crosshair`;const clearPreview = (ctx: ToolContext): void => {ctx.stores.shapePreview.set(null);@@ -144,6 +204,41 @@ export const createShapeTool = (): Tool => {clearPreview(ctx);};+ const noteModifiers = (ctx: ToolContext, modifiers: PointerModifiers): void => {+ const held = modeOf(modifiers, isMacOs) === 'cutout';+ if (held !== cutoutHeld) {+ cutoutHeld = held;+ ctx.updateCursor();+ }+ };++ /**+ * Tells the engine, once per box or freehand gesture, that it writes the selected layer's pixels as soon as the+ * modifiers make it so: at the press, or when the mod key turns a drag into a cutout. The engine asks+ * `editsSelectedLayer` before the press reaches the tool, too early to see its modifiers, so the tool answers here+ * instead. Polygons never count: vertex presses write nothing, and a close commits after its gesture has ended.+ */+ const noteSelectedLayerEdit = (+ ctx: ToolContext,+ gesture: Extract<Session, { editsSelected: boolean }>,+ modifiers: PointerModifiers+ ): void => {+ if (!gesture.editsSelected && resolveTarget(ctx, modeOf(modifiers, isMacOs), 'skip').kind === 'pixels') {+ gesture.editsSelected = true;+ ctx.beginSelectedLayerEdit?.();+ }+ };++ /** Reports why a press in `mode` would place nothing, so the user learns before drawing; true when refused. */+ const refusesPress = (ctx: ToolContext, mode: ShapeMode): boolean => {+ const target = resolveTarget(ctx, mode, 'request');+ if (target.kind !== 'refused') {+ return false;+ }+ ctx.reportEditRefusal?.(target.refusal);+ return true;+ };+/** The fill/stroke the next shape gets, resolved from the active pair now. */const styleFromOptions = (ctx: ToolContext): Pick<ShapeSource, 'fill' | 'stroke' | 'strokeWidth'> => {const options = ctx.stores.shapeOptions.get();@@ -156,32 +251,19 @@ export const createShapeTool = (): Tool => {};/**- * One pixel-shape stroke grows local bounds within selection/bbox clips, draws through the layer inverse and- * applies the same masks as brush painting, on paint pixels or mask alpha alike.+ * One pixel-shape stroke within selection/bbox clips, drawn through the layer inverse with the same masks as brush+ * painting, on paint pixels or mask alpha alike. A drawn shape grows the cache to cover it; a cutout erases its+ * opaque footprint from the pixels already cached and never grows it.*/- const commitPixels = (ctx: ToolContext, leaf: SemanticLeaf, placed: PlacedShape): PixelPlacement => {+ const commitPixels = (ctx: ToolContext, leaf: SemanticLeaf, placed: PlacedShape, mode: ShapeMode): void => {const layer = leaf.layer;- const paint = pixelTargetOf(layer);- if (!paint) {- return 'unsupported';- }if (drawsNothing(placed.source)) {- return 'nothing';- }- if (!isLeafPaintable(leaf)) {- return 'refused';- }- if (paint.bitmap) {- const existing = ctx.layers.get(layer.id);- if (!existing || existing.stale) {- // The durable pixels are not in the cache yet: drawing now would lose them.- ctx.requestLayerRasterization?.(layer.id);- return 'refused';- }+ return;}const toLocal = invert(layerMatrix(layer.transform));if (!toLocal) {- return 'refused';+ // A zero-scale layer has no pixels to draw into.+ return;}const clipMask: PlacedSurface | null = ctx.getSelectionMask?.() ?? null;const clipRect: Rect | null = ctx.getStrokeClipRect?.() ?? null;@@ -192,16 +274,20 @@ export const createShapeTool = (): Tool => {if (docRect && clipRect) {docRect = intersect(docRect, clipRect);}- const dirtyRect = docRect ? roundOut(transformBounds(toLocal, docRect)) : null;+ let dirtyRect = docRect ? roundOut(transformBounds(toLocal, docRect)) : null;+ const original = ctx.layers.peek(layer.id);+ if (dirtyRect && mode === 'cutout') {+ // Only cached pixels can be erased; an uncached layer has none.+ dirtyRect = original ? intersect(dirtyRect, original.rect) : null;+ }if (!dirtyRect || dirtyRect.width < 1 || dirtyRect.height < 1) {- return 'refused';+ return;}// Admitted before the first pixel changes: the before/after pair is the step's footprint.const edit = ctx.beginStrokeEdit(dirtyRect.width * dirtyRect.height * 8);if (!edit) {- return 'refused';+ return;}- const original = ctx.layers.peek(layer.id);const originalRect = original ? { ...original.rect } : null;let beforeImageData: ImageData | null = null;let sx = 0;@@ -232,7 +318,7 @@ export const createShapeTool = (): Tool => {const scratch = ctx.backend.createSurface(dirtyRect.width, dirtyRect.height);const draw = scratch.ctx;const { rect } = placed;- const source = isMaskLayer(layer) ? maskCoverageOf(placed.source) : placed.source;+ const source = mode === 'cutout' || isMaskLayer(layer) ? coverageOf(placed.source) : placed.source;const toScratch = multiply(translate(identity(), { x: -dirtyRect.x, y: -dirtyRect.y }), toLocal);draw.setTransform(toScratch.a, toScratch.b, toScratch.c, toScratch.d, toScratch.e, toScratch.f);drawShapeSource(draw, source, rect.x, rect.y, rect.width, rect.height);@@ -251,19 +337,19 @@ export const createShapeTool = (): Tool => {}surfaceCtx.save();surfaceCtx.setTransform(1, 0, 0, 1, 0, 0);- surfaceCtx.globalCompositeOperation = isLayerTransparencyLocked(layer) ? 'source-atop' : 'source-over';+ surfaceCtx.globalCompositeOperation =+ mode === 'cutout' ? 'destination-out' : isLayerTransparencyLocked(layer) ? 'source-atop' : 'source-over';surfaceCtx.drawImage(scratch.canvas, sx, sy);surfaceCtx.restore();const afterImageData = surfaceCtx.getImageData(sx, sy, dirtyRect.width, dirtyRect.height);- if (!edit.commit({ afterImageData, beforeImageData, dirtyRect, layerId: layer.id, tool: 'shape' })) {+ const tool = mode === 'cutout' ? 'shape-cutout' : 'shape';+ if (!edit.commit({ afterImageData, beforeImageData, dirtyRect, layerId: layer.id, tool })) {restore();- return 'refused';}} catch (error) {restore();throw error;}- return 'placed';};const commitLayer = (ctx: ToolContext, placed: PlacedShape): void => {@@ -289,26 +375,35 @@ export const createShapeTool = (): Tool => {type: 'addCanvasLayer',};const inverse: CanvasProjectMutation = { ids: [layerId], type: 'removeCanvasLayers' };- ctx.commitStructural('Add shape', forward, inverse);+ const { status } = ctx.commitStructural('Add shape', forward, inverse);+ // Refusals before dispatch say why the release added nothing; failures after it were reported where they arose.+ if (status === 'busy' || status === 'gesture-active' || status === 'not-ready' || status === 'over-budget') {+ ctx.reportEditRefusal?.(status);+ }};/**- * Places a finished shape on the selected paint layer or mask when asked, else on a new layer. A refused- * selected target places nothing rather than adding a layer the user did not ask for.+ * Places a finished shape in `mode` and ends the session. Called only once the gesture has ended. A refused selected+ * target places nothing, rather than adding a layer the user did not ask for, and says why; with `keepRefused` (a+ * polygon close) the session stays, so the shape can close again once the layer is fixed.*/- const commit = (ctx: ToolContext, placed: PlacedShape | null): void => {+ const commit = (ctx: ToolContext, placed: PlacedShape | null, mode: ShapeMode, keepRefused = false): void => {+ const target = placed && ctx.getDocument() ? resolveTarget(ctx, mode, 'request') : null;+ if (target?.kind === 'refused') {+ ctx.reportEditRefusal?.(target.refusal);+ if (keepRefused) {+ return;+ }+ }reset(ctx);- const doc = ctx.getDocument();- if (!placed || !doc) {+ if (!placed || !target) {return;}- if (ctx.stores.shapeOptions.get().target === 'selected') {- const leaf = doc.selectedLayerId ? lookupDocumentLeaf(doc, doc.selectedLayerId) : null;- if (leaf && commitPixels(ctx, leaf, placed) !== 'unsupported') {- return;- }+ if (target.kind === 'pixels') {+ commitPixels(ctx, target.leaf, placed, mode);+ } else if (target.kind === 'layer') {+ commitLayer(ctx, placed);}- commitLayer(ctx, placed);};const boxShape = (ctx: ToolContext, rect: Rect): PlacedShape | null => {@@ -319,70 +414,103 @@ export const createShapeTool = (): Tool => {return { rect, source: { ...styleFromOptions(ctx), height: rect.height, kind, type: 'shape', width: rect.width } };};- const closePolyline = (ctx: ToolContext, polyline: PolylineSession): void => {- commit(ctx, polygonShapeFrom(polyline.points, styleFromOptions(ctx)));+ /** Every polygon close, by click, double-click or Enter; a refused one keeps the vertices. */+ const closePolyline = (ctx: ToolContext, polyline: Extract<Session, { kind: 'polyline' }>, mode: ShapeMode): void => {+ polyline.closing = null;+ commit(ctx, polygonShapeFrom(polyline.session.points, styleFromOptions(ctx)), mode, true);+ };++ const pressPolygon = (ctx: ToolContext, input: PointerInput): void => {+ const mode = modeOf(input.modifiers, isMacOs);+ if (session?.kind !== 'polyline') {+ if (refusesPress(ctx, mode)) {+ return;+ }+ session = { closing: null, kind: 'polyline', pressed: true, session: startPolyline(input) };+ } else {+ session.pressed = true;+ if (pressPolyline(ctx, session.session, input) === 'close') {+ // A refused close keeps the vertices, so the user can fix the layer (or let go of Ctrl) and close again.+ if (!refusesPress(ctx, mode)) {+ session.closing = mode;+ }+ return;+ }+ }+ ctx.stores.lassoPreview.set(polylinePreview(session.session));+ ctx.invalidate({ overlay: true });};return {- cursor: () => (session?.kind === 'polyline' && session.session.closeArmed ? 'pointer' : 'crosshair'),- // Box and freehand drags draw into a selected paint layer or mask that accepts pixels, when aimed at the- // selection; anything else gets a new layer. A polygon's vertex presses are separate gestures that write nothing- // until it closes, so they leave a staged view alone instead of blinking.- editsSelectedLayer: (ctx) => {- const options = ctx.stores.shapeOptions.get();- if (options.target !== 'selected' || options.kind === 'polygon') {- return false;+ cursor: (ctx) => {+ if (session?.kind === 'polyline' && session.session.closeArmed) {+ return 'pointer';+ }+ const mode: ShapeMode = cutoutHeld ? 'cutout' : 'draw';+ if (resolveTarget(ctx, mode, 'skip').kind === 'refused') {+ return 'not-allowed';}- const doc = ctx.getDocument();- const leaf = doc?.selectedLayerId ? lookupDocumentLeaf(doc, doc.selectedLayerId) : null;- return !!leaf && pixelTargetOf(leaf.layer) !== null && isLeafPaintable(leaf);+ return mode === 'cutout' ? cutoutCursor : 'crosshair';},id: 'shape',+ usesAltKey: true,onDeactivate: (ctx, opts) => {// A modifier-hold switch (space → view to pan mid-polygon) keeps the session.if (!opts?.temporary) {+ cutoutHeld = false;reset(ctx);}},onKeyCommand: (ctx, command) => {if (!session) {- return;+ return false;}if (command === 'cancel') {reset(ctx);- } else if (session.kind === 'polyline') {- closePolyline(ctx, session.session);+ return true;+ }+ if (session.kind !== 'polyline') {+ return false;+ }+ if (session.pressed) {+ // Enter during a held press closes on its release, once the gesture has ended.+ session.closing ??= 'draw';+ } else {+ closePolyline(ctx, session, 'draw');}+ return true;},onPointerCancel: (ctx) => reset(ctx),onPointerDown: (ctx, input) => {if ((input.buttons & PRIMARY_BUTTON) === 0 || !ctx.getDocument()) {return;}+ noteModifiers(ctx, input.modifiers);const kind = ctx.stores.shapeOptions.get().kind;if (session && !sessionFitsKind(session, kind)) {reset(ctx);}if (kind === 'polygon') {- if (session?.kind !== 'polyline') {- session = { kind: 'polyline', session: startPolyline(input) };- } else if (pressPolyline(ctx, session.session, input) === 'close') {- closePolyline(ctx, session.session);- return;- }- ctx.stores.lassoPreview.set(polylinePreview(session.session));- ctx.invalidate({ overlay: true });+ pressPolygon(ctx, input);return;}- if (session) {+ if (session || refusesPress(ctx, modeOf(input.modifiers, isMacOs))) {return;}session =kind === 'freehand'- ? { ...startFreehandTrace(input), kind: 'freehand' }- : { kind: 'drag', moved: false, startDoc: input.documentPoint, startScreen: input.screenPoint };+ ? { ...startFreehandTrace(input), editsSelected: false, kind: 'freehand' }+ : {+ editsSelected: false,+ kind: 'drag',+ moved: false,+ startDoc: input.documentPoint,+ startScreen: input.screenPoint,+ };+ noteSelectedLayerEdit(ctx, session, input.modifiers);},onPointerMove: (ctx, input, batch) => {+ noteModifiers(ctx, input.modifiers);if (!session) {return;}@@ -399,6 +527,7 @@ export const createShapeTool = (): Tool => {ctx.invalidate({ overlay: true });return;}+ noteSelectedLayerEdit(ctx, session, input.modifiers);if (session.kind === 'freehand') {extendFreehandTrace(session, batch);ctx.stores.lassoPreview.set({ kind: 'freehand', points: session.points.slice() });@@ -414,24 +543,33 @@ export const createShapeTool = (): Tool => {session.moved = true;}if (kind !== 'polygon' && kind !== 'freehand') {- const rect = rectFromDrag(session.startDoc, input.documentPoint, input.modifiers.shift);+ const rect = dragRect(session.startDoc, input.documentPoint, constraintsOf(input.modifiers));ctx.stores.shapePreview.set({ kind, rect });ctx.invalidate({ overlay: true });}},onPointerUp: (ctx, input) => {- if (!session || session.kind === 'polyline') {+ noteModifiers(ctx, input.modifiers);+ if (!session) {+ return;+ }+ if (session.kind === 'polyline') {+ session.pressed = false;+ if (session.closing) {+ closePolyline(ctx, session, session.closing);+ }return;}+ const mode = modeOf(input.modifiers, isMacOs);if (session.kind === 'freehand') {- commit(ctx, polygonShapeFrom(finishFreehandTrace(session, input), styleFromOptions(ctx)));+ commit(ctx, polygonShapeFrom(finishFreehandTrace(session, input), styleFromOptions(ctx)), mode);return;}if (!session.moved) {reset(ctx);return;}- commit(ctx, boxShape(ctx, rectFromDrag(session.startDoc, input.documentPoint, input.modifiers.shift)));+ commit(ctx, boxShape(ctx, dragRect(session.startDoc, input.documentPoint, constraintsOf(input.modifiers))), mode);},};};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/textTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/textTool.test.tsindex 11ec21276d..b97a49bc2a 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/textTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/textTool.test.ts@@ -178,11 +178,31 @@ describe('text tool: teardown', () => {expect(h.cancelTextEdit).toHaveBeenCalledTimes(1);});- it('cancels the session on an Escape key command', () => {+ it('cancels an open session on an Escape key command, and leaves Escape to the ladder without one', () => {const h = createHarness(makeDoc());const tool = createTextTool();- tool.onKeyCommand?.(h.ctx, 'cancel');+ expect(tool.onKeyCommand?.(h.ctx, 'cancel')).toBe(false);+ expect(h.cancelTextEdit).not.toHaveBeenCalled();++ h.stores.textEditSession.set({+ id: 1,+ layerId: null,+ mode: 'create',+ source: {+ align: 'left',+ color: '#000000',+ content: '',+ fontFamily: 'Inter',+ fontSize: 20,+ fontWeight: 400,+ lineHeight: 1.2,+ type: 'text',+ },+ startSource: null,+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ });+ expect(tool.onKeyCommand?.(h.ctx, 'cancel')).toBe(true);expect(h.cancelTextEdit).toHaveBeenCalledTimes(1);// Apply is a no-op here (React owns the live content/commit).diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/textTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/textTool.tsindex 1786e23f9e..3516241a5b 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/textTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/textTool.ts@@ -75,11 +75,13 @@ export const createTextTool = (): Tool => ({ctx.cancelTextEdit?.();},onKeyCommand: (ctx, command) => {- // Direct harness cancellation is a backstop; production Escape uses the engine ladder. Apply needs portal- // content and does nothing here.- if (command === 'cancel') {- ctx.cancelTextEdit?.();+ // The engine ladder's text rung cancels an open session before the tool is asked, so this is a backstop. Apply+ // needs portal content and does nothing here.+ if (command !== 'cancel' || !ctx.stores.textEditSession.get()) {+ return false;}+ ctx.cancelTextEdit?.();+ return true;},onPointerDown: (ctx, input) => {if ((input.buttons & PRIMARY_BUTTON) === 0) {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.tsindex 7e22f9712a..23ecd9b765 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts@@ -37,8 +37,11 @@ export interface StrokeCommittedEvent {beforeImageData: ImageData;/** Cache pixels within `dirtyRect` after the stroke. */afterImageData: ImageData;- /** Which tool produced the stroke; a `shape` is one drawn as pixels onto a paint layer. */- tool: 'brush' | 'eraser' | 'shape';+ /**+ * Which tool produced the stroke; a `shape` is one drawn as pixels onto a paint layer or mask, a `shape-cutout` one+ * whose footprint was erased from it.+ */+ tool: 'brush' | 'eraser' | 'shape' | 'shape-cutout';/** Optional auto-created layer and insertion placement let stroke history remove/recreate both layer and pixels. */createdLayer?: { layer: CanvasLayerContract; anchor: CanvasNodeInsertionAnchor };}@@ -199,9 +202,10 @@ export interface ToolContext {/** True if `point` (document space) falls inside the live selection. */isPointInSelection?(point: Vec2): boolean;/**- * The gesture in progress has started editing the selected layer in place after its press, e.g. a move crossing- * its drag threshold. Answers what {@link Tool.editsSelectedLayer} would have at the press, for a tool that only- * knows later; outside a pointer gesture it does nothing.+ * The gesture in progress has started editing the selected layer in place: once its press reaches the tool (a+ * shape whose modifiers make it a cutout), or later (a move crossing its drag threshold). Answers what+ * {@link Tool.editsSelectedLayer} would have, for a tool that only knows after it was asked; outside a pointer+ * gesture it does nothing.*/beginSelectedLayerEdit?(): void;}@@ -230,24 +234,26 @@ export interface Tool {/** The active gesture was cancelled (Esc, pointercancel, focus loss). */onPointerCancel?(ctx: ToolContext): void;/**- * Optional session commands from the pipeline; tools may apply/cancel while gesture cancellation remains- * separate.+ * Session commands: `apply` from Enter on the surface, `cancel` from the engine's Escape ladder once no+ * engine-owned session (text edit, transform, float) took it. Returns whether the tool had an open session the+ * command applied or dropped: a handled cancel ends the ladder, so that Escape never also clears the selection.+ * Gesture cancellation stays separate (`onPointerCancel`) and runs first when Escape lands mid-press.*/- onKeyCommand?(ctx: ToolContext, command: 'apply' | 'cancel'): void;+ onKeyCommand?(ctx: ToolContext, command: 'apply' | 'cancel'): boolean;/** Wheel over the canvas; `screenAnchor` is the CSS-pixel cursor position. */onWheel?(ctx: ToolContext, deltaY: number, screenAnchor: { x: number; y: number }, modifiers: PointerModifiers): void;/** The CSS cursor to show while this tool is active. */cursor?(ctx: ToolContext): string;/**- * Alt is one of this tool's gesture modifiers (selection ops, grid bypass, scaling about the centre), so the- * pointer pipeline must not turn an alt-hold into the temporary color picker.+ * Alt is one of this tool's gesture modifiers (selection ops, grid bypass, scaling or drawing about the centre), so+ * the pointer pipeline must not turn an alt-hold into the temporary color picker.*/readonly usesAltKey?: boolean;/*** Whether a primary gesture starting now edits the selected layer in place, writing its pixels or its placement:* false when the press would be refused up front or would add a new layer instead. Asked once as each gesture- * starts; absent means never at the press (a tool that decides later calls- * {@link ToolContext.beginSelectedLayerEdit}). While such a gesture targets a mask or a region, the screen shows+ * starts, before the press reaches the tool; absent means not known then (a tool that decides from the press's+ * modifiers or later calls {@link ToolContext.beginSelectedLayerEdit}). While such a gesture targets a mask or a region, the screen shows* their stacks above a staged preview that otherwise hides them.*/editsSelectedLayer?(ctx: ToolContext): boolean;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.tsindex 7e6d5cd54d..c49b08f199 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.ts@@ -250,7 +250,7 @@ export const createTransformTool = (): Tool => {onKeyCommand: (ctx, command) => {if (gesture) {// Ignore apply/cancel during captured drags to avoid tearing down the still-active pointer session.- return;+ return false;}if (ctx.getFloatingSelection?.()) {if (command === 'apply') {@@ -258,13 +258,15 @@ export const createTransformTool = (): Tool => {} else {ctx.cancelFloatingSelection?.();}- return;+ return true;}+ const open = ctx.stores.transformSession.get() !== null;if (command === 'apply') {ctx.applyTransform?.();- } else {+ } else if (open) {ctx.cancelTransform?.();}+ return open;},onPointerCancel: (ctx) => {// Revert just this drag (keep the session / the float); Escape's owndiff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasEditRefusalNotices.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasEditRefusalNotices.browser.test.tsxindex 2fd9a919d6..7793112cbb 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasEditRefusalNotices.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasEditRefusalNotices.browser.test.tsx@@ -75,7 +75,7 @@ const mount = async (layers: readonly CanvasNodeContract[], selectedLayerId: str</ChakraProvider>));- const emit = (refusal: CanvasLayerEditRefusal) => act(() => listeners.forEach((listener) => listener(refusal)));+ const emit = (refusal: CanvasEditRefusal) => act(() => listeners.forEach((listener) => listener(refusal)));return { emit, stub };};@@ -90,11 +90,7 @@ describe('CanvasEditRefusalNotices', () => {it.each([['layer-hidden', '“Sky” is hidden', 'Show the layer to edit it.'],['layer-locked', '“Sky” is locked', 'Unlock the layer to edit it.'],- [- 'layer-alpha-locked',- '“Sky” has its transparency locked',- 'The eraser can’t remove pixels while transparency is locked.',- ],+ ['layer-alpha-locked', '“Sky” has its transparency locked', 'Unlock its transparency to remove pixels from it.'],['layer-loading', '“Sky” is still loading', 'Its pixels are on their way. Try again in a moment.'],] as const)('explains a %s refusal with no offer', async (status, title, message) => {const { emit } = await mount([layerContract('sky', 'raster', { name: 'Sky' })], 'sky');@@ -102,6 +98,19 @@ describe('CanvasEditRefusalNotices', () => {await expect.poll(toastTexts).toEqual([{ actions: [], message, title }]);});+ it('explains a shape cutout with nothing to cut from, once however often it is pressed', async () => {+ const { emit } = await mount([], null);+ await emit({ status: 'cutout-no-target' });+ await emit({ status: 'cutout-no-target' });+ await expect.poll(toastTexts).toEqual([+ {+ actions: [],+ message: 'Select a paint layer or mask to cut the shape out of it.',+ title: 'Nothing to cut the shape out of',+ },+ ]);+ });+it('replaces a repeated refusal without an offer, one toast per layer and reason', async () => {const { emit } = await mount([layerContract('sky', 'raster', { name: 'Sky' }), layerContract('sea', 'raster', { name: 'Sea' })],diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasEditRefusalNotices.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasEditRefusalNotices.tsxindex a6ebcf421a..d0d54fd81e 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasEditRefusalNotices.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasEditRefusalNotices.tsx@@ -97,12 +97,13 @@ const paintOnNewLayer = ();/**- * Explains edits the engine refused without a caller to report to: a stroke too large to undo, or a press on a layer- * the tool cannot edit (hidden, locked, still loading). A brush press on a locked or hidden image offers a new paint- * layer above it rather than making one unasked; that offer holds a closure, so it is a toast only, closed with this- * canvas or the account. Layer refusals are toasts only, one per layer and reason: a repeated press (every eraser- * press on a transparency-locked layer, say) replaces its toast instead of stacking another, and taking one offer- * closes the other offers. Keyed by engine.+ * Explains edits the engine refused without a caller to report to: a stroke too large to undo, a press on a layer+ * the tool cannot edit (hidden, locked, still loading), or a shape cutout with no paint layer or mask selected. A+ * brush press on a locked or hidden image offers a new paint layer above it rather than making one unasked; that+ * offer holds a closure, so it is a toast only, closed with this canvas or the account. Layer refusals are toasts+ * only, one per layer and reason: a repeated press (every eraser press on a transparency-locked layer, say) replaces+ * its toast instead of stacking another, and taking one offer closes the other offers. A cutout with nothing to cut+ * from keeps a single toast the same way. Keyed by engine.*/export const CanvasEditRefusalNotices = ({engine,@@ -130,10 +131,21 @@ export const CanvasEditRefusalNotices = ({notify.error(t('widgets.canvas.structural.failed'), describeAdjustmentRefusal(refusal, t));return;}+ const signal = AbortSignal.any([captureAccountScope().signal, mounted.signal]);+ if (refusal.status === 'cutout-no-target') {+ createActionToast({+ actions: [],+ description: t('widgets.canvas.editRefusal.noCutoutTargetMessage'),+ id: `${scope}:${refusal.status}`,+ signal,+ title: t('widgets.canvas.editRefusal.noCutoutTarget'),+ type: 'info',+ });+ return;+ }const { message, title } = describeLayerEditRefusal(refusal, t);// One toast per layer and reason: pressing again on the same layer replaces it rather than stacking another.const id = `${scope}:${refusal.status}:${refusal.layerId}`;- const signal = AbortSignal.any([captureAccountScope().signal, mounted.signal]);if (!refusal.canPaintNewLayer) {createActionToast({ actions: [], description: message, id, signal, title, type: 'info' });return;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStrip.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStrip.tsxindex d4e50d8d80..6e0d20b034 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStrip.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStrip.tsx@@ -15,24 +15,19 @@ import { applyCustomHotkeys } from '@workbench/hotkeys/resolve';import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';import {BrushIcon,- CircleIcon,EraserIcon,HandIcon,LassoIcon,MousePointer2Icon,- PenLineIcon,- PentagonIcon,ScalingIcon,ScanIcon,SquareDashedMousePointerIcon,- SquareIcon,- StarIcon,- TriangleIcon,TypeIcon,} from 'lucide-react';import { useCallback, useEffect, useMemo, type ElementType, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';+import { SHAPE_KIND_ORDER, SHAPE_KIND_PRESENTATION } from './canvasToolCommands';import { useCanvasActiveTool, useShapeOptions } from './engineStoreHooks';import { recordSelectFamilyTool, useSelectFamilyTool, type SelectFamilyTool } from './toolFamilyStore';import { ToolFamilyButton, type ToolFlyoutItem } from './ToolStripFlyout';@@ -81,24 +76,6 @@ const ToolStripButton = ({ description, engine, hotkey, icon, label, toolId }: T);};-const SHAPE_KIND_ICONS: Record<ShapeToolKind, React.ElementType> = {- ellipse: CircleIcon,- freehand: PenLineIcon,- polygon: PentagonIcon,- rect: SquareIcon,- star: StarIcon,- triangle: TriangleIcon,-};-const SHAPE_KIND_ORDER: readonly ShapeToolKind[] = ['rect', 'ellipse', 'triangle', 'star', 'polygon', 'freehand'];-const SHAPE_KIND_LABEL_KEYS: Record<ShapeToolKind, string> = {- ellipse: 'widgets.canvas.toolOptions.shapeEllipse',- freehand: 'widgets.canvas.toolOptions.shapeFreehand',- polygon: 'widgets.canvas.toolOptions.shapePolygon',- rect: 'widgets.canvas.toolOptions.shapeRect',- star: 'widgets.canvas.toolOptions.shapeStar',- triangle: 'widgets.canvas.toolOptions.shapeTriangle',-};-/** The Shape slot: one tool id, the flyout switching which kind the next drag draws. */const ShapeFamilyButton = ({ engine, hotkey }: { engine: ToolStripEngine; hotkey: string | undefined }) => {const { t } = useTranslation();@@ -109,9 +86,9 @@ const ShapeFamilyButton = ({ engine, hotkey }: { engine: ToolStripEngine; hotkeySHAPE_KIND_ORDER.map((kind) => ({// One key selects the Shape tool and cycles its kinds; each entry shows it.hotkeys: hotkey ? [hotkey] : undefined,- icon: SHAPE_KIND_ICONS[kind],+ icon: SHAPE_KIND_PRESENTATION[kind].icon,id: kind,- label: t(SHAPE_KIND_LABEL_KEYS[kind]),+ label: t(SHAPE_KIND_PRESENTATION[kind].labelKey),})),[hotkey, t]);@@ -126,7 +103,7 @@ const ShapeFamilyButton = ({ engine, hotkey }: { engine: ToolStripEngine; hotkeyreturn (<ToolFamilyButtoncurrentId={options.kind}- icon={SHAPE_KIND_ICONS[options.kind]}+ icon={SHAPE_KIND_PRESENTATION[options.kind].icon}isActive={activeTool === 'shape'}items={items}label={t('widgets.canvas.tools.shape')}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasToolCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasToolCommands.tsindex 62b041eb2d..d5f22d7af4 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasToolCommands.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasToolCommands.ts@@ -4,11 +4,14 @@ import type {CanvasDocumentContractV3,CanvasEngine,LayerUnreadable,+ ShapeToolKind,} from '@workbench/canvas-engine/api';import type { TFunction } from 'i18next';+import type { ElementType } from 'react';import { mergeDownEligibility } from '@workbench/canvas-engine/api';import { reportLayerOperation, type LayerOperationRefusal } from '@workbench/widgets/canvas/useStructuralCommit';+import { CircleIcon, PenLineIcon, PentagonIcon, SquareIcon, StarIcon, TriangleIcon } from 'lucide-react';/** One hotkey row: its command id, title key and default keys. */export type HotkeyTableEntry = readonly [id: string, titleKey: string, defaultKeys: readonly string[]];@@ -68,6 +71,29 @@ export const CANVAS_HISTORY_HOTKEYS = [['canvas.redo', 'widgets.canvas.commands.redo', ['mod+shift+z', 'mod+y']],] as const satisfies readonly HotkeyTableEntry[];+/**+ * How each shape kind is shown wherever the next shape's kind is chosen: the tool strip flyout and the Shape+ * options. It lives with the Shape key's command so the Canvas and the Layers pane share it from a chunk both load.+ */+export const SHAPE_KIND_PRESENTATION: Record<ShapeToolKind, { icon: ElementType; labelKey: string }> = {+ ellipse: { icon: CircleIcon, labelKey: 'widgets.canvas.toolOptions.shapeEllipse' },+ freehand: { icon: PenLineIcon, labelKey: 'widgets.canvas.toolOptions.shapeFreehand' },+ polygon: { icon: PentagonIcon, labelKey: 'widgets.canvas.toolOptions.shapePolygon' },+ rect: { icon: SquareIcon, labelKey: 'widgets.canvas.toolOptions.shapeRect' },+ star: { icon: StarIcon, labelKey: 'widgets.canvas.toolOptions.shapeStar' },+ triangle: { icon: TriangleIcon, labelKey: 'widgets.canvas.toolOptions.shapeTriangle' },+};++/** The order the kind lists show and the Shape key cycles through. */+export const SHAPE_KIND_ORDER: readonly ShapeToolKind[] = [+ 'rect',+ 'ellipse',+ 'triangle',+ 'star',+ 'polygon',+ 'freehand',+];+export type CanvasToolCommandId = (typeof CANVAS_COMPANION_HOTKEYS)[number][0];const CANVAS_TOOL_COMMAND_IDS: ReadonlySet<string> = new Set(CANVAS_COMPANION_HOTKEYS.map(([id]) => id));@@ -173,8 +199,7 @@ export const executeCanvasToolCommand = (commandId: CanvasToolCommandId, ctx: Caif (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]!;+ const next = SHAPE_KIND_ORDER[(SHAPE_KIND_ORDER.indexOf(shape.kind) + 1) % SHAPE_KIND_ORDER.length]!;engine.interaction.set('shapeOptions', { ...shape, kind: next });} else {engine.tools.setTool('shape');diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/shortcutHints.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/shortcutHints.test.tsindex f52c26ff79..c98789916f 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/shortcutHints.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/shortcutHints.test.ts@@ -68,6 +68,19 @@ describe('Canvas gesture guidance', () => {expect(notifications).toBe(afterRelease);unsubscribe();});+ it('teaches the Shape modifiers each kind honors', () => {+ const shape = { ...state, activeTool: 'shape' as const };+ const center = 'workbench.shortcuts.actions.drawFromCenter';+ const cutOut = 'workbench.shortcuts.actions.cutOutShape';+ expect(hintLabels({ ...shape, shapeKind: 'ellipse' })).toEqual(expect.arrayContaining([center, cutOut]));+ for (const shapeKind of ['polygon', 'freehand']) {+ const labels = hintLabels({ ...shape, shapeKind });+ expect(labels).toContain(cutOut);+ expect(labels).not.toContain(center);+ expect(labels).not.toContain('workbench.shortcuts.actions.constrain');+ }+ });+it('removes painting/session instructions during prompt-mode object selection and Filter', () => {expect(hintLabels({ ...state, operation: 'select-object', samVisual: false })).toEqual(['workbench.shortcuts.actions.pan',diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/shortcutHints.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/shortcutHints.tsindex e05f76f8a9..17e79555fb 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/shortcutHints.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/shortcutHints.ts@@ -2,6 +2,7 @@ import type { CanvasEngine, CanvasInteractionState, ToolId } from '@workbench/caimport type { ShortcutHint, ShortcutHintSnapshot, ShortcutHintSource } from '@workbench/hotkeys/hintSources';import { getCanvasOperations } from '@workbench/canvas-operations/api';+import { MOD_KEY_LABEL } from '@workbench/hotkeys/keys';const gesture = (label: string, parts: readonly string[] = [], pointerKey?: string): ShortcutHint => ({labelKey: `workbench.shortcuts.actions.${label}`,@@ -73,14 +74,12 @@ export const getCanvasShortcutHints = ({gesture('subtractSelection', ['alt']));} else if (tool === 'shape') {+ const isBox = shapeKind !== 'polygon' && shapeKind !== 'freehand';hints.push(- ...(shapeKind === 'polygon'- ? POLYGON_HINTS- : [- gesture('draw', [], 'drag'),- ...(shapeKind === 'freehand' ? [] : [gesture('constrain', ['shift'], 'drag')]),- CANCEL,- ])+ ...(shapeKind === 'polygon' ? POLYGON_HINTS : [gesture('draw', [], 'drag'), CANCEL]),+ ...(isBox ? [gesture('constrain', ['shift'], 'drag'), gesture('drawFromCenter', ['alt'], 'drag')] : []),+ // The platform's mod key cuts out: ⌘ on macOS, Ctrl elsewhere.+ gesture('cutOutShape', [MOD_KEY_LABEL]));} else if (tool === 'bbox') {hints.push(diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.browser.test.tsxnew file mode 100644index 0000000000..981329aa16--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.browser.test.tsx@@ -0,0 +1,335 @@+import type {+ CanvasLayerContract,+ CanvasLayerSourceContract,+ CanvasNodeContract,+ ShapeToolOptions,+} from '@workbench/canvas-engine/api';+import type { StructuralEngineStub } from '@workbench/canvas-engine/controllers/structuralEngine.testStub';+import type { Project } from '@workbench/projectContracts';+import type { ToolFormProps } from '@workbench/widgets/canvas/tool-presentation/toolFormContracts';++import { ChakraProvider } from '@chakra-ui/react';+import { system } from '@theme/system';+import { DEFAULT_SHAPE_OPTIONS, getDocumentLayer } from '@workbench/canvas-engine/api';+import { createStructuralEngineStub } from '@workbench/canvas-engine/controllers/structuralEngine.testStub';+import { groupContract, layerContract } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { PropertyGroup } from '@workbench/widgets/canvas/tool-presentation/PropertyPrimitives';+import { createInstance } from 'i18next';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { I18nextProvider } from 'react-i18next';+import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';+import { page, userEvent } from 'vitest/browser';++const harness = vi.hoisted(() => ({+ listeners: new Set<() => void>(),+ project: null as Project | null,+}));++vi.mock('@workbench/WorkbenchContext', async () => {+ const { useSyncExternalStore } = await import('react');+ const subscribe = (listener: () => void) => {+ harness.listeners.add(listener);+ return () => harness.listeners.delete(listener);+ };+ return {+ useActiveProjectSelector: (selector: (project: unknown) => unknown) =>+ selector(useSyncExternalStore(subscribe, () => harness.project)),+ useOptionalWorkbenchCommands: () => null,+ useWorkbenchCommands: () => ({ widgets: { patchValues: vi.fn() } }),+ useWorkbenchQueries: () => ({ getSnapshot: () => ({ activeProject: harness.project }) }),+ };+});+const notify = vi.hoisted(() => ({ error: vi.fn(), info: vi.fn(), success: vi.fn() }));+vi.mock('@workbench/useNotify', () => ({ useNotify: () => notify }));++import { shapeForm } from './ShapeOptions';++type ShapeSource = Extract<CanvasLayerSourceContract, { type: 'shape' }>;++const i18n = createInstance();+beforeAll(async () => {+ const translation = (await (await fetch('/locales/en.json')).json()) as Record<string, unknown>;+ await i18n.init({ initAsync: false, lng: 'en', resources: { en: { translation } } });+});++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const RECT_SOURCE: ShapeSource = {+ fill: '#ff0000',+ height: 40,+ kind: 'rect',+ stroke: '#0000ff',+ strokeWidth: 4,+ type: 'shape',+ width: 60,+};+const shapeLayer = (id: string): CanvasLayerContract =>+ ({ ...layerContract(id, 'raster', { name: 'Rect' }), source: RECT_SOURCE }) as CanvasLayerContract;++let stub: StructuralEngineStub;+let unsubscribe: () => void = () => undefined;+let shapeOptions: ShapeToolOptions;+const optionListeners = new Set<() => void>();+let host: HTMLDivElement | null = null;+let root: Root | null = null;++const publish = (): void => {+ harness.project = stub.project();+ harness.listeners.forEach((listener) => listener());+};++/** The form's engine: the structural stub over the real reducer and history, plus the tool's options store. */+const formEngine = (): ToolFormProps['engine'] =>+ ({+ ...stub.engine,+ interaction: {+ get: (key: string) => (key === 'shapeOptions' ? shapeOptions : undefined),+ set: (key: string, value: ShapeToolOptions) => {+ if (key === 'shapeOptions') {+ shapeOptions = value;+ optionListeners.forEach((listener) => listener());+ }+ },+ subscribe: (key: string, listener: () => void) => {+ if (key !== 'shapeOptions') {+ return () => undefined;+ }+ optionListeners.add(listener);+ return () => optionListeners.delete(listener);+ },+ },+ tools: { requestColorSample: () => Promise.resolve(null) },+ }) as unknown as ToolFormProps['engine'];++/** Renders the form's groups the way the Properties pane does. */+const mount = async (layers: readonly CanvasNodeContract[], selectedLayerId: string | null): Promise<void> => {+ unsubscribe();+ stub = createStructuralEngineStub({ layers, selectedLayerId });+ unsubscribe = stub.subscribe(publish);+ publish();+ shapeOptions = { ...DEFAULT_SHAPE_OPTIONS };+ const engine = formEngine();+ host = document.createElement('div');+ host.style.width = '300px';+ document.body.append(host);+ root = createRoot(host);+ await act(() =>+ root!.render(+ <I18nextProvider i18n={i18n}>+ <ChakraProvider value={system}>+ {shapeForm.groups.map((group) => (+ <PropertyGroup key={group.id} id={group.id} label={i18n.t(group.labelKey)}>+ <group.body engine={engine} />+ </PropertyGroup>+ ))}+ </ChakraProvider>+ </I18nextProvider>+ )+ );+};++const selectLayer = async (id: string | null): Promise<void> => {+ await act(() => {+ stub.ctx.dispatch({ id, type: 'setCanvasSelectedLayer' });+ });+};++const source = (id = 's1'): ShapeSource => {+ const layer = getDocumentLayer(stub.document(), id);+ if (layer?.type !== 'raster' || layer.source.type !== 'shape') {+ throw new Error(`${id} is not a shape layer`);+ }+ return layer.source;+};++const toolGroup = () => page.getByRole('group', { name: 'Shape' });+const appearanceGroup = () => page.getByRole('group', { name: 'Appearance' });+const kindGroup = () => toolGroup().getByRole('radiogroup', { name: 'Kind' });+/** The on/off button beside a color, not the color chip that shares its name. */+const clickToggle = (name: string) =>+ act(() =>+ appearanceGroup().element().querySelector<HTMLElement>(`button[aria-label="${name}"][aria-pressed]`)!.click()+ );+const hint = 'Select a paint layer or mask.';+const maskHint = 'Shapes add to the selected mask; fill and stroke set which parts, not their colors.';++afterEach(async () => {+ await act(() => root?.unmount());+ root = null;+ host?.remove();+ host = null;+ unsubscribe();+ unsubscribe = () => undefined;+ optionListeners.clear();+ vi.clearAllMocks();+});++describe('shape tool settings', () => {+ it('keeps every kind and Place on with a shape layer selected, and a kind only sets the next shape', async () => {+ await mount([shapeLayer('s1')], 's1');++ await expect.element(toolGroup().getByRole('radiogroup', { name: 'Place on' })).toBeVisible();+ for (const name of ['Rectangle', 'Ellipse', 'Triangle', 'Star', 'Polygon', 'Freehand']) {+ await expect.element(kindGroup().getByRole('radio', { exact: true, name })).toBeInTheDocument();+ }+ expect(kindGroup().getByRole('radio').elements()).toHaveLength(6);+ await expect.element(kindGroup().getByRole('radio', { name: 'Rectangle' })).toBeChecked();++ const polygon = kindGroup().getByRole('radio', { name: 'Polygon' });+ await userEvent.hover(polygon, { force: true });+ await expect.element(page.getByRole('tooltip')).toHaveTextContent('Polygon');+ await userEvent.click(polygon, { force: true });++ expect(shapeOptions.kind).toBe('polygon');+ await expect.element(polygon).toBeChecked();+ expect(source()).toBe(RECT_SOURCE);+ expect(stub.commits).toHaveLength(0);+ });++ it('picks a kind from the keyboard', async () => {+ await mount([layerContract('p1', 'raster')], 'p1');+ await act(() => (kindGroup().getByRole('radio', { name: 'Rectangle' }).element() as HTMLElement).focus());++ await userEvent.keyboard('{ArrowRight}');++ expect(shapeOptions.kind).toBe('ellipse');+ await expect.element(kindGroup().getByRole('radio', { name: 'Ellipse' })).toBeChecked();+ });++ it('shows the effective destination and restores the saved preference on an eligible selection', async () => {+ await mount([shapeLayer('s1'), layerContract('p1', 'raster'), layerContract('m1', 'inpaint_mask')], 's1');+ const target = toolGroup().getByRole('radiogroup', { name: 'Place on' });+ const selected = target.getByRole('radio', { name: 'Selected layer' });+ const newLayer = target.getByRole('radio', { name: 'New layer' });++ await expect.element(selected).toBeDisabled();+ await expect.element(newLayer).toBeChecked();+ await expect.element(toolGroup().getByText(hint)).toBeVisible();+ expect(target.element().getAttribute('aria-describedby')).toBe(toolGroup().getByText(hint).element().id);+ expect(shapeOptions.target).toBe('selected');+ await act(() => (newLayer.element() as HTMLElement).focus());+ await userEvent.keyboard('{ArrowLeft}');+ await expect.element(newLayer).toBeChecked();+ expect(shapeOptions.target).toBe('selected');++ await selectLayer('p1');+ await expect.element(selected).toBeEnabled();+ await expect.element(selected).toBeChecked();+ await expect.element(toolGroup().getByText(hint)).not.toBeInTheDocument();+ await userEvent.click(target.getByText('New layer'));+ expect(shapeOptions.target).toBe('new');+ await selectLayer('s1');+ await selectLayer('m1');+ await expect.element(newLayer).toBeChecked();+ await expect.element(toolGroup().getByText(maskHint)).not.toBeInTheDocument();+ await userEvent.click(target.getByText('Selected layer'));+ await expect.element(toolGroup().getByText(maskHint)).toBeVisible();+ expect(target.element().getAttribute('aria-describedby')).toBe(toolGroup().getByText(maskHint).element().id);+ });++ it.each([+ ['nothing', [], null],+ ['a group', [groupContract('g1')], 'g1'],+ ['a shape', [shapeLayer('s1')], 's1'],+ [+ 'an image',+ [layerContract('i1', 'raster', { source: { image: { imageName: 'i', width: 1, height: 1 }, type: 'image' } })],+ 'i1',+ ],+ [+ 'a gradient',+ [+ layerContract('g1', 'raster', {+ source: {+ type: 'gradient',+ kind: 'linear',+ angle: 0,+ width: 10,+ height: 10,+ stops: [+ { color: '#000000', offset: 0 },+ { color: '#ffffff', offset: 1 },+ ],+ },+ }),+ ],+ 'g1',+ ],+ [+ 'text',+ [+ layerContract('t1', 'raster', {+ source: {+ type: 'text',+ content: 'Text',+ color: '#000000',+ fontFamily: 'sans-serif',+ fontSize: 12,+ fontWeight: 400,+ lineHeight: 1,+ align: 'left',+ },+ }),+ ],+ 't1',+ ],+ ] as const)('disables Selected layer and explains New layer when %s is selected', async (_label, layers, id) => {+ await mount(layers, id);+ const target = toolGroup().getByRole('radiogroup', { name: 'Place on' });+ await expect.element(target.getByRole('radio', { name: 'Selected layer' })).toBeDisabled();+ await expect.element(target.getByRole('radio', { name: 'New layer' })).toBeChecked();+ await expect.element(toolGroup().getByText(hint)).toBeVisible();+ expect(shapeOptions.target).toBe('selected');+ });++ it.each([+ ['locked', { isLocked: true }],+ ['hidden', { isHidden: true }],+ ['loading', { source: { bitmap: { imageName: 'paint.png', width: 10, height: 10 }, type: 'paint' } }],+ ] as const)(+ 'keeps the selected destination for a %s paint layer so the engine can report its refusal',+ async (_label, overrides) => {+ await mount([layerContract('p1', 'raster', overrides)], 'p1');+ const selected = toolGroup().getByRole('radio', { name: 'Selected layer' });+ await expect.element(selected).toBeEnabled();+ await expect.element(selected).toBeChecked();+ await expect.element(toolGroup().getByText(hint)).not.toBeInTheDocument();+ }+ );+});++describe('shape appearance', () => {+ it('edits only creation defaults even with a shape layer selected', async () => {+ await mount([shapeLayer('s1')], 's1');+ await expect.element(appearanceGroup().getByText('Defaults')).toBeVisible();+ await clickToggle('Fill');+ expect(shapeOptions.fillEnabled).toBe(false);+ await clickToggle('Stroke');+ expect(shapeOptions.strokeEnabled).toBe(true);+ const width = appearanceGroup().getByRole('slider', { name: 'Stroke width' });+ await act(async () => {+ (width.element() as HTMLElement).focus();+ await userEvent.keyboard('{ArrowRight>3/}');+ });+ expect(shapeOptions.strokeWidth).toBe(DEFAULT_SHAPE_OPTIONS.strokeWidth + 3);+ expect(source()).toBe(RECT_SOURCE);+ expect(stub.commits).toHaveLength(0);+ });++ it('edits the tool defaults with no shape layer selected', async () => {+ await mount([layerContract('p1', 'raster')], 'p1');+ await expect.element(appearanceGroup().getByText('Defaults')).toBeVisible();++ await clickToggle('Stroke');+ expect(shapeOptions.strokeEnabled).toBe(true);++ const width = appearanceGroup().getByRole('slider', { name: 'Stroke width' });+ await act(async () => {+ (width.element() as HTMLElement).focus();+ await userEvent.keyboard('{ArrowRight>2/}');+ });+ expect(shapeOptions.strokeWidth).toBe(DEFAULT_SHAPE_OPTIONS.strokeWidth + 2);+ expect(stub.commits).toHaveLength(0);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.tsxindex e8a56c3cca..bf41571084 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.tsx@@ -1,11 +1,22 @@-import type { CanvasLayerSourceContract, ShapeToolOptions } from '@workbench/canvas-engine/api';+import type {+ CanvasLayerContract,+ CanvasLayerSourceContract,+ ShapeToolKind,+ ShapeToolOptions,+} from '@workbench/canvas-engine/api';import type { ToolFormProps, ToolPropertyForm } from '@workbench/widgets/canvas/tool-presentation/toolFormContracts';import { Text } from '@chakra-ui/react';import { ToggleIconButton } from '@platform/ui/Button';import { ColorPicker } from '@platform/ui/ColorPicker';import { ScrubberField } from '@platform/ui/ScrubberField';-import { DEFAULT_SHAPE_OPTIONS, MAX_SHAPE_STROKE_WIDTH, getDocumentLayer } from '@workbench/canvas-engine/api';+import {+ DEFAULT_SHAPE_OPTIONS,+ MAX_SHAPE_STROKE_WIDTH,+ getDocumentLayer,+ shapeDrawsOnLayer,+} from '@workbench/canvas-engine/api';+import { SHAPE_KIND_ORDER, SHAPE_KIND_PRESENTATION } from '@workbench/widgets/canvas/canvasToolCommands';import { useActiveColorCommands, useActiveColorPair } from '@workbench/widgets/canvas/color-system/useActiveColors';import { useShapeOptions } from '@workbench/widgets/canvas/engineStoreHooks';import { useSliderGesture } from '@workbench/widgets/canvas/tool-presentation/FormControls';@@ -14,222 +25,228 @@ import {PropertyControlRow,PropertySegmentedRow,} from '@workbench/widgets/canvas/tool-presentation/PropertyPrimitives';-import { useColorSampler } from '@workbench/widgets/canvas/useColorSampler';-import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';+import { useColorSampler, type ColorSamplerEngine } from '@workbench/widgets/canvas/useColorSampler';+import { usePreparedCommit, type CanvasPreparedEngine } from '@workbench/widgets/canvas/useStructuralCommit';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';import { PaintBucketIcon, SquareIcon } from 'lucide-react';-import { useCallback, useMemo } from 'react';+import { useCallback, useId, useMemo } from 'react';import { useTranslation } from 'react-i18next';type ShapeSource = Extract<CanvasLayerSourceContract, { type: 'shape' }>;-type ShapeKind = ShapeToolOptions['kind'];--interface SelectedShape {- id: string;- name: string;- source: ShapeSource;-}+type ShapeStylePatch = Partial<Pick<ShapeSource, 'fill' | 'stroke' | 'strokeWidth'>>;const FALLBACK_COLOR = '#000000';const formatPx = (value: number): string => `${value}px`;-/**- * Edit selected shape content or tool defaults with pair colors. Color gestures commit once; without a selected- * shape they edit the shared pair.- */-const useShapeEditor = (engine: ToolFormProps['engine']) => {+/** Where Place on = Selected layer sends the next shape, given the selection. */+type SelectedPlacement = 'none' | 'layer' | 'mask' | 'new-layer';++const setShapeOptions = (engine: ToolFormProps['engine'], patch: Partial<ShapeToolOptions>): void => {+ engine.interaction.set('shapeOptions', { ...engine.interaction.get('shapeOptions'), ...patch });+};++/** Settings for the next shape: what it is and where it lands. They never touch a selected layer. */+const ShapeToolSettings = ({ engine }: ToolFormProps) => {const { t } = useTranslation();- const commitPrepared = usePreparedCommit(engine);+ const options = useShapeOptions(engine);+ const placement = useActiveProjectSelector((project): SelectedPlacement => {+ const { document } = project.canvas;+ const layer = document.selectedLayerId ? getDocumentLayer(document, document.selectedLayerId) : undefined;+ if (!layer) {+ return 'none';+ }+ if (layer.type === 'inpaint_mask' || layer.type === 'regional_guidance') {+ return 'mask';+ }+ return shapeDrawsOnLayer(layer) ? 'layer' : 'new-layer';+ });+ const kindOptions = useMemo(+ () =>+ SHAPE_KIND_ORDER.map((value) => ({+ icon: SHAPE_KIND_PRESENTATION[value].icon,+ label: t(SHAPE_KIND_PRESENTATION[value].labelKey),+ value,+ })),+ [t]+ );+ const onKindChange = useCallback((kind: ShapeToolKind) => setShapeOptions(engine, { kind }), [engine]);+ const canPlaceSelected = placement === 'layer' || placement === 'mask';+ const targetOptions = useMemo(+ () => [+ {+ disabled: !canPlaceSelected,+ label: t('widgets.canvas.toolOptions.shapeTargetSelected'),+ value: 'selected' as const,+ },+ { label: t('widgets.canvas.toolOptions.shapeTargetNew'), value: 'new' as const },+ ],+ [canPlaceSelected, t]+ );+ const onTargetChange = useCallback(+ (target: ShapeToolOptions['target']) => setShapeOptions(engine, { target }),+ [engine]+ );+ const hintId = useId();+ const hintKey = !canPlaceSelected+ ? 'widgets.canvas.toolOptions.shapeTargetFallbackHint'+ : options.target === 'selected' && placement === 'mask'+ ? 'widgets.canvas.toolOptions.shapeMaskHint'+ : null;+ return (+ <>+ <PropertySegmentedRow+ label={t('widgets.properties.rows.kind')}+ options={kindOptions}+ value={options.kind}+ onValueChange={onKindChange}+ />+ <PropertySegmentedRow+ describedBy={hintKey ? hintId : undefined}+ label={t('widgets.canvas.toolOptions.shapeTarget')}+ options={targetOptions}+ value={canPlaceSelected ? options.target : 'new'}+ onValueChange={onTargetChange}+ />+ {hintKey ? (+ <Text color="fg.muted" fontSize="xs" id={hintId}>+ {t(hintKey)}+ </Text>+ ) : null}+ </>+ );+};++/** Creation defaults stay independent of the selected shape's appearance. */+const ShapeDefaultAppearanceSettings = ({ engine }: ToolFormProps) => {const options = useShapeOptions(engine);const pair = useActiveColorPair();const colorCommands = useActiveColorCommands();- const selected = useActiveProjectSelector(- (project): SelectedShape | null => {- const { document } = project.canvas;- const layer = document.selectedLayerId ? getDocumentLayer(document, document.selectedLayerId) : undefined;- return layer && layer.type === 'raster' && layer.source.type === 'shape'- ? { id: layer.id, name: layer.name, source: layer.source }- : null;- },- (a, b) => a?.id === b?.id && a?.name === b?.name && a?.source === b?.source+ const setStrokeWidth = useCallback((value: number) => setShapeOptions(engine, { strokeWidth: value }), [engine]);+ const setFillEnabled = useCallback((checked: boolean) => setShapeOptions(engine, { fillEnabled: checked }), [engine]);+ const setStrokeEnabled = useCallback(+ (checked: boolean) => setShapeOptions(engine, { strokeEnabled: checked }),+ [engine]+ );+ const setFillColor = useCallback((hex: string) => colorCommands.setPairColor('foreground', hex), [colorCommands]);+ const setStrokeColor = useCallback((hex: string) => colorCommands.setPairColor('background', hex), [colorCommands]);+ return (+ <>+ <EditTargetChip layerName={null} />+ <ShapeAppearanceControls+ engine={engine}+ fill={options.fillEnabled ? pair.foreground : null}+ previewStrokeWidth={setStrokeWidth}+ setFillColor={setFillColor}+ setFillEnabled={setFillEnabled}+ setStrokeColor={setStrokeColor}+ setStrokeEnabled={setStrokeEnabled}+ setStrokeWidth={setStrokeWidth}+ stroke={options.strokeEnabled ? pair.background : null}+ strokeWidth={options.strokeWidth}+ />+ </>);- const kind: ShapeKind = selected ? selected.source.kind : options.kind;- const fill = selected ? selected.source.fill : options.fillEnabled ? pair.foreground : null;- const stroke = selected ? selected.source.stroke : options.strokeEnabled ? pair.background : null;- const strokeWidth = selected ? selected.source.strokeWidth : options.strokeWidth;+};- const selectedId = selected?.id ?? null;- // Scrubbers keep the handler a gesture started with, so writes patch the live source and options: an undo or- // hotkey landing mid-drag survives the release.+/** Selected-layer appearance belongs to Layer properties, whichever canvas tool is active. */+export const SelectedShapeAppearanceSettings = ({+ engine,+ layer,+ source,+}: {+ engine: (CanvasPreparedEngine & ColorSamplerEngine) | null;+ layer: Pick<CanvasLayerContract, 'id' | 'name'>;+ source: ShapeSource;+}) => {+ const { t } = useTranslation();+ const commitPrepared = usePreparedCommit(engine);+ const pair = useActiveColorPair();+ // A scrub keeps its starting callback. Patch the live source, and drop a release after selection changed.const commitSource = useCallback(- (patch: Partial<ShapeSource>) => {- if (!selectedId) {- return;- }+ (patch: ShapeStylePatch) => {commitPrepared(t('widgets.canvas.toolOptions.shapeEdit'), (model) => {- const layer = model.getLayer(selectedId);- if (layer?.type !== 'raster' || layer.source.type !== 'shape') {- return { ids: [selectedId], status: 'missing' };+ if (model.document.selectedLayerId !== layer.id) {+ return { status: 'unchanged' };}- // Vertices belong to polygons only; a box kind never carries stale ones.- const { points, ...merged } = { ...layer.source, ...patch };- const after: ShapeSource = merged.kind === 'polygon' ? { ...merged, points } : merged;- return model.prepare({ id: selectedId, source: after, type: 'patch-source' });+ const current = model.getLayer(layer.id);+ if (current?.type !== 'raster' || current.source.type !== 'shape') {+ return { ids: [layer.id], status: 'missing' };+ }+ return model.prepare({ id: layer.id, source: { ...current.source, ...patch }, type: 'patch-source' });});},- [commitPrepared, selectedId, t]- );- const setOptions = useCallback(- (patch: Partial<ShapeToolOptions>) => {- engine.interaction.set('shapeOptions', { ...engine.interaction.get('shapeOptions'), ...patch });- },- [engine]- );- const setKind = useCallback(- (next: ShapeKind) => {- setOptions({ kind: next });- // Creation-only kinds never rewrite a selected layer; a box kind drops a polygon's points.- if (next !== 'freehand' && next !== 'polygon') {- commitSource({ kind: next });- }- },- [commitSource, setOptions]- );- const setTarget = useCallback((next: ShapeToolOptions['target']) => setOptions({ target: next }), [setOptions]);- const previewStrokeWidth = useCallback((value: number) => setOptions({ strokeWidth: value }), [setOptions]);- const setStrokeWidth = useCallback(- (value: number) => {- setOptions({ strokeWidth: value });- commitSource({ strokeWidth: value });- },- [commitSource, setOptions]+ [commitPrepared, layer.id, t]);const setFillEnabled = useCallback(- (checked: boolean) => {- setOptions({ fillEnabled: checked });- commitSource({ fill: checked ? (selected?.source.fill ?? pair.foreground) : null });- },- [commitSource, pair.foreground, selected, setOptions]+ (checked: boolean) => commitSource({ fill: checked ? (source.fill ?? pair.foreground) : null }),+ [commitSource, pair.foreground, source.fill]);const setStrokeEnabled = useCallback(- (checked: boolean) => {- setOptions({ strokeEnabled: checked });- commitSource({ stroke: checked ? (selected?.source.stroke ?? pair.background) : null });- },- [commitSource, pair.background, selected, setOptions]+ (checked: boolean) => commitSource({ stroke: checked ? (source.stroke ?? pair.background) : null }),+ [commitSource, pair.background, source.stroke]);+ const setStrokeWidth = useCallback((value: number) => commitSource({ strokeWidth: value }), [commitSource]);const setFillColor = useCallback((hex: string, commit: boolean) => {- if (selected) {- if (commit) {- commitSource({ fill: hex });- }- return;+ if (commit) {+ commitSource({ fill: hex });}- colorCommands.setPairColor('foreground', hex);},- [colorCommands, commitSource, selected]+ [commitSource]);const setStrokeColor = useCallback((hex: string, commit: boolean) => {- if (selected) {- if (commit) {- commitSource({ stroke: hex });- }- return;+ if (commit) {+ commitSource({ stroke: hex });}- colorCommands.setPairColor('background', hex);},- [colorCommands, commitSource, selected]+ [commitSource]+ );+ return (+ <ShapeAppearanceControls+ engine={engine}+ fill={source.fill}+ setFillColor={setFillColor}+ setFillEnabled={setFillEnabled}+ setStrokeColor={setStrokeColor}+ setStrokeEnabled={setStrokeEnabled}+ setStrokeWidth={setStrokeWidth}+ stroke={source.stroke}+ strokeWidth={source.strokeWidth}+ />);- return {- fill,- kind,- selectedIsPolygon: selected?.source.kind === 'polygon',- selectedName: selected?.name ?? null,- setTarget,- target: options.target,- setFillColor,- setFillEnabled,- setKind,- previewStrokeWidth,- setStrokeColor,- setStrokeEnabled,- setStrokeWidth,- stroke,- strokeWidth,- toolKind: options.kind,- };};-const ShapeSettings = ({ engine }: ToolFormProps) => {+/** The same fill, stroke and width controls for defaults and selected content, with separate write paths. */+const ShapeAppearanceControls = ({+ engine,+ ...editor+}: {+ engine: ColorSamplerEngine | null;+ fill: string | null;+ stroke: string | null;+ strokeWidth: number;+ setFillColor: (hex: string, commit: boolean) => void;+ setStrokeColor: (hex: string, commit: boolean) => void;+ setFillEnabled: (checked: boolean) => void;+ setStrokeEnabled: (checked: boolean) => void;+ setStrokeWidth: (value: number) => void;+ previewStrokeWidth?: (value: number) => void;+}) => {const { t } = useTranslation();- const editor = useShapeEditor(engine);- const selectsMask = useActiveProjectSelector((project) => {- const { document } = project.canvas;- const layer = document.selectedLayerId ? getDocumentLayer(document, document.selectedLayerId) : undefined;- return layer?.type === 'inpaint_mask' || layer?.type === 'regional_guidance';- });const sampleColor = useColorSampler(engine);- // A selected layer shows its own kind and can only switch among the box- // kinds (a box has no vertices to become a polygon; a polygon switched to a- // box drops its points). Polygon and freehand are creation gestures, offered- // while nothing is selected.- const kindOptions = useMemo(- () => [- { label: t('widgets.canvas.toolOptions.shapeRect'), value: 'rect' as const },- { label: t('widgets.canvas.toolOptions.shapeEllipse'), value: 'ellipse' as const },- { label: t('widgets.canvas.toolOptions.shapeTriangle'), value: 'triangle' as const },- { label: t('widgets.canvas.toolOptions.shapeStar'), value: 'star' as const },- ...(editor.selectedName === null || editor.selectedIsPolygon- ? [{ label: t('widgets.canvas.toolOptions.shapePolygon'), value: 'polygon' as const }]- : []),- ...(editor.selectedName === null- ? [{ label: t('widgets.canvas.toolOptions.shapeFreehand'), value: 'freehand' as const }]- : []),- ],- [editor.selectedIsPolygon, editor.selectedName, t]- );- const targetOptions = useMemo(- () => [- { label: t('widgets.canvas.toolOptions.shapeTargetSelected'), value: 'selected' as const },- { label: t('widgets.canvas.toolOptions.shapeTargetNew'), value: 'new' as const },- ],- [t]- );const onFillChange = useCallback((hex: string) => editor.setFillColor(hex, false), [editor]);const onFillChangeEnd = useCallback((hex: string) => editor.setFillColor(hex, true), [editor]);const onStrokeChange = useCallback((hex: string) => editor.setStrokeColor(hex, false), [editor]);const onStrokeChangeEnd = useCallback((hex: string) => editor.setStrokeColor(hex, true), [editor]);- // Slider ticks preview through the options store; ONE document commit lands on release.const previewWidth = useCallback(- (value: number) => editor.previewStrokeWidth(Math.max(0, Math.round(value))),+ (value: number) => editor.previewStrokeWidth?.(Math.max(0, Math.round(value))),[editor]);const setWidth = useCallback((value: number) => editor.setStrokeWidth(Math.max(0, Math.round(value))), [editor]);const widthGesture = useSliderGesture(Math.round(editor.strokeWidth), setWidth, previewWidth);return (<>- <EditTargetChip layerName={editor.selectedName} />- <PropertySegmentedRow- label={t('widgets.properties.rows.kind')}- options={kindOptions}- value={editor.kind}- onValueChange={editor.setKind}- />- {editor.selectedName === null ? (- <PropertySegmentedRow- label={t('widgets.canvas.toolOptions.shapeTarget')}- options={targetOptions}- value={editor.target}- onValueChange={editor.setTarget}- />- ) : null}- {selectsMask && editor.target === 'selected' ? (- <Text color="fg.muted" fontSize="xs">- {t('widgets.canvas.toolOptions.shapeMaskHint')}- </Text>- ) : null}{/* The chip stays enabled-looking but inert when the slot is off; the toggle owns enablement. */}<PropertyControlRow label={t('widgets.canvas.toolOptions.shapeFill')}><ColorPicker@@ -280,7 +297,10 @@ const ShapeSettings = ({ engine }: ToolFormProps) => {};export const shapeForm: ToolPropertyForm = {- groups: [{ body: ShapeSettings, id: 'shape', labelKey: 'widgets.properties.groups.shape' }],+ groups: [+ { body: ShapeToolSettings, id: 'shape', labelKey: 'widgets.properties.groups.shape' },+ { body: ShapeDefaultAppearanceSettings, id: 'shape-appearance', labelKey: 'widgets.properties.groups.appearance' },+ ],id: 'shape',paintsLeaf: true,};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/PropertyPrimitives.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/PropertyPrimitives.tsxindex f478076dc5..335c7aa315 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/PropertyPrimitives.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/PropertyPrimitives.tsx@@ -1,4 +1,4 @@-import type { PointerEvent as ReactPointerEvent, ReactNode } from 'react';+import type { ElementType, PointerEvent as ReactPointerEvent, ReactNode } from 'react';import { Badge, chakra, Flex, Grid, Icon, Stack, Switch, Text } from '@chakra-ui/react';import { SegmentedControl } from '@platform/ui/SegmentedControl';@@ -148,18 +148,20 @@ export const PropertyGroup = ({);};-/** A labelled choice row rendered as a full-width segmented control (≤5 options). */+/** A labelled choice row rendered as a full-width segmented control: up to 5 text options, or more as icons. */export const PropertySegmentedRow = <Value extends string>({+ describedBy,disabled,label,onValueChange,options,value,}: {+ describedBy?: string;disabled?: boolean;label: string;onValueChange: (value: Value) => void;- options: readonly { value: Value; label: string }[];+ options: readonly { value: Value; label: string; icon?: ElementType; disabled?: boolean }[];value: Value;}) => {const handleChange = useCallback(@@ -173,6 +175,7 @@ export const PropertySegmentedRow = <Value extends string>({return (<PropertyControlRow label={label}><SegmentedControl+ aria-describedby={describedBy}ariaLabel={label}disabled={disabled}gridColumn="2 / -1"diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsxindex 526b8979c9..a7b8e3a78c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsx@@ -15,7 +15,7 @@ import type { Project } from '@workbench/projectContracts';import { Box, ChakraProvider } from '@chakra-ui/react';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { system } from '@theme/system';-import { createDocumentModel, getDocumentLeaves } from '@workbench/canvas-engine/api';+import { createDocumentModel, getDocumentLayer, getDocumentLeaves } from '@workbench/canvas-engine/api';import {groupContract,layerContract,@@ -407,25 +407,95 @@ describe('Properties pane', () => {expect(page.getByRole('button', { exact: true, name: 'Brush color' }).query()).toBeNull();});- it('labels the shape form with its edit target and gates stroke width on the stroke slot', async () => {- await mount(PropertiesPane);- await act(() => engine!.tools.setTool('shape'));- await settle();- // Nothing selected: the chip says the form edits the creation defaults.- expect(host!.textContent).toContain('Defaults');- await expect.element(page.getByRole('radio', { exact: true, name: 'Rectangle' })).toBeInTheDocument();- await expect.element(page.getByRole('radio', { exact: true, name: 'Triangle' })).toBeInTheDocument();- await expect.element(page.getByRole('radio', { exact: true, name: 'Star' })).toBeInTheDocument();-- await act(() => root?.unmount());+ it('keeps one selected-shape appearance editor in Layer with any active tool', async () => {await mount(PropertiesPane, 'shape');- await act(() => engine!.tools.setTool('shape'));- await settle();- expect(host!.textContent).toContain('Editing: My Shape');- // The fixture shape has no stroke, so the width slider is disabled in place.- const width = page.getByRole('slider', { exact: true, name: 'Stroke width' });- await expect.element(width).toBeVisible();+ const layer = page.getByRole('group', { exact: true, name: 'Layer' });+ const appearance = layer.getByRole('group', { exact: true, name: 'Appearance' });+ for (const tool of ['brush', 'move', 'view', 'shape'] as const) {+ await act(() => engine!.tools.setTool(tool));+ await settle();+ await expect.element(appearance).toBeVisible();+ expect(layer.getByRole('slider', { exact: true, name: 'Stroke width' }).elements()).toHaveLength(1);+ await expect+ .element(appearance.getByRole('slider', { exact: true, name: 'Stroke width' }))+ .toHaveAttribute('aria-disabled', 'true');+ if (tool === 'shape') {+ const defaults = page.getByRole('group', { exact: true, name: 'Tool' });+ await expect.element(defaults.getByText('Defaults', { exact: true })).toBeVisible();+ await expect.element(defaults.getByRole('radiogroup', { name: 'Place on' })).toBeVisible();+ expect(layer.getByRole('radiogroup', { name: 'Kind' }).query()).toBeNull();+ }+ }+ });++ it('edits only the selected shape appearance, with one undo step per gesture', async () => {+ harness.appliesMutations = true;+ await mount(PropertiesPane, 'stroked-shape');+ await act(() => engine!.tools.setTool('view'));+ const optionsBefore = engine!.interaction.get('shapeOptions');+ const colorsBefore = harness.project!.widgetInstances.canvas!.state.values;+ const layer = page.getByRole('group', { exact: true, name: 'Layer' });+ const source = () => {+ const selected = getDocumentLayer(harness.project!.canvas.document, 'l0');+ if (selected?.type !== 'raster' || selected.source.type !== 'shape') {+ throw new Error('Expected selected shape');+ }+ return selected.source;+ };+ const toggle = (name: string) =>+ act(() => layer.element().querySelector<HTMLElement>(`button[aria-label="${name}"][aria-pressed]`)!.click());++ await toggle('Fill');+ expect(source().fill).toBeNull();+ expect(engine!.history.getEntries().past).toHaveLength(1);+ const width = layer.getByRole('slider', { exact: true, name: 'Stroke width' });+ await act(async () => {+ (width.element() as HTMLElement).focus();+ await userEvent.keyboard('{ArrowRight>3/}');+ });+ expect(source().strokeWidth).toBe(7);+ expect(engine!.history.getEntries().past).toHaveLength(2);+ await act(() => engine!.history.undo());+ expect(source().strokeWidth).toBe(4);+ expect(source().fill).toBeNull();+ await toggle('Stroke');+ expect(source().stroke).toBeNull();await expect.element(width).toHaveAttribute('aria-disabled', 'true');+ expect(source().kind).toBe('rect');+ expect(source().width).toBe(10);+ expect(engine!.interaction.get('shapeOptions')).toBe(optionsBefore);+ expect(harness.project!.widgetInstances.canvas!.state.values).toBe(colorsBefore);++ await act(() => operations!.start(true));+ expect(layer.element().hasAttribute('inert')).toBe(true);+ await act(() => operations!.start(false));+ expect(layer.element().hasAttribute('inert')).toBe(false);+ });++ it('drops a selected-shape width scrub when another shape becomes selected', async () => {+ harness.appliesMutations = true;+ const other = layerContract('s2', 'raster', { source: { ...SHAPE_SOURCE, stroke: '#000000', strokeWidth: 2 } });+ await mount(PropertiesPane, 'stroked-shape', { extraNodes: [other] });+ await act(() => engine!.tools.setTool('view'));+ const width = page.getByRole('slider', { exact: true, name: 'Stroke width' });+ const frame = width.element().closest<HTMLElement>('[data-scope="scrubber"]')!;+ const pointer = (target: EventTarget, type: 'pointerdown' | 'pointermove' | 'pointerup', clientX: number) =>+ act(() => target.dispatchEvent(new PointerEvent(type, { bubbles: true, button: 0, clientX })));+ const bounds = frame.getBoundingClientRect();+ await pointer(frame, 'pointerdown', bounds.left + bounds.width * 0.1);+ await pointer(window, 'pointermove', bounds.left + bounds.width * 0.5);+ expect(width.element().getAttribute('aria-valuenow')).not.toBe('4');+ await act(() => {+ harness.project = applyCanvasProjectMutation(harness.project!, { id: 's2', type: 'setCanvasSelectedLayer' });+ harness.listeners.forEach((listener) => listener());+ });+ await pointer(window, 'pointerup', bounds.left + bounds.width * 0.5);+ const first = getDocumentLayer(harness.project!.canvas.document, 'l0');+ const second = getDocumentLayer(harness.project!.canvas.document, 's2');+ expect(first?.type === 'raster' && first.source.type === 'shape' && first.source.strokeWidth).toBe(4);+ expect(second?.type === 'raster' && second.source.type === 'shape' && second.source.strokeWidth).toBe(2);+ expect(engine!.history.getEntries().past).toHaveLength(0);+ await expect.element(width).toHaveAttribute('aria-valuenow', '2');});it('previews the selected text layer above its form and offers style and weight on one row', async () => {@@ -660,7 +730,11 @@ describe('Tool property scrubbers', () => {beforeEach(() => resetPropertyGroupCollapse());afterEach(() => resetPropertyGroupCollapse());- const scrubber = (name: string) => page.getByRole('slider', { exact: true, name }).element() as HTMLElement;+ const scrubber = (name: string, section: 'Tool' | 'Layer' = 'Tool') =>+ page+ .getByRole('group', { exact: true, name: section })+ .getByRole('slider', { exact: true, name })+ .element() as HTMLElement;/** Presses the scrubber at `from` and moves through `to`; the gesture continues with `move` and ends on `release`. */const drag = async (slider: HTMLElement, from: number, ...to: number[]) => {@@ -727,24 +801,24 @@ describe('Tool property scrubbers', () => {['stroked-shape', 'Stroke width', 'shapeOptions'],['gradient', 'Angle', 'gradientOptions'],] as const)(- 'previews every step and commits once per drag or held key (%s, %s)',+ 'shows draft steps and commits once per drag or held key (%s, %s)',async (selection, name, optionsKey) => {await mount(PropertiesPane, selection);await act(() => engine!.tools.setTool(selection === 'stroked-shape' ? 'shape' : selection));await settle();const { commits, previews } = observe(optionsKey);- const slider = scrubber(name);+ const slider = scrubber(name, selection === 'stroked-shape' ? 'Layer' : 'Tool');const gesture = await drag(slider, 0.5, 0.55, 0.6);- expect(previews()).toBe(2);+ expect(previews()).toBe(selection === 'stroked-shape' ? 0 : 2);expect(commits).toHaveLength(0);await gesture.release();expect(commits).toHaveLength(1);- // The settle writes the defaults too; count the key steps from there.+ // Selected shape edits keep creation defaults untouched; other tools also preview in their options.const settled = previews();const releaseKey = await holdKey(slider, 'ArrowRight', 3);- expect(previews() - settled).toBe(3);+ expect(previews() - settled).toBe(selection === 'stroked-shape' ? 0 : 3);expect(commits).toHaveLength(1);await releaseKey();expect(commits).toHaveLength(2);@@ -757,7 +831,7 @@ describe('Tool property scrubbers', () => {await settle();const { committedSources, setLiveSource } = observe('shapeOptions');- const gesture = await drag(scrubber('Stroke width'), 0.5, 0.6);+ const gesture = await drag(scrubber('Stroke width', 'Layer'), 0.5, 0.6);await act(() =>engine!.interaction.set('shapeOptions', { ...engine!.interaction.get('shapeOptions'), kind: 'star' }));diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerSection.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerSection.tsxindex 1cfda91aa1..a0f01ed788 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerSection.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerSection.tsx@@ -4,6 +4,8 @@ import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';import { Stack, Switch, Text } from '@chakra-ui/react';import { getDocumentNode } from '@workbench/canvas-engine/api';import { useCanvasEngine } from '@workbench/canvas-operations/react';+import { SelectedShapeAppearanceSettings } from '@workbench/widgets/canvas/tool-options/ShapeOptions';+import { PropertyGroup } from '@workbench/widgets/canvas/tool-presentation/PropertyPrimitives';import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';import { AdjustmentSettings } from '@workbench/widgets/layers/AdjustmentSettings';import { ControlLayerSettings } from '@workbench/widgets/layers/ControlLayerSettings';@@ -204,6 +206,11 @@ const RasterLayerSettings = ({return (<Stack gap="2">+ {layer.source.type === 'shape' ? (+ <PropertyGroup id="layer-shape-appearance" label={t('widgets.properties.groups.appearance')}>+ <SelectedShapeAppearanceSettings engine={engine} layer={layer} source={layer.source} />+ </PropertyGroup>+ ) : null}<Switch.Root checked={isLocked} onCheckedChange={handleTransparencyLock}><Switch.HiddenInput /><Switch.Control>