Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(canvas): magnify the pixels under the color picker
Josh Corbettfc01bcdf4b00
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.mdindex 6e680f5f63..e409359419 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md@@ -146,6 +146,8 @@ A group surface is keyed by everything except its members' pixels and the float'The overlay renders in CSS pixels. It receives the document→CSS view, the CSS viewport size and the device-pixel ratio, clears the backing store in device pixels, then draws every handle, nub, dash and cursor under a DPR base transform (nested image and path transforms compose with it), so chrome keeps its CSS size at any ratio and matches the CSS-pixel hit tests. The viewport owns the ratio (capped at `MAX_DPR`, sub-one ratios kept) and both the backing-store size and the composite view matrix derive from it.+The color picker shows a loupe of the pixels under the pointer. It is anchored to the pipeline's last pointer position in screen space, so pans and zooms keep it under the pointer, and it shows as soon as the picker activates over a still pointer. Each overlay frame composites the square around that point through the same sampler, providers and coverage rules as a pick, so the magnified center pixel and its RGB readout are exactly what a click picks; the square holds fewer, larger pixels once the canvas zoom passes the loupe's own magnification. Hover chrome (the loupe and the brush ring) leaves the canvas with the pointer unless a gesture still owns it, and input handlers are stable so detach removes every listener attach added.+## Derived surfaces and invalidationEvery display-only pixel effect uses `DerivedSurfaceCache`. A slot is identified by layer ID and effect kind, and guarded by source surface identity, monotonic source version, and a deterministic parameter key. Reuse is safe only when every guard matches. Source replacement therefore cannot publish or reuse a surface produced for an older preview.diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.tsindex d1cf0b1ddf..5206a4c0de 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts@@ -3100,6 +3100,7 @@ const createInputCanvas = (): {element: HTMLCanvasElement;fire: (type: string, event: Partial<PointerEvent>) => void;+ listenerCount: (type: string) => number;surface: StubRasterSurface;} => {const surface = createTestStubRasterBackend().createSurface(width, height);@@ -3125,7 +3126,7 @@ const createInputCanvas = (handler({ preventDefault: () => {}, ...event } as unknown as Event);}};- return { element, fire, surface };+ return { element, fire, listenerCount: (type) => listeners.get(type)?.size ?? 0, surface };};const pointerAt = (x: number, y: number, opts: { button?: number; buttons?: number } = {}): Partial<PointerEvent> => ({@@ -18725,3 +18726,141 @@ describe('document epoch', () => {engine.lifecycle.dispose();});});++describe('color picker loupe', () => {+ const attachPicker = () => {+ const raf = createControllableRaf();+ vi.stubGlobal('requestAnimationFrame', raf.requestFrame);+ vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);+ vi.stubGlobal(+ 'Path2D',+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ );+ const { store } = createReactiveStore(paintDoc());+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ bitmapStore: createSpyBitmapStore(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId: 'p1',+ store,+ });+ const screen = createInputCanvas();+ const overlay = createInputCanvas();+ engine.surface.attach(screen.element, overlay.element);+ raf.flush();+ /** The arcs drawn in the next frame: the loupe's 60 px ring, and any other (the brush ring). */+ const frame = (): { drawn: boolean; loupe: { x: number; y: number } | null; rings: number } => {+ overlay.surface.callLog.length = 0;+ raf.flush();+ const arcs = overlay.surface.callLog.filter((op) => op.op === 'arc');+ const loupe = arcs.find((op) => op.args[2] === 60);+ return {+ drawn: overlay.surface.callLog.length > 0,+ loupe: loupe ? { x: loupe.args[0] as number, y: loupe.args[1] as number } : null,+ rings: arcs.filter((op) => op.args[2] !== 60).length,+ };+ };+ return { engine, frame, overlay, screen };+ };++ it('follows the hovering pointer and leaves the canvas with it', () => {+ const { engine, frame, overlay } = attachPicker();+ engine.tools.setTool('colorPicker');+ overlay.fire('pointerenter', pointerAt(20, 20, { buttons: 0 }));+ overlay.fire('pointermove', pointerAt(20, 20, { buttons: 0 }));+ expect(frame().loupe).toEqual({ x: 20, y: 20 });++ overlay.fire('pointerleave', pointerAt(120, 20, { buttons: 0 }));++ expect(frame()).toMatchObject({ drawn: true, loupe: null });+ engine.lifecycle.dispose();+ });++ it('stays with a pick that is dragged off the canvas', () => {+ const { engine, frame, overlay } = attachPicker();+ engine.tools.setTool('colorPicker');+ overlay.fire('pointerenter', pointerAt(20, 20, { buttons: 0 }));+ overlay.fire('pointerdown', pointerAt(20, 20));+ overlay.fire('pointermove', pointerAt(110, 20));+ overlay.fire('pointerleave', pointerAt(110, 20));++ expect(frame().loupe).toEqual({ x: 110, y: 20 });+ overlay.fire('pointerup', pointerAt(110, 20, { buttons: 0 }));+ engine.lifecycle.dispose();+ });++ it('appears at a still pointer when a pick request arms the picker', () => {+ const { engine, frame, overlay } = attachPicker();+ engine.tools.setTool('brush');+ overlay.fire('pointerenter', pointerAt(30, 40, { buttons: 0 }));+ overlay.fire('pointermove', pointerAt(30, 40, { buttons: 0 }));+ frame();++ void engine.tools.requestColorSample();++ expect(frame().loupe).toEqual({ x: 30, y: 40 });+ engine.lifecycle.dispose();+ });++ it('stays under the pointer while the canvas zooms around it', () => {+ const { engine, frame, overlay } = attachPicker();+ engine.tools.setTool('colorPicker');+ overlay.fire('pointerenter', pointerAt(20, 20, { buttons: 0 }));+ overlay.fire('pointermove', pointerAt(20, 20, { buttons: 0 }));+ frame();++ engine.viewport.getViewport().zoomAtPoint(4, { x: 70, y: 70 });++ expect(frame().loupe).toEqual({ x: 20, y: 20 });+ engine.lifecycle.dispose();+ });++ it('is gone once another tool takes over', () => {+ const { engine, frame, overlay } = attachPicker();+ engine.tools.setTool('colorPicker');+ overlay.fire('pointerenter', pointerAt(20, 20, { buttons: 0 }));+ overlay.fire('pointermove', pointerAt(20, 20, { buttons: 0 }));+ frame();++ engine.tools.setTool('view');++ expect(frame().loupe).toBeNull();+ engine.lifecycle.dispose();+ });++ it('takes the brush ring off the canvas on leave, but not during a stroke', () => {+ const { engine, frame, overlay } = attachPicker();+ engine.tools.setTool('brush');+ overlay.fire('pointerenter', pointerAt(20, 20, { buttons: 0 }));+ overlay.fire('pointermove', pointerAt(20, 20, { buttons: 0 }));+ expect(frame().rings).toBeGreaterThan(0);+ overlay.fire('pointerleave', pointerAt(120, 20, { buttons: 0 }));+ expect(frame().rings).toBe(0);++ overlay.fire('pointerenter', pointerAt(20, 20, { buttons: 0 }));+ overlay.fire('pointerdown', pointerAt(20, 20));+ overlay.fire('pointermove', pointerAt(60, 20));+ overlay.fire('pointerleave', pointerAt(60, 20));+ expect(frame().rings).toBeGreaterThan(0);+ overlay.fire('pointerup', pointerAt(60, 20, { buttons: 0 }));+ engine.lifecycle.dispose();+ });++ it('removes on detach every listener attach added, across re-attaching', () => {+ const { engine, overlay, screen } = attachPicker();++ engine.surface.detach();+ engine.surface.attach(screen.element, overlay.element);+ engine.surface.detach();++ for (const type of ['pointerdown', 'pointermove', 'pointerup', 'pointerleave', 'pointerenter', 'wheel']) {+ expect(overlay.listenerCount(type), type).toBe(0);+ }+ 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 b056556d49..9b34c76666 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -81,6 +81,7 @@ import type {CanvasLayerSourceContract,} from '@workbench/canvas-engine/contracts';import type { CreatePath2D } from '@workbench/canvas-engine/freehand';+import type { ColorSampleProviders, ColorSampler } from '@workbench/canvas-engine/render/colorSample';import type { CanvasFontRuntime, CanvasTextSource, FontLoadApi } from '@workbench/canvas-engine/render/fontLoader';import type { LayerCacheEntry, LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import type { OverlayCursor } from '@workbench/canvas-engine/render/overlayRenderer';@@ -141,6 +142,7 @@ import {import { createPointerPipeline, type PointerPipeline } from '@workbench/canvas-engine/input/pointerPipeline';import { createWheelHandler } from '@workbench/canvas-engine/input/wheel';import { isEmpty, union } from '@workbench/canvas-engine/math/rect';+import { createColorSampler } from '@workbench/canvas-engine/render/colorSample';import {compositeDocument,createCheckerboardTile,@@ -149,7 +151,7 @@ import {import { createFontLoader, domFontLoadApi } from '@workbench/canvas-engine/render/fontLoader';import { hasLayerDisplayEffect } from '@workbench/canvas-engine/render/layerDisplayEffect';import { createMaskPatternTile } from '@workbench/canvas-engine/render/maskFill';-import { renderOverlay } from '@workbench/canvas-engine/render/overlayRenderer';+import { colorLoupePixels, renderOverlay } from '@workbench/canvas-engine/render/overlayRenderer';import { trimPaintCacheToAlpha } from '@workbench/canvas-engine/render/paintCacheTrim';import { createDomRasterBackend, type RasterBackend, type RasterSurface } from '@workbench/canvas-engine/render/raster';import { rasterizeSource, type ImageResolver, type RasterizeDeps } from '@workbench/canvas-engine/render/rasterizers';@@ -434,6 +436,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC// The brush/eraser cursor ring, drawn on the overlay (set by the active tool).let overlayCursor: OverlayCursor | null = null;+ /** Whether the color picker wants its loupe; it sits at the pointer and is sampled when the overlay frame draws. */+ let colorLoupeShown = false;+ let colorLoupeSampler: ColorSampler | null = null;// Lazy checker tile reused until checker colors change, when the subscription clears it.let checkerboardTile: RasterSurface | null = null;@@ -464,6 +469,12 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst groupSurfaces = rasterController.groups;const getGroupSurface: NonNullable<CompositeOptions['groupSurface']> = (scope, members, matrices, content) =>groupSurfaces.get(scope, members, matrices, content);+ /** Picking and the picker's loupe see the same adjusted, derived and grouped pixels as the display. */+ const colorSampleProviders: ColorSampleProviders = {+ adjustedSurface: getAdjustedSurface,+ derivedSurfaces: derivedSurfaceCache,+ groupSurface: getGroupSurface,+ };// Completed-stroke subscribers (persistence P2.2, history P2.3).const strokeListeners = new Set<(event: StrokeCommittedEvent) => void>();@@ -1011,11 +1022,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCgetSamInteraction: () => stores.samInteraction.get(),openTextCreate: (docPoint) => openTextCreate(docPoint),openTextEdit: (layerId) => openTextEdit(layerId),- sampleProviders: {- adjustedSurface: getAdjustedSurface,- derivedSurfaces: derivedSurfaceCache,- groupSurface: getGroupSurface,- },+ sampleProviders: colorSampleProviders,resolveColorSample: (hex) => {if (pendingColorSample) {pendingColorSample.sampledHex = hex;@@ -1044,6 +1051,10 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCsetOverlayCursor: (cursor) => {overlayCursor = cursor;},+ showColorLoupe: (shown) => {+ colorLoupeShown = shown;+ scheduler.invalidate({ overlay: true });+ },stores,updateCursor: () => updateCursor(),updateSamInput: (input) => samInputHandler?.(input),@@ -1068,6 +1079,22 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCapplyCursorToInput(cursor);};+ /**+ * A pointer that left the canvas takes its hover chrome along, unless a gesture still owns it; the loupe follows+ * the pipeline's hover point, which leaves with it.+ */+ const onCanvasPointerLeave = (): void => {+ pipeline.onPointerLeave();+ if (!pipeline.isGestureActive()) {+ overlayCursor = null;+ scheduler.invalidate({ overlay: true });+ }+ };+ const resetInput = (): void => {+ pipeline.reset();+ overlayCursor = null;+ };+/** Size changes without pointer events update the cursor radius at its last center and invalidate the overlay. */const refreshBrushCursorRadius = (): void => {if (!overlayCursor) {@@ -1333,7 +1360,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst renderController = new RenderController({applyCursor: (value) => applyCursorToInput(value),clearPreview: () => clearStagedPreview(),- getInputHandlers: () => ({ ...pipeline, onWheel, reset: () => pipeline.reset() }),+ // Stable handlers: detach removes exactly the listeners attach added.+ getInputHandlers: () => ({ ...pipeline, onPointerLeave: onCanvasPointerLeave, onWheel, reset: resetInput }),isEngineDisposed: () => disposed,onPageHide: () => onPageHide(),onVisibilityChange: () => onVisibilityChange(),@@ -1367,6 +1395,17 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCgetAntsPhase: () => antsPhase,getSamPulseTime: () => (samPulseActive() ? nowMs() : null),getFloatingSelection: () => floatingSelection.get(),+ getColorLoupe: (doc) => {+ const screenPoint = colorLoupeShown ? pipeline.hoverPoint() : null;+ if (!screenPoint) {+ return null;+ }+ const point = viewport.screenToDocument(screenPoint);+ colorLoupeSampler ??= createColorSampler(backend);+ const size = colorLoupePixels(viewport.getZoom());+ const area = colorLoupeSampler.sampleArea(doc, layerCache, point, size, colorSampleProviders);+ return area ? { checker: getCheckerboardTile(), color: area.center, pixels: area.pixels, point } : null;+ },getOverlayCursor: () => overlayCursor,selection,stores,@@ -1812,7 +1851,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC}};const onWindowBlur = (): void => {- pipeline.reset();+ resetInput();+ scheduler.invalidate({ overlay: true });};const clearSamPreview = (): void => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.tsindex e927906f1a..d969d0bbf5 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.ts@@ -66,6 +66,11 @@ export interface PointerPipeline {onFocusIn(event: FocusEvent): void;/** Primary gesture state blocks undo/redo from injecting pixels during live strokes. */isGestureActive(): boolean;+ /**+ * Where the pointer last moved over the canvas, in CSS pixels, including moves a middle-button pan consumes; null+ * once it left (outside a gesture) or the pipeline reset.+ */+ hoverPoint(): Vec2 | null;/*** Cancels capture/tool state and refreshes the cursor. Used on document replacement so a later release cannot* commit stale drag state; idle calls do nothing.@@ -160,6 +165,7 @@ const isDocumentRootTarget = (target: EventTarget | null): boolean => {/** Creates a pointer pipeline bound to the engine's injected deps. */export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipeline => {let hovered = false;+ let hoverPoint: Vec2 | null = null;// Primary-button paint/drag gesture in progress.let gestureActive = false;let activePointerId: number | null = null;@@ -201,8 +207,7 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelin};};- const buildBatch = (event: PointerEvent): PointerInput[] => {- const origin = inputOrigin();+ const buildBatch = (event: PointerEvent, origin = inputOrigin()): PointerInput[] => {const coalesced = event.getCoalescedEvents?.();if (coalesced && coalesced.length > 0) {return coalesced.map((sample) => buildPointerInput(sample, origin));@@ -405,6 +410,7 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelinbeginBboxTempTool();}},+ hoverPoint: () => hoverPoint,isGestureActive: () => gestureActive,onFocusIn: (event) => {pointerFocused = event.target && arrivedByPointer(event.target) ? new WeakRef(event.target) : null;@@ -474,14 +480,19 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelin},onPointerLeave: () => {hovered = false;+ if (!gestureActive) {+ hoverPoint = null;+ }},onPointerMove: (event) => {// Ignore move events from a pointer other than the one driving the active gesture/pan.if (activePointerId !== null && event.pointerId !== activePointerId) {return;}+ const origin = inputOrigin();+ hoverPoint = { x: event.clientX - origin.left, y: event.clientY - origin.top };if (middlePanning && middleLast) {- const screenPoint = buildPointerInput(event).screenPoint;+ const screenPoint = hoverPoint;deps.viewport.panBy({ x: screenPoint.x - middleLast.x, y: screenPoint.y - middleLast.y });middleLast = screenPoint;return;@@ -492,7 +503,9 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelinif (cancelledPointerId === event.pointerId && !cancelledPress) {cancelledPointerId = null;}- const batch = cancelledPress ? buildBatch(event).map((input) => ({ ...input, buttons: 0 })) : buildBatch(event);+ const batch = cancelledPress+ ? buildBatch(event, origin).map((input) => ({ ...input, buttons: 0 }))+ : buildBatch(event, origin);const last = batch[batch.length - 1];if (!last) {return;@@ -538,6 +551,7 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelin}clearBboxTapTimer();hovered = false;+ hoverPoint = null;gestureActive = false;activePointerId = null;cancelledPointerId = null;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.browser.test.tsindex 92b52f3d64..f9e587d9a3 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.browser.test.ts@@ -64,4 +64,27 @@ describe('color sampling with real browser rasterization', () => {expect([...viewport.ctx.getImageData(20, 0, 1, 1).data]).toEqual(EXPECTED_PIXEL);expect(createColorSampler(backend).sample(doc, caches, { x: 20, y: 0 })).toEqual(EXPECTED_COLOR);});++ it('samples the square around a pixel with the pick at its center and empty canvas transparent', () => {+ const backend = createDomRasterBackend();+ const caches = createLayerCacheStore(backend);+ const entry = caches.getOrCreate('far-layer', 8, 8);+ entry.surface.ctx.fillStyle = '#ef1234';+ entry.surface.ctx.fillRect(0, 0, 4, 8);+ entry.surface.ctx.fillStyle = '#1234ef';+ entry.surface.ctx.fillRect(4, 0, 4, 8);+ caches.publishPixels('far-layer');+ const doc = documentWith(layer(0));+ const sampler = createColorSampler(backend);++ const area = sampler.sampleArea(doc, caches, { x: 3.5, y: 0.5 }, 5)!;++ expect(area.center).toEqual(sampler.sample(doc, caches, { x: 3.5, y: 0.5 }));+ expect(area.center).toEqual(EXPECTED_COLOR);+ const pixel = (x: number, y: number) => [...area.pixels.ctx.getImageData(x, y, 1, 1).data];+ // The area spans document x 1..5 and y -2..2: red up to x 3, blue from x 4, nothing above the layer.+ expect(pixel(2, 2)).toEqual(EXPECTED_PIXEL);+ expect(pixel(3, 2)).toEqual([18, 52, 239, 255]);+ expect(pixel(2, 0)).toEqual([0, 0, 0, 0]);+ });});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.tsindex b803f2ca0e..a4dcafe3be 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.ts@@ -1,6 +1,7 @@/**- * Samples composited layer pixels into a translated 1x1 scratch using normal ordering and display effects.- * Excludes background/checkerboard and staged previews so uncovered points return null.+ * Samples composited layer pixels into a translated scratch (1x1 for a pick, a small square for the picker's loupe)+ * using normal ordering and display effects. Excludes background/checkerboard and staged previews so uncovered points+ * return null.*/import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';@@ -23,6 +24,13 @@ export type ColorSampleProviders = Pick<CompositeOptions, 'adjustedSurface' | 'dconst RAW_PIXELS: ColorSampleProviders = {};+/** A square of composited document pixels centered on a sampled pixel. */+export interface ColorSampleArea {+ /** `size`×`size` pixels; the sampled pixel is the center one. Reused by the next area sample. */+ readonly pixels: RasterSurface;+ readonly center: RgbaSample | null;+}+export interface ColorSampler {/*** Floors document coordinates to a pixel; transformed content remains pickable outside document dimensions.@@ -35,53 +43,83 @@ export interface ColorSampler {docPoint: Vec2,providers?: ColorSampleProviders): RgbaSample | null;+ /** The pixels around `docPoint` (odd `size`), with the same coverage rules and reuse as {@link sample}. */+ sampleArea(+ doc: CanvasDocumentContractV3,+ layers: LayerCacheStore,+ docPoint: Vec2,+ size: number,+ providers?: ColorSampleProviders+ ): ColorSampleArea | null;}+const sampleAt = (data: Uint8ClampedArray, offset: number): RgbaSample | null => {+ const alpha = data[offset + 3] ?? 0;+ return alpha === 0 ? null : { a: alpha, b: data[offset + 2] ?? 0, g: data[offset + 1] ?? 0, r: data[offset] ?? 0 };+};+/** A sampler that keeps its scratch, draw plan and last sample across a picking gesture. */export const createColorSampler = (backend: RasterBackend): ColorSampler => {- let scratch: RasterSurface | null = null;let preparation: CompositePreparation | null = null;- let last: {+ const scratches = new Map<number, RasterSurface>();+ interface Last {doc: CanvasDocumentContractV3;layers: LayerCacheStore;revision: number;providers: ColorSampleProviders;px: number;py: number;- result: RgbaSample | null;- } | null = null;+ area: ColorSampleArea;+ }+ const lastBySize = new Map<number, Last>();- return {- sample: (doc, layers, docPoint, providers = RAW_PIXELS) => {- const px = Math.floor(docPoint.x);- const py = Math.floor(docPoint.y);- if (!Number.isFinite(px) || !Number.isFinite(py)) {- return null;- }- const revision = layers.revision();- if (- last?.doc === doc &&- last.layers === layers &&- last.revision === revision &&- last.providers === providers &&- last.px === px &&- last.py === py- ) {- return last.result;- }+ /** Composites the `size`-square around a pixel; the canonical compositor keeps placement and display effects. */+ const composite = (+ doc: CanvasDocumentContractV3,+ layers: LayerCacheStore,+ docPoint: Vec2,+ size: number,+ providers: ColorSampleProviders+ ): ColorSampleArea | null => {+ const px = Math.floor(docPoint.x);+ const py = Math.floor(docPoint.y);+ if (!Number.isFinite(px) || !Number.isFinite(py)) {+ return null;+ }+ const revision = layers.revision();+ const last = lastBySize.get(size);+ if (+ last?.doc === doc &&+ last.layers === layers &&+ last.revision === revision &&+ last.providers === providers &&+ last.px === px &&+ last.py === py+ ) {+ return last.area;+ }- scratch ??= backend.createSurface(1, 1);- preparation = reusePreparation(preparation, doc, { backend, ...providers });- const view: Mat2d = { a: 1, b: 0, c: 0, d: 1, e: -px, f: -py };- // Use canonical compositing for placement and display effects, omitting checkerboard/staged previews to- // retain transparent empty space.- compositeDocument(scratch, doc, layers, view, { backend, ...providers, preparation });+ let scratch = scratches.get(size);+ if (!scratch) {+ scratch = backend.createSurface(size, size);+ scratches.set(size, scratch);+ }+ const half = (size - 1) / 2;+ preparation = reusePreparation(preparation, doc, { backend, ...providers });+ const view: Mat2d = { a: 1, b: 0, c: 0, d: 1, e: half - px, f: half - py };+ // Omitting checkerboard and staged previews keeps empty space transparent.+ compositeDocument(scratch, doc, layers, view, { backend, ...providers, preparation });- const { data } = scratch.ctx.getImageData(0, 0, 1, 1);- const alpha = data[3] ?? 0;- const result = alpha === 0 ? null : { a: alpha, b: data[2] ?? 0, g: data[1] ?? 0, r: data[0] ?? 0 };- last = { doc, layers, providers, px, py, result, revision };- return result;- },+ const { data } = scratch.ctx.getImageData(half, half, 1, 1);+ const area: ColorSampleArea = { center: sampleAt(data, 0), pixels: scratch };+ lastBySize.set(size, { area, doc, layers, providers, px, py, revision });+ return area;+ };++ return {+ sample: (doc, layers, docPoint, providers = RAW_PIXELS) =>+ composite(doc, layers, docPoint, 1, providers)?.center ?? null,+ sampleArea: (doc, layers, docPoint, size, providers = RAW_PIXELS) =>+ composite(doc, layers, docPoint, Math.max(1, Math.floor(size / 2) * 2 + 1), providers),};};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.test.tsindex 6c17290e5f..e812a9e226 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.test.ts@@ -60,6 +60,7 @@ const makeHarness = (): Harness => {deps: {getActiveToolId: () => state.tool,getAntsPhase: () => state.phase,+ getColorLoupe: () => null,getSamPulseTime: () => state.pulseTime,getFloatingSelection: () => float.value,getOverlayCursor: () => state.cursor,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.tsindex 17c2a8f340..f49fe00d3c 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.ts@@ -2,6 +2,7 @@ import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/cimport type { SamPreviewState } from '@workbench/canvas-engine/controllers/previewStateController';import type { EngineStores } from '@workbench/canvas-engine/engineStores';import type {+ ColorLoupeOverlay,OverlayCursor,OverlayState,TransformFrameOverlay,@@ -42,6 +43,8 @@ export interface CreateOverlayFrameDeps {readonly getActiveToolId: () => ToolId;readonly getFloatingSelection: () => FloatingSelection | null;readonly getOverlayCursor: () => OverlayCursor | null;+ /** The picker's loupe over `doc`, sampled for this frame, or null while hidden. */+ readonly getColorLoupe: (doc: CanvasDocumentContractV3) => ColorLoupeOverlay | null;readonly getAntsPhase: () => number;/** The clock while the SAM pulse animates, `null` for the static opacity (reduced motion, no preview). */readonly getSamPulseTime: () => number | null;@@ -144,6 +147,7 @@ export const createOverlayFrame = (deps: CreateOverlayFrameDeps): OverlayFrame =bboxOverlay: stores.bboxOverlay.get(),// The checker's darker square is the theme's canvas surround (`bg.inset`).bboxOverlayColor: stores.checkerColors.get().a,+ colorLoupe: deps.getColorLoupe(doc),cursor: deps.getOverlayCursor(),gradientPreview: stores.gradientPreview.get(),// Grid spans the viewport at bbox snap size, independent of document bounds.diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.browser.test.tsindex 431836f95f..3868a758f1 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.browser.test.ts@@ -5,7 +5,8 @@ import { transformOverlayGeometry, transformTargetAt } from '@workbench/canvas-eimport { createViewport } from '@workbench/canvas-engine/viewport';import { describe, expect, it } from 'vitest';-import { renderOverlay } from './overlayRenderer';+import { createCheckerboardTile } from './compositor';+import { colorLoupePixels, renderOverlay } from './overlayRenderer';const CSS_SIZE = 200;const RECT = { height: 50, width: 50, x: 50, y: 50 };@@ -102,3 +103,71 @@ describe('overlay chrome across device-pixel ratios', () => {}});});++describe('color picker loupe', () => {+ const RED = [239, 18, 52, 255];+ const GREEN = [18, 200, 52, 255];+ const CHECKER = createCheckerboardTile(createDomRasterBackend(), { a: '#101010', b: '#202020' });++ /** A square of `size` pixels: red, transparent on the left two columns, green at the sampled center. */+ const loupePixels = (size: number) => {+ const pixels = createDomRasterBackend().createSurface(size, size);+ pixels.ctx.fillStyle = 'rgb(239, 18, 52)';+ pixels.ctx.fillRect(2, 0, size - 2, size);+ pixels.ctx.fillStyle = 'rgb(18, 200, 52)';+ pixels.ctx.fillRect((size - 1) / 2, (size - 1) / 2, 1, 1);+ return pixels;+ };++ const renderLoupe = (dpr: number, color: { r: number; g: number; b: number; a: number } | null, size = 15) => {+ const viewport = createViewport();+ viewport.setViewportSize(CSS_SIZE, CSS_SIZE, dpr);+ const target = createDomRasterBackend().createSurface(+ Math.round(CSS_SIZE * viewport.getDpr()),+ Math.round(CSS_SIZE * viewport.getDpr())+ );+ renderOverlay(target, {+ bbox: { height: 0, width: 0, x: -1000, y: -1000 },+ colorLoupe: {+ checker: CHECKER,+ color,+ pixels: loupePixels(size),+ point: viewport.screenToDocument({ x: 100, y: 100 }),+ },+ dpr: viewport.getDpr(),+ showBbox: false,+ view: viewport.viewMatrix(1),+ viewportSize: viewport.getViewportSize(),+ });+ return (x: number, y: number) => [...target.ctx.getImageData(Math.round(x * dpr), Math.round(y * dpr), 1, 1).data];+ };++ it.each([1, 2])('magnifies the pixels around the pointer without smoothing at %sx', (dpr) => {+ const at = renderLoupe(dpr, null);++ // The sampled pixel fills the 8 px cell under the pointer; its neighbours fill the next cells.+ expect(at(100, 100)).toEqual(GREEN);+ expect(at(110, 100)).toEqual(RED);+ expect(at(90, 90)).toEqual(RED);+ // Empty pixels show the checker, and nothing is drawn beyond the 60 px ring.+ expect([+ [16, 16, 16, 255],+ [32, 32, 32, 255],+ ]).toContainEqual(at(46, 100));+ expect(at(100, 166)).toEqual([0, 0, 0, 0]);+ });++ it('shows fewer, larger pixels as the canvas zooms past the loupe', () => {+ expect([0.25, 1, 4, 8, 20].map(colorLoupePixels)).toEqual([15, 15, 15, 7, 3]);+ const at = renderLoupe(1, null, 7);++ // Seven pixels span 120 px, so the sampled one covers about 17 px around the pointer (boxed at its edge).+ expect(at(105, 100)).toEqual(GREEN);+ expect(at(112, 100)).toEqual(RED);+ });++ it('labels the sampled color below the center, and shows no label over empty canvas', () => {+ expect(renderLoupe(1, null)(100, 125)).toEqual(RED);+ expect(renderLoupe(1, { a: 255, b: 52, g: 200, r: 18 })(100, 125)).not.toEqual(RED);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.tsindex 804b4a20ee..a458bd5d4e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.ts@@ -14,6 +14,7 @@ import { drawMarchingAnts, type MarchingAntsRender } from '@workbench/canvas-engimport { BBOX_HANDLES, bboxHandlePoint } from '@workbench/canvas-engine/tools/bboxHitTest';import { TRANSFORM_ROTATE_NUB_PX } from '@workbench/canvas-engine/transform/transformMath';+import type { RgbaSample } from './colorSample';import type { RasterSurface } from './raster';/** Minimum screen-space grid spacing (px) below which the grid is too dense to draw. */@@ -49,6 +50,33 @@ export interface OverlayCursor {radiusDoc: number;}+/** The color picker's loupe diameter in CSS pixels. */+const COLOR_LOUPE_DIAMETER_PX = 120;+/** Each magnified pixel spans at least this many CSS pixels, and twice the canvas zoom. */+const COLOR_LOUPE_MIN_CELL_PX = 8;+const COLOR_LOUPE_RING = '#d4d4d4';+const COLOR_LOUPE_LABEL_FONT = '600 11px ui-monospace, SFMono-Regular, Menlo, monospace';+const COLOR_LOUPE_LABEL_FILL = 'rgba(0, 0, 0, 0.72)';++/** Document pixels across the loupe at `zoom`: odd, so the sampled one sits at the center, and at least three. */+export const colorLoupePixels = (zoom: number): number => {+ const cell = Math.max(COLOR_LOUPE_MIN_CELL_PX, zoom * 2);+ const count = Math.floor(COLOR_LOUPE_DIAMETER_PX / cell);+ return Math.max(3, count % 2 === 0 ? count - 1 : count);+};++/** The color picker's magnified view of the pixels under the pointer. */+export interface ColorLoupeOverlay {+ /** The pointer in document space; the loupe is centered on it. */+ point: Vec2;+ /** A square of document pixels around the sampled one, which is the center pixel. */+ pixels: RasterSurface;+ /** The sampled color, or null over empty canvas. */+ color: RgbaSample | null;+ /** The canvas checkerboard tile, shown where the canvas is empty. */+ checker: RasterSurface;+}+/** A live parametric-shape drag outline in document space (shape and marquee tools). */export interface RectShapePreview {rect: Rect;@@ -81,6 +109,8 @@ export interface OverlayState {gridSize?: number;/** Brush cursor ring, or `null`/absent to hide it. */cursor?: OverlayCursor | null;+ /** The color picker's loupe, or `null`/absent to hide it. */+ colorLoupe?: ColorLoupeOverlay | null;/** Move outline uses four document-space content corners projected through view; null/absence hides it. */layerOutline?: readonly Vec2[] | null;/**@@ -216,6 +246,74 @@ const drawCursor = (ctx: Ctx, state: OverlayState): void => {ctx.restore();};+/** Strokes the current path dark-then-light so it reads over any pixels. */+const strokeOutlined = (ctx: Ctx, light: string, lightWidth: number): void => {+ ctx.strokeStyle = CURSOR_DARK;+ ctx.lineWidth = lightWidth + 2;+ ctx.stroke();+ ctx.strokeStyle = light;+ ctx.lineWidth = lightWidth;+ ctx.stroke();+};++/**+ * Draws the picker's loupe: the pixels around the pointer magnified without smoothing inside a ring, the sampled+ * center pixel boxed under the crosshair cursor, and its RGB values below.+ */+const drawColorLoupe = (ctx: Ctx, state: OverlayState): void => {+ const loupe = state.colorLoupe;+ if (!loupe) {+ return;+ }+ const point = applyToPoint(state.view, loupe.point);+ // Whole device pixels keep the magnified cells crisp.+ const center = { x: Math.round(point.x * state.dpr) / state.dpr, y: Math.round(point.y * state.dpr) / state.dpr };+ const radius = COLOR_LOUPE_DIAMETER_PX / 2;+ const cell = COLOR_LOUPE_DIAMETER_PX / loupe.pixels.width;+ ctx.save();+ ctx.setLineDash([]);+ ctx.beginPath();+ ctx.arc(center.x, center.y, radius, 0, Math.PI * 2);+ ctx.clip();+ const checker = ctx.createPattern(loupe.checker.canvas, 'repeat');+ if (checker) {+ ctx.fillStyle = checker;+ ctx.fillRect(center.x - radius, center.y - radius, radius * 2, radius * 2);+ }+ ctx.imageSmoothingEnabled = false;+ ctx.drawImage(loupe.pixels.canvas, center.x - radius, center.y - radius, radius * 2, radius * 2);+ ctx.restore();++ ctx.save();+ ctx.setLineDash([]);+ ctx.beginPath();+ ctx.rect(center.x - cell / 2, center.y - cell / 2, cell, cell);+ strokeOutlined(ctx, CURSOR_LIGHT, 1);+ ctx.beginPath();+ ctx.arc(center.x, center.y, radius, 0, Math.PI * 2);+ strokeOutlined(ctx, COLOR_LOUPE_RING, 2);++ if (loupe.color) {+ const label = `${loupe.color.r} ${loupe.color.g} ${loupe.color.b}`;+ ctx.font = COLOR_LOUPE_LABEL_FONT;+ ctx.textAlign = 'center';+ ctx.textBaseline = 'middle';+ const width = ctx.measureText(label).width + 12;+ const height = 18;+ const labelY = center.y + cell / 2 + 12 + height / 2;+ const end = height / 2;+ ctx.beginPath();+ ctx.arc(center.x - width / 2 + end, labelY, end, Math.PI / 2, (Math.PI * 3) / 2);+ ctx.arc(center.x + width / 2 - end, labelY, end, -Math.PI / 2, Math.PI / 2);+ ctx.closePath();+ ctx.fillStyle = COLOR_LOUPE_LABEL_FILL;+ ctx.fill();+ ctx.fillStyle = CURSOR_LIGHT;+ ctx.fillText(label, center.x, labelY);+ }+ ctx.restore();+};+/** Draws a layer's rendered-bounds outline as a closed polygon in screen space. */const drawLayerOutline = (ctx: Ctx, state: OverlayState): void => {const corners = state.layerOutline;@@ -565,6 +663,7 @@ export const renderOverlay = (target: RasterSurface, state: OverlayState): voiddrawRectShapePreview(ctx, state, state.shapePreview);drawGradientPreview(ctx, state);drawCursor(ctx, state);+ drawColorLoupe(ctx, state);ctx.restore();};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.test.tsindex b8e10cdba3..cd1572e29c 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.test.ts@@ -81,7 +81,7 @@ interface Harness {layers: LayerCacheStore;dispatched: CanvasProjectMutation[];strokes: unknown[];- overlayCursors: unknown[];+ loupes: unknown[];}const createHarness = (doc: CanvasDocumentContractV3 | null): Harness => {@@ -94,7 +94,7 @@ const createHarness = (doc: CanvasDocumentContractV3 | null): Harness => {const stores = createEngineStores();const dispatched: CanvasProjectMutation[] = [];const strokes: unknown[] = [];- const overlayCursors: unknown[] = [];+ const loupes: unknown[] = [];const ctx: ToolContext = {scheduleFrame: () => () => undefined,@@ -113,13 +113,14 @@ const createHarness = (doc: CanvasDocumentContractV3 | null): Harness => {layers,notifyLayerPainted: vi.fn(),setLayerTransformOverride: vi.fn(),- setOverlayCursor: (cursor) => overlayCursors.push(cursor),+ showColorLoupe: (shown) => loupes.push(shown),+ setOverlayCursor: vi.fn(),stores,updateCursor: vi.fn(),viewport: { getZoom: () => 1 } as unknown as ToolContext['viewport'],};- return { ctx, dispatched, layers, overlayCursors, pixel, strokes };+ return { ctx, dispatched, layers, loupes, pixel, strokes };};const down = (t: Tool, ctx: ToolContext, i: PointerInput): void => t.onPointerDown?.(ctx, i);@@ -233,15 +234,18 @@ describe('color picker tool', () => {expect(h.strokes).toHaveLength(0);});- it('shows a ring cursor while active and clears it on deactivate', () => {+ it('shows the loupe on activation and while the pointer moves, and hides it on deactivate', () => {const h = createHarness(makeDoc());const tool = createColorPickerTool();+ tool.onActivate?.(h.ctx);+ expect(h.loupes).toEqual([true]);move(tool, h.ctx, pointer(10, 10, { buttons: 0 }));- expect(h.overlayCursors.at(-1)).toMatchObject({ point: { x: 10, y: 10 } });+ down(tool, h.ctx, pointer(12, 11));+ expect(h.loupes.at(-1)).toBe(true);tool.onDeactivate?.(h.ctx);- expect(h.overlayCursors.at(-1)).toBeNull();+ expect(h.loupes.at(-1)).toBe(false);});it('reports a crosshair cursor', () => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.tsindex eda32c19cd..5e6837db60 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.ts@@ -1,6 +1,7 @@/**- * Samples composited cached color while pressed and routes it to the active color target. Alt-hold restoration- * returns to the prior tool; the picker neither dispatches nor edits pixels. State is per engine.+ * Shows a loupe of the composited pixels under the pointer, samples while pressed and routes the color to the active+ * color target. Alt-hold restoration returns to the prior tool; the picker neither dispatches nor edits pixels.+ * State is per engine.*/import type { PointerInput } from '@workbench/canvas-engine/types';@@ -13,13 +14,9 @@ import type { Tool, ToolContext } from './tool';/** Bit for the primary (usually left) mouse button in `PointerEvent.buttons`. */const PRIMARY_BUTTON = 1;-/** Fixed on-screen radius (px) for the picker's ring cursor, independent of zoom. */-const CURSOR_SCREEN_RADIUS_PX = 8;--const updateCursorRing = (ctx: ToolContext, input: PointerInput): void => {- const zoom = ctx.viewport.getZoom();- ctx.setOverlayCursor({ point: input.documentPoint, radiusDoc: CURSOR_SCREEN_RADIUS_PX / Math.max(zoom, 1e-6) });- ctx.invalidate({ overlay: true });+/** The loupe follows the pointer, hovering or pressed; the engine samples it once per overlay frame. */+const updateLoupe = (ctx: ToolContext): void => {+ ctx.showColorLoupe?.(true);};/** Offers sampled color to the one-shot claim then workbench router; standalone fallback updates brush color. */@@ -53,9 +50,10 @@ export const createColorPickerTool = (): Tool => {return {cursor: () => 'crosshair',id: 'colorPicker',+ // A pointer already over the canvas (an Alt hold, a pick request) gets the loupe without moving.+ onActivate: (ctx) => updateLoupe(ctx),onDeactivate: (ctx) => {- ctx.setOverlayCursor(null);- ctx.invalidate({ overlay: true });+ ctx.showColorLoupe?.(false);},onPointerCancel: (ctx) => {ctx.discardColorSample?.();@@ -65,17 +63,17 @@ export const createColorPickerTool = (): Tool => {return;}ctx.discardColorSample?.();- updateCursorRing(ctx, input);+ updateLoupe(ctx);pick(ctx, input);},onPointerMove: (ctx, input) => {- updateCursorRing(ctx, input);+ updateLoupe(ctx);if (input.buttons & PRIMARY_BUTTON) {pick(ctx, input);}},- onPointerUp: (ctx, input) => {- updateCursorRing(ctx, input);+ onPointerUp: (ctx) => {+ updateLoupe(ctx);ctx.commitColorSample?.();},};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.tsindex 57474b9d29..7e545b3c66 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts@@ -132,6 +132,8 @@ export interface ToolContext {getSamInteraction?(): SamInteractionState | null;/** Sets (or clears) the brush cursor ring drawn on the overlay. */setOverlayCursor(cursor: OverlayCursor | null): void;+ /** Shows or hides the color picker's loupe, which follows the pointer while shown; optional in test harnesses. */+ showColorLoupe?(shown: boolean): void;/*** Route samples to one-shot claim, then persistent workbench target. Return whether consumed; otherwise picker* falls back to brush color. Optional in test harnesses.