1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
|
// 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 };
}
|