window.ts 16.6 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 nls = require('vs/nls');
E
Erich Gamma 已提交
9
import platform = require('vs/base/common/platform');
10
import URI from 'vs/base/common/uri';
11 12
import errors = require('vs/base/common/errors');
import types = require('vs/base/common/types');
J
Johannes Rieken 已提交
13
import { TPromise } from 'vs/base/common/winjs.base';
14
import arrays = require('vs/base/common/arrays');
15
import DOM = require('vs/base/browser/dom');
16 17 18
import Severity from 'vs/base/common/severity';
import { Separator } from 'vs/base/browser/ui/actionbar/actionbar';
import { IAction, Action } from 'vs/base/common/actions';
J
Johannes Rieken 已提交
19
import { IPartService } from 'vs/workbench/services/part/common/partService';
20
import { AutoSaveConfiguration, IFileService } from 'vs/platform/files/common/files';
21
import { toResource } from 'vs/workbench/common/editor';
22
import { IWorkbenchEditorService, IResourceInputType } from 'vs/workbench/services/editor/common/editorService';
J
Johannes Rieken 已提交
23
import { IEditorGroupService } from 'vs/workbench/services/group/common/groupService';
24
import { IMessageService } from 'vs/platform/message/common/message';
J
Johannes Rieken 已提交
25
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
26
import { IWorkspaceConfigurationService } from 'vs/workbench/services/configuration/common/configuration';
27
import { IWindowsService, IWindowService, IWindowSettings, IPath, IOpenFileRequest, IWindowsConfiguration, IAddFoldersRequest } from 'vs/platform/windows/common/windows';
28 29 30 31
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IConfigurationEditingService, ConfigurationTarget } from 'vs/workbench/services/configuration/common/configurationEditing';
B
Benjamin Pasero 已提交
32
import { ITitleService } from 'vs/workbench/services/title/common/titleService';
33
import { IWorkbenchThemeService, VS_HC_THEME, VS_DARK_THEME } from 'vs/workbench/services/themes/common/workbenchThemeService';
34 35 36
import * as browser from 'vs/base/browser/browser';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';
N
Nick Snyder 已提交
37
import { Position, IResourceInput, IUntitledResourceInput, IEditor } from 'vs/platform/editor/common/editor';
38
import { IExtensionService } from 'vs/platform/extensions/common/extensions';
A
Alex Dima 已提交
39
import { KeyboardMapperFactory } from 'vs/workbench/services/keybinding/electron-browser/keybindingService';
40
import { Themable } from 'vs/workbench/common/theme';
41
import { ipcRenderer as ipc, webFrame } from 'electron';
42
import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
43
import { IWorkspaceEditingService } from 'vs/workbench/services/workspace/common/workspaceEditing';
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 static AUTO_SAVE_SETTING = 'files.autoSave';

E
Erich Gamma 已提交
60 61 62
	constructor(
		shellContainer: HTMLElement,
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
63
		@IEditorGroupService private editorGroupService: IEditorGroupService,
64
		@IPartService private partService: IPartService,
65
		@IWindowsService private windowsService: IWindowsService,
B
Benjamin Pasero 已提交
66
		@IWindowService private windowService: IWindowService,
67 68
		@IWorkspaceConfigurationService private configurationService: IWorkspaceConfigurationService,
		@ITitleService private titleService: ITitleService,
69
		@IWorkbenchThemeService protected themeService: IWorkbenchThemeService,
70 71 72 73 74 75 76
		@IMessageService private messageService: IMessageService,
		@IConfigurationEditingService private configurationEditingService: IConfigurationEditingService,
		@ICommandService private commandService: ICommandService,
		@IExtensionService private extensionService: IExtensionService,
		@IViewletService private viewletService: IViewletService,
		@IContextMenuService private contextMenuService: IContextMenuService,
		@IKeybindingService private keybindingService: IKeybindingService,
J
Johannes Rieken 已提交
77
		@IEnvironmentService private environmentService: IEnvironmentService,
78 79
		@ITelemetryService private telemetryService: ITelemetryService,
		@IWorkspaceContextService private contextService: IWorkspaceContextService,
80 81
		@IWorkspaceEditingService private workspaceEditingService: IWorkspaceEditingService,
		@IFileService private fileService: IFileService
E
Erich Gamma 已提交
82
	) {
83 84
		super(themeService);

E
Erich Gamma 已提交
85
		this.registerListeners();
86
		this.setup();
E
Erich Gamma 已提交
87 88 89 90
	}

	private registerListeners(): void {

91 92 93
		// React to editor input changes
		this.editorGroupService.onEditorsChanged(() => {
			const file = toResource(this.editorService.getActiveEditorInput(), { supportSideBySide: true, filter: 'file' });
E
Erich Gamma 已提交
94

95 96
			this.titleService.setRepresentedFilename(file ? file.fsPath : '');
		});
E
Erich Gamma 已提交
97

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

		// Handle window.open() calls
J
Joao Moreno 已提交
106
		const $this = this;
107
		(<any>window).open = function (url: string, target: string, features: string, replace: boolean): any {
J
Joao Moreno 已提交
108
			$this.windowsService.openExternal(url);
B
Benjamin Pasero 已提交
109

B
Benjamin Pasero 已提交
110
			return null;
E
Erich Gamma 已提交
111 112 113
		};
	}

