forked from 1j01/jspaint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunctions.js
2421 lines (2143 loc) · 72.4 KB
/
functions.js
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
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// expresses order in the URL as well as type
const param_types = {
// settings
"eye-gaze-mode": "bool",
"vertical-color-box-mode": "bool",
"speech-recognition-mode": "bool",
// sessions
"local": "string",
"session": "string",
"load": "string",
};
const exclusive_params = [
"local",
"session",
"load",
];
function get_all_url_params() {
const params = {};
location.hash.replace(/^#/, "").split(/,/).forEach((param_decl)=> {
// colon is used in param value for URLs so split(":") isn't good enough
const colon_index = param_decl.indexOf(":");
if (colon_index === -1) {
// boolean value, implicitly true because it's in the URL
const param_name = param_decl;
params[param_name] = true;
} else {
const param_name = param_decl.slice(0, colon_index);
const param_value = param_decl.slice(colon_index + 1);
params[param_name] = decodeURIComponent(param_value);
}
});
for (const [param_name, param_type] of Object.entries(param_types)) {
if (param_type === "bool" && !params[param_name]) {
params[param_name] = false;
}
}
return params;
}
function get_url_param(param_name) {
return get_all_url_params()[param_name];
}
function change_url_param(param_name, value, {replace_history_state=false}={}) {
change_some_url_params({[param_name]: value}, {replace_history_state});
}
function change_some_url_params(updates, {replace_history_state=false}={}) {
for (const exclusive_param of exclusive_params) {
if (updates[exclusive_param]) {
exclusive_params.forEach((param)=> {
if (param !== exclusive_param) {
updates[param] = null; // must be enumerated (for Object.assign) but falsey, to get removed from the URL
}
});
}
}
set_all_url_params(Object.assign({}, get_all_url_params(), updates), {replace_history_state});
}
function set_all_url_params(params, {replace_history_state=false}={}) {
let new_hash = "";
for (const [param_name, param_type] of Object.entries(param_types)) {
if (params[param_name]) {
if (new_hash.length) {
new_hash += ",";
}
new_hash += encodeURIComponent(param_name);
if (param_type !== "bool") {
new_hash += ":" + encodeURIComponent(params[param_name]);
}
}
}
// Note: gets rid of query string (?) portion of the URL
// This is desired for upgrading backwards compatibility URLs;
// may not be desired for future cases.
const new_url = `${location.origin}${location.pathname}#${new_hash}`;
if (replace_history_state) {
history.replaceState(null, document.title, new_url);
} else {
history.pushState(null, document.title, new_url);
}
$G.triggerHandler("change-url-params");
}
function update_magnified_canvas_size(){
$canvas.css("width", canvas.width * magnification);
$canvas.css("height", canvas.height * magnification);
update_canvas_rect();
}
function update_canvas_rect() {
canvas_bounding_client_rect = canvas.getBoundingClientRect();
update_helper_layer();
}
let helper_layer_update_queued;
let info_for_updating_pointer; // for updating on scroll or resize, where the mouse stays in the same place but its coordinates in the document change
function update_helper_layer(e){
// e may be a number from requestAnimationFrame callback; ignore that
if (e && isFinite(e.clientX)) {
info_for_updating_pointer = {clientX: e.clientX, clientY: e.clientY, devicePixelRatio};
}
if (helper_layer_update_queued) {
// window.console && console.log("update_helper_layer - nah, already queued");
return;
} else {
// window.console && console.log("update_helper_layer");
}
helper_layer_update_queued = true;
requestAnimationFrame(()=> {
helper_layer_update_queued = false;
update_helper_layer_immediately();
});
}
function update_helper_layer_immediately() {
// window.console && console.log("Update helper layer NOW");
if (info_for_updating_pointer) {
const rescale = info_for_updating_pointer.devicePixelRatio / devicePixelRatio;
info_for_updating_pointer.clientX *= rescale;
info_for_updating_pointer.clientY *= rescale;
info_for_updating_pointer.devicePixelRatio = devicePixelRatio;
pointer = to_canvas_coords(info_for_updating_pointer);
}
update_fill_and_stroke_colors_and_lineWidth(selected_tool);
const grid_visible = show_grid && magnification >= 4 && (window.devicePixelRatio * magnification) >= 4;
const scale = magnification * window.devicePixelRatio;
if (!helper_layer) {
helper_layer = new OnCanvasHelperLayer(0, 0, canvas.width, canvas.height, false, scale);
}
const hcanvas = helper_layer.canvas;
const hctx = hcanvas.ctx;
const margin = 15;
const viewport_x = Math.floor(Math.max($canvas_area.scrollLeft() / magnification - margin, 0));
const viewport_y = Math.floor(Math.max($canvas_area.scrollTop() / magnification - margin, 0));
const viewport_x2 = Math.floor(Math.min(viewport_x + $canvas_area.width() / magnification + margin*2, canvas.width));
const viewport_y2 = Math.floor(Math.min(viewport_y + $canvas_area.height() / magnification + margin*2, canvas.height));
const viewport_width = viewport_x2 - viewport_x;
const viewport_height = viewport_y2 - viewport_y;
const resolution_width = viewport_width * scale;
const resolution_height = viewport_height * scale;
if (
hcanvas.width !== resolution_width ||
hcanvas.height !== resolution_height
) {
hcanvas.width = resolution_width;
hcanvas.height = resolution_height;
hcanvas.ctx.disable_image_smoothing();
helper_layer.width = viewport_width;
helper_layer.height = viewport_height;
}
helper_layer.x = viewport_x;
helper_layer.y = viewport_y;
helper_layer.position();
hctx.clearRect(0, 0, hcanvas.width, hcanvas.height);
var tools_to_preview = [...selected_tools];
// the select box previews draw the document canvas onto the preview canvas
// so they have something to invert within the preview canvas
// but this means they block out anything earlier
// NOTE: sort Select after Free-Form Select,
// Brush after Eraser, as they are from the toolbar ordering
tools_to_preview.sort((a, b)=> {
if (a.selectBox && !b.selectBox) {
return -1;
}
if (!a.selectBox && b.selectBox) {
return 1;
}
return 0;
});
// two select box previews would just invert and cancel each other out
// so only render one if there's one or more
var select_box_index = tools_to_preview.findIndex((tool)=> tool.selectBox);
if (select_box_index >= 0) {
tools_to_preview = tools_to_preview.filter((tool, index)=> !tool.selectBox || index == select_box_index);
}
tools_to_preview.forEach((tool)=> {
if(tool.drawPreviewUnderGrid && pointer && pointers.length < 2){
hctx.save();
tool.drawPreviewUnderGrid(hctx, pointer.x, pointer.y, grid_visible, scale, -viewport_x, -viewport_y);
hctx.restore();
}
});
if (selection) {
hctx.save();
hctx.scale(scale, scale);
hctx.translate(-viewport_x, -viewport_y);
hctx.drawImage(selection.canvas, selection.x, selection.y);
hctx.restore();
}
if (textbox) {
hctx.save();
hctx.scale(scale, scale);
hctx.translate(-viewport_x, -viewport_y);
hctx.drawImage(textbox.canvas, textbox.x, textbox.y);
hctx.restore();
}
if (grid_visible) {
draw_grid(hctx, scale);
}
tools_to_preview.forEach((tool)=> {
if(tool.drawPreviewAboveGrid && pointer && pointers.length < 2){
hctx.save();
tool.drawPreviewAboveGrid(hctx, pointer.x, pointer.y, grid_visible, scale, -viewport_x, -viewport_y);
hctx.restore();
}
});
}
function update_disable_aa() {
const dots_per_canvas_px = window.devicePixelRatio * magnification;
const round = Math.floor(dots_per_canvas_px) === dots_per_canvas_px;
$canvas_area.toggleClass("disable-aa-for-things-at-main-canvas-scale", dots_per_canvas_px >= 3 || round);
}
function set_magnification(scale){
const prev_magnification = magnification;
let scroll_left = $canvas_area.scrollLeft();
let scroll_top = $canvas_area.scrollTop();
magnification = scale;
if(scale !== 1){
return_to_magnification = scale;
}
update_magnified_canvas_size();
// rescale viewport with top left as anchor
scroll_left *= magnification / prev_magnification;
scroll_top *= magnification / prev_magnification;
$canvas_area.scrollLeft(scroll_left);
$canvas_area.scrollTop(scroll_top);
$G.triggerHandler("resize"); // updates handles & grid
$G.trigger("option-changed"); // updates options area
}
let $custom_zoom_window;
function show_custom_zoom_window() {
if ($custom_zoom_window) {
$custom_zoom_window.close();
}
const $w = new $FormToolWindow("Custom Zoom");
$custom_zoom_window = $w;
// @TODO: show Current zoom: blah% ?
const $fieldset = $(E("fieldset")).appendTo($w.$main);
$fieldset.append("<legend>Zoom to</legend>");
$fieldset.append("<label><input type='radio' name='custom-zoom-radio' value='1'/>100%</label>");
$fieldset.append("<label><input type='radio' name='custom-zoom-radio' value='2'/>200%</label>");
$fieldset.append("<label><input type='radio' name='custom-zoom-radio' value='4'/>400%</label>");
$fieldset.append("<label><input type='radio' name='custom-zoom-radio' value='6'/>600%</label>");
$fieldset.append("<label><input type='radio' name='custom-zoom-radio' value='8'/>800%</label>");
$fieldset.append("<label><input type='radio' name='custom-zoom-radio' value='really-custom'/><input type='number' min='10' max='1000' name='really-custom-zoom-input' value=''/>%</label>");
let is_custom = true;
$fieldset.find("input[type=radio]").get().forEach((el)=> {
if (parseFloat(el.value) === magnification) {
el.checked = true;
is_custom = false;
}
});
const $really_custom_radio_option = $fieldset.find("input[value='really-custom']");
const $really_custom_input = $fieldset.find("input[name='really-custom-zoom-input']");
$really_custom_input.closest("label").on("click", ()=> {
$really_custom_radio_option.prop("checked", true);
$really_custom_input[0].focus();
});
if (is_custom) {
$really_custom_input.val(magnification * 100);
$really_custom_radio_option.prop("checked", true);
}
$fieldset.find("label").css({display: "block"});
$w.$Button("Okay", () => {
let option_val = $fieldset.find("input[name='custom-zoom-radio']:checked").val();
let mag;
if(option_val === "really-custom"){
option_val = $really_custom_input.val();
if(`${option_val}`.match(/\dx$/)) { // ...you can't actually type an x; oh well...
mag = parseFloat(option_val);
}else if(`${option_val}`.match(/\d%?$/)) {
mag = parseFloat(option_val) / 100;
}
if(isNaN(mag)){
const $msgw = new $FormToolWindow("Invalid Value").addClass("dialogue-window");
$msgw.$main.text("The value specified for custom zoom was invalid.");
$msgw.$Button("Okay", () => {
$msgw.close();
});
return;
}
}else{
mag = parseFloat(option_val);
}
set_magnification(mag);
$w.close();
})[0].focus();
$w.$Button("Cancel", () => {
$w.close();
});
$w.center();
}
function toggle_grid() {
show_grid = !show_grid;
// $G.trigger("option-changed");
update_helper_layer();
}
function reset_colors(){
colors = {
foreground: "#000000",
background: "#ffffff",
ternary: "",
};
$G.trigger("option-changed");
}
function reset_file(){
document_file_path = null;
file_name = "untitled";
update_title();
saved = true;
}
function reset_canvas_and_history(){
undos.length = 0;
redos.length = 0;
current_history_node = root_history_node = make_history_node({
name: "New Document",
icon: get_help_folder_icon("p_blank.png"),
});
history_node_to_cancel_to = null;
canvas.width = Math.max(1, my_canvas_width);
canvas.height = Math.max(1, my_canvas_height);
ctx.disable_image_smoothing();
ctx.fillStyle = colors.background;
ctx.fillRect(0, 0, canvas.width, canvas.height);
current_history_node.image_data = ctx.getImageData(0, 0, canvas.width, canvas.height);
$canvas_area.trigger("resize");
$G.triggerHandler("history-update"); // update history view
}
function make_history_node({
parent = null,
futures = [],
timestamp = Date.now(),
soft = false,
image_data = null,
selection_image_data = null,
selection_x,
selection_y,
textbox_text,
textbox_x,
textbox_y,
textbox_width,
textbox_height,
text_tool_font = null,
tool_transparent_mode,
foreground_color,
background_color,
ternary_color,
name,
icon = null,
}) {
return {
parent,
futures,
timestamp,
soft,
image_data,
selection_image_data,
selection_x,
selection_y,
textbox_text,
textbox_x,
textbox_y,
textbox_width,
textbox_height,
text_tool_font,
tool_transparent_mode,
foreground_color,
background_color,
ternary_color,
name,
icon,
};
}
function update_title(){
document.title = `${file_name} - ${is_pride_month ? "Gay es " : ""}Paint`;
if (is_pride_month) {
$("link[rel~='icon']").attr("href", "./images/icons/gay-es-paint-16x16-light-outline.png");
}
}
function create_and_trigger_input(attrs, callback){
const $input = $(E("input")).attr(attrs)
.on("change", ()=> {
callback($input[0]);
$input.remove();
})
.appendTo($app)
.hide()
.trigger("click");
return $input;
}
// @TODO: rename these functions to lowercase (and maybe say "files" in this case)
function get_FileList_from_file_select_dialog(callback){
// @TODO: specify mime types?
create_and_trigger_input({type: "file"}, input => {
callback(input.files);
});
}
function open_from_Image(img, callback, canceled){
are_you_sure(() => {
// @TODO: shouldn't open_from_* start a new session?
deselect();
cancel();
saved = false;
reset_file();
reset_colors();
reset_canvas_and_history(); // (with newly reset colors)
set_magnification(default_magnification);
ctx.copy(img);
detect_transparency();
$canvas_area.trigger("resize");
current_history_node.name = "Load Document";
current_history_node.image_data = ctx.getImageData(0, 0, canvas.width, canvas.height);
current_history_node.icon = null; // @TODO
$G.triggerHandler("session-update"); // autosave
$G.triggerHandler("history-update"); // update history view
callback && callback();
}, canceled);
}
function get_URIs(text) {
// parse text/uri-list
// get lines, discarding comments
const lines = text.split(/[\n\r]+/).filter(line => line[0] !== "#" && line);
// discard text with too many lines (likely pasted HTML or something) - may want to revisit this
if (lines.length > 15) {
return [];
}
// parse URLs, discarding anything that parses as a relative URL
const uris = [];
for (let i=0; i<lines.length; i++) {
try {
const url = new URL(lines[i]);
uris.push(url.href);
// eslint-disable-next-line no-empty
} catch(e) {}
}
return uris;
}
function load_image_from_URI(uri, callback){
const is_blob_uri = uri.match(/^blob:/);
const is_download = !uri.match(/^(blob|data):/);
if (is_blob_uri && uri.indexOf(`blob:${location.origin}`) === -1) {
const error = new Error("can't load blob: URI from another domain");
error.code = "cors-blob-uri";
callback(error);
return;
}
const uris_to_try = is_download ? [
uri,
// work around CORS headers not sent by whatever server
`https://jspaint-cors-proxy.herokuapp.com/${uri}`,
// if the image isn't available on the live web, see if it's archived
`https://web.archive.org/${uri}`,
] : [uri];
let index = 0;
const try_next_uri = ()=> {
const uri_to_try = uris_to_try[index];
if (is_download) {
$status_text.text("Downloading picture...");
}
const handle_fetch_fail = ()=> {
index += 1;
if (index >= uris_to_try.length) {
if (is_download) {
$status_text.text("Failed to download picture.");
}
callback && callback(new Error(`failed to download image from any of three URIs (${JSON.stringify(uris_to_try)}).`));
} else {
try_next_uri();
}
};
const show_progress = ({loaded, total})=> {
if (is_download) {
$status_text.text(`Downloading picture... (${Math.round(loaded/total*100)}%)`);
}
};
if (is_download) {
console.log(`Try loading image from URI (${index + 1}/${uris_to_try.length}): "${uri_to_try}"`);
}
fetch(uri_to_try)
.then(response => {
if (!response.ok) {
throw Error(`${response.status} ${response.statusText}`);
}
if (!response.body) {
if (is_download) {
console.log("ReadableStream not yet supported in this browser. Progress won't be shown for image requests.");
}
return response;
}
// to access headers, server must send CORS header "Access-Control-Expose-Headers: content-encoding, content-length x-file-size"
// server must send custom x-file-size header if gzip or other content-encoding is used
const contentEncoding = response.headers.get("content-encoding");
const contentLength = response.headers.get(contentEncoding ? "x-file-size" : "content-length");
if (contentLength === null) {
if (is_download) {
console.log("Response size header unavailable. Progress won't be shown for this image request.");
}
return response;
}
const total = parseInt(contentLength, 10);
let loaded = 0;
return new Response(
new ReadableStream({
start(controller) {
const reader = response.body.getReader();
read();
function read() {
reader.read().then(({done, value}) => {
if (done) {
controller.close();
return;
}
loaded += value.byteLength;
show_progress({loaded, total})
controller.enqueue(value);
read();
}).catch(error => {
console.error(error);
controller.error(error)
})
}
}
})
);
})
.then(response => response.blob())
.then(blob => {
if (is_download) {
console.log("Download complete.");
$status_text.text("Download complete.");
}
const img = new Image();
img.crossOrigin = "Anonymous";
const handle_decode_fail = ()=> {
// @TODO: use headers to detect HTML instead, since a doctype is not guaranteed
// @TODO: fall back to WayBack Machine still for decode errors,
// since a website might start redirecting swathes of URLs regardless of what they originally pointed to,
// at which point they would likely point to a web page instead of an image.
// (But still show an error about it not being an image, if WayBack also fails.)
var fr = new FileReader();
fr.onerror = ()=> {
const error = new Error("failed to decode blob as image or text");
error.code = "decode-fail";
callback(error);
};
fr.onload = (e)=> {
const error = new Error("failed to decode blob as an image");
error.code = e.target.result.match(/^\s*<!doctype\s+html/i) ? "html-not-image" : "decode-fail";
callback(error);
};
fr.readAsText(blob);
};
img.onload = ()=> {
if (!img.complete || typeof img.naturalWidth == "undefined" || img.naturalWidth === 0) {
handle_decode_fail();
return;
}
callback(null, img);
};
img.onerror = handle_decode_fail;
img.src = window.URL.createObjectURL(blob);
})
.catch(handle_fetch_fail);
};
try_next_uri();
}
function open_from_URI(uri, callback, canceled){
load_image_from_URI(uri, (error, img) => {
if(error){ return callback(error); }
open_from_Image(img, callback, canceled);
});
}
function open_from_File(file, callback, canceled){
const blob_url = URL.createObjectURL(file);
load_image_from_URI(blob_url, (error, img) => {
// revoke object URL regardless of error
URL.revokeObjectURL(file);
if(error){ return callback(error); }
open_from_Image(img, () => {
file_name = file.name;
document_file_path = file.path; // available in Electron
update_title();
saved = true;
callback();
}, canceled);
});
}
function open_from_FileList(files, user_input_method_verb_past_tense){
for (const file of files) {
if (file.type.match(/^image/)) {
open_from_File(file, err => {
if(err){ return show_error_message("Failed to open file:", err); }
});
return;
} else if (file.name.match(/\.theme(pack)?$/i)) {
loadThemeFile(file);
return;
}
}
if(files.length > 1){
show_error_message(`None of the files ${user_input_method_verb_past_tense} appear to be images.`);
}else{
show_error_message(`File ${user_input_method_verb_past_tense} does not appear to be an image.`);
}
}
function loadThemeFile(file) {
var reader = new FileReader();
reader.onload = ()=> {
loadThemeFromText(reader.result);
};
reader.readAsText(file);
}
function loadThemeFromText(fileText) {
var cssProperties = parseThemeFileString(fileText);
applyCSSProperties(cssProperties);
window.themeCSSProperties = cssProperties;
$("iframe").each((i, iframe)=> {
try {
applyCSSProperties(cssProperties, iframe.contentDocument.documentElement);
} catch(error) {
console.log("error applying theme to iframe", iframe, error);
}
})
$G.triggerHandler("theme-load");
}
function file_new(){
are_you_sure(() => {
deselect();
cancel();
saved = false;
reset_file();
reset_colors();
reset_canvas_and_history(); // (with newly reset colors)
set_magnification(default_magnification);
$G.triggerHandler("session-update"); // autosave
});
}
// @TODO: factor out open_select/choose_file_dialog or get_file_from_file_select_dialog or whatever
// all these open_from_* things are done backwards, basically
// there's this little thing called Inversion of Control...
// also paste_from_file_select_dialog
function file_open(){
get_FileList_from_file_select_dialog(files => {
open_from_FileList(files, "selected");
});
}
let $file_load_from_url_window;
function file_load_from_url(){
if($file_load_from_url_window){
$file_load_from_url_window.close();
}
const $w = new $FormToolWindow().addClass("dialogue-window");
$file_load_from_url_window = $w;
$w.title("Load from URL");
// @TODO: URL validation (input has to be in a form (and we don't want the form to submit))
$w.$main.html("<label>URL: <input type='url' required value='' class='url-input'/></label>");
const $input = $w.$main.find(".url-input");
$w.$Button("Load", () => {
const uris = get_URIs($input.val());
if (uris.length > 0) {
// @TODO: retry loading if same URL entered
// actually, make it change the hash only after loading successfully
// (but still load from the hash when necessary)
// make sure it doesn't overwrite the old session before switching
$w.close();
change_url_param("load", uris[0]);
} else {
show_error_message("Invalid URL. It must include a protocol (https:// or http://)");
}
});
$w.$Button("Cancel", () => {
$w.close();
});
$w.center();
$input[0].focus();
}
function file_save(){
deselect();
if(file_name.match(/\.svg$/)){
// @TODO: only affect suggested name in save dialog, don't change file_name
file_name = `${file_name.replace(/\.svg$/, "")}.png`;
return file_save_as();
}
if(document_file_path){
// @TODO: save as JPEG by default if the previously opened/saved file was a JPEG?
return save_to_file_path(document_file_path, "PNG", (saved_file_path, saved_file_name) => {
saved = true;
document_file_path = saved_file_path;
file_name = saved_file_name;
update_title();
});
}
file_save_as();
}
function file_save_as(){
deselect();
save_canvas_as(canvas, `${file_name.replace(/\.(bmp|dib|a?png|gif|jpe?g|jpe|jfif|tiff?|webp|raw)$/, "")}.png`, (saved_file_path, saved_file_name) => {
saved = true;
document_file_path = saved_file_path;
file_name = saved_file_name;
update_title();
});
}
function are_you_sure(action, canceled){
if(saved){
action();
}else{
const $w = new $FormToolWindow().addClass("dialogue-window");
$w.title("Paint");
$w.$main.text(`Save changes to ${file_name}?`);
$w.$Button("Save", () => {
$w.close();
file_save();
action();
})[0].focus();
$w.$Button("Discard", () => {
$w.close();
action();
});
$w.$Button("Cancel", () => {
$w.close();
canceled && canceled();
});
$w.$x.on("click", () => {
canceled && canceled();
});
$w.center();
}
}
function show_error_message(message, error){
const $w = $FormToolWindow().title("Error").addClass("dialogue-window");
$w.$main.text(message);
$w.$main.css("max-width", "600px");
if(error){
$(E("pre"))
.appendTo($w.$main)
.text(error.stack || error.toString())
.css({
background: "white",
color: "#333",
// background: "#A00",
// color: "white",
fontFamily: "monospace",
width: "500px",
overflow: "auto",
});
}
$w.$Button("OK", () => {
$w.close();
});
$w.center();
if (error) {
window.console && console.error(message, error);
} else {
window.console && console.error(message);
}
}
// @TODO: close are_you_sure windows and these Error windows when switching sessions
// because it can get pretty confusing
function show_resource_load_error_message(error){
const $w = $FormToolWindow().title("Error").addClass("dialogue-window");
const firefox = navigator.userAgent.toLowerCase().indexOf("firefox") > -1;
if (error.code === "cors-blob-uri") {
$w.$main.html(`
<p>Can't load image from address starting with "blob:".</p>
${
firefox ?
`<p>Try "Copy Image" instead of "Copy Image Location".</p>` :
`<p>Try "Copy image" instead of "Copy image address".</p>`
}
`);
} else if (error.code === "html-not-image") {
$w.$main.html(`
<p>Address points to a web page, not an image file.</p>
<p>Try copying and pasting an image instead of a URL.</p>
`);
} else if (error.code === "decode-fail") {
$w.$main.html(`
<p>Address doesn't point to an image file of a supported format.</p>
<p>Try copying and pasting an image instead of a URL.</p>
`);
} else {
$w.$main.html(`
<p>Failed to load image from URL.</p>
<p>Check your browser's devtools for details.</p>
`);
}
$w.$main.css({maxWidth: "500px"});
$w.$Button("OK", () => {
$w.close();
});
$w.center();
}
let $about_paint_window;
const $about_paint_content = $("#about-paint");
let $news_window;
const $this_version_news = $("#news");
let $latest_news = $this_version_news;
// not included directly in the HTML as a simple way of not showing it if it's loaded with fetch
// (...not sure how to phrase this clearly and concisely...)
// "Showing the news as of this version of JS Paint. For the latest, see <a href='https://jspaint.app'>jspaint.app</a>"
if (location.origin !== "https://jspaint.app") {
$this_version_news.prepend(
$("<p>For the latest news, visit <a href='https://jspaint.app'>jspaint.app</a></p>")
.css({padding: "8px 15px"})
);
}
function show_about_paint(){
if($about_paint_window){
$about_paint_window.close();
}
$about_paint_window = $ToolWindow().title("About Paint");
if (is_pride_month) {
$("#paint-32x32").attr("src", "./images/icons/gay-es-paint-32x32-light-outline.png");
}
$about_paint_window.$content.append($about_paint_content.show()).css({padding: "15px"});
$("#maybe-outdated-view-project-news").removeAttr("hidden");
$("#failed-to-check-if-outdated").attr("hidden", "hidden");
$("#outdated").attr("hidden", "hidden");
$about_paint_window.center();
$about_paint_window.center(); // @XXX - but it helps tho
$("#refresh-to-update").on("click", (event)=> {
event.preventDefault();
location.reload();
});
$("#view-project-news").on("click", ()=> {
show_news();
});
$("#checking-for-updates").removeAttr("hidden");
const url =
// ".";
// "test-news-newer.html";
"https://jspaint.app";
fetch(url)
.then((response)=> response.text())
.then((text)=> {
const parser = new DOMParser();
const htmlDoc = parser.parseFromString(text, "text/html");
$latest_news = $(htmlDoc).find("#news");
const $latest_entries = $latest_news.find(".news-entry");
const $this_version_entries = $this_version_news.find(".news-entry");
if (!$latest_entries.length) {
$latest_news = $this_version_news;
throw new Error(`No news found at fetched site (${url})`);
}
function entries_contains_update($entries, id) {
return $entries.get().some((el_from_this_version)=>
id === el_from_this_version.id
);
}
// @TODO: visibly mark entries that overlap
entries_newer_than_this_version =
$latest_entries.get().filter((el_from_latest)=>
!entries_contains_update($this_version_entries, el_from_latest.id)
);
entries_new_in_this_version = // i.e. in development, when updating the news
$this_version_entries.get().filter((el_from_latest)=>
!entries_contains_update($latest_entries, el_from_latest.id)
);
if (entries_newer_than_this_version.length > 0) {
$("#outdated").removeAttr("hidden");
} else if(entries_new_in_this_version.length > 0) {
$latest_news = $this_version_news; // show this version's news for development
}
$("#checking-for-updates").attr("hidden", "hidden");
update_css_classes_for_conditional_messages();
}).catch((exception)=> {
$("#failed-to-check-if-outdated").removeAttr("hidden");
$("#checking-for-updates").attr("hidden", "hidden");
update_css_classes_for_conditional_messages();
window.console && console.log("Couldn't check for updates.", exception);
});
}
// show_about_paint(); // for testing
function update_css_classes_for_conditional_messages() {
$(".on-dev-host, .on-third-party-host, .on-official-host").hide();
if (location.hostname.match(/localhost|127.0.0.1/)) {
$(".on-dev-host").show();
} else if (location.hostname.match(/jspaint.app/)) {
$(".on-official-host").show();
} else {
$(".on-third-party-host").show();
}
$(".navigator-online, .navigator-offline").hide();
if (navigator.onLine) {
$(".navigator-online").show();
} else {
$(".navigator-offline").show();
}
}
function show_news(){
if($news_window){
$news_window.close();
}