-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.js
2306 lines (2234 loc) · 74.2 KB
/
main.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
import {
app, BrowserWindow, Menu, TouchBar, ipcMain, dialog, session,
} from 'electron';
import path from 'node:path';
import fs from 'fs-extra';
import yauzl from 'yauzl';
import util from 'node:util';
import { fileURLToPath } from 'node:url';
import log from 'electron-log/main.js';
import menu from './components/menu.js';
import installRPackages from './components/install-r.js';
import { refreshEngineJwt, isTokenExpired } from './components/engine.cjs';
import exampleAppsData from './components/example-apps.js';
import LangParser from './components/LangParser.js';
import addModelData from './components/import-data.js';
import verifyApp from './components/verify-app.js';
import addMiroscen from './components/miroscen-parser.js';
import AppDataStore from './components/AppDataStore.js';
import ConfigManager from './components/ConfigManager.js';
import unzip from './components/Unzip.js';
import MiroProcessManager from './components/MiroProcessManager.js';
import {
getAppDbPath,
} from './components/util.js';
import {
apiVersion, miroVersion, miroRelease, libVersion,
} from './components/globals.js';
const { TouchBarButton, TouchBarSpacer } = TouchBar;
// eslint-disable-next-line no-underscore-dangle
const __dirname = path.dirname(fileURLToPath(import.meta.url));
log.initialize({ preload: true });
const isMac = process.platform === 'darwin';
const DEVELOPMENT_MODE = !app.isPackaged;
const miroWorkspaceDir = path.join(app.getPath('home'), '.miro');
const miroBuildMode = process.env.MIRO_BUILD === 'true';
const miroDevelopMode = process.env.MIRO_DEV_MODE === 'true' || miroBuildMode;
if (!DEVELOPMENT_MODE) {
log.transports.console.level = false;
}
(async () => {
try {
if (!fs.existsSync(miroWorkspaceDir)) {
fs.mkdirSync(miroWorkspaceDir);
}
} catch (e) {
log.error('Could not create miro workspace!');
}
})();
let errMsg;
const appRootDir = DEVELOPMENT_MODE
? app.getAppPath() : path.dirname(process.execPath);
const configData = (() => {
try {
return new ConfigManager(appRootDir, miroWorkspaceDir);
} catch (err) {
errMsg = `Couldn't create configuration file in workspace: ${miroWorkspaceDir}.\
Please make sure you have sufficient permissions and restart MIRO.`;
}
return false;
})();
if (!errMsg) {
(async () => {
const logPath = await configData.get('logpath');
if (!fs.existsSync(logPath)) {
fs.mkdirSync(logPath, { recursive: true });
}
log.transports.file.resolvePathFn = () => (path.join(
logPath,
'launcher.log',
));
log.info(`MIRO launcher (version ${miroVersion} is being started (execPath: ${appRootDir}, \
pid: ${process.pid}, Log path: ${logPath}, \
platform: ${process.platform}, arch: ${process.arch}, \
version: ${process.getSystemVersion()})...`);
})();
}
const appDataPath = errMsg ? null
: path.join(configData.getConfigPath(), 'miro_apps');
const appsData = errMsg ? null
: new AppDataStore(configData.getConfigPath());
const langParser = new LangParser(configData.getSync('language'));
// Set global variables
const lang = langParser.get();
global.lang = lang;
let applicationMenu;
let rPackagesInstalled = true;
let libPath = isMac && !DEVELOPMENT_MODE
? path.resolve(path.join(process.resourcesPath, 'r', 'library'))
: path.join(appRootDir, 'r', 'library');
const miroResourcePath = DEVELOPMENT_MODE ? path.join(app.getAppPath(), 'src')
: path.join(process.resourcesPath, 'src');
const miroProcessManager = new MiroProcessManager(
configData,
miroDevelopMode,
miroBuildMode,
miroResourcePath,
appDataPath,
);
log.info(`MIRO launcher is being started (rootDir: ${appRootDir}, pid: ${process.pid}, \
platform: ${process.platform}, arch: ${process.arch}, \
version: ${process.getSystemVersion()})...`);
let mainWindow;
let settingsWindow;
let checkForUpdateWindow;
let aboutDialogWindow;
let fileToOpen;
let appLoaded = false;
function showErrorMsg(optionsTmp, windowObj = mainWindow) {
if (windowObj) {
const options = optionsTmp;
if (!options.buttons) {
options.buttons = ['OK'];
}
dialog.showMessageBoxSync(windowObj, options);
}
}
function hideZoomMenu() {
if (!applicationMenu) {
return;
}
const editMenuId = isMac ? 3 : 2;
[1, 2, 3].forEach((i) => {
applicationMenu.items[editMenuId].submenu.items[i].enabled = false;
applicationMenu.items[editMenuId].submenu.items[i].visible = false;
});
}
let newAppConf;
function validateMIROApp(filePathArg, sendToRendererProc = true) {
log.debug(`Validating new MIRO app (filePath: ${filePathArg.join(',')}).`);
return new Promise((resolve) => {
const filePath = filePathArg.filter((el) => el.toLowerCase().endsWith('.miroapp'));
if (filePath.length === 0) {
log.error('Validation of MIRO app failed due to invalid file path.');
showErrorMsg({
type: 'info',
title: lang.main.ErrorInvalidHdr,
message: lang.main.ErrorInvalidMsg,
});
resolve(false);
}
if (filePath.length > 1) {
log.error('Validation of MIRO app failed due to invalid file path.');
showErrorMsg({
type: 'info',
title: lang.main.ErrorInvalidHdr,
message: lang.main.ErrorInvalidTwoMsg,
});
resolve(false);
}
yauzl.open(filePath[0], (err, zipfile) => {
const showZipfileError = (e) => {
log.debug(`Problems extracting and validating new MIRO app. Error message: ${e.message}`);
if (mainWindow) {
mainWindow.setProgressBar(-1);
}
showErrorMsg({
type: 'error',
title: lang.main.ErrorUnexpectedHdr,
message: `${lang.main.ErrorReadMsg} '${e.message}'`,
});
resolve(false);
};
if (err) {
resolve(showZipfileError(err));
}
const appFileNames = [];
const incAmt = 0.8 / zipfile.entryCount;
let fileCnt = 0;
let skipCntAppInfo = 0;
let appLogoFound = false;
const appInfoContentPromises = [];
newAppConf = {
modesAvailable: [],
usetmpdir: true,
};
zipfile.on('error', (error) => {
log.error(`MIRO app could not be extracted. Error message: ${error.message}.`);
resolve(showZipfileError(error));
});
zipfile.on('entry', (entry) => {
if (!mainWindow) {
zipfile.close();
}
fileCnt += 1;
mainWindow.setProgressBar(fileCnt * incAmt);
appFileNames.push(entry.fileName);
if (skipCntAppInfo < 2 || appLogoFound === false) {
const filenameInZip = path.basename(entry.fileName.toLowerCase());
const isInStaticDir = path.dirname(entry.fileName).startsWith('static_');
if (filenameInZip === 'miroapp.json' || (isInStaticDir && filenameInZip === 'app_info.json')) {
log.debug(`${filenameInZip} file in new MIRO app found.`);
skipCntAppInfo += 1;
appInfoContentPromises.push(new Promise((resolveData) => {
zipfile.openReadStream(entry, (error, readStream) => {
if (error) {
resolve(showZipfileError(error));
}
const appInfoData = [];
readStream.on('data', (chunk) => {
appInfoData.push(chunk);
});
readStream.on('end', () => {
try {
const jsonData = JSON.parse(Buffer
.concat(appInfoData)
.toString('utf8'));
resolveData({ file: filenameInZip, data: jsonData });
} catch (e) {
if (e instanceof SyntaxError) {
log.debug(`Invalid JSON syntax in ${filenameInZip}. File will be ignored. Error message: ${e.message}`);
} else {
log.warn(`Unexpected error occurred while reading ${filenameInZip}. Error message: ${e.message}`);
}
showErrorMsg({
type: 'error',
title: lang.main.ErrorUnexpectedHdr,
message: `${lang.main.ErrorReadMsg} '${e.message}'`,
});
resolve(false);
}
});
});
}));
}
if (isInStaticDir) {
const logoExt = filenameInZip.match(/.*_logo\.(jpg|jpeg|png)$/);
if (logoExt) {
if (appLogoFound === true && filenameInZip !== `app_logo.${logoExt[1]}`) {
// multiple logos in app found, using app_logo if available
return;
}
appLogoFound = true;
newAppConf.logoPath = entry.fileName;
log.debug('Logo in new MIRO app found.');
const logoPathTmp = path.join(app.getPath('temp'), `logo.${logoExt[1]}`);
zipfile.openReadStream(entry, (error, readStream) => {
if (error) {
resolve(showZipfileError(error));
}
readStream.pipe(fs.createWriteStream(logoPathTmp));
readStream.on('end', () => {
newAppConf.logoPathTmp = logoPathTmp;
if (mainWindow && sendToRendererProc) {
mainWindow.webContents.send('validated-logo-received', { path: logoPathTmp });
}
});
});
}
}
}
});
zipfile.once('end', async () => {
log.debug('New MIRO app extracted successfully.');
let invalidMiroApp = false;
const errMsgTemplate = 'The MIRO app you want to add is invalid. Please make sure to upload a valid MIRO app!';
let appMetadata = null;
const appInfoContent = await Promise.all(appInfoContentPromises);
appInfoContent.forEach((content) => {
if (content.file === 'miroapp.json') {
appMetadata = content.data;
return;
}
if (content.file === 'app_info.json') {
newAppConf.title = content.data.title;
newAppConf.description = content.data.description;
newAppConf.id = content.data.appId;
}
});
const validateAppId = (appIdToValidate) => {
if (typeof appIdToValidate === 'string' || appIdToValidate instanceof String) {
if (/^[a-z0-9][a-z0-9-_]{0,59}$/.test(appIdToValidate)) {
return true;
}
}
log.warn("The App ID may only contain ASCII lowercase letters, digits, '-' and '_', must not start with '-' or '_' and may not be longer than 60 characters! Invalid app.");
return false;
};
if (appMetadata == null) {
// old app (< MIRO 2.3)
const miroConfFormat = /(.*)_(\d)_(\d+)_(\d+\.\d+\.\d+)(_hcube)?\.miroconf$/;
// eslint-disable-next-line no-restricted-syntax
for (const fileName of appFileNames) {
if (path.dirname(fileName) === '.' && fileName.endsWith('.miroconf')) {
const miroConfMatch = fileName.match(miroConfFormat);
if (miroConfMatch && miroConfMatch[1].length) {
if (miroConfMatch[5]) {
log.warn('Hypercube configuration found in app bundle. It will be ignored because the Hypercube Mode is no longer supported as of MIRO 2.2.');
} else {
if (newAppConf.modesAvailable.includes('base')) {
log.warn('Multiple base configurations found in app bundle. Invalid app.');
invalidMiroApp = true;
break;
}
log.debug('Base mode configuration in new MIRO app found.');
newAppConf.modesAvailable.push('base');
newAppConf.usetmpdir = miroConfMatch[2] === '1';
[newAppConf.path] = filePath;
[, , , , newAppConf.miroversion] = miroConfMatch;
if (newAppConf.id == null) {
[, newAppConf.id] = miroConfMatch;
}
newAppConf.gmsName = `${newAppConf.id}.gms`;
newAppConf.apiversion = parseInt(miroConfMatch[3], 10);
if (!validateAppId(newAppConf.id)) {
invalidMiroApp = true;
break;
}
log.info(`New MIRO app successfully identified. Id: ${newAppConf.id}, \
API version: ${newAppConf.apiversion}, \
MIRO version: ${newAppConf.miroversion}.`);
}
} else {
log.debug(`Invalid MIROconf file found in new MIRO app: ${fileName}.`);
invalidMiroApp = true;
break;
}
}
}
} else {
// new app (MIRO >=2.3)
if (!['use_temp_dir', 'miro_version', 'api_version', 'modes_included', 'main_gms_name'].every((requiredKey) => Object.prototype.hasOwnProperty.call(appMetadata, requiredKey))) {
log.warn('App info file does not contain all the required information.');
if (mainWindow) {
mainWindow.setProgressBar(-1);
}
showErrorMsg({
type: 'info',
title: lang.main.ErrorInvalidThreeMsg,
message: errMsgTemplate,
});
resolve(false);
}
const miroConfFormatBase = /(.*)_(\d)_(\d+)_(\d+\.\d+\.\d+)\.miroconf$/;
if (!appFileNames.includes('.miroconf')
&& appFileNames.findIndex((fileName) => fileName.match(miroConfFormatBase)) === -1) {
log.warn('No valid miroconf file found.');
if (mainWindow) {
mainWindow.setProgressBar(-1);
}
showErrorMsg({
type: 'info',
title: lang.main.ErrorInvalidThreeMsg,
message: errMsgTemplate,
});
resolve(false);
return;
}
newAppConf.modesAvailable.push('base');
newAppConf.usetmpdir = appMetadata.use_temp_dir === true;
newAppConf.miroversion = appMetadata.miro_version;
newAppConf.apiversion = parseInt(appMetadata.api_version, 10);
if (newAppConf.id == null) {
newAppConf.id = path.parse(appMetadata.main_gms_name).name.toLowerCase();
}
newAppConf.gmsName = appMetadata.main_gms_name;
[newAppConf.path] = filePath;
if (!validateAppId(newAppConf.id)) {
if (mainWindow) {
mainWindow.setProgressBar(-1);
}
showErrorMsg({
type: 'info',
title: lang.main.ErrorInvalidThreeMsg,
message: errMsgTemplate,
});
resolve(false);
}
log.info(`New MIRO app successfully identified. Id: ${newAppConf.id}, \
API version: ${newAppConf.apiversion}, \
MIRO version: ${newAppConf.miroversion}.`);
}
if (mainWindow) {
mainWindow.setProgressBar(0.9);
}
if (!newAppConf.apiversion || invalidMiroApp) {
if (mainWindow) {
mainWindow.setProgressBar(-1);
}
showErrorMsg({
type: 'info',
title: lang.main.ErrorInvalidThreeMsg,
message: errMsgTemplate,
});
resolve(false);
return;
}
if (!ConfigManager.vComp(miroVersion, newAppConf.miroversion)) {
if (mainWindow) {
mainWindow.setProgressBar(-1);
}
showErrorMsg({
type: 'info',
title: lang.main.ErrorAPIHdr,
message: lang.main.ErrorVersionMsg,
});
resolve(false);
return;
}
if (!newAppConf.apiversion
|| newAppConf.apiversion !== apiVersion) {
if (mainWindow) {
mainWindow.setProgressBar(-1);
}
showErrorMsg({
type: 'info',
title: lang.main.ErrorAPIHdr,
message: lang.main.ErrorAPIMsg,
});
resolve(false);
return;
}
if (mainWindow) {
mainWindow.setProgressBar(-1);
}
if (sendToRendererProc) {
if (mainWindow) {
log.debug('New MIRO app configuration sent to renderer process.');
mainWindow.webContents.send('app-validated', newAppConf);
resolve(true);
} else {
resolve(false);
}
} else {
resolve(newAppConf);
}
});
});
});
}
function validateAppLogo(filePath, id = null) {
log.debug(`Request to validate MIRO app logo received (file path: ${filePath}, id: ${id}).`);
const filteredPath = filePath.filter((el) => el
.toLowerCase()
.match(/\.(jpg|jpeg|png)$/));
if (filteredPath.length === 0) {
log.info('App logo not valid due to bad format.');
showErrorMsg({
type: 'info',
title: lang.main.ErrorLogoHdr,
message: lang.main.ErrorLogoMsg,
});
return;
} if (filteredPath.length > 1) {
log.info('App logo not valid due to multiple files being dropped.');
showErrorMsg({
type: 'info',
title: lang.main.ErrorLogoHdr,
message: lang.main.ErrorLogoMultiMsg,
});
return;
}
const logoSize = fs.statSync(filteredPath[0]).size / 1000000.0;
if (logoSize > 10) {
log.info(`App logo not valid due to file size being too large (${logoSize}MB)`);
showErrorMsg({
type: 'info',
title: lang.main.ErrorLogoLargeHdr,
message: lang.main.ErrorLogoLargeMsg,
});
return;
}
log.info('MIRO app logo successfully validate.');
mainWindow.webContents.send(
'validated-logopath-received',
{ id, path: filteredPath[0] },
);
}
function addExampleApps() {
const examplesToAdd = exampleAppsData
.filter((exampleApp) => appsData.isUniqueId(exampleApp.id));
const examplesToAddNames = examplesToAdd.map((exampleApp) => exampleApp.id);
const examplesSkipped = exampleAppsData
.filter((exampleApp) => !examplesToAddNames.includes(exampleApp.id))
.map((exampleApp) => exampleApp.id);
if (examplesToAddNames.length === 0) {
log.debug('All example models already exist. Nothing was added.');
return showErrorMsg({
type: 'info',
title: lang.main.ErrorExampleExistsHdr,
message: `${lang.main.ErrorModelExistsMsg} ${examplesSkipped.toString()}`,
});
}
fs.copy(
path.join(miroResourcePath, 'examples'),
appDataPath,
(e) => {
if (e) {
log.error(`Unexpected error while copying example apps from: \
${path.join(miroResourcePath, 'examples')} to: ${appDataPath}. Error mesage: ${e.message}`);
if (e.code === 'EACCES') {
showErrorMsg({
type: 'error',
title: lang.main.ErrorWriteHdr,
message: `${lang.main.ErrorWriteMsg} '${appDataPath}.'`,
});
return;
}
showErrorMsg({
type: 'error',
title: lang.main.ErrorUnexpectedHdr,
message: `${lang.main.ErrorUnexpectedMsg2} '${e.message}'`,
});
return;
}
try {
examplesToAdd.forEach((exampleApp) => {
appsData.addApp(exampleApp);
});
const updatedApps = appsData.getApps();
mainWindow.send('apps-received', updatedApps, appDataPath);
} catch (err) {
log.error(`Problems writing app data: \
${path.join(miroResourcePath, 'examples')} to: ${appDataPath}. Error mesage: ${err.message}`);
if (err.code === 'EACCES') {
showErrorMsg({
type: 'error',
title: lang.main.ErrorWriteHdr,
message: `${lang.main.ErrorWriteMsg} '${configData.getConfigPath()}.'`,
});
return;
}
showErrorMsg({
type: 'error',
title: lang.main.ErrorUnexpectedHdr,
message: `${lang.main.ErrorUnexpectedMsg2} '${err.message}'`,
});
}
},
);
log.debug(`Example models: ${examplesToAddNames.toString()} added to library.`);
if (examplesSkipped.length) {
return showErrorMsg({
type: 'info',
title: lang.main.ErrorExampleExistsHdr,
message: `${lang.main.ErrorModelExistsMsg} ${examplesSkipped.toString()}`,
});
}
return null;
}
function activateEditMode(openNewAppForm = false, scrollToBottom = false) {
log.debug(`Activating edit mode. Open 'new app' form: ${openNewAppForm}.`);
if (mainWindow) {
mainWindow.send('activate-edit-mode', openNewAppForm, scrollToBottom);
}
}
async function updateMIROApp(newAppParam, appIdToUpdate = null) {
const newApp = newAppParam;
if (newApp === false) {
if (appIdToUpdate != null) {
mainWindow.send('add-app-progress', -1, appIdToUpdate);
}
log.debug('Error updating app (validation failed).');
return;
}
if (appIdToUpdate != null && appIdToUpdate !== newApp.id) {
if (appIdToUpdate.toLowerCase() === newApp.id.toLowerCase()) {
log.info(`App was dropped on legacy (MIRO < 2.5.2) app with ID that includes uppercase letters ('${appIdToUpdate}'). Changing app ID accordingly.`);
newApp.id = appIdToUpdate;
} else {
mainWindow.send('add-app-progress', -1, appIdToUpdate);
log.info('Error updating app (app was dropped on app with different ID).');
showErrorMsg({
type: 'info',
title: lang.main.AppIdConflictHdr,
message: util.format(lang.main.AppIdConflictMsg, newApp.id, appIdToUpdate),
});
return;
}
}
const overwriteData = dialog.showMessageBoxSync(
mainWindow,
{
type: 'info',
title: lang.main.OverwriteDataHdr,
message: lang.main.OverwriteDataMsg,
buttons: [lang.main.BtnCancel, lang.main.OverwriteDataBtnYes, lang.main.OverwriteDataBtnNo],
cancelId: 0,
},
);
if (overwriteData === 0) {
mainWindow.send('add-app-progress', -1, newApp.id);
log.debug('Updating app interrupted.');
return;
}
let appConf;
try {
appConf = appsData.getAppConfig(newApp.id);
} catch (err) {
log.error('The app to be updated does not exist. This should not happen!');
mainWindow.send('add-app-progress', -1, newApp.id);
showErrorMsg({
type: 'error',
title: lang.main.ErrorUnexpectedHdr,
message: `${lang.main.ErrorUnexpectedMsg2} '${err.message}'`,
});
return;
}
mainWindow.send('add-app-progress', 0, newApp.id);
mainWindow.setProgressBar(0);
const appDir = path.join(appDataPath, appConf.id);
const appDirTmp = path.join(appDataPath, `~$${appConf.id}`);
const appDirTmp2 = path.join(appDataPath, `~$~$${appConf.id}`);
try {
[appDirTmp, appDirTmp2].forEach((dirName) => {
if (fs.existsSync(dirName)) {
fs.rmSync(dirName, { recursive: true });
}
});
} catch (err) {
mainWindow.send('add-app-progress', -1, newApp.id);
mainWindow.setProgressBar(-1);
log.error(`Problems removing existing temporary app directories. Error message: ${err.message}.`);
showErrorMsg({
type: 'error',
title: lang.main.ErrorUnexpectedHdr,
message: `${lang.main.ErrorUnexpectedMsg2} '${err.message}'`,
});
return;
}
try {
await unzip(newApp.path, appDirTmp);
const appValid = await verifyApp(configData, libPath, miroResourcePath, mainWindow, appDirTmp);
if (appValid !== true) {
log.info(`The app: ${newApp.id} could not be validated. Aborting.`);
throw new Error('suppress');
}
appConf.miroversion = newApp.miroversion;
appConf.usetmpdir = newApp.usetmpdir;
await addModelData(
miroProcessManager,
{
libPath,
dbpath: appConf.dbpath,
appDir: appDirTmp,
},
appConf.id,
appConf.miroversion,
appConf.usetmpdir,
mainWindow,
'',
'add-app-progress',
overwriteData === 1,
true,
);
} catch (err) {
mainWindow.send('add-app-progress', -1, newApp.id);
mainWindow.setProgressBar(-1);
try {
if (fs.existsSync(appDirTmp)) {
fs.rmSync(appDirTmp, { recursive: true });
}
} catch (errRm) {
log.error(`Problems removing temporary app directory: ${appDirTmp}. Error message: ${errRm.message}.`);
}
if (err.message === 'suppress') {
return;
}
log.error(`Update app request failed. Error message: ${err.message}`);
if (err.code === 'EACCES') {
showErrorMsg({
type: 'error',
title: lang.main.ErrorWriteHdr,
message: `${lang.main.ErrorWritePerm2Msg} '${configData.getConfigPath()}.'`,
});
return;
}
showErrorMsg({
type: 'error',
title: lang.main.ErrorUnexpectedHdr,
message: `${lang.main.ErrorUnexpectedMsg2} '${err.message}'`,
});
return;
}
try {
fs.renameSync(appDir, appDirTmp2);
fs.renameSync(appDirTmp, appDir);
if (appConf.logoPath != null) {
if (!fs.existsSync(path.dirname(path.join(appDir, appConf.logoPath)))) {
fs.mkdirSync(path.dirname(path.join(appDir, appConf.logoPath)));
}
fs.copyFileSync(path.join(appDirTmp2, appConf.logoPath), path.join(appDir, appConf.logoPath));
}
appsData.updateApp(appConf);
try {
const cacheContent = await fs.promises.readdir(path.join(miroWorkspaceDir, 'cache'));
const removeCacheFilePromises = cacheContent
.filter((cacheFile) => cacheFile.startsWith(`${newApp.id}_`))
.forEach((cacheFile) => fs.promises.unlink(path.join(miroWorkspaceDir, 'cache', cacheFile)));
if (removeCacheFilePromises != null) {
await Promise.all(removeCacheFilePromises);
}
} catch (err) {
if (err.code !== 'ENOENT') {
log.error(`Problems removing cache! Error message: '${err.message}'.`);
}
}
const promiseRmTmpDir = fs.promises.rm(appDirTmp2, { recursive: true });
mainWindow.send('apps-received', appsData.getApps(), appDataPath);
await promiseRmTmpDir;
} catch (err) {
log.error(`Problems replacing app directory. Error message: ${err.message}.`);
showErrorMsg({
type: 'error',
title: lang.main.ErrorUnexpectedHdr,
message: `${lang.main.ErrorUnexpectedMsg2} '${err.message}'`,
});
return;
} finally {
mainWindow.send('add-app-progress', -1, newApp.id);
mainWindow.setProgressBar(-1);
}
}
async function addOrUpdateMIROApp(filePath) {
const newApp = await validateMIROApp([filePath], false);
if (newApp === false) {
log.debug('Error adding/updating app (validation failed).');
return;
}
if (appsData.isUniqueId(newApp.id)) {
log.debug(`Received MIROAPP file for new MIRO app with ID: ${newApp.id}.`);
activateEditMode(false, true);
if (mainWindow) {
mainWindow.webContents.send('app-validated', newApp);
}
return;
}
const existingAppIds = appsData.getApps().map((t) => t.id);
const appIdx = existingAppIds.findIndex((t) => t.toLowerCase() === newApp.id.toLowerCase());
if (appIdx === -1) {
log.debug('Error updating app: Could not find index of existing app. This should never happen..');
return;
}
log.debug(`Received MIROAPP file for already existing MIRO app with ID: ${existingAppIds[appIdx]}.`);
await updateMIROApp(newApp, existingAppIds[appIdx]);
}
async function addMiroscenFile(filePath) {
let miroscenPath = filePath;
if (!miroscenPath) {
miroscenPath = dialog.showOpenDialogSync(mainWindow, {
title: lang.dialogNewScenFilesHdr,
message: lang.dialogNewScenFilesMsg,
buttonLabel: lang.dialogNewScenFilesBtn,
properties: ['openFile'],
filters: [
{ name: lang.dialogNewScenFilesFilter, extensions: ['miroscen'] },
],
});
if (!miroscenPath || miroscenPath.length === 0) {
return;
}
[miroscenPath] = miroscenPath;
}
if (miroscenPath) {
if (!miroscenPath.toLowerCase().endsWith('.miroscen')) {
log.debug('Incorrect file type discovered when trying to add MIRO scenario.');
showErrorMsg({
type: 'error',
title: lang.main.ErrorNewScenHdr,
message: `${lang.main.ErrorNewScenMsg}Incorrect file type`,
});
return;
}
mainWindow.send('toggle-loading-screen-progress', 'show');
try {
await addMiroscen(
miroProcessManager,
miroscenPath,
mainWindow,
{
libPath,
appDataPath,
},
appsData,
);
} catch (e) {
log.info(`Problems adding MIRO scenario. Error message: ${e.toString()}.`);
showErrorMsg({
type: 'error',
title: lang.main.ErrorNewScenHdr,
message: lang.main.ErrorNewScenMsg + e.toString(),
});
} finally {
mainWindow.setProgressBar(-1);
mainWindow.send('toggle-loading-screen-progress', 'hide');
}
}
}
const btAddApp = new TouchBarButton({
label: lang.menu.addApp,
backgroundColor: '#F39619',
click: () => {
log.debug('Add new MIRO app button clicked on TouchBar.');
activateEditMode(true, true);
},
});
const btManageApps = new TouchBarButton({
label: lang.menu.editApp,
click: () => {
log.debug('Edit apps button clicked on TouchBar.');
activateEditMode();
},
});
const btAddMiroscen = new TouchBarButton({
label: lang.menu.addMiroScen,
backgroundColor: '#F39619',
click: async () => {
log.debug('Add new MIRO scenario button clicked on TouchBar.');
await addMiroscenFile();
},
});
const mainWindowTouchBar = new TouchBar({
items: [
btAddApp,
btManageApps,
new TouchBarSpacer({ size: 'large' }),
btAddMiroscen,
],
});
const dockMenu = Menu.buildFromTemplate([
{
label: lang.menu.addApp,
click: () => {
log.debug('Add new MIRO app button clicked in dock menu.');
activateEditMode(true, true);
},
},
{
label: lang.menu.editApp,
click: () => {
log.debug('Edit apps button clicked in dock menu.');
activateEditMode();
},
},
{
label: lang.menu.addMiroScen,
click: async () => {
log.debug('Add new MIRO scenario button clicked in dock menu.');
await addMiroscenFile();
},
},
]);
function createSettingsWindow() {
log.debug('Creating settings window..');
if (settingsWindow) {
log.debug('Settings window already open.');
settingsWindow.show();
return;
}
settingsWindow = new BrowserWindow({
title: lang.settings.title,
width: 570,
height: 710,
resizable: DEVELOPMENT_MODE,
titleBarStyle: process.platform === 'darwin' ? 'hidden' : null,
show: false,
frame: false,
icon: process.platform === 'linux' ? path.join(__dirname, 'static', 'icon_64x64.png') : undefined,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
enableRemoteModule: false,
},
});
settingsWindow.loadFile(path.join(
__dirname,
'renderer',
'settings.html',
));
settingsWindow.once('ready-to-show', async () => {
log.debug('Settings window ready to show.');
settingsWindow.webContents.send(
'settings-loaded',
await configData.getAll(),
await configData.getAll(true),
lang.settings,
);
log.debug('Settings window settings loaded.');
settingsWindow.show();
});
if (DEVELOPMENT_MODE) {
settingsWindow.webContents.openDevTools();
}
settingsWindow.on('page-title-updated', (e) => {
e.preventDefault();
});
settingsWindow.on('closed', () => {
log.debug('Settings window closed.');
settingsWindow = null;
});
}
function openAboutDialog() {
log.debug('Creating about dialog window..');
if (aboutDialogWindow) {
log.debug('About dialog already open.');
aboutDialogWindow.show();
return;
}
aboutDialogWindow = new BrowserWindow({
title: 'About GAMS MIRO',
width: 600,
height: 380,
resizable: false,
show: false,
frame: false,
icon: process.platform === 'linux' ? path.join(__dirname, 'static', 'icon_64x64.png') : undefined,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
enableRemoteModule: false,
},
});
aboutDialogWindow.loadFile(
path.join(
__dirname,
'renderer',
'about.html',
),
{
query: {
miroVersion,
miroRelease,
btClose: lang.update.btClose,
},
},
);
aboutDialogWindow.once('ready-to-show', async () => {
log.debug('About dialog ready to show.');
aboutDialogWindow.show();
});
aboutDialogWindow.on('page-title-updated', (e) => {
e.preventDefault();
});
aboutDialogWindow.on('closed', () => {
log.debug('About dialog closed.');
aboutDialogWindow = null;
});
}
function openCheckUpdateWindow() {
log.debug('Creating Check for Update window..');
if (checkForUpdateWindow) {
log.debug('Check for Update window already open.');
checkForUpdateWindow.show();
return;
}
checkForUpdateWindow = new BrowserWindow({
title: lang.update.title,
width: 400,
height: 200,
resizable: false,
titleBarStyle: process.platform === 'darwin' ? 'hidden' : null,
show: false,
frame: false,
icon: process.platform === 'linux' ? path.join(__dirname, 'static', 'icon_64x64.png') : undefined,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
enableRemoteModule: false,
},
});
checkForUpdateWindow.loadFile(path.join(
__dirname,
'renderer',
'update.html',
), { query: { miroVersion } });
checkForUpdateWindow.once('ready-to-show', async () => {
log.debug('Check for Update window ready to show.');
checkForUpdateWindow.send('lang-data-received', lang.update);
checkForUpdateWindow.show();
});
checkForUpdateWindow.on('page-title-updated', (e) => {
e.preventDefault();
});
checkForUpdateWindow.on('closed', () => {
log.debug('Check for Update window closed.');
checkForUpdateWindow = null;