actions.ts 15.3 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 URI from 'vs/base/common/uri';
9
import {TPromise} from 'vs/base/common/winjs.base';
E
Erich Gamma 已提交
10 11 12 13
import timer = require('vs/base/common/timer');
import {Action} from 'vs/base/common/actions';
import {IWindowService} from 'vs/workbench/services/window/electron-browser/windowService';
import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService';
14 15
import {EditorInput} from 'vs/workbench/common/editor';
import {DiffEditorInput} from 'vs/workbench/common/editor/diffEditorInput';
E
Erich Gamma 已提交
16
import nls = require('vs/nls');
B
Benjamin Pasero 已提交
17
import errors = require('vs/base/common/errors');
E
Erich Gamma 已提交
18
import {IMessageService, Severity} from 'vs/platform/message/common/message';
19
import {IWindowConfiguration} from 'vs/workbench/electron-browser/common';
20
import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace';
B
Benjamin Pasero 已提交
21
import {IEnvironmentService} from 'vs/platform/environment/common/environment';
22
import {IConfigurationService} from 'vs/platform/configuration/common/configuration';
23
import {CommandsRegistry} from 'vs/platform/commands/common/commands';
B
Benjamin Pasero 已提交
24 25
import paths = require('vs/base/common/paths');
import {isMacintosh} from 'vs/base/common/platform';
B
Benjamin Pasero 已提交
26
import {IQuickOpenService, IPickOpenEntry, IFilePickOpenEntry, ISeparator} from 'vs/workbench/services/quickopen/common/quickOpenService';
B
Benjamin Pasero 已提交
27
import {KeyMod} from 'vs/base/common/keyCodes';
28
import {ServicesAccessor} from 'vs/platform/instantiation/common/instantiation';
29
import * as browser from 'vs/base/browser/browser';
E
Erich Gamma 已提交
30

B
Benjamin Pasero 已提交
31
import {ipcRenderer as ipc, webFrame, remote} from 'electron';
E
Erich Gamma 已提交
32

33 34
// --- actions

E
Erich Gamma 已提交
35 36 37 38 39 40 41 42
export class CloseEditorAction extends Action {

	public static ID = 'workbench.action.closeActiveEditor';
	public static LABEL = nls.localize('closeActiveEditor', "Close Editor");

	constructor(
		id: string,
		label: string,
43
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService
E
Erich Gamma 已提交
44 45 46 47
	) {
		super(id, label);
	}

48
	public run(): TPromise<any> {
B
Benjamin Pasero 已提交
49
		const activeEditor = this.editorService.getActiveEditor();
E
Erich Gamma 已提交
50
		if (activeEditor) {
51
			return this.editorService.closeEditor(activeEditor.position, activeEditor.input);
E
Erich Gamma 已提交
52 53
		}

A
Alex Dima 已提交
54
		return TPromise.as(false);
E
Erich Gamma 已提交
55 56 57 58 59 60 61 62 63 64 65 66
	}
}

export class CloseWindowAction extends Action {

	public static ID = 'workbench.action.closeWindow';
	public static LABEL = nls.localize('closeWindow', "Close Window");

	constructor(id: string, label: string, @IWindowService private windowService: IWindowService) {
		super(id, label);
	}

67
	public run(): TPromise<boolean> {
E
Erich Gamma 已提交
68 69
		this.windowService.getWindow().close();

A
Alex Dima 已提交
70
		return TPromise.as(true);
E
Erich Gamma 已提交
71 72 73
	}
}

74
export class SwitchWindow extends Action {
75

76 77
	public static ID = 'workbench.action.switchWindow';
	public static LABEL = nls.localize('switchWindow', "Switch Window");
78 79 80 81 82 83 84 85 86 87 88

	constructor(
		id: string,
		label: string,
		@IWindowService private windowService: IWindowService,
		@IQuickOpenService private quickOpenService: IQuickOpenService
	) {
		super(id, label);
	}

	public run(): TPromise<boolean> {
89 90
		ipc.send('vscode:switchWindow', this.windowService.getWindowId());
		ipc.once('vscode:switchWindow', (event, workspaces) => {
91 92
			const picks: IPickOpenEntry[] = workspaces.map(w => {
				return {
93
					label: w.title,
94 95 96 97 98
					run: () => {
						ipc.send('vscode:showWindow', w.id);
					}
				};
			});
99
			this.quickOpenService.pick(picks, {placeHolder: nls.localize('switchWindowPlaceHolder', "Select a window")});
100 101 102 103 104 105
		});

		return TPromise.as(true);
	}
}

