diff --git a/site/package.json b/site/package.json index 8cab54b..d6502de 100644 --- a/site/package.json +++ b/site/package.json @@ -7,7 +7,8 @@ "dev": "astro dev", "build": "astro check && astro build", "preview": "astro preview", - "capture": "node scripts/capture-screenshots.mjs" + "capture": "node scripts/capture-screenshots.mjs", + "verify": "node scripts/verify-editor.mjs" }, "dependencies": { "@astrojs/sitemap": "^3.6.0", diff --git a/site/public/screenshots/brush.webp b/site/public/screenshots/brush.webp index a4b1423..677f3e2 100644 Binary files a/site/public/screenshots/brush.webp and b/site/public/screenshots/brush.webp differ diff --git a/site/public/screenshots/brush@2x.webp b/site/public/screenshots/brush@2x.webp index ec80725..822fcd1 100644 Binary files a/site/public/screenshots/brush@2x.webp and b/site/public/screenshots/brush@2x.webp differ diff --git a/site/public/screenshots/hero.webp b/site/public/screenshots/hero.webp index 03241cb..aceda8c 100644 Binary files a/site/public/screenshots/hero.webp and b/site/public/screenshots/hero.webp differ diff --git a/site/public/screenshots/hero@2x.webp b/site/public/screenshots/hero@2x.webp index 35fd8a3..58fed54 100644 Binary files a/site/public/screenshots/hero@2x.webp and b/site/public/screenshots/hero@2x.webp differ diff --git a/site/public/screenshots/selections.webp b/site/public/screenshots/selections.webp index e79903d..398145b 100644 Binary files a/site/public/screenshots/selections.webp and b/site/public/screenshots/selections.webp differ diff --git a/site/public/screenshots/selections@2x.webp b/site/public/screenshots/selections@2x.webp index 7bc654f..97b5a88 100644 Binary files a/site/public/screenshots/selections@2x.webp and b/site/public/screenshots/selections@2x.webp differ diff --git a/site/scripts/verify-editor.mjs b/site/scripts/verify-editor.mjs new file mode 100644 index 0000000..13e8a95 --- /dev/null +++ b/site/scripts/verify-editor.mjs @@ -0,0 +1,492 @@ +/** + * Behavioural checks that drive the real editor in a browser and assert on + * what actually lands on the canvas. These cover the things unit tests cannot: + * pointer interaction, clipping, and compositing. + * + * pnpm verify # every check + * pnpm verify brush-clip # one check + * + * Runs against `pnpm dev` at the repo root. Tauri-only paths are skipped here; + * those are covered by the manual QA flow in docs/qa-flow.md. + */ +import { spawn } from 'node:child_process'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { chromium } from 'playwright'; + +const SITE_DIR = path.resolve(fileURLToPath(new URL('..', import.meta.url))); +const REPO_DIR = path.resolve(SITE_DIR, '..'); +const APP_URL = 'http://localhost:1420'; + +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + +/* ------------------------------------------------------------------ helpers */ + +async function isUp(url) { + try { + return (await fetch(url)).ok; + } catch { + return false; + } +} + +async function waitForServer(url) { + const deadline = Date.now() + 180_000; + while (Date.now() < deadline) { + try { + if ((await fetch(url)).ok) return; + } catch { + /* not up yet */ + } + await sleep(400); + } + throw new Error(`dev server never came up at ${url}`); +} + +async function waitForEditor(page) { + await page.waitForSelector('button[aria-label="Move"]', { timeout: 60_000 }); + await page.waitForSelector('aside ul li select', { timeout: 60_000 }); + await sleep(800); +} + +const tool = async (page, label) => { + await page.click(`button[aria-label="${label}"]`); + await sleep(200); +}; + +async function canvasBox(page) { + const box = await page.locator('.pv-canvas').first().boundingBox(); + if (!box) throw new Error('canvas not found'); + return box; +} + +async function drag(page, from, to, steps = 24) { + const box = await canvasBox(page); + const at = (p) => [box.x + box.width * p[0], box.y + box.height * p[1]]; + const [x1, y1] = at(from); + const [x2, y2] = at(to); + await page.mouse.move(x1, y1); + await page.mouse.down(); + for (let i = 1; i <= steps; i += 1) { + await page.mouse.move(x1 + ((x2 - x1) * i) / steps, y1 + ((y2 - y1) * i) / steps); + } + await page.mouse.up(); + await sleep(500); +} + +/** Reads pixels off the live canvas at fractional positions. */ +async function samplePixels(page, points) { + // A mid-run hot reload can briefly unmount the canvas; wait it out rather + // than failing with an opaque null dereference. + await page.waitForSelector('.pv-canvas canvas', { timeout: 15_000 }); + return page.evaluate((pts) => { + const canvas = document.querySelector('.pv-canvas canvas'); + if (!canvas) throw new Error('canvas disappeared while sampling'); + const probe = document.createElement('canvas'); + probe.width = canvas.width; + probe.height = canvas.height; + const ctx = probe.getContext('2d'); + ctx.drawImage(canvas, 0, 0); + return pts.map(([fx, fy]) => { + const d = ctx.getImageData(Math.round(canvas.width * fx), Math.round(canvas.height * fy), 1, 1).data; + return { r: d[0], g: d[1], b: d[2], a: d[3] }; + }); + }, points); +} + +const isDark = (c) => c.r < 90 && c.g < 90 && c.b < 90; + +/** Opens Image > > and confirms the dialog if it has one. */ +async function applyMenuFilter(page, submenu, item) { + await page.getByRole('button', { name: 'Image', exact: true }).click(); + await sleep(250); + await page.getByRole('menuitem', { name: submenu, exact: true }).click(); + await sleep(250); + await page.getByRole('menuitem', { name: item, exact: true }).click(); + await sleep(600); + const apply = page.getByRole('button', { name: 'Apply', exact: true }); + if (await apply.count()) { + await apply.click(); + await sleep(800); + } +} + +async function setBrushSize(page, value) { + const size = page.locator('aside input[type="range"]').first(); + await size.fill(String(value)); + await size.dispatchEvent('input'); + await sleep(300); +} + +/* ------------------------------------------------------------------- checks */ + +const checks = { + /** #3 — brush and eraser must not paint outside an active selection. */ + async 'brush-clip'(page) { + await tool(page, 'Marquee'); + await drag(page, [0.35, 0.3], [0.65, 0.7]); + + await tool(page, 'Brush'); + await setBrushSize(page, 40); + await drag(page, [0.1, 0.5], [0.9, 0.5], 40); + + const [left, insideA, insideB, right] = await samplePixels(page, [ + [0.18, 0.5], + [0.42, 0.5], + [0.58, 0.5], + [0.82, 0.5], + ]); + + const problems = []; + if (!isDark(insideA) || !isDark(insideB)) problems.push('no paint landed inside the selection'); + if (isDark(left)) problems.push(`paint leaked left of the selection (${left.r},${left.g},${left.b})`); + if (isDark(right)) problems.push(`paint leaked right of the selection (${right.r},${right.g},${right.b})`); + return problems; + }, + + /** #3 — with no selection the brush must still paint everywhere. */ + async 'brush-unclipped'(page) { + await tool(page, 'Brush'); + await setBrushSize(page, 40); + await drag(page, [0.1, 0.5], [0.9, 0.5], 40); + + const [left, middle, right] = await samplePixels(page, [ + [0.18, 0.5], + [0.5, 0.5], + [0.82, 0.5], + ]); + return [left, middle, right].every(isDark) + ? [] + : ['brush did not paint across the whole layer with no selection active']; + }, + + /** + * #5 - Alt+right-drag must change the brush size smoothly. The old scheme + * pinned the OS cursor and swallowed alternate events, so the size lurched + * back and forth; this samples it along the drag and rejects any reversal. + */ + async 'brush-resize'(page) { + await tool(page, 'Brush'); + await setBrushSize(page, 20); + + const box = await canvasBox(page); + const y = box.y + box.height * 0.5; + const startX = box.x + box.width * 0.5; + + const readSize = () => + page.evaluate(() => { + const label = [...document.querySelectorAll('aside span')].find((el) => + /^Brush \d+px$/.test(el.textContent ?? ''), + ); + return label ? Number(label.textContent.match(/(\d+)/)[1]) : null; + }); + + await page.mouse.move(startX, y); + await page.keyboard.down('Alt'); + await page.mouse.down({ button: 'right' }); + + const sizes = []; + for (let i = 1; i <= 12; i += 1) { + await page.mouse.move(startX + i * 12, y); + await sleep(60); + sizes.push(await readSize()); + } + + await page.mouse.up({ button: 'right' }); + await page.keyboard.up('Alt'); + await sleep(200); + + const problems = []; + if (sizes.some((size) => size === null)) return ['could not read the brush size label']; + if (sizes[sizes.length - 1] <= sizes[0]) { + problems.push(`dragging right did not grow the brush (${sizes[0]} -> ${sizes[sizes.length - 1]})`); + } + for (let i = 1; i < sizes.length; i += 1) { + if (sizes[i] < sizes[i - 1]) { + problems.push(`size went backwards mid-drag: ${sizes.join(', ')}`); + break; + } + } + return problems; + }, + + /** + * #11 - Cursor (A) drag inside a selection moves the selected pixels; the + * region it came from is left empty and the pixels show up further right. + */ + async 'selection-move-pixels'(page) { + await tool(page, 'Brush'); + await setBrushSize(page, 60); + await drag(page, [0.2, 0.5], [0.34, 0.5], 20); + + await tool(page, 'Marquee'); + await drag(page, [0.14, 0.38], [0.4, 0.62]); + + await tool(page, 'Cursor'); + await drag(page, [0.27, 0.5], [0.67, 0.5], 20); + await sleep(400); + + const [origin, destination] = await samplePixels(page, [ + [0.27, 0.5], + [0.67, 0.5], + ]); + + const problems = []; + if (isDark(origin)) problems.push('pixels were left behind at the original position'); + if (!isDark(destination)) problems.push('pixels did not arrive at the drop position'); + return problems; + }, + + /** + * #11 - Alt+drag moves only the outline. The painted pixels must stay put, + * and the moved selection must now clip painting to its new position. + */ + async 'selection-move-outline'(page) { + await tool(page, 'Brush'); + await setBrushSize(page, 60); + await drag(page, [0.2, 0.5], [0.34, 0.5], 20); + + await tool(page, 'Marquee'); + await drag(page, [0.14, 0.38], [0.4, 0.62]); + + await tool(page, 'Cursor'); + const box = await canvasBox(page); + const at = (p) => [box.x + box.width * p[0], box.y + box.height * p[1]]; + const [x1, y1] = at([0.27, 0.5]); + const [x2, y2] = at([0.67, 0.5]); + await page.keyboard.down('Alt'); + await page.mouse.move(x1, y1); + await page.mouse.down(); + for (let i = 1; i <= 20; i += 1) { + await page.mouse.move(x1 + ((x2 - x1) * i) / 20, y1 + ((y2 - y1) * i) / 20); + } + await page.mouse.up(); + await page.keyboard.up('Alt'); + await sleep(500); + + const [origin] = await samplePixels(page, [[0.27, 0.5]]); + const problems = []; + if (!isDark(origin)) problems.push('Alt+drag moved the pixels; it should move only the outline'); + + // The outline should now clip painting to where it was dragged. + await tool(page, 'Brush'); + await drag(page, [0.45, 0.5], [0.9, 0.5], 30); + const [between, moved] = await samplePixels(page, [ + [0.45, 0.5], + [0.67, 0.5], + ]); + if (isDark(between)) problems.push('paint landed outside the moved selection'); + if (!isDark(moved)) problems.push('paint did not land inside the moved selection'); + return problems; + }, + + /** + * #9 - Ctrl+X must clear the selected pixels, and Ctrl+V must bring them back + * as a new layer. + */ + async 'cut-and-paste'(page) { + await tool(page, 'Brush'); + await setBrushSize(page, 60); + await drag(page, [0.2, 0.5], [0.34, 0.5], 20); + + await tool(page, 'Marquee'); + await drag(page, [0.14, 0.38], [0.4, 0.62]); + + const layersBefore = await page.locator('aside ul li').count(); + + await page.keyboard.press('Control+x'); + await sleep(900); + const [afterCut] = await samplePixels(page, [[0.27, 0.5]]); + + await page.keyboard.press('Control+v'); + await sleep(1200); + const layersAfter = await page.locator('aside ul li').count(); + + const problems = []; + if (isDark(afterCut)) problems.push('Ctrl+X left the pixels in place'); + if (layersAfter <= layersBefore) problems.push('Ctrl+V did not add a layer'); + return problems; + }, + + /** #12 - Invert applies to the whole layer when nothing is selected. */ + async 'filter-whole-layer'(page) { + const [before] = await samplePixels(page, [[0.5, 0.5]]); + await applyMenuFilter(page, 'Adjustments', 'Invert'); + const [after] = await samplePixels(page, [[0.5, 0.5]]); + return before.r === after.r && before.g === after.g && before.b === after.b + ? ['Invert did not change the layer'] + : []; + }, + + /** #12 - and only inside the selection when there is one. */ + async 'filter-selection-only'(page) { + await tool(page, 'Marquee'); + await drag(page, [0.35, 0.3], [0.65, 0.7]); + + const [insideBefore, outsideBefore] = await samplePixels(page, [ + [0.5, 0.5], + [0.85, 0.5], + ]); + + await applyMenuFilter(page, 'Adjustments', 'Invert'); + + const [insideAfter, outsideAfter] = await samplePixels(page, [ + [0.5, 0.5], + [0.85, 0.5], + ]); + + const same = (a, b) => a.r === b.r && a.g === b.g && a.b === b.b; + const problems = []; + if (same(insideBefore, insideAfter)) problems.push('the selection was not inverted'); + if (!same(outsideBefore, outsideAfter)) problems.push('the filter leaked outside the selection'); + return problems; + }, + + /** + * #12 - the dialog previews live on the canvas, and Cancel must put the + * original pixels back rather than leaving the preview behind. + */ + async 'filter-preview-and-cancel'(page) { + const [before] = await samplePixels(page, [[0.5, 0.5]]); + + await page.getByRole('button', { name: 'Image', exact: true }).click(); + await sleep(250); + await page.getByRole('menuitem', { name: 'Adjustments', exact: true }).click(); + await sleep(250); + await page.getByRole('menuitem', { name: 'Hue / Saturation…', exact: true }).click(); + await sleep(600); + + const dialog = page.getByRole('dialog'); + const lightness = dialog.locator('input[type="range"]').nth(2); + await lightness.fill('-90'); + await lightness.dispatchEvent('input'); + await sleep(900); + const [previewed] = await samplePixels(page, [[0.5, 0.5]]); + + await dialog.getByRole('button', { name: 'Cancel', exact: true }).click(); + await sleep(800); + const [afterCancel] = await samplePixels(page, [[0.5, 0.5]]); + + const same = (a, b) => a.r === b.r && a.g === b.g && a.b === b.b; + const problems = []; + if (same(before, previewed)) problems.push('the dialog did not preview on the canvas'); + if (!same(before, afterCancel)) problems.push('Cancel left the preview applied'); + return problems; + }, + /** Undo must reverse a single brush stroke and leave earlier ones alone. */ + async 'undo-brush'(page) { + await tool(page, 'Brush'); + await setBrushSize(page, 50); + await drag(page, [0.2, 0.35], [0.45, 0.35], 20); + await sleep(400); + await drag(page, [0.2, 0.65], [0.45, 0.65], 20); + await sleep(400); + + let [first, second] = await samplePixels(page, [[0.3, 0.35], [0.3, 0.65]]); + if (!isDark(first) || !isDark(second)) return ['both strokes should have painted']; + + await page.keyboard.press('Control+z'); + await sleep(700); + [first, second] = await samplePixels(page, [[0.3, 0.35], [0.3, 0.65]]); + + const problems = []; + if (isDark(second)) problems.push('one undo did not remove the second stroke'); + if (!isDark(first)) problems.push('one undo removed the first stroke too - strokes are coalescing'); + + await page.keyboard.press('Control+Shift+z'); + await sleep(700); + const [redone] = await samplePixels(page, [[0.3, 0.65]]); + if (!isDark(redone)) problems.push('redo did not put the stroke back'); + return problems; + }, + + /** Undo must reverse an erase - the case reported broken. */ + async 'undo-eraser'(page) { + await tool(page, 'Brush'); + await setBrushSize(page, 70); + await drag(page, [0.2, 0.5], [0.7, 0.5], 25); + await sleep(500); + + const [before] = await samplePixels(page, [[0.45, 0.5]]); + if (!isDark(before)) return ['the brush stroke did not paint, so the erase cannot be tested']; + + await tool(page, 'Eraser'); + await setBrushSize(page, 70); + await drag(page, [0.4, 0.5], [0.5, 0.5], 10); + await sleep(600); + + const [erased] = await samplePixels(page, [[0.45, 0.5]]); + if (isDark(erased)) return ['the eraser did not erase, so undo cannot be tested']; + + await page.keyboard.press('Control+z'); + await sleep(800); + const [restored] = await samplePixels(page, [[0.45, 0.5]]); + return isDark(restored) ? [] : ['undo did not restore the erased pixels']; + }, +}; + +/* --------------------------------------------------------------------- main */ + +async function main() { + const requested = process.argv.slice(2); + const names = requested.length ? requested : Object.keys(checks); + for (const name of names) { + if (!checks[name]) throw new Error(`Unknown check "${name}". Known: ${Object.keys(checks).join(', ')}`); + } + + // Vite uses strictPort, so a dev server left running by a previous run would + // make a second one fail silently. Reuse whatever is already listening. + const alreadyRunning = await isUp(APP_URL); + const server = alreadyRunning + ? null + : spawn('pnpm', ['dev'], { cwd: REPO_DIR, stdio: 'ignore', shell: process.platform === 'win32' }); + if (alreadyRunning) console.log(`reusing the dev server already on ${APP_URL}`); + + const browser = await chromium.launch({ + args: ['--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'], + }); + + let failed = 0; + try { + await waitForServer(APP_URL); + for (const name of names) { + const context = await browser.newContext({ viewport: { width: 1440, height: 900 }, reducedMotion: 'reduce' }); + const page = await context.newPage(); + await page.goto(APP_URL, { waitUntil: 'networkidle' }); + await waitForEditor(page); + + let problems; + try { + problems = await checks[name](page); + } catch (error) { + problems = [`threw: ${error.message}`]; + } + await context.close(); + + if (problems.length) { + failed += 1; + console.log(`FAIL ${name}`); + for (const problem of problems) console.log(` ${problem}`); + } else { + console.log(`ok ${name}`); + } + } + } finally { + await browser.close(); + if (server) { + if (process.platform === 'win32' && server.pid) { + spawn('taskkill', ['/pid', String(server.pid), '/T', '/F'], { stdio: 'ignore' }); + } else { + server.kill(); + } + } + } + + console.log(failed ? `\n${failed} check(s) failed.` : `\nAll ${names.length} check(s) passed.`); + process.exitCode = failed ? 1 : 0; +} + +main().catch((error) => { + console.error(error); + process.exit(1); +}); diff --git a/site/src/consts.ts b/site/src/consts.ts index 8626033..c0f937e 100644 --- a/site/src/consts.ts +++ b/site/src/consts.ts @@ -52,11 +52,14 @@ export const BLEND_MODES = [ export const WORKS_TODAY = [ 'Multi-layer documents with per-layer opacity and 13 blend modes', 'Open PNG, JPEG and WebP files; save your work back to disk', - 'Rectangular, freehand and magic-wand selections', + 'Rectangular, freehand and magic-wand selections that clip every edit', 'Brush, eraser, gradient, healing and text tools', + 'Brightness, exposure, hue/saturation, levels, blur, sharpen and more', + 'Cut, copy and paste the selected region', + 'Drag an image in from the desktop, or paste one from the clipboard', + 'A colour picker with a wheel and RGB, HSL and hex fields', 'Full undo/redo history with named steps', 'Image resizing, cropping and a fit-to-screen canvas', - 'System colour picker that samples anywhere on screen', 'GPU compositing through a custom WebGL engine', ]; @@ -65,6 +68,5 @@ export const COMING_NEXT = [ 'Layer masks and non-destructive adjustment layers', 'Canvas size, rotate and flip', 'Invert and refine-edge for selections', - 'A filter gallery', 'macOS and Linux builds', ]; diff --git a/site/src/content/docs/roadmap.md b/site/src/content/docs/roadmap.md index 582ff56..1aea742 100644 --- a/site/src/content/docs/roadmap.md +++ b/site/src/content/docs/roadmap.md @@ -24,13 +24,20 @@ you cannot use today. - Duplicate, delete, reorder by selection, and hide layers **Editing** -- Brush, eraser, gradient and healing tools +- Brush, eraser, gradient and healing tools, all clipped to the active selection - Editable text layers using any installed system font - Eyedropper, including sampling from anywhere on screen in the desktop build +- A colour picker with a hue/saturation wheel and RGB, HSL, alpha and hex fields - Rectangular, freehand and magic-wand selections -- Moving selected pixels with the Move tool +- Moving the selected pixels, or just the outline, with the Cursor tool +- Cut, copy and paste the selected region - Full undo/redo history, with each step named +**Adjustments and filters** +- Brightness/contrast, exposure, hue/saturation, levels, invert, grayscale, sepia +- Gaussian blur, sharpen, vignette and noise +- All of them apply to the selection when there is one, with a live preview + **Application** - Windows desktop build, signed with Azure Trusted Signing - Entirely offline; no account, telemetry or network calls beyond an update check @@ -44,7 +51,6 @@ These appear in the menus, greyed out: |---|---| | Export PNG / JPEG / WebP dialogs | File | | Open Recent | File | -| Cut and Copy | Edit | | Canvas Size | Image | | Rotate Canvas, Flip Horizontal, Flip Vertical | Image | | Layer Mask | Layer | @@ -60,11 +66,11 @@ Roughly in the order we intend to tackle them: 1. **Export dialogs** — explicit PNG, JPEG and WebP export with quality control, rather than saving back over the source file. 2. **Layer masks** — non-destructive masking, the single biggest gap against Photoshop. -3. **Adjustment layers** — levels, curves, hue/saturation, applied non-destructively. +3. **Adjustment layers** — the adjustments above, applied non-destructively on their own + layer rather than baked into the pixels. 4. **Canvas transforms** — canvas size, rotate and flip. 5. **Selection refinement** — invert, feather, grow and shrink. -6. **Filters** — a small, honest set of filters rather than a large weak one. -7. **macOS and Linux builds** — the Tauri shell already supports both; they need signing, +6. **macOS and Linux builds** — the Tauri shell already supports both; they need signing, notarisation and testing before we publish them. ## Ideas and requests diff --git a/site/src/content/docs/selections.md b/site/src/content/docs/selections.md index dbadf6a..0df911a 100644 --- a/site/src/content/docs/selections.md +++ b/site/src/content/docs/selections.md @@ -28,12 +28,16 @@ flat backgrounds and other broad areas of even colour. ## Using a selection -- **Paint inside it** — brush, eraser and gradient strokes are clipped to the selection. -- **Move the pixels** — switch to the Move tool (V) and Alt-drag. - The selected pixels lift off the layer and follow the cursor, leaving transparency - behind. -- **Move the selection itself** — drag inside it with the Move tool without holding - Alt. +- **Paint inside it** — brush and eraser strokes are clipped to the selection. +- **Move the selected pixels** — with the Cursor tool (A), drag from inside the + selection. The pixels lift off the layer and travel with the outline, leaving + transparency behind. +- **Move just the outline** — Alt-drag with the Cursor tool. The pixels stay + put and the selection moves to a new part of the image. +- **Copy or cut it** — Ctrl+C and Ctrl+X. + Ctrl+V pastes the region back as a new layer. +- **Filter it** — everything under **Image → Adjustments** and **Image → Filters** applies + only to the selected pixels while a selection is active. ## Select menu @@ -41,6 +45,7 @@ flat backgrounds and other broad areas of even colour. |---|---|---| | All | Ctrl+A | Selects the whole canvas | | Deselect | Esc | Clears the selection | +| Deselect | Ctrl+D | Clears the selection | | Inverse | Ctrl+Shift+I | Not implemented yet | | Refine Edge | — | Not implemented yet | @@ -49,8 +54,9 @@ Inverse and Refine Edge appear in the menu but are greyed out; both are on the ## Tips -- Deselect before painting broadly. A forgotten selection silently confining your brush is - the most common source of "why is nothing happening?". +- Deselect before painting broadly — Ctrl+D or Esc. A + forgotten selection silently confining your brush is the most common source of "why is + nothing happening?". - Selections survive switching layers, so you can select once and then edit several layers through the same shape. - Everything here is undoable — Ctrl+Z steps back through selection diff --git a/site/src/content/docs/tools-and-shortcuts.md b/site/src/content/docs/tools-and-shortcuts.md index 32eb0b6..425a5e8 100644 --- a/site/src/content/docs/tools-and-shortcuts.md +++ b/site/src/content/docs/tools-and-shortcuts.md @@ -11,7 +11,7 @@ works whenever you are not typing into a field. | Tool | Key | What it does | |---|---|---| -| Cursor | A | Click a layer to select it without moving anything. | +| Cursor | A | Click a layer to select it. With a selection active, drag to move the selected pixels, or Alt-drag to move just the outline. | | Move | V | Drag the active layer around the canvas. Alt-drag moves the current selection instead. | | Marquee | M | Drag out a rectangular selection. | | Lasso | L | Draw a freehand selection. | @@ -29,9 +29,12 @@ works whenever you are not typing into a field. ![Painting with a sampled colour on a new layer](/screenshots/brush.webp) The options bar shows the current colour and a size slider while the brush, eraser or -healing tool is active. You can also resize without leaving the canvas: hold -Ctrl+Alt and right-drag. The ring around the cursor previews the -size as you go. +healing tool is active. You can also resize without leaving the canvas: hold Alt +and right-drag. The cursor stays pinned while you drag and returns to where it started, and +the ring previews the size as you go. + +Strokes are clipped to the active selection, so a marquee or lasso is the simplest way to +confine painting to one part of the image. Painting on an image layer edits that image directly. If you would rather keep the original intact, add a layer first with **Layer → New Layer** @@ -43,6 +46,15 @@ Click anywhere on the canvas to make that colour the foreground colour. In the d build the eyedropper can also sample from outside the Photovibe window — anywhere on your screen — which is useful for matching a colour from another application. +Once you pick a colour, Photovibe switches back to whichever tool you were using before, so +sampling mid-stroke costs nothing. + +### Choosing a colour directly + +Click the colour swatch in the options bar, or the one in the properties panel, to open the +colour picker: a hue and saturation wheel with a value slider, plus RGB, HSL, alpha and hex +fields. + ### Text ![A committed text layer above the photo](/screenshots/text.webp) @@ -68,7 +80,9 @@ layer with the Text tool reopens it for editing. | Action | Shortcut | |---|---| | Undo | Ctrl+Z | -| Redo | Ctrl+Shift+Z | +| Redo | Ctrl+Shift+Z or Ctrl+Y | +| Copy the selected region | Ctrl+C | +| Cut the selected region | Ctrl+X | | Paste image from clipboard | Ctrl+V | ### Layer @@ -76,14 +90,14 @@ layer with the Text tool reopens it for editing. | Action | Shortcut | |---|---| | New layer | Ctrl+Shift+N | -| Duplicate layer | Ctrl+D | +| Duplicate layer | Ctrl+J | ### Select | Action | Shortcut | |---|---| | Select all | Ctrl+A | -| Deselect | Esc | +| Deselect | Ctrl+D or Esc | ### Image and View @@ -102,5 +116,7 @@ layer with the Text tool reopens it for editing. |---|---| | Pan | Hold Space and drag | | Zoom | Scroll wheel | -| Resize brush | Ctrl+Alt+right-drag | -| Move a selection's pixels | Alt-drag with the Move tool | +| Resize brush | Alt+right-drag | +| Move the selected pixels | Drag inside the selection with the Cursor tool | +| Move the selection outline | Alt-drag with the Cursor tool | +| Add an image | Drag an image file onto the canvas | diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json index c78c295..740aa87 100644 --- a/src-tauri/capabilities/default.json +++ b/src-tauri/capabilities/default.json @@ -14,6 +14,7 @@ "allow": [{ "path": "**" }] }, "clipboard-manager:allow-read-image", + "clipboard-manager:allow-write-image", "clipboard-manager:allow-read-text", "core:window:allow-close", "core:window:allow-minimize", diff --git a/src-tauri/examples/clipboard_files.rs b/src-tauri/examples/clipboard_files.rs new file mode 100644 index 0000000..0788f83 --- /dev/null +++ b/src-tauri/examples/clipboard_files.rs @@ -0,0 +1,80 @@ +//! Prints image paths currently on the Windows clipboard as CF_HDROP. +//! +//! Mirrors the `read_clipboard_files` command so the Win32 usage can be +//! exercised without launching the app: +//! +//! ```powershell +//! Set-Clipboard -LiteralPath C:\some\photo.jpg +//! cargo run --example clipboard_files +//! ``` +fn main() { + #[cfg(windows)] + { + match read() { + Ok(paths) if paths.is_empty() => println!("clipboard holds no CF_HDROP file list"), + Ok(paths) => { + println!("{} path(s):", paths.len()); + for path in paths { + println!(" {path}"); + } + } + Err(error) => println!("error: {error}"), + } + } + #[cfg(not(windows))] + println!("windows only"); +} + +#[cfg(windows)] +fn read() -> Result, String> { + use std::ffi::c_void; + + const CF_HDROP: u32 = 15; + + #[link(name = "user32")] + extern "system" { + fn OpenClipboard(hwnd: *mut c_void) -> i32; + fn CloseClipboard() -> i32; + fn GetClipboardData(format: u32) -> *mut c_void; + fn IsClipboardFormatAvailable(format: u32) -> i32; + } + + #[link(name = "shell32")] + extern "system" { + fn DragQueryFileW(drop: *mut c_void, index: u32, buffer: *mut u16, size: u32) -> u32; + } + + unsafe { + if IsClipboardFormatAvailable(CF_HDROP) == 0 { + return Ok(Vec::new()); + } + if OpenClipboard(std::ptr::null_mut()) == 0 { + return Err("Could not open the clipboard".into()); + } + + let handle = GetClipboardData(CF_HDROP); + if handle.is_null() { + CloseClipboard(); + return Ok(Vec::new()); + } + + let count = DragQueryFileW(handle, u32::MAX, std::ptr::null_mut(), 0); + let mut paths = Vec::with_capacity(count as usize); + for index in 0..count { + let len = DragQueryFileW(handle, index, std::ptr::null_mut(), 0); + if len == 0 { + continue; + } + let mut buffer = vec![0u16; len as usize + 1]; + let written = DragQueryFileW(handle, index, buffer.as_mut_ptr(), buffer.len() as u32); + if written == 0 { + continue; + } + buffer.truncate(written as usize); + paths.push(String::from_utf16_lossy(&buffer)); + } + + CloseClipboard(); + Ok(paths) + } +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 6b11fe4..579d6d0 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -10,6 +10,7 @@ pub fn run() { .invoke_handler(tauri::generate_handler![ sample_screen_color, pin_cursor, + read_clipboard_files, list_system_fonts, app_version ]) @@ -70,6 +71,76 @@ fn windows_pin_cursor(x: i32, y: i32) -> Result<(), String> { Ok(()) } +/// File Explorer puts a CF_HDROP file list on the clipboard rather than a +/// bitmap, which the clipboard plugin cannot see. Returns the dropped paths so +/// the frontend can load the first image among them. +#[tauri::command] +fn read_clipboard_files() -> Result, String> { + #[cfg(windows)] + { + return windows_read_clipboard_files(); + } + #[cfg(not(windows))] + { + Ok(Vec::new()) + } +} + +#[cfg(windows)] +fn windows_read_clipboard_files() -> Result, String> { + use std::ffi::c_void; + + const CF_HDROP: u32 = 15; + + #[link(name = "user32")] + extern "system" { + fn OpenClipboard(hwnd: *mut c_void) -> i32; + fn CloseClipboard() -> i32; + fn GetClipboardData(format: u32) -> *mut c_void; + fn IsClipboardFormatAvailable(format: u32) -> i32; + } + + #[link(name = "shell32")] + extern "system" { + fn DragQueryFileW(drop: *mut c_void, index: u32, buffer: *mut u16, size: u32) -> u32; + } + + unsafe { + if IsClipboardFormatAvailable(CF_HDROP) == 0 { + return Ok(Vec::new()); + } + if OpenClipboard(std::ptr::null_mut()) == 0 { + return Err("Could not open the clipboard".into()); + } + + let handle = GetClipboardData(CF_HDROP); + if handle.is_null() { + CloseClipboard(); + return Ok(Vec::new()); + } + + let count = DragQueryFileW(handle, u32::MAX, std::ptr::null_mut(), 0); + let mut paths = Vec::with_capacity(count as usize); + for index in 0..count { + // Ask for the length first, then read into a buffer of that size. + let len = DragQueryFileW(handle, index, std::ptr::null_mut(), 0); + if len == 0 { + continue; + } + let mut buffer = vec![0u16; len as usize + 1]; + let written = DragQueryFileW(handle, index, buffer.as_mut_ptr(), buffer.len() as u32); + if written == 0 { + continue; + } + buffer.truncate(written as usize); + paths.push(String::from_utf16_lossy(&buffer)); + } + + CloseClipboard(); + Ok(paths) + } +} + #[tauri::command] fn list_system_fonts() -> Vec { #[cfg(windows)] diff --git a/src/app/AppShell.tsx b/src/app/AppShell.tsx index ccf9906..a6e2026 100644 --- a/src/app/AppShell.tsx +++ b/src/app/AppShell.tsx @@ -9,14 +9,51 @@ import { OptionsBar } from "../components/OptionsBar"; import { SplashScreen } from "../components/SplashScreen"; import { StatusBar } from "../components/StatusBar"; import { Toolbar, type ToolId } from "../components/Toolbar"; -import { listSystemFonts, openImagePath, readClipboardImage, sampleScreenColor } from "../lib/native"; -import { useDocumentStore } from "../store/document-store"; +import { FilterDialog, type FilterSpec } from "../components/FilterDialog"; +import type { Filter } from "../engine/filters/adjustments"; +import { beginFilter, previewFilter } from "../engine/filters/apply"; +import { ADJUSTMENTS, EFFECTS } from "../engine/filters/catalogue"; +import { canvasToBlob, clearSelectionRegion, copySelectionRegion } from "../engine/pixels/clipboard-region"; +import { selectionStore } from "../engine/selections/selection-store"; +import { useSelectionGeneration } from "../hooks/use-selection"; +import { + listSystemFonts, + openImagePath, + readClipboardImage, + readClipboardImagePaths, + readImageAtPath, + sampleScreenColor, + writeClipboardImage, +} from "../lib/native"; +import { useActiveLayer, useDocumentStore } from "../store/document-store"; import { useEditorStore } from "../store/editor-store"; import { useViewportStore } from "../store/viewport-store"; +/** + * Cut and Copy keep the region here as well as on the system clipboard, so a + * Paste inside Photovibe is exact rather than a PNG round-trip. + */ +const internalClipboard: { canvas: HTMLCanvasElement | null } = { canvas: null }; + const SPLASH_MIN_MS = 1200; const SKELETON_MS = 350; +/** + * Only real text entry should swallow shortcuts. Sliders, checkboxes and + * dropdowns are focusable too, and treating them as text entry meant that + * touching the brush-size slider silently killed Ctrl+Z until you clicked + * somewhere else. + */ +const TEXT_INPUT_TYPES = new Set(["text", "search", "url", "tel", "email", "password", "number"]); + +function isTextEntry(target: EventTarget | null): boolean { + const el = target as HTMLElement | null; + if (!el) return false; + if (el.isContentEditable || el.tagName === "TEXTAREA") return true; + if (el.tagName !== "INPUT") return false; + return TEXT_INPUT_TYPES.has((el as HTMLInputElement).type); +} + function shouldBlockBrowserShortcut(e: KeyboardEvent): boolean { const key = e.key.toLowerCase(); const ctrl = e.ctrlKey || e.metaKey; @@ -45,6 +82,14 @@ export function AppShell() { const setSelection = useDocumentStore((s) => s.setSelection); const selectAll = useDocumentStore((s) => s.selectAll); const addImageLayer = useDocumentStore((s) => s.addImageLayer); + const beginStroke = useDocumentStore((s) => s.beginStroke); + const touchPixels = useDocumentStore((s) => s.touchPixels); + const activeLayer = useActiveLayer(); + // selectionStore is not a React store; this subscribes so menu enablement + // tracks whether a selection exists. + useSelectionGeneration(); + const hasSelection = !!selectionStore.mask; + const canFilter = !!activeLayer && activeLayer.kind !== "adjustment"; const saveDocument = useDocumentStore((s) => s.saveDocument); const saveDocumentAs = useDocumentStore((s) => s.saveDocumentAs); const resizeImage = useDocumentStore((s) => s.resizeImage); @@ -63,10 +108,12 @@ export function AppShell() { const [phase, setPhase] = useState<"splash" | "skeleton" | "ready">("splash"); const [splashExiting, setSplashExiting] = useState(false); const [activeTool, setActiveTool] = useState("move"); + const previousToolRef = useRef("move"); const [showGrid, setShowGrid] = useState(false); const [showNew, setShowNew] = useState(false); const [showImageSize, setShowImageSize] = useState(false); const [showAbout, setShowAbout] = useState(false); + const [activeFilter, setActiveFilter] = useState(null); const fittedDocRef = useRef(null); useEffect(() => { @@ -110,19 +157,84 @@ export function AppShell() { const el = e.target as HTMLElement; if (el.closest("button, input, select, textarea, [role='menu'], [role='menuitem'], a")) return; if (hoverColor) setForeground(hoverColor); + // Picking a colour is a means to an end, so hand the user back whatever + // they were doing before they reached for the eyedropper. + setActiveTool(previousToolRef.current); } window.addEventListener("pointerdown", onDown, true); return () => window.removeEventListener("pointerdown", onDown, true); }, [activeTool, hoverColor, setForeground]); + const selectTool = useCallback( + (next: ToolId) => { + if (next === "eyedropper" && activeTool !== "eyedropper") previousToolRef.current = activeTool; + setActiveTool(next); + }, + [activeTool], + ); + const handleNewDocument = useCallback(() => { setShowNew(true); }, []); + const handleCopy = useCallback( + async (cut: boolean) => { + if (!activeLayer || !selectionStore.mask) return; + + const region = copySelectionRegion(activeLayer); + if (!region) return; + + // Keep the canvas in process so Paste round-trips without re-encoding, + // and mirror it onto the system clipboard for other applications. + internalClipboard.canvas = region; + const blob = await canvasToBlob(region); + if (blob) await writeClipboardImage(new Uint8Array(await blob.arrayBuffer())); + + if (cut) { + beginStroke("Cut"); + clearSelectionRegion(activeLayer); + touchPixels(); + } + }, + [activeLayer, beginStroke, touchPixels], + ); + + const runFilter = useCallback( + (spec: FilterSpec, filter: Filter) => { + if (!activeLayer) return; + // FilterDialog has already put the original pixels back, so the history + // entry opens on the unfiltered state. + beginStroke(spec.name); + const target = beginFilter(activeLayer); + if (target) previewFilter(target, filter); + touchPixels(); + }, + [activeLayer, beginStroke, touchPixels], + ); + const handlePaste = useCallback(async () => { + // The system clipboard wins. Our own Copy writes a PNG there too, and PNG + // round-trips losslessly, so consulting it first costs nothing - whereas + // preferring the in-process copy meant one Ctrl+C shadowed every later + // paste from outside the app. const clip = await readClipboardImage(); - if (!clip) return; - await addImageLayer(clip.blob, "Pasted"); + if (clip) { + await addImageLayer(clip.blob, "Pasted"); + return; + } + // File Explorer copies a file as a CF_HDROP path list, not a bitmap. + for (const path of await readClipboardImagePaths()) { + const file = await readImageAtPath(path); + if (file) { + await addImageLayer(file.blob, file.name); + return; + } + } + // Last resort: the browser build cannot reach the system clipboard. + if (internalClipboard.canvas) { + const blob = await canvasToBlob(internalClipboard.canvas); + if (blob) await addImageLayer(blob, "Pasted"); + } }, [addImageLayer]); const handleOpen = useCallback(async () => { @@ -179,16 +291,43 @@ export function AppShell() { action: redo, }, { separator: true }, - { label: "Cut", shortcut: "Ctrl+X", disabled: true }, - { label: "Copy", shortcut: "Ctrl+C", disabled: true }, + { + label: "Cut", + shortcut: "Ctrl+X", + disabled: !hasSelection, + action: () => void handleCopy(true), + }, + { + label: "Copy", + shortcut: "Ctrl+C", + disabled: !hasSelection, + action: () => void handleCopy(false), + }, { label: "Paste", shortcut: "Ctrl+V", action: () => void handlePaste() }, ], }, { label: "Image", items: [ - { label: "Adjust…", shortcut: "Ctrl+Alt+I", action: () => setShowImageSize(true) }, - { label: "Image Size…", action: () => setShowImageSize(true) }, + { label: "Image Size…", shortcut: "Ctrl+Alt+I", action: () => setShowImageSize(true) }, + { separator: true }, + { + label: "Adjustments", + disabled: !canFilter, + items: ADJUSTMENTS.map((spec) => ({ + label: spec.params.length ? `${spec.name}…` : spec.name, + action: () => setActiveFilter(spec), + })), + }, + { + label: "Filters", + disabled: !canFilter, + items: EFFECTS.map((spec) => ({ + label: `${spec.name}…`, + action: () => setActiveFilter(spec), + })), + }, + { separator: true }, { label: "Canvas Size…", disabled: true }, { label: "Rotate Canvas", disabled: true }, { label: "Flip Horizontal", disabled: true }, @@ -200,7 +339,7 @@ export function AppShell() { items: [ { label: "New Layer", shortcut: "Ctrl+Shift+N", action: addEmptyLayer }, { label: "New Fill Layer", action: () => addFillLayer() }, - { label: "Duplicate Layer", shortcut: "Ctrl+D", action: duplicateActiveLayer }, + { label: "Duplicate Layer", shortcut: "Ctrl+J", action: duplicateActiveLayer }, { label: "Delete Layer", action: deleteActiveLayer }, { separator: true }, { label: "Layer Mask", disabled: true }, @@ -210,7 +349,7 @@ export function AppShell() { label: "Select", items: [ { label: "All", shortcut: "Ctrl+A", action: selectAll }, - { label: "Deselect", shortcut: "Esc", action: () => setSelection(null) }, + { label: "Deselect", shortcut: "Ctrl+D", action: () => setSelection(null) }, { label: "Inverse", shortcut: "Ctrl+Shift+I", disabled: true }, { separator: true }, { label: "Refine Edge…", disabled: true }, @@ -260,6 +399,9 @@ export function AppShell() { [ handleNewDocument, handleOpen, + handleCopy, + hasSelection, + canFilter, handlePaste, saveDocument, saveDocumentAs, @@ -298,10 +440,7 @@ export function AppShell() { e.preventDefault(); e.stopPropagation(); } - const target = e.target as HTMLElement | null; - if (target && (target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.isContentEditable)) { - return; - } + if (isTextEntry(e.target)) return; const toolMap: Record = { a: "cursor", v: "move", @@ -317,7 +456,7 @@ export function AppShell() { g: "gradient", }; if (toolMap[key] && !e.ctrlKey && !e.metaKey && !e.altKey) { - setActiveTool(toolMap[key]); + selectTool(toolMap[key]); } if ((e.ctrlKey || e.metaKey) && key === "z" && e.shiftKey) { e.preventDefault(); @@ -347,11 +486,24 @@ export function AppShell() { e.preventDefault(); void handleOpen(); } - if (e.ctrlKey && (key === "j" || key === "d")) { + if (e.ctrlKey && key === "d") { + e.preventDefault(); + // Ctrl+D deselects when there is something to deselect, which is what + // reaching for it during a selection almost always means. + if (selectionStore.mask) setSelection(null); + else duplicateActiveLayer(); + return; + } + if (e.ctrlKey && key === "j") { e.preventDefault(); duplicateActiveLayer(); return; } + if (e.ctrlKey && (key === "c" || key === "x") && selectionStore.mask) { + e.preventDefault(); + void handleCopy(key === "x"); + return; + } if (e.ctrlKey && key === "v") { e.preventDefault(); void handlePaste(); @@ -416,7 +568,9 @@ export function AppShell() { }, [ handleNewDocument, handleOpen, + handleCopy, handlePaste, + selectTool, saveDocument, saveDocumentAs, addEmptyLayer, @@ -446,12 +600,12 @@ export function AppShell() {
- setActiveTool(id as ToolId)} /> + selectTool(id as ToolId)} />
@@ -479,6 +633,15 @@ export function AppShell() { /> )} {showAbout && setShowAbout(false)} />} + {activeFilter && activeLayer && ( + runFilter(activeFilter, filter)} + onClose={() => setActiveFilter(null)} + /> + )} ); } diff --git a/src/canvas/CanvasViewport.tsx b/src/canvas/CanvasViewport.tsx index 9cf2bb8..2e22514 100644 --- a/src/canvas/CanvasViewport.tsx +++ b/src/canvas/CanvasViewport.tsx @@ -9,11 +9,13 @@ import { strokeBrushes } from "../engine/pixels/paint"; import { pixelStore } from "../engine/pixels/pixel-store"; import { hideLayer } from "../engine/document/hide-layer"; import { textOverlayLayout } from "../engine/pixels/text-metrics"; +import { DEFAULT_TRANSFORM } from "../engine/document/types"; +import { withSelectionClip } from "../engine/selections/clip"; import { fillLassoMask, fillRectMask, fillWandMask, flattenDocument, normalizeRect } from "../engine/selections/create-mask"; import { selectionStore } from "../engine/selections/selection-store"; import { usePixelGeneration } from "../hooks/use-pixel-generation"; import { useSelectionGeneration } from "../hooks/use-selection"; -import { pinCursor, readClipboardImage } from "../lib/native"; +import { isImagePath, pinCursor, readClipboardImage, readImageAtPath } from "../lib/native"; import { useActiveLayer, useDocumentStore } from "../store/document-store"; import { useEditorStore } from "../store/editor-store"; import { useViewportStore } from "../store/viewport-store"; @@ -83,7 +85,7 @@ export function CanvasViewport({ showGrid, loading, activeTool, onToolChange }: const paintingRef = useRef(false); const paintRaf = useRef(0); const dragRef = useRef<{ - kind: "pan" | "move" | "pixels" | "paint" | "rect" | "crop" | "lasso" | "crop-handle" | "brush-size"; + kind: "pan" | "move" | "pixels" | "selection" | "paint" | "rect" | "crop" | "lasso" | "crop-handle" | "brush-size"; layerId?: string; handle?: CropHandle; lastX: number; @@ -94,7 +96,7 @@ export function CanvasViewport({ showGrid, loading, activeTool, onToolChange }: pinX?: number; pinY?: number; acc?: number; - ignoreNext?: boolean; + locked?: boolean; } | null>(null); useEffect(() => { @@ -110,6 +112,47 @@ export function CanvasViewport({ showGrid, loading, activeTool, onToolChange }: }; }, [canvasEl]); + const [dropActive, setDropActive] = useState(false); + + useEffect(() => { + let dispose: (() => void) | undefined; + let cancelled = false; + + void (async () => { + try { + const { getCurrentWebview } = await import("@tauri-apps/api/webview"); + const unlisten = await getCurrentWebview().onDragDropEvent(async (event) => { + if (event.payload.type === "over") { + setDropActive(true); + return; + } + if (event.payload.type === "leave") { + setDropActive(false); + return; + } + setDropActive(false); + for (const path of event.payload.paths) { + if (!isImagePath(path)) continue; + const file = await readImageAtPath(path); + if (file) { + await addImageLayer(file.blob, file.name); + return; + } + } + }); + if (cancelled) unlisten(); + else dispose = unlisten; + } catch { + // Browser build: the HTML5 handlers below cover it. + } + })(); + + return () => { + cancelled = true; + dispose?.(); + }; + }, [addImageLayer]); + useEffect(() => { const host = hostRef.current; if (!host) return; @@ -213,7 +256,13 @@ export function CanvasViewport({ showGrid, loading, activeTool, onToolChange }: const canvas = getMutableCanvas(layerId); const ctx = canvas?.getContext("2d"); if (!canvas || !ctx) return; - strokeBrushes(ctx, from, to, brushSize / 2, foreground, erase); + // ensurePaintLayer normalises the paint target to document size with an + // identity transform, so stroke coordinates are already document space. + const layer = document?.layers.find((item) => item.id === layerId); + const transform = layer && layer.kind !== "adjustment" ? layer.transform : DEFAULT_TRANSFORM; + withSelectionClip(ctx, transform, (target) => { + strokeBrushes(target, from, to, brushSize / 2, foreground, erase); + }); schedulePaintFrame(layerId); } @@ -311,6 +360,12 @@ export function CanvasViewport({ showGrid, loading, activeTool, onToolChange }: const { screen } = toDoc(e); setHoverPos(screen); setBrushSizing(true); + // Pointer lock gives clean relative deltas without moving the OS cursor, + // so the size follows the drag smoothly and the cursor reappears exactly + // where it started. pin_cursor is the fallback where lock is refused. + const host = hostRef.current; + const locked = typeof host?.requestPointerLock === "function"; + if (locked) void Promise.resolve(host.requestPointerLock()).catch(() => {}); dragRef.current = { kind: "brush-size", lastX: e.clientX, @@ -319,7 +374,7 @@ export function CanvasViewport({ showGrid, loading, activeTool, onToolChange }: pinX: e.screenX, pinY: e.screenY, acc: 0, - ignoreNext: false, + locked, }; e.currentTarget.setPointerCapture(e.pointerId); return; @@ -333,6 +388,19 @@ export function CanvasViewport({ showGrid, loading, activeTool, onToolChange }: if (e.button !== 0) return; if (activeTool === "cursor") { + // A selection under the cursor wins over the focus box: dragging inside + // one is how you move the selected chunk, and Alt moves just the outline. + if (selectionStore.mask && selectionStore.hitTest(docPos.x, docPos.y)) { + if (e.altKey) { + beginStroke("Move selection"); + dragRef.current = { kind: "selection", lastX: e.clientX, lastY: e.clientY }; + } else { + beginPixelMove(); + dragRef.current = { kind: "pixels", lastX: e.clientX, lastY: e.clientY }; + } + e.currentTarget.setPointerCapture(e.pointerId); + return; + } if (focusBox && pointInBox(docPos, focusBox)) { const layer = document.layers.find((item) => item.id === focusBox.layerId); if (layer && !layer.locked && layer.kind !== "adjustment") { @@ -471,15 +539,10 @@ export function CanvasViewport({ showGrid, loading, activeTool, onToolChange }: const drag = dragRef.current; if (!drag) return; - if (drag.kind === "brush-size" && drag.startSize != null && drag.pinX != null && drag.pinY != null) { - if (drag.ignoreNext) { - drag.ignoreNext = false; - return; - } + if (drag.kind === "brush-size" && drag.startSize != null) { drag.acc = (drag.acc ?? 0) + e.movementX * 0.4; setBrushSize(drag.startSize + drag.acc); - drag.ignoreNext = true; - void pinCursor(drag.pinX, drag.pinY); + if (!drag.locked && drag.pinX != null && drag.pinY != null) void pinCursor(drag.pinX, drag.pinY); return; } @@ -512,6 +575,17 @@ export function CanvasViewport({ showGrid, loading, activeTool, onToolChange }: return; } + if (drag.kind === "selection") { + // Shifting the offset moves the marching ants, the hit test and the paint + // clip together, leaving the pixels underneath alone. + selectionStore.offsetX += (e.clientX - drag.lastX) / viewport.zoom; + selectionStore.offsetY += (e.clientY - drag.lastY) / viewport.zoom; + selectionStore.bump(); + drag.lastX = e.clientX; + drag.lastY = e.clientY; + return; + } + if (drag.kind === "paint" && drag.layerId && drag.lastDoc) { paintAt(drag.layerId, drag.lastDoc, docPos, activeTool === "eraser"); drag.lastDoc = docPos; @@ -540,7 +614,10 @@ export function CanvasViewport({ showGrid, loading, activeTool, onToolChange }: function onPointerUp() { const drag = dragRef.current; dragRef.current = null; - if (drag?.kind === "brush-size") setBrushSizing(false); + if (drag?.kind === "brush-size") { + setBrushSizing(false); + if (drag.locked && window.document.pointerLockElement) window.document.exitPointerLock(); + } if (!document) return; if (drag?.kind === "paint") { @@ -558,6 +635,10 @@ export function CanvasViewport({ showGrid, loading, activeTool, onToolChange }: setSelection(selectionStore.toDocumentSelection(), { history: false }); } + if (drag?.kind === "selection") { + setSelection(selectionStore.toDocumentSelection(), { history: false }); + } + if (drag?.kind === "crop-handle") { return; } @@ -670,6 +751,21 @@ export function CanvasViewport({ showGrid, loading, activeTool, onToolChange }: }} onWheel={onWheel} onDragStart={(e) => e.preventDefault()} + onDragOver={(e) => { + if (!e.dataTransfer.types.includes("Files")) return; + e.preventDefault(); + setDropActive(true); + }} + onDragLeave={() => setDropActive(false)} + onDrop={async (e) => { + // Browser build only; the desktop app receives paths through + // onDragDropEvent instead, because the webview swallows the DOM event. + const file = [...e.dataTransfer.files].find((item) => item.type.startsWith("image/")); + if (!file) return; + e.preventDefault(); + setDropActive(false); + await addImageLayer(file, file.name); + }} onContextMenu={(e) => { e.preventDefault(); if (e.altKey) return; @@ -785,6 +881,9 @@ export function CanvasViewport({ showGrid, loading, activeTool, onToolChange }: }} /> )} + {dropActive && ( +
+ )} {showBrushRing && (
)} {selectionStore.floating && ( - { + const floating = selectionStore.floating; + if (!node || !floating) return; + const ctx = node.getContext("2d"); + if (!ctx) return; + ctx.clearRect(0, 0, node.width, node.height); + ctx.drawImage(floating, 0, 0); + }} /> )}
diff --git a/src/components/ColorPickerDialog.tsx b/src/components/ColorPickerDialog.tsx new file mode 100644 index 0000000..334bdae --- /dev/null +++ b/src/components/ColorPickerDialog.tsx @@ -0,0 +1,223 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import type { Color } from "../engine/document/types"; +import { colorToCss } from "../engine/pixels/generate"; +import { colorToHex, hexToRgb, hslToRgb, hsvToRgb, rgbToHsl, rgbToHsv, type Hsv } from "../lib/color"; +import { Modal } from "./ui/Modal"; + +interface ColorPickerDialogProps { + color: Color; + onChange: (color: Color) => void; + onClose: () => void; +} + +const WHEEL = 168; +const RADIUS = WHEEL / 2; + +/** + * Hue/saturation wheel plus a value slider, with RGB, HSL, alpha and hex + * fields. HSV is the source of truth while the dialog is open so that dragging + * through black or grey does not lose the hue you picked. + */ +export function ColorPickerDialog({ color, onChange, onClose }: ColorPickerDialogProps) { + const [hsv, setHsv] = useState(() => rgbToHsv(color)); + const [alpha, setAlpha] = useState(color.a); + const [hexDraft, setHexDraft] = useState(() => colorToHex(color)); + const wheelRef = useRef(null); + const draggingRef = useRef(false); + + const rgb = useMemo(() => hsvToRgb(hsv), [hsv]); + const hsl = useMemo(() => rgbToHsl(rgb), [rgb]); + const current: Color = useMemo(() => ({ ...rgb, a: alpha }), [rgb, alpha]); + + useEffect(() => { + setHexDraft(colorToHex(rgb)); + }, [rgb.r, rgb.g, rgb.b]); + + // Repaint the wheel whenever value changes so it previews the current shade. + useEffect(() => { + const canvas = wheelRef.current; + const ctx = canvas?.getContext("2d"); + if (!canvas || !ctx) return; + + const image = ctx.createImageData(WHEEL, WHEEL); + for (let y = 0; y < WHEEL; y += 1) { + for (let x = 0; x < WHEEL; x += 1) { + const dx = x - RADIUS + 0.5; + const dy = y - RADIUS + 0.5; + const distance = Math.hypot(dx, dy); + const offset = (x + y * WHEEL) * 4; + if (distance > RADIUS) { + image.data[offset + 3] = 0; + continue; + } + const hue = (Math.atan2(dy, dx) * 180) / Math.PI + 90; + const { r, g, b } = hsvToRgb({ h: hue, s: Math.min(1, distance / RADIUS), v: hsv.v }); + image.data[offset] = r; + image.data[offset + 1] = g; + image.data[offset + 2] = b; + // Feather the rim so the circle does not look jagged. + image.data[offset + 3] = Math.round(255 * Math.min(1, RADIUS - distance)); + } + } + ctx.putImageData(image, 0, 0); + }, [hsv.v]); + + const pickFromWheel = useCallback((clientX: number, clientY: number) => { + const canvas = wheelRef.current; + if (!canvas) return; + const rect = canvas.getBoundingClientRect(); + const dx = clientX - rect.left - RADIUS; + const dy = clientY - rect.top - RADIUS; + const distance = Math.hypot(dx, dy); + const hue = (Math.atan2(dy, dx) * 180) / Math.PI + 90; + setHsv((prev) => ({ ...prev, h: (hue + 360) % 360, s: Math.min(1, distance / RADIUS) })); + }, []); + + const markerX = RADIUS + Math.sin((hsv.h * Math.PI) / 180) * hsv.s * RADIUS; + const markerY = RADIUS - Math.cos((hsv.h * Math.PI) / 180) * hsv.s * RADIUS; + + const setChannel = (channel: "r" | "g" | "b", value: number) => { + const next = { ...rgb, [channel]: Math.min(255, Math.max(0, Math.round(value || 0))) }; + setHsv(rgbToHsv(next)); + }; + + const setHslPart = (part: "h" | "s" | "l", value: number) => { + const next = { ...hsl, [part]: part === "h" ? value : value / 100 }; + setHsv(rgbToHsv(hslToRgb(next))); + }; + + return ( + +
+
+
+ { + draggingRef.current = true; + e.currentTarget.setPointerCapture(e.pointerId); + pickFromWheel(e.clientX, e.clientY); + }} + onPointerMove={(e) => draggingRef.current && pickFromWheel(e.clientX, e.clientY)} + onPointerUp={() => (draggingRef.current = false)} + /> +
+ + +
+ +
+
+ + +
+ + setChannel("r", v)} /> + setChannel("g", v)} /> + setChannel("b", v)} /> + + setHslPart("h", v)} /> + setHslPart("s", v)} /> + setHslPart("l", v)} /> + + setAlpha(Math.min(1, Math.max(0, v / 100)))} + /> + +
+ + +
+
+
+
+ ); +} + +function Row({ + label, + value, + max, + suffix, + onChange, +}: { + label: string; + value: number; + max: number; + suffix?: string; + onChange: (value: number) => void; +}) { + return ( + + ); +} diff --git a/src/components/FilterDialog.tsx b/src/components/FilterDialog.tsx new file mode 100644 index 0000000..1e8fa03 --- /dev/null +++ b/src/components/FilterDialog.tsx @@ -0,0 +1,111 @@ +import { useEffect, useMemo, useRef, useState } from "react"; +import type { Filter } from "../engine/filters/adjustments"; +import { beginFilter, previewFilter, revertFilter, type FilterTarget } from "../engine/filters/apply"; +import type { Layer } from "../engine/document/types"; +import { CanvasClearModal } from "./ui/CanvasClearModal"; +import { Slider } from "./ui/Slider"; + +export interface FilterParam { + key: string; + label: string; + min: number; + max: number; + step?: number; + initial: number; + suffix?: string; +} + +export interface FilterSpec { + name: string; + params: FilterParam[]; + build: (values: Record) => Filter; +} + +interface FilterDialogProps { + spec: FilterSpec; + layer: Layer; + scopedToSelection: boolean; + onApply: (filter: Filter) => void; + onClose: () => void; +} + +/** + * Runs a filter live on the layer so the canvas itself is the preview, then + * either commits it through the caller (which wraps it in a history step) or + * puts the original pixels back. + */ +export function FilterDialog({ spec, layer, scopedToSelection, onApply, onClose }: FilterDialogProps) { + const [values, setValues] = useState>(() => + Object.fromEntries(spec.params.map((param) => [param.key, param.initial])), + ); + const targetRef = useRef(null); + const committedRef = useRef(false); + + // Capture the untouched pixels once, and restore them if the dialog closes + // without applying. + useEffect(() => { + targetRef.current = beginFilter(layer); + return () => { + if (targetRef.current && !committedRef.current) revertFilter(targetRef.current); + targetRef.current = null; + }; + }, [layer]); + + const filter = useMemo(() => spec.build(values), [spec, values]); + + useEffect(() => { + if (targetRef.current) previewFilter(targetRef.current, filter); + }, [filter]); + + return ( + +
+ {spec.params.length === 0 && ( +

+ Applies immediately with no settings to adjust. +

+ )} + + {spec.params.map((param) => ( + setValues((prev) => ({ ...prev, [param.key]: value }))} + /> + ))} + +

