Repository navigation
Expand file tree
/
Copy pathelectron.js
More file actions
4247 lines (3668 loc) · 112 KB
/
Copy pathelectron.js
File metadata and controls
4247 lines (3668 loc) · 112 KB
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 fs from 'fs';
import { promises as fsProm } from 'fs';
import path from 'path';
import url from 'url';
import {Menu as menu, shell, dialog, session, screen, ClipboardItem,
clipboard, nativeImage, nativeTheme, ipcMain, app, BrowserWindow} from 'electron';
import crc from 'crc';
import zlib from 'zlib';
import log from'electron-log';
import { parseDrawioArgs, formatHelp, validFormatRegExp as validFormatRegExpImport } from './args.js';
import { parseLastWinSize, placeWindowOnDisplays } from './window-bounds.js';
import { getUpdateChannel } from './update-channel.js';
import { getUpdateMode, getReleaseUrl } from './update-mode.js';
import { listExportFiles, lexists, openExportFile } from './export-files.js';
import { getSystem32Path } from './system-path.js';
import { writeBackupFile } from './backup-file.js';
import { getPrintOptions } from './print-options.js';
import { readPngXml } from './png-xml.js';
import { readPdfXml } from './pdf-xml.js';
import { buildHtmlExport } from './html-export.js';
import FileWatcher from './file-watcher.js';
import { ConfigPathGrants } from './config-paths.js';
import { getUrlParams, getUrlParamsFiles } from './url-params.js';
import elecUpPkg from 'electron-updater';
const {autoUpdater} = elecUpPkg;
import {PDFDocument, PDFHexString, PDFName} from '@cantoo/pdf-lib';
import Store from 'electron-store';
import ProgressBar from './progress-bar.js';
import contextMenu from 'electron-context-menu';
import {spawn, execFile} from 'child_process';
import {disableUpdate as disUpPkg} from './disableUpdate.js';
// electron-store's when-exit hooks SIGTRAP. A V8 fatal error ends in a trap
// instruction, and on arm64 the handler returns to that same instruction, so
// the process spins forever instead of crashing
process.removeAllListeners('SIGTRAP');
let store;
try
{
store = new Store();
}
catch (e)
{
console.error('Failed to initialize electron-store:', e);
store = null;
}
// One-shot migration: detect whether this is a fresh install or an update,
// so we can seed the drawio Configuration's defaultAdaptiveColors accordingly.
// 'auto' for fresh installs (matches drawio.com behaviour), 'simple' for
// updates (preserves what desktop users have been seeing historically).
// Returns 'auto' / 'simple' / 'none' on the first launch with this code,
// null on every subsequent launch. Safe to call before app.whenReady().
function detectInitialAdaptiveColorsDefault()
{
if (store == null) return null;
const MIGRATION_KEY = 'adaptiveColorsDefaultMigrated';
if (store.get(MIGRATION_KEY)) return null;
let hadPriorState = store.size > 0;
if (!hadPriorState)
{
try
{
const lsPath = path.join(app.getPath('userData'), 'Local Storage', 'leveldb');
hadPriorState = fs.existsSync(lsPath) && fs.readdirSync(lsPath).length > 0;
}
catch (e)
{
// If we can't read userData for any reason, fall through and treat
// as a fresh install. The preload guard won't overwrite an existing
// explicit user choice, so this is safe.
}
}
const mode = hadPriorState ? 'simple' : 'auto';
store.set(MIGRATION_KEY, app.getVersion());
return mode;
}
const disableUpdate = disUpPkg() ||
process.env.DRAWIO_DISABLE_UPDATE === 'true' ||
process.argv.indexOf('--disable-update') !== -1;
const updateMode = disableUpdate ? 'off' : getUpdateMode({
platform: process.platform,
env: process.env,
execPath: process.execPath,
resourcesPath: process.resourcesPath,
productName: app.name,
windowsStore: process.windowsStore === true,
exists: fs.existsSync
});
// Asks before downloading instead of downloading in the background
const silentUpdate = updateMode == 'auto' && process.env.DRAWIO_NO_SILENT_UPDATE !== 'true' &&
process.argv.indexOf('--no-silent-update') === -1;
let manualUpdateCheck = false; // Set when the user clicks "Check for updates" so the manual flow stays interactive even when silentUpdate is on
// status is null, 'available' (notify mode), 'downloading' or 'downloaded'
let updateState = {status: null, version: null};
let restartForUpdate = false;
autoUpdater.logger = log
autoUpdater.logger.transports.file.level = 'error'
autoUpdater.logger.transports.console.level = 'error'
// autoDownload is always false: we trigger downloadUpdate() explicitly so silent vs. interactive paths can branch on manualUpdateCheck
autoUpdater.autoDownload = false
// A downloaded update is installed when the app quits, unless Restart to Update installed it first
autoUpdater.autoInstallOnAppQuit = updateMode == 'auto'
const UPDATE_DOWNLOAD_URL = 'https://get.draw.io';
let updateFailureDialogShown = false;
// Shows a user-facing fallback message when the in-app updater fails for any reason.
// Deduped within a short window so a single underlying failure (which can fan out into
// both a sync throw and an 'error' event) doesn't produce stacked dialogs.
// Background checks and downloads fail quietly (offline, GitHub down) and are
// retried at the next check
function notifyUpdateFailure(err, context)
{
const userStarted = manualUpdateCheck || updateProgressBar != null;
manualUpdateCheck = false;
if (updateState.status == 'downloading')
{
setUpdateState(null, null);
}
try { log.error('Update failure (' + (context || 'unknown') + '):', err); }
catch (e) { /* swallow logger errors */ }
if (!userStarted || updateFailureDialogShown) return;
updateFailureDialogShown = true;
setTimeout(() => { updateFailureDialogShown = false; }, 5000);
try
{
dialog.showMessageBox(
{
type: 'error',
title: 'Update Error',
message: 'There was a problem updating draw.io.',
detail: 'Please manually download and update from ' + UPDATE_DOWNLOAD_URL
});
}
catch (dialogErr)
{
try { log.error('Failed to show update error dialog:', dialogErr); }
catch (e) { /* swallow */ }
}
}
// Invokes an autoUpdater method, catching synchronous throws (e.g. NPEs deep inside
// electron-updater) and unhandled promise rejections, routing both to the fallback dialog.
function safeUpdaterCall(label, fn)
{
try
{
const result = fn();
if (result != null && typeof result.catch === 'function')
{
result.catch(err => notifyUpdateFailure(err, label));
}
return result;
}
catch (err)
{
notifyUpdateFailure(err, label);
return null;
}
}
// Wraps an event listener so an exception in the handler can't escape and tear down
// the updater (or, worse, crash the process via an unhandled exception in a callback).
function safeUpdaterListener(label, fn)
{
return function(...args)
{
try
{
return fn.apply(this, args);
}
catch (err)
{
notifyUpdateFailure(err, label);
}
};
}
const __dirname = path.dirname(url.fileURLToPath(import.meta.url));
//Command option to disable hardware acceleration
if (process.argv.indexOf('--disable-acceleration') !== -1)
{
app.disableHardwareAcceleration();
}
// Configure context menu for text fields
contextMenu({
showCopyImage: true,
showSaveImage: true,
showSaveImageAs: true,
showLookUpSelection: false,
showSearchWithGoogle: false,
showCopyLink: false,
showSelectAll: true,
showPasteAndMatchStyle: true
});
const __DEV__ = process.env.DRAWIO_ENV === 'dev'
let windowsRegistry = []
let cmdQPressed = false
let firstWinLoaded = false
let firstWinFilePath = null
const isMac = process.platform === 'darwin'
const isWin = process.platform === 'win32'
// Dependencies still start programs by bare name (electron-updater's signature
// check runs chcp and powershell.exe through cmd.exe). If this variable exists,
// cmd.exe and libuv skip the working directory when they look for a program
// [GHSA-qg46-52fx-h7p8]
if (isWin)
{
process.env.NoDefaultCurrentDirectoryInExePath = '1';
}
let enableSpellCheck = store != null ? store.get('enableSpellCheck') : false;
enableSpellCheck = enableSpellCheck != null ? enableSpellCheck : isMac;
let enableStoreBkp = store != null ? (store.get('enableStoreBkp') != null ? store.get('enableStoreBkp') : true) : false;
let dialogOpen = false;
// One-shot value used to seed the drawio Configuration's defaultAdaptiveColors
// for users running this version for the first time. 'auto' for new installs,
// 'simple' for updates from a previous desktop version. Null after migration.
let initialAdaptiveColorsDefault = null;
const codeDir = path.join(__dirname, '/../../drawio/src/main/webapp');
const codeUrl = url.pathToFileURL(codeDir).href.replace(/\/.\:\//, str => str.toUpperCase()); // Fix for windows drive letter
// Production app uses asar archive, so we need to go up two more level. It's extra cautious since asar is read-only anyway.
const appBaseDir = path.join(__dirname, __dirname.endsWith(path.join('resources', 'app.asar', 'src', 'main')) ?
'/../../../../' : '/../../');
// Paths the user has authorised through trusted UI (file picker, file association,
// command line). The renderer is not allowed to write to anything else, even via
// IPC handlers that pass validateSender. Symlinks are resolved before insertion so
// the realpath of a blessed path is what's actually authorised.
//
// Persisted across sessions via electron-store so drawio's "Open Recent" (which
// fakes an args-obj entirely in the renderer) still works — recent files are
// only added to the menu after a successful open via trusted UI, so a path in
// the persisted set is one we previously authorised.
const BLESSED_PATHS_KEY = 'blessedPaths';
const BLESSED_PATHS_MAX = 500;
const blessedPaths = new Set();
if (store != null)
{
try
{
const persisted = store.get(BLESSED_PATHS_KEY);
if (Array.isArray(persisted))
{
for (const p of persisted)
{
if (typeof p === 'string' && p) blessedPaths.add(p);
}
}
}
catch (e) {} // Bad store contents — start with an empty set.
}
function persistBlessedPaths()
{
if (store == null) return;
try
{
let arr = Array.from(blessedPaths);
// Cap to keep the store bounded; newest insertions win.
if (arr.length > BLESSED_PATHS_MAX)
{
arr = arr.slice(arr.length - BLESSED_PATHS_MAX);
}
store.set(BLESSED_PATHS_KEY, arr);
}
catch (e) {}
}
function blessPath(p)
{
if (typeof p !== 'string' || !p) return;
try
{
const resolved = path.resolve(p);
blessedPaths.add(resolved);
// Must be the native realpath that canonicalisePath checks against.
// Node's JS walker (fs.realpathSync) keeps mapped and subst drive
// letters and the case as given, where the native call returns
// \\server\share, the substituted folder and the case on disk, so files
// on network drives were refused [jgraph/drawio-desktop#2559].
try
{
blessedPaths.add(fs.realpathSync.native(resolved));
}
catch (e)
{
// Save As can select a new file in a symlinked directory. Authorise
// its canonical destination before the file exists too.
try
{
blessedPaths.add(path.join(fs.realpathSync.native(path.dirname(resolved)), path.basename(resolved)));
}
catch (e2) {} // Some filesystems do not support realpath.
}
persistBlessedPaths();
}
catch (e) {} // Defensive: blessPath must never throw into a caller's flow.
}
// Paths declared in the user's configuration become readable for the window
// that loaded it once the user has allowed them, see config-paths.js
// [jgraph/drawio-desktop#1278]
const configPathGrants = new ConfigPathGrants(fs, store, confirmConfigPaths);
// The trusted half of ConfigPathGrants: a dialog of the main process, which no
// script in the renderer can answer. Asked when a window loads a configuration
// that names files not allowed before, which is after the restart that a
// configuration change asks for.
async function confirmConfigPaths(webContents, entries)
{
const win = BrowserWindow.fromWebContents(webContents);
if (win == null || win.isDestroyed())
{
return false;
}
const names = entries.map((entry) => (entry.path == entry.realpath) ?
entry.path : entry.path + ' (' + entry.realpath + ')');
const result = await dialog.showMessageBox(win,
{
type: 'warning',
title: 'Configuration',
message: 'Allow draw.io to read the files named in its configuration?',
detail: 'Extras > Configuration names local files that draw.io has not been allowed to read:\n\n' +
names.join('\n') + '\n\nOnly allow this if you added them to the configuration yourself.',
buttons: ['Allow', 'Don\'t Allow'],
defaultId: 1,
cancelId: 1,
noLink: true
});
return result.response === 0;
}
// fs.statSync that never throws (returns null for missing, deleted-in-between
// or inaccessible paths) so callers can't crash the main process on a race
function statSafe(p)
{
try
{
return (typeof p === 'string' && p) ? fs.statSync(p) : null;
}
catch (e)
{
return null;
}
}
// One-shot migration: on first launch with the blessedPaths fix, the renderer's
// drawio "Open Recent" list (in localStorage at key '.recent') contains paths
// that were opened in prior versions and so were never blessed. Without this
// migration, autosave would break for every legacy recent file until the user
// re-opened it via the file picker. Trust-on-first-use is acceptable here: any
// attacker who could have poisoned localStorage in a prior version already had
// the broader (pre-fix) attack surface, so this migration does not widen it.
const BLESSED_PATHS_MIGRATION_KEY = 'blessedPathsLegacyMigrated';
async function migrateLegacyRecentsOnce(webContents)
{
if (store == null) return;
if (store.get(BLESSED_PATHS_MIGRATION_KEY)) return;
try
{
const recentsJson = await webContents.executeJavaScript(
'try { localStorage.getItem(".recent") } catch (e) { null }');
if (typeof recentsJson === 'string')
{
const recents = JSON.parse(recentsJson);
if (Array.isArray(recents))
{
for (const entry of recents)
{
if (entry != null && typeof entry.id === 'string' &&
entry.id && fs.existsSync(entry.id))
{
blessPath(entry.id);
}
}
}
}
}
catch (e) {} // Migration is best-effort; never block app startup.
try { store.set(BLESSED_PATHS_MIGRATION_KEY, true); } catch (e) {}
}
// One-shot migration for the read-side path gate: custom libraries added
// through File > Open Library in versions before blessPath existed are still
// in the renderer's settings but were never authorised, so assertReadablePath
// would now refuse to load them into the sidebar. Same trust-on-first-use
// reasoning as migrateLegacyRecentsOnce, and its own key so it also runs for
// installs that already completed that migration.
const BLESSED_LIBRARIES_MIGRATION_KEY = 'blessedLibrariesLegacyMigrated';
// Held so assertReadablePath can wait for the migration instead of refusing a
// legacy library that the sidebar requests while it is still running
let legacyLibrariesMigration = null;
async function migrateLegacyLibrariesOnce(webContents)
{
if (store == null) return;
if (store.get(BLESSED_LIBRARIES_MIGRATION_KEY)) return;
try
{
const settingsJson = await webContents.executeJavaScript(
'try { localStorage.getItem(".drawio-config") } catch (e) { null }');
if (typeof settingsJson === 'string')
{
const settings = JSON.parse(settingsJson);
if (settings != null && Array.isArray(settings.customLibraries))
{
for (const id of settings.customLibraries)
{
// 'S' is the desktop (local file) library service, the
// only one whose id is a filesystem path
if (typeof id !== 'string' || id.charAt(0) !== 'S') continue;
let libPath = id.substring(1);
try
{
libPath = decodeURIComponent(libPath);
}
catch (e) {} // Not encoded, use as-is
if (libPath && fs.existsSync(libPath))
{
blessPath(libPath);
}
}
}
}
}
catch (e) {} // Migration is best-effort; never block app startup.
try { store.set(BLESSED_LIBRARIES_MIGRATION_KEY, true); } catch (e) {}
}
let appZoom = 1;
// Disabled by default
let isGoogleFontsEnabled = store != null ? (store.get('isGoogleFontsEnabled') != null? store.get('isGoogleFontsEnabled') : false) : false;
// dev=1 makes bootstrap.js load the unminified editor sources, which the
// packaged app.asar leaves out (see files in electron-builder-*.json), and
// the desktop scripts from js/desktop, which public drawio releases move to
// js/diagramly. A packaged build or the public submodule started with
// DRAWIO_ENV=dev therefore keeps the minified bundles
const devSources = __DEV__ && fs.existsSync(path.join(codeDir, 'js', 'diagramly', 'Devel.js')) &&
fs.existsSync(path.join(codeDir, 'js', 'desktop', 'ElectronApp.js'));
//Read config file
var queryObj = getUrlParams({
defaults: {
'dev': devSources ? 1 : 0,
'test': __DEV__ ? 1 : 0,
'gapi': 0,
'db': 0,
'od': 0,
'gh': 0,
'gl': 0,
'tr': 0,
'browser': 0,
'picker': 0,
'mode': 'device',
'export': 'https://convert.diagrams.net/node/export'
},
state: {
'disableUpdate': updateMode == 'off'? 1 : 0,
'enableSpellCheck': enableSpellCheck? 1 : 0,
'enableStoreBkp': enableStoreBkp? 1 : 0,
'isGoogleFontsEnabled': isGoogleFontsEnabled? 1 : 0
},
files: getUrlParamsFiles({
exeDir: path.dirname(process.execPath),
userDataDir: app.getPath('userData'),
cwd: process.cwd(),
dev: __DEV__
}),
readFile: (file) => fs.readFileSync(file, 'utf8'),
log: console.log
});
// Trying sandboxing the renderer for more protection
//app.enableSandbox(); // This maybe the reason snap stopped working
// Only allow request from the app code itself
function validateSender (frame)
{
// senderFrame may be null if the frame has navigated or been destroyed
// before the IPC handler runs (documented behaviour on IpcMainEvent).
if (frame == null) return false;
return frame.url.replace(/\/.\:\//, str => str.toUpperCase()).startsWith(codeUrl);
}
function createWindow (opt = {})
{
let lastWinSizeStr = (store && store.get('lastWinSize')) || '1200,800,0,0,false,false';
let lastWinSize = parseLastWinSize(lastWinSizeStr);
const additionalArguments = [];
if (initialAdaptiveColorsDefault != null)
{
additionalArguments.push('--initial-adaptive-colors=' + initialAdaptiveColorsDefault);
}
let options = Object.assign(
{
// Matches the background of the loading splash to avoid a white flash in dark mode
backgroundColor: nativeTheme.shouldUseDarkColors ? '#1B1D1E' : '#F1F3F4',
width: lastWinSize.width,
height: lastWinSize.height,
icon: `${codeDir}/images/drawlogo256.png`,
webPreferences: {
preload: `${__dirname}/electron-preload.js`,
spellcheck: enableSpellCheck,
contextIsolation: true,
nodeIntegration: false,
// webviewTag and webSecurity belong here, not on the top-level
// BrowserWindow options, where they are silently ignored
webviewTag: false,
webSecurity: true,
disableBlinkFeatures: 'Auxclick', // Is this needed?
additionalArguments: additionalArguments
}
}, opt)
// Displays may have been removed or changed resolution since the window
// size was saved, leaving the saved position off-screen or the saved size
// too large for the remaining displays [jgraph/drawio-desktop#2282]
const bounds = placeWindowOnDisplays(
{x: lastWinSize.x, y: lastWinSize.y, width: options.width, height: options.height},
screen.getAllDisplays().map(display => display.workArea),
screen.getPrimaryDisplay().workArea);
options.x = bounds.x;
options.y = bounds.y;
options.width = bounds.width;
options.height = bounds.height;
let mainWindow = new BrowserWindow(options)
windowsRegistry.push(mainWindow)
if (lastWinSize.maximized)
{
mainWindow.maximize()
}
if (lastWinSize.fullScreen)
{
mainWindow.setFullScreen(true);
}
if (__DEV__)
{
console.log('createWindow', opt)
}
//Cannot be read before app is ready
queryObj['appLang'] = app.getLocale();
queryObj['autoUpdate'] = isAutoUpdateEnabled()? 1 : 0;
let ourl = url.format(
{
pathname: `${codeDir}/index.html`,
protocol: 'file:',
query: queryObj,
slashes: true
})
// The local paths named in this window's configuration are read once, at its
// app-load-finished message (see the handler next to rendererReq), and only
// this window may read them
const configOwner = mainWindow.webContents;
configPathGrants.register(configOwner);
configOwner.on('destroyed', () =>
{
configPathGrants.unregister(configOwner);
});
mainWindow.loadURL(ourl)
mainWindow.webContents.on('did-finish-load', function()
{
legacyLibrariesMigration = migrateLegacyLibrariesOnce(mainWindow.webContents);
});
// File watches are keyed by webContents, so drop this window's watches when
// it goes away or navigates: the renderer that armed them is gone and its
// fs listeners would keep polling forever [jgraph/drawio-desktop#2541]
const watchOwner = mainWindow.webContents;
watchOwner.on('destroyed', () =>
{
fileWatcher.unwatchAll(watchOwner);
});
// Only fires once a main frame navigation has committed, so the page that
// armed these watches is already gone and an aborted navigation cannot
// clear a watch that is still live
watchOwner.on('did-navigate', () =>
{
fileWatcher.unwatchAll(watchOwner);
});
// Intercept Ctrl/Cmd+Shift+V before it reaches the renderer
// so paste-without-formatting works even when the web app captures the shortcut
mainWindow.webContents.on('before-input-event', (event, input) =>
{
if (input.type === 'keyDown' && input.key === 'v' &&
input.shift && (isMac ? input.meta : input.control) && !input.alt)
{
event.preventDefault();
mainWindow.webContents.pasteAndMatchStyle();
}
});
// Open the DevTools.
if (__DEV__)
{
mainWindow.webContents.openDevTools()
}
function rememberWinSize(win)
{
if (store != null)
{
const size = win.getSize();
const pos = win.getPosition();
store.set('lastWinSize', size[0] + ',' + size[1] + ',' + pos[0] + ',' + pos[1] + ',' + win.isMaximized() + ',' + win.isFullScreen());
}
}
mainWindow.on('maximize', function()
{
mainWindow.webContents.send('maximize')
});
mainWindow.on('unmaximize', function()
{
mainWindow.webContents.send('unmaximize')
});
mainWindow.on('resize', function()
{
mainWindow.webContents.send('resize')
});
let uniqueIsModifiedId, modifiedModalOpen = false;
ipcMain.on('isModified-result', async (e, data) =>
{
if (!validateSender(e.senderFrame) || uniqueIsModifiedId != data.uniqueId || modifiedModalOpen) return null;
if (data.isModified)
{
modifiedModalOpen = true;
// Button order follows platform conventions, indices are mapped below.
// Enter triggers Save, Esc triggers Cancel, Alt+S/Alt+D work on Windows and Linux
let saveBtn = 0, cancelBtn, discardBtn, buttons;
if (isMac)
{
buttons = ['Save', 'Cancel', 'Discard Changes'];
cancelBtn = 1;
discardBtn = 2;
}
else
{
buttons = ['&Save', '&Discard Changes', 'Cancel'];
discardBtn = 1;
cancelBtn = 2;
}
// Can't use async function here because it crashes on Linux when win.destroy is called
let response = dialog.showMessageBoxSync(
mainWindow,
{
type: 'question',
buttons: buttons,
defaultId: saveBtn,
cancelId: cancelBtn,
noLink: true,
normalizeAccessKeys: true,
title: 'Confirm',
message: 'The document has unsaved changes. Do you want to save them?'
});
if (response === saveBtn)
{
//Save in the renderer (opens Save As dialog for new files), then
//close the window unless saving failed or was cancelled
const saveUniqueId = uniqueIsModifiedId;
mainWindow.webContents.send('saveAndClose', saveUniqueId);
const saveAndCloseResult = (e, result) =>
{
if (!validateSender(e.senderFrame) || saveUniqueId != result.uniqueId) return null;
ipcMain.removeListener('saveAndClose-result', saveAndCloseResult);
if (result.success && !mainWindow.isDestroyed())
{
mainWindow.destroy();
}
else
{
cmdQPressed = false;
restartForUpdate = false;
modifiedModalOpen = false;
}
};
ipcMain.on('saveAndClose-result', saveAndCloseResult);
}
else if (response === discardBtn)
{
//If user chose not to save, remove the draft
if (data.draftPath != null)
{
try
{
await deleteFile(data.draftPath);
}
catch (e)
{
// Closes the window even if the draft cannot be deleted, eg. if
// a save deleted it and the next draft was not written yet
}
mainWindow.destroy();
}
else
{
mainWindow.webContents.send('removeDraft');
ipcMain.once('draftRemoved', (e) =>
{
if (!validateSender(e.senderFrame)) return null;
mainWindow.destroy();
});
}
}
else
{
cmdQPressed = false;
restartForUpdate = false;
modifiedModalOpen = false;
}
}
else
{
mainWindow.destroy();
}
});
mainWindow.on('close', (event) =>
{
uniqueIsModifiedId = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
if (__DEV__)
{
const index = windowsRegistry.indexOf(mainWindow)
console.log('Window on close', index, uniqueIsModifiedId)
}
const contents = mainWindow.webContents
if (contents != null)
{
contents.send('isModified', uniqueIsModifiedId);
event.preventDefault();
}
rememberWinSize(mainWindow);
})
// Emitted when the window is closed.
mainWindow.on('closed', () =>
{
const index = windowsRegistry.indexOf(mainWindow)
if (__DEV__)
{
console.log('Window closed idx:%d', index)
}
windowsRegistry.splice(index, 1)
})
return mainWindow
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() =>
{
// Determine initial defaultAdaptiveColors for the drawio Configuration
// before any window is created so the value is passed to the preload.
initialAdaptiveColorsDefault = detectInitialAdaptiveColorsDefault();
// Enforce our CSP on all contents
session.defaultSession.webRequest.onHeadersReceived((details, callback) =>
{
callback({
responseHeaders: {
...details.responseHeaders,
// 'wasm-unsafe-eval' is required to compile the inlined libavoid WASM edge
// router; without it this header CSP overrides the more permissive meta CSP
// set in ElectronApp.js (the strictest of multiple policies wins)
'Content-Security-Policy': ['default-src \'self\'; script-src \'self\' \'wasm-unsafe-eval\'; connect-src \'self\'' +
(isGoogleFontsEnabled? ' https://fonts.googleapis.com https://fonts.gstatic.com' : '') + '; img-src * data:; media-src *; font-src * data:; frame-src \'self\'; style-src \'self\' \'unsafe-inline\'' +
(isGoogleFontsEnabled? ' https://fonts.googleapis.com' : '') + '; base-uri \'none\';child-src \'self\';object-src \'none\';']
}
})
});
// Enforce loading file only from our app directory
session.defaultSession.webRequest.onBeforeRequest({urls: ['file://*']}, (details, callback) =>
{
const url = details.url.replace(/\/.\:\//, str => str.toUpperCase());
if (!url.startsWith(codeUrl))
{
console.log('Blocked loading file from ' + details.url, url, codeUrl);
callback({cancel: true});
}
else
{
callback({});
}
});
// Registered once, not per window: per-window handlers leaked on window
// close and crashed the main process on the next openDevTools message
ipcMain.on('openDevTools', (e) =>
{
if (!validateSender(e.senderFrame)) return null;
e.sender.openDevTools();
})
ipcMain.on('newfile', (e, arg) =>
{
if (!validateSender(e.senderFrame)) return null;
let opts = {};
if (arg)
{
if (arg.width)
{
opts.width = arg.width;
}
if (arg.height)
{
opts.height = arg.height;
}
}
createWindow(opts);
})
let argv = process.argv
// https://github.com/electron/electron/issues/4690#issuecomment-217435222
if (process.defaultApp != true)
{
argv.unshift(null)
}
var validFormatRegExp = validFormatRegExpImport;
var { opts: options, args: parsedArgs } = parseDrawioArgs(argv);
if (options.zoom != null)
{
appZoom = options.zoom;
}
//Start export mode?
if (options.export)
{
// Electron shows an uncaught error in a modal dialog, which stalls a CI
// run. Nothing can be trusted after one, so fail the whole export. Also
// stops Electron's dialog, which only shows without other listeners
process.on('uncaughtException', function(e)
{
console.error('Error: uncaught exception: ' + ((e != null && e.stack) || e));
app.exit(1);
});
var dummyWin = new BrowserWindow({
show : false,
webPreferences: {
preload: `${__dirname}/electron-preload.js`,
contextIsolation: true,
nodeIntegration: false,
webviewTag: false,
webSecurity: true,
disableBlinkFeatures: 'Auxclick' // Is this needed?
}
});
windowsRegistry.push(dummyWin);
/*ipcMain.on('log', function(event, msg)
{
console.log(msg);
});*/
try
{
//Prepare arguments and confirm it's valid
var format = null;
var outType = null;
//Format & Output
if (options.output)
{
try
{
var outStat = fs.statSync(options.output);
if (outStat.isDirectory())
{
outType = {isDir: true};
}
else //If we can get file stat, then it exists
{
throw 'Error: Output file already exists';
}
}
catch(e) //on error, file doesn't exist and it is not a dir
{
outType = {isFile: true};
format = path.extname(options.output).substr(1);
if (!validFormatRegExp.test(format))
{
format = null;
}
}
}
if (format == null)
{
format = options.format;
}
let from = null, to = null;
if (options.pageIndex != null)
{
// The 1-based CLI value arrives shifted to 0-based, so 0, negative and
// non-numeric input all land below 0. Page indexes were 0-based before
// v27.0.2 and old scripts pass 0 — fail loudly instead of silently
// exporting the first page [jgraph/drawio-desktop#2319]
if (!(options.pageIndex >= 0))
{
console.error('Invalid page index: pages are numbered from 1 (0-based before v27.0.2)');