E
Erich Gamma 已提交
106 107 108 109 110 111 112 113 114
export class CloseFolderAction extends Action {

	public static ID = 'workbench.action.closeFolder';
	public static LABEL = nls.localize('closeFolder', "Close Folder");

	constructor(
		id: string,
		label: string,
		@IWorkspaceContextService private contextService: IWorkspaceContextService,
B
Benjamin Pasero 已提交
115 116
		@IMessageService private messageService: IMessageService,
		@IWindowService private windowService: IWindowService
E
Erich Gamma 已提交
117 118 119 120
	) {
		super(id, label);
	}

121
	public run(): TPromise<boolean> {
E
Erich Gamma 已提交
122
		if (this.contextService.getWorkspace()) {
B
Benjamin Pasero 已提交
123
			ipc.send('vscode:closeFolder', this.windowService.getWindowId()); // handled from browser process
E
Erich Gamma 已提交
124 125 126 127
		} else {
			this.messageService.show(Severity.Info, nls.localize('noFolderOpened', "There is currently no folder opened in this instance to close."));
		}

A
Alex Dima 已提交
128
		return TPromise.as(true);
E
Erich Gamma 已提交
129 130 131 132 133 134 135 136
	}
}

export class NewWindowAction extends Action {

	public static ID = 'workbench.action.newWindow';
	public static LABEL = nls.localize('newWindow', "New Window");

B
Benjamin Pasero 已提交
137 138 139 140 141
	constructor(
		id: string,
		label: string,
		@IWindowService private windowService: IWindowService
	) {
E
Erich Gamma 已提交
142 143 144
		super(id, label);
	}

145
	public run(): TPromise<boolean> {
E
Erich Gamma 已提交
146 147
		this.windowService.getWindow().openNew();

A
Alex Dima 已提交
148
		return TPromise.as(true);
E
Erich Gamma 已提交
149 150 151 152 153 154 155 156 157 158 159 160
	}
}

export class ToggleFullScreenAction extends Action {

	public static ID = 'workbench.action.toggleFullScreen';
	public static LABEL = nls.localize('toggleFullScreen', "Toggle Full Screen");

	constructor(id: string, label: string, @IWindowService private windowService: IWindowService) {
		super(id, label);
	}

161
	public run(): TPromise<boolean> {
E
Erich Gamma 已提交
162 163
		ipc.send('vscode:toggleFullScreen', this.windowService.getWindowId());

A
Alex Dima 已提交
164
		return TPromise.as(true);
E
Erich Gamma 已提交
165 166 167
	}
}

168 169 170 171 172 173 174 175 176
export class ToggleMenuBarAction extends Action {

	public static ID = 'workbench.action.toggleMenuBar';
	public static LABEL = nls.localize('toggleMenuBar', "Toggle Menu Bar");

	constructor(id: string, label: string, @IWindowService private windowService: IWindowService) {
		super(id, label);
	}

177
	public run(): TPromise<boolean> {
178 179
		ipc.send('vscode:toggleMenuBar', this.windowService.getWindowId());

A
Alex Dima 已提交
180
		return TPromise.as(true);
181 182 183
	}
}

E
Erich Gamma 已提交
184 185 186 187 188
export class ToggleDevToolsAction extends Action {

	public static ID = 'workbench.action.toggleDevTools';
	public static LABEL = nls.localize('toggleDevTools', "Toggle Developer Tools");

189
	constructor(id: string, label: string, @IWindowService private windowService: IWindowService) {
E
Erich Gamma 已提交
190 191 192
		super(id, label);
	}

193
	public run(): TPromise<boolean> {
194
		ipc.send('vscode:toggleDevTools', this.windowService.getWindowId());
E
Erich Gamma 已提交
195

A
Alex Dima 已提交
196
		return TPromise.as(true);
E
Erich Gamma 已提交
197 198 199 200 201 202
	}
}

export class ZoomInAction extends Action {

	public static ID = 'workbench.action.zoomIn';
B
Benjamin Pasero 已提交
203
	public static LABEL = nls.localize('zoomIn', "Zoom In");
E
Erich Gamma 已提交
204

205
	constructor(id: string, label: string) {
E
Erich Gamma 已提交
206 207 208
		super(id, label);
	}

209
	public run(): TPromise<boolean> {
E
Erich Gamma 已提交
210
		webFrame.setZoomLevel(webFrame.getZoomLevel() + 1);
B
Benjamin Pasero 已提交
211
		browser.setZoomLevel(webFrame.getZoomLevel()); // Ensure others can listen to zoom level changes
E
Erich Gamma 已提交
212

A
Alex Dima 已提交
213
		return TPromise.as(true);
E
Erich Gamma 已提交
214 215 216
	}
}

