// Selection tools: rectangle, ellipse, lasso (freehand + polygonal), magic wand. import { Tool, selectionModeFor } from './tool.js'; import { combineSelection, shapeMask } from '../core/selection.js'; import { regionMask, regionToCanvas } from '../imaging/floodfill.js'; import { flattenToCanvas } from '../render/compositor.js'; const MODE_FIELD = { key: 'mode', label: '', type: 'buttons', default: 'replace', options: [ { value: 'replace', icon: 'selReplace', title: 'New selection' }, { value: 'add', icon: 'selAdd', title: 'Add to selection (Shift)' }, { value: 'subtract', icon: 'selSubtract', title: 'Subtract from selection (Alt)' }, { value: 'intersect', icon: 'selIntersect', title: 'Intersect with selection (Shift+Alt)' }, ], }; const FEATHER_FIELD = { key: 'feather', label: 'Feather', type: 'range', min: 0, max: 100, default: 0, unit: 'px' }; const AA_FIELD = { key: 'antialias', label: 'Anti-alias', type: 'checkbox', default: true }; const ASPECTS = { free: null, '1:1': 1, '4:3': 4 / 3, '3:2': 3 / 2, '16:9': 16 / 9, '3:4': 3 / 4, '2:3': 2 / 3, '9:16': 9 / 16 }; /** Shared behaviour: build mask -> combine -> feather -> commit; drag inside selection to move it. */ class SelectionToolBase extends Tool { get cursor() { return 'crosshair'; } get hint() { return 'Shift: add · Alt: subtract · Shift+Alt: intersect · drag inside selection to move it'; } commitShape(mask, mode) { const doc = this.doc; let sel = combineSelection(doc.selection, mask, mode); if (sel && this.options.feather > 0) sel = sel.feathered(this.options.feather); doc.setSelection(sel, sel ? 'Select' : 'Deselect'); } /** Start dragging the selection outline if the click lands inside it. Returns true if handled. */ maybeStartMove(e, p) { const doc = this.doc; if (!doc.selection || e.shiftKey || e.altKey || this.options.mode !== 'replace') return false; if (!doc.selection.contains(p.x, p.y)) return false; this.moving = { start: p, original: doc.selection, dx: 0, dy: 0 }; return true; } moveDrag(p) { const m = this.moving; ({ dx: m.dx, dy: m.dy } = this.app.guides.snapMove(m.original.bounds, Math.round(p.x - m.start.x), Math.round(p.y - m.start.y))); this.app.renderer.request(); } moveEnd() { const m = this.moving; this.moving = null; if (m.dx || m.dy) this.doc.setSelection(m.original.translated(m.dx, m.dy), 'Move selection'); this.app.renderer.request(); } get hidesSelection() { return !!this.moving; } drawMoving(ctx, view, doc) { const m = this.moving; const { zoom, panX, panY } = doc.view; const path = m.original.outline; ctx.save(); ctx.translate(panX + m.dx * zoom, panY + m.dy * zoom); ctx.scale(zoom, zoom); ctx.lineWidth = 1 / zoom; ctx.strokeStyle = '#000'; ctx.stroke(path); ctx.setLineDash([4 / zoom, 4 / zoom]); ctx.strokeStyle = '#fff'; ctx.stroke(path); ctx.restore(); } onKeyDown(e) { if (this.moving) return false; const doc = this.doc; if (doc?.selection && e.key.startsWith('Arrow') && !e.ctrlKey && !e.metaKey) { const step = e.shiftKey ? 10 : 1; const dx = e.key === 'ArrowLeft' ? -step : e.key === 'ArrowRight' ? step : 0; const dy = e.key === 'ArrowUp' ? -step : e.key === 'ArrowDown' ? step : 0; doc.setSelection(doc.selection.translated(dx, dy), 'Nudge selection'); return true; } return false; } } class MarqueeTool extends SelectionToolBase { static shape = 'rect'; onPointerDown(e, p) { if (this.maybeStartMove(e, p)) return; p = this.app.guides.snapPoint(p); this.drag = { start: p, end: p, mode: selectionModeFor(e, this.options.mode) }; } onPointerMove(e, p) { if (this.moving) return this.moveDrag(p); if (!this.drag) return; this.drag.end = this.app.guides.snapPoint(p); this.drag.shift = e.shiftKey; this.drag.alt = e.altKey; this.app.renderer.request(); this.app.setStatusHint(this.rect ? `${Math.round(Math.abs(this.rect.w))} × ${Math.round(Math.abs(this.rect.h))}` : ''); } get rect() { const d = this.drag; if (!d) return null; let dx = d.end.x - d.start.x, dy = d.end.y - d.start.y; const aspect = ASPECTS[this.options.aspect] ?? null; const ratio = aspect ?? (d.shift && d.mode !== 'add' ? 1 : null); if (ratio) { const w = Math.max(Math.abs(dx), Math.abs(dy) * ratio); dx = Math.sign(dx || 1) * w; dy = Math.sign(dy || 1) * (w / ratio); } let x0 = d.start.x, y0 = d.start.y; if (d.alt && d.mode !== 'subtract') { x0 -= dx; y0 -= dy; dx *= 2; dy *= 2; } const shapeIsRect = this.constructor.shape === 'rect'; const r = (v) => (shapeIsRect ? Math.round(v) : v); const x = r(Math.min(x0, x0 + dx)), y = r(Math.min(y0, y0 + dy)); return { x, y, w: r(Math.max(x0, x0 + dx)) - x, h: r(Math.max(y0, y0 + dy)) - y }; } onPointerUp(e, p) { if (this.moving) return this.moveEnd(); if (!this.drag) return; const r = this.rect; const mode = this.drag.mode; this.drag = null; const doc = this.doc; if (!r || r.w < 1 || r.h < 1) { if (mode === 'replace') doc.setSelection(null, 'Deselect'); this.app.renderer.request(); return; } const mask = shapeMask(doc.width, doc.height, { type: this.constructor.shape, ...r }, this.options.antialias); this.commitShape(mask, mode); } cancel() { this.drag = null; this.moving = null; } drawOverlay(ctx, view, doc) { if (this.moving) return this.drawMoving(ctx, view, doc); const r = this.rect; if (!r) return; if (this.constructor.shape === 'rect') { view.outlineRect(r, doc); } else { const path = new Path2D(); path.ellipse(r.x + r.w / 2, r.y + r.h / 2, Math.abs(r.w / 2), Math.abs(r.h / 2), 0, 0, Math.PI * 2); view.outlinePath(path, doc); } } } export class RectSelectTool extends MarqueeTool { static id = 'rect-select'; static label = 'Rectangle Select'; static icon = 'rectSelect'; static shortcut = 'M'; static shape = 'rect'; static schema = [ MODE_FIELD, FEATHER_FIELD, { key: 'aspect', label: 'Aspect', type: 'select', default: 'free', options: Object.keys(ASPECTS).map((k) => ({ value: k, label: k === 'free' ? 'Free' : k })) }, { key: 'antialias', type: 'hidden', default: false }, ]; } export class EllipseSelectTool extends MarqueeTool { static id = 'ellipse-select'; static label = 'Ellipse Select'; static icon = 'ellipseSelect'; static shortcut = 'M'; static shape = 'ellipse'; static schema = [ MODE_FIELD, FEATHER_FIELD, AA_FIELD, { key: 'aspect', label: 'Aspect', type: 'select', default: 'free', options: Object.keys(ASPECTS).map((k) => ({ value: k, label: k === 'free' ? 'Free' : k })) }, ]; } export class LassoTool extends SelectionToolBase { static id = 'lasso'; static label = 'Lasso'; static icon = 'lasso'; static shortcut = 'L'; static schema = [ MODE_FIELD, FEATHER_FIELD, AA_FIELD, { key: 'polygonal', label: 'Polygonal', type: 'checkbox', default: false }, ]; get hint() { return this.options.polygonal ? 'Click to add points · double-click / Enter / click first point to close · Esc cancels · Backspace removes point' : super.hint; } get animatedOverlay() { return !!this.points; } onPointerDown(e, p) { if (this.options.polygonal) { if (!this.points) { if (this.maybeStartMove(e, p)) return; this.mode = selectionModeFor(e, this.options.mode); this.points = [p]; this.hover = p; } else { const first = this.points[0]; const zoom = this.doc.view.zoom; if (this.points.length > 2 && Math.hypot(p.x - first.x, p.y - first.y) * zoom < 8) this.finish(); else this.points.push(p); } this.app.renderer.request(); return; } if (this.maybeStartMove(e, p)) return; this.mode = selectionModeFor(e, this.options.mode); this.points = [p]; } onPointerMove(e, p) { if (this.moving) return this.moveDrag(p); if (!this.points) return; if (this.options.polygonal) { this.hover = p; } else { const last = this.points[this.points.length - 1]; if (Math.hypot(p.x - last.x, p.y - last.y) * this.doc.view.zoom >= 2) this.points.push(p); } this.app.renderer.request(); } onHover(e, p) { if (this.points && this.options.polygonal) { this.hover = p; this.app.renderer.request(); } } onPointerUp() { if (this.moving) return this.moveEnd(); if (!this.points || this.options.polygonal) return; this.finish(); } onDoubleClick() { if (this.points && this.options.polygonal) this.finish(); } finish() { const pts = this.points; this.points = null; const doc = this.doc; if (!pts || pts.length < 3) { if (this.mode === 'replace') doc.setSelection(null, 'Deselect'); this.app.renderer.request(); return; } const mask = shapeMask(doc.width, doc.height, { type: 'polygon', points: pts }, this.options.antialias); this.commitShape(mask, this.mode); } onKeyDown(e) { if (this.points) { if (e.key === 'Enter') { this.finish(); return true; } if (e.key === 'Escape') { this.cancel(); return true; } if (e.key === 'Backspace' && this.options.polygonal) { this.points.pop(); if (!this.points.length) this.points = null; this.app.renderer.request(); return true; } } return super.onKeyDown(e); } cancel() { this.points = null; this.moving = null; this.app.renderer.request(); } commit() { if (this.points && this.options.polygonal) this.finish(); } drawOverlay(ctx, view, doc) { if (this.moving) return this.drawMoving(ctx, view, doc); if (!this.points) return; const path = new Path2D(); this.points.forEach((pt, i) => (i ? path.lineTo(pt.x, pt.y) : path.moveTo(pt.x, pt.y))); if (this.options.polygonal && this.hover) path.lineTo(this.hover.x, this.hover.y); view.outlinePath(path, doc); if (this.options.polygonal) view.handle(this.points[0], 7, doc); } } export class MagicWandTool extends SelectionToolBase { static id = 'wand'; static label = 'Magic Wand'; static icon = 'wand'; static shortcut = 'W'; static schema = [ MODE_FIELD, { key: 'tolerance', label: 'Tolerance', type: 'range', min: 0, max: 255, default: 32 }, { key: 'contiguous', label: 'Contiguous', type: 'checkbox', default: true }, { key: 'sampleMerged', label: 'All layers', type: 'checkbox', default: false }, AA_FIELD, FEATHER_FIELD, ]; get hint() { return 'Click to select similar colors · Shift: add · Alt: subtract'; } onPointerDown(e, p) { const doc = this.doc; const mode = selectionModeFor(e, this.options.mode); const src = this.options.sampleMerged ? flattenToCanvas(doc) : doc.activeLayer?.canvas; if (!src) return; const id = src.getContext('2d', { willReadFrequently: true }).getImageData(0, 0, doc.width, doc.height); const region = regionMask(id, p.x, p.y, this.options.tolerance, this.options.contiguous); if (!region) { if (mode === 'replace') doc.setSelection(null, 'Deselect'); return; } const mask = regionToCanvas(region, doc.width, doc.height, this.options.antialias); this.commitShape(mask, mode); } }