/
gui.js
529 lines (449 loc) · 16.2 KB
/
gui.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
import { get as getConfig } from './ConfigStorage';
import MSP from './msp';
window.TABS = {}; // filled by individual tab js file
const GUI_MODES = {
NWJS: "NW.js",
Cordova: "Cordova",
Other: "Other",
};
class GuiControl {
constructor() {
this.auto_connect = false;
this.connecting_to = false;
this.connected_to = false;
this.connect_lock = false;
this.active_tab = null;
this.tab_switch_in_progress = false;
this.operating_system = null;
this.interval_array = [];
this.timeout_array = [];
this.buttonDisabledClass = "disabled";
this.defaultAllowedTabsWhenDisconnected = [
'landing',
'changelog',
'firmware_flasher',
'privacy_policy',
'options',
'help',
];
this.defaultAllowedFCTabsWhenConnected = [
'setup',
'failsafe',
'transponder',
'osd',
'power',
'adjustments',
'auxiliary',
'presets',
'cli',
'configuration',
'gps',
'led_strip',
'logging',
'onboard_logging',
'modes',
'motors',
'pid_tuning',
'ports',
'receiver',
'sensors',
'servos',
'vtx',
];
this.allowedTabs = this.defaultAllowedTabsWhenDisconnected;
// check which operating system is user running
this.operating_system = GUI_checkOperatingSystem();
// Check the method of execution
this.nwGui = null;
try {
this.nwGui = require('nw.gui');
this.Mode = GUI_MODES.NWJS;
} catch (ex) {
if (typeof cordovaApp !== 'undefined') {
this.Mode = GUI_MODES.Cordova;
} else {
this.Mode = GUI_MODES.Other;
}
}
}
// Timer managing methods
// name = string
// code = function reference (code to be executed)
// interval = time interval in miliseconds
// first = true/false if code should be ran initially before next timer interval hits
interval_add(name, code, interval, first) {
const data = { 'name': name, 'timer': null, 'code': code, 'interval': interval, 'fired': 0, 'paused': false };
if (first === true) {
code(); // execute code
data.fired++; // increment counter
}
data.timer = setInterval(function () {
code(); // execute code
data.fired++; // increment counter
}, interval);
this.interval_array.push(data); // push to primary interval array
return data;
}
// name = string
// code = function reference (code to be executed)
// interval = time interval in miliseconds
// first = true/false if code should be ran initially before next timer interval hits
// condition = function reference with true/false result, a condition to be checked before every interval code execution
interval_add_condition(name, code, interval, first, condition) {
this.interval_add(name, () => {
if (condition()) {
code();
} else {
this.interval_remove(name);
}
}, interval, first);
}
// name = string
interval_remove(name) {
for (let i = 0; i < this.interval_array.length; i++) {
if (this.interval_array[i].name === name) {
clearInterval(this.interval_array[i].timer); // stop timer
this.interval_array.splice(i, 1); // remove element/object from array
return true;
}
}
return false;
}
// name = string
interval_pause(name) {
for (let i = 0; i < this.interval_array.length; i++) {
if (this.interval_array[i].name === name) {
clearInterval(this.interval_array[i].timer);
this.interval_array[i].paused = true;
return true;
}
}
return false;
}
// name = string
interval_resume(name) {
function executeCode(obj) {
obj.code(); // execute code
obj.fired++; // increment counter
}
for (let i = 0; i < this.interval_array.length; i++) {
if (this.interval_array[i].name === name && this.interval_array[i].paused) {
const obj = this.interval_array[i];
obj.timer = setInterval(executeCode, obj.interval, obj);
obj.paused = false;
return true;
}
}
return false;
}
// input = array of timers thats meant to be kept, or nothing
// return = returns timers killed in last call
interval_kill_all(keepArray) {
const self = this;
let timersKilled = 0;
for (let i = (this.interval_array.length - 1); i >= 0; i--) { // reverse iteration
let keep = false;
if (keepArray) { // only run through the array if it exists
keepArray.forEach(function (name) {
if (self.interval_array[i].name === name) {
keep = true;
}
});
}
if (!keep) {
clearInterval(this.interval_array[i].timer); // stop timer
this.interval_array.splice(i, 1); // remove element/object from array
timersKilled++;
}
}
return timersKilled;
}
// name = string
// code = function reference (code to be executed)
// timeout = timeout in miliseconds
timeout_add(name, code, timeout) {
const self = this;
const data = {
'name': name,
'timer': null,
'timeout': timeout,
};
// start timer with "cleaning" callback
data.timer = setTimeout(function () {
code(); // execute code
// remove object from array
const index = self.timeout_array.indexOf(data);
if (index > -1) {
self.timeout_array.splice(index, 1);
}
}, timeout);
this.timeout_array.push(data); // push to primary timeout array
return data;
}
// name = string
timeout_remove(name) {
for (let i = 0; i < this.timeout_array.length; i++) {
if (this.timeout_array[i].name === name) {
clearTimeout(this.timeout_array[i].timer); // stop timer
this.timeout_array.splice(i, 1); // remove element/object from array
return true;
}
}
return false;
}
// no input parameters
// return = returns timers killed in last call
timeout_kill_all() {
let timersKilled = 0;
for (let i = 0; i < this.timeout_array.length; i++) {
clearTimeout(this.timeout_array[i].timer); // stop timer
timersKilled++;
}
this.timeout_array = []; // drop objects
return timersKilled;
}
// Method is called every time a valid tab change event is received
// callback = code to run when cleanup is finished
// default switch doesn't require callback to be set
tab_switch_cleanup(callback) {
MSP.callbacks_cleanup(); // we don't care about any old data that might or might not arrive
this.interval_kill_all(); // all intervals (mostly data pulling) needs to be removed on tab switch
if (this.active_tab && TABS[this.active_tab]) {
TABS[this.active_tab].cleanup(callback);
} else {
callback();
}
}
switchery() {
const COLOR_ACCENT = 'var(--accent)';
const COLOR_SWITCHERY_SECOND = 'var(--switcherysecond)';
$('.togglesmall').each(function (index, elem) {
const switchery = new Switchery(elem, {
size: 'small',
color: COLOR_ACCENT,
secondaryColor: COLOR_SWITCHERY_SECOND,
});
$(elem).on("change", function () {
switchery.setPosition();
});
$(elem).removeClass('togglesmall');
});
$('.toggle').each(function (index, elem) {
const switchery = new Switchery(elem, {
color: COLOR_ACCENT,
secondaryColor: COLOR_SWITCHERY_SECOND,
});
$(elem).on("change", function () {
switchery.setPosition();
});
$(elem).removeClass('toggle');
});
$('.togglemedium').each(function (index, elem) {
const switchery = new Switchery(elem, {
className: 'switcherymid',
color: COLOR_ACCENT,
secondaryColor: COLOR_SWITCHERY_SECOND,
});
$(elem).on("change", function () {
switchery.setPosition();
});
$(elem).removeClass('togglemedium');
});
}
content_ready(callback) {
this.switchery();
const documentationButton = $('div#content #button-documentation');
documentationButton.html("Wiki");
if (GUI.active_tab !== 'firmware_flasher') { // hack till we have a nice solution for individual wiki URLs for each page
documentationButton.attr("href", "https://github.com/betaflight/betaflight/wiki");
}
// loading tooltip
jQuery(function () {
new jBox('Tooltip', {
attach: '.cf_tip',
trigger: 'mouseenter',
closeOnMouseleave: true,
closeOnClick: 'body',
delayOpen: 100,
delayClose: 100,
position: {
x: 'right',
y: 'center',
},
outside: 'x',
});
new jBox('Tooltip', {
theme: 'Widetip',
attach: '.cf_tip_wide',
trigger: 'mouseenter',
closeOnMouseleave: true,
closeOnClick: 'body',
delayOpen: 100,
delayClose: 100,
position: {
x: 'right',
y: 'center',
},
outside: 'x',
});
});
if (callback) {
callback();
}
}
selectDefaultTabWhenConnected() {
const result = getConfig(['rememberLastTab', 'lastTab']);
const tab = result.rememberLastTab && result.lastTab ? result.lastTab : 'tab_setup';
$(`#tabs ul.mode-connected .${tab} a`).trigger('click');
}
isNWJS() {
return this.Mode === GUI_MODES.NWJS;
}
isCordova() {
return this.Mode === GUI_MODES.Cordova;
}
isOther() {
return this.Mode === GUI_MODES.Other;
}
showYesNoDialog(yesNoDialogSettings) {
// yesNoDialogSettings:
// title, text, buttonYesText, buttonNoText, buttonYesCallback, buttonNoCallback
const dialog = $(".dialogYesNo");
const title = dialog.find(".dialogYesNoTitle");
const content = dialog.find(".dialogYesNoContent");
const buttonYes = dialog.find(".dialogYesNo-yesButton");
const buttonNo = dialog.find(".dialogYesNo-noButton");
title.html(yesNoDialogSettings.title);
content.html(yesNoDialogSettings.text);
buttonYes.html(yesNoDialogSettings.buttonYesText);
buttonNo.html(yesNoDialogSettings.buttonNoText);
buttonYes.off("click");
buttonNo.off("click");
buttonYes.on("click", () => {
dialog[0].close();
yesNoDialogSettings.buttonYesCallback?.();
});
buttonNo.on("click", () => {
dialog[0].close();
yesNoDialogSettings.buttonNoCallback?.();
});
dialog[0].showModal();
}
showWaitDialog(waitDialogSettings) {
// waitDialogSettings:
// title, buttonCancelCallback
const dialog = $(".dialogWait")[0];
const title = $(".dialogWaitTitle");
const buttonCancel = $(".dialogWait-cancelButton");
title.html(waitDialogSettings.title);
buttonCancel.toggle(!!waitDialogSettings.buttonCancelCallback);
buttonCancel.off("click");
buttonCancel.on("click", () => {
dialog.close();
waitDialogSettings.buttonCancelCallback?.();
});
dialog.showModal();
return dialog;
}
showInformationDialog(informationDialogSettings) {
// informationDialogSettings:
// title, text, buttonConfirmText
return new Promise(resolve => {
const dialog = $(".dialogInformation");
const title = dialog.find(".dialogInformationTitle");
const content = dialog.find(".dialogInformationContent");
const buttonConfirm = dialog.find(".dialogInformation-confirmButton");
title.html(informationDialogSettings.title);
content.html(informationDialogSettings.text);
buttonConfirm.html(informationDialogSettings.buttonConfirmText);
buttonConfirm.off("click");
buttonConfirm.on("click", () => {
dialog[0].close();
resolve();
});
dialog[0].showModal();
});
}
saveToTextFileDialog(textToSave, suggestedFileName, extension) {
return new Promise((resolve, reject) => {
const accepts = [{ description: `${extension.toUpperCase()} files`, extensions: [extension] }];
chrome.fileSystem.chooseEntry(
{
type: 'saveFile',
suggestedName: suggestedFileName,
accepts: accepts,
},
entry => this._saveToTextFileDialogFileSelected(entry, textToSave, resolve, reject),
);
});
}
_saveToTextFileDialogFileSelected(entry, textToSave, resolve, reject) {
checkChromeRuntimeError();
if (!entry) {
console.log('No file selected for saving');
resolve(false);
return;
}
entry.createWriter(writer => {
writer.onerror = () => {
reject();
console.error('Failed to write file');
};
writer.onwriteend = () => {
if (textToSave.length > 0 && writer.length === 0) {
writer.write(new Blob([textToSave], { type: 'text/plain' }));
} else {
resolve(true);
console.log('File write complete');
}
};
writer.truncate(0);
},
() => {
reject();
console.error('Failed to get file writer');
});
}
readTextFileDialog(extension) {
const accepts = [{ description: `${extension.toUpperCase()} files`, extensions: [extension] }];
return new Promise(resolve => {
chrome.fileSystem.chooseEntry({ type: 'openFile', accepts: accepts }, function (entry) {
checkChromeRuntimeError();
if (!entry) {
console.log('No file selected for loading');
resolve(false);
return;
}
entry.file((file) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = () => {
console.error(reader.error);
reject();
};
reader.readAsText(file);
});
});
});
}
escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
addLinksTargetBlank(element) {
element.find('a').each(function () {
$(this).attr('target', '_blank');
});
}
}
function GUI_checkOperatingSystem() {
return navigator?.userAgentData?.platform || 'Android';
}
const GUI = new GuiControl();
// initialize object into GUI variable
window.GUI = GUI;
export default GUI;