This repository has been archived by the owner on May 22, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathindex.js
900 lines (744 loc) · 31.2 KB
/
index.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
/*
index.js
*/
// built\-in modules
let fs = require('fs');
let path = require('path');
let electron = require('electron');
let os = require('os');
let app = electron.app; // Module to control application life.
let BrowserWindow = electron.BrowserWindow;
let crashReporter = electron.crashReporter;
let globalShortcut = electron.globalShortcut;
let ipc = electron.ipcMain;
let Menu = electron.Menu;
// npm modules
let _ = require('underscore');
let minimist = require('minimist');
// local modules
let Application = require('./src/browser/api/application.js').Application;
let System = require('./src/browser/api/system.js').System;
import { Window } from './src/browser/api/window';
let apiProtocol = require('./src/browser/api_protocol');
import socketServer from './src/browser/transports/socket_server';
import { addPendingAuthRequests, createAuthUI } from './src/browser/authentication_delegate';
let convertOptions = require('./src/browser/convert_options.js');
import * as coreState from './src/browser/core_state';
let webRequestHandlers = require('./src/browser/web_request_handler.js');
let errors = require('./src/common/errors.js');
import ofEvents from './src/browser/of_events';
import {
portDiscovery
} from './src/browser/port_discovery';
import { reservedHotKeys } from './src/browser/api/global_hotkey';
import {
default as connectionManager,
meshEnabled,
getMeshUuid,
isMeshEnabledRuntime
} from './src/browser/connection_manager';
import * as log from './src/browser/log';
import {
applyAllRemoteSubscriptions
} from './src/browser/remote_subscriptions';
import route from './src/common/route';
import { createWillDownloadEventListener } from './src/browser/api/file_download';
import duplicateUuidTransport from './src/browser/duplicate_uuid_delegation';
import { deleteApp } from './src/browser/core_state';
import { lockUuid } from './src/browser/uuid_availability';
// locals
let firstApp = null;
let rvmBus;
let otherInstanceRunning = false;
let appIsReady = false;
const deferredLaunches = [];
let resolveServerReady;
const serverReadyPromise = new Promise((resolve) => {
resolveServerReady = () => resolve();
});
//Event either comes from the runtime or the core when registering an externalWindow.
// Payload is a browserWindow id
app.on('child-window-created', function(parentBwId, childBwId, childOptions) {
const parent = BrowserWindow.fromId(parentBwId);
const child = BrowserWindow.fromId(childBwId);
const parentId = parent.webContents.id;
const childId = child.webContents.id;
if (!coreState.addChildToWin(parentId, childId)) {
console.warn('failed to add');
}
Window.create(childId, childOptions);
});
app.on('select-client-certificate', function(event, webContents, url, list, callback) {
// No need to choose if there are
// fewer than two certificates
if (list.length < 2) {
return;
}
event.preventDefault();
let clientCertDialog = new BrowserWindow({
width: 450,
height: 280,
show: false,
frame: false,
skipTaskbar: true,
resizable: false,
alwaysOnTop: true,
webPreferences: {
nodeIntegration: true,
openfinIntegration: false
}
});
let ipcUuid = app.generateGUID();
let ipcTopic = 'client-certificate-selection/' + ipcUuid;
function resolve(cert) {
cleanup();
callback(cert);
}
function cleanup() {
ipc.removeListener(ipcTopic, onClientCertificateSelection);
clientCertDialog.removeListener('closed', onClosed);
}
function onClientCertificateSelection(event, index) {
if (index >= 0 && index < list.length) {
resolve(list[index]);
clientCertDialog.close();
}
}
function onClosed() {
resolve({}); // NOTE: Will cause a page load failure
}
ipc.on(ipcTopic, onClientCertificateSelection);
clientCertDialog.on('closed', onClosed);
let params = '?url=' + encodeURIComponent(url) + '&uuid=' + encodeURIComponent(ipcUuid) + '&certs=' + encodeURIComponent(_.pluck(list, 'issuerName'));
clientCertDialog.loadURL(path.resolve(__dirname, 'assets', 'certificate.html') + params);
});
portDiscovery.on(route.runtime('launched'), (portInfo) => {
//check if the ports match:
const myPortInfo = coreState.getSocketServerState();
const myUuid = getMeshUuid();
log.writeToLog('info', `Port discovery message received ${JSON.stringify(portInfo)}`);
//TODO include old runtimes in the determination.
if (meshEnabled && portInfo.port !== myPortInfo.port && isMeshEnabledRuntime(portInfo)) {
connectionManager.connectToRuntime(myUuid, portInfo).then((runtimePeer) => {
//one connected we broadcast our port discovery message.
staggerPortBroadcast(myPortInfo);
log.writeToLog('info', `Connected to runtime ${JSON.stringify(runtimePeer.portInfo)}`);
applyAllRemoteSubscriptions(runtimePeer);
}).catch(err => {
log.writeToLog('info', `Failed to connect to runtime ${JSON.stringify(portInfo)}, ${JSON.stringify(errors.errorToPOJO(err))}`);
});
}
});
includeFlashPlugin();
// Opt in to launch crash reporter
initializeCrashReporter(coreState.argo);
initializeDiagnosticReporter(coreState.argo);
// Safe errors initialization
errors.initSafeErrors(coreState.argo);
// Has a local copy of an app config
if (coreState.argo['local-startup-url']) {
try {
// Use this version of the fs module because the decorated version checks if the file
// has a matching signature file
const originalFs = require('original-fs');
let localConfig = JSON.parse(originalFs.readFileSync(coreState.argo['local-startup-url']));
if (typeof localConfig['devtools_port'] === 'number') {
if (!coreState.argo['remote-debugging-port']) {
log.writeToLog(1, `remote-debugging-port: ${localConfig['devtools_port']}`, true);
app.commandLine.appendSwitch('remote-debugging-port', localConfig['devtools_port'].toString());
} else {
log.writeToLog(1, 'Ignoring devtools_port from manifest', true);
}
}
} catch (err) {
log.writeToLog(1, err, true);
}
}
const handleDelegatedLaunch = function(commandLine) {
let otherInstanceArgo = minimist(commandLine);
initializeCrashReporter(otherInstanceArgo);
log.writeToLog('info', 'handling delegated launch with the following args');
log.writeToLog('info', JSON.stringify(otherInstanceArgo));
// delegated args from a second instance
launchApp(otherInstanceArgo, false);
// Will queue if server is not ready.
serverReadyPromise.then(() => {
const socketServerState = coreState.getSocketServerState();
const portInfo = portDiscovery.getPortInfoByArgs(otherInstanceArgo, socketServerState.port);
portDiscovery.broadcast(portInfo);
});
// command line flag --delete-cache-on-exit
rvmCleanup(otherInstanceArgo);
return true;
};
function handleDeferredLaunches() {
deferredLaunches.forEach((commandLine) => {
handleDelegatedLaunch(commandLine);
});
deferredLaunches.length = 0;
}
otherInstanceRunning = !app.requestSingleInstanceLock();
if (otherInstanceRunning) {
if (appIsReady) {
deleteProcessLogfile(true);
}
app.commandLine.appendArgument('noerrdialogs');
process.argv.push('--noerrdialogs');
app.exit(0);
} else {
app.on('second-instance', (event, commandLine, workingDirectory) => {
log.writeToLog(1, `second-instance callback ${commandLine}`, true);
const socketServerState = coreState.getSocketServerState();
if (appIsReady && socketServerState && socketServerState.port) {
return handleDelegatedLaunch(commandLine);
} else {
deferredLaunches.push(commandLine);
return true;
}
});
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', function() {
appIsReady = true;
if (otherInstanceRunning) {
deleteProcessLogfile(true);
app.quit();
return;
}
app.registerNamedCallback('convertToElectron', convertOptions.convertToElectron);
// Runtime will use BrowserWindow id
app.registerNamedCallback('getWindowOptionsById', coreState.getWindowOptionsByBrowserWindowId);
if (process.platform === 'win32') {
log.writeToLog('info', `group-policy build: ${process.buildFlags.groupPolicy}`);
log.writeToLog('info', `enable-chromium build: ${process.buildFlags.enableChromium}`);
}
log.writeToLog('info', `build architecture: ${process.arch}`);
app.vlog(1, 'process.versions: ' + JSON.stringify(process.versions, null, 2));
rvmBus = require('./src/browser/rvm/rvm_message_bus').rvmMessageBus;
electron.session.defaultSession.allowNTLMCredentialsForDomains('*');
if (process.platform === 'win32') {
let integrityLevel = app.getIntegrityLevel();
System.log('info', `Runtime integrity level of the app: ${integrityLevel}`);
}
rotateLogs(coreState.argo);
migrateCookies();
migrateLocalStorage(coreState.argo);
//Once we determine we are the first instance running we setup the API's
//Create the new Application.
initServer();
duplicateUuidTransport.init(handleDelegatedLaunch);
webRequestHandlers.initHandlers();
launchApp(coreState.argo, true);
registerShortcuts();
registerMacMenu();
app.on('activate', function() {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
launchApp(coreState.argo, true);
});
//subscribe to auth requests:
app.on('login', (event, webContents, request, authInfo, callback) => {
let browserWindow = webContents.getOwnerBrowserWindow();
let ofWindow = coreState.getWinById(browserWindow.webContents.id).openfinWindow;
let identity = {
name: ofWindow._options.name,
uuid: ofWindow._options.uuid
};
const windowEvtName = route.window('auth-requested', identity.uuid, identity.name);
const appEvtName = route.application('window-auth-requested', identity.uuid);
addPendingAuthRequests(identity, authInfo, callback);
if (ofEvents.listeners(windowEvtName).length < 1 && ofEvents.listeners(appEvtName).length < 1) {
createAuthUI(identity);
} else {
ofEvents.emit(windowEvtName, {
topic: 'window',
type: 'auth-requested',
uuid: identity.uuid,
name: identity.name,
authInfo: authInfo
});
}
event.preventDefault();
});
// native code in AtomRendererClient::ShouldFork
app.on('enable-chromium-renderer-fork', event => {
// @TODO it should be an option for app, not runtime->arguments
if (coreState.argo['enable-chromium-renderer-fork']) {
app.vlog(1, 'applying Chromium renderer fork');
event.preventDefault();
}
});
rvmBus.on(route.rvmMessageBus('broadcast', 'download-asset', 'progress'), payload => {
if (payload) {
ofEvents.emit(route.system(`asset-download-progress-${payload.downloadId}`), {
totalBytes: payload.totalBytes,
downloadedBytes: payload.downloadedBytes
});
}
});
rvmBus.on(route.rvmMessageBus('broadcast', 'download-asset', 'error'), payload => {
if (payload) {
ofEvents.emit(route.system(`asset-download-error-${payload.downloadId}`), {
reason: payload.error,
err: errors.errorToPOJO(new Error(payload.error))
});
}
});
rvmBus.on(route.rvmMessageBus('broadcast', 'download-asset', 'complete'), payload => {
if (payload) {
ofEvents.emit(route.system(`asset-download-complete-${payload.downloadId}`), {
path: payload.path
});
}
});
rvmBus.on(route.rvmMessageBus('broadcast', 'application', 'runtime-download-progress'), payload => {
if (payload) {
ofEvents.emit(route.system(`runtime-download-progress-${ payload.downloadId }`), payload);
}
});
rvmBus.on(route.rvmMessageBus('broadcast', 'application', 'runtime-download-error'), payload => {
if (payload) {
ofEvents.emit(route.system(`runtime-download-error-${ payload.downloadId }`), {
reason: payload.error,
err: errors.errorToPOJO(new Error(payload.error))
});
}
});
rvmBus.on(route.rvmMessageBus('broadcast', 'application', 'runtime-download-complete'), payload => {
if (payload) {
ofEvents.emit(route.system(`runtime-download-complete-${ payload.downloadId }`), {
path: payload.path
});
}
});
try {
electron.session.defaultSession.on('will-download', (event, item, webContents) => {
try {
const { uuid, name } = webContents.browserWindowOptions;
const downloadListener = createWillDownloadEventListener({ uuid, name });
downloadListener(event, item, webContents);
} catch (err) {
log.writeToLog('info', 'Error while processing will-download event.');
log.writeToLog('info', err);
}
});
} catch (err) {
log.writeToLog('info', 'Could not wire up File Download API');
log.writeToLog('info', err);
}
handleDeferredLaunches();
logSystemMemoryInfo();
}); // end app.ready
} // else !otherInstanceRunning
function staggerPortBroadcast(myPortInfo) {
setTimeout(() => {
try {
portDiscovery.broadcast(myPortInfo);
} catch (e) {
log.writeToLog('info', e);
}
}, Math.floor(Math.random() * 50));
}
function includeFlashPlugin() {
let pluginName;
switch (process.platform) {
case 'win32':
pluginName = 'pepflashplayer.dll';
break;
case 'darwin':
pluginName = 'PepperFlashPlayer.plugin';
break;
case 'linux':
pluginName = 'libpepflashplayer.so';
break;
default:
pluginName = '';
break;
}
if (pluginName) {
app.commandLine.appendSwitch('ppapi-flash-path', path.join(process.resourcesPath, 'plugins', 'flash', pluginName));
// Currently for enable_chromium build the flash version need to be
// specified. See RUN-4510 and RUN-4580.
app.commandLine.appendSwitch('ppapi-flash-version', '32.0.0.207');
}
}
function initializeCrashReporter(argo) {
if (!needsCrashReporter(argo)) {
return;
}
const configUrl = argo['startup-url'] || argo['config'];
const diagnosticMode = argo['diagnostics'] || false;
const sandboxDisabled = argo['sandbox'] === false; // means '--no-sandbox' flag exists
if (diagnosticMode && !sandboxDisabled) {
log.writeToLog('info', `'--no-sandbox' flag has been automatically added, ` +
`because the application is running in diagnostics mode and has '--diagnostics' flag specified`);
app.commandLine.appendSwitch('no-sandbox');
}
crashReporter.startOFCrashReporter({ diagnosticMode, configUrl });
}
function initializeDiagnosticReporter(argo) {
if (!argo['diagnostics']) {
return;
}
// This event may be fired more than once for an unresponsive window.
ofEvents.on(route.window('not-responding', '*'), (payload) => {
log.writeToLog('info', `Window is not responding. uuid: ${payload.data[0].uuid}, name: ${payload.data[0].name}`);
});
ofEvents.on(route.window('responding', '*'), (payload) => {
log.writeToLog('info', `Window responding again. uuid: ${payload.data[0].uuid}, name: ${payload.data[0].name}`);
});
}
function rotateLogs(argo) {
// only keep the 7 most recent logfiles
System.getLogList((err, files) => {
if (err) {
System.log('error', `logfile error: ${err}`);
} else {
files.filter(file => {
return !(file.name === 'debug.log' || file.name.indexOf('debugp') === 0);
}).sort((a, b) => {
return (b.date - a.date);
}).slice(6).forEach(file => {
let filepath = path.join(app.getPath('userData'), file.name);
fs.unlink(filepath, err => {
if (err) {
System.log('error', `cannot delete logfile: ${filepath}`);
} else {
System.log('info', `deleting logfile: ${filepath}`);
}
});
});
}
});
app.reopenLogfile();
// delete debugp????.log file
deleteProcessLogfile(false);
rvmCleanup(argo);
}
function deleteProcessLogfile(closeLogfile) {
let filename = app.getProcessLogfileName();
if (!filename) {
System.log('info', 'process logfile name is undefined');
System.log('info', coreState.argo);
return;
}
let filepath = path.join(app.getPath('userData'), filename);
if (closeLogfile) {
app.closeLogfile();
}
try {
fs.unlinkSync(filepath);
System.log('info', `deleting process logfile: ${filepath}`);
} catch (e) {
System.log('error', `cannot delete process logfile: ${filepath}`);
}
}
function rvmCleanup(argo) {
let deleteCacheOnExitFlag = 'delete-cache-on-exit';
// notify RVM with necessary information to clean up cache folders on exit when we're called with --delete-cache-on-exit
let deleteCacheOnExit = argo[deleteCacheOnExitFlag];
if (deleteCacheOnExit) {
System.deleteCacheOnExit(() => {
console.log('Successfully sent a delete-cache-on-exit message to the RVM.');
}, (err) => {
console.log(err);
});
}
}
function migrateLocalStorage(argo) {
const oldLocalStoragePath = argo['old-local-storage-path'] || '';
const newLocalStoragePath = argo['new-local-storage-path'] || '';
const localStorageUrl = argo['local-storage-url'] || '';
if (oldLocalStoragePath && newLocalStoragePath && localStorageUrl) {
try {
System.log('info', 'Migrating Local Storage from ' + oldLocalStoragePath + ' to ' + newLocalStoragePath);
app.migrateLocalStorage(oldLocalStoragePath, newLocalStoragePath, localStorageUrl);
System.log('info', 'Migrated Local Storage');
} catch (e) {
System.log('error', `Couldn't migrate cache from ${oldLocalStoragePath} to ${newLocalStoragePath}`);
System.log('error', e);
}
}
}
function initServer() {
let attemptedHardcodedPort = false;
apiProtocol.initApiHandlers();
socketServer.on('server/error', function(err) {
// Guard against non listen errors and infinite retries.
if (err && err.syscall === 'listen' && !attemptedHardcodedPort) {
// Assuming connection issue. Bind on any available port
console.log('Assuming connection issue. Bind on any available port');
attemptedHardcodedPort = true;
socketServer.start(0);
}
});
socketServer.on('server/open', function(port) {
console.log('Opened on', port);
portDiscovery.broadcast(portDiscovery.getPortInfoByArgs(coreState.argo, port));
resolveServerReady();
handleDeferredLaunches();
});
socketServer.on('connection/message', function(id, message) {
console.log('Receieved message', message);
});
return socketServer;
}
//TODO: this function actually does more than just launch apps, it will initiate the web socket server and
//is essential for proper runtime startup and adapter connectivity. we want to split into smaller independent parts.
//please see the discussion on https://github.com/openfin/runtime-core/pull/194
function launchApp(argo, startExternalAdapterServer) {
if (needsCrashReporter(argo)) {
log.setToVerbose();
}
convertOptions.fetchOptions(argo, configuration => {
const {
configUrl,
configObject,
configObject: { licenseKey, shortcut = {} }
} = configuration;
coreState.setManifest(configUrl, configObject);
if (argo['user-app-config-args']) {
const tempUrl = configObject['startup_app'].url;
const delimiter = tempUrl.indexOf('?') < 0 ? '?' : '&';
configObject['startup_app'].url = `${tempUrl}${delimiter}${argo['user-app-config-args']}`;
}
const startupAppOptions = convertOptions.getStartupAppOptions(configObject);
const uuid = startupAppOptions && startupAppOptions.uuid;
const name = startupAppOptions && startupAppOptions.name;
const ofApp = Application.wrap(uuid);
const ofManifestUrl = ofApp && ofApp._configUrl;
let isRunning = Application.isRunning(ofApp);
const { company, name: shortcutName } = shortcut;
let appUserModelId;
let namePart;
if (company) {
namePart = shortcutName ? `.${shortcutName}` : '';
appUserModelId = `${company}${namePart}`;
} else {
namePart = name ? `.${name}` : '';
appUserModelId = `${uuid}${namePart}`;
}
app.setAppUserModelId(appUserModelId);
// this ensures that external connections that start the runtime can do so without a main window
let successfulInitialLaunch = true;
let passedMutexCheck = false;
let failedMutexCheck = false;
if (uuid && !isRunning) {
if (!lockUuid(uuid)) {
deleteApp(uuid);
// We need to rebuild a new argv to have correct app info in it.
let newArgv = Object.keys(argo).map(key => {
if (key === '_') {
return argo[key].length === 1 ? argo[key][0] : argo[key];
} else {
return '--' + key + '=' + argo[key];
}
});
duplicateUuidTransport.broadcast({ argv: newArgv, uuid });
failedMutexCheck = true;
// close the runtime if it's only app.
if (coreState.shouldCloseRuntime()) {
app.quit();
return;
}
} else {
passedMutexCheck = true;
}
}
// comparing ofManifestUrl and configUrl shouldn't consider query strings. Otherwise, it will break deep linking
const shouldRun = passedMutexCheck && (!isRunning || ofManifestUrl.split('?')[0] !== configUrl.split('?')[0]);
if (startupAppOptions && shouldRun) {
//making sure that if a window is present we set the window name === to the uuid as per 5.0
startupAppOptions.name = uuid;
successfulInitialLaunch = initFirstApp(configObject, configUrl, licenseKey);
} else if (uuid && !failedMutexCheck) {
Application.run({
uuid,
name: uuid
},
'',
argo['user-app-config-args']
);
}
if (startExternalAdapterServer && successfulInitialLaunch) {
coreState.setStartManifest(configUrl, configObject);
socketServer.start(configObject['websocket_port'] || 9696);
}
app.emit('synth-desktop-icon-clicked', {
mouse: System.getMousePosition(),
tickCount: app.getTickCount(),
uuid
});
}, (error) => {
const title = errors.ERROR_TITLE_APP_INITIALIZATION;
const type = errors.ERROR_BOX_TYPES.APP_INITIALIZATION;
const args = { error, title, type };
errors.showErrorBox(args)
.catch((error) => log.writeToLog('info', error))
.then(app.quit);
});
}
function initFirstApp(configObject, configUrl, licenseKey) {
let startupAppOptions;
let successfulLaunch = false;
try {
startupAppOptions = convertOptions.getStartupAppOptions(configObject);
validatePreloadScripts(startupAppOptions);
// Needs proper configs
firstApp = Application.create(startupAppOptions, configUrl);
coreState.setLicenseKey({ uuid: startupAppOptions.uuid }, licenseKey);
Application.run({
uuid: firstApp.uuid
});
firstApp.mainWindow.on('closed', function() {
firstApp = null;
});
successfulLaunch = true;
} catch (error) {
if (rvmBus) {
rvmBus.publish({
topic: 'application',
action: 'hide-splashscreen',
sourceUrl: configUrl
});
}
const message = startupAppOptions.loadErrorMessage;
const title = errors.ERROR_TITLE_APP_INITIALIZATION;
const type = errors.ERROR_BOX_TYPES.APP_INITIALIZATION;
const args = { error, message, title, type };
errors.showErrorBox(args)
.catch((error) => log.writeToLog('info', error))
.then(() => {
if (coreState.shouldCloseRuntime()) {
app.quit();
}
});
}
return successfulLaunch;
}
//Please add any hotkeys added here to the the reservedHotKeys list.
function registerShortcuts() {
app.on('browser-window-focus', (event, browserWindow) => {
const windowOptions = coreState.getWindowOptionsById(browserWindow.webContents.id);
const accelerator = windowOptions && windowOptions.accelerator || {};
const webContents = browserWindow.webContents;
if (accelerator.zoom) {
const zoom = increment => { return () => { webContents.send('zoom', { increment }); }; };
globalShortcut.register('CommandOrControl+0', zoom(0));
globalShortcut.register('CommandOrControl+=', zoom(+1));
globalShortcut.register('CommandOrControl+Plus', zoom(+1));
globalShortcut.register('CommandOrControl+-', zoom(-1));
globalShortcut.register('CommandOrControl+_', zoom(-1));
}
if (accelerator.devtools) {
const devtools = () => { webContents.openDevTools(); };
globalShortcut.register('CommandOrControl+Shift+I', devtools);
}
if (accelerator.reload) {
const reload = () => { webContents.reload(); };
globalShortcut.register('F5', reload);
globalShortcut.register('CommandOrControl+R', reload);
}
if (accelerator.reloadIgnoringCache) {
const reloadIgnoringCache = () => { webContents.reloadIgnoringCache(); };
globalShortcut.register('Shift+F5', reloadIgnoringCache);
globalShortcut.register('CommandOrControl+Shift+R', reloadIgnoringCache);
}
});
const unhookShortcuts = (event, browserWindow) => {
if (!globalShortcut.isDestroyed()) {
reservedHotKeys.forEach(a => globalShortcut.unregister(a));
}
};
app.on('browser-window-closed', unhookShortcuts);
app.on('browser-window-blur', unhookShortcuts);
}
function registerMacMenu() {
if (process.platform === 'darwin') {
const template = [{
label: 'OpenFin',
submenu: [
{ role: 'quit' }
]
},
{
role: 'editMenu'
}
];
const menu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(menu);
}
}
function migrateCookies() {
if (!process.buildFlags.enableChromium) {
return;
}
const userData = app.getPath('userData');
const cookiePath = path.join(path.join(userData, 'Default'));
const legacyCookiePath = userData;
const cookieFile = path.join(path.join(cookiePath, 'Cookies'));
const cookieJrFile = path.join(path.join(cookiePath, 'Cookies-journal'));
const legacyCookieFile = path.join(path.join(legacyCookiePath, 'Cookies'));
const legacyCookieJrFile = path.join(path.join(legacyCookiePath, 'Cookies-journal'));
try {
if (fs.existsSync(legacyCookieFile) && !fs.existsSync(cookieFile)) {
log.writeToLog('info', `migrating cookies from ${legacyCookiePath} to ${cookiePath}`);
fs.copyFileSync(legacyCookieFile, cookieFile);
fs.copyFileSync(legacyCookieJrFile, cookieJrFile);
} else {
log.writeToLog(1, `skip cookie migration in ${cookiePath}`, true);
}
} catch (err) {
log.writeToLog('info', `Error migrating cookies from ${legacyCookiePath} to ${cookiePath} ${err}`);
try {
fs.unlinkSync(cookieFile);
} catch (ignored) {}
try {
fs.unlinkSync(cookieJrFile);
} catch (ignored) {}
}
}
function needsCrashReporter(argo) {
return !!(argo['diagnostics'] || argo['enable-crash-reporting']);
}
function validatePreloadScripts(options) {
const { name, uuid } = options;
const genErrorMsg = (propName) => {
return `Invalid shape of '${propName}' window option. Please, consult the API documentation.`;
};
const isValidPreloadScriptsArray = (v = []) => v.every((e) => {
return typeof e === 'object' && typeof e.url === 'string';
});
if ('preload' in options) {
log.writeToLog('info', `[preloadScripts] [${uuid}]-[${name}]: 'preload' option ` +
`is deprecated, use 'preloadScripts' instead`);
if (Array.isArray(options.preload)) {
if (!isValidPreloadScriptsArray(options.preload)) {
throw new Error(genErrorMsg('preload'));
}
} else if (typeof options.preload !== 'string' && options.preload) {
throw new Error(genErrorMsg('preload'));
}
} else if ('preloadScripts' in options) {
if (Array.isArray(options.preloadScripts)) {
if (!isValidPreloadScriptsArray(options.preloadScripts)) {
throw new Error(genErrorMsg('preloadScripts'));
}
} else {
if (options.preloadScripts) {
throw new Error(genErrorMsg('preloadScripts'));
} else {
log.writeToLog('info', `[preloadScripts] [${uuid}]-[${name}]: Consider using an empty ` +
`array with 'preloadScripts', instead of a falsy value`);
}
}
}
return true;
}
function logSystemMemoryInfo() {
const systemMemoryInfo = process.getSystemMemoryInfo();
log.writeToLog('info', `System memory info for: ${process.platform} ${os.release()} ${electron.app.getSystemArch()}`);
for (const i of Object.keys(systemMemoryInfo)) {
log.writeToLog('info', `${i}: ${systemMemoryInfo[i]} KB`);
}
}