B
Benjamin Pasero 已提交
217
export class ZoomOutAction extends Action {
E
Erich Gamma 已提交
218 219

	public static ID = 'workbench.action.zoomOut';
B
Benjamin Pasero 已提交
220
	public static LABEL = nls.localize('zoomOut', "Zoom Out");
E
Erich Gamma 已提交
221

222 223
	constructor(
		id: string,
B
Benjamin Pasero 已提交
224
		label: string
225
	) {
B
Benjamin Pasero 已提交
226
		super(id, label);
E
Erich Gamma 已提交
227 228
	}

229
	public run(): TPromise<boolean> {
B
Benjamin Pasero 已提交
230 231
		webFrame.setZoomLevel(webFrame.getZoomLevel() - 1);
		browser.setZoomLevel(webFrame.getZoomLevel()); // Ensure others can listen to zoom level changes
232

233
		return TPromise.as(true);
E
Erich Gamma 已提交
234 235 236
	}
}

B
Benjamin Pasero 已提交
237
export class ZoomResetAction extends Action {
E
Erich Gamma 已提交
238 239 240 241

	public static ID = 'workbench.action.zoomReset';
	public static LABEL = nls.localize('zoomReset', "Reset Zoom");

242 243 244
	constructor(
		id: string,
		label: string,
B
Benjamin Pasero 已提交
245
		@IConfigurationService private configurationService: IConfigurationService
246
	) {
B
Benjamin Pasero 已提交
247
		super(id, label);
E
Erich Gamma 已提交
248 249
	}

250
	public run(): TPromise<boolean> {
251 252
		const level = this.getConfiguredZoomLevel();
		webFrame.setZoomLevel(level);
B
Benjamin Pasero 已提交
253
		browser.setZoomLevel(webFrame.getZoomLevel()); // Ensure others can listen to zoom level changes
254

255
		return TPromise.as(true);
E
Erich Gamma 已提交
256
	}
B
Benjamin Pasero 已提交
257 258 259 260 261 262 263 264 265

	private getConfiguredZoomLevel(): number {
		const windowConfig = this.configurationService.getConfiguration<IWindowConfiguration>();
		if (windowConfig.window && typeof windowConfig.window.zoomLevel === 'number') {
			return windowConfig.window.zoomLevel;
		}

		return 0; // default
	}
E
Erich Gamma 已提交
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
}

/* Copied from loader.ts */
enum LoaderEventType {
	LoaderAvailable = 1,

	BeginLoadingScript = 10,
	EndLoadingScriptOK = 11,
	EndLoadingScriptError = 12,

	BeginInvokeFactory = 21,
	EndInvokeFactory = 22,

	NodeBeginEvaluatingScript = 31,
	NodeEndEvaluatingScript = 32,

	NodeBeginNativeRequire = 33,
	NodeEndNativeRequire = 34
}
interface ILoaderEvent {
	type: LoaderEventType;
	timestamp: number;
	detail: string;
}
export class ShowStartupPerformance extends Action {

	public static ID = 'workbench.action.appPerf';
	public static LABEL = nls.localize('appPerf', "Startup Performance");

295 296 297 298
	constructor(
		id: string,
		label: string,
		@IWindowService private windowService: IWindowService,
B
Benjamin Pasero 已提交
299
		@IEnvironmentService private environmentService: IEnvironmentService
300
	) {
E
Erich Gamma 已提交
301
		super(id, label);
302

B
Benjamin Pasero 已提交
303
		this.enabled = environmentService.performance;
E
Erich Gamma 已提交
304 305 306
	}