114 115 116 117
	private setup(): void {

		// Support runAction event
		ipc.on('vscode:runAction', (event, actionId: string) => {
J
Johannes Rieken 已提交
118 119 120 121 122
			this.commandService.executeCommand(actionId, { from: 'menu' }).done(_ => {
				this.telemetryService.publicLog('commandExecuted', { id: actionId, from: 'menu' });
			}, err => {
				this.messageService.show(Severity.Error, err);
			});
123 124 125 126 127 128 129 130 131 132 133 134
		});

		// Support resolve keybindings event
		ipc.on('vscode:resolveKeybindings', (event, rawActionIds: string) => {
			let actionIds: string[] = [];
			try {
				actionIds = JSON.parse(rawActionIds);
			} catch (error) {
				// should not happen
			}

			// Resolve keys using the keybinding service and send back to browser process
135
			this.resolveKeybindings(actionIds).done(keybindings => {
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
				if (keybindings.length) {
					ipc.send('vscode:keybindingsResolved', JSON.stringify(keybindings));
				}
			}, () => errors.onUnexpectedError);
		});

		// Send over all extension viewlets when extensions are ready
		this.extensionService.onReady().then(() => {
			ipc.send('vscode:extensionViewlets', JSON.stringify(this.viewletService.getViewlets().filter(v => !!v.extensionId).map(v => { return { id: v.id, label: v.name }; })));
		});

		ipc.on('vscode:reportError', (event, error) => {
			if (error) {
				const errorParsed = JSON.parse(error);
				errorParsed.mainProcess = true;
				errors.onUnexpectedError(errorParsed);
			}
		});

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

158 159 160
		// Support addFolders event if we have a workspace opened
		ipc.on('vscode:addFolders', (event, request: IAddFoldersRequest) => this.onAddFolders(request));

161 162
		// Emit event when vscode has loaded
		this.partService.joinCreation().then(() => {
163
			ipc.send('vscode:workbenchLoaded', this.windowService.getCurrentWindowId());
164 165 166 167 168 169 170 171
		});

		// Message support
		ipc.on('vscode:showInfoMessage', (event, message: string) => {
			this.messageService.show(Severity.Info, message);
		});

		// Support toggling auto save
172
		ipc.on('vscode.toggleAutoSave', event => {
173 174 175 176
			this.toggleAutoSave();
		});

		// Fullscreen Events
177
		ipc.on('vscode:enterFullScreen', event => {
178 179 180 181 182
			this.partService.joinCreation().then(() => {
				browser.setFullscreen(true);
			});
		});

183
		ipc.on('vscode:leaveFullScreen', event => {
184 185 186 187 188 189
			this.partService.joinCreation().then(() => {
				browser.setFullscreen(false);
			});
		});

		// High Contrast Events
190
		ipc.on('vscode:enterHighContrast', event => {
191
			const windowConfig = this.configurationService.getConfiguration<IWindowSettings>('window');
192
			if (windowConfig && windowConfig.autoDetectHighContrast) {
193
				this.partService.joinCreation().then(() => {
M
Martin Aeschlimann 已提交
194
					this.themeService.setColorTheme(VS_HC_THEME, null);
195 196
				});
			}
197 198
		});

199
		ipc.on('vscode:leaveHighContrast', event => {
200
			const windowConfig = this.configurationService.getConfiguration<IWindowSettings>('window');
201
			if (windowConfig && windowConfig.autoDetectHighContrast) {
202
				this.partService.joinCreation().then(() => {
M
Martin Aeschlimann 已提交
203
					this.themeService.setColorTheme(VS_DARK_THEME, null);
204 205
				});
			}
206 207
		});

A
Alex Dima 已提交
208
		// keyboard layout changed event
209 210
		ipc.on('vscode:keyboardLayoutChanged', (event, isISOKeyboard: boolean) => {
			KeyboardMapperFactory.INSTANCE._onKeyboardLayoutChanged(isISOKeyboard);
A
Alex Dima 已提交
211 212
		});

213 214
		// keyboard layout changed event
		ipc.on('vscode:accessibilitySupportChanged', (event, accessibilitySupportEnabled: boolean) => {
215
			browser.setAccessibilitySupport(accessibilitySupportEnabled ? platform.AccessibilitySupport.Enabled : platform.AccessibilitySupport.Disabled);
216 217
		});

218 219 220
		// Configuration changes
		let previousConfiguredZoomLevel: number;
		this.configurationService.onDidUpdateConfiguration(e => {
221
			const windowConfig: IWindowsConfiguration = this.configurationService.getConfiguration<IWindowsConfiguration>();
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237

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

				// Leave early if the configured zoom level did not change (https://github.com/Microsoft/vscode/issues/1536)
				if (previousConfiguredZoomLevel === newZoomLevel) {
					return;
				}

				previousConfiguredZoomLevel = newZoomLevel;
			}

			if (webFrame.getZoomLevel() !== newZoomLevel) {
				webFrame.setZoomLevel(newZoomLevel);
				browser.setZoomFactor(webFrame.getZoomFactor());
238 239 240 241
				// 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);
242 243 244 245
			}
		});

		// Context menu support in input/textarea
