window.ts 17.2 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6 7
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

'use strict';

8
import * as nls from 'vs/nls';
9
import URI from 'vs/base/common/uri';
10
import * as errors from 'vs/base/common/errors';
J
Johannes Rieken 已提交
11
import { TPromise } from 'vs/base/common/winjs.base';
12 13
import * as objects from 'vs/base/common/objects';
import * as DOM from 'vs/base/browser/dom';
14 15
import { Separator } from 'vs/base/browser/ui/actionbar/actionbar';
import { IAction, Action } from 'vs/base/common/actions';
S
SteVen Batten 已提交
16
import { IFileService } from 'vs/platform/files/common/files';
B
Benjamin Pasero 已提交
17
import { toResource, IUntitledResourceInput } from 'vs/workbench/common/editor';
18
import { IEditorService, IResourceEditor } from 'vs/workbench/services/editor/common/editorService';
J
Johannes Rieken 已提交
19
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
20
import { IWorkspaceConfigurationService } from 'vs/workbench/services/configuration/common/configuration';
21
import { IWindowsService, IWindowService, IWindowSettings, IPath, IOpenFileRequest, IWindowsConfiguration, IAddFoldersRequest, IRunActionInWindowRequest } from 'vs/platform/windows/common/windows';
22
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
B
Benjamin Pasero 已提交
23
import { ITitleService } from 'vs/workbench/services/title/common/titleService';
24
import { IWorkbenchThemeService, VS_HC_THEME, VS_DARK_THEME } from 'vs/workbench/services/themes/common/workbenchThemeService';
25 26
import * as browser from 'vs/base/browser/browser';
import { ICommandService } from 'vs/platform/commands/common/commands';
B
Benjamin Pasero 已提交
27
import { IResourceInput } from 'vs/platform/editor/common/editor';
A
Alex Dima 已提交
28
import { KeyboardMapperFactory } from 'vs/workbench/services/keybinding/electron-browser/keybindingService';
29
import { Themable } from 'vs/workbench/common/theme';
30
import { ipcRenderer as ipc, webFrame } from 'electron';
31
import { IWorkspaceEditingService } from 'vs/workbench/services/workspace/common/workspaceEditing';
32 33
import { IMenuService, MenuId, IMenu, MenuItemAction, ICommandAction } from 'vs/platform/actions/common/actions';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
34
import { fillInActionBarActions } from 'vs/platform/actions/browser/menuItemActionItem';
35 36
import { RunOnceScheduler } from 'vs/base/common/async';
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
37
import { LifecyclePhase, ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle';
38
import { IWorkspaceFolderCreationData } from 'vs/platform/workspaces/common/workspaces';
39 40 41
import { IIntegrityService } from 'vs/platform/integrity/common/integrity';
import { AccessibilitySupport, isRootUser, isWindows, isMacintosh } from 'vs/base/common/platform';
import product from 'vs/platform/node/product';
42
import { INotificationService } from 'vs/platform/notification/common/notification';
B
Benjamin Pasero 已提交
43
import { EditorServiceImpl } from 'vs/workbench/browser/parts/editor/editor';
E
Erich Gamma 已提交
44

45 46 47 48 49 50 51 52 53 54 55
const TextInputActions: IAction[] = [
	new Action('undo', nls.localize('undo', "Undo"), null, true, () => document.execCommand('undo') && TPromise.as(true)),
	new Action('redo', nls.localize('redo', "Redo"), null, true, () => document.execCommand('redo') && TPromise.as(true)),
	new Separator(),
	new Action('editor.action.clipboardCutAction', nls.localize('cut', "Cut"), null, true, () => document.execCommand('cut') && TPromise.as(true)),
	new Action('editor.action.clipboardCopyAction', nls.localize('copy', "Copy"), null, true, () => document.execCommand('copy') && TPromise.as(true)),
	new Action('editor.action.clipboardPasteAction', nls.localize('paste', "Paste"), null, true, () => document.execCommand('paste') && TPromise.as(true)),
	new Separator(),
	new Action('editor.action.selectAll', nls.localize('selectAll', "Select All"), null, true, () => document.execCommand('selectAll') && TPromise.as(true))
];

56
export class ElectronWindow extends Themable {
57

58 59
	private touchBarMenu: IMenu;
	private touchBarUpdater: RunOnceScheduler;
60 61 62 63 64
	private touchBarDisposables: IDisposable[];
	private lastInstalledTouchedBar: ICommandAction[][];

	private previousConfiguredZoomLevel: number;

65
	private addFoldersScheduler: RunOnceScheduler;
66
	private pendingFoldersToAdd: URI[];
67

E
Erich Gamma 已提交
68
	constructor(
B
Benjamin Pasero 已提交
69
		@IEditorService private editorService: EditorServiceImpl,
70
		@IWindowsService private windowsService: IWindowsService,
B
Benjamin Pasero 已提交
71
		@IWindowService private windowService: IWindowService,
72 73
		@IWorkspaceConfigurationService private configurationService: IWorkspaceConfigurationService,
		@ITitleService private titleService: ITitleService,
74
		@IWorkbenchThemeService protected themeService: IWorkbenchThemeService,
75
		@INotificationService private notificationService: INotificationService,
76 77
		@ICommandService private commandService: ICommandService,
		@IContextMenuService private contextMenuService: IContextMenuService,
78
		@ITelemetryService private telemetryService: ITelemetryService,
79
		@IWorkspaceEditingService private workspaceEditingService: IWorkspaceEditingService,
80
		@IFileService private fileService: IFileService,
81
		@IMenuService private menuService: IMenuService,
82 83
		@ILifecycleService private lifecycleService: ILifecycleService,
		@IIntegrityService private integrityService: IIntegrityService
E
Erich Gamma 已提交
84
	) {
85 86
		super(themeService);

87 88
		this.touchBarDisposables = [];

89
		this.pendingFoldersToAdd = [];
B
Benjamin Pasero 已提交
90
		this.addFoldersScheduler = this._register(new RunOnceScheduler(() => this.doAddFolders(), 100));
91

E
Erich Gamma 已提交
92
		this.registerListeners();
93
		this.create();
E
Erich Gamma 已提交
94 95 96 97
	}

	private registerListeners(): void {

98
		// React to editor input changes
B
Benjamin Pasero 已提交
99
		this._register(this.editorService.onDidActiveEditorChange(() => this.updateTouchbarMenu()));
E
Erich Gamma 已提交
100

101
		// prevent opening a real URL inside the shell
102 103 104 105
		[DOM.EventType.DRAG_OVER, DOM.EventType.DROP].forEach(event => {
			window.document.body.addEventListener(event, (e: DragEvent) => {
				DOM.EventHelper.stop(e);
			});
E
Erich Gamma 已提交
106 107
		});

108
		// Support runAction event
109
		ipc.on('vscode:runAction', (event: any, request: IRunActionInWindowRequest) => {
110 111 112 113 114
			const args: any[] = [];

			// If we run an action from the touchbar, we fill in the currently active resource
			// as payload because the touch bar items are context aware depending on the editor
			if (request.from === 'touchbar') {
B
Benjamin Pasero 已提交
115
				const activeEditor = this.editorService.activeEditor;
116
				if (activeEditor) {
B
Benjamin Pasero 已提交
117
					const resource = toResource(activeEditor, { supportSideBySide: true });
118 119 120 121 122 123 124 125 126
					if (resource) {
						args.push(resource);
					}
				}
			} else {
				args.push({ from: request.from }); // TODO@telemetry this is a bit weird to send this to every action?
			}

			this.commandService.executeCommand(request.id, ...args).done(_ => {
K
kieferrm 已提交
127
				/* __GDPR__
K
kieferrm 已提交
128 129 130 131 132
					"commandExecuted" : {
						"id" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
						"from": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
					}
				*/
133
				this.telemetryService.publicLog('commandExecuted', { id: request.id, from: request.from });
J
Johannes Rieken 已提交
134
			}, err => {
135
				this.notificationService.error(err);
J
Johannes Rieken 已提交
136
			});
137 138
		});

139
		ipc.on('vscode:reportError', (event: any, error: string) => {
140 141 142 143 144 145 146 147
			if (error) {
				const errorParsed = JSON.parse(error);
				errorParsed.mainProcess = true;
				errors.onUnexpectedError(errorParsed);
			}
		});

		// Support openFiles event for existing and new files
148
		ipc.on('vscode:openFiles', (event: any, request: IOpenFileRequest) => this.onOpenFiles(request));
149

150
		// Support addFolders event if we have a workspace opened
151
		ipc.on('vscode:addFolders', (event: any, request: IAddFoldersRequest) => this.onAddFoldersRequest(request));
152

153
		// Message support
154
		ipc.on('vscode:showInfoMessage', (event: any, message: string) => {
155
			this.notificationService.info(message);
156 157 158
		});

		// Fullscreen Events
159
		ipc.on('vscode:enterFullScreen', () => {
160
			this.lifecycleService.when(LifecyclePhase.Running).then(() => {
161 162 163 164
				browser.setFullscreen(true);
			});
		});

165
		ipc.on('vscode:leaveFullScreen', () => {
166
			this.lifecycleService.when(LifecyclePhase.Running).then(() => {
167 168 169 170 171
				browser.setFullscreen(false);
			});
		});

		// High Contrast Events
172
		ipc.on('vscode:enterHighContrast', () => {
173
			const windowConfig = this.configurationService.getValue<IWindowSettings>('window');
174
			if (windowConfig && windowConfig.autoDetectHighContrast) {
175
				this.lifecycleService.when(LifecyclePhase.Running).then(() => {
M
Martin Aeschlimann 已提交
176
					this.themeService.setColorTheme(VS_HC_THEME, null);
177 178
				});
			}
179 180
		});

181
		ipc.on('vscode:leaveHighContrast', () => {
182
			const windowConfig = this.configurationService.getValue<IWindowSettings>('window');
183
			if (windowConfig && windowConfig.autoDetectHighContrast) {
184
				this.lifecycleService.when(LifecyclePhase.Running).then(() => {
M
Martin Aeschlimann 已提交
185
					this.themeService.setColorTheme(VS_DARK_THEME, null);
186 187
				});
			}
188 189
		});

A
Alex Dima 已提交
190
		// keyboard layout changed event
191
		ipc.on('vscode:keyboardLayoutChanged', () => {
192
			KeyboardMapperFactory.INSTANCE._onKeyboardLayoutChanged();
A
Alex Dima 已提交
193 194
		});

195
		// keyboard layout changed event
196
		ipc.on('vscode:accessibilitySupportChanged', (event: any, accessibilitySupportEnabled: boolean) => {
197
			browser.setAccessibilitySupport(accessibilitySupportEnabled ? AccessibilitySupport.Enabled : AccessibilitySupport.Disabled);
198 199
		});

S
Sandeep Somavarapu 已提交
200 201
		// Zoom level changes
		this.updateWindowZoomLevel();
B
Benjamin Pasero 已提交
202
		this._register(this.configurationService.onDidChangeConfiguration(e => {
S
Sandeep Somavarapu 已提交
203 204 205 206
			if (e.affectsConfiguration('window.zoomLevel')) {
				this.updateWindowZoomLevel();
			}
		}));
207

208 209 210
		// Context menu support in input/textarea
		window.document.addEventListener('contextmenu', e => this.onContextMenu(e));
	}
211

212 213 214 215
	private onContextMenu(e: PointerEvent): void {
		if (e.target instanceof HTMLElement) {
			const target = <HTMLElement>e.target;
			if (target.nodeName && (target.nodeName.toLowerCase() === 'input' || target.nodeName.toLowerCase() === 'textarea')) {
B
Benjamin Pasero 已提交
216
				DOM.EventHelper.stop(e, true);
217

218 219
				this.contextMenuService.showContextMenu({
					getAnchor: () => e,
B
Benjamin Pasero 已提交
220 221
					getActions: () => TPromise.as(TextInputActions),
					onHide: () => target.focus() // fixes https://github.com/Microsoft/vscode/issues/52948
222
				});
223
			}
224 225 226
		}
	}

S
Sandeep Somavarapu 已提交
227
	private updateWindowZoomLevel(): void {
228
		const windowConfig: IWindowsConfiguration = this.configurationService.getValue<IWindowsConfiguration>();
229 230 231 232

		let newZoomLevel = 0;
		if (windowConfig.window && typeof windowConfig.window.zoomLevel === 'number') {
			newZoomLevel = windowConfig.window.zoomLevel;
233

234 235 236
			// Leave early if the configured zoom level did not change (https://github.com/Microsoft/vscode/issues/1536)
			if (this.previousConfiguredZoomLevel === newZoomLevel) {
				return;
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

			this.previousConfiguredZoomLevel = newZoomLevel;
		}

		if (webFrame.getZoomLevel() !== newZoomLevel) {
			webFrame.setZoomLevel(newZoomLevel);
			browser.setZoomFactor(webFrame.getZoomFactor());
			// See https://github.com/Microsoft/vscode/issues/26151
			// Cannot be trusted because the webFrame might take some time
			// until it really applies the new zoom level
			browser.setZoomLevel(webFrame.getZoomLevel(), /*isTrusted*/false);
		}
	}

	private create(): void {

		// Handle window.open() calls
		const $this = this;
		(<any>window).open = function (url: string, target: string, features: string, replace: boolean): any {
			$this.windowsService.openExternal(url);

			return null;
		};

		// Emit event when vscode has loaded
263
		this.lifecycleService.when(LifecyclePhase.Running).then(() => {
264 265 266
			ipc.send('vscode:workbenchLoaded', this.windowService.getCurrentWindowId());
		});

267 268 269 270 271 272 273 274 275
		// Integrity warning
		this.integrityService.isPure().then(res => this.titleService.updateProperties({ isPure: res.isPure }));

		// Root warning
		this.lifecycleService.when(LifecyclePhase.Running).then(() => {
			let isAdminPromise: Promise<boolean>;
			if (isWindows) {
				isAdminPromise = import('native-is-elevated').then(isElevated => isElevated());
			} else {
A
Alex Dima 已提交
276
				isAdminPromise = Promise.resolve(isRootUser());
277 278 279 280 281 282 283
			}

			return isAdminPromise.then(isAdmin => {

				// Update title
				this.titleService.updateProperties({ isAdmin });

284 285
				// Show warning message (unix only)
				if (isAdmin && !isWindows) {
286
					this.notificationService.warn(nls.localize('runningAsRoot', "It is not recommended to run {0} as root user.", product.nameShort));
287 288 289
				}
			});
		});
290 291 292

		// Touchbar menu (if enabled)
		this.updateTouchbarMenu();
293 294 295
	}

	private updateTouchbarMenu(): void {
296 297 298 299 300
		if (
			!isMacintosh || // macOS only
			!this.configurationService.getValue<boolean>('keyboard.touchbar.enabled') // disabled via setting
		) {
			return;
301 302
		}

303 304
		// Dispose old
		this.touchBarDisposables = dispose(this.touchBarDisposables);
305
		this.touchBarMenu = void 0;
306

307 308 309 310
		// Create new (delayed)
		this.touchBarUpdater = new RunOnceScheduler(() => this.doUpdateTouchbarMenu(), 300);
		this.touchBarDisposables.push(this.touchBarUpdater);
		this.touchBarUpdater.schedule();
311 312
	}

313 314 315 316 317 318 319
	private doUpdateTouchbarMenu(): void {
		if (!this.touchBarMenu) {
			this.touchBarMenu = this.editorService.invokeWithinEditorContext(accessor => this.menuService.createMenu(MenuId.TouchBarContext, accessor.get(IContextKeyService)));
			this.touchBarDisposables.push(this.touchBarMenu);
			this.touchBarDisposables.push(this.touchBarMenu.onDidChange(() => this.touchBarUpdater.schedule()));
		}

320 321 322
		const actions: (MenuItemAction | Separator)[] = [];

		// Fill actions into groups respecting order
323
		fillInActionBarActions(this.touchBarMenu, void 0, actions);
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339

		// Convert into command action multi array
		const items: ICommandAction[][] = [];
		let group: ICommandAction[] = [];
		for (let i = 0; i < actions.length; i++) {
			const action = actions[i];

			// Command
			if (action instanceof MenuItemAction) {
				group.push(action.item);
			}

			// Separator
			else if (action instanceof Separator) {
				if (group.length) {
					items.push(group);
340
				}
341 342

				group = [];
343
			}
344 345 346 347 348 349 350 351 352 353 354
		}

		if (group.length) {
			items.push(group);
		}

		// Only update if the actions have changed
		if (!objects.equals(this.lastInstalledTouchedBar, items)) {
			this.lastInstalledTouchedBar = items;
			this.windowService.updateTouchBar(items);
		}
355 356
	}

357 358 359
	private onAddFoldersRequest(request: IAddFoldersRequest): void {

		// Buffer all pending requests
360
		this.pendingFoldersToAdd.push(...request.foldersToAdd.map(f => URI.revive(f)));
361 362 363 364 365 366 367 368 369 370

		// Delay the adding of folders a bit to buffer in case more requests are coming
		if (!this.addFoldersScheduler.isScheduled()) {
			this.addFoldersScheduler.schedule();
		}
	}

	private doAddFolders(): void {
		const foldersToAdd: IWorkspaceFolderCreationData[] = [];

371 372
		this.pendingFoldersToAdd.forEach(folder => {
			foldersToAdd.push(({ uri: folder }));
373 374 375
		});

		this.pendingFoldersToAdd = [];
376

377
		this.workspaceEditingService.addFolders(foldersToAdd).done(null, errors.onUnexpectedError);
378 379
	}

380
	private onOpenFiles(request: IOpenFileRequest): void {
B
Benjamin Pasero 已提交
381
		const inputs: IResourceEditor[] = [];
382
		const diffMode = (request.filesToDiff.length === 2);
383 384 385 386 387 388 389 390 391 392 393 394 395 396

		if (!diffMode && request.filesToOpen) {
			inputs.push(...this.toInputs(request.filesToOpen, false));
		}

		if (!diffMode && request.filesToCreate) {
			inputs.push(...this.toInputs(request.filesToCreate, true));
		}

		if (diffMode) {
			inputs.push(...this.toInputs(request.filesToDiff, false));
		}

		if (inputs.length) {
397
			this.openResources(inputs, diffMode).then(null, errors.onUnexpectedError);
398
		}
399 400 401 402 403

		if (request.filesToWait && inputs.length) {
			// In wait mode, listen to changes to the editors and wait until the files
			// are closed that the user wants to wait for. When this happens we delete
			// the wait marker file to signal to the outside that editing is done.
404
			const resourcesToWaitFor = request.filesToWait.paths.map(p => p.fileUri);
405
			const waitMarkerFile = URI.file(request.filesToWait.waitMarkerFilePath);
B
Benjamin Pasero 已提交
406 407
			const unbind = this.editorService.onDidCloseEditor(() => {
				if (resourcesToWaitFor.every(resource => !this.editorService.isOpen({ resource }))) {
408 409 410 411 412
					unbind.dispose();
					this.fileService.del(waitMarkerFile).done(null, errors.onUnexpectedError);
				}
			});
		}
413 414
	}

B
Benjamin Pasero 已提交
415 416
	private openResources(resources: (IResourceInput | IUntitledResourceInput)[], diffMode: boolean): Thenable<any> {
		return this.lifecycleService.when(LifecyclePhase.Running).then((): TPromise<any> => {
N
Nick Snyder 已提交
417

418
			// In diffMode we open 2 resources as diff
419
			if (diffMode && resources.length === 2) {
420
				return this.editorService.openEditor({ leftResource: resources[0].resource, rightResource: resources[1].resource, options: { pinned: true } });
421 422 423 424 425 426 427 428
			}

			// For one file, just put it into the current active editor
			if (resources.length === 1) {
				return this.editorService.openEditor(resources[0]);
			}

			// Otherwise open all
B
Benjamin Pasero 已提交
429
			return this.editorService.openEditors(resources);
430 431 432
		});
	}

B
Benjamin Pasero 已提交
433
	private toInputs(paths: IPath[], isNew: boolean): IResourceEditor[] {
434
		return paths.map(p => {
435
			const resource = p.fileUri;
436 437 438 439 440 441
			let input: IResourceInput | IUntitledResourceInput;
			if (isNew) {
				input = { filePath: resource.fsPath, options: { pinned: true } } as IUntitledResourceInput;
			} else {
				input = { resource, options: { pinned: true } } as IResourceInput;
			}
442 443 444 445 446 447 448 449 450 451 452 453

			if (!isNew && p.lineNumber) {
				input.options.selection = {
					startLineNumber: p.lineNumber,
					startColumn: p.columnNumber
				};
			}

			return input;
		});
	}

B
Benjamin Pasero 已提交
454
	dispose(): void {
455 456 457 458
		this.touchBarDisposables = dispose(this.touchBarDisposables);

		super.dispose();
	}
J
Johannes Rieken 已提交
459
}