-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
Copy pathInputWaiter.mjs
1448 lines (1272 loc) · 46.6 KB
/
InputWaiter.mjs
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
/**
* @author n1474335 [[email protected]]
* @author j433866 [[email protected]]
* @copyright Crown Copyright 2016
* @license Apache-2.0
*/
import LoaderWorker from "worker-loader?inline=no-fallback!../workers/LoaderWorker.js";
import InputWorker from "worker-loader?inline=no-fallback!../workers/InputWorker.mjs";
import Utils, { debounce } from "../../core/Utils.mjs";
import { toBase64 } from "../../core/lib/Base64.mjs";
import { isImage } from "../../core/lib/FileType.mjs";
/**
* Waiter to handle events related to the input.
*/
class InputWaiter {
/**
* InputWaiter constructor.
*
* @param {App} app - The main view object for CyberChef.
* @param {Manager} manager - The CyberChef event manager.
*/
constructor(app, manager) {
this.app = app;
this.manager = manager;
// Define keys that don't change the input so we don't have to autobake when they are pressed
this.badKeys = [
16, // Shift
17, // Ctrl
18, // Alt
19, // Pause
20, // Caps
27, // Esc
33, 34, 35, 36, // PgUp, PgDn, End, Home
37, 38, 39, 40, // Directional
44, // PrntScrn
91, 92, // Win
93, // Context
112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, // F1-12
144, // Num
145, // Scroll
];
this.inputWorker = null;
this.loaderWorkers = [];
this.workerId = 0;
this.maxTabs = this.manager.tabs.calcMaxTabs();
this.callbacks = {};
this.callbackID = 0;
this.maxWorkers = 1;
if (navigator.hardwareConcurrency !== undefined &&
navigator.hardwareConcurrency > 1) {
// Subtract 1 from hardwareConcurrency value to avoid using
// the entire available resources
this.maxWorkers = navigator.hardwareConcurrency - 1;
}
}
/**
* Calculates the maximum number of tabs to display
*/
calcMaxTabs() {
const numTabs = this.manager.tabs.calcMaxTabs();
if (this.inputWorker && this.maxTabs !== numTabs) {
this.maxTabs = numTabs;
this.inputWorker.postMessage({
action: "updateMaxTabs",
data: {
maxTabs: numTabs,
activeTab: this.manager.tabs.getActiveInputTab()
}
});
}
}
/**
* Terminates any existing workers and sets up a new InputWorker and LoaderWorker
*/
setupInputWorker() {
if (this.inputWorker !== null) {
this.inputWorker.terminate();
this.inputWorker = null;
}
for (let i = this.loaderWorkers.length - 1; i >= 0; i--) {
this.removeLoaderWorker(this.loaderWorkers[i]);
}
log.debug("Adding new InputWorker");
this.inputWorker = new InputWorker();
this.inputWorker.postMessage({
action: "updateMaxWorkers",
data: this.maxWorkers
});
this.inputWorker.postMessage({
action: "updateMaxTabs",
data: {
maxTabs: this.maxTabs,
activeTab: this.manager.tabs.getActiveInputTab()
}
});
this.inputWorker.postMessage({
action: "setLogLevel",
data: log.getLevel()
});
this.inputWorker.addEventListener("message", this.handleInputWorkerMessage.bind(this));
}
/**
* Activates a loaderWorker and sends it to the InputWorker
*/
activateLoaderWorker() {
const workerIdx = this.addLoaderWorker();
if (workerIdx === -1) return;
const workerObj = this.loaderWorkers[workerIdx];
this.inputWorker.postMessage({
action: "loaderWorkerReady",
data: {
id: workerObj.id
}
});
}
/**
* Adds a new loaderWorker
*
* @returns {number} - The index of the created worker
*/
addLoaderWorker() {
if (this.loaderWorkers.length === this.maxWorkers) {
return -1;
}
log.debug("Adding new LoaderWorker.");
const newWorker = new LoaderWorker();
const workerId = this.workerId++;
newWorker.addEventListener("message", this.handleLoaderMessage.bind(this));
newWorker.postMessage({id: workerId});
const newWorkerObj = {
worker: newWorker,
id: workerId
};
this.loaderWorkers.push(newWorkerObj);
return this.loaderWorkers.indexOf(newWorkerObj);
}
/**
* Removes a loaderworker
*
* @param {Object} workerObj - Object containing the loaderWorker and its id
* @param {LoaderWorker} workerObj.worker - The actual loaderWorker
* @param {number} workerObj.id - The ID of the loaderWorker
*/
removeLoaderWorker(workerObj) {
const idx = this.loaderWorkers.indexOf(workerObj);
if (idx === -1) {
return;
}
log.debug(`Terminating worker ${this.loaderWorkers[idx].id}`);
this.loaderWorkers[idx].worker.terminate();
this.loaderWorkers.splice(idx, 1);
}
/**
* Finds and returns the object for the loaderWorker of a given id
*
* @param {number} id - The ID of the loaderWorker to find
* @returns {object}
*/
getLoaderWorker(id) {
const idx = this.getLoaderWorkerIndex(id);
if (idx === -1) return;
return this.loaderWorkers[idx];
}
/**
* Gets the index for the loaderWorker of a given id
*
* @param {number} id - The ID of hte loaderWorker to find
* @returns {number} The current index of the loaderWorker in the array
*/
getLoaderWorkerIndex(id) {
for (let i = 0; i < this.loaderWorkers.length; i++) {
if (this.loaderWorkers[i].id === id) {
return i;
}
}
return -1;
}
/**
* Sends an input to be loaded to the loaderWorker
*
* @param {object} inputData - Object containing the input to be loaded
* @param {File} inputData.file - The actual file object to load
* @param {number} inputData.inputNum - The inputNum for the file object
* @param {number} inputData.workerId - The ID of the loaderWorker that will load it
*/
loadInput(inputData) {
const idx = this.getLoaderWorkerIndex(inputData.workerId);
if (idx === -1) return;
this.loaderWorkers[idx].worker.postMessage({
file: inputData.file,
inputNum: inputData.inputNum
});
}
/**
* Handler for messages sent back by the loaderWorker
* Sends the message straight to the inputWorker to be handled there.
*
* @param {MessageEvent} e
*/
handleLoaderMessage(e) {
const r = e.data;
if (Object.prototype.hasOwnProperty.call(r, "progress") &&
Object.prototype.hasOwnProperty.call(r, "inputNum")) {
this.manager.tabs.updateInputTabProgress(r.inputNum, r.progress, 100);
}
const transferable = Object.prototype.hasOwnProperty.call(r, "fileBuffer") ? [r.fileBuffer] : undefined;
this.inputWorker.postMessage({
action: "loaderWorkerMessage",
data: r
}, transferable);
}
/**
* Handler for messages sent back by the inputWorker
*
* @param {MessageEvent} e
*/
handleInputWorkerMessage(e) {
const r = e.data;
if (!("action" in r)) {
log.error("A message was received from the InputWorker with no action property. Ignoring message.");
return;
}
log.debug(`Receiving ${r.action} from InputWorker.`);
switch (r.action) {
case "activateLoaderWorker":
this.activateLoaderWorker();
break;
case "loadInput":
this.loadInput(r.data);
break;
case "terminateLoaderWorker":
this.removeLoaderWorker(this.getLoaderWorker(r.data));
break;
case "refreshTabs":
this.refreshTabs(r.data.nums, r.data.activeTab, r.data.tabsLeft, r.data.tabsRight);
break;
case "changeTab":
this.changeTab(r.data, this.app.options.syncTabs);
break;
case "updateTabHeader":
this.manager.tabs.updateInputTabHeader(r.data.inputNum, r.data.input);
break;
case "loadingInfo":
this.showLoadingInfo(r.data, true);
break;
case "setInput":
debounce(this.set, 50, "setInput", this, [r.data.inputObj, r.data.silent])();
break;
case "inputAdded":
this.inputAdded(r.data.changeTab, r.data.inputNum);
break;
case "queueInput":
this.manager.worker.queueInput(r.data);
break;
case "queueInputError":
this.manager.worker.queueInputError(r.data);
break;
case "bakeAllInputs":
this.manager.worker.bakeAllInputs(r.data);
break;
case "displayTabSearchResults":
this.displayTabSearchResults(r.data);
break;
case "filterTabError":
this.app.handleError(r.data);
break;
case "setUrl":
this.setUrl(r.data);
break;
case "inputSwitch":
this.manager.output.inputSwitch(r.data);
break;
case "getInput":
case "getInputNums":
this.callbacks[r.data.id](r.data);
break;
case "removeChefWorker":
this.removeChefWorker();
break;
case "fileLoaded":
this.fileLoaded(r.data.inputNum);
break;
default:
log.error(`Unknown action ${r.action}.`);
}
}
/**
* Sends a message to the inputWorker to bake all inputs
*/
bakeAll() {
this.app.progress = 0;
debounce(this.manager.controls.toggleBakeButtonFunction, 20, "toggleBakeButton", this, ["loading"]);
this.inputWorker.postMessage({
action: "bakeAll"
});
}
/**
* Sets the input in the input area
*
* @param {object} inputData - Object containing the input and its metadata
* @param {number} inputData.inputNum - The unique inputNum for the selected input
* @param {string | object} inputData.input - The actual input data
* @param {string} inputData.name - The name of the input file
* @param {number} inputData.size - The size in bytes of the input file
* @param {string} inputData.type - The MIME type of the input file
* @param {number} inputData.progress - The load progress of the input file
* @param {boolean} [silent=false] - If false, fires the manager statechange event
*/
async set(inputData, silent=false) {
return new Promise(function(resolve, reject) {
const activeTab = this.manager.tabs.getActiveInputTab();
if (inputData.inputNum !== activeTab) return;
const inputText = document.getElementById("input-text");
if (typeof inputData.input === "string") {
inputText.value = inputData.input;
const fileOverlay = document.getElementById("input-file"),
fileName = document.getElementById("input-file-name"),
fileSize = document.getElementById("input-file-size"),
fileType = document.getElementById("input-file-type"),
fileLoaded = document.getElementById("input-file-loaded");
fileOverlay.style.display = "none";
fileName.textContent = "";
fileSize.textContent = "";
fileType.textContent = "";
fileLoaded.textContent = "";
inputText.style.overflow = "auto";
inputText.classList.remove("blur");
inputText.scroll(0, 0);
const lines = inputData.input.length < (this.app.options.ioDisplayThreshold * 1024) ?
inputData.input.count("\n") + 1 : null;
this.setInputInfo(inputData.input.length, lines);
// Set URL to current input
const inputStr = toBase64(inputData.input, "A-Za-z0-9+/");
if (inputStr.length > 0 && inputStr.length <= 68267) {
this.setUrl({
includeInput: true,
input: inputStr
});
}
if (!silent) window.dispatchEvent(this.manager.statechange);
} else {
this.setFile(inputData, silent);
}
}.bind(this));
}
/**
* Displays file details
*
* @param {object} inputData - Object containing the input and its metadata
* @param {number} inputData.inputNum - The unique inputNum for the selected input
* @param {string | object} inputData.input - The actual input data
* @param {string} inputData.name - The name of the input file
* @param {number} inputData.size - The size in bytes of the input file
* @param {string} inputData.type - The MIME type of the input file
* @param {number} inputData.progress - The load progress of the input file
* @param {boolean} [silent=true] - If false, fires the manager statechange event
*/
setFile(inputData, silent=true) {
const activeTab = this.manager.tabs.getActiveInputTab();
if (inputData.inputNum !== activeTab) return;
const fileOverlay = document.getElementById("input-file"),
fileName = document.getElementById("input-file-name"),
fileSize = document.getElementById("input-file-size"),
fileType = document.getElementById("input-file-type"),
fileLoaded = document.getElementById("input-file-loaded");
fileOverlay.style.display = "block";
fileName.textContent = inputData.name;
fileSize.textContent = inputData.size + " bytes";
fileType.textContent = inputData.type;
if (inputData.status === "error") {
fileLoaded.textContent = "Error";
fileLoaded.style.color = "#FF0000";
} else {
fileLoaded.style.color = "";
fileLoaded.textContent = inputData.progress + "%";
}
this.setInputInfo(inputData.size, null);
this.displayFilePreview(inputData);
if (!silent) window.dispatchEvent(this.manager.statechange);
}
/**
* Update file details when a file completes loading
*
* @param {number} inputNum - The inputNum of the input which has finished loading
*/
fileLoaded(inputNum) {
this.manager.tabs.updateInputTabProgress(inputNum, 100, 100);
const activeTab = this.manager.tabs.getActiveInputTab();
if (activeTab !== inputNum) return;
this.inputWorker.postMessage({
action: "setInput",
data: {
inputNum: inputNum,
silent: false
}
});
this.updateFileProgress(inputNum, 100);
}
/**
* Render the input thumbnail
*/
async renderFileThumb() {
const activeTab = this.manager.tabs.getActiveInputTab(),
input = await this.getInputValue(activeTab),
fileThumb = document.getElementById("input-file-thumbnail");
if (typeof input === "string" ||
!this.app.options.imagePreview) {
this.resetFileThumb();
return;
}
const inputArr = new Uint8Array(input),
type = isImage(inputArr);
if (type && type !== "image/tiff" && inputArr.byteLength <= 512000) {
// Most browsers don't support displaying TIFFs, so ignore them
// Don't render images over 512000 bytes
const blob = new Blob([inputArr], {type: type}),
url = URL.createObjectURL(blob);
fileThumb.src = url;
} else {
this.resetFileThumb();
}
}
/**
* Reset the input thumbnail to the default icon
*/
resetFileThumb() {
const fileThumb = document.getElementById("input-file-thumbnail");
fileThumb.src = require("../static/images/file-128x128.png").default;
}
/**
* Shows a chunk of the file in the input behind the file overlay
*
* @param {Object} inputData - Object containing the input data
* @param {number} inputData.inputNum - The inputNum of the file being displayed
* @param {ArrayBuffer} inputData.input - The actual input to display
*/
displayFilePreview(inputData) {
const activeTab = this.manager.tabs.getActiveInputTab(),
input = inputData.input,
inputText = document.getElementById("input-text");
if (inputData.inputNum !== activeTab) return;
inputText.style.overflow = "hidden";
inputText.classList.add("blur");
inputText.value = Utils.printable(Utils.arrayBufferToStr(input.slice(0, 4096)));
this.renderFileThumb();
}
/**
* Updates the displayed load progress for a file
*
* @param {number} inputNum
* @param {number | string} progress - Either a number or "error"
*/
updateFileProgress(inputNum, progress) {
const activeTab = this.manager.tabs.getActiveInputTab();
if (inputNum !== activeTab) return;
const fileLoaded = document.getElementById("input-file-loaded");
if (progress === "error") {
fileLoaded.textContent = "Error";
fileLoaded.style.color = "#FF0000";
} else {
fileLoaded.textContent = progress + "%";
fileLoaded.style.color = "";
}
}
/**
* Updates the stored value for the specified inputNum
*
* @param {number} inputNum
* @param {string | ArrayBuffer} value
* @param {boolean} [force=false] - If true, forces the value to be updated even if the type is different to the currently stored type
*/
updateInputValue(inputNum, value, force=false) {
let includeInput = false;
const recipeStr = toBase64(value, "A-Za-z0-9+/"); // B64 alphabet with no padding
if (recipeStr.length > 0 && recipeStr.length <= 68267) {
includeInput = true;
}
this.setUrl({
includeInput: includeInput,
input: recipeStr
});
// Value is either a string set by the input or an ArrayBuffer from a LoaderWorker,
// so is safe to use typeof === "string"
const transferable = (typeof value !== "string") ? [value] : undefined;
this.inputWorker.postMessage({
action: "updateInputValue",
data: {
inputNum: inputNum,
value: value,
force: force
}
}, transferable);
}
/**
* Updates the .data property for the input of the specified inputNum.
* Used for switching the output into the input
*
* @param {number} inputNum - The inputNum of the input we're changing
* @param {object} inputData - The new data object
*/
updateInputObj(inputNum, inputData) {
const transferable = (typeof inputData !== "string") ? [inputData.fileBuffer] : undefined;
this.inputWorker.postMessage({
action: "updateInputObj",
data: {
inputNum: inputNum,
data: inputData
}
}, transferable);
}
/**
* Get the input value for the specified input
*
* @param {number} inputNum - The inputNum of the input to retrieve from the inputWorker
* @returns {ArrayBuffer | string}
*/
async getInputValue(inputNum) {
return await new Promise(resolve => {
this.getInput(inputNum, false, r => {
resolve(r.data);
});
});
}
/**
* Get the input object for the specified input
*
* @param {number} inputNum - The inputNum of the input to retrieve from the inputWorker
* @returns {object}
*/
async getInputObj(inputNum) {
return await new Promise(resolve => {
this.getInput(inputNum, true, r => {
resolve(r.data);
});
});
}
/**
* Gets the specified input from the inputWorker
*
* @param {number} inputNum - The inputNum of the data to get
* @param {boolean} getObj - If true, get the actual data object of the input instead of just the value
* @param {Function} callback - The callback to execute when the input is returned
* @returns {ArrayBuffer | string | object}
*/
getInput(inputNum, getObj, callback) {
const id = this.callbackID++;
this.callbacks[id] = callback;
this.inputWorker.postMessage({
action: "getInput",
data: {
inputNum: inputNum,
getObj: getObj,
id: id
}
});
}
/**
* Gets the number of inputs from the inputWorker
*
* @returns {object}
*/
async getInputNums() {
return await new Promise(resolve => {
this.getNums(r => {
resolve(r);
});
});
}
/**
* Gets a list of inputNums from the inputWorker, and sends
* them back to the specified callback
*/
getNums(callback) {
const id = this.callbackID++;
this.callbacks[id] = callback;
this.inputWorker.postMessage({
action: "getInputNums",
data: id
});
}
/**
* Displays information about the input.
*
* @param {number} length - The length of the current input string
* @param {number} lines - The number of the lines in the current input string
*/
setInputInfo(length, lines) {
let width = length.toString().length.toLocaleString();
width = width < 2 ? 2 : width;
const lengthStr = length.toString().padStart(width, " ").replace(/ /g, " ");
let msg = "length: " + lengthStr;
if (typeof lines === "number") {
const linesStr = lines.toString().padStart(width, " ").replace(/ /g, " ");
msg += "<br>lines: " + linesStr;
}
document.getElementById("input-info").innerHTML = msg;
}
/**
* Handler for input change events.
* Debounces the input so we don't call autobake too often.
*
* @param {event} e
*/
debounceInputChange(e) {
debounce(this.inputChange, 50, "inputChange", this, [e])();
}
/**
* Handler for input change events.
* Updates the value stored in the inputWorker
*
* @param {event} e
*
* @fires Manager#statechange
*/
inputChange(e) {
// Ignore this function if the input is a file
const fileOverlay = document.getElementById("input-file");
if (fileOverlay.style.display === "block") return;
// Remove highlighting from input and output panes as the offsets might be different now
this.manager.highlighter.removeHighlights();
const textArea = document.getElementById("input-text");
const value = (textArea.value !== undefined) ? textArea.value : "";
const activeTab = this.manager.tabs.getActiveInputTab();
this.app.progress = 0;
const lines = value.length < (this.app.options.ioDisplayThreshold * 1024) ?
(value.count("\n") + 1) : null;
this.setInputInfo(value.length, lines);
this.updateInputValue(activeTab, value);
this.manager.tabs.updateInputTabHeader(activeTab, value.replace(/[\n\r]/g, "").slice(0, 100));
if (e && this.badKeys.indexOf(e.keyCode) < 0) {
// Fire the statechange event as the input has been modified
window.dispatchEvent(this.manager.statechange);
}
}
/**
* Handler for input paste events
* Checks that the size of the input is below the display limit, otherwise treats it as a file/blob
*
* @param {event} e
*/
async inputPaste(e) {
e.preventDefault();
e.stopPropagation();
const self = this;
/**
* Triggers the input file/binary data overlay
*
* @param {string} pastedData
*/
function triggerOverlay(pastedData) {
const file = new File([pastedData], "PastedData", {
type: "text/plain",
lastModified: Date.now()
});
self.loadUIFiles([file]);
}
const pastedData = e.clipboardData.getData("Text");
const inputText = document.getElementById("input-text");
const selStart = inputText.selectionStart;
const selEnd = inputText.selectionEnd;
const startVal = inputText.value.slice(0, selStart);
const endVal = inputText.value.slice(selEnd);
const val = startVal + pastedData + endVal;
if (val.length >= (this.app.options.ioDisplayThreshold * 1024)) {
// Data too large to display, use overlay
triggerOverlay(val);
return false;
} else if (await this.preserveCarriageReturns(val)) {
// Data contains a carriage return and the user doesn't wish to edit it, use overlay
// We check this in a separate condition to make sure it is not run unless absolutely
// necessary.
triggerOverlay(val);
return false;
} else {
// Pasting normally fires the inputChange() event before
// changing the value, so instead change it here ourselves
// and manually fire inputChange()
inputText.value = val;
inputText.setSelectionRange(selStart + pastedData.length, selStart + pastedData.length);
// Don't debounce here otherwise the keyup event for the Ctrl key will cancel an autobake
// (at least for large inputs)
this.inputChange(e, true);
}
}
/**
* Handler for input dragover events.
* Gives the user a visual cue to show that items can be dropped here.
*
* @param {event} e
*/
inputDragover(e) {
// This will be set if we're dragging an operation
if (e.dataTransfer.effectAllowed === "move")
return false;
e.stopPropagation();
e.preventDefault();
e.target.closest("#input-text,#input-file").classList.add("dropping-file");
}
/**
* Handler for input dragleave events.
* Removes the visual cue.
*
* @param {event} e
*/
inputDragleave(e) {
e.stopPropagation();
e.preventDefault();
e.target.closest("#input-text,#input-file").classList.remove("dropping-file");
}
/**
* Handler for input drop events.
* Loads the dragged data.
*
* @param {event} e
*/
inputDrop(e) {
// This will be set if we're dragging an operation
if (e.dataTransfer.effectAllowed === "move")
return false;
e.stopPropagation();
e.preventDefault();
const text = e.dataTransfer.getData("Text");
e.target.closest("#input-text,#input-file").classList.remove("dropping-file");
if (text) {
// Append the text to the current input and fire inputChange()
document.getElementById("input-text").value += text;
this.inputChange(e);
return;
}
if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
this.loadUIFiles(e.dataTransfer.files);
}
}
/**
* Handler for open input button events
* Loads the opened data into the input textarea
*
* @param {event} e
*/
inputOpen(e) {
e.preventDefault();
if (e.target.files.length > 0) {
this.loadUIFiles(e.target.files);
e.target.value = "";
}
}
/**
* Checks if an input contains carriage returns.
* If a CR is detected, checks if the preserve CR option has been set,
* and if not, asks the user for their preference.
*
* @param {string} input - The input to be checked
* @returns {boolean} - If true, the input contains a CR which should be
* preserved, so display an overlay so it can't be edited
*/
async preserveCarriageReturns(input) {
if (input.indexOf("\r") < 0) return false;
const optionsStr = "This behaviour can be changed in the <a href='#' onclick='document.getElementById(\"options\").click()'>Options pane</a>";
const preserveStr = `A carriage return (\\r, 0x0d) was detected in your input. To preserve it, editing has been disabled.<br>${optionsStr}`;
const dontPreserveStr = `A carriage return (\\r, 0x0d) was detected in your input. It has not been preserved.<br>${optionsStr}`;
switch (this.app.options.preserveCR) {
case "always":
this.app.alert(preserveStr, 6000);
return true;
case "never":
this.app.alert(dontPreserveStr, 6000);
return false;
}
// Only preserve for high-entropy inputs
const data = Utils.strToArrayBuffer(input);
const entropy = Utils.calculateShannonEntropy(data);
if (entropy > 6) {
this.app.alert(preserveStr, 6000);
return true;
}
this.app.alert(dontPreserveStr, 6000);
return false;
}
/**
* Load files from the UI into the inputWorker
*
* @param {FileList} files - The list of files to be loaded
*/
loadUIFiles(files) {
const numFiles = files.length;
const activeTab = this.manager.tabs.getActiveInputTab();
log.debug(`Loading ${numFiles} files.`);
// Display the number of files as pending so the user
// knows that we've received the files.
this.showLoadingInfo({
pending: numFiles,
loading: 0,
loaded: 0,
total: numFiles,
activeProgress: {
inputNum: activeTab,
progress: 0
}
}, false);
this.inputWorker.postMessage({
action: "loadUIFiles",
data: {
files: files,
activeTab: activeTab
}
});
}
/**
* Handler for open input button click.
* Opens the open file dialog.
*/
inputOpenClick() {
document.getElementById("open-file").click();
}
/**
* Handler for open folder button click
* Opens the open folder dialog.
*/
folderOpenClick() {
document.getElementById("open-folder").click();
}
/**
* Display the loaded files information in the input header.
* Also, sets the background of the Input header to be a progress bar
* @param {object} loadedData - Object containing the loading information
* @param {number} loadedData.pending - How many files are pending (not loading / loaded)
* @param {number} loadedData.loading - How many files are being loaded
* @param {number} loadedData.loaded - How many files have been loaded
* @param {number} loadedData.total - The total number of files
* @param {object} loadedData.activeProgress - Object containing data about the active tab
* @param {number} loadedData.activeProgress.inputNum - The inputNum of the input the progress is for
* @param {number} loadedData.activeProgress.progress - The loading progress of the active input
* @param {boolean} autoRefresh - If true, automatically refreshes the loading info by sending a message to the inputWorker after 100ms
*/
showLoadingInfo(loadedData, autoRefresh) {
const pending = loadedData.pending;
const loading = loadedData.loading;
const loaded = loadedData.loaded;
const total = loadedData.total;
let width = total.toLocaleString().length;
width = width < 2 ? 2 : width;
const totalStr = total.toLocaleString().padStart(width, " ").replace(/ /g, " ");
let msg = "total: " + totalStr;
const loadedStr = loaded.toLocaleString().padStart(width, " ").replace(/ /g, " ");
msg += "<br>loaded: " + loadedStr;
if (pending > 0) {
const pendingStr = pending.toLocaleString().padStart(width, " ").replace(/ /g, " ");
msg += "<br>pending: " + pendingStr;
} else if (loading > 0) {
const loadingStr = loading.toLocaleString().padStart(width, " ").replace(/ /g, " ");
msg += "<br>loading: " + loadingStr;
}
const inFiles = document.getElementById("input-files-info");
if (total > 1) {
inFiles.innerHTML = msg;
inFiles.style.display = "";
} else {
inFiles.style.display = "none";
}
this.updateFileProgress(loadedData.activeProgress.inputNum, loadedData.activeProgress.progress);
const inputTitle = document.getElementById("input").firstElementChild;
if (loaded < total) {
const percentComplete = loaded / total * 100;
inputTitle.style.background = `linear-gradient(to right, var(--title-background-colour) ${percentComplete}%, var(--primary-background-colour) ${percentComplete}%)`;
} else {
inputTitle.style.background = "";
}
if (loaded < total && autoRefresh) {
setTimeout(function() {
this.inputWorker.postMessage({
action: "getLoadProgress",
data: this.manager.tabs.getActiveInputTab()
});
}.bind(this), 100);
}
}
/**
* Change to a different tab.
*
* @param {number} inputNum - The inputNum of the tab to change to
* @param {boolean} [changeOutput=false] - If true, also changes the output