246
		window.document.addEventListener('contextmenu', e => {
247 248 249 250 251 252 253
			if (e.target instanceof HTMLElement) {
				const target = <HTMLElement>e.target;
				if (target.nodeName && (target.nodeName.toLowerCase() === 'input' || target.nodeName.toLowerCase() === 'textarea')) {
					e.preventDefault();
					e.stopPropagation();

					this.contextMenuService.showContextMenu({
254
						getAnchor: () => e,
255
						getActions: () => TPromise.as(TextInputActions)
256 257 258 259 260 261
					});
				}
			}
		});
	}

262
	private resolveKeybindings(actionIds: string[]): TPromise<{ id: string; label: string, isNative: boolean; }[]> {
263
		return TPromise.join([this.partService.joinCreation(), this.extensionService.onReady()]).then(() => {
264
			return arrays.coalesce(actionIds.map(id => {
265
				const binding = this.keybindingService.lookupKeybinding(id);
266 267 268
				if (!binding) {
					return null;
				}
269

270 271 272 273 274
				// first try to resolve a native accelerator
				const electronAccelerator = binding.getElectronAccelerator();
				if (electronAccelerator) {
					return { id, label: electronAccelerator, isNative: true };
				}
275

276 277 278 279
				// we need this fallback to support keybindings that cannot show in electron menus (e.g. chords)
				const acceleratorLabel = binding.getLabel();
				if (acceleratorLabel) {
					return { id, label: acceleratorLabel, isNative: false };
280 281 282 283 284 285 286
				}

				return null;
			}));
		});
	}