+ {scopedToSelection ? "Applies to the current selection." : "Applies to the whole layer."} +

+ +
+ + +
+
+
+ ); +} + +function formatValue(value: number, param: FilterParam): string { + const rounded = param.step && param.step < 1 ? value.toFixed(1) : String(Math.round(value)); + return `${rounded}${param.suffix ?? ""}`; +} diff --git a/src/components/InspectorPanel.tsx b/src/components/InspectorPanel.tsx index 817811d..09f3052 100644 --- a/src/components/InspectorPanel.tsx +++ b/src/components/InspectorPanel.tsx @@ -6,6 +6,7 @@ import { cn } from "../lib/utils"; import { colorToCss } from "../engine/pixels/generate"; import { useActiveLayer, useDocumentStore } from "../store/document-store"; import { useEditorStore } from "../store/editor-store"; +import { ColorPickerDialog } from "./ColorPickerDialog"; import { ContextMenu, type ContextMenuState } from "./ContextMenu"; import { Slider } from "./ui/Slider"; import { Skeleton } from "./ui/Skeleton"; @@ -28,6 +29,8 @@ export function InspectorPanel({ loading }: InspectorPanelProps) { const foreground = useEditorStore((s) => s.foreground); const brushSize = useEditorStore((s) => s.brushSize); const setBrushSize = useEditorStore((s) => s.setBrushSize); + const setForeground = useEditorStore((s) => s.setForeground); + const [pickerOpen, setPickerOpen] = useState(false); const [menu, setMenu] = useState(null); if (loading || !document) { @@ -75,11 +78,15 @@ export function InspectorPanel({ loading }: InspectorPanelProps) { -
+
+ ) : ( @@ -186,6 +193,9 @@ export function InspectorPanel({ loading }: InspectorPanelProps) { setMenu(null)} /> + {pickerOpen && ( + setPickerOpen(false)} /> + )} ); } diff --git a/src/components/MenuBar.tsx b/src/components/MenuBar.tsx index ccb1a6e..b731cb8 100644 --- a/src/components/MenuBar.tsx +++ b/src/components/MenuBar.tsx @@ -7,6 +7,8 @@ export interface MenuAction { disabled?: boolean; separator?: false; action?: () => void; + /** Present on a submenu; `action` is ignored when it is. */ + items?: MenuAction[]; } export interface MenuSeparator { @@ -80,30 +82,10 @@ export function MenuBar({ menus }: MenuBarProps) { {menu.items.map((item, i) => item.separator ? (
+ ) : item.items ? ( + ) : ( - + ), )}
@@ -113,3 +95,59 @@ export function MenuBar({ menus }: MenuBarProps) { ); } + +function MenuButton({ item, onPick }: { item: MenuAction; onPick: () => void }) { + return ( + + ); +} + +function Submenu({ item, onPick }: { item: MenuAction; onPick: () => void }) { + const [open, setOpen] = useState(false); + + return ( +
setOpen(true)} onMouseLeave={() => setOpen(false)}> + + + {open && !item.disabled && ( +
+ {item.items?.map((child) => )} +
+ )} +
+ ); +} diff --git a/src/components/OptionsBar.tsx b/src/components/OptionsBar.tsx index 660b444..4bcd69a 100644 --- a/src/components/OptionsBar.tsx +++ b/src/components/OptionsBar.tsx @@ -1,7 +1,9 @@ +import { useState } from "react"; import type { ToolId } from "./Toolbar"; import { colorToCss } from "../engine/pixels/generate"; import { formatBrushSize } from "../lib/round-brush-size"; import { useEditorStore } from "../store/editor-store"; +import { ColorPickerDialog } from "./ColorPickerDialog"; import { Slider } from "./ui/Slider"; @@ -19,11 +21,17 @@ export function OptionsBar({ activeTool }: OptionsBarProps) { const systemFonts = useEditorStore((s) => s.systemFonts); const setFontFamily = useEditorStore((s) => s.setFontFamily); const setFontSize = useEditorStore((s) => s.setFontSize); + const setForeground = useEditorStore((s) => s.setForeground); + const [pickerOpen, setPickerOpen] = useState(false); return (
{(activeTool === "brush" || activeTool === "eraser" || activeTool === "eyedropper" || activeTool === "text") && ( - + setPickerOpen(true)} + /> )} {(activeTool === "brush" || activeTool === "eraser" || activeTool === "heal") && (
); } -function ColorChip({ color, label }: { color: { r: number; g: number; b: number; a: number }; label: string }) { +function ColorChip({ + color, + label, + onClick, +}: { + color: { r: number; g: number; b: number; a: number }; + label: string; + onClick: () => void; +}) { return ( -
+
+ ); } diff --git a/src/components/Toolbar.tsx b/src/components/Toolbar.tsx index 000a798..476e5d2 100644 --- a/src/components/Toolbar.tsx +++ b/src/components/Toolbar.tsx @@ -23,10 +23,10 @@ const TOOLS = [ { id: "brush", label: "Brush", shortcut: "B", icon: Brush }, { id: "wand", label: "Magic Wand", shortcut: "W", icon: Wand2 }, { id: "crop", label: "Crop", shortcut: "C", icon: Crop }, + { id: "eraser", label: "Eraser", shortcut: "E", icon: Eraser }, { id: "eyedropper", label: "Eyedropper", shortcut: "I", icon: Pipette }, { id: "text", label: "Text", shortcut: "T", icon: Type }, { id: "heal", label: "Healing", shortcut: "J", icon: Bandage }, - { id: "eraser", label: "Eraser", shortcut: "E", icon: Eraser }, { id: "gradient", label: "Gradient", shortcut: "G", icon: GraduationCap }, ] as const satisfies ReadonlyArray<{ id: string; diff --git a/src/components/ui/CanvasClearModal.tsx b/src/components/ui/CanvasClearModal.tsx new file mode 100644 index 0000000..270cd04 --- /dev/null +++ b/src/components/ui/CanvasClearModal.tsx @@ -0,0 +1,94 @@ +import { useEffect, useState, type ReactNode } from "react"; + +interface Rect { + top: number; + left: number; + width: number; + height: number; +} + +/** + * A modal for tools that edit the image live. It sits in the top-left corner + * rather than centred, and dims everything *except* the canvas, so the picture + * you are adjusting keeps its true colours while the rest of the interface + * recedes. + * + * The dim is drawn as four panels around the canvas rather than one sheet with + * a hole, so the canvas is never composited through a translucent layer. + */ +export function CanvasClearModal({ + title, + children, + onClose, + width = 340, +}: { + title: string; + children: ReactNode; + onClose: () => void; + width?: number; +}) { + const [rect, setRect] = useState(null); + + useEffect(() => { + const host = document.querySelector(".pv-canvas"); + if (!host) return; + + const measure = () => { + const box = host.getBoundingClientRect(); + setRect({ top: box.top, left: box.left, width: box.width, height: box.height }); + }; + measure(); + + const observer = new ResizeObserver(measure); + observer.observe(host); + window.addEventListener("resize", measure); + window.addEventListener("scroll", measure, true); + return () => { + observer.disconnect(); + window.removeEventListener("resize", measure); + window.removeEventListener("scroll", measure, true); + }; + }, []); + + useEffect(() => { + function onKey(e: KeyboardEvent) { + if (e.key === "Escape") onClose(); + } + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, [onClose]); + + const shade = "fixed bg-black/55"; + + return ( + <> + {rect && ( +