aboutsummaryrefslogtreecommitdiff
path: root/build/js/core/ops.js
blob: 6e05b86f4310cb2dd26fca6893f819c067144660 (plain)
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
// 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;
}