287 288 289
	private onAddFolders(request: IAddFoldersRequest): void {
		const foldersToAdd = request.foldersToAdd.map(folderToAdd => URI.file(folderToAdd.filePath));

290
		// Workspace: just add to workspace config
291
		if (this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE) {
S
Sandeep Somavarapu 已提交
292
			this.workspaceEditingService.addFolders(foldersToAdd).done(null, errors.onUnexpectedError);
293 294
		}

295
		// Single folder or no workspace: create workspace and open
296
		else {
S
Sandeep Somavarapu 已提交
297
			const workspaceFolders: URI[] = [...this.contextService.getWorkspace().folders];
298 299 300 301 302 303 304 305 306

			// Fill in remaining ones from request
			workspaceFolders.push(...request.foldersToAdd.map(folderToAdd => URI.file(folderToAdd.filePath)));

			// Create workspace and open (ensure no duplicates)
			this.windowService.createAndOpenWorkspace(arrays.distinct(workspaceFolders.map(folder => folder.fsPath), folder => platform.isLinux ? folder : folder.toLowerCase()));
		}
	}

307
	private onOpenFiles(request: IOpenFileRequest): void {
308 309
		const inputs: IResourceInputType[] = [];
		const diffMode = (request.filesToDiff.length === 2);
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325

		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) {
			this.openResources(inputs, diffMode).done(null, errors.onUnexpectedError);
		}
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340

		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.
			const resourcesToWaitFor = request.filesToWait.paths.map(p => URI.file(p.filePath));
			const waitMarkerFile = URI.file(request.filesToWait.waitMarkerFilePath);
			const stacks = this.editorGroupService.getStacksModel();
			const unbind = stacks.onEditorClosed(() => {
				if (resourcesToWaitFor.every(r => !stacks.isOpen(r))) {
					unbind.dispose();
					this.fileService.del(waitMarkerFile).done(null, errors.onUnexpectedError);
				}
			});
		}
341 342
	}

N
Nick Snyder 已提交
343 344 345
	private openResources(resources: (IResourceInput | IUntitledResourceInput)[], diffMode: boolean): TPromise<IEditor | IEditor[]> {
		return this.partService.joinCreation().then((): TPromise<IEditor | IEditor[]> => {

346
			// In diffMode we open 2 resources as diff
347
			if (diffMode && resources.length === 2) {
348
				return this.editorService.openEditor({ leftResource: resources[0].resource, rightResource: resources[1].resource, options: { pinned: true } });
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
			}

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

			// Otherwise open all
			const activeEditor = this.editorService.getActiveEditor();
			return this.editorService.openEditors(resources.map((r, index) => {
				return {
					input: r,
					position: activeEditor ? activeEditor.position : Position.ONE
				};
			}));
		});
	}

367
	private toInputs(paths: IPath[], isNew: boolean): IResourceInputType[] {
368
		return paths.map(p => {
369 370 371 372 373 374 375
			const resource = URI.file(p.filePath);
			let input: IResourceInput | IUntitledResourceInput;
			if (isNew) {
				input = { filePath: resource.fsPath, options: { pinned: true } } as IUntitledResourceInput;
			} else {
				input = { resource, options: { pinned: true } } as IResourceInput;
			}
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

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

			return input;
		});
	}

	private toggleAutoSave(): void {
		const setting = this.configurationService.lookup(ElectronWindow.AUTO_SAVE_SETTING);
		let userAutoSaveConfig = setting.user;
		if (types.isUndefinedOrNull(userAutoSaveConfig)) {
			userAutoSaveConfig = setting.default; // use default if setting not defined
		}

		let newAutoSaveValue: string;
		if ([AutoSaveConfiguration.AFTER_DELAY, AutoSaveConfiguration.ON_FOCUS_CHANGE, AutoSaveConfiguration.ON_WINDOW_CHANGE].some(s => s === userAutoSaveConfig)) {
			newAutoSaveValue = AutoSaveConfiguration.OFF;
		} else {
			newAutoSaveValue = AutoSaveConfiguration.AFTER_DELAY;
		}

S
Sandeep Somavarapu 已提交
402
		this.configurationEditingService.writeConfiguration(ConfigurationTarget.USER, { key: ElectronWindow.AUTO_SAVE_SETTING, value: newAutoSaveValue });
403
	}
J
Johannes Rieken 已提交
404
}