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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
|
// Command registry: every menu item / shortcut maps to one of these actions.
import { el, createCanvas, cloneCanvas, downloadBlob, stripExtension, formatBytes, debounce, pickFiles } from './core/util.js';
import { Color } from './core/color.js';
import { Layer, BLEND_MODES } from './core/layer.js';
import { Selection } from './core/selection.js';
import { PixelEdit, historyLimits } from './core/history.js';
import { commandPalette } from './ui/palette.js';
import * as ops from './core/ops.js';
import { formDialog, openDialog, alertDialog } from './ui/dialogs.js';
import { FILTERS, defaultParams } from './imaging/filters.js';
import { flattenToCanvas } from './render/compositor.js';
import { availableFormats, exportImage, FORMATS } from './io/export.js';
import { IMAGE_ACCEPT } from './io/import.js';
import { hasEffects } from './render/effects.js';
import { layerStyleDialog } from './ui/layerstyle.js';
import { setUserScripts, algorithmOptions } from './imaging/dither.js';
import { ditherScriptsDialog } from './ui/ditherscripts.js';
const docRequired = (app) => !!app.doc;
const hasSelection = (app) => !!app.doc?.selection;
const hasLayer = (app) => !!app.doc?.activeLayer;
export function registerActions(app) {
const A = new Map();
const def = (id, spec) => A.set(id, { id, ...spec });
// ------------------------------------------------------------ file
def('file.new', { label: 'New…', shortcut: 'Ctrl+Alt+N', run: () => newDocumentDialog(app) });
def('file.open', { label: 'Open…', shortcut: 'Ctrl+O', run: () => app.openFiles() });
def('file.place', {
label: 'Place Image as Layer…', shortcut: 'Ctrl+Shift+P', enabled: docRequired,
run: async () => {
const files = await pickFiles({ accept: IMAGE_ACCEPT, multiple: true });
for (const f of files) await app.placeImageFile(f);
},
});
def('file.save', { label: 'Save Project', shortcut: 'Ctrl+S', enabled: docRequired, run: () => app.saveProject(false) });
def('file.saveAs', { label: 'Save Project As…', shortcut: 'Ctrl+Shift+S', enabled: docRequired, run: () => app.saveProject(true) });
def('file.export', { label: 'Export Image…', shortcut: 'Ctrl+Shift+E', enabled: docRequired, run: () => exportDialog(app) });
def('file.quickPNG', {
label: 'Quick Export as PNG', shortcut: 'Ctrl+Alt+Shift+E', enabled: docRequired,
run: async () => {
const blob = await exportImage(app.doc, { format: 'png' });
downloadBlob(blob, `${stripExtension(app.doc.name)}.png`);
},
});
def('file.close', { label: 'Close', shortcut: 'Ctrl+Alt+W', enabled: docRequired, run: () => app.closeDocument(app.doc) });
def('file.recover', { label: 'Recover Autosaved Session…', run: () => app.autosave.offerRecovery(true) });
// ------------------------------------------------------------ edit
def('edit.undo', { label: 'Undo', shortcut: 'Ctrl+Z', enabled: (a) => !!a.doc?.history.canUndo, run: () => app.undo() });
def('edit.redo', { label: 'Redo', shortcut: 'Ctrl+Shift+Z', enabled: (a) => !!a.doc?.history.canRedo, run: () => app.redo() });
def('edit.cut', { label: 'Cut', shortcut: 'Ctrl+X', enabled: hasLayer, run: () => app.clipboard.cut() });
def('edit.copy', { label: 'Copy', shortcut: 'Ctrl+C', enabled: hasLayer, run: () => app.clipboard.copy(false) });
def('edit.copyMerged', { label: 'Copy Merged', shortcut: 'Ctrl+Shift+C', enabled: docRequired, run: () => app.clipboard.copy(true) });
def('edit.paste', { label: 'Paste as New Layer', shortcut: 'Ctrl+V', run: () => app.clipboard.pasteFromMenu() });
def('edit.pasteNewImage', { label: 'Paste as New Image', shortcut: 'Ctrl+Alt+V', run: () => app.clipboard.pasteFromMenu(true) });
def('edit.clear', { label: 'Clear', shortcut: 'Delete', enabled: hasLayer, run: () => clearSelection(app) });
def('edit.fill', { label: 'Fill…', shortcut: 'Shift+F5', enabled: hasLayer, run: () => fillDialog(app) });
def('edit.fillFG', { label: 'Fill with Foreground', shortcut: 'Alt+Backspace', enabled: hasLayer, run: () => fillWith(app, app.colors.fg) });
def('edit.fillBG', { label: 'Fill with Background', shortcut: 'Ctrl+Backspace', enabled: hasLayer, run: () => fillWith(app, app.colors.bg) });
def('edit.stroke', { label: 'Stroke Selection…', enabled: hasSelection, run: () => strokeDialog(app) });
def('edit.transform', { label: 'Free Transform', shortcut: 'Ctrl+T', enabled: hasLayer, run: () => app.setTool('transform') });
// ------------------------------------------------------------ image
def('image.size', { label: 'Image Size…', shortcut: 'Ctrl+Alt+I', enabled: docRequired, run: () => imageSizeDialog(app) });
def('image.canvasSize', { label: 'Canvas Size…', shortcut: 'Ctrl+Alt+C', enabled: docRequired, run: () => canvasSizeDialog(app) });
def('image.rotateCW', { label: 'Rotate 90° Clockwise', enabled: docRequired, run: () => ops.rotateImage(app.doc, 90) });
def('image.rotateCCW', { label: 'Rotate 90° Counter-clockwise', enabled: docRequired, run: () => ops.rotateImage(app.doc, -90) });
def('image.rotate180', { label: 'Rotate 180°', enabled: docRequired, run: () => ops.rotateImage(app.doc, 180) });
def('image.flipH', { label: 'Flip Canvas Horizontal', enabled: docRequired, run: () => ops.flipImage(app.doc, 'h') });
def('image.flipV', { label: 'Flip Canvas Vertical', enabled: docRequired, run: () => ops.flipImage(app.doc, 'v') });
def('image.crop', {
label: 'Crop to Selection', enabled: hasSelection,
run: () => { ops.cropTo(app.doc, app.doc.selection.bounds); app.doc.setSelection(null, 'Deselect'); },
});
def('image.trim', { label: 'Trim Transparent Pixels', enabled: docRequired, run: () => { if (!ops.trimDocument(app.doc)) app.toast('Nothing to trim'); } });
def('image.flatten', { label: 'Flatten Image', enabled: docRequired, run: () => ops.flatten(app.doc, app.colors.bg.toCSS()) });
def('image.duplicate', { label: 'Duplicate Image', enabled: docRequired, run: () => duplicateDocument(app) });
// ------------------------------------------------------------ layer
def('layer.new', { label: 'New Layer', shortcut: 'Ctrl+Shift+N', enabled: docRequired, run: () => ops.addLayer(app.doc) });
def('layer.newFill', { label: 'New Fill Layer (Foreground)', enabled: docRequired, run: () => newFillLayer(app) });
def('layer.duplicate', { label: 'Duplicate Layer', enabled: hasLayer, run: () => ops.duplicateLayer(app.doc) });
def('layer.viaCopy', {
label: 'New Layer via Copy', shortcut: 'Ctrl+J', enabled: hasLayer,
run: () => (app.doc.selection ? layerFromSelection(app, false) : ops.duplicateLayer(app.doc)),
});
def('layer.viaCut', { label: 'New Layer via Cut', shortcut: 'Ctrl+Shift+J', enabled: hasSelection, run: () => layerFromSelection(app, true) });
def('layer.delete', { label: 'Delete Layer', enabled: (a) => (a.doc?.layers.length || 0) > 1, run: () => ops.deleteLayer(app.doc) });
def('layer.properties', { label: 'Layer Properties…', enabled: hasLayer, run: () => layerPropertiesDialog(app) });
def('layer.rasterize', { label: 'Rasterize Layer', enabled: (a) => !!a.doc?.activeLayer?.isText, run: () => ops.rasterizeLayer(app.doc) });
def('layer.mergeDown', { label: 'Merge Down', shortcut: 'Ctrl+E', enabled: (a) => (a.doc?.activeIndex || 0) > 0, run: () => ops.mergeDown(app.doc) });
def('layer.mergeVisible', { label: 'Merge Visible', shortcut: 'Ctrl+Shift+M', enabled: docRequired, run: () => ops.mergeVisible(app.doc) || app.toast('Need at least two visible layers') });
def('layer.raise', { label: 'Bring Forward', shortcut: 'Ctrl+]', enabled: hasLayer, run: () => ops.moveLayer(app.doc, app.doc.activeLayer, app.doc.activeIndex + 1) });
def('layer.lower', { label: 'Send Backward', shortcut: 'Ctrl+[', enabled: hasLayer, run: () => ops.moveLayer(app.doc, app.doc.activeLayer, app.doc.activeIndex - 1) });
def('layer.top', { label: 'Bring to Front', shortcut: 'Ctrl+Shift+]', enabled: hasLayer, run: () => ops.moveLayer(app.doc, app.doc.activeLayer, app.doc.layers.length - 1) });
def('layer.bottom', { label: 'Send to Back', shortcut: 'Ctrl+Shift+[', enabled: hasLayer, run: () => ops.moveLayer(app.doc, app.doc.activeLayer, 0) });
def('layer.selectAbove', { label: 'Select Layer Above', shortcut: 'Alt+]', enabled: hasLayer, run: () => stepLayer(app, 1) });
def('layer.selectBelow', { label: 'Select Layer Below', shortcut: 'Alt+[', enabled: hasLayer, run: () => stepLayer(app, -1) });
def('layer.addMask', {
label: 'Add Layer Mask', enabled: (a) => !!a.doc?.activeLayer && !a.doc.activeLayer.mask,
run: () => (app.doc.activeLayer.mask ? app.toast('Layer already has a mask') : ops.addMask(app.doc)),
});
def('layer.deleteMask', { label: 'Delete Layer Mask', enabled: (a) => !!a.doc?.activeLayer?.mask, run: () => ops.deleteMask(app.doc) });
def('layer.applyMask', { label: 'Apply Layer Mask', enabled: (a) => !!a.doc?.activeLayer?.mask, run: () => ops.deleteMask(app.doc, undefined, true) });
def('layer.toggleMask', {
label: 'Disable Layer Mask', enabled: (a) => !!a.doc?.activeLayer?.mask, checked: (a) => a.doc?.activeLayer?.mask && !a.doc.activeLayer.maskEnabled,
run: () => { const l = app.doc.activeLayer; ops.setLayerProps(app.doc, l, { maskEnabled: !l.maskEnabled }, 'Toggle mask'); },
});
def('layer.editMask', {
label: 'Edit Mask (instead of pixels)', shortcut: 'Ctrl+\\', enabled: (a) => !!a.doc?.activeLayer?.mask, checked: (a) => !!a.doc?.editMask,
run: () => { app.doc.editMask = !app.doc.editMask; app.doc.markDirty(true); app.toast(app.doc.editMask ? 'Editing layer mask' : 'Editing layer pixels'); },
});
def('layer.clip', {
label: 'Clipping Mask', shortcut: 'Ctrl+Alt+G', enabled: hasLayer, checked: (a) => !!a.doc?.activeLayer?.clip,
run: () => { const l = app.doc.activeLayer; ops.setLayerProps(app.doc, l, { clip: !l.clip }, 'Clipping mask'); },
});
def('layer.lock', {
label: 'Lock Layer', shortcut: 'Ctrl+/', enabled: hasLayer, checked: (a) => !!a.doc?.activeLayer?.locked,
run: () => { const l = app.doc.activeLayer; ops.setLayerProps(app.doc, l, { locked: !l.locked }, 'Lock layer'); },
});
def('layer.alphaLock', {
label: 'Lock Transparency', shortcut: '/', enabled: hasLayer, checked: (a) => !!a.doc?.activeLayer?.alphaLock,
run: () => { const l = app.doc.activeLayer; ops.setLayerProps(app.doc, l, { alphaLock: !l.alphaLock }, 'Lock transparency'); },
});
def('layer.style', { label: 'Layer Style…', enabled: hasLayer, run: (focus) => layerStyleDialog(app, typeof focus === 'string' ? focus : null) });
def('layer.copyStyle', {
label: 'Copy Layer Style', enabled: (a) => hasEffects(a.doc?.activeLayer),
run: () => { app.copiedStyle = app.doc.activeLayer.effects; app.toast('Layer style copied'); },
});
def('layer.pasteStyle', {
label: 'Paste Layer Style', enabled: (a) => !!a.copiedStyle && hasLayer(a),
run: () => ops.setLayerProps(app.doc, app.doc.activeLayer, { effects: app.copiedStyle }, 'Paste layer style'),
});
def('layer.clearStyle', {
label: 'Clear Layer Style', enabled: (a) => !!a.doc?.activeLayer?.effects,
run: () => ops.setLayerProps(app.doc, app.doc.activeLayer, { effects: null }, 'Clear layer style'),
});
for (const [edge, label] of [['left', 'Left Edges'], ['hcenter', 'Horizontal Centers'], ['right', 'Right Edges'], ['top', 'Top Edges'], ['vcenter', 'Vertical Centers'], ['bottom', 'Bottom Edges']]) {
def(`layer.align-${edge}`, {
label, enabled: hasLayer,
run: () => {
const doc = app.doc;
const target = doc.selection?.bounds || { x: 0, y: 0, w: doc.width, h: doc.height };
if (!ops.alignLayer(doc, doc.activeLayer, edge, target)) app.toast(doc.activeLayer.locked ? 'Layer is locked' : 'Layer is empty');
},
});
}
for (const [id, label] of [['flip-h', 'Flip Layer Horizontal'], ['flip-v', 'Flip Layer Vertical'], ['rotate-cw', 'Rotate Layer 90° CW'], ['rotate-ccw', 'Rotate Layer 90° CCW'], ['rotate-180', 'Rotate Layer 180°']]) {
def(`layer.${id}`, { label, enabled: hasLayer, run: () => ops.transformLayer(app.doc, id) || app.toast('Layer is locked') });
}
// ------------------------------------------------------------ select
def('select.all', { label: 'All', shortcut: 'Ctrl+A', enabled: docRequired, run: () => app.doc.setSelection(Selection.all(app.doc.width, app.doc.height), 'Select all') });
def('select.none', { label: 'Deselect', shortcut: 'Ctrl+D', enabled: hasSelection, run: () => app.doc.setSelection(null, 'Deselect') });
def('select.invert', { label: 'Inverse', shortcut: 'Ctrl+Shift+I', enabled: docRequired, run: () => invertSelection(app) });
def('select.layerAlpha', {
label: 'Select Layer Pixels', enabled: hasLayer,
run: (layer) => app.doc.setSelection(Selection.fromAlpha((layer instanceof Layer ? layer : app.doc.activeLayer).canvas), 'Select layer pixels'),
});
def('select.feather', { label: 'Feather…', shortcut: 'Shift+F6', enabled: hasSelection, run: () => modifySelection(app, 'feather') });
def('select.grow', { label: 'Expand…', enabled: hasSelection, run: () => modifySelection(app, 'grow') });
def('select.shrink', { label: 'Contract…', enabled: hasSelection, run: () => modifySelection(app, 'shrink') });
def('select.border', { label: 'Border…', enabled: hasSelection, run: () => modifySelection(app, 'border') });
def('select.smooth', { label: 'Smooth…', enabled: hasSelection, run: () => modifySelection(app, 'smooth') });
def('select.harden', { label: 'Remove Feathering', enabled: hasSelection, run: () => app.doc.setSelection(app.doc.selection.hardened(), 'Harden selection') });
def('select.colorRange', { label: 'Color Range (from Foreground)…', enabled: hasLayer, run: () => colorRangeDialog(app) });
// ------------------------------------------------------------ filters
setUserScripts(app.prefs.get('ditherScripts', []));
for (const [id, f] of Object.entries(FILTERS)) {
def(`filter.${id}`, { label: f.params ? `${f.label}…` : f.label, enabled: hasLayer, run: () => runFilter(app, id) });
}
def('filter.ditherScripts', { label: 'Dither Scripts…', run: () => ditherScriptsDialog(app) });
def('filter.repeat', {
label: 'Repeat Last Filter', shortcut: 'Ctrl+F', enabled: (a) => !!a.lastFilter && hasLayer(a),
run: () => runFilter(app, app.lastFilter.id, app.lastFilter.params),
});
// ------------------------------------------------------------ view
def('view.zoomIn', { label: 'Zoom In', shortcut: 'Ctrl+=', enabled: docRequired, run: () => app.renderer.zoomStep(1) });
def('view.zoomOut', { label: 'Zoom Out', shortcut: 'Ctrl+-', enabled: docRequired, run: () => app.renderer.zoomStep(-1) });
def('view.fit', { label: 'Fit on Screen', shortcut: 'Ctrl+0', enabled: docRequired, run: () => app.renderer.fit(app.doc, true) });
def('view.actual', { label: 'Actual Pixels (100%)', shortcut: 'Ctrl+1', enabled: docRequired, run: () => app.renderer.setZoom(1) });
def('view.pixelGrid', {
label: 'Pixel Grid', checked: (a) => a.renderer.showPixelGrid,
run: () => { app.renderer.showPixelGrid = !app.renderer.showPixelGrid; app.prefs.set('pixelGrid', app.renderer.showPixelGrid); app.renderer.request(); },
});
def('view.grid', {
label: 'Grid', shortcut: "Ctrl+'", enabled: docRequired, checked: (a) => !!a.doc?.guides.show,
run: () => { app.doc.guides.show = !app.doc.guides.show; app.renderer.request(); },
});
def('view.gridSize', {
label: 'Grid Size…', enabled: docRequired,
run: async () => {
const v = await formDialog({ title: 'Grid', fields: [{ key: 'grid', label: 'Spacing', type: 'number', min: 2, max: 2000, unit: 'px' }], values: { grid: app.doc.guides.grid } });
if (v) { app.doc.guides.grid = v.grid; app.doc.guides.show = true; app.renderer.request(); }
},
});
const viewPref = (id, key, label, shortcut, fallback, after) => def(id, {
label, shortcut, checked: (a) => !!a.prefs.get(key, fallback),
run: () => { app.prefs.set(key, !app.prefs.get(key, fallback)); after?.(); app.renderer.request(); },
});
viewPref('view.rulers', 'rulers', 'Rulers', 'Ctrl+R', false, () => app.toast(app.guides.rulers ? 'Rulers on — drag from a ruler to add a guide' : 'Rulers off', 1600));
viewPref('view.guides', 'guides', 'Show Guides', 'Ctrl+;', true);
viewPref('view.snap', 'snap', 'Snap', 'Ctrl+Shift+;', true);
viewPref('view.lockGuides', 'lockGuides', 'Lock Guides', 'Ctrl+Alt+;', false);
def('view.newGuide', { label: 'New Guide…', enabled: docRequired, run: () => newGuideDialog(app) });
def('view.clearGuides', {
label: 'Clear Guides', enabled: (a) => !!a.doc?.guideLines.length,
run: () => app.doc.change('Clear guides', () => { app.doc.guideLines = []; }),
});
def('view.zoomSelection', {
label: 'Zoom to Selection', shortcut: 'Ctrl+Alt+0', enabled: hasSelection,
run: () => zoomToRect(app, app.doc.selection.bounds),
});
def('view.panels', { label: 'Toggle Panels', shortcut: 'Tab', run: () => document.body.classList.toggle('panels-hidden') });
def('view.theme', {
label: 'Light Theme', checked: () => document.documentElement.dataset.theme === 'light',
run: () => app.applyTheme(document.documentElement.dataset.theme === 'light' ? 'dark' : 'light'),
});
def('edit.preferences', { label: 'Preferences…', shortcut: 'Ctrl+,', run: () => preferencesDialog(app) });
def('help.commands', { label: 'Command Palette…', shortcut: 'Ctrl+K', run: () => commandPalette(app) });
// ------------------------------------------------------------ colors & misc
def('color.swap', { label: 'Swap Colors', shortcut: 'X', run: () => app.swapColors() });
def('color.reset', { label: 'Default Colors', shortcut: 'D', run: () => { app.setColor('fg', new Color(0, 0, 0)); app.setColor('bg', new Color(255, 255, 255)); } });
def('help.shortcuts', { label: 'Keyboard Shortcuts', shortcut: 'F1', run: () => shortcutsDialog(app) });
def('help.about', {
label: 'About Atelier',
run: () => alertDialog('Atelier — a layered image editor that runs entirely in your browser. No uploads, no dependencies.', 'About'),
});
return A;
}
// =================================================================== implementations
const PRESETS = [
{ value: 'custom', label: 'Custom' },
{ value: '1920x1080', label: 'HD 1920 × 1080' },
{ value: '1280x720', label: '720p 1280 × 720' },
{ value: '3840x2160', label: '4K 3840 × 2160' },
{ value: '1080x1080', label: 'Square post 1080 × 1080' },
{ value: '1080x1920', label: 'Story 1080 × 1920' },
{ value: '2480x3508', label: 'A4 @300dpi 2480 × 3508' },
{ value: '2550x3300', label: 'Letter @300dpi 2550 × 3300' },
{ value: '800x600', label: '800 × 600' },
{ value: '512x512', label: 'Icon 512 × 512' },
{ value: '64x64', label: 'Pixel art 64 × 64' },
];
async function newDocumentDialog(app) {
const last = app.prefs.get('newDoc', { width: 1200, height: 800, background: 'white' });
let form = null;
const v = await formDialog({
title: 'New Image',
fields: [
{ key: 'name', label: 'Name', type: 'text', default: 'Untitled' },
{ key: 'preset', label: 'Preset', type: 'select', default: 'custom', options: PRESETS },
{ key: 'width', label: 'Width', type: 'number', min: 1, max: 16384, unit: 'px' },
{ key: 'height', label: 'Height', type: 'number', min: 1, max: 16384, unit: 'px' },
{
key: 'background', label: 'Background', type: 'select', options: [
{ value: 'white', label: 'White' }, { value: 'black', label: 'Black' }, { value: 'bg', label: 'Background color' },
{ value: 'fg', label: 'Foreground color' }, { value: 'transparent', label: 'Transparent' },
],
},
],
values: { ...last, name: `Untitled-${app.untitledCounter + 1}` },
onChange: (vals, key) => {
if (key === 'preset' && vals.preset !== 'custom') {
const [w, h] = vals.preset.split('x').map(Number);
form.setValues({ width: w, height: h });
}
},
onReady: (f) => { form = f; },
});
if (!v) return;
app.prefs.set('newDoc', { width: v.width, height: v.height, background: v.background });
const bg = { white: '#ffffff', black: '#000000', transparent: null, bg: app.colors.bg.toCSS(), fg: app.colors.fg.toCSS() }[v.background];
app.untitledCounter++;
app.newDocument({ width: v.width, height: v.height, name: v.name || 'Untitled', background: bg });
}
async function exportDialog(app) {
const doc = app.doc;
const formats = availableFormats();
const saved = app.prefs.get('export', { format: 'png', quality: 90, scale: 100, background: '#ffffff', dither: true, colors: 256 });
const sizeInfo = el('div', { class: 'form-info export-info' }, 'Estimating size…');
const preview = createCanvas(1, 1);
preview.className = 'export-preview';
const estimate = debounce(async (vals) => {
try {
const blob = await exportImage(doc, toOpts(vals));
sizeInfo.textContent = `${Math.round(doc.width * vals.scale / 100)} × ${Math.round(doc.height * vals.scale / 100)} px · ≈ ${formatBytes(blob.size)}`;
if (['jpeg', 'webp', 'avif', 'gif'].includes(vals.format)) {
const img = await createImageBitmap(blob);
const k = Math.min(1, 320 / img.width, 180 / img.height);
preview.width = Math.max(1, Math.round(img.width * k));
preview.height = Math.max(1, Math.round(img.height * k));
preview.getContext('2d').drawImage(img, 0, 0, preview.width, preview.height);
preview.style.display = '';
} else {
preview.style.display = 'none';
}
} catch (err) {
sizeInfo.textContent = err.message;
}
}, 350);
const toOpts = (vals) => ({
format: vals.format, quality: vals.quality / 100, scale: vals.scale / 100, background: vals.background,
dither: vals.dither, colors: vals.colors, icoSizes: [16, 32, 48, 64, 128, 256].filter((s) => vals[`ico${s}`]),
});
const fmtHas = (key) => (vals) => !!FORMATS.find((f) => f.id === vals.format)?.[key];
const fields = [
{ key: 'filename', label: 'File name', type: 'text', default: stripExtension(doc.name) },
{ key: 'format', label: 'Format', type: 'select', options: formats.map((f) => ({ value: f.id, label: f.label })) },
{ key: 'quality', label: 'Quality', type: 'range', min: 1, max: 100, unit: '%', when: fmtHas('quality') },
{ key: 'colors', label: 'Colors', type: 'range', min: 2, max: 256, when: fmtHas('palette') },
{ key: 'dither', label: 'Dithering', type: 'checkbox', when: fmtHas('palette') },
{ key: 'background', label: 'Matte (for formats without alpha)', type: 'color', when: (v) => !FORMATS.find((f) => f.id === v.format)?.alpha },
{ key: 'scale', label: 'Scale', type: 'range', min: 1, max: 400, unit: '%', when: (v) => v.format !== 'ico' },
...[16, 32, 48, 64, 128, 256].map((s) => ({ key: `ico${s}`, label: `${s}×${s}`, type: 'checkbox', default: [16, 32, 48, 256].includes(s), when: fmtHas('icon') })),
{ type: 'element', element: sizeInfo },
{ type: 'element', element: preview },
];
const initial = { ...saved, filename: stripExtension(doc.name) };
if (!formats.find((f) => f.id === initial.format)) initial.format = 'png';
estimate(initial);
const v = await formDialog({ title: 'Export Image', fields, values: initial, onChange: (vals) => { sizeInfo.textContent = 'Estimating size…'; estimate(vals); }, okLabel: 'Export', width: 420 });
if (!v) return;
const { filename, ...rest } = v;
app.prefs.set('export', rest);
try {
const blob = await exportImage(doc, toOpts(v));
const fmt = FORMATS.find((f) => f.id === v.format);
downloadBlob(blob, `${filename || 'image'}.${fmt.ext}`);
app.toast(`Exported ${fmt.label} (${formatBytes(blob.size)})`);
} catch (err) {
alertDialog(`Export failed: ${err.message}`);
}
}
function targetOrToast(app, { allowText = false } = {}) {
const doc = app.doc;
const t = doc?.editTarget;
if (!t) return null;
if (t.layer.locked) { app.toast('Layer is locked'); return null; }
if (t.layer.isText && t.key === 'canvas' && !allowText) { app.toast('Rasterize the text layer first'); return null; }
return t;
}
function clearSelection(app) {
const doc = app.doc;
const t = targetOrToast(app);
if (!t) return;
const edit = new PixelEdit(doc, t.layer, t.key);
const ctx = t.layer[t.key].getContext('2d');
ctx.save();
if (t.key === 'mask') {
ctx.fillStyle = '#000';
if (doc.selection) {
const tmp = createCanvas(doc.width, doc.height);
const tctx = tmp.getContext('2d');
tctx.fillStyle = '#000';
tctx.fillRect(0, 0, doc.width, doc.height);
tctx.globalCompositeOperation = 'destination-in';
tctx.drawImage(doc.selection.mask, 0, 0);
ctx.drawImage(tmp, 0, 0);
} else ctx.fillRect(0, 0, doc.width, doc.height);
} else if (doc.selection) {
ctx.globalCompositeOperation = 'destination-out';
ctx.drawImage(doc.selection.mask, 0, 0);
} else {
ctx.clearRect(0, 0, doc.width, doc.height);
}
ctx.restore();
edit.commit('Clear', doc.selection?.bounds || null);
}
/** Fill selection (or whole layer) with a color. */
function fillWith(app, color, { opacity = 1, mode = 'normal', preserveAlpha = false } = {}) {
const doc = app.doc;
const t = targetOrToast(app);
if (!t) return;
const c = t.key === 'mask' ? color.toGray() : color;
if (t.key === 'canvas') app.noteColorUsed(color);
const edit = new PixelEdit(doc, t.layer, t.key);
const tmp = createCanvas(doc.width, doc.height);
const tctx = tmp.getContext('2d');
tctx.fillStyle = c.toCSS();
tctx.fillRect(0, 0, doc.width, doc.height);
if (doc.selection) {
tctx.globalCompositeOperation = 'destination-in';
tctx.drawImage(doc.selection.mask, 0, 0);
}
const ctx = t.layer[t.key].getContext('2d');
ctx.save();
ctx.globalAlpha = opacity;
ctx.globalCompositeOperation = preserveAlpha || t.layer.alphaLock ? 'source-atop' : BLEND_MODES.find((m) => m.id === mode)?.op || 'source-over';
ctx.drawImage(tmp, 0, 0);
ctx.restore();
edit.commit('Fill', doc.selection?.bounds || null);
}
async function fillDialog(app) {
const v = await formDialog({
title: 'Fill',
fields: [
{ key: 'use', label: 'Contents', type: 'select', default: 'fg', options: [{ value: 'fg', label: 'Foreground color' }, { value: 'bg', label: 'Background color' }, { value: 'black', label: 'Black' }, { value: 'white', label: 'White' }, { value: 'gray', label: '50% Gray' }] },
{ key: 'mode', label: 'Mode', type: 'select', default: 'normal', options: 'blend' },
{ key: 'opacity', label: 'Opacity', type: 'range', min: 1, max: 100, default: 100, unit: '%' },
{ key: 'preserveAlpha', label: 'Preserve transparency', type: 'checkbox', default: false },
],
});
if (!v) return;
const color = { fg: app.colors.fg, bg: app.colors.bg, black: new Color(0, 0, 0), white: new Color(255, 255, 255), gray: new Color(128, 128, 128) }[v.use];
fillWith(app, color, { opacity: v.opacity / 100, mode: v.mode, preserveAlpha: v.preserveAlpha });
}
async function strokeDialog(app) {
const doc = app.doc;
const v = await formDialog({
title: 'Stroke Selection',
fields: [
{ key: 'width', label: 'Width', type: 'range', min: 1, max: 100, default: 4, unit: 'px' },
{ key: 'position', label: 'Location', type: 'select', default: 'center', options: [{ value: 'inside', label: 'Inside' }, { value: 'center', label: 'Center' }, { value: 'outside', label: 'Outside' }] },
{ key: 'opacity', label: 'Opacity', type: 'range', min: 1, max: 100, default: 100, unit: '%' },
],
});
if (!v) return;
const t = targetOrToast(app);
if (!t) return;
const sel = doc.selection.hardened() || doc.selection;
// Build the stroke as (dilated - eroded) of the selection mask.
const r = v.width;
const outer = v.position === 'inside' ? sel : sel.resized(v.position === 'center' ? Math.ceil(r / 2) : r);
const inner = v.position === 'outside' ? sel : sel.resized(-(v.position === 'center' ? Math.floor(r / 2) : r));
const ring = createCanvas(doc.width, doc.height);
const rctx = ring.getContext('2d');
rctx.fillStyle = (t.key === 'mask' ? app.colors.fg.toGray() : app.colors.fg).toCSS();
rctx.fillRect(0, 0, doc.width, doc.height);
rctx.globalCompositeOperation = 'destination-in';
if (outer) rctx.drawImage(outer.mask, 0, 0);
rctx.globalCompositeOperation = 'destination-out';
if (inner) rctx.drawImage(inner.mask, 0, 0);
const edit = new PixelEdit(doc, t.layer, t.key);
const ctx = t.layer[t.key].getContext('2d');
ctx.save();
ctx.globalAlpha = v.opacity / 100;
if (t.layer.alphaLock) ctx.globalCompositeOperation = 'source-atop';
ctx.drawImage(ring, 0, 0);
ctx.restore();
edit.commit('Stroke', outer?.bounds || null);
}
async function imageSizeDialog(app) {
const doc = app.doc;
const ratio = doc.width / doc.height;
let form = null;
const v = await formDialog({
title: 'Image Size',
onReady: (f) => { form = f; },
fields: [
{ key: 'width', label: 'Width', type: 'number', min: 1, max: 16384, unit: 'px' },
{ key: 'height', label: 'Height', type: 'number', min: 1, max: 16384, unit: 'px' },
{ key: 'percent', label: 'Percent', type: 'number', min: 1, max: 1000, step: 0.1, unit: '%' },
{ key: 'constrain', label: 'Constrain proportions', type: 'checkbox' },
{ key: 'smooth', label: 'Smooth resampling (off = nearest neighbour)', type: 'checkbox' },
],
values: { width: doc.width, height: doc.height, percent: 100, constrain: true, smooth: true },
onChange: (vals, key) => {
if (key === 'width' && vals.constrain) form.setValues({ height: Math.max(1, Math.round(vals.width / ratio)), percent: +((vals.width / doc.width) * 100).toFixed(1) });
if (key === 'height' && vals.constrain) form.setValues({ width: Math.max(1, Math.round(vals.height * ratio)), percent: +((vals.height / doc.height) * 100).toFixed(1) });
if (key === 'percent') form.setValues({ width: Math.max(1, Math.round((doc.width * vals.percent) / 100)), height: Math.max(1, Math.round((doc.height * vals.percent) / 100)) });
},
});
if (!v || (v.width === doc.width && v.height === doc.height)) return;
ops.resizeImage(doc, v.width, v.height, v.smooth);
}
async function canvasSizeDialog(app) {
const doc = app.doc;
let anchor = { x: 0.5, y: 0.5 };
const grid = el('div', { class: 'anchor-grid' });
const cells = [];
for (let y = 0; y < 3; y++) {
for (let x = 0; x < 3; x++) {
const b = el('button', { type: 'button', class: 'anchor-cell' });
b.addEventListener('click', () => { anchor = { x: x / 2, y: y / 2 }; cells.forEach((c) => c.classList.toggle('active', c === b)); });
if (x === 1 && y === 1) b.classList.add('active');
cells.push(b);
grid.appendChild(b);
}
}
const v = await formDialog({
title: 'Canvas Size',
fields: [
{ key: 'width', label: 'Width', type: 'number', min: 1, max: 16384, unit: 'px' },
{ key: 'height', label: 'Height', type: 'number', min: 1, max: 16384, unit: 'px' },
{ type: 'info', label: 'Anchor' },
{ type: 'element', element: grid },
],
values: { width: doc.width, height: doc.height },
});
if (!v || (v.width === doc.width && v.height === doc.height)) return;
ops.resizeCanvas(doc, v.width, v.height, anchor);
}
async function preferencesDialog(app) {
const p = app.prefs;
const v = await formDialog({
title: 'Preferences',
width: 440,
fields: [
{ type: 'info', label: 'Interface' },
{ key: 'theme', label: 'Theme', type: 'select', options: [{ value: 'auto', label: 'Match system' }, { value: 'dark', label: 'Dark' }, { value: 'light', label: 'Light' }] },
{ key: 'wheelZoom', label: 'Mouse wheel zooms (instead of scrolling)', type: 'checkbox' },
{ key: 'pixelGrid', label: 'Show pixel grid at high zoom', type: 'checkbox' },
{ type: 'info', label: 'Files' },
{ key: 'useFilePicker', label: 'Save projects with the system file dialog when available', type: 'checkbox' },
{ key: 'autosave', label: 'Autosave unsaved work for crash recovery', type: 'checkbox' },
{ type: 'info', label: 'Performance' },
{ key: 'historySteps', label: 'History steps', type: 'range', min: 10, max: 500 },
],
values: {
theme: p.get('theme', 'dark'), wheelZoom: p.get('wheelZoom', false), pixelGrid: app.renderer.showPixelGrid,
useFilePicker: p.get('useFilePicker', true), autosave: p.get('autosave', true), historySteps: historyLimits.entries,
},
});
if (!v) return;
app.applyTheme(v.theme);
p.set('wheelZoom', v.wheelZoom);
p.set('pixelGrid', v.pixelGrid);
app.renderer.showPixelGrid = v.pixelGrid;
p.set('useFilePicker', v.useFilePicker);
p.set('autosave', v.autosave);
p.set('historySteps', v.historySteps);
historyLimits.entries = v.historySteps;
app.renderer.request();
}
async function newGuideDialog(app) {
const doc = app.doc;
const v = await formDialog({
title: 'New Guide',
fields: [
{ key: 'axis', label: 'Orientation', type: 'select', options: [{ value: 'y', label: 'Horizontal' }, { value: 'x', label: 'Vertical' }] },
{ key: 'pos', label: 'Position', type: 'number', min: -16384, max: 32768, unit: 'px' },
],
values: app.prefs.get('newGuide', { axis: 'x', pos: Math.round(doc.width / 2) }),
});
if (!v) return;
app.prefs.set('newGuide', v);
app.prefs.set('guides', true);
doc.change('New guide', () => { doc.guideLines = [...doc.guideLines, { axis: v.axis, pos: v.pos }]; });
}
/** Zoom and pan so a document rectangle fills the view. */
function zoomToRect(app, r) {
const rend = app.renderer;
const pad = 40;
rend.setZoom(Math.min((rend.width - pad * 2) / r.w, (rend.height - pad * 2) / r.h));
const v = app.doc.view;
v.panX = Math.round(rend.width / 2 - (r.x + r.w / 2) * v.zoom);
v.panY = Math.round(rend.height / 2 - (r.y + r.h / 2) * v.zoom);
rend.request();
app.emit('view');
}
function duplicateDocument(app) {
const src = app.doc;
const doc = app.newDocument({ width: src.width, height: src.height, name: `${stripExtension(src.name)} copy`, empty: true });
doc.layers = src.layers.map((l) => {
const c = l.duplicate('');
c.name = l.name;
if (c.isText) c.renderText();
return c;
});
doc.activeLayerId = doc.layers[Math.max(0, src.activeIndex)].id;
doc.guides = { ...src.guides };
doc.guideLines = src.guideLines;
doc.markDirty(true);
app.emit('doc');
}
function newFillLayer(app) {
const doc = app.doc;
const layer = new Layer(doc.width, doc.height, { name: doc.nextLayerName('Fill') });
const ctx = layer.ctx;
ctx.fillStyle = app.colors.fg.toCSS();
ctx.fillRect(0, 0, doc.width, doc.height);
if (doc.selection) {
ctx.globalCompositeOperation = 'destination-in';
ctx.drawImage(doc.selection.mask, 0, 0);
ctx.globalCompositeOperation = 'source-over';
}
ops.addLayer(doc, layer, { label: 'New fill layer' });
}
function layerFromSelection(app, cut) {
const doc = app.doc;
const src = doc.activeLayer;
if (!src) return;
if (cut && (src.locked || src.isText)) { app.toast(src.locked ? 'Layer is locked' : 'Rasterize the text layer first'); return; }
const sel = doc.selection;
doc.change(cut ? 'Layer via cut' : 'Layer via copy', () => {
const layer = new Layer(doc.width, doc.height, { name: doc.nextLayerName() });
const ctx = layer.ctx;
ctx.drawImage(src.canvas, 0, 0);
ctx.globalCompositeOperation = 'destination-in';
ctx.drawImage(sel.mask, 0, 0);
ctx.globalCompositeOperation = 'source-over';
if (cut) {
const rest = cloneCanvas(src.canvas);
const rctx = rest.getContext('2d');
rctx.globalCompositeOperation = 'destination-out';
rctx.drawImage(sel.mask, 0, 0);
rctx.globalCompositeOperation = 'source-over';
src.canvas = rest;
src.touch();
}
doc.layers.splice(doc.layers.indexOf(src) + 1, 0, layer);
doc.activeLayerId = layer.id;
doc.editMask = false;
doc.selection = null;
});
}
function stepLayer(app, dir) {
const doc = app.doc;
const i = Math.max(0, Math.min(doc.layers.length - 1, doc.activeIndex + dir));
doc.setActiveLayer(doc.layers[i].id);
}
async function layerPropertiesDialog(app) {
const doc = app.doc;
const layer = doc.activeLayer;
const v = await formDialog({
title: 'Layer Properties',
fields: [
{ key: 'name', label: 'Name', type: 'text' },
{ key: 'blendMode', label: 'Blend mode', type: 'select', options: 'blend' },
{ key: 'opacity', label: 'Opacity', type: 'range', min: 0, max: 100, unit: '%' },
{ key: 'visible', label: 'Visible', type: 'checkbox' },
{ key: 'locked', label: 'Locked', type: 'checkbox' },
{ key: 'alphaLock', label: 'Lock transparency', type: 'checkbox' },
{ key: 'clip', label: 'Clip to layer below', type: 'checkbox' },
],
values: { ...layer.captureProps(), opacity: Math.round(layer.opacity * 100) },
});
if (!v) return;
ops.setLayerProps(doc, layer, {
name: v.name || layer.name, blendMode: v.blendMode, opacity: v.opacity / 100, visible: v.visible,
locked: v.locked, alphaLock: v.alphaLock, clip: v.clip,
}, 'Layer properties');
}
function invertSelection(app) {
const doc = app.doc;
const sel = doc.selection ? doc.selection.inverted() : Selection.all(doc.width, doc.height);
doc.setSelection(sel, 'Invert selection');
}
async function modifySelection(app, kind) {
const doc = app.doc;
const spec = {
feather: ['Feather Selection', 'Feather radius', 'Feather', (s, n) => s.feathered(n)],
grow: ['Expand Selection', 'Expand by', 'Expand selection', (s, n) => s.resized(n)],
shrink: ['Contract Selection', 'Contract by', 'Contract selection', (s, n) => s.resized(-n)],
border: ['Border Selection', 'Width', 'Border selection', (s, n) => s.border(n)],
smooth: ['Smooth Selection', 'Sample radius', 'Smooth selection', (s, n) => s.smoothed(n)],
}[kind];
const v = await formDialog({
title: spec[0],
fields: [{ key: 'amount', label: spec[1], type: 'range', min: 1, max: 200, default: app.prefs.get(`sel.${kind}`, 8), unit: 'px' }],
});
if (!v) return;
app.prefs.set(`sel.${kind}`, v.amount);
const next = spec[3](doc.selection, v.amount);
if (!next) app.toast('The selection would be empty');
doc.setSelection(next, spec[2]);
}
async function colorRangeDialog(app) {
const doc = app.doc;
const v = await formDialog({
title: 'Color Range',
fields: [
{ type: 'info', label: 'Selects every pixel similar to the foreground color.' },
{ key: 'fuzz', label: 'Fuzziness', type: 'range', min: 0, max: 255, default: 40 },
{ key: 'merged', label: 'Sample all layers', type: 'checkbox', default: true },
],
});
if (!v) return;
const src = v.merged ? flattenToCanvas(doc) : doc.activeLayer.canvas;
const id = src.getContext('2d', { willReadFrequently: true }).getImageData(0, 0, doc.width, doc.height);
const d = id.data;
const fg = app.colors.fg;
const out = createCanvas(doc.width, doc.height);
const oid = out.getContext('2d').createImageData(doc.width, doc.height);
for (let i = 0; i < d.length; i += 4) {
if (!d[i + 3]) continue;
const dist = Math.max(Math.abs(d[i] - fg.r), Math.abs(d[i + 1] - fg.g), Math.abs(d[i + 2] - fg.b));
// smooth falloff over the fuzziness range
const a = dist <= v.fuzz ? 255 : Math.max(0, 255 - (dist - v.fuzz) * 8);
oid.data[i + 3] = a;
}
out.getContext('2d').putImageData(oid, 0, 0);
doc.setSelection(Selection.orNull(out), 'Color range');
if (!doc.selection) app.toast('No matching pixels');
}
// ------------------------------------------------------------ filters with live preview
/** Reset select values that are no longer among the options (e.g. a deleted dither script). */
function sanitizeSelects(fields, values) {
for (const f of fields || []) {
if (f.type === 'select' && Array.isArray(f.options) && !f.options.some((o) => String(o.value ?? o) === String(values[f.key]))) values[f.key] = f.default;
}
return values;
}
/** Extra buttons for particular filter dialogs. ctx: { app, getParams, setParams, form, refresh }. */
const FILTER_DIALOG_EXTRAS = {
dither: (ctx) => [el('button', {
type: 'button', class: 'btn', title: 'Write your own dithering algorithms in JavaScript',
onclick: async () => {
const cur = ctx.getParams().algorithm;
const picked = await ditherScriptsDialog(ctx.app, { selectId: cur?.startsWith('script:') ? cur.slice(7) : null, offerUse: true });
const ctl = ctx.form()?.controls.algorithm;
if (!ctl) return;
const opts = algorithmOptions();
ctl.setOptions(opts);
if (picked) ctx.setParams({ algorithm: `script:${picked}` });
else if (!opts.some((o) => o.value === ctx.getParams().algorithm)) ctx.setParams({ algorithm: 'floyd-steinberg' });
ctx.refresh(); // a script's source may have changed
},
}, 'Scripts…')],
};
async function runFilter(app, id, presetParams = null) {
const doc = app.doc;
const filter = FILTERS[id];
const t = targetOrToast(app);
if (!t) return;
const { layer, key } = t;
const sel = doc.selection;
const region = sel ? sel.bounds : { x: 0, y: 0, w: doc.width, h: doc.height };
const env = { docWidth: doc.width, docHeight: doc.height, fg: app.colors.fg, bg: app.colors.bg };
const original = layer[key];
/** Compute filtered canvas (full layer size). Async because filters may return a Promise. */
const compute = async (params) => {
const pad = Math.ceil(filter.pad?.(params) || 0);
const rx = Math.max(0, region.x - pad), ry = Math.max(0, region.y - pad);
const rw = Math.min(doc.width, region.x + region.w + pad) - rx, rh = Math.min(doc.height, region.y + region.h + pad) - ry;
const srcData = original.getContext('2d', { willReadFrequently: true }).getImageData(rx, ry, rw, rh);
const result = await filter.apply(srcData, params, { ...env, x: rx, y: ry });
const piece = createCanvas(rw, rh);
piece.getContext('2d').putImageData(result, 0, 0);
const out = cloneCanvas(original);
const octx = out.getContext('2d');
if (sel) {
// blend through the selection mask: out = original*(1-m) + piece*m
const masked = createCanvas(doc.width, doc.height);
const mctx = masked.getContext('2d');
mctx.drawImage(piece, rx, ry);
mctx.globalCompositeOperation = 'destination-in';
mctx.drawImage(sel.mask, 0, 0);
octx.globalCompositeOperation = 'destination-out';
octx.drawImage(sel.mask, 0, 0);
octx.globalCompositeOperation = 'source-over';
octx.drawImage(masked, 0, 0);
} else {
octx.clearRect(rx, ry, rw, rh);
octx.drawImage(piece, rx, ry);
}
if (layer.alphaLock && key === 'canvas') {
// Keep the original alpha exactly (compositing would multiply it in twice).
const od = octx.getImageData(rx, ry, rw, rh);
const ad = original.getContext('2d', { willReadFrequently: true }).getImageData(rx, ry, rw, rh).data;
for (let i = 3; i < ad.length; i += 4) od.data[i] = ad[i];
octx.putImageData(od, rx, ry);
}
return out;
};
const setPreview = (canvas) => {
if (key === 'canvas') layer.preview = canvas;
else { layer.mask = canvas || original; layer.touchMask(); }
layer.touch();
doc.markDirty();
};
const commit = (result) => {
setPreview(null);
const edit = new PixelEdit(doc, layer, key);
const ctx = original.getContext('2d');
ctx.save();
ctx.globalCompositeOperation = 'copy';
ctx.drawImage(result, 0, 0);
ctx.restore();
edit.commit(filter.label, region);
};
const fields = filter.params; // may be a getter that rebuilds options (dither scripts)
let params = presetParams || app.prefs.get(`filter.${id}`, null) || defaultParams(filter);
params = sanitizeSelects(fields, { ...defaultParams(filter), ...params });
/** Apply for real; errors (e.g. from a user script) end up in an alert, not the console. */
const apply = async (p) => {
app.busy(true);
await new Promise((r) => setTimeout(r, 10));
try { commit(await compute(p)); return true; } catch (err) {
setPreview(null);
if (!err.superseded) alertDialog(err.message, filter.label);
return false;
} finally { app.busy(false); }
};
if (!fields || presetParams) {
if (await apply(params)) app.lastFilter = { id, params };
return;
}
let previewOn = true;
let closed = false;
let job = 0;
const update = debounce(() => {
if (closed) return;
const my = ++job;
if (!previewOn) { setPreview(null); return; }
requestAnimationFrame(async () => {
if (my !== job) return;
try {
const out = await compute(params);
if (my === job) { setPreview(out); setError(null); }
} catch (err) {
if (err.superseded || my !== job) return;
setPreview(null);
setError(err.message);
}
});
}, 60);
const errorLine = el('div', { class: 'form-error', role: 'alert', style: 'display:none' });
const setError = (msg) => { errorLine.textContent = msg || ''; errorLine.style.display = msg ? '' : 'none'; };
const previewToggle = el('label', { class: 'field check-field' },
el('input', { type: 'checkbox', checked: true, onchange: (e) => { previewOn = e.target.checked; update(); } }),
el('span', {}, 'Preview'));
const resetBtn = el('button', { type: 'button', class: 'btn', onclick: () => { params = defaultParams(filter); form?.setValues(params); update(); } }, 'Reset');
let form = null;
const extraButtons = FILTER_DIALOG_EXTRAS[id]?.({
app,
getParams: () => params,
setParams: (nv) => { params = { ...params, ...nv }; form?.setValues(nv); },
form: () => form,
refresh: () => update(),
}) || [];
update();
const result = await formDialog({
title: filter.label,
fields,
values: params,
width: filter.width,
onChange: (vals) => { params = { ...vals }; update(); },
extra: el('div', {}, errorLine, el('div', { class: 'form-row' }, previewToggle, ...extraButtons, resetBtn)),
onReady: (f) => { form = f; },
});
form = null;
closed = true;
job++;
if (!result) { setPreview(null); return; }
app.prefs.set(`filter.${id}`, result);
if (!(await apply(result))) return;
app.lastFilter = { id, params: result };
}
function shortcutsDialog(app) {
const rows = [];
for (const [id, T] of app.toolClasses) if (T.shortcut) rows.push([T.label, T.shortcut]);
for (const a of app.actions.values()) if (a.shortcut) rows.push([a.label.replace(/…$/, ''), a.shortcut]);
rows.push(
['Pan (temporary hand)', 'Space'], ['Brush size', '[ / ]'], ['Zoom with wheel', 'Ctrl+Wheel'], ['Layer opacity', '1…0 (with Move tool)'],
['Open the menu bar (then arrows, Enter, Esc)', 'F10'], ['Zoom / pan on touch screens', 'Two-finger pinch'],
['Move a guide (drag back to a ruler to delete)', 'Move tool drag'], ['Opposite dodge/burn or sponge mode', 'Alt+drag'],
);
const table = el('table', { class: 'shortcut-table' }, ...rows.map(([l, s]) => el('tr', {}, el('td', {}, l), el('td', {}, el('kbd', {}, s)))));
openDialog({ title: 'Keyboard Shortcuts', body: el('div', { class: 'shortcut-scroll' }, table), width: 460 });
}
|