aboutsummaryrefslogtreecommitdiff
path: root/build/js/io/clipboard.js
blob: 36cc997e5e23ea66bb501d2aefc59554157fa778 (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
// Copy / cut / paste. Keeps an internal clipboard (with the original position for
// paste-in-place) and mirrors copies to the system clipboard as PNG when allowed.
import { createCanvas, cropCanvas, canvasToBlob, blobToImage } from '../core/util.js';
import { Layer, DEFAULT_TEXT } from '../core/layer.js';
import { flattenToCanvas } from '../render/compositor.js';
import { addLayer } from '../core/ops.js';

export class Clipboard {
  constructor(app) {
    this.app = app;
    this.data = null; // { canvas, x, y }
    document.addEventListener('paste', (e) => this.onPaste(e));
  }

  copy(merged) {
    const doc = this.app.doc;
    if (!doc) return false;
    const target = doc.editTarget;
    const src = merged ? flattenToCanvas(doc) : target?.layer[target.key];
    if (!src) return false;
    const sel = doc.selection;
    const b = sel ? sel.bounds : { x: 0, y: 0, w: doc.width, h: doc.height };
    const piece = cropCanvas(src, b.x, b.y, b.w, b.h);
    if (sel) {
      const ctx = piece.getContext('2d');
      ctx.globalCompositeOperation = 'destination-in';
      ctx.drawImage(sel.mask, -b.x, -b.y);
    }
    this.data = { canvas: piece, x: b.x, y: b.y, at: Date.now() };
    this.app.toast(`Copied ${b.w} × ${b.h}${merged ? ' (merged)' : ''}`);
    this.writeSystem(piece);
    return true;
  }

  async writeSystem(canvas) {
    try {
      if (!navigator.clipboard?.write || typeof ClipboardItem === 'undefined') return;
      const blob = await canvasToBlob(canvas, 'image/png');
      await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);
    } catch {
      /* permission denied or unsupported: the internal clipboard still works */
    }
  }

  cut() {
    const doc = this.app.doc;
    const layer = doc?.activeLayer;
    if (!layer) return;
    if (layer.locked) { this.app.toast('Layer is locked'); return; }
    if (layer.isText && doc.editTarget.key === 'canvas') { this.app.toast('Rasterize the text layer first'); return; }
    if (this.copy(false)) this.app.run('edit.clear');
  }

  async onPaste(e) {
    const t = e.target;
    if (t instanceof HTMLInputElement || t instanceof HTMLTextAreaElement || t?.isContentEditable) return;
    e.preventDefault();
    const items = Array.from(e.clipboardData?.items || []);
    const imgItem = items.find((it) => it.type.startsWith('image/'));
    if (imgItem) {
      const file = imgItem.getAsFile();
      if (file) {
        const canvas = await this.decode(file);
        if (canvas) { this.pasteCanvas(this.preferInternal(canvas)); return; }
      }
    }
    const textItem = items.find((it) => it.type === 'text/plain');
    if (!this.data && textItem && this.app.doc) {
      textItem.getAsString((s) => { if (s.trim()) this.pasteText(s); });
      return;
    }
    if (this.data) this.pasteCanvas(this.data);
    else this.app.toast('Clipboard is empty');
  }

  /** If the system image matches our own last copy, keep its original position. */
  preferInternal(canvas) {
    const d = this.data;
    if (d && d.canvas.width === canvas.width && d.canvas.height === canvas.height) return d;
    return { canvas };
  }

  async decode(blob) {
    try {
      const img = await blobToImage(blob);
      const c = createCanvas(img.naturalWidth, img.naturalHeight);
      c.getContext('2d').drawImage(img, 0, 0);
      return c;
    } catch {
      return null;
    }
  }

  async pasteFromMenu(newImage = false) {
    try {
      if (navigator.clipboard?.read) {
        const items = await navigator.clipboard.read();
        for (const it of items) {
          const type = it.types.find((ty) => ty.startsWith('image/'));
          if (type) {
            const canvas = await this.decode(await it.getType(type));
            if (canvas) { this.pasteCanvas(this.preferInternal(canvas), newImage); return; }
          }
        }
      }
    } catch {
      /* fall back to the internal clipboard */
    }
    if (this.data) this.pasteCanvas(this.data, newImage);
    else this.app.toast('Clipboard is empty (or clipboard access was denied — try Ctrl+V)');
  }

  pasteCanvas(data, newImage = false) {
    const app = this.app;
    if (newImage || !app.doc) {
      const doc = app.newDocument({ width: data.canvas.width, height: data.canvas.height, name: 'Pasted', background: null });
      doc.layers[0].ctx.drawImage(data.canvas, 0, 0);
      doc.layers[0].touch();
      doc.markDirty(true);
      return;
    }
    const doc = app.doc;
    let { x, y } = data;
    if (x == null || x + data.canvas.width > doc.width || y + data.canvas.height > doc.height) {
      // centre in the visible area
      const r = app.renderer;
      const c = r.screenToDoc({ x: r.width / 2, y: r.height / 2 });
      x = Math.round(Math.max(0, Math.min(doc.width - data.canvas.width, c.x - data.canvas.width / 2)));
      y = Math.round(Math.max(0, Math.min(doc.height - data.canvas.height, c.y - data.canvas.height / 2)));
      if (data.canvas.width > doc.width) x = 0;
      if (data.canvas.height > doc.height) y = 0;
    }
    const layer = new Layer(doc.width, doc.height, { name: doc.nextLayerName('Pasted') });
    layer.ctx.drawImage(data.canvas, x, y);
    addLayer(doc, layer, { label: 'Paste' });
    if (data.canvas.width > doc.width || data.canvas.height > doc.height) app.toast('Pasted image is larger than the canvas (use Image ▸ Trim/Canvas Size)');
  }

  pasteText(text) {
    const doc = this.app.doc;
    const layer = new Layer(doc.width, doc.height, { name: text.split('\n')[0].slice(0, 24), type: 'text' });
    const r = this.app.renderer;
    const c = r.screenToDoc({ x: r.width / 2, y: r.height / 2 });
    layer.text = { ...DEFAULT_TEXT, color: this.app.colors.fg.toHex(), content: text, x: Math.round(c.x), y: Math.round(c.y) };
    layer.renderText();
    addLayer(doc, layer, { label: 'Paste text' });
  }
}