-
Notifications
You must be signed in to change notification settings - Fork 30.4k
/
Copy pathwindowImpl.ts
1490 lines (1216 loc) · 53.9 KB
/
windowImpl.ts
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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import electron, { BrowserWindowConstructorOptions } from 'electron';
import { DeferredPromise, RunOnceScheduler, timeout } from 'vs/base/common/async';
import { CancellationToken } from 'vs/base/common/cancellation';
import { toErrorMessage } from 'vs/base/common/errorMessage';
import { Emitter, Event } from 'vs/base/common/event';
import { Disposable } from 'vs/base/common/lifecycle';
import { FileAccess, Schemas } from 'vs/base/common/network';
import { getMarks, mark } from 'vs/base/common/performance';
import { isBigSurOrNewer, isMacintosh, isWindows } from 'vs/base/common/platform';
import { URI } from 'vs/base/common/uri';
import { localize } from 'vs/nls';
import { release } from 'os';
import { ISerializableCommandAction } from 'vs/platform/action/common/action';
import { IBackupMainService } from 'vs/platform/backup/electron-main/backup';
import { IConfigurationChangeEvent, IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IDialogMainService } from 'vs/platform/dialogs/electron-main/dialogMainService';
import { NativeParsedArgs } from 'vs/platform/environment/common/argv';
import { IEnvironmentMainService } from 'vs/platform/environment/electron-main/environmentMainService';
import { isLaunchedFromCli } from 'vs/platform/environment/node/argvHelper';
import { IFileService } from 'vs/platform/files/common/files';
import { ILifecycleMainService } from 'vs/platform/lifecycle/electron-main/lifecycleMainService';
import { ILogService } from 'vs/platform/log/common/log';
import { IProductService } from 'vs/platform/product/common/productService';
import { IProtocolMainService } from 'vs/platform/protocol/electron-main/protocol';
import { resolveMarketplaceHeaders } from 'vs/platform/externalServices/common/marketplace';
import { IApplicationStorageMainService, IStorageMainService } from 'vs/platform/storage/electron-main/storageMainService';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { ThemeIcon } from 'vs/base/common/themables';
import { IThemeMainService } from 'vs/platform/theme/electron-main/themeMainService';
import { getMenuBarVisibility, IFolderToOpen, INativeWindowConfiguration, IWindowSettings, IWorkspaceToOpen, MenuBarVisibility, hasNativeTitlebar, useNativeFullScreen, useWindowControlsOverlay, DEFAULT_CUSTOM_TITLEBAR_HEIGHT, TitlebarStyle } from 'vs/platform/window/common/window';
import { defaultBrowserWindowOptions, IWindowsMainService, OpenContext, WindowStateValidator } from 'vs/platform/windows/electron-main/windows';
import { ISingleFolderWorkspaceIdentifier, IWorkspaceIdentifier, isSingleFolderWorkspaceIdentifier, isWorkspaceIdentifier, toWorkspaceIdentifier } from 'vs/platform/workspace/common/workspace';
import { IWorkspacesManagementMainService } from 'vs/platform/workspaces/electron-main/workspacesManagementMainService';
import { IWindowState, ICodeWindow, ILoadEvent, WindowMode, WindowError, LoadReason, defaultWindowState, IBaseWindow } from 'vs/platform/window/electron-main/window';
import { IPolicyService } from 'vs/platform/policy/common/policy';
import { IUserDataProfile } from 'vs/platform/userDataProfile/common/userDataProfile';
import { IStateService } from 'vs/platform/state/node/state';
import { IUserDataProfilesMainService } from 'vs/platform/userDataProfile/electron-main/userDataProfile';
import { ILoggerMainService } from 'vs/platform/log/electron-main/loggerService';
import { firstOrDefault } from 'vs/base/common/arrays';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { isESM } from 'vs/base/common/amd';
export interface IWindowCreationOptions {
readonly state: IWindowState;
readonly extensionDevelopmentPath?: string[];
readonly isExtensionTestHost?: boolean;
}
interface ITouchBarSegment extends electron.SegmentedControlSegment {
readonly id: string;
}
interface ILoadOptions {
readonly isReload?: boolean;
readonly disableExtensions?: boolean;
}
const enum ReadyState {
/**
* This window has not loaded anything yet
* and this is the initial state of every
* window.
*/
NONE,
/**
* This window is navigating, either for the
* first time or subsequent times.
*/
NAVIGATING,
/**
* This window has finished loading and is ready
* to forward IPC requests to the web contents.
*/
READY
}
export abstract class BaseWindow extends Disposable implements IBaseWindow {
//#region Events
private readonly _onDidClose = this._register(new Emitter<void>());
readonly onDidClose = this._onDidClose.event;
private readonly _onDidMaximize = this._register(new Emitter<void>());
readonly onDidMaximize = this._onDidMaximize.event;
private readonly _onDidUnmaximize = this._register(new Emitter<void>());
readonly onDidUnmaximize = this._onDidUnmaximize.event;
private readonly _onDidTriggerSystemContextMenu = this._register(new Emitter<{ x: number; y: number }>());
readonly onDidTriggerSystemContextMenu = this._onDidTriggerSystemContextMenu.event;
private readonly _onDidEnterFullScreen = this._register(new Emitter<void>());
readonly onDidEnterFullScreen = this._onDidEnterFullScreen.event;
private readonly _onDidLeaveFullScreen = this._register(new Emitter<void>());
readonly onDidLeaveFullScreen = this._onDidLeaveFullScreen.event;
//#endregion
abstract readonly id: number;
protected _lastFocusTime = Date.now(); // window is shown on creation so take current time
get lastFocusTime(): number { return this._lastFocusTime; }
protected _win: electron.BrowserWindow | null = null;
get win() { return this._win; }
protected setWin(win: electron.BrowserWindow, options?: BrowserWindowConstructorOptions): void {
this._win = win;
// Window Events
this._register(Event.fromNodeEventEmitter(win, 'maximize')(() => this._onDidMaximize.fire()));
this._register(Event.fromNodeEventEmitter(win, 'unmaximize')(() => this._onDidUnmaximize.fire()));
this._register(Event.fromNodeEventEmitter(win, 'closed')(() => {
this._onDidClose.fire();
this.dispose();
}));
this._register(Event.fromNodeEventEmitter(win, 'focus')(() => {
this._lastFocusTime = Date.now();
}));
this._register(Event.fromNodeEventEmitter(this._win, 'enter-full-screen')(() => this._onDidEnterFullScreen.fire()));
this._register(Event.fromNodeEventEmitter(this._win, 'leave-full-screen')(() => this._onDidLeaveFullScreen.fire()));
// Sheet Offsets
const useCustomTitleStyle = !hasNativeTitlebar(this.configurationService, options?.titleBarStyle === 'hidden' ? TitlebarStyle.CUSTOM : undefined /* unknown */);
if (isMacintosh && useCustomTitleStyle) {
win.setSheetOffset(isBigSurOrNewer(release()) ? 28 : 22); // offset dialogs by the height of the custom title bar if we have any
}
// Update the window controls immediately based on cached or default values
if (useCustomTitleStyle && (useWindowControlsOverlay(this.configurationService) || isMacintosh)) {
const cachedWindowControlHeight = this.stateService.getItem<number>((BaseWindow.windowControlHeightStateStorageKey));
if (cachedWindowControlHeight) {
this.updateWindowControls({ height: cachedWindowControlHeight });
} else {
this.updateWindowControls({ height: DEFAULT_CUSTOM_TITLEBAR_HEIGHT });
}
}
// Windows Custom System Context Menu
// See https://github.com/electron/electron/issues/24893
//
// The purpose of this is to allow for the context menu in the Windows Title Bar
//
// Currently, all mouse events in the title bar are captured by the OS
// thus we need to capture them here with a window hook specific to Windows
// and then forward them to the correct window.
if (isWindows && useCustomTitleStyle) {
const WM_INITMENU = 0x0116; // https://docs.microsoft.com/en-us/windows/win32/menurc/wm-initmenu
// This sets up a listener for the window hook. This is a Windows-only API provided by electron.
win.hookWindowMessage(WM_INITMENU, () => {
const [x, y] = win.getPosition();
const cursorPos = electron.screen.getCursorScreenPoint();
const cx = cursorPos.x - x;
const cy = cursorPos.y - y;
// In some cases, show the default system context menu
// 1) The mouse position is not within the title bar
// 2) The mouse position is within the title bar, but over the app icon
// We do not know the exact title bar height but we make an estimate based on window height
const shouldTriggerDefaultSystemContextMenu = () => {
// Use the custom context menu when over the title bar, but not over the app icon
// The app icon is estimated to be 30px wide
// The title bar is estimated to be the max of 35px and 15% of the window height
if (cx > 30 && cy >= 0 && cy <= Math.max(win.getBounds().height * 0.15, 35)) {
return false;
}
return true;
};
if (!shouldTriggerDefaultSystemContextMenu()) {
// This is necessary to make sure the native system context menu does not show up.
win.setEnabled(false);
win.setEnabled(true);
this._onDidTriggerSystemContextMenu.fire({ x: cx, y: cy });
}
return 0;
});
}
// Open devtools if instructed from command line args
if (this.environmentMainService.args['open-devtools'] === true) {
win.webContents.openDevTools();
}
// macOS: Window Fullscreen Transitions
if (isMacintosh) {
this._register(this.onDidEnterFullScreen(() => {
this.joinNativeFullScreenTransition?.complete(true);
}));
this._register(this.onDidLeaveFullScreen(() => {
this.joinNativeFullScreenTransition?.complete(true);
}));
}
}
constructor(
protected readonly configurationService: IConfigurationService,
protected readonly stateService: IStateService,
protected readonly environmentMainService: IEnvironmentMainService,
protected readonly logService: ILogService
) {
super();
}
protected applyState(state: IWindowState, hasMultipleDisplays = electron.screen.getAllDisplays().length > 0): void {
// TODO@electron (Electron 4 regression): when running on multiple displays where the target display
// to open the window has a larger resolution than the primary display, the window will not size
// correctly unless we set the bounds again (https://github.com/microsoft/vscode/issues/74872)
//
// Extended to cover Windows as well as Mac (https://github.com/microsoft/vscode/issues/146499)
//
// However, when running with native tabs with multiple windows we cannot use this workaround
// because there is a potential that the new window will be added as native tab instead of being
// a window on its own. In that case calling setBounds() would cause https://github.com/microsoft/vscode/issues/75830
const windowSettings = this.configurationService.getValue<IWindowSettings | undefined>('window');
const useNativeTabs = isMacintosh && windowSettings?.nativeTabs === true;
if ((isMacintosh || isWindows) && hasMultipleDisplays && (!useNativeTabs || electron.BrowserWindow.getAllWindows().length === 1)) {
if ([state.width, state.height, state.x, state.y].every(value => typeof value === 'number')) {
this._win?.setBounds({
width: state.width,
height: state.height,
x: state.x,
y: state.y
});
}
}
if (state.mode === WindowMode.Maximized || state.mode === WindowMode.Fullscreen) {
// this call may or may not show the window, depends
// on the platform: currently on Windows and Linux will
// show the window as active. To be on the safe side,
// we show the window at the end of this block.
this._win?.maximize();
if (state.mode === WindowMode.Fullscreen) {
this.setFullScreen(true, true);
}
// to reduce flicker from the default window size
// to maximize or fullscreen, we only show after
this._win?.show();
}
}
private representedFilename: string | undefined;
setRepresentedFilename(filename: string): void {
if (isMacintosh) {
this.win?.setRepresentedFilename(filename);
} else {
this.representedFilename = filename;
}
}
getRepresentedFilename(): string | undefined {
if (isMacintosh) {
return this.win?.getRepresentedFilename();
}
return this.representedFilename;
}
private documentEdited: boolean | undefined;
setDocumentEdited(edited: boolean): void {
if (isMacintosh) {
this.win?.setDocumentEdited(edited);
}
this.documentEdited = edited;
}
isDocumentEdited(): boolean {
if (isMacintosh) {
return Boolean(this.win?.isDocumentEdited());
}
return !!this.documentEdited;
}
focus(options?: { force: boolean }): void {
if (isMacintosh && options?.force) {
electron.app.focus({ steal: true });
}
const win = this.win;
if (!win) {
return;
}
if (win.isMinimized()) {
win.restore();
}
win.focus();
}
handleTitleDoubleClick(): void {
const win = this.win;
if (!win) {
return;
}
// Respect system settings on mac with regards to title click on windows title
if (isMacintosh) {
const action = electron.systemPreferences.getUserDefault('AppleActionOnDoubleClick', 'string');
switch (action) {
case 'Minimize':
win.minimize();
break;
case 'None':
break;
case 'Maximize':
default:
if (win.isMaximized()) {
win.unmaximize();
} else {
win.maximize();
}
}
}
// Linux/Windows: just toggle maximize/minimized state
else {
if (win.isMaximized()) {
win.unmaximize();
} else {
win.maximize();
}
}
}
//#region Window Control Overlays
private static readonly windowControlHeightStateStorageKey = 'windowControlHeight';
private readonly hasWindowControlOverlay = useWindowControlsOverlay(this.configurationService);
updateWindowControls(options: { height?: number; backgroundColor?: string; foregroundColor?: string }): void {
const win = this.win;
if (!win) {
return;
}
// Cache the height for speeds lookups on startup
if (options.height) {
this.stateService.setItem((CodeWindow.windowControlHeightStateStorageKey), options.height);
}
// Windows/Linux: window control overlay (WCO)
if (this.hasWindowControlOverlay) {
win.setTitleBarOverlay({
color: options.backgroundColor?.trim() === '' ? undefined : options.backgroundColor,
symbolColor: options.foregroundColor?.trim() === '' ? undefined : options.foregroundColor,
height: options.height ? options.height - 1 : undefined // account for window border
});
}
// macOS: traffic lights
else if (isMacintosh && options.height !== undefined) {
const verticalOffset = (options.height - 15) / 2; // 15px is the height of the traffic lights
if (!verticalOffset) {
win.setWindowButtonPosition(null);
} else {
win.setWindowButtonPosition({ x: verticalOffset, y: verticalOffset });
}
}
}
//#endregion
//#region Fullscreen
private transientIsNativeFullScreen: boolean | undefined = undefined;
private joinNativeFullScreenTransition: DeferredPromise<boolean> | undefined = undefined;
toggleFullScreen(): void {
this.setFullScreen(!this.isFullScreen, false);
}
protected setFullScreen(fullscreen: boolean, fromRestore: boolean): void {
// Set fullscreen state
if (useNativeFullScreen(this.configurationService)) {
this.setNativeFullScreen(fullscreen, fromRestore);
} else {
this.setSimpleFullScreen(fullscreen);
}
}
get isFullScreen(): boolean {
if (isMacintosh && typeof this.transientIsNativeFullScreen === 'boolean') {
return this.transientIsNativeFullScreen;
}
const win = this.win;
const isFullScreen = win?.isFullScreen();
const isSimpleFullScreen = win?.isSimpleFullScreen();
return Boolean(isFullScreen || isSimpleFullScreen);
}
private setNativeFullScreen(fullscreen: boolean, fromRestore: boolean): void {
const win = this.win;
if (win?.isSimpleFullScreen()) {
win?.setSimpleFullScreen(false);
}
this.doSetNativeFullScreen(fullscreen, fromRestore);
}
private doSetNativeFullScreen(fullscreen: boolean, fromRestore: boolean): void {
if (isMacintosh) {
// macOS: Electron windows report `false` for `isFullScreen()` for as long
// as the fullscreen transition animation takes place. As such, we need to
// listen to the transition events and carry around an intermediate state
// for knowing if we are in fullscreen or not
// Refs: https://github.com/electron/electron/issues/35360
this.transientIsNativeFullScreen = fullscreen;
const joinNativeFullScreenTransition = this.joinNativeFullScreenTransition = new DeferredPromise<boolean>();
(async () => {
const transitioned = await Promise.race([
joinNativeFullScreenTransition.p,
timeout(10000).then(() => false)
]);
if (this.joinNativeFullScreenTransition !== joinNativeFullScreenTransition) {
return; // another transition was requested later
}
this.transientIsNativeFullScreen = undefined;
this.joinNativeFullScreenTransition = undefined;
// There is one interesting gotcha on macOS: when you are opening a new
// window from a fullscreen window, that new window will immediately
// open fullscreen and emit the `enter-full-screen` event even before we
// reach this method. In that case, we actually will timeout after 10s
// for detecting the transition and as such it is important that we only
// signal to leave fullscreen if the window reports as not being in fullscreen.
if (!transitioned && fullscreen && fromRestore && this.win && !this.win.isFullScreen()) {
// We have seen requests for fullscreen failing eventually after some
// time, for example when an OS update was performed and windows restore.
// In those cases a user would find a window that is not in fullscreen
// but also does not show any custom titlebar (and thus window controls)
// because we think the window is in fullscreen.
//
// As a workaround in that case we emit a warning and leave fullscreen
// so that at least the window controls are back.
this.logService.warn('window: native macOS fullscreen transition did not happen within 10s from restoring');
this._onDidLeaveFullScreen.fire();
}
})();
}
const win = this.win;
win?.setFullScreen(fullscreen);
}
private setSimpleFullScreen(fullscreen: boolean): void {
const win = this.win;
if (win?.isFullScreen()) {
this.doSetNativeFullScreen(false, false);
}
win?.setSimpleFullScreen(fullscreen);
win?.webContents.focus(); // workaround issue where focus is not going into window
}
//#endregion
abstract matches(webContents: electron.WebContents): boolean;
override dispose(): void {
super.dispose();
this._win = null!; // Important to dereference the window object to allow for GC
}
}
export class CodeWindow extends BaseWindow implements ICodeWindow {
//#region Events
private readonly _onWillLoad = this._register(new Emitter<ILoadEvent>());
readonly onWillLoad = this._onWillLoad.event;
private readonly _onDidSignalReady = this._register(new Emitter<void>());
readonly onDidSignalReady = this._onDidSignalReady.event;
private readonly _onDidDestroy = this._register(new Emitter<void>());
readonly onDidDestroy = this._onDidDestroy.event;
//#endregion
//#region Properties
private _id: number;
get id(): number { return this._id; }
protected override _win: electron.BrowserWindow;
get backupPath(): string | undefined { return this._config?.backupPath; }
get openedWorkspace(): IWorkspaceIdentifier | ISingleFolderWorkspaceIdentifier | undefined { return this._config?.workspace; }
get profile(): IUserDataProfile | undefined {
if (!this.config) {
return undefined;
}
const profile = this.userDataProfilesService.profiles.find(profile => profile.id === this.config?.profiles.profile.id);
if (this.isExtensionDevelopmentHost && profile) {
return profile;
}
return this.userDataProfilesService.getProfileForWorkspace(this.config.workspace ?? toWorkspaceIdentifier(this.backupPath, this.isExtensionDevelopmentHost)) ?? this.userDataProfilesService.defaultProfile;
}
get remoteAuthority(): string | undefined { return this._config?.remoteAuthority; }
private _config: INativeWindowConfiguration | undefined;
get config(): INativeWindowConfiguration | undefined { return this._config; }
get isExtensionDevelopmentHost(): boolean { return !!(this._config?.extensionDevelopmentPath); }
get isExtensionTestHost(): boolean { return !!(this._config?.extensionTestsPath); }
get isExtensionDevelopmentTestFromCli(): boolean { return this.isExtensionDevelopmentHost && this.isExtensionTestHost && !this._config?.debugId; }
//#endregion
private readonly windowState: IWindowState;
private currentMenuBarVisibility: MenuBarVisibility | undefined;
private readonly whenReadyCallbacks: { (window: ICodeWindow): void }[] = [];
private readonly touchBarGroups: electron.TouchBarSegmentedControl[] = [];
private currentHttpProxy: string | undefined = undefined;
private currentNoProxy: string | undefined = undefined;
private customZoomLevel: number | undefined = undefined;
private readonly configObjectUrl = this._register(this.protocolMainService.createIPCObjectUrl<INativeWindowConfiguration>());
private pendingLoadConfig: INativeWindowConfiguration | undefined;
private wasLoaded = false;
constructor(
config: IWindowCreationOptions,
@ILogService logService: ILogService,
@ILoggerMainService private readonly loggerMainService: ILoggerMainService,
@IEnvironmentMainService environmentMainService: IEnvironmentMainService,
@IPolicyService private readonly policyService: IPolicyService,
@IUserDataProfilesMainService private readonly userDataProfilesService: IUserDataProfilesMainService,
@IFileService private readonly fileService: IFileService,
@IApplicationStorageMainService private readonly applicationStorageMainService: IApplicationStorageMainService,
@IStorageMainService private readonly storageMainService: IStorageMainService,
@IConfigurationService configurationService: IConfigurationService,
@IThemeMainService private readonly themeMainService: IThemeMainService,
@IWorkspacesManagementMainService private readonly workspacesManagementMainService: IWorkspacesManagementMainService,
@IBackupMainService private readonly backupMainService: IBackupMainService,
@ITelemetryService private readonly telemetryService: ITelemetryService,
@IDialogMainService private readonly dialogMainService: IDialogMainService,
@ILifecycleMainService private readonly lifecycleMainService: ILifecycleMainService,
@IProductService private readonly productService: IProductService,
@IProtocolMainService private readonly protocolMainService: IProtocolMainService,
@IWindowsMainService private readonly windowsMainService: IWindowsMainService,
@IStateService stateService: IStateService,
@IInstantiationService instantiationService: IInstantiationService
) {
super(configurationService, stateService, environmentMainService, logService);
//#region create browser window
{
// Load window state
const [state, hasMultipleDisplays] = this.restoreWindowState(config.state);
this.windowState = state;
this.logService.trace('window#ctor: using window state', state);
const options = instantiationService.invokeFunction(defaultBrowserWindowOptions, this.windowState, undefined, {
preload: FileAccess.asFileUri('vs/base/parts/sandbox/electron-sandbox/preload.js').fsPath,
additionalArguments: [`--vscode-window-config=${this.configObjectUrl.resource.toString()}`],
v8CacheOptions: this.environmentMainService.useCodeCache ? 'bypassHeatCheck' : 'none',
});
// Create the browser window
mark('code/willCreateCodeBrowserWindow');
this._win = new electron.BrowserWindow(options);
mark('code/didCreateCodeBrowserWindow');
this._id = this._win.id;
this.setWin(this._win, options);
// Apply some state after window creation
this.applyState(this.windowState, hasMultipleDisplays);
this._lastFocusTime = Date.now(); // since we show directly, we need to set the last focus time too
}
//#endregion
// respect configured menu bar visibility
this.onConfigurationUpdated();
// macOS: touch bar support
this.createTouchBar();
// Eventing
this.registerListeners();
}
private readyState = ReadyState.NONE;
setReady(): void {
this.logService.trace(`window#load: window reported ready (id: ${this._id})`);
this.readyState = ReadyState.READY;
// inform all waiting promises that we are ready now
while (this.whenReadyCallbacks.length) {
this.whenReadyCallbacks.pop()!(this);
}
// Events
this._onDidSignalReady.fire();
}
ready(): Promise<ICodeWindow> {
return new Promise<ICodeWindow>(resolve => {
if (this.isReady) {
return resolve(this);
}
// otherwise keep and call later when we are ready
this.whenReadyCallbacks.push(resolve);
});
}
get isReady(): boolean {
return this.readyState === ReadyState.READY;
}
get whenClosedOrLoaded(): Promise<void> {
return new Promise<void>(resolve => {
function handle() {
closeListener.dispose();
loadListener.dispose();
resolve();
}
const closeListener = this.onDidClose(() => handle());
const loadListener = this.onWillLoad(() => handle());
});
}
private registerListeners(): void {
// Window error conditions to handle
this._register(Event.fromNodeEventEmitter(this._win, 'unresponsive')(() => this.onWindowError(WindowError.UNRESPONSIVE)));
this._register(Event.fromNodeEventEmitter(this._win.webContents, 'render-process-gone', (event, details) => details)(details => this.onWindowError(WindowError.PROCESS_GONE, { ...details })));
this._register(Event.fromNodeEventEmitter(this._win.webContents, 'did-fail-load', (event, exitCode, reason) => ({ exitCode, reason }))(({ exitCode, reason }) => this.onWindowError(WindowError.LOAD, { reason, exitCode })));
// Prevent windows/iframes from blocking the unload
// through DOM events. We have our own logic for
// unloading a window that should not be confused
// with the DOM way.
// (https://github.com/microsoft/vscode/issues/122736)
this._register(Event.fromNodeEventEmitter<electron.Event>(this._win.webContents, 'will-prevent-unload')(event => event.preventDefault()));
// Remember that we loaded
this._register(Event.fromNodeEventEmitter(this._win.webContents, 'did-finish-load')(() => {
// Associate properties from the load request if provided
if (this.pendingLoadConfig) {
this._config = this.pendingLoadConfig;
this.pendingLoadConfig = undefined;
}
}));
// Window (Un)Maximize
this._register(this.onDidMaximize(() => {
if (this._config) {
this._config.maximized = true;
}
}));
this._register(this.onDidUnmaximize(() => {
if (this._config) {
this._config.maximized = false;
}
}));
// Window Fullscreen
this._register(this.onDidEnterFullScreen(() => {
this.sendWhenReady('vscode:enterFullScreen', CancellationToken.None);
}));
this._register(this.onDidLeaveFullScreen(() => {
this.sendWhenReady('vscode:leaveFullScreen', CancellationToken.None);
}));
// Handle configuration changes
this._register(this.configurationService.onDidChangeConfiguration(e => this.onConfigurationUpdated(e)));
// Handle Workspace events
this._register(this.workspacesManagementMainService.onDidDeleteUntitledWorkspace(e => this.onDidDeleteUntitledWorkspace(e)));
// Inject headers when requests are incoming
const urls = ['https://marketplace.visualstudio.com/*', 'https://*.vsassets.io/*'];
this._win.webContents.session.webRequest.onBeforeSendHeaders({ urls }, async (details, cb) => {
const headers = await this.getMarketplaceHeaders();
cb({ cancel: false, requestHeaders: Object.assign(details.requestHeaders, headers) });
});
}
private marketplaceHeadersPromise: Promise<object> | undefined;
private getMarketplaceHeaders(): Promise<object> {
if (!this.marketplaceHeadersPromise) {
this.marketplaceHeadersPromise = resolveMarketplaceHeaders(
this.productService.version,
this.productService,
this.environmentMainService,
this.configurationService,
this.fileService,
this.applicationStorageMainService,
this.telemetryService);
}
return this.marketplaceHeadersPromise;
}
private async onWindowError(error: WindowError.UNRESPONSIVE): Promise<void>;
private async onWindowError(error: WindowError.PROCESS_GONE, details: { reason: string; exitCode: number }): Promise<void>;
private async onWindowError(error: WindowError.LOAD, details: { reason: string; exitCode: number }): Promise<void>;
private async onWindowError(type: WindowError, details?: { reason?: string; exitCode?: number }): Promise<void> {
switch (type) {
case WindowError.PROCESS_GONE:
this.logService.error(`CodeWindow: renderer process gone (reason: ${details?.reason || '<unknown>'}, code: ${details?.exitCode || '<unknown>'})`);
break;
case WindowError.UNRESPONSIVE:
this.logService.error('CodeWindow: detected unresponsive');
break;
case WindowError.LOAD:
this.logService.error(`CodeWindow: failed to load (reason: ${details?.reason || '<unknown>'}, code: ${details?.exitCode || '<unknown>'})`);
break;
}
// Telemetry
type WindowErrorClassification = {
type: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; comment: 'The type of window error to understand the nature of the error better.' };
reason: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; comment: 'The reason of the window error to understand the nature of the error better.' };
code: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; comment: 'The exit code of the window process to understand the nature of the error better' };
owner: 'bpasero';
comment: 'Provides insight into reasons the vscode window had an error.';
};
type WindowErrorEvent = {
type: WindowError;
reason: string | undefined;
code: number | undefined;
};
this.telemetryService.publicLog2<WindowErrorEvent, WindowErrorClassification>('windowerror', {
type,
reason: details?.reason,
code: details?.exitCode
});
// Inform User if non-recoverable
switch (type) {
case WindowError.UNRESPONSIVE:
case WindowError.PROCESS_GONE:
// If we run extension tests from CLI, we want to signal
// back this state to the test runner by exiting with a
// non-zero exit code.
if (this.isExtensionDevelopmentTestFromCli) {
this.lifecycleMainService.kill(1);
return;
}
// If we run smoke tests, want to proceed with an orderly
// shutdown as much as possible by destroying the window
// and then calling the normal `quit` routine.
if (this.environmentMainService.args['enable-smoke-test-driver']) {
await this.destroyWindow(false, false);
this.lifecycleMainService.quit(); // still allow for an orderly shutdown
return;
}
// Unresponsive
if (type === WindowError.UNRESPONSIVE) {
if (this.isExtensionDevelopmentHost || this.isExtensionTestHost || (this._win && this._win.webContents && this._win.webContents.isDevToolsOpened())) {
// TODO@electron Workaround for https://github.com/microsoft/vscode/issues/56994
// In certain cases the window can report unresponsiveness because a breakpoint was hit
// and the process is stopped executing. The most typical cases are:
// - devtools are opened and debugging happens
// - window is an extensions development host that is being debugged
// - window is an extension test development host that is being debugged
return;
}
// Show Dialog
const { response, checkboxChecked } = await this.dialogMainService.showMessageBox({
type: 'warning',
buttons: [
localize({ key: 'reopen', comment: ['&& denotes a mnemonic'] }, "&&Reopen"),
localize({ key: 'close', comment: ['&& denotes a mnemonic'] }, "&&Close"),
localize({ key: 'wait', comment: ['&& denotes a mnemonic'] }, "&&Keep Waiting")
],
message: localize('appStalled', "The window is not responding"),
detail: localize('appStalledDetail', "You can reopen or close the window or keep waiting."),
checkboxLabel: this._config?.workspace ? localize('doNotRestoreEditors', "Don't restore editors") : undefined
}, this._win);
// Handle choice
if (response !== 2 /* keep waiting */) {
const reopen = response === 0;
await this.destroyWindow(reopen, checkboxChecked);
}
}
// Process gone
else if (type === WindowError.PROCESS_GONE) {
let message: string;
if (!details) {
message = localize('appGone', "The window terminated unexpectedly");
} else {
message = localize('appGoneDetails', "The window terminated unexpectedly (reason: '{0}', code: '{1}')", details.reason, details.exitCode ?? '<unknown>');
}
// Show Dialog
const { response, checkboxChecked } = await this.dialogMainService.showMessageBox({
type: 'warning',
buttons: [
this._config?.workspace ? localize({ key: 'reopen', comment: ['&& denotes a mnemonic'] }, "&&Reopen") : localize({ key: 'newWindow', comment: ['&& denotes a mnemonic'] }, "&&New Window"),
localize({ key: 'close', comment: ['&& denotes a mnemonic'] }, "&&Close")
],
message,
detail: this._config?.workspace ?
localize('appGoneDetailWorkspace', "We are sorry for the inconvenience. You can reopen the window to continue where you left off.") :
localize('appGoneDetailEmptyWindow', "We are sorry for the inconvenience. You can open a new empty window to start again."),
checkboxLabel: this._config?.workspace ? localize('doNotRestoreEditors', "Don't restore editors") : undefined
}, this._win);
// Handle choice
const reopen = response === 0;
await this.destroyWindow(reopen, checkboxChecked);
}
break;
}
}
private async destroyWindow(reopen: boolean, skipRestoreEditors: boolean): Promise<void> {
const workspace = this._config?.workspace;
// check to discard editor state first
if (skipRestoreEditors && workspace) {
try {
const workspaceStorage = this.storageMainService.workspaceStorage(workspace);
await workspaceStorage.init();
workspaceStorage.delete('memento/workbench.parts.editor');
await workspaceStorage.close();
} catch (error) {
this.logService.error(error);
}
}
// 'close' event will not be fired on destroy(), so signal crash via explicit event
this._onDidDestroy.fire();
try {
// ask the windows service to open a new fresh window if specified
if (reopen && this._config) {
// We have to reconstruct a openable from the current workspace
let uriToOpen: IWorkspaceToOpen | IFolderToOpen | undefined = undefined;
let forceEmpty = undefined;
if (isSingleFolderWorkspaceIdentifier(workspace)) {
uriToOpen = { folderUri: workspace.uri };
} else if (isWorkspaceIdentifier(workspace)) {
uriToOpen = { workspaceUri: workspace.configPath };
} else {
forceEmpty = true;
}
// Delegate to windows service
const window = firstOrDefault(await this.windowsMainService.open({
context: OpenContext.API,
userEnv: this._config.userEnv,
cli: {
...this.environmentMainService.args,
_: [] // we pass in the workspace to open explicitly via `urisToOpen`
},
urisToOpen: uriToOpen ? [uriToOpen] : undefined,
forceEmpty,
forceNewWindow: true,
remoteAuthority: this.remoteAuthority
}));
window?.focus();
}
} finally {
// make sure to destroy the window as its renderer process is gone. do this
// after the code for reopening the window, to prevent the entire application
// from quitting when the last window closes as a result.
this._win?.destroy();
}
}
private onDidDeleteUntitledWorkspace(workspace: IWorkspaceIdentifier): void {
// Make sure to update our workspace config if we detect that it
// was deleted
if (this._config?.workspace?.id === workspace.id) {
this._config.workspace = undefined;
}
}
private onConfigurationUpdated(e?: IConfigurationChangeEvent): void {
// Menubar
if (!e || e.affectsConfiguration('window.menuBarVisibility')) {
const newMenuBarVisibility = this.getMenuBarVisibility();
if (newMenuBarVisibility !== this.currentMenuBarVisibility) {
this.currentMenuBarVisibility = newMenuBarVisibility;
this.setMenuBarVisibility(newMenuBarVisibility);
}
}
// Proxy
if (!e || e.affectsConfiguration('http.proxy') || e.affectsConfiguration('http.noProxy')) {
let newHttpProxy = (this.configurationService.getValue<string>('http.proxy') || '').trim()
|| (process.env['https_proxy'] || process.env['HTTPS_PROXY'] || process.env['http_proxy'] || process.env['HTTP_PROXY'] || '').trim() // Not standardized.
|| undefined;
if (newHttpProxy?.indexOf('@') !== -1) {
const uri = URI.parse(newHttpProxy!);
const i = uri.authority.indexOf('@');
if (i !== -1) {
newHttpProxy = uri.with({ authority: uri.authority.substring(i + 1) })
.toString();
}
}
if (newHttpProxy?.endsWith('/')) {
newHttpProxy = newHttpProxy.substr(0, newHttpProxy.length - 1);
}
const newNoProxy = (this.configurationService.getValue<string[]>('http.noProxy') || []).map((item) => item.trim()).join(',')
|| (process.env['no_proxy'] || process.env['NO_PROXY'] || '').trim() || undefined; // Not standardized.
if ((newHttpProxy || '').indexOf('@') === -1 && (newHttpProxy !== this.currentHttpProxy || newNoProxy !== this.currentNoProxy)) {
this.currentHttpProxy = newHttpProxy;
this.currentNoProxy = newNoProxy;
const proxyRules = newHttpProxy || '';
const proxyBypassRules = newNoProxy ? `${newNoProxy},<local>` : '<local>';
this.logService.trace(`Setting proxy to '${proxyRules}', bypassing '${proxyBypassRules}'`);
this._win.webContents.session.setProxy({ proxyRules, proxyBypassRules, pacScript: '' });
electron.app.setProxy({ proxyRules, proxyBypassRules, pacScript: '' });
}
}
}
addTabbedWindow(window: ICodeWindow): void {
if (isMacintosh && window.win) {
this._win.addTabbedWindow(window.win);
}
}
load(configuration: INativeWindowConfiguration, options: ILoadOptions = Object.create(null)): void {
this.logService.trace(`window#load: attempt to load window (id: ${this._id})`);