	private _analyzeLoaderTimes(): any[] {
B
Benjamin Pasero 已提交
307 308
		const stats = <ILoaderEvent[]>(<any>require).getStats();
		const result = [];
E
Erich Gamma 已提交
309 310 311 312 313 314

		let total = 0;

		for (let i = 0, len = stats.length; i < len; i++) {
			if (stats[i].type === LoaderEventType.NodeEndNativeRequire) {
				if (stats[i - 1].type === LoaderEventType.NodeBeginNativeRequire && stats[i - 1].detail === stats[i].detail) {
B
Benjamin Pasero 已提交
315
					const entry: any = {};
E
Erich Gamma 已提交
316 317 318 319 320 321 322 323 324 325 326
					entry['Event'] = 'nodeRequire ' + stats[i].detail;
					entry['Took (ms)'] = (stats[i].timestamp - stats[i - 1].timestamp);
					total += (stats[i].timestamp - stats[i - 1].timestamp);
					entry['Start (ms)'] = '**' + stats[i - 1].timestamp;
					entry['End (ms)'] = '**' + stats[i - 1].timestamp;
					result.push(entry);
				}
			}
		}

		if (total > 0) {
B
Benjamin Pasero 已提交
327
			const entry: any = {};
E
Erich Gamma 已提交
328 329 330 331 332 333 334 335 336 337
			entry['Event'] = '===nodeRequire TOTAL';
			entry['Took (ms)'] = total;
			entry['Start (ms)'] = '**';
			entry['End (ms)'] = '**';
			result.push(entry);
		}

		return result;
	}

338
	public run(): TPromise<boolean> {
B
Benjamin Pasero 已提交
339
		const table: any[] = [];
E
Erich Gamma 已提交
340 341
		table.push(...this._analyzeLoaderTimes());

J
Joao Moreno 已提交
342
		const start = Math.round(remote.getGlobal('vscodeStart'));
B
Benjamin Pasero 已提交
343
		const windowShowTime = Math.round(remote.getGlobal('windowShow'));
E
Erich Gamma 已提交
344 345

		let lastEvent: timer.ITimerEvent;
B
Benjamin Pasero 已提交
346
		const events = timer.getTimeKeeper().getCollectedEvents();
E
Erich Gamma 已提交
347 348 349
		events.forEach((e) => {
			if (e.topic === 'Startup') {
				lastEvent = e;
B
Benjamin Pasero 已提交
350
				const entry: any = {};
E
Erich Gamma 已提交
351 352 353 354 355 356 357 358 359 360 361 362

				entry['Event'] = e.name;
				entry['Took (ms)'] = e.stopTime.getTime() - e.startTime.getTime();
				entry['Start (ms)'] = Math.max(e.startTime.getTime() - start, 0);
				entry['End (ms)'] = e.stopTime.getTime() - start;

				table.push(entry);
			}
		});

		table.push({ Event: '---------------------------' });

B
Benjamin Pasero 已提交
363
		const windowShowEvent: any = {};
E
Erich Gamma 已提交
364 365 366 367
		windowShowEvent['Event'] = 'Show Window at';
		windowShowEvent['Start (ms)'] = windowShowTime - start;
		table.push(windowShowEvent);

B
Benjamin Pasero 已提交
368
		const sum: any = {};
E
Erich Gamma 已提交
369 370 371 372 373 374 375 376 377 378 379 380 381 382
		sum['Event'] = 'Total';
		sum['Took (ms)'] = lastEvent.stopTime.getTime() - start;
		table.push(sum);


		// Show dev tools
		this.windowService.getWindow().openDevTools();

		// Print to console
		setTimeout(() => {
			console.warn('Run the action again if you do not see the numbers!');
			(<any>console).table(table);
		}, 1000);

A
Alex Dima 已提交
383
		return TPromise.as(true);
E
Erich Gamma 已提交
384 385 386 387 388 389 390 391 392 393 394 395
	}
}

export class ReloadWindowAction extends Action {

	public static ID = 'workbench.action.reloadWindow';
	public static LABEL = nls.localize('reloadWindow', "Reload Window");

	constructor(id: string, label: string, @IWindowService private windowService: IWindowService) {
		super(id, label);
	}

396
	public run(): TPromise<boolean> {
397
		this.windowService.getWindow().reload();
E
Erich Gamma 已提交
398

399
		return TPromise.as(true);
E
Erich Gamma 已提交
400 401 402 403 404 405 406 407 408 409 410
	}
}

export class OpenRecentAction extends Action {

	public static ID = 'workbench.action.openRecent';
	public static LABEL = nls.localize('openRecent', "Open Recent");

	constructor(
		id: string,
		label: string,
B
Benjamin Pasero 已提交
411 412 413
		@IWindowService private windowService: IWindowService,
		@IQuickOpenService private quickOpenService: IQuickOpenService,
		@IWorkspaceContextService private contextService: IWorkspaceContextService
E
Erich Gamma 已提交
414 415 416 417
	) {
		super(id, label);
	}

418
	public run(): TPromise<boolean> {
419
		ipc.send('vscode:openRecent', this.windowService.getWindowId());
E
Erich Gamma 已提交
420

B
Benjamin Pasero 已提交
421 422 423 424 425 426 427 428 429 430
		return new TPromise<boolean>((c, e, p) => {
			ipc.once('vscode:openRecent', (event, files: string[], folders: string[]) => {
				this.openRecent(files, folders);

				c(true);
			});
		});
	}

