-
Notifications
You must be signed in to change notification settings - Fork 117
/
script.js
2815 lines (2616 loc) · 109 KB
/
script.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
/* Only used when debugging:
window.onerror = (msg, url, line, column, error) => {
const message = {
message: msg,
url: url,
line: line,
column: column,
error: JSON.stringify(error)
}
if (window.webkit) {
window.webkit.messageHandlers.aShell.postMessage('JS Error:' + msg + ' message: ' + error.message + ' stack: ' + error.stack + '\n');
} else {
console.log("Error:", message);
}
};
*/
//
// functions to deal with executeJavaScript:
function print(printString) {
window.webkit.messageHandlers.aShell.postMessage('print:' + printString);
}
function println(printString) {
window.webkit.messageHandlers.aShell.postMessage('print:' + printString + '\n');
}
function print_error(printString) {
window.webkit.messageHandlers.aShell.postMessage('print_error:' + printString);
}
function luminance(color) {
var colorArray = lib.colors.crackRGB(color);
return colorArray[0] * 0.2126 + colorArray[1] * 0.7152 + colorArray[2] * 0.0722;
}
function initContent(io) {
const ver = lib.resource.getData('libdot/changelog/version');
const date = lib.resource.getData('libdot/changelog/date');
const pkg = `libdot ${ver} (${date})`;
};
function isInteractive(commandString) {
// If the command is interactive or contains interactive commands, set the flag,
// forward all keyboard input, let them deal with command history.
// Commands that call CPR (Cursor Position Request) are not in the list because we detect them separately
// (vim, ipython, ptpython, jupyter-console...) (see hterm.VT.CSI['n'])
// ssh and ssh-keygen (new version) are both interactive. So is scp. sftp is interactive until connected.
// vim is back on the list because it can be called by the Files app, and we have initialization issues.
let interactiveRegexp = /^less|^more|^vim|^ssh|^scp|^sftp|\|&? *less|\|&? *more|^man|^pico/;
return interactiveRegexp.test(commandString)
// It's easier to match a regexp, then take the negation than to test a regexp that does not contain a pattern:
// This is disabled for now, but kept in case it can become useful again.
// let notInteractiveRegexp = /^ssh-keygen/;
// return interactiveRegexp.test(commandString) && !notInteractiveRegexp.test(commandString);
}
// standard functions (terminal, autocomplete, etc)
var lastDirectory = '';
var lastOnlyDirectories = false;
var fileList = [];
var currentCommandCursorPosition;
var autocompleteList = [];
var autocompleteOn = false;
var autocompleteIndex = 0;
function disableAutocompleteMenu() {
printString('');
autocompleteOn = false;
autocompleteList = [];
autocompleteIndex = 0;
fileList = '';
lastDirectory = '';
lastOnlyDirectories = false;
}
function cleanupLastLine() {
// console.log("Before: " + window.printedContent);
// Clean up the last line (it can contain a lot of control characters, up arrow, down arrow, etc):
var lastNewline = window.printedContent.lastIndexOf("\n");
var lastLine = window.printedContent.substr(lastNewline +1 ); // skip past before-last \n
window.printedContent = window.printedContent.substr(0, lastNewline); // remove last \n
var emptyLastLine = false;
if (lastLine.length == 0) {
emptyLastLine = true;
lastNewline = window.printedContent.lastIndexOf("\n");
lastLine = window.printedContent.substr(lastNewline +1 ); // skip past before-last \n
window.printedContent = window.printedContent.substr(0, lastNewline); // remove last line
}
// console.log("Last line, before : " + lastLine);
if (window.commandRunning == '') {
lastLine = "\n\r\x1b[0m\x1b[39;49m" + window.promptMessage + window.term_.io.currentCommand ;
} else {
// promptMessage has been set in updatePromptPosition
lastLine = window.promptMessage + window.term_.io.currentCommand ;
}
// console.log("Last line, after : " + lastLine);
// This needs thinking. There's a "\n" missing after that.
window.printedContent += lastLine;
if (emptyLastLine) {
window.printedContent += '\r\n';
}
// console.log("After: " + window.printedContent);
}
function isLetter(c) {
// TODO: extension for CJK characters (hard)
return (c.toLowerCase() != c.toUpperCase());
}
// Required because printedContent now arrives after the first prompt has been printed.
function setWindowContent(string) {
window.term_.wipeContents();
window.printedContent = '';
window.term_.io.print(string);
printPrompt();
io.currentCommand = '';
}
function printPrompt() {
// prints the prompt and initializes all variables related to prompt position
window.term_.io.print('\x1b[0m\x1b[39;49m'); // default font, default color
// cut window.printedContent if it gets too large:
if (window.printedContent.length > 30000) {
window.printedContent = window.printedContent.substring(5000);
}
if (window.commandRunning == '') {
window.term_.io.print(window.promptMessage);
window.commandRunning = '';
window.term_.io.currentCommand = '';
window.interactiveCommandRunning = false;
window.term_.reportFocus = false; // That was causing ^[[I sometimes
} else {
window.webkit.messageHandlers.aShell.postMessage('input:' + '\n');
}
}
function updatePromptPosition() {
window.promptEnd = window.term_.screen_.cursorPosition.column;
var lastNewline = window.printedContent.lastIndexOf("\r");
var lastLine = window.printedContent.substr(lastNewline +1 ); // skip past last \n
if (lastLine.length == 0) {
lastNewline = window.printedContent.lastIndexOf("\n");
lastLine = window.printedContent.substr(lastNewline +1 );
}
if ((lastLine.length == 1) && ((lastLine[0] == '\n') || (lastLine[0] == '\r'))) {
lastLine = '';
} else if (window.commandRunning != '') {
window.promptMessage = lastLine; // store current command prompt message.
}
// required because some commands can take several lines, especially on a phone.
window.promptLine = window.term_.screen_.cursorPosition.row;
window.promptScroll = window.term_.scrollPort_.getTopRowIndex();
currentCommandCursorPosition = 0;
}
// returns the actual width, on screen, of a string, including with emojis.
// This is different from lib.wc.strWidth, which returns the length in characters.
// A family emoji has strWidth = 8, screenWidth = 2
function screenWidth(str) {
let rv = 0;
let afterJoiner = false;
let isModifier = false;
// modifiers (skin color) are *after* the emoji they change, zero-width-joiners are *between* two emojis.
for (let i = 0; i < str.length;) {
const codePoint = str.codePointAt(i);
const charAtCodePoint = String.fromCodePoint(codePoint);
isModifier = (charAtCodePoint.match(/\p{Emoji_Modifier}/gu) != null);
const width = lib.wc.charWidth(codePoint);
if (width < 0) {
return -1;
}
if ((!afterJoiner) && (!isModifier)) {
rv += width;
}
afterJoiner = (codePoint == 8205);
i += (codePoint <= 0xffff) ? 1 : 2;
}
return rv;
}
// prints a string and move the rest of the command around, even if it is over multiple lines
// we use lib.wc.strWidth instead of length because of multiple-width characters (CJK, mostly).
// TODO: get correct character width for emojis.
function printString(string) {
var l = lib.wc.strWidth(string);
var currentCommand = window.term_.io.currentCommand;
// clear the rest of the line, then reprint.
window.term_.io.print('\x1b[0J'); // delete display after cursor
window.term_.io.print(string);
// print remainder of command line
window.term_.io.print(currentCommand.slice(currentCommandCursorPosition, currentCommand.length));
// move cursor back to where it was (don't use term.screen_.cursorPosition):
var endOfCommand = currentCommand.slice(currentCommandCursorPosition, currentCommand.length);
var endOfCommandWidth = lib.wc.strWidth(endOfCommand);
if ((lib.wc.strWidth(currentCommand) + lib.wc.strWidth(window.promptMessage) + 1 >= window.term_.screenSize.width) && (endOfCommandWidth == 0)) {
window.term_.io.print(' ');
endOfCommandWidth = 1;
}
// window.term_.io.print has issues (known) when a wide char crosses the end of line. Annoying.
for (var i = 0; i < endOfCommandWidth; i++) {
window.term_.io.print('\b');
}
}
// prints a string for autocomplete and move the rest of the command around, even if it is over multiple lines.
// keep the command as it is until autocomplete has been accepted.
function printAutocompleteString(string) {
var currentCommand = window.term_.io.currentCommand;
// clear entire buffer, then reprint
window.term_.io.print('\x1b[0J'); // delete display after cursor
if (luminance(window.term_.getBackgroundColor()) < luminance(window.term_.getForegroundColor())) {
// We are in dark mode. Use yellow font for higher contrast
window.term_.io.print('\x1b[33m'); // yellow
} else {
window.term_.io.print('\x1b[32m'); // green
}
window.term_.io.print(string);
window.term_.io.print('\x1b[39m'); // back to normal foreground color
// print remainder of command line
window.term_.io.print(currentCommand.slice(currentCommandCursorPosition, currentCommand.length))
// move cursor back to where it was (don't use term.screen_.cursorPosition):
// don't use length because of multiple-byte chars.
var endOfCommand = currentCommand.slice(currentCommandCursorPosition, currentCommand.length);
var wcwidth = lib.wc.strWidth(endOfCommand) + lib.wc.strWidth(string);
for (var i = 0; i < wcwidth; i++) {
window.term_.io.print('\b');
}
}
// behaves as if delete key is pressed.
function deleteBackward() {
if (currentCommandCursorPosition <= 0) {
return;
}
var previousCursorPosition = 0;
var currentChar;
for (const v of window.term_.io.currentCommand) {
if (previousCursorPosition + v.length >= currentCommandCursorPosition) {
currentChar = v;
break;
}
previousCursorPosition += v.length;
}
const currentCharWidth = lib.wc.strWidth(currentChar);
for (let i = 0; i < currentCharWidth; i++) {
window.term_.io.print('\b'); // move cursor back n chars, across lines
}
window.term_.io.print('\x1b[0J'); // delete display after cursor
// print remainder of command line
const endOfCommand = window.term_.io.currentCommand.slice(currentCommandCursorPosition);
window.term_.io.print(endOfCommand);
// move cursor back to where it was (don't use term.screen_.cursorPosition):
const wcwidth = lib.wc.strWidth(endOfCommand);
for (let i = 0; i < wcwidth; i++) {
window.term_.io.print('\b');
}
// remove character from command at current position:
window.term_.io.currentCommand = window.term_.io.currentCommand.slice(0, previousCursorPosition) + endOfCommand;
currentCommandCursorPosition = previousCursorPosition;
}
function pickCurrentValue() {
var currentCommand = window.term_.io.currentCommand;
var cursorPosition = window.term_.screen_.cursorPosition.column - window.promptEnd;
selected = autocompleteList[autocompleteIndex];
printString(selected);
window.term_.io.currentCommand = currentCommand.slice(0, currentCommandCursorPosition) + selected +
currentCommand.slice(currentCommandCursorPosition, currentCommand.length);
// is not enough to push the rest of the command if it's longer than a line
currentCommandCursorPosition += selected.length;
disableAutocompleteMenu();
}
// called once the list of files has been updated, asynchronously.
function updateFileMenu() {
var cursorPosition = window.term_.screen_.cursorPosition.column - window.promptEnd;
updateAutocompleteMenu(window.term_.io, cursorPosition);
}
function updateAutocompleteMenu(io, cursorPosition) {
var lastFound = '';
// string to use for research: from beginning of line to cursor position
var rootForMatch = io.currentCommand.slice(0, currentCommandCursorPosition);
var predicate = rootForMatch;
var n = predicate.lastIndexOf("|");
var lastPipePosition = 0;
if (n < predicate.length) {
lastPipePosition = n + 1;
predicate = predicate.substr(n + 1);
}
n = predicate.lastIndexOf(" ");
while ((n > 0) && (predicate[n-1] == "\\")) {
// escaped space
n = predicate.lastIndexOf(" ", n - 1);
}
if (n < predicate.length) {
predicate = predicate.substr(n + 1);
}
n = predicate.lastIndexOf(">");
if (n < predicate.length) {
predicate = predicate.substr(n + 1);
}
if (predicate[0] == '-') return; // arguments to function, no autocomplete
// we have the string to use for matching (predicate). Is it a file or a command?
var beforePredicate = rootForMatch.substr(0, rootForMatch.lastIndexOf(predicate));
// remove all trailing spaces:
while ((beforePredicate.length > 0) && (beforePredicate.slice(-1) == " ")) {
beforePredicate = beforePredicate.slice(0, beforePredicate.length - 1)
}
autocompleteIndex = 0;
autocompleteList = [];
var numFound = 0;
var matchToCommands = false;
var listDirectories = false;
var matchingWithZ = false;
if (beforePredicate.length == 0) {
matchToCommands = true; // beginning of line, must be a command
} else if (beforePredicate.slice(-1) == "|") {
matchToCommands = true; // right after a pipe, must be a command
}
// Now extract the command after the pipe:
var beforePredicate = rootForMatch.substr(lastPipePosition, rootForMatch.lastIndexOf(predicate));
// remove all trailing spaces:
while ((beforePredicate.length > 0) && (beforePredicate.slice(-1) == " ")) {
beforePredicate = beforePredicate.slice(0, beforePredicate.length - 1)
}
// remove all beginning spaces:
while ((beforePredicate.length > 0) && (beforePredicate[0] == " ")) {
beforePredicate = beforePredicate.slice(1)
}
if (beforePredicate === "cd") {
listDirectories = true;
} else if (beforePredicate === "z") {
// Specific action for z + tab. *Very* specific.
if (fileList.length == 0) {
window.webkit.messageHandlers.aShell.postMessage('listDirectoriesForZ:' + predicate);
return;
} else {
// Erase the "z" command (to the start of beforePredicate), replace with "cd"
const wcwidth = lib.wc.strWidth(predicate);
for (let i = 0; i < wcwidth; i++) {
deleteBackward()
}
var toDelete = window.term_.io.currentCommand.lastIndexOf("z");
var toDeleteStr = window.term_.io.currentCommand.slice(toDelete);
const wcwidth2 = lib.wc.strWidth(toDeleteStr);
for (let i = 0; i < wcwidth2; i++) {
deleteBackward()
}
printString("cd ");
io.currentCommand = io.currentCommand.slice(0, currentCommandCursorPosition) + "cd " +
io.currentCommand.slice(currentCommandCursorPosition, io.currentCommand.length);
currentCommandCursorPosition += "cd ".length;
if (fileList.length == 1) {
// only one solution: print it
printString(fileList[0]);
io.currentCommand = io.currentCommand.slice(0, currentCommandCursorPosition) + fileList[0] +
io.currentCommand.slice(currentCommandCursorPosition, io.currentCommand.length);
currentCommandCursorPosition += fileList[0].length;
autocompleteOn = false;
return
} else {
// multiple solutions, print all:
for (var i = 0, len = fileList.length; i < len; i++) {
autocompleteList[numFound] = fileList[i];
lastFound = value;
numFound += 1;
}
autocompleteOn = true;
autocompleteIndex = 0;
printAutocompleteString(autocompleteList[autocompleteIndex]);
return;
}
}
return;
}
// otherwise, it's probably a file
var file = '';
var directory = '.';
// Compute list of files from current directory:
if ((predicate[0] == "~") && (predicate.lastIndexOf("/") == -1)) {
// string beginning with ~, with no / at the end: it's a bookmark.
directory = '';
file = predicate;
// recompute if the directory listed has changed, or if we now want files instead of directories:
if ((lastDirectory != '~bookmarkNames') || (lastOnlyDirectories != listDirectories)) {
// asynchronous communication. Will have to execute the rest of the command too.
if (listDirectories) {
window.webkit.messageHandlers.aShell.postMessage('listBookmarksDir:');
} else {
window.webkit.messageHandlers.aShell.postMessage('listBookmarks:');
}
}
} else {
// compute list of files from local directory
var lastSlash = predicate.lastIndexOf("/");
if ((predicate.length > 0) && (lastSlash > 0) && (lastSlash < predicate.length)) {
var directory = predicate.substr(0, lastSlash); // include "/" in directory
file = predicate.substr(lastSlash + 1); // don't include "/" in file name
} else {
directory = ".";
file = predicate;
}
// recompute if the directory listed has changed, or if we now want files instead of directories:
if ((directory != lastDirectory) || (lastOnlyDirectories != listDirectories)){
// asynchronous communication. Will have to execute the rest of the command too.
if (listDirectories) {
// Only directories, include bookmarks for directories
window.webkit.messageHandlers.aShell.postMessage('listDirectoryDir:' + directory);
} else {
window.webkit.messageHandlers.aShell.postMessage('listDirectory:' + directory);
}
}
}
if (matchToCommands) {
// First, match command with history:
for (var i = 0 , len = window.commandArray.length; i < len ; i++) {
if (window.commandArray[i].startsWith(predicate)) {
var value = window.commandArray[i].replace(predicate, "");
autocompleteList[numFound] = value;
lastFound = value;
numFound += 1;
}
}
// only keep the last version of the command from history:
unique = autocompleteList.filter((v,i,a) => a.lastIndexOf(v) == i);
autocompleteList = unique;
// Stop on latest command matching, up = history, down = commands.
numFound = autocompleteList.length;
if (numFound > 0) {
autocompleteIndex = autocompleteList.length - 1;
}
for (var i = 0, len = commandList.length; i < len; i++) {
if (commandList[i].startsWith(predicate)) {
var value = commandList[i].replace(predicate, "") + ' '; // add a space at the end if it's a command;
autocompleteList[numFound] = value;
lastFound = value;
numFound += 1;
}
}
}
// Then add list of files from local directory:
if ((predicate[0] == "~") && (predicate.lastIndexOf("/") == -1)) {
// string beginning with ~, with no / at the end: it's a bookmark.
directory = '';
file = predicate;
if (lastDirectory == '~bookmarkNames') {
// First, remove predicate from the autocomplete list:
for (var i = 0, len = fileList.length; i < len; i++) {
if (fileList[i].startsWith(file)) {
var value = fileList[i].replace(file, "")
autocompleteList[numFound] = value;
lastFound = value;
numFound += 1;
}
}
}
} else {
if ((predicate[0] == "/") && (predicate.lastIndexOf("/") == 0)) {
// special case for root
directory = "/";
file = predicate.substr(1);
// This will only work for shortcuts expansion:
} else {
var lastSlash = predicate.lastIndexOf("/");
if ((predicate.length > 0) && (lastSlash > 0) && (lastSlash < predicate.length)) {
var directory = predicate.substr(0, lastSlash); // include "/" in directory
file = predicate.substr(lastSlash + 1); // don't include "/" in file name
} else {
directory = ".";
file = predicate;
}
}
// Need to get list of files from directory.
if ((directory == lastDirectory) && (lastOnlyDirectories == listDirectories)) {
// First, remove
for (var i = 0, len = fileList.length; i < len; i++) {
if (fileList[i].startsWith(file)) {
var value = fileList[i].replace(file, "")
autocompleteList[numFound] = value;
lastFound = value;
numFound += 1;
}
}
}
}
// substring of io.currentCommand, ending at currentCommandCursorPosition, going back until first space or "/"
// list to use for autocomplete = commandList if at beginning of line (modulo spaces) or after | (module spaces)
// list of files inside directory otherwise. e.g. "../Library/Preferences/" (going back until next space)
// TODO: no autocomplete on file for commands that don't operate on files (difficult)
if (numFound > 1) {
// If list is not empty:
// Find largest starting substring:
if (((directory == lastDirectory) && (lastOnlyDirectories == listDirectories))
|| ((lastDirectory == '~bookmarkNames') && (predicate[0] == "~") && (lastOnlyDirectories == listDirectories))) {
var commonSubstring = ''
for (var l = 1; l < autocompleteList[0].length; l++) {
substring = autocompleteList[0].substr(0, l)
var contained = true
for (var i = 0, len = autocompleteList.length; i < len; i++) {
if (!autocompleteList[i].startsWith(substring)) {
contained = false;
break;
}
}
if (contained) {
commonSubstring = substring;
} else {
break;
}
}
if (commonSubstring.length > 0) {
printString(commonSubstring);
io.currentCommand = io.currentCommand.slice(0, currentCommandCursorPosition) + commonSubstring +
io.currentCommand.slice(currentCommandCursorPosition, io.currentCommand.length);
currentCommandCursorPosition += commonSubstring.length;
for (var i = 0, len = autocompleteList.length; i < len; i++) {
var value = autocompleteList[i].replace(commonSubstring, "")
autocompleteList[i] = value;
}
}
//
autocompleteOn = true;
// Don't display files starting with "." first (they're in the list, but we don't start with them)
// Don't do this with directories because we already sorted them
if ((file.length == 0) && (!listDirectories)) {
while ((autocompleteList[autocompleteIndex][0] == ".") && (autocompleteIndex < autocompleteList.length - 1)) {
autocompleteIndex += 1;
}
if (autocompleteIndex == autocompleteList.length - 1) {
// directory with only ".*" files
autocompleteIndex = 0;
}
}
printAutocompleteString(autocompleteList[autocompleteIndex]);
}
} else {
if (numFound == 1) {
if (((directory == lastDirectory) && (lastOnlyDirectories == listDirectories))
|| ((lastDirectory == '~bookmarkNames') && (predicate[0] == "~") && (lastOnlyDirectories == listDirectories))) {
printString(lastFound);
io.currentCommand = io.currentCommand.slice(0, currentCommandCursorPosition) + lastFound +
io.currentCommand.slice(currentCommandCursorPosition, io.currentCommand.length);
currentCommandCursorPosition += lastFound.length;
}
}
autocompleteOn = false;
disableAutocompleteMenu();
}
}
function setupHterm() {
const term = new hterm.Terminal();
// Default monospaced fonts installed: Menlo and Courier.
term.prefs_.set('cursor-shape', window.cursorShape);
term.prefs_.set('font-family', window.fontFamily);
term.prefs_.set('font-size', window.fontSize);
term.prefs_.set('foreground-color', window.foregroundColor);
term.prefs_.set('background-color', window.backgroundColor);
term.prefs_.set('cursor-color', window.cursorColor);
term.prefs_.set('cursor-blink', false);
term.prefs_.set('enable-clipboard-notice', false);
term.prefs_.set('use-default-window-copy', true);
term.prefs_.set('clear-selection-after-copy', true);
term.prefs_.set('copy-on-select', false);
term.prefs_.set('audible-bell-sound', '');
term.prefs_.set('receive-encoding', 'utf-8');
term.prefs_.set('meta-sends-escape', 'false');
term.prefs_.set('allow-images-inline', true);
term.setReverseWraparound(true);
term.setWraparound(true);
//
term.onCut = function(e) {
var text = this.getSelectionText();
// compose events tend to create a selection node with range, which breaks insertion:
if (text == null) {
// TODO: force the HTML cursor to go back to the actual cursor position (HOW?)
this.document_.getSelection().collapse(this.scrollPort_.getScreenNode());
this.syncCursorPosition_();
return false;
}
// We also need to remove it from the command line -- if it is in.
var startRow = this.scrollPort_.selection.startRow.rowIndex;
var endRow = this.scrollPort_.selection.endRow.rowIndex;
if ((startRow >= window.promptScroll + window.promptLine ) &&
(endRow >= window.promptScroll + window.promptLine )) {
// the selected text is inside the current command line: we can cut it.
// startOffset = position of selection from start of startRow (not necessarily start of command)
var startOffset = this.scrollPort_.selection.startOffset;
// endOffset = position of selection from start of endRow (not used)
var endOffset = this.scrollPort_.selection.endOffset;
var startPosition = this.io.currentCommand.indexOf(text)
var xcursor = startOffset;
if (startPosition != -1) {
// check if text is inside currentCommand *once*, if yes, just remove it.
if (this.io.currentCommand.lastIndexOf(text) == startPosition) {
this.io.currentCommand = this.io.currentCommand.slice(0, startPosition) + this.io.currentCommand.slice(startPosition + text.length, this.io.currentCommand.length);
} else {
const startNode = this.scrollPort_.selection.startNode;
const endNode = this.scrollPort_.selection.endNode
const numLines = (startRow - window.promptScroll - window.promptLine);
var fullOffset = 0;
if (this.scrollPort_.selection.startRow.childNodes[0] == startNode) {
// easy case, we're on the first node.
startOffset += numLines * this.screenSize.width - window.promptEnd;
var cutText = this.io.currentCommand.slice(startOffset, startOffset + text.length);
if (cutText == text) {
startPosition = startOffset;
this.io.currentCommand = this.io.currentCommand.slice(0, startPosition) + this.io.currentCommand.slice(startPosition + text.length, this.io.currentCommand.length);
}
} else {
// Multiple nodes, the selected text is not on the first node.
// We must advance inside currentCommand by at least this much:
startPosition = numLines * this.screenSize.width - window.promptEnd;
startPosition += this.scrollPort_.selection.startRow.childNodes[0].length;
var cutText = this.io.currentCommand.slice(startPosition, this.io.currentCommand.length);
for (let i = 1; i < this.scrollPort_.selection.startRow.childNodes.length; i++) {
const node = this.scrollPort_.selection.startRow.childNodes[i];
if (node.nodeName == "#text") {
if (startNode != node) {
startPosition += node.data.length;
} else {
startPosition += startOffset;
break;
}
} else {
var foundNode = false;
for (let j = 0; j < node.childNodes.length; j++) {
const secondNode = node.childNodes[j];
if (startNode != secondNode) {
startPosition += secondNote.data.length;
} else {
startPosition += startOffset;
foundNode = true;
break;
}
}
if (foundNode) {
break;
}
}
}
var cutText = this.io.currentCommand.slice(startPosition, startPosition + text.length);
if (cutText == text) {
this.io.currentCommand = this.io.currentCommand.slice(0, startPosition) + this.io.currentCommand.slice(startPosition + text.length, this.io.currentCommand.length);
} else {
// This happens too often.
// TODO: make sure we don't cut "newline" instead of actual text.
// Do not cut if we don't agree on what to cut
if (e != null) {
e.preventDefault();
}
return false;
}
}
}
// Move cursor to startLine, startOffset
// We redraw the command ourselves because iOS removes extra spaces around the text.
// var scrolledLines = window.promptScroll - term.scrollPort_.getTopRowIndex();
// io.print('\x1b[' + (window.promptLine + scrolledLines + 1) + ';' + (window.promptEnd + 1) + 'H'); // move cursor to position at start of line
xcursor = window.promptEnd + startPosition;
while (xcursor > this.screenSize.width) {
xcursor -= this.screenSize.width;
}
currentCommandCursorPosition = startPosition
var ycursor = startRow - this.scrollPort_.getTopRowIndex();
this.io.print('\x1b[' + (ycursor + 1) + ';' + (xcursor + 1) + 'H'); // move cursor to new position
this.io.print('\x1b[0J'); // delete display after cursor
var endOfCommand = this.io.currentCommand.slice(startPosition, this.io.currentCommand.length);
this.io.print(endOfCommand);
this.io.print('\x1b[' + (ycursor + 1) + ';' + (xcursor + 1) + 'H'); // move cursor back to new position
window.webkit.messageHandlers.aShell.postMessage('copy:' + text); // copy the text to clipboard. We can't use JS fonctions because we removed the text.
e.preventDefault();
return true;
} else {
window.webkit.messageHandlers.aShell.postMessage("Really cannot find text = " + text + " in " + this.io.currentCommand);
// Do not cut if we don't agree on what to cut
if (e != null) {
e.preventDefault();
}
return false;
}
}
// Do not cut if we are outside the command line:
if (e != null) {
e.preventDefault();
return false;
}
};
//
term.onTerminalReady = function() {
const io = this.io.push();
io.onVTKeystroke = (string) => {
if (window.controlOn) {
// on-screen control is On
// produce string = control + character
// Replace on-screen-control + arrow with alt + arrow (already present in code)
switch (string) {
case String.fromCharCode(27) + "[A": // Up arrow
case String.fromCharCode(27) + "OA": // Up arrow
string = String.fromCharCode(27) + "[1;3A"; // Alt-Up arrow
break;
case String.fromCharCode(27) + "[B": // Down arrow
case String.fromCharCode(27) + "OB": // Down arrow
string = String.fromCharCode(27) + "[1;3B"; // Alt-Down arrow
break;
case String.fromCharCode(27) + "[D": // Left arrow
case String.fromCharCode(27) + "OD": // Left arrow
string = String.fromCharCode(27) + "[1;3D"; // Alt-left arrow
break;
case String.fromCharCode(27) + "[C": // Right arrow
case String.fromCharCode(27) + "OC": // Right arrow
string = String.fromCharCode(27) + "[1;3C"; // Alt-right arrow
break;
default:
// default case: just take the first character and remove 64:
var charcode = string.toUpperCase().charCodeAt(0);
string = String.fromCharCode(charcode - 64);
}
window.controlOn = false;
window.webkit.messageHandlers.aShell.postMessage('controlOff');
}
// always post keyboard input to TTY:
window.webkit.messageHandlers.aShell.postMessage('inputTTY:' + string);
// If help() is running in iPython, then it stops being interactive.
var helpRunning = false;
if (window.commandRunning.startsWith("ipython") || window.commandRunning.startsWith("isympy")) {
var lastNewline = window.printedContent.lastIndexOf("\n");
var lastLine = window.printedContent.substr(lastNewline + 1); // 1 to skip \n.
lastLine = lastLine.replace(/(\r\n|\n|\r|\n\r)/gm,""); // skip past \r and \n, if any
if (lastLine.startsWith("help>")) {
helpRunning = true;
} else if (lastLine.includes("Do you really want to exit ([y]/n)?")) {
helpRunning = true;
}
}
// Easiest way to handle the case where Python (non-interactive) starts help, which starts less, which
// changes the status to interactive, but does not reset it when leaving.
// TODO: adress the larger issue where a non-interactive command starts an interactive command.
if (window.commandRunning.startsWith("python")) {
var lastNewline = window.printedContent.lastIndexOf("\n");
var lastLine = window.printedContent.substr(lastNewline + 1); // 1 to skip \n.
lastLine = lastLine.replace(/(\r\n|\n|\r|\n\r)/gm,""); // skip past \r and \n, if any
if ((lastLine.startsWith("help>")) || (lastLine.startsWith(">>>"))) {
window.interactiveCommandRunning = false;
}
}
if ((window.commandRunning != '') && (term.vt.mouseReport != term.vt.MOUSE_REPORT_DISABLED)) {
// if an application has enabled mouse report, it is likely to be interactive:
// (this was added for textual)
window.webkit.messageHandlers.aShell.postMessage('inputInteractive:' + string);
} else if (window.interactiveCommandRunning && (window.commandRunning != '') && !helpRunning) {
// specific treatment for interactive commands: forward all keyboard input to them
// window.webkit.messageHandlers.aShell.postMessage('sending: ' + string); // for debugging
// post keyboard input to stdin
window.webkit.messageHandlers.aShell.postMessage('inputInteractive:' + string);
} else if ((window.commandRunning != '') && ((string.charCodeAt(0) == 3) || (string.charCodeAt(0) == 4))) {
// Send control messages back to command:
// first, flush existing input:
if (io.currentCommand != '') {
window.webkit.messageHandlers.aShell.postMessage('input:' + io.currentCommand);
io.currentCommand = '';
}
window.webkit.messageHandlers.aShell.postMessage('input:' + string);
} else {
// window.webkit.messageHandlers.aShell.postMessage('Received character: ' + string + ' ' + string.length); // for debugging
if (io.currentCommand === '') {
// new line, reset things: (required for commands inside commands)
updatePromptPosition();
}
var cursorPosition = term.screen_.cursorPosition.column - window.promptEnd; // remove prompt length
switch (string) {
case '\r':
if (autocompleteOn) {
// Autocomplete menu being displayed + press return: select what's visible and remove
pickCurrentValue();
break;
}
// Before executing command, move to end of line if not already there, and cleanup the line content:
// Compute how many lines should we move downward:
var beginCommand = io.currentCommand.slice(0, currentCommandCursorPosition);
var lineCursor = Math.floor((lib.wc.strWidth(beginCommand) + window.promptEnd)/ term.screenSize.width);
var lineEndCommand = Math.floor((lib.wc.strWidth(io.currentCommand) + window.promptEnd)/ term.screenSize.width);
for (var i = 0; i < lineEndCommand - lineCursor; i++) {
io.println('');
}
io.println('');
cleanupLastLine();
if (window.commandRunning != '') {
// The command takes care of the prompt. Just send the input data:
window.webkit.messageHandlers.aShell.postMessage('input:' + io.currentCommand + '\n');
// remove temporarily stored command -- if any
if (window.maxCommandInsideCommandIndex < window.commandInsideCommandArray.length) {
window.commandInsideCommandArray.pop();
}
// only store non-empty commands:
// store commands sent:
if (io.currentCommand.length > 0) {
if (io.currentCommand != window.commandInsideCommandArray[window.maxCommandInsideCommandIndex - 1]) {
// only add command to history if it is different from the last one:
window.maxCommandInsideCommandIndex = window.commandInsideCommandArray.push(io.currentCommand);
}
}
while (window.maxCommandInsideCommandIndex >= 100) {
// We have stored more than 100 commands
window.commandInsideCommandArray.shift(); // remove first element
window.maxCommandInsideCommandIndex = window.commandInsideCommandArray.length;
}
window.commandInsideCommandIndex = window.maxCommandInsideCommandIndex;
} else {
if (io.currentCommand.length > 0) {
// Reinitialize before sending:
window.commandRunning = io.currentCommand;
window.interactiveCommandRunning = isInteractive(window.commandRunning);
// ...and send the command to iOS:
window.webkit.messageHandlers.aShell.postMessage('shell:' + io.currentCommand);
// remove temporarily stored command -- if any
if (window.maxCommandIndex < window.commandArray.length) {
window.commandArray.pop();
}
if (io.currentCommand != window.commandArray[window.maxCommandIndex - 1]) {
// only add command to history if it is different from the last one:
window.maxCommandIndex = window.commandArray.push(window.commandRunning);
while (window.maxCommandIndex >= 100) {
// We have stored more than 100 commands
window.commandArray.shift(); // remove first element
window.maxCommandIndex = window.commandArray.length;
}
}
window.commandIndex = window.maxCommandIndex;
// clear history inside command:
window.commandInsideCommandArray = [];
window.commandInsideCommandIndex = 0;
window.maxCommandInsideCommandIndex = 0;
} else {
printPrompt();
updatePromptPosition();
}
}
io.currentCommand = '';
break;
case String.fromCharCode(127): // delete key from iOS keyboard
case String.fromCharCode(8): // Ctrl+H
if (currentCommandCursorPosition > 0) {
if (this.document_.getSelection().type == 'Range') {
term.onCut(null); // remove the selection without copying it
} else {
deleteBackward();
}
}
disableAutocompleteMenu();
break;
case String.fromCharCode(24): // Ctrl-X
case String.fromCharCode(26): // Ctrl-Z // Cancel. Make popup menu disappear
disableAutocompleteMenu();
break;
case String.fromCharCode(27): // Escape. Make popup menu disappear
disableAutocompleteMenu();
break;
case String.fromCharCode(27) + "[A": // Up arrow
case String.fromCharCode(27) + "OA": // Up arrow
case String.fromCharCode(27) + "[1;3A": // Alt-Up arrow
case String.fromCharCode(16): // Ctrl+P
// popup menu being displayed, change it:
if (autocompleteOn) {
if (autocompleteIndex > 0) {
autocompleteIndex -= 1;
printAutocompleteString(autocompleteList[autocompleteIndex]);
}
break;
} else if (window.commandRunning != '') {
if (window.commandInsideCommandIndex > 0) {
if (window.commandInsideCommandIndex === window.maxCommandInsideCommandIndex) {
// Store current command:
window.commandInsideCommandArray[window.commandInsideCommandIndex] = io.currentCommand;
}
io.print('\x1b[' + (window.promptLine + 1) + ';' + (window.promptEnd + 1) + 'H'); // move cursor back to initial position
io.print('\x1b[0J'); // delete display after cursor
if (string != String.fromCharCode(27) + "[1;3A") {
window.commandInsideCommandIndex -= 1;
if (window.commandInsideCommandIndex < 0) {
window.commandInsideCommandIndex = 0;
}
} else {
window.commandInsideCommandIndex -= 5;
if (window.commandInsideCommandIndex < 0) {
window.commandInsideCommandIndex = 0;
}
}
io.currentCommand = window.commandInsideCommandArray[window.commandInsideCommandIndex];
io.print(io.currentCommand);
cleanupLastLine();
currentCommandCursorPosition = io.currentCommand.length;
}
} else {
if (window.commandIndex > 0) {
if (window.commandIndex === window.maxCommandIndex) {
// Store current command:
window.commandArray[window.commandIndex] = io.currentCommand;
}
var scrolledLines = window.promptScroll - term.scrollPort_.getTopRowIndex();
io.print('\x1b[' + (window.promptLine + scrolledLines + 1) + ';' + (window.promptEnd + 1) + 'H'); // move cursor to position at start of line
io.print('\x1b[0J'); // delete display after cursor
if (string != String.fromCharCode(27) + "[1;3A") {
window.commandIndex -= 1;
} else {
window.commandIndex -= 5;
if (window.commandIndex < 0) {
window.commandIndex = 0;
}
}
io.currentCommand = window.commandArray[window.commandIndex];
io.print(io.currentCommand);
cleanupLastLine();
currentCommandCursorPosition = io.currentCommand.length;
}
}
break;
case String.fromCharCode(27) + "[B": // Down arrow
case String.fromCharCode(27) + "OB": // Down arrow
case String.fromCharCode(27) + "[1;3B": // Alt-Down arrow
case String.fromCharCode(14): // Ctrl+N
// popup menu being displayed, change it:
if (autocompleteOn) {
if (autocompleteIndex < autocompleteList.length - 1) {
autocompleteIndex += 1;
printAutocompleteString(autocompleteList[autocompleteIndex]);
}
break;
} else if (window.commandRunning != '') {
if (window.commandInsideCommandIndex < window.maxCommandInsideCommandIndex) {
io.print('\x1b[' + (window.promptLine + 1) + ';' + (window.promptEnd + 1) + 'H'); // move cursor to position at start of line
io.print('\x1b[0J'); // delete display after cursor
if (string != String.fromCharCode(27) + "[1;3B") {
window.commandInsideCommandIndex += 1;
} else {
window.commandInsideCommandIndex += 5;
if (window.commandInsideCommandIndex >= window.maxCommandInsideCommandIndex) {
window.commandInsideCommandIndex = window.maxCommandInsideCommandIndex;
}
}
io.currentCommand = window.commandInsideCommandArray[window.commandInsideCommandIndex];
io.print(io.currentCommand);
cleanupLastLine();
currentCommandCursorPosition = io.currentCommand.length;
}
} else {
if (window.commandIndex < window.maxCommandIndex) {
var scrolledLines = window.promptScroll - term.scrollPort_.getTopRowIndex();
io.print('\x1b[' + (window.promptLine + scrolledLines + 1) + ';' + (window.promptEnd + 1) + 'H'); // move cursor to position at start of line
io.print('\x1b[0J'); // delete display after cursor
if (string != String.fromCharCode(27) + "[1;3B") {
window.commandIndex += 1;
} else {
window.commandIndex += 5;
if (window.commandIndex >= window.maxCommandIndex) {
window.commandIndex = window.maxCommandIndex;
}
}
io.currentCommand = window.commandArray[window.commandIndex];
io.print(io.currentCommand);
cleanupLastLine();
currentCommandCursorPosition = io.currentCommand.length;
}
}
break;
case String.fromCharCode(27) + "[D": // Left arrow
case String.fromCharCode(27) + "OD": // Left arrow
case String.fromCharCode(2): // Ctrl+B
if (this.document_.getSelection().type == 'Range') {
// move cursor to start of selection
this.moveCursorPosition(term.scrollPort_.selection.startRow.rowIndex - term.scrollPort_.getTopRowIndex(), term.scrollPort_.selection.startOffset);
this.document_.getSelection().collapseToStart();
disableAutocompleteMenu();
} else {
if (currentCommandCursorPosition > 0) {
var previousCursorPosition = 0;
var currentChar;
for (const v of window.term_.io.currentCommand) {
if (previousCursorPosition + v.length >= currentCommandCursorPosition) {
currentChar = v;
break;
}
previousCursorPosition += v.length;
}
var currentCharWidth = lib.wc.strWidth(currentChar);