// Base class for tools. Tools receive pointer events in document coordinates and // may draw overlays in screen space. `options` is a schema rendered by the // tool-options bar; values persist per tool in localStorage. export class Tool { constructor(app) { this.app = app; this.options = {}; this.active = false; } static id = 'tool'; static label = 'Tool'; static icon = 'brush'; static shortcut = ''; /** Option schema: [{key, label, type: 'range'|'number'|'select'|'checkbox'|'buttons'|'text'|'font', ...}] */ static schema = []; get id() { return this.constructor.id; } get label() { return this.constructor.label; } get doc() { return this.app.doc; } get cursor() { return 'crosshair'; } initOptions() { const saved = this.app.prefs.get(`tool.${this.id}`, {}); for (const f of this.constructor.schema) { if (f.key) this.options[f.key] = saved[f.key] ?? f.default; } } setOption(key, value) { this.options[key] = value; this.app.prefs.set(`tool.${this.id}`, { ...this.options }); this.onOptionChange?.(key, value); this.app.renderer.request(); } activate() {} deactivate() {} /** Commit any pending interactive state (called before switching tools / documents). */ commit() {} /** Abort pending interactive state. */ cancel() {} onPointerDown(_e, _p) {} onPointerMove(_e, _p) {} onPointerUp(_e, _p) {} onHover(_e, _p) {} onDoubleClick(_e, _p) {} /** Return true if the key was handled. */ onKeyDown(_e) { return false; } /** Info shown in the status bar while this tool is active. */ get hint() { return ''; } /** Common: reject edits on locked/hidden layers with a message. Returns the edit target or null. */ requireEditable({ allowText = false } = {}) { const doc = this.doc; const target = doc?.editTarget; if (!target) return null; const { layer, key } = target; if (layer.locked) { this.app.toast('Layer is locked'); return null; } if (!layer.visible) { this.app.toast('Layer is hidden'); return null; } if (layer.isText && key === 'canvas' && !allowText) { this.app.toast('Text layer: rasterize it first (Layer ▸ Rasterize)'); return null; } return target; } } /** Selection mode from modifier keys + the tool's default mode option. */ export function selectionModeFor(e, fallback = 'replace') { if (e.shiftKey && e.altKey) return 'intersect'; if (e.shiftKey) return 'add'; if (e.altKey) return 'subtract'; return fallback; } /** Constrain a vector to multiples of 45°. */ export function snap45(dx, dy) { const ang = Math.round(Math.atan2(dy, dx) / (Math.PI / 4)) * (Math.PI / 4); const len = Math.hypot(dx, dy); return { x: Math.cos(ang) * len, y: Math.sin(ang) * len }; }