// Application shell: documents, tools, colors, input routing and UI wiring. import { Emitter } from './core/emitter.js'; import { ImageDocument } from './core/document.js'; import { Color } from './core/color.js'; import { Layer } from './core/layer.js'; import { addLayer } from './core/ops.js'; import { el, pickFiles, downloadBlob, stripExtension, prettyShortcut } from './core/util.js'; import { Renderer, MIN_ZOOM, MAX_ZOOM } from './render/renderer.js'; import { registerActions } from './actions.js'; import { MenuBar } from './ui/menu.js'; import { buildMenus, layerContextMenu, canvasContextMenu } from './ui/menudef.js'; import { Toolbox, ToolOptionsBar, DocTabs, StatusBar } from './ui/chrome.js'; import { LayersPanel } from './ui/panels/layers.js'; import { ColorPanel } from './ui/panels/color.js'; import { HistoryPanel } from './ui/panels/history.js'; import { NavigatorPanel } from './ui/panels/navigator.js'; import { isDialogOpen, confirmDialog, alertDialog } from './ui/dialogs.js'; import { icon } from './ui/icons.js'; import { Clipboard } from './io/clipboard.js'; import { Autosave } from './io/autosave.js'; import { saveProject, loadProject, isProjectFile, PROJECT_EXT } from './io/project.js'; import { decodeImageFile, isImageFile, IMAGE_ACCEPT } from './io/import.js'; import { FONT_FAMILIES } from './tools/text.js'; import { GuideController } from './ui/guides.js'; import { historyLimits } from './core/history.js'; import { MoveTool } from './tools/move.js'; import { RectSelectTool, EllipseSelectTool, LassoTool, MagicWandTool } from './tools/select.js'; import { CropTool } from './tools/crop.js'; import { BrushTool, PencilTool, EraserTool } from './tools/paint.js'; import { BucketTool, GradientTool, ShapeTool } from './tools/fill.js'; import { TextTool } from './tools/text.js'; import { HandTool, ZoomTool, EyedropperTool } from './tools/nav.js'; import { CloneTool, SmudgeTool, ToningTool } from './tools/retouch.js'; import { TransformTool } from './tools/transform.js'; const TOOL_CLASSES = [ MoveTool, TransformTool, RectSelectTool, EllipseSelectTool, LassoTool, MagicWandTool, CropTool, EyedropperTool, BrushTool, PencilTool, EraserTool, CloneTool, SmudgeTool, ToningTool, BucketTool, GradientTool, TextTool, ShapeTool, HandTool, ZoomTool, ]; const TOOL_ORDER = [ 'move', 'transform', 'rect-select', 'ellipse-select', 'lasso', 'wand', 'crop', 'eyedropper', '-', 'brush', 'pencil', 'eraser', 'clone', 'smudge', 'dodge', 'bucket', 'gradient', '-', 'text', 'shape', '-', 'hand', 'zoom', ]; class Prefs { constructor(ns = 'atelier.') { this.ns = ns; } get(key, fallback) { try { const v = localStorage.getItem(this.ns + key); return v == null ? fallback : JSON.parse(v); } catch { return fallback; } } set(key, value) { try { localStorage.setItem(this.ns + key, JSON.stringify(value)); } catch { /* storage full or blocked */ } } } /** Convert a keyboard event to a shortcut string like "Ctrl+Shift+Z". */ export function shortcutOf(e) { const codeMap = { BracketLeft: '[', BracketRight: ']', Backslash: '\\', Quote: "'", Slash: '/', Equal: '=', Minus: '-', Comma: ',', Period: '.', Semicolon: ';', Backquote: '`', NumpadAdd: '=', NumpadSubtract: '-', }; let key; if (codeMap[e.code]) key = codeMap[e.code]; else if (/^Key[A-Z]$/.test(e.code)) key = e.code.slice(3); else if (/^Digit\d$/.test(e.code)) key = e.code.slice(5); else key = e.key.length === 1 ? e.key.toUpperCase() : e.key; if (key === '+') key = '='; const parts = []; if (e.ctrlKey || e.metaKey) parts.push('Ctrl'); if (e.altKey) parts.push('Alt'); if (e.shiftKey) parts.push('Shift'); parts.push(key); return parts.join('+'); } export class App extends Emitter { constructor(root) { super(); this.root = root; this.prefs = new Prefs(); this.documents = []; this.doc = null; this.untitledCounter = 0; this.colors = { fg: Color.from(this.prefs.get('fg', '#000000')), bg: Color.from(this.prefs.get('bg', '#ffffff')), }; this.toolClasses = new Map(TOOL_CLASSES.map((T) => [T.id, T])); this.tools = new Map(); this.tool = null; this.spaceDown = false; this.pointerDown = null; this.ui = {}; } init() { this.applyTheme(this.prefs.get('theme', 'dark')); historyLimits.entries = this.prefs.get('historySteps', historyLimits.entries); this.buildLayout(); this.guides = new GuideController(this); this.renderer = new Renderer(this, this.workspace); this.renderer.showPixelGrid = this.prefs.get('pixelGrid', true); for (const T of TOOL_CLASSES) { const t = new T(this); t.initOptions(); this.tools.set(T.id, t); } this.actions = registerActions(this); this.shortcuts = new Map(); for (const a of this.actions.values()) { if (!a.shortcut) continue; if (this.shortcuts.has(a.shortcut)) console.warn(`Shortcut ${a.shortcut} used by ${this.shortcuts.get(a.shortcut)} and ${a.id}`); this.shortcuts.set(a.shortcut, a.id); } this.clipboard = new Clipboard(this); this.autosave = new Autosave(this); this.ui.menu = new MenuBar(this, this.menuHost, buildMenus()); this.ui.layerContextMenu = layerContextMenu; this.ui.toolbox = new Toolbox(this, this.toolboxHost, TOOL_ORDER); this.ui.toolOptions = new ToolOptionsBar(this, this.optionsHost); this.ui.tabs = new DocTabs(this, this.tabsHost); this.ui.status = new StatusBar(this, this.statusHost); this.ui.navigator = new NavigatorPanel(this, this.panelsHost); this.ui.color = new ColorPanel(this, this.panelsHost); this.ui.layers = new LayersPanel(this, this.panelsHost); this.ui.history = new HistoryPanel(this, this.panelsHost); for (const title of this.panelsHost.querySelectorAll('.panel-title')) { const panel = title.parentElement; const key = `panel.${[...panel.classList].find((c) => c.endsWith('-panel'))}.collapsed`; if (this.prefs.get(key, panel.classList.contains('nav-panel'))) panel.classList.add('collapsed'); title.addEventListener('click', () => { panel.classList.toggle('collapsed'); this.prefs.set(key, panel.classList.contains('collapsed')); }); } this.bindInput(); this.setTool(this.prefs.get('tool', 'brush')); this.updateWelcome(); window.addEventListener('beforeunload', (e) => { if (this.documents.some((d) => d.isModified)) { this.autosave.tick(true); e.preventDefault(); e.returnValue = ''; } }); this.autosave.offerRecovery(); return this; } /** theme: 'dark' | 'light' | 'auto' (follow the OS setting). */ applyTheme(theme) { this.prefs.set('theme', theme); const media = window.matchMedia?.('(prefers-color-scheme: light)'); const apply = () => { document.documentElement.dataset.theme = theme === 'auto' ? (media?.matches ? 'light' : 'dark') : theme; this.renderer?.request(); }; if (!this._themeListener && media) { this._themeListener = () => { if (this.prefs.get('theme') === 'auto') apply(); }; media.addEventListener?.('change', this._themeListener); } apply(); } buildLayout() { const fontList = el('datalist', { id: 'font-list' }, ...FONT_FAMILIES.map((f) => el('option', { value: f }))); this.menuHost = el('header', { class: 'top-bar' }); this.optionsHost = el('div', { class: 'options-host' }); this.toolboxHost = el('aside', { class: 'toolbox-host' }); this.tabsHost = el('div', { class: 'tabs-host' }); this.workspace = el('div', { class: 'workspace', tabindex: '0' }); this.panelsHost = el('aside', { class: 'panels-host' }); this.statusHost = el('footer', { class: 'status-host' }); this.welcome = this.buildWelcome(); this.workspace.appendChild(this.welcome); this.toasts = el('div', { class: 'toasts' }); this.busyEl = el('div', { class: 'busy' }, el('div', { class: 'spinner' })); this.root.append( fontList, this.menuHost, this.optionsHost, el('main', { class: 'main' }, this.toolboxHost, el('section', { class: 'center' }, this.tabsHost, this.workspace), this.panelsHost), this.statusHost, this.toasts, this.busyEl, ); this.menuHost.appendChild(el('div', { class: 'brand', title: 'Atelier' }, el('span', { class: 'brand-mark' }), 'Atelier')); } buildWelcome() { const card = (label, sub, onclick, iconName) => el('button', { type: 'button', class: 'welcome-card', onclick }, el('span', { html: icon(iconName, 28) }), el('strong', {}, label), el('small', {}, sub)); return el('div', { class: 'welcome' }, el('h1', {}, 'Atelier'), el('p', {}, 'Layered image editing in your browser. Drop an image or project anywhere to open it.'), el('div', { class: 'welcome-cards' }, card('New image', 'Blank canvas', () => this.run('file.new'), 'plus'), card('Open…', `Images or ${PROJECT_EXT} projects`, () => this.run('file.open'), 'folder'), card('Paste', 'From clipboard', () => this.run('edit.paste'), 'duplicate'), card('Quick canvas', '1200 × 800 white', () => this.newDocument({ width: 1200, height: 800 }), 'image')), el('p', { class: 'welcome-tip' }, 'Tip: press ', el('kbd', {}, prettyShortcut('Ctrl+K')), ' to search every command and tool.')); } updateWelcome() { this.welcome.style.display = this.doc ? 'none' : ''; this.renderer?.canvas.classList.toggle('hidden', !this.doc); } // ------------------------------------------------------------------ documents addDocument(doc) { this.documents.push(doc); doc.on('change', (info) => { if (doc !== this.doc) return; this.renderer.request(); this.emit('docChange', info); if (doc.activeLayerId !== this._lastActiveLayer) { this._lastActiveLayer = doc.activeLayerId; this.emit('activeLayer'); } }); doc.on('history', () => { if (doc === this.doc) this.emit('history'); }); this.setDocument(doc); this.emit('docs'); return doc; } newDocument(opts = {}) { const doc = new ImageDocument(opts); if (!opts.name) { this.untitledCounter++; doc.name = `Untitled-${this.untitledCounter}`; } return this.addDocument(doc); } setDocument(doc) { if (this.doc === doc) return; this.tool?.commit(); this.tool?.cancel?.(); this.doc = doc; this._lastActiveLayer = doc?.activeLayerId; this.updateWelcome(); if (doc?.view.needsFit) this.renderer.fit(doc); this.renderer.request(); this.emit('doc'); this.emit('activeLayer'); this.emit('view'); // Tools hold per-document state; re-activate to reset. Free Transform would // start transforming the new document, so leave it instead. if (this.tool?.id === 'transform') this.setTool(this.previousToolId || 'move'); else if (this.tool) { this.tool.deactivate(); this.tool.activate(); } } async closeDocument(doc) { if (!doc) return; if (doc.isModified) { this.setDocument(doc); const r = await confirmDialog(`Save changes to “${doc.name}” before closing?`, { title: 'Unsaved changes', ok: 'Save', cancel: 'Cancel', extra: { label: "Don't save", value: 'discard' }, }); if (r === false || r === null) return; if (r === true && !(await this.saveProject(false))) return; } if (doc === this.doc) this.tool?.cancel?.(); const idx = this.documents.indexOf(doc); this.documents.splice(idx, 1); if (this.doc === doc) { this.doc = null; this.setDocument(this.documents[Math.min(idx, this.documents.length - 1)] || null); } this.emit('docs'); this.updateWelcome(); this.autosave.tick(true); } async openFiles() { const files = await pickFiles({ accept: `${IMAGE_ACCEPT},${PROJECT_EXT}`, multiple: true }); for (const f of files) await this.openFile(f); } async openFile(file) { this.busy(true); try { if (await isProjectFile(file)) { const { doc } = await loadProject(file); doc.name = stripExtension(file.name); this.addDocument(doc); this.toast(`Opened project ${file.name}`); return; } const canvas = await decodeImageFile(file); const doc = new ImageDocument({ width: canvas.width, height: canvas.height, name: stripExtension(file.name) || 'Image', background: null }); doc.layers[0].name = 'Background'; doc.layers[0].ctx.drawImage(canvas, 0, 0); doc.layers[0].touch(); this.addDocument(doc); } catch (err) { alertDialog(err.message || String(err), 'Could not open file'); } finally { this.busy(false); } } async placeImageFile(file) { if (!this.doc) return this.openFile(file); try { const canvas = await decodeImageFile(file); const doc = this.doc; const layer = new Layer(doc.width, doc.height, { name: stripExtension(file.name) || 'Image' }); // scale down to fit if larger than the canvas, centre it const k = Math.min(1, doc.width / canvas.width, doc.height / canvas.height); const w = canvas.width * k, h = canvas.height * k; layer.ctx.imageSmoothingQuality = 'high'; layer.ctx.drawImage(canvas, Math.round((doc.width - w) / 2), Math.round((doc.height - h) / 2), w, h); addLayer(doc, layer, { label: 'Place image' }); } catch (err) { alertDialog(err.message || String(err), 'Could not place image'); } } /** Save the active document as a project. Returns true on success. */ async saveProject(saveAs) { const doc = this.doc; if (!doc) return false; this.tool?.commit(); this.busy(true); try { const blob = await saveProject(doc); const filename = `${stripExtension(doc.name)}${PROJECT_EXT}`; if (window.showSaveFilePicker && this.prefs.get('useFilePicker', true)) { try { if (!doc.fileHandle || saveAs) { doc.fileHandle = await window.showSaveFilePicker({ suggestedName: filename, types: [{ description: 'Atelier project', accept: { 'application/x-atelier': [PROJECT_EXT] } }], }); doc.name = stripExtension(doc.fileHandle.name); } const w = await doc.fileHandle.createWritable(); await w.write(blob); await w.close(); } catch (err) { if (err.name === 'AbortError') return false; console.warn('File picker unavailable, falling back to download', err); downloadBlob(blob, filename); } } else { downloadBlob(blob, filename); } doc.history.markSaved(); this.emit('docs'); this.toast(`Saved ${doc.name}${PROJECT_EXT}`); this.autosave.tick(true); return true; } catch (err) { alertDialog(`Could not save: ${err.message}`); return false; } finally { this.busy(false); } } // ------------------------------------------------------------------ tools & colors setTool(id) { if (!this.tools.has(id)) id = 'brush'; if (this.tool?.id === id) return; if (this.tool) { this.tool.commit(); this.tool.deactivate(); this.tool.active = false; this.previousToolId = this.tool.id; } this.tool = this.tools.get(id); this.tool.active = true; if (id !== 'transform') this.prefs.set('tool', id); this.tool.activate(); this.updateCursor(); this.emit('tool'); this.renderer.request(); } setColor(which, color, meta = {}) { this.colors[which] = Color.from(color); this.prefs.set(which, this.colors[which].toHex(true)); this.emit('colors', meta); } /** Remember a color that was painted with (shown under "Recent" in the color panel). */ noteColorUsed(color) { const hex = Color.from(color).toHex(true); const list = this.prefs.get('recentColors', []); if (list[0] === hex) return; this.prefs.set('recentColors', [hex, ...list.filter((h) => h !== hex)].slice(0, 8)); this.emit('recentColors'); } swapColors() { [this.colors.fg, this.colors.bg] = [this.colors.bg, this.colors.fg]; this.prefs.set('fg', this.colors.fg.toHex(true)); this.prefs.set('bg', this.colors.bg.toHex(true)); this.emit('colors', {}); } run(id, ...args) { const a = this.actions.get(id); if (!a) { console.warn('Unknown action', id); return; } if (a.enabled && !a.enabled(this)) return; if (!id.startsWith('view.') && !id.startsWith('color.') && id !== 'edit.transform') this.tool?.commit(); try { const r = a.run(...args); if (r?.catch) r.catch((err) => { console.error(err); alertDialog(err.message || String(err), 'Error'); }); } catch (err) { console.error(err); alertDialog(err.message || String(err), 'Error'); } } undo() { if (!this.doc) return; if (this.tool?.cancelOnUndo?.()) return; this.tool?.commit(); this.doc.history.undo(); } redo() { if (!this.doc) return; this.tool?.commit(); this.doc.history.redo(); } // ------------------------------------------------------------------ helpers for tools eventToDoc(e) { return this.renderer.screenToDoc(this.renderer.clientToScreen(e)); } pickColorAt(p, toBackground = false, { merged = true, size = 1 } = {}) { const doc = this.doc; if (!doc) return; const x = Math.floor(p.x), y = Math.floor(p.y); if (x < 0 || y < 0 || x >= doc.width || y >= doc.height) return; const src = merged ? this.renderer.composite : doc.activeLayer.canvas; const r = Math.floor(size / 2); const x0 = Math.max(0, x - r), y0 = Math.max(0, y - r); const w = Math.min(doc.width, x + r + 1) - x0, h = Math.min(doc.height, y + r + 1) - y0; const d = src.getContext('2d', { willReadFrequently: true }).getImageData(x0, y0, w, h).data; let R = 0, G = 0, B = 0, A = 0; for (let i = 0; i < d.length; i += 4) { R += d[i] * d[i + 3]; G += d[i + 1] * d[i + 3]; B += d[i + 2] * d[i + 3]; A += d[i + 3]; } if (!A) return; this.setColor(toBackground ? 'bg' : 'fg', new Color(Math.round(R / A), Math.round(G / A), Math.round(B / A), 1)); } /** Topmost visible layer with a non-transparent pixel at p. */ layerAt(p) { const doc = this.doc; const x = Math.floor(p.x), y = Math.floor(p.y); if (!doc || x < 0 || y < 0 || x >= doc.width || y >= doc.height) return null; for (let i = doc.layers.length - 1; i >= 0; i--) { const l = doc.layers[i]; if (!l.visible) continue; if (l.canvas.getContext('2d', { willReadFrequently: true }).getImageData(x, y, 1, 1).data[3] > 10) return l; } return null; } toast(message, ms = 2200) { const t = el('div', { class: 'toast' }, message); this.toasts.appendChild(t); setTimeout(() => t.classList.add('out'), ms); setTimeout(() => t.remove(), ms + 400); } busy(on) { this._busy = (this._busy || 0) + (on ? 1 : -1); this.busyEl.classList.toggle('on', this._busy > 0); } setStatusHint(text) { this.ui.status?.setHint(text); } updateCursor() { const c = this.spaceDown || this.panning ? (this.panning ? 'grabbing' : 'grab') : this.hoverCursor || this.tool?.cursor || 'default'; this.renderer.canvas.style.cursor = c; } // ------------------------------------------------------------------ input bindInput() { const canvas = this.renderer.canvas; canvas.addEventListener('pointerdown', (e) => this.onPointerDown(e)); canvas.addEventListener('pointermove', (e) => this.onPointerMove(e)); canvas.addEventListener('pointerup', (e) => this.onPointerUp(e)); canvas.addEventListener('pointercancel', (e) => this.onPointerUp(e)); canvas.addEventListener('pointerleave', () => { this.renderer.pointer = null; this.renderer.request(); this.emit('pointerInfo', null); }); canvas.addEventListener('dblclick', (e) => this.doc && this.tool?.onDoubleClick(e, this.eventToDoc(e))); canvas.addEventListener('contextmenu', (e) => { e.preventDefault(); if (this.doc && !this.pointerDown) this.ui.menu.showContext(e.clientX, e.clientY, canvasContextMenu()); }); this.workspace.addEventListener('wheel', (e) => this.onWheel(e), { passive: false }); window.addEventListener('keydown', (e) => this.onKeyDown(e)); window.addEventListener('keyup', (e) => { if (e.code === 'Space') { this.spaceDown = false; this.updateCursor(); } }); window.addEventListener('blur', () => { this.spaceDown = false; }); // drag & drop files const root = document.body; root.addEventListener('dragover', (e) => { if ([...(e.dataTransfer?.types || [])].includes('Files')) { e.preventDefault(); root.classList.add('dropping'); } }); root.addEventListener('dragleave', (e) => { if (!e.relatedTarget) root.classList.remove('dropping'); }); root.addEventListener('drop', async (e) => { root.classList.remove('dropping'); const files = Array.from(e.dataTransfer?.files || []); if (!files.length) return; e.preventDefault(); for (const f of files) { if (await isProjectFile(f)) await this.openFile(f); else if (isImageFile(f)) { if (this.doc && !e.shiftKey) await this.placeImageFile(f); else await this.openFile(f); } } }); } onPointerDown(e) { if (!this.doc) return; this.workspace.focus({ preventScroll: true }); if (document.activeElement && document.activeElement !== this.workspace && document.activeElement.blur) { if (!document.activeElement.classList.contains('text-editor')) document.activeElement.blur(); } this.renderer.canvas.setPointerCapture(e.pointerId); if (e.pointerType === 'touch' && this.touchGesture(e, 'down')) return; const p = this.eventToDoc(e); if (e.button === 1 || (e.button === 0 && this.spaceDown)) { this.panning = { x: e.clientX, y: e.clientY }; this.updateCursor(); return; } if (e.button !== 0) return; if (this.guides.pointerDown(e, this.renderer.clientToScreen(e), p)) { this.guideDrag = true; return; } this.pointerDown = { id: e.pointerId }; try { this.tool?.onPointerDown(e, p); } catch (err) { console.error(err); this.toast(`Error: ${err.message}`); } this.renderer.request(); } onPointerMove(e) { if (!this.doc) return; if (e.pointerType === 'touch' && this.touchGesture(e, 'move')) return; const s = this.renderer.clientToScreen(e); this.renderer.pointer = s; const p = this.renderer.screenToDoc(s); if (this.panning) { this.renderer.pan(e.clientX - this.panning.x, e.clientY - this.panning.y); this.panning = { x: e.clientX, y: e.clientY }; return; } if (this.guideDrag) { this.guides.pointerMove(e, s, p); this.reportPointer(p); return; } if (!this.pointerDown) { const hc = this.guides.hoverCursor(s); if (hc !== this.hoverCursor) { this.hoverCursor = hc; this.updateCursor(); } } try { if (this.pointerDown) this.tool?.onPointerMove(e, p); else this.tool?.onHover?.(e, p); } catch (err) { console.error(err); } if (this.tool?.cursorRadius || this.guides.rulers) this.renderer.request(); this.reportPointer(p); } reportPointer(p) { const now = performance.now(); if (now - (this._lastInfo || 0) < 60) return; this._lastInfo = now; const doc = this.doc; const x = Math.floor(p.x), y = Math.floor(p.y); let color = null; if (x >= 0 && y >= 0 && x < doc.width && y < doc.height && !this.pointerDown) { color = Array.from(this.renderer.composite.getContext('2d', { willReadFrequently: true }).getImageData(x, y, 1, 1).data); } this.emit('pointerInfo', { x, y, color }); } /** * Two-finger touch: pinch to zoom and drag to pan. A second finger cancels whatever * the first one started, and the remaining finger does nothing until all are lifted. * Returns true if the event belongs to the gesture. */ touchGesture(e, phase) { const touches = this.touches || (this.touches = new Map()); const pt = { clientX: e.clientX, clientY: e.clientY }; const measure = () => { const [a, b] = [...touches.values()]; return { dist: Math.hypot(a.clientX - b.clientX, a.clientY - b.clientY) || 1, center: this.renderer.clientToScreen({ clientX: (a.clientX + b.clientX) / 2, clientY: (a.clientY + b.clientY) / 2 }), }; }; if (phase === 'down') { touches.set(e.pointerId, pt); if (touches.size !== 2) return !!(this.pinch || this.pinchEnded); if (this.pointerDown) { this.pointerDown = null; this.tool?.cancel(); } if (this.guideDrag) { this.guideDrag = false; this.guides.cancel(); } this.panning = null; const m = measure(); this.pinch = { dist: m.dist, zoom: this.doc.view.zoom, anchor: this.renderer.screenToDoc(m.center) }; this.renderer.request(); return true; } if (!touches.has(e.pointerId)) return false; if (phase === 'move') { touches.set(e.pointerId, pt); if (!this.pinch) return !!this.pinchEnded; const m = measure(); const v = this.doc.view; v.zoom = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, (this.pinch.zoom * m.dist) / this.pinch.dist)); v.panX = m.center.x - this.pinch.anchor.x * v.zoom; v.panY = m.center.y - this.pinch.anchor.y * v.zoom; this.renderer.request(); this.emit('view'); return true; } touches.delete(e.pointerId); if (this.pinch) { if (touches.size < 2) { this.pinch = null; this.pinchEnded = touches.size > 0; } return true; } if (this.pinchEnded) { if (!touches.size) this.pinchEnded = false; return true; } return false; } onPointerUp(e) { if (e.pointerType === 'touch' && this.touchGesture(e, 'up')) return; if (this.panning) { this.panning = null; this.updateCursor(); return; } if (this.guideDrag) { this.guideDrag = false; this.guides.pointerUp(e); return; } if (!this.pointerDown) return; this.pointerDown = null; this.guides.snapped = null; try { this.tool?.onPointerUp(e, this.eventToDoc(e)); } catch (err) { console.error(err); this.toast(`Error: ${err.message}`); } this.renderer.request(); } onWheel(e) { if (!this.doc) return; e.preventDefault(); const s = this.renderer.clientToScreen(e); if (e.ctrlKey || e.metaKey || this.prefs.get('wheelZoom', false)) { const factor = Math.exp(-e.deltaY * (e.deltaMode === 1 ? 0.05 : 0.0025)); this.renderer.setZoom(this.doc.view.zoom * factor, s); } else { const k = e.deltaMode === 1 ? 20 : 1; if (e.shiftKey) this.renderer.pan(-(e.deltaY || e.deltaX) * k, 0); else this.renderer.pan(-e.deltaX * k, -e.deltaY * k); } } onKeyDown(e) { if (isDialogOpen()) return; const t = e.target; if (t instanceof HTMLInputElement || t instanceof HTMLTextAreaElement || t instanceof HTMLSelectElement || t?.isContentEditable) return; if (e.code === 'Space' && !e.repeat) { this.spaceDown = true; this.updateCursor(); e.preventDefault(); return; } if (this.doc && this.tool?.onKeyDown(e)) { e.preventDefault(); return; } const sc = shortcutOf(e); if (sc === 'Ctrl+V') return; // handled by the native paste event if (sc === 'Ctrl+Y') { e.preventDefault(); this.redo(); return; } if (sc === 'Backspace' || sc === 'Delete') { e.preventDefault(); this.run('edit.clear'); return; } if (sc === 'Escape') { if (this.guideDrag) { this.guideDrag = false; this.guides.cancel(); return; } if (this.doc) this.tool?.cancel(); this.ui.menu.close(); this.renderer.request(); return; } const actionId = this.shortcuts.get(sc); if (actionId) { e.preventDefault(); this.run(actionId); return; } // tool shortcuts: single letters, repeated presses cycle through tools sharing a key if (!e.ctrlKey && !e.metaKey && !e.altKey && sc.length <= 7) { const letter = sc.replace('Shift+', ''); const matches = TOOL_CLASSES.filter((T) => T.shortcut === letter).map((T) => T.id); if (matches.length) { e.preventDefault(); const cur = matches.indexOf(this.tool?.id); this.setTool(cur >= 0 ? matches[(cur + 1) % matches.length] : matches[0]); return; } // number keys: opacity of paint tool, or of the active layer if (/^\d$/.test(letter) && this.doc) { e.preventDefault(); const v = letter === '0' ? 100 : Number(letter) * 10; if ('opacity' in (this.tool?.options || {}) && this.tool.id !== 'move') { this.tool.setOption('opacity', v); this.ui.toolOptions.refresh(); this.toast(`${this.tool.label} opacity ${v}%`, 900); } else if (this.doc.activeLayer) { const l = this.doc.activeLayer; this.doc.change('Layer opacity', () => { l.opacity = v / 100; }, { coalesceKey: `opacity-${l.id}` }); this.toast(`Layer opacity ${v}%`, 900); } } } } }