// Free transform: scale / rotate / move the selection contents or whole layer. import { Tool } from './tool.js'; import { createCanvas, cloneCanvas, opaqueBounds } from '../core/util.js'; import { Selection } from '../core/selection.js'; const HANDLES = [[-1, -1], [0, -1], [1, -1], [1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0]]; export class TransformTool extends Tool { static id = 'transform'; static label = 'Free Transform'; static icon = 'transform'; static shortcut = 'Ctrl+T'; static schema = [ { key: 'smooth', label: 'Smooth', type: 'checkbox', default: true }, { type: 'readout', key: 'readout' }, { type: 'action', label: 'Flip H', action: 'flipH' }, { type: 'action', label: 'Flip V', action: 'flipV' }, { type: 'action', label: 'Apply', action: 'apply', primary: true }, { type: 'action', label: 'Cancel', action: 'cancel' }, ]; get hint() { return 'Drag handles to scale (Shift: keep ratio, Alt: from center) · drag outside to rotate (Shift: 15°) · Enter applies'; } get hidesSelection() { return !!this.state; } get cursor() { return this.hoverCursor || 'default'; } get readout() { const s = this.state; if (!s) return ''; const deg = ((s.angle * 180) / Math.PI).toFixed(1); return `W ${((s.w / s.sw) * 100).toFixed(1)}% H ${((s.h / s.sh) * 100).toFixed(1)}% ∠ ${deg}°`; } activate() { this.begin(); } deactivate() { this.apply(); } begin() { const doc = this.doc; if (!doc) return; const target = doc.editTarget; const layer = target?.layer; if (!layer) return; if (layer.locked) { this.app.toast('Layer is locked'); return this.bail(); } if (layer.isText && target.key === 'canvas') { this.app.toast('Rasterize the text layer to transform it'); return this.bail(); } const src = layer[target.key]; const sel = doc.selection; const b = sel ? sel.bounds : opaqueBounds(src); if (!b) { this.app.toast('Nothing to transform'); return this.bail(); } const before = doc.captureState(); const piece = createCanvas(b.w, b.h); const pctx = piece.getContext('2d'); pctx.drawImage(src, -b.x, -b.y); if (sel) { pctx.globalCompositeOperation = 'destination-in'; pctx.drawImage(sel.mask, -b.x, -b.y); } const base = cloneCanvas(src); const bctx = base.getContext('2d'); if (sel) { bctx.globalCompositeOperation = 'destination-out'; bctx.drawImage(sel.mask, 0, 0); bctx.globalCompositeOperation = 'source-over'; } else { bctx.clearRect(b.x, b.y, b.w, b.h); } let selPiece = null; if (sel) selPiece = cloneCanvas(sel.mask); layer[target.key] = base; this.state = { before, layer, key: target.key, piece, base, selPiece, selBounds: b, sw: b.w, sh: b.h, cx: b.x + b.w / 2, cy: b.y + b.h / 2, w: b.w, h: b.h, angle: 0, }; if (target.key === 'canvas') doc.floating = { canvas: piece, layer, transform: this.matrix() }; else this.renderMask(); doc.selection = null; doc.markDirty(); this.app.ui?.toolOptions.refresh(); } /** Can't transform: go back to the previous tool. */ bail() { this.state = null; setTimeout(() => this.app.setTool(this.app.previousToolId || 'move'), 0); } matrix() { const s = this.state; const m = new DOMMatrix() .translate(s.cx, s.cy) .rotate((s.angle * 180) / Math.PI) .scale(s.w / s.sw, s.h / s.sh) .translate(-s.sw / 2, -s.sh / 2); return m; } update() { const s = this.state; if (s.key === 'canvas') this.doc.floating.transform = this.matrix(); else this.renderMask(); this.doc.markDirty(); this.app.ui?.toolOptions.refreshReadout(); } renderMask() { const s = this.state; const out = cloneCanvas(s.base); const ctx = out.getContext('2d'); const m = this.matrix(); ctx.setTransform(m.a, m.b, m.c, m.d, m.e, m.f); ctx.drawImage(s.piece, 0, 0); fillMaskHoles(out); s.layer.mask = out; s.layer.touchMask(); } corners() { const s = this.state; const m = this.matrix(); return HANDLES.map(([hx, hy]) => m.transformPoint(new DOMPoint(((hx + 1) / 2) * s.sw, ((hy + 1) / 2) * s.sh))); } toLocal(p, s = this.state) { const dx = p.x - s.cx, dy = p.y - s.cy; const c = Math.cos(-s.angle), sn = Math.sin(-s.angle); return { x: dx * c - dy * sn, y: dx * sn + dy * c }; } hitTest(p) { if (!this.state) return null; const view = this.app.renderer; const sp = view.docToScreen(p); const pts = this.corners(); for (let i = 0; i < pts.length; i++) { const hp = view.docToScreen(pts[i]); if (Math.abs(hp.x - sp.x) <= 7 && Math.abs(hp.y - sp.y) <= 7) return { handle: i }; } const l = this.toLocal(p); const s = this.state; if (Math.abs(l.x) <= Math.abs(s.w) / 2 && Math.abs(l.y) <= Math.abs(s.h) / 2) return { inside: true }; return { rotate: true }; } onHover(e, p) { const hit = this.hitTest(p); let c = 'default'; if (hit?.handle != null) c = HANDLES[hit.handle][0] === 0 ? 'ns-resize' : HANDLES[hit.handle][1] === 0 ? 'ew-resize' : 'nwse-resize'; else if (hit?.inside) c = 'move'; else if (hit?.rotate) c = 'alias'; if (c !== this.hoverCursor) { this.hoverCursor = c; this.app.updateCursor(); } } onPointerDown(e, p) { if (!this.state) { this.begin(); if (!this.state) return; } const hit = this.hitTest(p); this.drag = { hit, start: p, orig: { ...this.state } }; } onPointerMove(e, p) { const d = this.drag; if (!d) return; const s = this.state; const o = d.orig; if (d.hit.inside) { s.cx = o.cx + (p.x - d.start.x); s.cy = o.cy + (p.y - d.start.y); } else if (d.hit.rotate) { const a0 = Math.atan2(d.start.y - o.cy, d.start.x - o.cx); const a1 = Math.atan2(p.y - o.cy, p.x - o.cx); let ang = o.angle + (a1 - a0); if (e.shiftKey) ang = Math.round(ang / (Math.PI / 12)) * (Math.PI / 12); s.angle = ang; } else { const [hx, hy] = HANDLES[d.hit.handle]; const l = this.toLocal(p, o); let w = o.w, h = o.h, lcx = 0, lcy = 0; if (e.altKey) { if (hx) w = 2 * hx * l.x * Math.sign(o.w); if (hy) h = 2 * hy * l.y * Math.sign(o.h); } else { // anchor = opposite edge in local coordinates if (hx) { const ax = -hx * Math.abs(o.w) / 2; w = (l.x - ax) * hx * Math.sign(o.w); lcx = (l.x + ax) / 2; } if (hy) { const ay = -hy * Math.abs(o.h) / 2; h = (l.y - ay) * hy * Math.sign(o.h); lcy = (l.y + ay) / 2; } } if (e.shiftKey && hx && hy) { const k = Math.max(Math.abs(w / o.w), Math.abs(h / o.h)); const nw = Math.sign(w || 1) * Math.abs(o.w) * k, nh = Math.sign(h || 1) * Math.abs(o.h) * k; if (!e.altKey) { lcx += (hx * (Math.abs(nw) - Math.abs(w))) / 2; lcy += (hy * (Math.abs(nh) - Math.abs(h))) / 2; } w = nw; h = nh; } if (Math.abs(w) < 1) w = Math.sign(w || 1); if (Math.abs(h) < 1) h = Math.sign(h || 1); const c = Math.cos(o.angle), sn = Math.sin(o.angle); s.cx = o.cx + lcx * c - lcy * sn; s.cy = o.cy + lcx * sn + lcy * c; s.w = w; s.h = h; } this.update(); } onPointerUp() { this.drag = null; } onKeyDown(e) { if (!this.state) return false; if (e.key === 'Enter') { this.apply(); this.app.setTool(this.app.previousToolId || 'move'); return true; } if (e.key === 'Escape') { this.cancel(); this.app.setTool(this.app.previousToolId || 'move'); return true; } if (e.key.startsWith('Arrow')) { const step = e.shiftKey ? 10 : 1; if (e.key === 'ArrowLeft') this.state.cx -= step; if (e.key === 'ArrowRight') this.state.cx += step; if (e.key === 'ArrowUp') this.state.cy -= step; if (e.key === 'ArrowDown') this.state.cy += step; this.update(); return true; } return false; } runAction(name) { if (!this.state) return; if (name === 'flipH') { this.state.w *= -1; this.update(); } else if (name === 'flipV') { this.state.h *= -1; this.update(); } else if (name === 'apply') { this.apply(); this.app.setTool(this.app.previousToolId || 'move'); } else if (name === 'cancel') { this.cancel(); this.app.setTool(this.app.previousToolId || 'move'); } } commit() { this.apply(); } apply() { const s = this.state; if (!s) return; this.state = null; this.drag = null; const doc = this.doc; const m = this.matrixFor(s); const out = s.base; const ctx = out.getContext('2d'); ctx.save(); ctx.setTransform(m.a, m.b, m.c, m.d, m.e, m.f); ctx.imageSmoothingEnabled = this.options.smooth; ctx.imageSmoothingQuality = 'high'; ctx.drawImage(s.piece, 0, 0); ctx.restore(); if (s.key === 'mask') fillMaskHoles(out); s.layer[s.key] = out; if (s.key === 'canvas') s.layer.touch(); else s.layer.touchMask(); doc.floating = null; if (s.selPiece) { const piece = createCanvas(s.sw, s.sh); piece.getContext('2d').drawImage(s.selPiece, -s.selBounds.x, -s.selBounds.y); const selC = createCanvas(doc.width, doc.height); const sctx = selC.getContext('2d'); sctx.setTransform(m.a, m.b, m.c, m.d, m.e, m.f); sctx.drawImage(piece, 0, 0); doc.selection = Selection.orNull(selC); } doc.commitChange('Free transform', s.before); } matrixFor(s) { const prev = this.state; this.state = s; const m = this.matrix(); this.state = prev; return m; } cancel() { const s = this.state; if (!s) return; this.state = null; this.drag = null; this.doc.floating = null; this.doc.restoreState(s.before); } drawOverlay(ctx, view, doc) { if (!this.state) return; const pts = this.corners().map((p) => view.docToScreen(p, doc)); ctx.save(); ctx.beginPath(); [0, 2, 4, 6].forEach((i, k) => (k ? ctx.lineTo(pts[i].x, pts[i].y) : ctx.moveTo(pts[i].x, pts[i].y))); ctx.closePath(); ctx.strokeStyle = '#1a73e8'; ctx.lineWidth = 1.5; ctx.stroke(); ctx.restore(); for (const p of this.corners()) view.handle(p, 9, doc); const c = view.docToScreen({ x: this.state.cx, y: this.state.cy }, doc); ctx.save(); ctx.strokeStyle = '#1a73e8'; ctx.beginPath(); ctx.arc(c.x, c.y, 4, 0, Math.PI * 2); ctx.stroke(); ctx.restore(); } } /** Masks stay opaque: areas the transform uncovers become white (visible). */ function fillMaskHoles(canvas) { const ctx = canvas.getContext('2d'); ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalCompositeOperation = 'destination-over'; ctx.fillStyle = '#fff'; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.restore(); }