// Document-level operations. Each runs inside doc.change() and replaces canvases // instead of mutating them, so a single StateEntry can undo it. import { createCanvas, cloneCanvas, opaqueBounds } from './util.js'; import { Layer, makeMaskCanvas, blendOp, layoutText } from './layer.js'; import { Selection } from './selection.js'; import { compositeDocument, layerSurface } from '../render/compositor.js'; /** * Map every layer canvas (and mask) through fn(canvas, isMask) -> new canvas. * textMode 'keep' re-renders text layers at the new document size (w, h). */ function mapLayers(doc, fn, { textMode = 'rasterize', textFn = null, w = doc.width, h = doc.height } = {}) { for (const layer of doc.layers) { if (layer.isText) { if (textMode === 'keep' && textFn) { textFn(layer); layer.canvas = createCanvas(w, h); layer.renderText(); } else { layer.canvas = fn(layer.canvas, false); layer.type = 'raster'; layer.text = null; } } else { layer.canvas = fn(layer.canvas, false); } if (layer.mask) layer.mask = fn(layer.mask, true); layer.touch(); layer.touchMask(); } } function drawInto(w, h, draw, fillWhite = false) { const c = createCanvas(w, h); const ctx = c.getContext('2d'); if (fillWhite) { ctx.fillStyle = '#fff'; ctx.fillRect(0, 0, w, h); } draw(ctx); return c; } export function resizeImage(doc, w, h, smooth = true) { w = Math.max(1, Math.round(w)); h = Math.max(1, Math.round(h)); const sx = w / doc.width, sy = h / doc.height; doc.change('Image size', () => { mapLayers(doc, (src) => resampleCanvas(src, w, h, smooth), { textMode: 'keep', w, h, textFn: (l) => { l.text.x *= sx; l.text.y *= sy; l.text.fontSize = Math.max(1, l.text.fontSize * Math.sqrt(sx * sy)); l.text.strokeWidth *= Math.sqrt(sx * sy); }, }); if (doc.selection) doc.selection = Selection.orNull(resampleCanvas(doc.selection.mask, w, h, smooth)); doc.guideLines = doc.guideLines.map((g) => ({ axis: g.axis, pos: Math.round(g.pos * (g.axis === 'x' ? sx : sy)) })); doc.width = w; doc.height = h; }); doc.view.needsFit = true; } /** High quality resample (steps down by halves for big reductions). */ export function resampleCanvas(src, w, h, smooth = true) { let cur = src; if (smooth) { while (cur.width / 2 >= w * 1.0001 && cur.height / 2 >= h * 1.0001) { const half = createCanvas(Math.max(w, Math.round(cur.width / 2)), Math.max(h, Math.round(cur.height / 2))); const hctx = half.getContext('2d'); hctx.imageSmoothingQuality = 'high'; hctx.drawImage(cur, 0, 0, half.width, half.height); cur = half; } } return drawInto(w, h, (ctx) => { ctx.imageSmoothingEnabled = smooth; ctx.imageSmoothingQuality = 'high'; ctx.drawImage(cur, 0, 0, w, h); }); } /** Change canvas size. anchor: {x, y} in 0..1 (0.5,0.5 = center). */ export function resizeCanvas(doc, w, h, anchor = { x: 0.5, y: 0.5 }, label = 'Canvas size') { w = Math.max(1, Math.round(w)); h = Math.max(1, Math.round(h)); const ox = Math.round((w - doc.width) * anchor.x); const oy = Math.round((h - doc.height) * anchor.y); offsetCanvas(doc, w, h, ox, oy, label); } export function cropTo(doc, r) { const x = Math.round(r.x), y = Math.round(r.y); const w = Math.max(1, Math.round(r.w)), h = Math.max(1, Math.round(r.h)); offsetCanvas(doc, w, h, -x, -y, 'Crop'); } function offsetCanvas(doc, w, h, ox, oy, label) { doc.change(label, () => { mapLayers(doc, (src, isMask) => drawInto(w, h, (ctx) => ctx.drawImage(src, ox, oy), isMask), { textMode: 'keep', w, h, textFn: (l) => { l.text.x += ox; l.text.y += oy; }, }); if (doc.selection) doc.selection = Selection.orNull(drawInto(w, h, (ctx) => ctx.drawImage(doc.selection.mask, ox, oy))); doc.guideLines = doc.guideLines.map((g) => ({ axis: g.axis, pos: g.pos + (g.axis === 'x' ? ox : oy) })); doc.width = w; doc.height = h; }); doc.view.needsFit = true; } /** Rotate the whole image by 90, -90 or 180 degrees. */ export function rotateImage(doc, deg) { const swap = Math.abs(deg) === 90; const w = swap ? doc.height : doc.width, h = swap ? doc.width : doc.height; const rot = (src) => drawInto(w, h, (ctx) => { ctx.translate(w / 2, h / 2); ctx.rotate((deg * Math.PI) / 180); ctx.drawImage(src, -src.width / 2, -src.height / 2); }); doc.change(`Rotate ${deg}°`, () => { mapLayers(doc, rot); if (doc.selection) doc.selection = Selection.orNull(rot(doc.selection.mask)); const W = doc.width, H = doc.height; doc.guideLines = doc.guideLines.map(({ axis, pos }) => { if (deg === 180) return { axis, pos: (axis === 'x' ? W : H) - pos }; // 90° clockwise maps (x, y) to (H - y, x); counter-clockwise to (y, W - x) if (deg === 90) return axis === 'x' ? { axis: 'y', pos } : { axis: 'x', pos: H - pos }; return axis === 'x' ? { axis: 'y', pos: W - pos } : { axis: 'x', pos }; }); doc.width = w; doc.height = h; }); doc.view.needsFit = true; } export function flipImage(doc, axis) { const flip = (src) => flipCanvas(src, axis); doc.change(axis === 'h' ? 'Flip horizontal' : 'Flip vertical', () => { mapLayers(doc, flip); if (doc.selection) doc.selection = Selection.orNull(flip(doc.selection.mask)); const along = axis === 'h' ? 'x' : 'y'; doc.guideLines = doc.guideLines.map((g) => (g.axis === along ? { axis: g.axis, pos: (along === 'x' ? doc.width : doc.height) - g.pos } : g)); }); } export function flipCanvas(src, axis) { return drawInto(src.width, src.height, (ctx) => { if (axis === 'h') { ctx.translate(src.width, 0); ctx.scale(-1, 1); } else { ctx.translate(0, src.height); ctx.scale(1, -1); } ctx.drawImage(src, 0, 0); }); } /** Flip or rotate just the active layer (or the selected part of it) in place. */ export function transformLayer(doc, kind) { const layer = doc.activeLayer; if (!layer || layer.locked) return false; const key = doc.editTarget.key; const src = layer[key]; const sel = doc.selection; const b = sel ? sel.bounds : opaqueBounds(src) || { x: 0, y: 0, w: doc.width, h: doc.height }; doc.change(`Layer ${kind}`, () => { if (layer.isText && key === 'canvas') rasterize(layer); 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 out = cloneCanvas(src); const octx = out.getContext('2d'); if (sel) { octx.globalCompositeOperation = 'destination-out'; octx.drawImage(sel.mask, 0, 0); } else { octx.clearRect(b.x, b.y, b.w, b.h); } octx.globalCompositeOperation = 'source-over'; const cx = b.x + b.w / 2, cy = b.y + b.h / 2; octx.translate(cx, cy); if (kind === 'flip-h') octx.scale(-1, 1); else if (kind === 'flip-v') octx.scale(1, -1); else if (kind === 'rotate-cw') octx.rotate(Math.PI / 2); else if (kind === 'rotate-ccw') octx.rotate(-Math.PI / 2); else if (kind === 'rotate-180') octx.rotate(Math.PI); octx.drawImage(piece, -b.w / 2, -b.h / 2); if (key === 'mask') { // Masks stay opaque: areas the rotation uncovers become white (visible). octx.setTransform(1, 0, 0, 1, 0, 0); octx.globalCompositeOperation = 'destination-over'; octx.fillStyle = '#fff'; octx.fillRect(0, 0, out.width, out.height); } layer[key] = out; if (key === 'mask') layer.touchMask(); else layer.touch(); }); return true; } // ---------------------------------------------------------------- layers export function addLayer(doc, layer = null, { above = doc.activeLayer, label = 'New layer' } = {}) { return doc.change(label, () => { const l = layer || new Layer(doc.width, doc.height, { name: doc.nextLayerName() }); const idx = above ? doc.layers.indexOf(above) + 1 : doc.layers.length; doc.layers.splice(idx, 0, l); doc.activeLayerId = l.id; doc.editMask = false; return l; }); } export function deleteLayer(doc, layer = doc.activeLayer) { if (!layer || doc.layers.length <= 1) return false; doc.change('Delete layer', () => { const idx = doc.layers.indexOf(layer); doc.layers.splice(idx, 1); doc.activeLayerId = doc.layers[Math.max(0, idx - 1)].id; doc.editMask = false; }); return true; } export function duplicateLayer(doc, layer = doc.activeLayer) { if (!layer) return null; const copy = layer.duplicate(); return addLayer(doc, copy, { above: layer, label: 'Duplicate layer' }); } export function moveLayer(doc, layer, toIndex) { const from = doc.layers.indexOf(layer); toIndex = Math.max(0, Math.min(doc.layers.length - 1, toIndex)); if (from < 0 || from === toIndex) return; doc.change('Reorder layers', () => { doc.layers.splice(from, 1); doc.layers.splice(toIndex, 0, layer); }); } export function setLayerProps(doc, layer, props, label = 'Layer properties', coalesceKey = null) { doc.change(label, () => { Object.assign(layer, props); }, { coalesceKey }); } /** Turn a text layer into plain pixels (in place; call inside doc.change). */ export function rasterize(layer) { if (!layer.isText) return; layer.canvas = cloneCanvas(layer.canvas); layer.type = 'raster'; layer.text = null; layer.touch(); } export function rasterizeLayer(doc, layer = doc.activeLayer) { if (!layer?.isText) return; doc.change('Rasterize layer', () => rasterize(layer)); } /** Pixels of a layer with mask applied (for merging). */ function bakedLayer(doc, layer) { const s = layerSurface(doc, layer, 'bake'); return cloneCanvas(s); } export function mergeDown(doc, layer = doc.activeLayer) { const idx = doc.layers.indexOf(layer); if (idx <= 0) return false; const below = doc.layers[idx - 1]; doc.change('Merge down', () => { const base = bakedLayer(doc, below); const top = bakedLayer(doc, layer); const ctx = base.getContext('2d'); if (layer.visible) { if (layer.clip) { const tmp = cloneCanvas(top); const t = tmp.getContext('2d'); t.globalCompositeOperation = 'destination-in'; t.drawImage(base, 0, 0); ctx.globalAlpha = layer.opacity; ctx.globalCompositeOperation = blendOp(layer.blendMode); ctx.drawImage(tmp, 0, 0); } else { ctx.globalAlpha = layer.opacity; ctx.globalCompositeOperation = blendOp(layer.blendMode); ctx.drawImage(top, 0, 0); } ctx.globalAlpha = 1; ctx.globalCompositeOperation = 'source-over'; } below.canvas = base; below.mask = null; below.effects = null; // baked into base if (below.isText) { below.type = 'raster'; below.text = null; } below.touch(); doc.layers.splice(idx, 1); doc.activeLayerId = below.id; doc.editMask = false; }); return true; } export function mergeVisible(doc) { const visible = doc.layers.filter((l) => l.visible); if (visible.length < 2) return false; doc.change('Merge visible', () => { const merged = new Layer(doc.width, doc.height, { name: 'Merged' }); // Composite the full stack: it skips hidden layers itself, and filtering them out // first would re-attach layers clipped to a hidden base to another layer. compositeDocument(doc, merged.canvas); const idx = doc.layers.indexOf(visible[visible.length - 1]); doc.layers.splice(idx + 1, 0, merged); doc.layers = doc.layers.filter((l) => !l.visible || l === merged); doc.activeLayerId = merged.id; doc.editMask = false; }); return true; } export function flatten(doc, background = '#ffffff') { doc.change('Flatten image', () => { const flat = new Layer(doc.width, doc.height, { name: 'Background' }); compositeDocument(doc, flat.canvas, { background }); doc.layers = [flat]; doc.activeLayerId = flat.id; doc.editMask = false; }); } /** Shift a layer's pixels (and mask) by whole pixels. Call inside doc.change. */ export function offsetLayer(layer, dx, dy) { if (!dx && !dy) return; if (layer.isText) { layer.text = { ...layer.text, x: layer.text.x + dx, y: layer.text.y + dy }; layer.canvas = createCanvas(layer.canvas.width, layer.canvas.height); layer.renderText(); } else { layer.canvas = drawInto(layer.canvas.width, layer.canvas.height, (ctx) => ctx.drawImage(layer.canvas, dx, dy)); } if (layer.mask) { // Areas uncovered by the move stay visible (white), like the Move tool. const src = layer.mask; layer.mask = drawInto(src.width, src.height, (ctx) => { ctx.clearRect(dx, dy, src.width, src.height); ctx.drawImage(src, dx, dy); }, true); layer.touchMask(); } layer.touch(); } /** Content bounds of a layer (text box for text layers), or null if empty. */ export function layerBounds(layer) { if (layer.isText) { const b = layoutText(layer.text); return { x: Math.round(b.x), y: Math.round(b.y), w: Math.round(b.w), h: Math.round(b.h) }; } return opaqueBounds(layer.canvas); } /** * Align a layer's content to `target` (a rect: the selection or the canvas). * edge: 'left' | 'hcenter' | 'right' | 'top' | 'vcenter' | 'bottom'. * Returns false if the layer is empty or locked. */ export function alignLayer(doc, layer, edge, target) { const b = layer && !layer.locked ? layerBounds(layer) : null; if (!b) return false; let dx = 0, dy = 0; if (edge === 'left') dx = target.x - b.x; else if (edge === 'right') dx = target.x + target.w - (b.x + b.w); else if (edge === 'hcenter') dx = Math.round(target.x + target.w / 2 - (b.x + b.w / 2)); else if (edge === 'top') dy = target.y - b.y; else if (edge === 'bottom') dy = target.y + target.h - (b.y + b.h); else if (edge === 'vcenter') dy = Math.round(target.y + target.h / 2 - (b.y + b.h / 2)); if (dx || dy) doc.change('Align layer', () => offsetLayer(layer, dx, dy)); return true; } // ---------------------------------------------------------------- masks export function addMask(doc, layer = doc.activeLayer, fromSelection = true) { if (!layer || layer.mask) return; doc.change('Add layer mask', () => { const sel = fromSelection ? doc.selection : null; const m = makeMaskCanvas(doc.width, doc.height, sel ? '#000000' : '#ffffff'); if (sel) { // white where selected const white = createCanvas(doc.width, doc.height); const wctx = white.getContext('2d'); wctx.fillStyle = '#fff'; wctx.fillRect(0, 0, doc.width, doc.height); wctx.globalCompositeOperation = 'destination-in'; wctx.drawImage(sel.mask, 0, 0); m.getContext('2d').drawImage(white, 0, 0); } layer.mask = m; layer.maskEnabled = true; layer.touchMask(); doc.editMask = true; }); } export function deleteMask(doc, layer = doc.activeLayer, apply = false) { if (!layer?.mask) return; doc.change(apply ? 'Apply layer mask' : 'Delete layer mask', () => { if (apply) { if (layer.isText) rasterize(layer); const c = cloneCanvas(layer.canvas); const ctx = c.getContext('2d'); ctx.globalCompositeOperation = 'destination-in'; ctx.drawImage(layer.maskAlpha(), 0, 0); ctx.globalCompositeOperation = 'source-over'; layer.canvas = c; } layer.mask = null; layer.touch(); layer.touchMask(); doc.editMask = false; }); } /** Trim transparent borders (or borders matching nothing visible). */ export function trimDocument(doc) { const flat = createCanvas(doc.width, doc.height); compositeDocument(doc, flat); const b = opaqueBounds(flat); if (!b || (b.w === doc.width && b.h === doc.height)) return false; cropTo(doc, b); return true; }