	private openRecent(recentFiles: string[], recentFolders: string[]): void {
B
Benjamin Pasero 已提交
431
		function toPick(path: string, separator: ISeparator, isFolder: boolean): IFilePickOpenEntry {
B
Benjamin Pasero 已提交
432
			return {
B
Benjamin Pasero 已提交
433 434
				resource: URI.file(path),
				isFolder,
B
Benjamin Pasero 已提交
435 436 437 438 439 440 441 442 443 444 445 446 447
				label: paths.basename(path),
				description: paths.dirname(path),
				separator,
				run: (context) => runPick(path, context)
			};
		}

		function runPick(path: string, context): void {
			const newWindow = context.keymods.indexOf(KeyMod.CtrlCmd) >= 0;

			ipc.send('vscode:windowOpen', [path], newWindow);
		}

B
Benjamin Pasero 已提交
448 449
		const folderPicks: IFilePickOpenEntry[] = recentFolders.map((p, index) => toPick(p, index === 0 ? { label: nls.localize('folders', "folders") } : void 0, true));
		const filePicks: IFilePickOpenEntry[] = recentFiles.map((p, index) => toPick(p, index === 0 ? { label: nls.localize('files', "files"), border: true } : void 0, false));
B
Benjamin Pasero 已提交
450 451 452 453 454 455 456 457

		const hasWorkspace = !!this.contextService.getWorkspace();

		this.quickOpenService.pick(folderPicks.concat(...filePicks), {
			autoFocus: { autoFocusFirstEntry: !hasWorkspace, autoFocusSecondEntry: hasWorkspace },
			placeHolder: isMacintosh ? nls.localize('openRecentPlaceHolderMac', "Select a path (hold Cmd-key to open in new window)") : nls.localize('openRecentPlaceHolder', "Select a path to open (hold Ctrl-key to open in new window)"),
			matchOnDescription: true
		}).done(null, errors.onUnexpectedError);
E
Erich Gamma 已提交
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
	}
}

export class CloseMessagesAction extends Action {

	public static ID = 'workbench.action.closeMessages';
	public static LABEL = nls.localize('closeMessages', "Close Notification Messages");

	constructor(
		id: string,
		label: string,
		@IMessageService private messageService: IMessageService,
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService
	) {
		super(id, label);
	}

475
	public run(): TPromise<boolean> {
E
Erich Gamma 已提交
476 477 478 479 480 481 482 483 484 485

		// Close any Message if visible
		this.messageService.hideAll();

		// Restore focus if we got an editor
		const editor = this.editorService.getActiveEditor();
		if (editor) {
			editor.focus();
		}

486
		return TPromise.as(true);
E
Erich Gamma 已提交
487
	}
488 489 490 491
}

// --- commands

492 493 494 495 496 497
CommandsRegistry.registerCommand('_workbench.ipc', function (accessor: ServicesAccessor, ipcMessage: string, ipcArgs: any[]) {
	if (ipcMessage && Array.isArray(ipcArgs)) {
		ipc.send(ipcMessage, ...ipcArgs);
	} else {
		ipc.send(ipcMessage);
	}
498 499
});

500 501 502
CommandsRegistry.registerCommand('_workbench.diff', function (accessor: ServicesAccessor, args: [URI, URI, string]) {
	const editorService = accessor.get(IWorkbenchEditorService);
	let [left, right, label] = args;
503

504 505 506
	if (!label) {
		label = nls.localize('diffLeftRightLabel', "{0} ⟷ {1}", left.toString(true), right.toString(true));
	}
507

508 509
	return TPromise.join([editorService.createInput({ resource: left }), editorService.createInput({ resource: right })]).then(inputs => {
		const [left, right] = inputs;
510

511 512 513 514 515
		const diff = new DiffEditorInput(label, undefined, <EditorInput>left, <EditorInput>right);
		return editorService.openEditor(diff);
	}).then(() => {
		return void 0;
	});
516 517
});

518 519
CommandsRegistry.registerCommand('_workbench.open', function (accessor: ServicesAccessor, args: [URI, number]) {
	const editorService = accessor.get(IWorkbenchEditorService);
B
Benjamin Pasero 已提交
520
	const [resource, column] = args;
521

522 523 524
	return editorService.openEditor({ resource }, column).then(() => {
		return void 0;
	});
525
});