-
-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathmain.js
More file actions
4361 lines (3939 loc) · 128 KB
/
main.js
File metadata and controls
4361 lines (3939 loc) · 128 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
// Modules to control application life and create native browser window
const electron = require('electron')
const process = require('process')
const prompt = require('electron-prompt');
const unhandled = require('electron-unhandled');
const fs = require('fs');
const path = require('path');
const {app, BrowserWindow, BrowserView, webFrameMain, desktopCapturer, ipcMain, screen, shell, globalShortcut, session, dialog} = require('electron')
const contextMenu = require('electron-context-menu');
const Yargs = require('yargs')
const isDev = require('electron-is-dev');
ipcMain.on('getSources', async function(eventRet, args) {
try{
const sources = await desktopCapturer.getSources({ types: args.types });
eventRet.returnValue = sources;
} catch(e){console.error(e);}
});
// Test logging handler - forwards renderer logs to main process console
ipcMain.on('test-log', (event, { type, msg }) => {
const prefix = type === 'error' ? '\x1b[31m' : type === 'success' ? '\x1b[32m' : '\x1b[36m';
const reset = '\x1b[0m';
console.log(`${prefix}[TEST:${type.toUpperCase()}]${reset} ${msg}`);
});
const { Readable } = require('stream');
const { fetch: undiciFetch } = require('undici');
const activeStreams = new Map();
const https = require('https');
const { execSync } = require('child_process');
let windowAudioCapture = null;
const WINDOW_AUDIO_EVENT_CHANNEL = 'windowAudioStreamData';
let activeWindowAudioSession = null;
let cachedElevationState;
const namedWindowRegistry = new Map();
function normalizeWindowName(value) {
if (typeof value !== 'string') {
return null;
}
const trimmed = value.trim();
return trimmed.length ? trimmed : null;
}
function getWindowRegistryKey(name) {
const normalized = normalizeWindowName(name);
return normalized ? normalized.toLowerCase() : null;
}
function getNamedWindowInstance(name) {
const key = getWindowRegistryKey(name);
if (!key) {
return null;
}
const instance = namedWindowRegistry.get(key);
if (instance && !instance.isDestroyed()) {
return instance;
}
if (namedWindowRegistry.has(key)) {
namedWindowRegistry.delete(key);
}
return null;
}
function registerNamedWindowInstance(windowInstance, name) {
const key = getWindowRegistryKey(name);
if (!key || !windowInstance) {
return;
}
namedWindowRegistry.set(key, windowInstance);
windowInstance.__namedWindowKey = key;
windowInstance.once('closed', () => {
if (namedWindowRegistry.get(key) === windowInstance) {
namedWindowRegistry.delete(key);
}
});
}
function clearWindowCloseTimers(windowInstance) {
if (!windowInstance) {
return;
}
if (windowInstance.__pendingHangupTimeout) {
clearTimeout(windowInstance.__pendingHangupTimeout);
windowInstance.__pendingHangupTimeout = null;
}
if (windowInstance.__pendingDestroyTimeout) {
clearTimeout(windowInstance.__pendingDestroyTimeout);
windowInstance.__pendingDestroyTimeout = null;
}
windowInstance.__pendingCloseRequested = false;
}
function prepareWindowForReuse(windowInstance, options = {}) {
if (!windowInstance || windowInstance.isDestroyed()) {
return;
}
const shouldShow = options.show !== false;
const initialState = {};
try {
initialState.isVisible = windowInstance.isVisible();
initialState.isMinimized = windowInstance.isMinimized();
initialState.bounds = windowInstance.getBounds();
} catch (error) {
console.warn('Unable to capture initial window state for reuse:', error);
}
console.log('Preparing window for reuse. Initial state:', initialState);
try {
if (windowInstance.isMinimized()) {
windowInstance.restore();
console.log('Restored minimized window prior to reuse.');
}
} catch (error) {
console.warn('Failed to restore window prior to reuse:', error);
}
if (shouldShow) {
try {
if (!windowInstance.isVisible()) {
windowInstance.showInactive();
console.log('Window was hidden; showInactive() invoked prior to reuse.');
}
} catch (error) {
console.warn('Failed to show window prior to reuse:', error);
}
}
}
function getImmutablePreferencesForWindow(windowInstance) {
if (!windowInstance || typeof windowInstance !== 'object') {
return null;
}
if (windowInstance.__immutableWebPreferences && typeof windowInstance.__immutableWebPreferences === 'object') {
return windowInstance.__immutableWebPreferences;
}
if (typeof windowInstance.node === 'boolean') {
const nodeEnabled = !!windowInstance.node;
return {
nodeIntegration: nodeEnabled,
nodeIntegrationInSubFrames: nodeEnabled,
contextIsolation: !nodeEnabled
};
}
return null;
}
function immutablePreferencesMatch(existingWindow, requestedPreferences) {
if (!requestedPreferences || typeof requestedPreferences !== 'object') {
return true;
}
const existingPreferences = getImmutablePreferencesForWindow(existingWindow);
if (!existingPreferences) {
return false;
}
return Object.keys(requestedPreferences).every((key) => existingPreferences[key] === requestedPreferences[key]);
}
// Window bounds persistence for remembering size between sessions
const BOUNDS_FILE = path.join(app.getPath('userData'), 'window-bounds.json');
function saveWindowBounds(bounds) {
try {
fs.writeFileSync(BOUNDS_FILE, JSON.stringify(bounds));
} catch (e) {
// Ignore write errors
}
}
function loadWindowBounds() {
try {
const data = fs.readFileSync(BOUNDS_FILE, 'utf8');
const bounds = JSON.parse(data);
// Validate bounds have required properties
if (bounds && typeof bounds.width === 'number' && typeof bounds.height === 'number') {
return bounds;
}
} catch (e) {
// File doesn't exist or invalid - return null
}
return null;
}
function getScaleFactorForWindow(targetWindow) {
const fallbackScale = () => {
const primary = getPrimaryDisplaySafe();
return (primary && primary.scaleFactor) || 1;
};
if (!targetWindow || targetWindow.isDestroyed()) {
return fallbackScale();
}
const boundsUsable = (rect) =>
rect &&
Number.isFinite(rect.width) &&
Number.isFinite(rect.height) &&
rect.width > 10 &&
rect.height > 10;
let display = null;
let bounds = null;
try {
bounds = targetWindow.getBounds();
} catch (error) {
console.warn('Failed to read window bounds while resolving scale factor:', error);
}
if (boundsUsable(bounds)) {
try {
display = screen.getDisplayMatching(bounds);
} catch (error) {
console.warn('screen.getDisplayMatching failed for active bounds:', error);
}
}
if (!display && typeof targetWindow.getNormalBounds === 'function') {
try {
const normalBounds = targetWindow.getNormalBounds();
if (boundsUsable(normalBounds)) {
display = screen.getDisplayMatching(normalBounds);
}
} catch (error) {
console.warn('Unable to resolve display from normal bounds:', error);
}
}
if (!display && targetWindow.__lastDisplayId) {
const match = getAllDisplaysSorted().find((d) => d.id === targetWindow.__lastDisplayId);
if (match) {
display = match;
}
}
if (!display) {
display = getPrimaryDisplaySafe();
}
return (display && display.scaleFactor) || fallbackScale();
}
function getPrimaryDisplaySafe() {
try {
return screen.getPrimaryDisplay();
} catch (error) {
return null;
}
}
function getAllDisplaysSorted() {
const displays = screen.getAllDisplays();
if (!Array.isArray(displays)) {
return [];
}
return [...displays].sort((a, b) => a.id - b.id);
}
function getPhysicalBoundsForDisplay(display) {
if (!display || !display.bounds) {
return null;
}
const scaleFactor = display.scaleFactor || 1;
return {
x: Math.round(display.bounds.x * scaleFactor),
y: Math.round(display.bounds.y * scaleFactor),
width: Math.round(display.bounds.width * scaleFactor),
height: Math.round(display.bounds.height * scaleFactor)
};
}
function isUsableRect(rect) {
return (
rect &&
Number.isFinite(rect.x) &&
Number.isFinite(rect.y) &&
Number.isFinite(rect.width) &&
Number.isFinite(rect.height) &&
rect.width > 10 &&
rect.height > 10
);
}
function getUsableWindowBounds(windowInstance, options = {}) {
if (!windowInstance || windowInstance.isDestroyed()) {
return null;
}
const preferNormal = options.preferNormal === true;
const attempts = [];
if (!preferNormal) {
attempts.push(() => {
try {
return windowInstance.getBounds();
} catch (error) {
console.warn('Failed to read window bounds:', error);
return null;
}
});
}
if (typeof windowInstance.getNormalBounds === 'function') {
attempts.push(() => {
try {
return windowInstance.getNormalBounds();
} catch (error) {
console.warn('Failed to read normal window bounds:', error);
return null;
}
});
}
if (preferNormal) {
attempts.push(() => {
try {
return windowInstance.getBounds();
} catch (error) {
console.warn('Failed to read window bounds (fallback):', error);
return null;
}
});
}
for (const readBounds of attempts) {
const rect = readBounds();
if (isUsableRect(rect)) {
return rect;
}
}
return null;
}
function rectanglesOverlap(a, b) {
if (!a || !b) {
return false;
}
return (
a.x < b.x + b.width &&
a.x + a.width > b.x &&
a.y < b.y + b.height &&
a.y + a.height > b.y
);
}
function getDisplayWorkArea(display) {
if (!display) {
return null;
}
if (display.workArea && typeof display.workArea === 'object') {
return display.workArea;
}
if (display.bounds && typeof display.bounds === 'object') {
return display.bounds;
}
return null;
}
function findDisplayByPhysicalPoint(point) {
if (!point) {
return null;
}
const displays = getAllDisplaysSorted();
for (const display of displays) {
const bounds = getPhysicalBoundsForDisplay(display);
if (!bounds) {
continue;
}
if (
point.x >= bounds.x &&
point.x < bounds.x + bounds.width &&
point.y >= bounds.y &&
point.y < bounds.y + bounds.height
) {
return display;
}
}
return null;
}
function resolveDisplayForArgs(args) {
const displays = getAllDisplaysSorted();
if (!displays.length) {
return getPrimaryDisplaySafe();
}
if (typeof args.monitor === 'number' && !Number.isNaN(args.monitor) && args.monitor >= 0) {
const index = Math.min(displays.length - 1, Math.floor(args.monitor));
return displays[index];
}
const hasExplicitX = typeof args.x === 'number' && args.x !== -1;
const hasExplicitY = typeof args.y === 'number' && args.y !== -1;
if (hasExplicitX || hasExplicitY) {
try {
const physicalPoint = {
x: hasExplicitX ? args.x : 0,
y: hasExplicitY ? args.y : 0
};
const display = findDisplayByPhysicalPoint(physicalPoint);
if (display) {
return display;
}
const primaryScale = getPrimaryDisplaySafe()?.scaleFactor || 1;
const dipPoint = {
x: Math.round(physicalPoint.x / primaryScale),
y: Math.round(physicalPoint.y / primaryScale)
};
const fallbackDisplay = screen.getDisplayNearestPoint(dipPoint);
if (fallbackDisplay) {
return fallbackDisplay;
}
} catch (error) {
console.warn('Failed to resolve display from coordinates, falling back to primary:', error);
}
}
return displays.find((display) => display.id === getPrimaryDisplaySafe()?.id) || displays[0];
}
function clampPhysicalSizeToDisplay(display, requestedWidth, requestedHeight) {
const safeDisplay = display || getPrimaryDisplaySafe();
const scaleFactor = (safeDisplay && safeDisplay.scaleFactor) || 1;
const workArea = (safeDisplay && safeDisplay.workAreaSize) || (safeDisplay && safeDisplay.size);
if (!workArea) {
return {
width: requestedWidth,
height: requestedHeight
};
}
const maxPhysicalWidth = Math.max(1, Math.round(workArea.width * scaleFactor));
const maxPhysicalHeight = Math.max(1, Math.round(workArea.height * scaleFactor));
let width = requestedWidth;
let height = requestedHeight;
if (typeof width === 'number' && typeof height === 'number') {
if (width > maxPhysicalWidth) {
height = Math.round(height * maxPhysicalWidth / width);
width = maxPhysicalWidth;
}
if (height > maxPhysicalHeight) {
width = Math.round(width * maxPhysicalHeight / height);
height = maxPhysicalHeight;
}
} else if (typeof width === 'number' && width > maxPhysicalWidth) {
width = maxPhysicalWidth;
} else if (typeof height === 'number' && height > maxPhysicalHeight) {
height = maxPhysicalHeight;
}
return { width, height };
}
function applyRequestedWindowSize(windowInstance, options = {}) {
if (!windowInstance || windowInstance.isDestroyed()) {
return;
}
const clampToWorkArea = !!options.clampToWorkArea;
if (windowInstance.isDestroyed()) {
return;
}
if (windowInstance.isFullScreen()) {
return;
}
const requestedWidth = typeof windowInstance.args?.width === 'number' ? windowInstance.args.width : null;
const requestedHeight = typeof windowInstance.args?.height === 'number' ? windowInstance.args.height : null;
if (requestedWidth === null && requestedHeight === null) {
console.log('applyRequestedWindowSize: no explicit width/height provided; skipping resize.');
return;
}
const usableBounds = getUsableWindowBounds(windowInstance);
let display;
try {
if (usableBounds) {
display = screen.getDisplayMatching(usableBounds);
} else {
display = screen.getDisplayMatching(windowInstance.getBounds());
}
} catch (error) {
display = getPrimaryDisplaySafe();
}
const scaleFactor = (display && display.scaleFactor) || 1;
const currentSize = usableBounds ? [usableBounds.width, usableBounds.height] : windowInstance.getSize();
let targetPhysicalWidth = requestedWidth !== null ? requestedWidth : currentSize[0] * scaleFactor;
let targetPhysicalHeight = requestedHeight !== null ? requestedHeight : currentSize[1] * scaleFactor;
if (clampToWorkArea) {
const clamped = clampPhysicalSizeToDisplay(display, targetPhysicalWidth, targetPhysicalHeight);
targetPhysicalWidth = requestedWidth !== null ? clamped.width : targetPhysicalWidth;
targetPhysicalHeight = requestedHeight !== null ? clamped.height : targetPhysicalHeight;
}
const nextWidth = requestedWidth !== null ? Math.max(1, Math.round(targetPhysicalWidth / scaleFactor)) : currentSize[0];
const nextHeight = requestedHeight !== null ? Math.max(1, Math.round(targetPhysicalHeight / scaleFactor)) : currentSize[1];
console.log('applyRequestedWindowSize: computed resize', {
requestedWidth,
requestedHeight,
scaleFactor,
currentSize,
targetPhysicalWidth,
targetPhysicalHeight,
nextWidth,
nextHeight,
displayId: display ? display.id : null
});
if (nextWidth !== currentSize[0] || nextHeight !== currentSize[1]) {
const baseBounds = usableBounds || getUsableWindowBounds(windowInstance, { preferNormal: true });
if (baseBounds) {
windowInstance.setBounds({
x: baseBounds.x,
y: baseBounds.y,
width: nextWidth,
height: nextHeight
});
} else {
windowInstance.setSize(nextWidth, nextHeight);
}
}
windowInstance.__lastDisplayId = display ? display.id : windowInstance.__lastDisplayId;
}
function isWindowBoundsVisible(bounds) {
if (!bounds) {
return true;
}
const displays = getAllDisplaysSorted();
if (!displays.length) {
return true;
}
for (const display of displays) {
const area = getDisplayWorkArea(display);
if (!area) {
continue;
}
if (rectanglesOverlap(bounds, area)) {
return true;
}
}
return false;
}
function repositionWindowToPrimaryDisplay(windowInstance, lastBounds) {
const targetDisplay = getPrimaryDisplaySafe() || getAllDisplaysSorted()[0] || null;
const workArea = getDisplayWorkArea(targetDisplay);
if (!workArea) {
try {
console.log('No workArea available; centering window to keep visible.');
windowInstance.center();
} catch (error) {
console.warn('Failed to center window while ensuring visibility:', error);
}
return;
}
const width = Math.max(
200,
Math.min(lastBounds?.width || workArea.width, workArea.width)
);
const height = Math.max(
200,
Math.min(lastBounds?.height || workArea.height, workArea.height)
);
const nextBounds = {
x: workArea.x + Math.round((workArea.width - width) / 2),
y: workArea.y + Math.round((workArea.height - height) / 2),
width,
height
};
try {
console.log('Repositioning window to primary display with bounds:', nextBounds);
windowInstance.setBounds(nextBounds);
} catch (error) {
console.warn('Failed to reposition window to primary display:', error);
}
}
function ensureWindowVisible(windowInstance, options = {}) {
if (!windowInstance || windowInstance.isDestroyed()) {
return;
}
const shouldFocus = options.focus !== false;
const forceShow = options.forceShow === true;
const usableBounds = getUsableWindowBounds(windowInstance);
const bounds = isUsableRect(usableBounds) ? usableBounds : null;
if (bounds && !isWindowBoundsVisible(bounds)) {
console.log('Window detected off-screen. Attempting to reposition.', bounds);
repositionWindowToPrimaryDisplay(windowInstance, bounds);
}
if (windowInstance.isMinimized()) {
try {
windowInstance.restore();
} catch (error) {
console.warn('Failed to restore window while ensuring visibility:', error);
}
}
if (!windowInstance.isVisible() || forceShow) {
try {
windowInstance.show();
} catch (error) {
console.warn('Failed to show window while ensuring visibility:', error);
}
}
if (shouldFocus) {
try {
windowInstance.focus();
} catch (error) {
console.warn('Failed to focus window while ensuring visibility:', error);
}
}
}
function applyArgsToExistingWindow(windowInstance, args) {
if (!windowInstance || windowInstance.isDestroyed()) {
return false;
}
clearWindowCloseTimers(windowInstance);
prepareWindowForReuse(windowInstance, { show: false });
const mergedArgs = {
...(windowInstance.args || {}),
...args
};
windowInstance.args = mergedArgs;
if (typeof mergedArgs.defaultDragRegion === 'boolean') {
windowInstance.__defaultDragRegionEnabled = mergedArgs.defaultDragRegion;
}
console.log('applyArgsToExistingWindow: merged args', {
windowName: windowInstance.windowName || windowInstance.__namedWindowKey,
width: mergedArgs.width,
height: mergedArgs.height,
x: mergedArgs.x,
y: mergedArgs.y,
min: mergedArgs.min,
fullscreen: mergedArgs.fullscreen,
pin: mergedArgs.pin
});
const factor = getScaleFactorForWindow(windowInstance);
let loggedBounds = null;
try {
loggedBounds = windowInstance.getBounds();
console.log('Reusing window bounds before applying args:', loggedBounds);
} catch (error) {
console.warn('Unable to read bounds before applying args:', error);
}
try {
if (typeof mergedArgs.url === 'string' && mergedArgs.url.length) {
const currentUrl = windowInstance.webContents.getURL();
if (currentUrl !== mergedArgs.url) {
windowInstance.webContents.loadURL(mergedArgs.url);
}
}
const needsExplicitResize = typeof mergedArgs.width === 'number' || typeof mergedArgs.height === 'number';
if (needsExplicitResize) {
const isFullScreen = typeof windowInstance.isFullScreen === 'function' ? windowInstance.isFullScreen() : false;
if (isFullScreen) {
try {
windowInstance.setFullScreen(false);
} catch (error) {
console.warn('Failed to exit fullscreen prior to resize:', error);
}
}
const isMaximized = typeof windowInstance.isMaximized === 'function' ? windowInstance.isMaximized() : false;
if (isMaximized) {
try {
windowInstance.unmaximize();
} catch (error) {
console.warn('Failed to unmaximize prior to resize:', error);
}
}
applyRequestedWindowSize(windowInstance, { clampToWorkArea: true });
try {
console.log('Reusing window bounds after resize:', windowInstance.getBounds());
} catch (error) {
console.warn('Unable to read bounds after resize:', error);
}
}
const hasExplicitX = typeof mergedArgs.x === 'number' && mergedArgs.x !== -1;
const hasExplicitY = typeof mergedArgs.y === 'number' && mergedArgs.y !== -1;
if (hasExplicitX || hasExplicitY) {
const hasValidPosition = hasExplicitX && hasExplicitY;
if (hasValidPosition) {
const nextX = Math.floor(mergedArgs.x / factor);
const nextY = Math.floor(mergedArgs.y / factor);
windowInstance.setPosition(nextX, nextY);
} else {
const currentPosition = windowInstance.getPosition();
const nextX = hasExplicitX ? Math.floor(mergedArgs.x / factor) : currentPosition[0];
const nextY = hasExplicitY ? Math.floor(mergedArgs.y / factor) : currentPosition[1];
windowInstance.setPosition(nextX, nextY);
}
}
if (typeof mergedArgs.pin === 'boolean') {
if (mergedArgs.pin) {
if (process.platform === 'darwin') {
windowInstance.setAlwaysOnTop(true, 'floating', 1);
} else {
windowInstance.setAlwaysOnTop(true, 'level');
}
windowInstance.setVisibleOnAllWorkspaces(true);
} else {
windowInstance.setAlwaysOnTop(false);
windowInstance.setVisibleOnAllWorkspaces(false);
}
}
if (typeof mergedArgs.fullscreen === 'boolean') {
const currentlyFullScreen = typeof windowInstance.isFullScreen === 'function' ? windowInstance.isFullScreen() : false;
if (mergedArgs.fullscreen !== currentlyFullScreen) {
windowInstance.full = mergedArgs.fullscreen;
windowInstance.setFullScreen(mergedArgs.fullscreen);
} else {
windowInstance.full = mergedArgs.fullscreen;
}
}
const shouldMinimize = mergedArgs.min === true;
if (shouldMinimize) {
windowInstance.minimize();
} else {
ensureWindowVisible(windowInstance, { forceShow: true, focus: true });
}
try {
const finalBounds = windowInstance.getBounds();
const normalBounds = typeof windowInstance.getNormalBounds === 'function' ? windowInstance.getNormalBounds() : null;
console.log('applyArgsToExistingWindow: final state', {
isVisible: windowInstance.isVisible(),
isMinimized: windowInstance.isMinimized(),
bounds: finalBounds,
normalBounds
});
} catch (stateError) {
console.warn('applyArgsToExistingWindow: unable to capture final state:', stateError);
}
} catch (error) {
console.error('Failed to apply arguments to existing window:', error);
return false;
}
return true;
}
function isProcessElevated() {
if (typeof cachedElevationState === 'boolean') {
return cachedElevationState;
}
if (process.platform === 'win32') {
try {
execSync('fltmc', { stdio: 'ignore' });
cachedElevationState = true;
} catch (error) {
if (error && error.code === 'ENOENT') {
console.warn('Elevation check failed: fltmc command not available; assuming process is not elevated.');
}
cachedElevationState = false;
}
return cachedElevationState;
}
if (typeof process.getuid === 'function') {
cachedElevationState = process.getuid() === 0;
return cachedElevationState;
}
cachedElevationState = false;
return cachedElevationState;
}
process.on('uncaughtException', function (error) {
console.error("uncaughtException");
console.error(error);
});
unhandled();
try {
console.log('Loading window-audio-capture module...');
windowAudioCapture = require('./native-modules/window-audio-capture');
console.log('Module loaded successfully');
// Test if the module methods exist and log them
const methods = Object.keys(windowAudioCapture);
console.log('Module methods:', methods);
// Check if we have the expected API structure
if (!windowAudioCapture.getWindowList && windowAudioCapture.captureInstance) {
console.log('Module has captureInstance structure');
}
// Test the getWindowList function
try {
let windows;
if (windowAudioCapture.getWindowList) {
windows = windowAudioCapture.getWindowList();
} else if (windowAudioCapture.captureInstance && windowAudioCapture.captureInstance.getWindowList) {
windows = windowAudioCapture.captureInstance.getWindowList();
}
console.log('Windows list type:', typeof windows);
console.log('Is array:', Array.isArray(windows));
console.log('Windows length:', windows ? (Array.isArray(windows) ? windows.length : 'not an array') : 'undefined');
console.log('First window:', windows && windows.length > 0 ? windows[0] : 'none');
} catch (testError) {
console.error('Error testing getWindowList:', testError);
}
} catch (err) {
console.error('Error loading window-audio-capture module:', err);
}
// Load ASIO audio capture module (Windows only)
let asioIpcHandlers = null;
try {
if (process.platform === 'win32') {
console.log('Loading electron-asio module...');
asioIpcHandlers = require('./native-modules/electron-asio/preload/ipc-handlers');
asioIpcHandlers.setupAsioIpc(ipcMain);
console.log('ASIO IPC handlers registered');
}
} catch (err) {
console.warn('ASIO module not available:', err.message);
}
var ver = app.getVersion();
const DEFAULT_URL = `https://vdo.ninja/electron?version=${ver}`;
function createYargs(){
var argv = Yargs.usage('Usage: $0 -w=num -h=num -u="string" -p')
.example(
'$0 -w=1280 -h=720 -u="https://vdo.ninja/?view=xxxx"',
"Loads the stream with ID xxxx into a window sized 1280x720"
)
.option("w", {
alias: "width",
describe: "The width of the window in pixel.",
type: "number",
nargs: 1,
default: 1280
})
.option("h", {
alias: "height",
describe: "The height of the window in pixels.",
type: "number",
nargs: 1,
default: 720
})
.option("monitor", {
alias: "m",
describe: "Monitor index to open on (0-based index)",
type: "number",
default: 0
})
.option("u", {
alias: "url",
describe: "The URL of the window to load.",
default: DEFAULT_URL,
type: "string"
})
.option("t", {
alias: "title",
describe: "The default Title for the app Window",
type: "string",
default: null
})
.option("p", {
alias: "pin",
describe: "Toggle always on top",
type: "boolean",
default: process.platform == 'darwin'
})
.option("a", {
alias: "hwa",
describe: "Enable Hardware Acceleration",
type: "boolean",
default: true
})
.option("x", {
alias: "x",
describe: "Window X position",
type: "number",
nargs: 1,
default: -1
})
.option("y", {
alias: "y",
describe: "Window Y position",
type: "number",
nargs: 1,
default: -1
})
.option("node", {
alias: "n",
describe: "Enables node-integration, allowing for screen capture, global hotkeys, prompts, and more.",
type: "boolean",
default: false
})
.option("minimized", {
alias: "min",
describe: "Starts the window minimized",
type: "boolean",
default: false
})
.option("fullscreen", {
alias: "f",
describe: "Enables full-screen mode for the first window on its load.",
type: "boolean",
default: false
})
.option("defaultDragRegion", {
alias: "dragbar",
describe: "Inject a transparent draggable strip when the page does not provide its own -webkit-app-region: drag.",
type: "boolean",
default: true
})
.option("multiinstance", {
alias: ["standalone"],
describe: "Opt-out of the single-instance lock so this run stays isolated from other launches.",
type: "boolean",
default: false
})
.option("unclickable", {
alias: "uc",
describe: "The page will pass thru any mouse clicks or other mouse events",
type: "boolean",
default: false
})
.option("js", {
alias: "js",
describe: "Have local JavaScript script be auto-loaded into every page",
type: "string",
default: null
})
.option("savefolder", {
alias: "sf",
describe: "Where to save a file on disk",
type: "string",
default: null
})
.option("mediafoundation", {
alias: "mf",
describe: "Enable media foundation video capture",
type: "string",
default: null
})
.option("disablemediafoundation", {
alias: "dmf",
describe: "Disable media foundation video capture; helps capture some webcams",
type: "string",
default: null
})
.option("css", {
alias: "css",
describe: "Have local CSS script be auto-loaded into every page",
type: "string",
default: null
})
.option("chroma", {
alias: "color",
describe: "Set background CSS to target hex color; FFF or 0000 are examples.",
type: "string",
default: null
})
.option("hidecursor", {
alias: "hc",
describe: "Hide the mouse pointer / cursor",
type: "boolean",
default: null
})
.option("usewgc", {
alias: "wgc",
describe: "Allow Windows Graphics Capture backend. Disable for better compatibility when running elevated.",
type: "boolean"
})
.option("d3d12Encoder", {
alias: "d3d12enc",
describe: "Enable D3D12 hardware video encoders on Windows when supported.",
type: "boolean",
default: false
})
.option("vaapiEncoder", {
alias: "vaapienc",
describe: "Enable VA-API hardware video encoders on Linux when supported.",
type: "boolean",
default: true
})
.option("ignoreGpuBlocklist", {
alias: "ignoregpub",
describe: "Ignore Chromium's GPU blocklist (forces hardware acceleration even when blocklisted).",
type: "boolean",
default: false
})
.option("respectGpuBlocklist", {