/
cli.js
609 lines (506 loc) · 19.5 KB
/
cli.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
import { i18n } from "../localization";
import Clipboard from "../Clipboard";
import { generateFilename } from "../utils/generate_filename";
import GUI, { TABS } from '../gui';
import BuildApi from '../BuildApi';
import { tracking } from '../Analytics';
import { reinitializeConnection } from "../serial_backend";
import CONFIGURATOR from "../data_storage";
import serial from "../serial";
import CliAutoComplete from "../CliAutoComplete";
import UI_PHONES from "../phones_ui";
import { gui_log } from "../gui_log";
import jBox from "jbox";
import { checkChromeRuntimeError } from "../utils/common";
const cli = {
lineDelayMs: 15,
profileSwitchDelayMs: 100,
outputHistory: "",
cliBuffer: "",
startProcessing: false,
GUI: {
snippetPreviewWindow: null,
copyButton: null,
windowWrapper: null,
},
lastArrival: 0,
};
function removePromptHash(promptText) {
return promptText.replace(/^# /, '');
}
function cliBufferCharsToDelete(command, buffer) {
let commonChars = 0;
for (let i = 0; i < buffer.length; i++) {
if (command[i] === buffer[i]) {
commonChars++;
} else {
break;
}
}
return buffer.length - commonChars;
}
function commandWithBackSpaces(command, buffer, noOfCharsToDelete) {
const backspace = String.fromCharCode(127);
return backspace.repeat(noOfCharsToDelete) + command.substring(buffer.length - noOfCharsToDelete, command.length);
}
function getCliCommand(command, cliBuffer) {
const buffer = removePromptHash(cliBuffer);
const bufferRegex = new RegExp(`^${buffer}`, 'g');
if (command.match(bufferRegex)) {
return command.replace(bufferRegex, '');
}
const noOfCharsToDelete = cliBufferCharsToDelete(command, buffer);
return commandWithBackSpaces(command, buffer, noOfCharsToDelete);
}
function copyToClipboard(text) {
function onCopySuccessful() {
tracking.sendEvent(tracking.EVENT_CATEGORIES.FLIGHT_CONTROLLER, 'CliCopyToClipboard', text.length);
const button = TABS.cli.GUI.copyButton;
const origText = button.text();
const origWidth = button.css("width");
button.text(i18n.getMessage("cliCopySuccessful"));
button.css({
width: origWidth,
textAlign: "center",
});
setTimeout(() => {
button.text(origText);
button.css({
width: "",
textAlign: "",
});
}, 1500);
}
function onCopyFailed(ex) {
console.warn(ex);
}
Clipboard.writeText(text, onCopySuccessful, onCopyFailed);
}
cli.initialize = function (callback) {
const self = this;
if (GUI.active_tab !== 'cli') {
GUI.active_tab = 'cli';
}
self.outputHistory = "";
self.cliBuffer = "";
self.startProcessing = false;
const enterKeyCode = 13;
function clearHistory() {
self.outputHistory = "";
self.GUI.windowWrapper.empty();
}
function executeCommands(outString) {
self.history.add(outString.trim());
const outputArray = outString.split("\n");
return outputArray.reduce((p, line, index) =>
p.then((delay) =>
new Promise((resolve) => {
GUI.timeout_add('CLI_send_slowly', function () {
let processingDelay = self.lineDelayMs;
line = line.trim();
if (line.toLowerCase().startsWith('profile')) {
processingDelay = self.profileSwitchDelayMs;
}
const isLastCommand = outputArray.length === index + 1;
if (isLastCommand && self.cliBuffer) {
line = getCliCommand(line, self.cliBuffer);
}
self.sendLine(line, function () {
resolve(processingDelay);
});
}, delay);
}),
),
Promise.resolve(0),
);
}
$('#content').load("./tabs/cli.html", function () {
// translate to user-selected language
i18n.localizePage();
TABS.cli.adaptPhones();
CONFIGURATOR.cliActive = true;
self.GUI.copyButton = $('.tab-cli .copy');
self.GUI.windowWrapper = $('.tab-cli .window .wrapper');
const textarea = $('.tab-cli textarea[name="commands"]');
CliAutoComplete.initialize(textarea, self.sendLine.bind(self), writeToOutput);
$(CliAutoComplete).on('build:start', function() {
textarea
.val('')
.attr('placeholder', i18n.getMessage('cliInputPlaceholderBuilding'))
.prop('disabled', true);
});
$(CliAutoComplete).on('build:stop', function() {
textarea
.attr('placeholder', i18n.getMessage('cliInputPlaceholder'))
.prop('disabled', false)
.focus();
});
$('.tab-cli .save').click(function() {
const prefix = 'cli';
const suffix = 'txt';
const filename = generateFilename(prefix, suffix);
const accepts = [{
description: `${suffix.toUpperCase()} files`, extensions: [suffix],
}];
chrome.fileSystem.chooseEntry({type: 'saveFile', suggestedName: filename, accepts: accepts}, function(entry) {
if (checkChromeRuntimeError()) {
return;
}
if (!entry) {
console.log('No file selected');
return;
}
entry.createWriter(function (writer) {
writer.onerror = function (){
console.error('Failed to write file');
};
writer.onwriteend = function () {
if (self.outputHistory.length > 0 && writer.length === 0) {
writer.write(new Blob([self.outputHistory], {type: 'text/plain'}));
} else {
tracking.sendEvent(tracking.EVENT_CATEGORIES.FLIGHT_CONTROLLER, 'CliSave', self.outputHistory.length);
console.log('write complete');
}
};
writer.truncate(0);
}, function (){
console.error('Failed to get file writer');
});
});
});
$('.tab-cli .clear').click(function() {
clearHistory();
});
if (Clipboard.available) {
self.GUI.copyButton.click(function() {
copyToClipboard(self.outputHistory);
});
} else {
self.GUI.copyButton.hide();
}
$('.tab-cli .load').click(function() {
const accepts = [
{
description: 'Config files', extensions: ["txt", "config"],
},
{
description: 'All files',
},
];
chrome.fileSystem.chooseEntry({type: 'openFile', accepts: accepts}, function(entry) {
if (checkChromeRuntimeError()) {
return;
}
const previewArea = $("#snippetpreviewcontent textarea#preview");
function executeSnippet(fileName) {
const commands = previewArea.val();
tracking.sendEvent(tracking.EVENT_CATEGORIES.FLIGHT_CONTROLLER, 'CliExecuteFromFile', fileName);
executeCommands(commands);
self.GUI.snippetPreviewWindow.close();
}
function previewCommands(result, fileName) {
if (!self.GUI.snippetPreviewWindow) {
self.GUI.snippetPreviewWindow = new jBox("Modal", {
id: "snippetPreviewWindow",
width: 'auto',
height: 'auto',
closeButton: 'title',
animation: false,
isolateScroll: false,
title: i18n.getMessage("cliConfirmSnippetDialogTitle", { fileName: fileName }),
content: $('#snippetpreviewcontent'),
onCreated: () =>
$("#snippetpreviewcontent a.confirm").click(() => executeSnippet(fileName))
,
});
}
previewArea.val(result);
self.GUI.snippetPreviewWindow.open();
}
entry.file((file) => {
const reader = new FileReader();
reader.onload =
() => previewCommands(reader.result, file.name);
reader.onerror = () => console.error(reader.error);
reader.readAsText(file);
});
});
});
$('.tab-cli .support').click(function() {
function submitSupportData(data) {
clearHistory();
const api = new BuildApi();
api.getSupportCommands(commands => {
commands = [`###\n# Problem description\n# ${data}\n###`, ...commands];
executeCommands(commands.join('\n')).then(() => {
const delay = setInterval(() => {
const time = new Date().getTime();
if (self.lastArrival < time - 250) {
clearInterval(delay);
const text = self.outputHistory;
api.submitSupportData(text, key => {
writeToOutput(i18n.getMessage('buildServerSupportRequestSubmission', [key]));
});
}
}, 250);
});
});
}
self.supportWarningDialog(submitSupportData);
});
// Tab key detection must be on keydown,
// `keypress`/`keyup` happens too late, as `textarea` will have already lost focus.
textarea.keydown(function (event) {
const tabKeyCode = 9;
if (event.which === tabKeyCode) {
// prevent default tabbing behaviour
event.preventDefault();
if (!CliAutoComplete.isEnabled()) {
// Native FC autoComplete
const outString = textarea.val();
const lastCommand = outString.split("\n").pop();
const command = getCliCommand(lastCommand, self.cliBuffer);
if (command) {
self.sendNativeAutoComplete(command);
textarea.val('');
}
}
else if (!CliAutoComplete.isOpen() && !CliAutoComplete.isBuilding()) {
// force show autocomplete on Tab
CliAutoComplete.openLater(true);
}
}
});
textarea.keypress(function (event) {
if (event.which === enterKeyCode) {
event.preventDefault(); // prevent the adding of new line
if (CliAutoComplete.isBuilding()) {
return; // silently ignore commands if autocomplete is still building
}
const outString = textarea.val();
executeCommands(outString);
textarea.val('');
}
});
textarea.keyup(function (event) {
const keyUp = {38: true};
const keyDown = {40: true};
if (CliAutoComplete.isOpen()) {
return; // disable history keys if autocomplete is open
}
if (event.keyCode in keyUp) {
textarea.val(self.history.prev());
}
if (event.keyCode in keyDown) {
textarea.val(self.history.next());
}
});
// give input element user focus
textarea.focus();
GUI.timeout_add('enter_cli', function enter_cli() {
// Enter CLI mode
const bufferOut = new ArrayBuffer(1);
const bufView = new Uint8Array(bufferOut);
bufView[0] = 0x23; // #
serial.send(bufferOut);
}, 250);
GUI.content_ready(callback);
});
};
cli.adaptPhones = function() {
if ($(window).width() < 575) {
const backdropHeight = $('.note').height() + 22 + 38;
$('.backdrop').css('height', `calc(100% - ${backdropHeight}px)`);
}
if (GUI.isCordova()) {
UI_PHONES.initToolbar();
}
};
cli.history = {
history: [],
index: 0,
};
cli.history.add = function (str) {
this.history.push(str);
this.index = this.history.length;
};
cli.history.prev = function () {
if (this.index > 0) {
this.index -= 1;
}
return this.history[this.index];
};
cli.history.next = function () {
if (this.index < this.history.length) {
this.index += 1;
}
return this.history[this.index - 1];
};
const backspaceCode = 8;
const lineFeedCode = 10;
const carriageReturnCode = 13;
function writeToOutput(text) {
TABS.cli.GUI.windowWrapper.append(text);
const cliWindow = $('.tab-cli .window');
cliWindow.scrollTop(cliWindow.prop("scrollHeight"));
}
function writeLineToOutput(text) {
if (CliAutoComplete.isBuilding()) {
CliAutoComplete.builderParseLine(text);
return; // suppress output if in building state
}
if (text.startsWith("###ERROR")) {
writeToOutput(`<span class="error_message">${text}</span><br>`);
} else {
writeToOutput(`${text}<br>`);
}
}
function setPrompt(text) {
$('.tab-cli textarea').val(text);
}
cli.read = function (readInfo) {
/* Some info about handling line feeds and carriage return
line feed = LF = \n = 0x0A = 10
carriage return = CR = \r = 0x0D = 13
MAC only understands CR
Linux and Unix only understand LF
Windows understands (both) CRLF
Chrome OS currently unknown
*/
const data = new Uint8Array(readInfo.data);
let validateText = "";
let sequenceCharsToSkip = 0;
for (let i = 0; i < data.length; i++) {
const currentChar = String.fromCharCode(data[i]);
const isCRLF = currentChar.charCodeAt() === lineFeedCode || currentChar.charCodeAt() === carriageReturnCode;
if (!CONFIGURATOR.cliValid && (isCRLF || this.startProcessing)) {
// try to catch part of valid CLI enter message (firmware message starts with CRLF)
this.startProcessing = true;
validateText += currentChar;
writeToOutput(currentChar);
continue;
}
const escapeSequenceCode = 27;
const escapeSequenceCharLength = 3;
if (data[i] === escapeSequenceCode && !sequenceCharsToSkip) { // ESC + other
sequenceCharsToSkip = escapeSequenceCharLength;
}
if (sequenceCharsToSkip) {
sequenceCharsToSkip--;
continue;
}
if (CONFIGURATOR.cliValid) {
switch (data[i]) {
case lineFeedCode:
if (GUI.operating_system === "Windows") {
writeLineToOutput(this.cliBuffer);
this.cliBuffer = "";
}
break;
case carriageReturnCode:
if (GUI.operating_system !== "Windows") {
writeLineToOutput(this.cliBuffer);
this.cliBuffer = "";
}
break;
case 60:
this.cliBuffer += '<';
break;
case 62:
this.cliBuffer += '>';
break;
case backspaceCode:
this.cliBuffer = this.cliBuffer.slice(0, -1);
this.outputHistory = this.outputHistory.slice(0, -1);
continue;
default:
this.cliBuffer += currentChar;
}
}
if (!CliAutoComplete.isBuilding()) {
// do not include the building dialog into the history
this.outputHistory += currentChar;
}
if (this.cliBuffer === 'Rebooting') {
CONFIGURATOR.cliActive = false;
CONFIGURATOR.cliValid = false;
gui_log(i18n.getMessage('cliReboot'));
reinitializeConnection();
}
}
this.lastArrival = new Date().getTime();
if (!CONFIGURATOR.cliValid && validateText.indexOf('CLI') !== -1) {
gui_log(i18n.getMessage('cliEnter'));
CONFIGURATOR.cliValid = true;
// begin output history with the prompt (last line of welcome message)
// this is to match the content of the history with what the user sees on this tab
const lastLine = validateText.split("\n").pop();
this.outputHistory = lastLine;
if (CliAutoComplete.isEnabled() && !CliAutoComplete.isBuilding()) {
// start building autoComplete
CliAutoComplete.builderStart();
}
}
// fallback to native autocomplete
if (!CliAutoComplete.isEnabled()) {
setPrompt(removePromptHash(this.cliBuffer));
}
};
cli.sendLine = function (line, callback) {
this.send(`${line}\n`, callback);
};
cli.sendNativeAutoComplete = function (line, callback) {
this.send(`${line}\t`, callback);
};
cli.send = function (line, callback) {
const bufferOut = new ArrayBuffer(line.length);
const bufView = new Uint8Array(bufferOut);
for (let cKey = 0; cKey < line.length; cKey++) {
bufView[cKey] = line.charCodeAt(cKey);
}
serial.send(bufferOut, callback);
};
cli.supportWarningDialog = function (onAccept) {
const supportWarningDialog = $('.supportWarningDialog')[0];
const supportWarningDialogTextArea = $('.tab-cli textarea[name="supportWarningDialogInput"]');
if (!supportWarningDialog.hasAttribute('open')) {
supportWarningDialog.showModal();
$('.cancel').on('click', function() {
supportWarningDialog.close();
});
$('.submit').on('click', function() {
supportWarningDialog.close();
onAccept(supportWarningDialogTextArea.val());
supportWarningDialogTextArea.val('');
});
}
};
cli.cleanup = function (callback) {
if (TABS.cli.GUI.snippetPreviewWindow) {
TABS.cli.GUI.snippetPreviewWindow.destroy();
TABS.cli.GUI.snippetPreviewWindow = null;
}
if (!(CONFIGURATOR.connectionValid && CONFIGURATOR.cliValid && CONFIGURATOR.cliActive)) {
if (callback) {
callback();
}
return;
}
this.send(getCliCommand('exit\r', this.cliBuffer), function () {
// we could handle this "nicely", but this will do for now
// (another approach is however much more complicated):
// we can setup an interval asking for data lets say every 200ms, when data arrives, callback will be triggered and tab switched
// we could probably implement this someday
if (callback) {
callback();
}
CONFIGURATOR.cliActive = false;
CONFIGURATOR.cliValid = false;
});
CliAutoComplete.cleanup();
$(CliAutoComplete).off();
};
TABS.cli = cli;
export {
cli,
};