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

I
isidor 已提交
6
import * as nls from 'vs/nls';
M
Matt Bierner 已提交
7
import { Event, Emitter } from 'vs/base/common/event';
I
isidor 已提交
8
import * as resources from 'vs/base/common/resources';
9
import { URI as uri } from 'vs/base/common/uri';
I
isidor 已提交
10 11 12
import { first, distinct } from 'vs/base/common/arrays';
import { isObject, isUndefinedOrNull } from 'vs/base/common/types';
import * as errors from 'vs/base/common/errors';
E
Erich Gamma 已提交
13
import severity from 'vs/base/common/severity';
J
Johannes Rieken 已提交
14
import { TPromise } from 'vs/base/common/winjs.base';
I
isidor 已提交
15
import * as aria from 'vs/base/browser/ui/aria/aria';
J
Johannes Rieken 已提交
16 17 18
import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
import { IMarkerService } from 'vs/platform/markers/common/markers';
import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle';
A
Andre Weinand 已提交
19
import { IExtensionService, IExtensionDescription } from 'vs/workbench/services/extensions/common/extensions';
J
Johannes Rieken 已提交
20
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
21
import { FileChangesEvent, FileChangeType, IFileService } from 'vs/platform/files/common/files';
I
isidor 已提交
22
import { IWindowService } from 'vs/platform/windows/common/windows';
J
Johannes Rieken 已提交
23 24
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
I
isidor 已提交
25
import { Model, ExceptionBreakpoint, FunctionBreakpoint, Breakpoint, Expression, RawObjectReplElement } from 'vs/workbench/parts/debug/common/debugModel';
I
isidor 已提交
26 27
import { ViewModel } from 'vs/workbench/parts/debug/common/debugViewModel';
import * as debugactions from 'vs/workbench/parts/debug/browser/debugActions';
28
import { ConfigurationManager } from 'vs/workbench/parts/debug/electron-browser/debugConfigurationManager';
29
import Constants from 'vs/workbench/parts/markers/electron-browser/constants';
30
import { ITaskService, ITaskSummary } from 'vs/workbench/parts/tasks/common/taskService';
31
import { TaskError } from 'vs/workbench/parts/tasks/common/taskSystem';
I
isidor 已提交
32
import { VIEWLET_ID as EXPLORER_VIEWLET_ID } from 'vs/workbench/parts/files/common/files';
B
Benjamin Pasero 已提交
33
import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';
J
Johannes Rieken 已提交
34
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';
35
import { IPartService, Parts } from 'vs/workbench/services/part/common/partService';
J
Johannes Rieken 已提交
36 37
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
S
Sandeep Somavarapu 已提交
38
import { IWorkspaceContextService, WorkbenchState, IWorkspaceFolder } from 'vs/platform/workspace/common/workspace';
39
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
I
isidor 已提交
40
import { EXTENSION_LOG_BROADCAST_CHANNEL, EXTENSION_ATTACH_BROADCAST_CHANNEL, EXTENSION_TERMINATE_BROADCAST_CHANNEL, EXTENSION_RELOAD_BROADCAST_CHANNEL, EXTENSION_CLOSE_EXTHOST_BROADCAST_CHANNEL } from 'vs/platform/extensions/common/extensionHost';
41
import { IBroadcastService } from 'vs/platform/broadcast/electron-browser/broadcastService';
42
import { IRemoteConsoleLog, parse, getFirstFrame } from 'vs/base/node/console';
I
isidor 已提交
43
import { TaskEvent, TaskEventKind, TaskIdentifier } from 'vs/workbench/parts/tasks/common/tasks';
44
import { IDialogService } from 'vs/platform/dialogs/common/dialogs';
I
isidor 已提交
45 46
import { INotificationService } from 'vs/platform/notification/common/notification';
import { IAction, Action } from 'vs/base/common/actions';
47
import { deepClone, equals } from 'vs/base/common/objects';
48
import { DebugSession } from 'vs/workbench/parts/debug/electron-browser/debugSession';
I
isidor 已提交
49
import { dispose, IDisposable } from 'vs/base/common/lifecycle';
A
Andre Weinand 已提交
50
import { IDebugService, State, IDebugSession, CONTEXT_DEBUG_TYPE, CONTEXT_DEBUG_STATE, CONTEXT_IN_DEBUG_MODE, IThread, IDebugConfiguration, VIEWLET_ID, REPL_ID, IConfig, ILaunch, IViewModel, IConfigurationManager, IModel, IReplElementSource, IEnablement, IBreakpoint, IBreakpointData, IExpression, ICompound, IGlobalConfig, IStackFrame, AdapterEndEvent } from 'vs/workbench/parts/debug/common/debug';
51
import { isExtensionHostDebugging } from 'vs/workbench/parts/debug/common/debugUtils';
E
Erich Gamma 已提交
52

I
isidor 已提交
53 54 55 56 57
const DEBUG_BREAKPOINTS_KEY = 'debug.breakpoint';
const DEBUG_BREAKPOINTS_ACTIVATED_KEY = 'debug.breakpointactivated';
const DEBUG_FUNCTION_BREAKPOINTS_KEY = 'debug.functionbreakpoint';
const DEBUG_EXCEPTION_BREAKPOINTS_KEY = 'debug.exceptionbreakpoint';
const DEBUG_WATCH_EXPRESSIONS_KEY = 'debug.watchexpressions';
E
Erich Gamma 已提交
58

I
isidor 已提交
59 60
export class DebugService implements IDebugService {
	_serviceBrand: any;
E
Erich Gamma 已提交
61

I
isidor 已提交
62
	private readonly _onDidChangeState: Emitter<State>;
63 64 65
	private readonly _onDidNewSession: Emitter<IDebugSession>;
	private readonly _onWillNewSession: Emitter<IDebugSession>;
	private readonly _onDidEndSession: Emitter<IDebugSession>;
I
isidor 已提交
66 67
	private model: Model;
	private viewModel: ViewModel;
68
	private configurationManager: ConfigurationManager;
69
	private allSessions = new Map<string, IDebugSession>();
I
isidor 已提交
70
	private toDispose: IDisposable[];
I
isidor 已提交
71
	private debugType: IContextKey<string>;
I
isidor 已提交
72
	private debugState: IContextKey<string>;
I
isidor 已提交
73
	private inDebugMode: IContextKey<boolean>;
I
isidor 已提交
74
	private breakpointsToSendOnResourceSaved: Set<string>;
75
	private skipRunningTask: boolean;
I
isidor 已提交
76
	private initializing = false;
I
isidor 已提交
77
	private previousState: State;
E
Erich Gamma 已提交
78 79 80

	constructor(
		@IStorageService private storageService: IStorageService,
81
		@IEditorService private editorService: IEditorService,
82 83
		@ITextFileService private textFileService: ITextFileService,
		@IViewletService private viewletService: IViewletService,
I
isidor 已提交
84
		@IPanelService private panelService: IPanelService,
85
		@INotificationService private notificationService: INotificationService,
86
		@IDialogService private dialogService: IDialogService,
E
Erich Gamma 已提交
87
		@IPartService private partService: IPartService,
88 89
		@IWindowService private windowService: IWindowService,
		@IBroadcastService private broadcastService: IBroadcastService,
E
Erich Gamma 已提交
90 91
		@ITelemetryService private telemetryService: ITelemetryService,
		@IWorkspaceContextService private contextService: IWorkspaceContextService,
92
		@IContextKeyService contextKeyService: IContextKeyService,
93
		@ILifecycleService private lifecycleService: ILifecycleService,
I
isidor 已提交
94
		@IInstantiationService private instantiationService: IInstantiationService,
A
Alex Dima 已提交
95
		@IExtensionService private extensionService: IExtensionService,
96
		@IMarkerService private markerService: IMarkerService,
97
		@ITaskService private taskService: ITaskService,
98
		@IFileService private fileService: IFileService,
I
isidor 已提交
99
		@IConfigurationService private configurationService: IConfigurationService,
E
Erich Gamma 已提交
100 101
	) {
		this.toDispose = [];
102

I
isidor 已提交
103
		this.breakpointsToSendOnResourceSaved = new Set<string>();
104

I
isidor 已提交
105
		this._onDidChangeState = new Emitter<State>();
106 107 108
		this._onDidNewSession = new Emitter<IDebugSession>();
		this._onWillNewSession = new Emitter<IDebugSession>();
		this._onDidEndSession = new Emitter<IDebugSession>();
E
Erich Gamma 已提交
109

110
		this.configurationManager = this.instantiationService.createInstance(ConfigurationManager);
111
		this.toDispose.push(this.configurationManager);
112

I
isidor 已提交
113 114 115
		this.debugType = CONTEXT_DEBUG_TYPE.bindTo(contextKeyService);
		this.debugState = CONTEXT_DEBUG_STATE.bindTo(contextKeyService);
		this.inDebugMode = CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService);
E
Erich Gamma 已提交
116

I
isidor 已提交
117
		this.model = new Model(this.loadBreakpoints(), this.storageService.getBoolean(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE, true), this.loadFunctionBreakpoints(),
118
			this.loadExceptionBreakpoints(), this.loadWatchExpressions(), this.textFileService);
I
isidor 已提交
119
		this.toDispose.push(this.model);
120

121
		this.viewModel = new ViewModel(contextKeyService);
E
Erich Gamma 已提交
122

123
		this.toDispose.push(this.fileService.onFileChanges(e => this.onFileChanges(e)));
124 125
		this.lifecycleService.onShutdown(this.store, this);
		this.lifecycleService.onShutdown(this.dispose, this);
126

127
		this.toDispose.push(this.broadcastService.onBroadcast(broadcast => {
A
Andre Weinand 已提交
128
			const session = this.getSession(broadcast.payload.debugId);
129 130
			if (session) {
				switch (broadcast.channel) {
131

132 133 134 135
					case EXTENSION_ATTACH_BROADCAST_CHANNEL:
						// EH was started in debug mode -> attach to it
						this.attachExtensionHost(session, broadcast.payload.port);
						break;
136

137
					case EXTENSION_TERMINATE_BROADCAST_CHANNEL:
A
Andre Weinand 已提交
138 139
						// EH was terminated
						session.disconnect();
140
						break;
141

142 143 144 145
					case EXTENSION_LOG_BROADCAST_CHANNEL:
						// extension logged output -> show it in REPL
						this.addToRepl(session, broadcast.payload.logEntry);
						break;
146 147
				}
			}
148
		}, this));
149

150 151 152 153 154
		this.toDispose.push(this.viewModel.onDidFocusSession(s => {
			const id = s ? s.getId() : undefined;
			this.model.setBreakpointsSessionId(id);
			this.onStateChange();
		}));
E
Erich Gamma 已提交
155 156
	}

157
	getSession(sessionId: string): IDebugSession {
A
Andre Weinand 已提交
158 159 160
		return this.allSessions.get(sessionId);
	}

161 162
	getModel(): IModel {
		return this.model;
I
isidor 已提交
163 164
	}

165 166
	getViewModel(): IViewModel {
		return this.viewModel;
E
Erich Gamma 已提交
167 168
	}

169 170
	getConfigurationManager(): IConfigurationManager {
		return this.configurationManager;
I
isidor 已提交
171 172
	}

173 174
	sourceIsNotAvailable(uri: uri): void {
		this.model.sourceIsNotAvailable(uri);
E
Erich Gamma 已提交
175 176
	}

177 178
	dispose(): void {
		this.toDispose = dispose(this.toDispose);
E
Erich Gamma 已提交
179 180
	}

181 182
	//---- state management

I
isidor 已提交
183
	get state(): State {
I
isidor 已提交
184
		const focusedSession = this.viewModel.focusedSession;
I
isidor 已提交
185 186
		if (focusedSession) {
			return focusedSession.state;
I
isidor 已提交
187
		}
188 189 190 191

		return this.initializing ? State.Initializing : State.Inactive;
	}

A
Andre Weinand 已提交
192
	private startInitializingState() {
193 194 195 196 197 198
		if (!this.initializing) {
			this.initializing = true;
			this.onStateChange();
		}
	}

A
Andre Weinand 已提交
199
	private endInitializingState() {
I
isidor 已提交
200
		if (this.initializing) {
201 202
			this.initializing = false;
			this.onStateChange();
I
isidor 已提交
203
		}
204
	}
I
isidor 已提交
205

206 207 208 209 210 211 212 213 214 215 216
	private onStateChange(): void {
		const state = this.state;
		if (this.previousState !== state) {
			const stateLabel = State[state];
			if (stateLabel) {
				this.debugState.set(stateLabel.toLowerCase());
				this.inDebugMode.set(state !== State.Inactive);
			}
			this.previousState = state;
			this._onDidChangeState.fire(state);
		}
E
Erich Gamma 已提交
217 218
	}

I
isidor 已提交
219
	get onDidChangeState(): Event<State> {
220 221 222
		return this._onDidChangeState.event;
	}

223
	get onDidNewSession(): Event<IDebugSession> {
I
isidor 已提交
224
		return this._onDidNewSession.event;
225 226
	}

227
	get onWillNewSession(): Event<IDebugSession> {
I
isidor 已提交
228 229 230
		return this._onWillNewSession.event;
	}

231
	get onDidEndSession(): Event<IDebugSession> {
I
isidor 已提交
232
		return this._onDidEndSession.event;
I
isidor 已提交
233 234
	}

235
	//---- life cycle management
E
Erich Gamma 已提交
236

A
Andre Weinand 已提交
237 238 239
	/**
	 * main entry point
	 */
I
isidor 已提交
240
	startDebugging(launch: ILaunch, configOrName?: IConfig | string, noDebug = false, unresolvedConfiguration?: IConfig, ): TPromise<void> {
241

242
		// make sure to save all files and that the configuration is up to date
A
Andre Weinand 已提交
243 244 245 246 247 248 249 250
		return this.extensionService.activateByEvent('onDebug').then(() =>
			this.textFileService.saveAll().then(() =>
				this.configurationService.reloadConfiguration(launch ? launch.workspace : undefined).then(() =>
					this.extensionService.whenInstalledExtensionsRegistered().then(() => {

						if (this.model.getSessions().length === 0) {
							this.removeReplExpressions();
							this.allSessions.clear();
I
isidor 已提交
251 252
						}

A
Andre Weinand 已提交
253 254 255 256 257 258 259 260 261 262 263 264
						let config: IConfig, compound: ICompound;
						if (!configOrName) {
							configOrName = this.configurationManager.selectedConfiguration.name;
						}
						if (typeof configOrName === 'string' && launch) {
							config = launch.getConfiguration(configOrName);
							compound = launch.getCompound(configOrName);

							const sessions = this.model.getSessions();
							const alreadyRunningMessage = nls.localize('configurationAlreadyRunning', "There is already a debug configuration \"{0}\" running.", configOrName);
							if (sessions.some(s => s.getName(false) === configOrName && (!launch || !launch.workspace || !s.root || s.root.uri.toString() === launch.workspace.uri.toString()))) {
								return TPromise.wrapError(new Error(alreadyRunningMessage));
265
							}
A
Andre Weinand 已提交
266 267
							if (compound && compound.configurations && sessions.some(p => compound.configurations.indexOf(p.getName(false)) !== -1)) {
								return TPromise.wrapError(new Error(alreadyRunningMessage));
268
							}
A
Andre Weinand 已提交
269 270
						} else if (typeof configOrName !== 'string') {
							config = configOrName;
I
isidor 已提交
271 272
						}

A
Andre Weinand 已提交
273 274 275 276 277
						if (compound) {
							if (!compound.configurations) {
								return TPromise.wrapError(new Error(nls.localize({ key: 'compoundMustHaveConfigurations', comment: ['compound indicates a "compounds" configuration item', '"configurations" is an attribute and should not be localized'] },
									"Compound must have \"configurations\" attribute set in order to start multiple configurations.")));
							}
I
isidor 已提交
278

A
Andre Weinand 已提交
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
							return TPromise.join(compound.configurations.map(configData => {
								const name = typeof configData === 'string' ? configData : configData.name;
								if (name === compound.name) {
									return TPromise.as(null);
								}

								let launchForName: ILaunch;
								if (typeof configData === 'string') {
									const launchesContainingName = this.configurationManager.getLaunches().filter(l => !!l.getConfiguration(name));
									if (launchesContainingName.length === 1) {
										launchForName = launchesContainingName[0];
									} else if (launchesContainingName.length > 1 && launchesContainingName.indexOf(launch) >= 0) {
										// If there are multiple launches containing the configuration give priority to the configuration in the current launch
										launchForName = launch;
									} else {
										return TPromise.wrapError(new Error(launchesContainingName.length === 0 ? nls.localize('noConfigurationNameInWorkspace', "Could not find launch configuration '{0}' in the workspace.", name)
											: nls.localize('multipleConfigurationNamesInWorkspace', "There are multiple launch configurations '{0}' in the workspace. Use folder name to qualify the configuration.", name)));
									}
								} else if (configData.folder) {
									const launchesMatchingConfigData = this.configurationManager.getLaunches().filter(l => l.workspace && l.workspace.name === configData.folder && !!l.getConfiguration(configData.name));
									if (launchesMatchingConfigData.length === 1) {
										launchForName = launchesMatchingConfigData[0];
									} else {
										return TPromise.wrapError(new Error(nls.localize('noFolderWithName', "Can not find folder with name '{0}' for configuration '{1}' in compound '{2}'.", configData.folder, configData.name, compound.name)));
									}
								}

								return this.startDebugging(launchForName, name, noDebug, unresolvedConfiguration);
							}));
						}
						if (configOrName && !config) {
							const message = !!launch ? nls.localize('configMissing', "Configuration '{0}' is missing in 'launch.json'.", typeof configOrName === 'string' ? configOrName : JSON.stringify(configOrName)) :
								nls.localize('launchJsonDoesNotExist', "'launch.json' does not exist.");
							return TPromise.wrapError(new Error(message));
						}
314

A
Andre Weinand 已提交
315 316 317 318 319 320 321 322
						// We keep the debug type in a separate variable 'type' so that a no-folder config has no attributes.
						// Storing the type in the config would break extensions that assume that the no-folder case is indicated by an empty config.
						let type: string;
						if (config) {
							type = config.type;
						} else {
							// a no-folder workspace has no launch.config
							config = <IConfig>{};
323
						}
A
Andre Weinand 已提交
324
						unresolvedConfiguration = unresolvedConfiguration || deepClone(config);
325

A
Andre Weinand 已提交
326 327
						if (noDebug) {
							config.noDebug = true;
328 329
						}

A
Andre Weinand 已提交
330 331 332 333 334 335 336
						return (type ? TPromise.as(null) : this.configurationManager.guessDebugger().then(a => type = a && a.type)).then(() =>
							this.configurationManager.resolveConfigurationByProviders(launch && launch.workspace ? launch.workspace.uri : undefined, type, config).then(config => {
								// a falsy config indicates an aborted launch
								if (config && config.type) {
									return this.createSession(launch, config, unresolvedConfiguration);
								}

337
								if (launch && type && config === null) {	// show launch.json only for "config" being "null".
A
Andre Weinand 已提交
338 339 340 341 342 343
									return launch.openConfigFile(false, true, type).then(() => undefined);
								}

								return undefined;
							})
						).then(() => undefined);
344
					})
A
Andre Weinand 已提交
345
				)));
A
Andre Weinand 已提交
346 347
	}

A
Andre Weinand 已提交
348
	private createSession(launch: ILaunch, config: IConfig, unresolvedConfig: IConfig): TPromise<void> {
349

A
Andre Weinand 已提交
350
		this.startInitializingState();
351

I
isidor 已提交
352
		return this.textFileService.saveAll().then(() =>
A
Andre Weinand 已提交
353 354
			this.substituteVariables(launch, config).then(resolvedConfig => {

355 356 357 358
				if (!resolvedConfig) {
					// User canceled resolving of interactive variables, silently return
					return undefined;
				}
I
isidor 已提交
359

360
				if (!this.configurationManager.getDebugger(resolvedConfig.type) || (config.request !== 'attach' && config.request !== 'launch')) {
361 362
					let message: string;
					if (config.request !== 'attach' && config.request !== 'launch') {
363
						message = config.request ? nls.localize('debugRequestNotSupported', "Attribute '{0}' has an unsupported value '{1}' in the chosen debug configuration.", 'request', config.request)
A
Andre Weinand 已提交
364
							: nls.localize('debugRequesMissing', "Attribute '{0}' is missing from the chosen debug configuration.", 'request');
365 366 367

					} else {
						message = resolvedConfig.type ? nls.localize('debugTypeNotSupported', "Configured debug type '{0}' is not supported.", resolvedConfig.type) :
368
							nls.localize('debugTypeMissing', "Missing property 'type' for the chosen launch configuration.");
369 370
					}

I
isidor 已提交
371
					return this.showError(message);
372
				}
J
Johannes Rieken 已提交
373

374
				const workspace = launch ? launch.workspace : undefined;
A
Andre Weinand 已提交
375
				return this.runTask(workspace, resolvedConfig.preLaunchTask, resolvedConfig, unresolvedConfig).then(success => {
376 377
					if (success) {
						return this.doCreateSession(workspace, { resolved: resolvedConfig, unresolved: unresolvedConfig });
378
					}
379
					return undefined;
380
				});
381
			}, err => {
I
isidor 已提交
382 383 384
				if (err && err.message) {
					return this.showError(err.message);
				}
385
				if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
I
isidor 已提交
386
					return this.showError(nls.localize('noFolderWorkspaceDebugError', "The active file can not be debugged. Make sure it is saved on disk and that you have a debug extension installed for that file type."));
387
				}
E
Erich Gamma 已提交
388

389
				return launch && launch.openConfigFile(false, true).then(editor => void 0);
390
			})
I
isidor 已提交
391
		).then(() => {
A
Andre Weinand 已提交
392
			this.endInitializingState();
393
		}, err => {
A
Andre Weinand 已提交
394
			this.endInitializingState();
395
			return TPromise.wrapError(err);
I
isidor 已提交
396
		});
397
	}
398

A
Andre Weinand 已提交
399
	private attachExtensionHost(session: IDebugSession, port: number): TPromise<void> {
A
Andre Weinand 已提交
400

401 402 403
		session.configuration.request = 'attach';
		session.configuration.port = port;
		const dbgr = this.configurationManager.getDebugger(session.configuration.type);
A
Andre Weinand 已提交
404

405
		return session.initialize(dbgr).then(() => {
A
Andre Weinand 已提交
406
			session.launchOrAttach(session.configuration).then(() => {
A
Andre Weinand 已提交
407 408
				this.focusStackFrame(undefined, undefined, session);
			});
409 410 411
		});
	}

A
Andre Weinand 已提交
412
	private doCreateSession(root: IWorkspaceFolder, configuration: { resolved: IConfig, unresolved: IConfig }): TPromise<any> {
413

A
Andre Weinand 已提交
414
		const session = <IDebugSession>this.instantiationService.createInstance(DebugSession, configuration, root, this.model);
A
Andre Weinand 已提交
415
		this.allSessions.set(session.getId(), session);
416

417 418 419 420 421
		// register listeners as the very first thing!
		this.registerSessionListeners(session);

		// since the Session is now properly registered under its ID and hooked, we can announce it
		// this event doesn't go to extensions
I
isidor 已提交
422
		this._onWillNewSession.fire(session);
A
Andre Weinand 已提交
423 424 425 426

		const resolved = configuration.resolved;
		const dbgr = this.configurationManager.getDebugger(resolved.type);

I
isidor 已提交
427
		return session.initialize(dbgr).then(() => {
A
Andre Weinand 已提交
428

A
Andre Weinand 已提交
429
			return session.launchOrAttach(resolved).then(() => {
430

A
Andre Weinand 已提交
431
				this.focusStackFrame(undefined, undefined, session);
432

433
				// since the initialized response has arrived announce the new Session (including extensions)
A
Andre Weinand 已提交
434
				this._onDidNewSession.fire(session);
A
Andre Weinand 已提交
435

A
Andre Weinand 已提交
436 437 438 439
				const internalConsoleOptions = resolved.internalConsoleOptions || this.configurationService.getValue<IDebugConfiguration>('debug').internalConsoleOptions;
				if (internalConsoleOptions === 'openOnSessionStart' || (this.viewModel.firstSessionStart && internalConsoleOptions === 'openOnFirstSessionStart')) {
					this.panelService.openPanel(REPL_ID, false);
				}
440

A
Andre Weinand 已提交
441 442 443 444 445 446
				const openDebug = this.configurationService.getValue<IDebugConfiguration>('debug').openDebug;
				// Open debug viewlet based on the visibility of the side bar and openDebug setting
				if (openDebug === 'openOnSessionStart' || (openDebug === 'openOnFirstSessionStart' && this.viewModel.firstSessionStart)) {
					this.viewletService.openViewlet(VIEWLET_ID);
				}
				this.viewModel.firstSessionStart = false;
I
isidor 已提交
447

A
Andre Weinand 已提交
448 449 450 451
				this.debugType.set(resolved.type);
				if (this.model.getSessions().length > 1) {
					this.viewModel.setMultiSessionView(true);
				}
452

A
Andre Weinand 已提交
453 454 455
				return this.telemetryDebugSessionStart(root, resolved.type, dbgr.extensionDescription);

			}).then(() => session, (error: Error | string) => {
456

A
Andre Weinand 已提交
457 458 459 460 461
				if (session) {
					session.dispose();
				}

				if (errors.isPromiseCanceledError(error)) {
A
Andre Weinand 已提交
462 463
					// don't show 'canceled' error messages to the user #7906
					return TPromise.as(undefined);
A
Andre Weinand 已提交
464 465 466 467 468 469 470 471 472 473 474 475 476 477
				}

				// Show the repl if some error got logged there #5870
				if (this.model.getReplElements().length > 0) {
					this.panelService.openPanel(REPL_ID, false);
				}

				if (resolved && resolved.request === 'attach' && resolved.__autoAttach) {
					// ignore attach timeouts in auto attach mode
				} else {
					const errorMessage = error instanceof Error ? error.message : error;
					this.telemetryDebugMisconfiguration(resolved ? resolved.type : undefined, errorMessage);
					this.showError(errorMessage, errors.isErrorWithActions(error) ? error.actions : []);
				}
A
Andre Weinand 已提交
478
				return TPromise.as(undefined);
A
Andre Weinand 已提交
479
			});
480 481

		}).then(undefined, error => {
482

483 484 485 486
			if (session) {
				session.dispose();
			}

487
			if (errors.isPromiseCanceledError(error)) {
A
Andre Weinand 已提交
488
				// don't show 'canceled' error messages to the user #7906
489 490 491
				return TPromise.as(null);
			}
			return TPromise.wrapError(error);
E
Erich Gamma 已提交
492 493 494
		});
	}

A
Andre Weinand 已提交
495
	private registerSessionListeners(session: IDebugSession): void {
496

497 498
		this.toDispose.push(session.onDidChangeState((state) => {
			if (state === State.Running && this.viewModel.focusedSession && this.viewModel.focusedSession.getId() === session.getId()) {
I
isidor 已提交
499 500 501 502 503
				this.focusStackFrame(undefined);
			}
			this.onStateChange();
		}));

A
Andre Weinand 已提交
504
		this.toDispose.push(session.onDidEndAdapter(adapterExitEvent => {
505

A
Andre Weinand 已提交
506 507
			if (adapterExitEvent.error) {
				this.notificationService.error(nls.localize('debugAdapterCrash', "Debug adapter process has terminated unexpectedly ({0})", adapterExitEvent.error.message || adapterExitEvent.error.toString()));
508
			}
509

I
isidor 已提交
510
			// 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905
511
			if (isExtensionHostDebugging(session.configuration) && session.state === State.Running && session.configuration.noDebug) {
I
isidor 已提交
512 513
				this.broadcastService.broadcast({
					channel: EXTENSION_CLOSE_EXTHOST_BROADCAST_CHANNEL,
514
					payload: [session.root.uri.toString()]
I
isidor 已提交
515 516 517
				});
			}

A
Andre Weinand 已提交
518
			this.telemetryDebugSessionStop(session, adapterExitEvent);
I
isidor 已提交
519 520

			if (session.configuration.postDebugTask) {
A
Andre Weinand 已提交
521
				this.doRunTask(session.root, session.configuration.postDebugTask).then(undefined, err =>
I
isidor 已提交
522 523 524
					this.notificationService.error(err)
				);
			}
525
			session.dispose();
I
isidor 已提交
526 527 528 529
			this._onDidEndSession.fire(session);

			const focusedSession = this.viewModel.focusedSession;
			if (focusedSession && focusedSession.getId() === session.getId()) {
530
				this.focusStackFrame(undefined);
I
isidor 已提交
531 532 533 534 535 536 537
			}

			if (this.model.getSessions().length === 0) {
				this.debugType.reset();
				this.viewModel.setMultiSessionView(false);

				if (this.partService.isVisible(Parts.SIDEBAR_PART) && this.configurationService.getValue<IDebugConfiguration>('debug').openExplorerOnEnd) {
538
					this.viewletService.openViewlet(EXPLORER_VIEWLET_ID);
I
isidor 已提交
539 540 541 542 543 544
				}
			}

		}));
	}

545
	restartSession(session: IDebugSession, restartData?: any): TPromise<any> {
A
Andre Weinand 已提交
546 547


548
		return this.textFileService.saveAll().then(() => {
A
Andre Weinand 已提交
549 550

			const unresolvedConfiguration = session.unresolvedConfiguration;
551
			if (session.capabilities.supportsRestartRequest) {
A
Andre Weinand 已提交
552 553
				return this.runTask(session.root, session.configuration.postDebugTask, session.configuration, unresolvedConfiguration)
					.then(success => success ? this.runTask(session.root, session.configuration.preLaunchTask, session.configuration, unresolvedConfiguration)
A
Andre Weinand 已提交
554
						.then(success => success ? session.restart() : undefined) : TPromise.as(<any>undefined));
555 556 557 558
			}

			const focusedSession = this.viewModel.focusedSession;
			const preserveFocus = focusedSession && session.getId() === focusedSession.getId();
A
Andre Weinand 已提交
559

560
			// Do not run preLaunch and postDebug tasks for automatic restarts
A
Andre Weinand 已提交
561 562
			const isAutoRestart = !!restartData;
			this.skipRunningTask = isAutoRestart;
563

564
			if (isExtensionHostDebugging(session.configuration) && session.root) {
565 566 567 568 569 570
				return this.broadcastService.broadcast({
					channel: EXTENSION_RELOAD_BROADCAST_CHANNEL,
					payload: [session.root.uri.toString()]
				});
			}

A
Andre Weinand 已提交
571 572
			// If the restart is automatic  -> disconnect, otherwise -> terminate #55064
			return (isAutoRestart ? session.disconnect(true) : session.terminate(true)).then(() => {
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589

				return new TPromise<void>((c, e) => {
					setTimeout(() => {
						// Read the configuration again if a launch.json has been changed, if not just use the inmemory configuration
						let configToUse = session.configuration;

						const launch = session.root ? this.configurationManager.getLaunch(session.root.uri) : undefined;
						if (launch) {
							const config = launch.getConfiguration(session.configuration.name);
							if (config && !equals(config, unresolvedConfiguration)) {
								// Take the type from the session since the debug extension might overwrite it #21316
								configToUse = config;
								configToUse.type = session.configuration.type;
								configToUse.noDebug = session.configuration.noDebug;
							}
						}
						configToUse.__restart = restartData;
A
Andre Weinand 已提交
590
						this.skipRunningTask = isAutoRestart;
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
						this.startDebugging(launch, configToUse, configToUse.noDebug, unresolvedConfiguration).then(() => c(null), err => e(err));
					}, 300);
				});
			}).then(() => {
				if (preserveFocus) {
					// Restart should preserve the focused session
					const restartedSession = this.model.getSessions().filter(p => p.configuration.name === session.configuration.name).pop();
					if (restartedSession && restartedSession !== this.viewModel.focusedSession) {
						this.focusStackFrame(undefined, undefined, restartedSession);
					}
				}
			});
		});
	}

606
	stopSession(session: IDebugSession): TPromise<any> {
A
Andre Weinand 已提交
607

608
		if (session) {
A
Andre Weinand 已提交
609
			return session.terminate();
610 611 612 613
		}

		const sessions = this.model.getSessions();
		if (sessions.length) {
A
Andre Weinand 已提交
614
			return TPromise.join(sessions.map(s => s.terminate()));
615 616
		}

A
Andre Weinand 已提交
617
		this._onDidChangeState.fire();	// TODO@AW why state change?
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
		return undefined;
	}

	private substituteVariables(launch: ILaunch | undefined, config: IConfig): TPromise<IConfig> {
		const dbg = this.configurationManager.getDebugger(config.type);
		if (dbg) {
			let folder: IWorkspaceFolder = undefined;
			if (launch && launch.workspace) {
				folder = launch.workspace;
			} else {
				const folders = this.contextService.getWorkspace().folders;
				if (folders.length === 1) {
					folder = folders[0];
				}
			}
			return dbg.substituteVariables(folder, config).then(config => {
				return config;
			}, (err: Error) => {
				this.showError(err.message);
				return undefined;	// bail out
			});
		}
		return TPromise.as(config);
	}

I
isidor 已提交
643 644 645
	private showError(message: string, actions: IAction[] = []): TPromise<any> {
		const configureAction = this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL);
		actions.push(configureAction);
646
		return this.dialogService.show(severity.Error, message, actions.map(a => a.label).concat(nls.localize('cancel', "Cancel")), { cancelId: actions.length }).then(choice => {
I
isidor 已提交
647 648 649 650 651 652 653 654
			if (choice < actions.length) {
				return actions[choice].run();
			}

			return TPromise.as(null);
		});
	}

655 656
	//---- task management

A
Andre Weinand 已提交
657 658
	private runTask(root: IWorkspaceFolder, taskId: string | TaskIdentifier, config: IConfig, unresolvedConfig: IConfig): TPromise<boolean> {

659
		const debugAnywayAction = new Action('debug.debugAnyway', nls.localize('debugAnyway', "Debug Anyway"), undefined, true, () => {
A
Andre Weinand 已提交
660
			return this.doCreateSession(root, { resolved: config, unresolved: unresolvedConfig });
661 662
		});

A
Andre Weinand 已提交
663
		return this.doRunTask(root, taskId).then((taskSummary: ITaskSummary) => {
664 665 666 667
			const errorCount = config.preLaunchTask ? this.markerService.getStatistics().errors : 0;
			const successExitCode = taskSummary && taskSummary.exitCode === 0;
			const failureExitCode = taskSummary && taskSummary.exitCode !== undefined && taskSummary.exitCode !== 0;
			if (successExitCode || (errorCount === 0 && !failureExitCode)) {
668
				return true;
669 670
			}

671 672 673 674 675 676
			const taskId = typeof config.preLaunchTask === 'string' ? config.preLaunchTask : JSON.stringify(config.preLaunchTask);
			const message = errorCount > 1
				? nls.localize('preLaunchTaskErrors', "Build errors have been detected during preLaunchTask '{0}'.", taskId)
				: errorCount === 1
					? nls.localize('preLaunchTaskError', "Build error has been detected during preLaunchTask '{0}'.", taskId)
					: nls.localize('preLaunchTaskExitCode', "The preLaunchTask '{0}' terminated with exit code {1}.", taskId, taskSummary.exitCode);
677 678 679 680 681

			const showErrorsAction = new Action('debug.showErrors', nls.localize('showErrors', "Show Errors"), undefined, true, () => {
				return this.panelService.openPanel(Constants.MARKERS_PANEL_ID).then(() => undefined);
			});

682
			return this.showError(message, [debugAnywayAction, showErrorsAction]).then(() => false);
683
		}, (err: TaskError) => {
684
			return this.showError(err.message, [debugAnywayAction, this.taskService.configureAction()]).then(() => false);
685 686 687
		});
	}

A
Andre Weinand 已提交
688
	private doRunTask(root: IWorkspaceFolder, taskId: string | TaskIdentifier): TPromise<ITaskSummary> {
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
		if (!taskId || this.skipRunningTask) {
			this.skipRunningTask = false;
			return TPromise.as(null);
		}
		// run a task before starting a debug session
		return this.taskService.getTask(root, taskId).then(task => {
			if (!task) {
				const errorMessage = typeof taskId === 'string'
					? nls.localize('DebugTaskNotFoundWithTaskId', "Could not find the task '{0}'.", taskId)
					: nls.localize('DebugTaskNotFound', "Could not find the specified task.");
				return TPromise.wrapError(errors.create(errorMessage));
			}

			function once(kind: TaskEventKind, event: Event<TaskEvent>): Event<TaskEvent> {
				return (listener, thisArgs = null, disposables?) => {
					const result = event(e => {
						if (e.kind === kind) {
							result.dispose();
							return listener.call(thisArgs, e);
						}
					}, null, disposables);
					return result;
				};
			}
			// If a task is missing the problem matcher the promise will never complete, so we need to have a workaround #35340
			let taskStarted = false;
			const promise = this.taskService.getActiveTasks().then(tasks => {
				if (tasks.filter(t => t._id === task._id).length) {
					// task is already running - nothing to do.
					return TPromise.as(null);
				}
				once(TaskEventKind.Active, this.taskService.onDidStateChange)((taskEvent) => {
					taskStarted = true;
				});
				const taskPromise = this.taskService.run(task);
				if (task.isBackground) {
					return new TPromise((c, e) => once(TaskEventKind.Inactive, this.taskService.onDidStateChange)(() => c(null)));
				}

				return taskPromise;
			});

			return new TPromise((c, e) => {
				promise.then(result => {
					taskStarted = true;
					c(result);
				}, error => e(error));

				setTimeout(() => {
					if (!taskStarted) {
						const errorMessage = typeof taskId === 'string'
							? nls.localize('taskNotTrackedWithTaskId', "The specified task cannot be tracked.")
741
							: nls.localize('taskNotTracked', "The task '{0}' cannot be tracked.", JSON.stringify(taskId));
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
						e({ severity: severity.Error, message: errorMessage });
					}
				}, 10000);
			});
		});
	}

	//---- focus management

	tryToAutoFocusStackFrame(thread: IThread): TPromise<any> {
		const callStack = thread.getCallStack();
		if (!callStack.length || (this.viewModel.focusedStackFrame && this.viewModel.focusedStackFrame.thread.getId() === thread.getId())) {
			return TPromise.as(null);
		}

		// focus first stack frame from top that has source location if no other stack frame is focused
		const stackFrameToFocus = first(callStack, sf => sf.source && sf.source.available, undefined);
		if (!stackFrameToFocus) {
			return TPromise.as(null);
		}

		this.focusStackFrame(stackFrameToFocus);
		if (thread.stoppedDetails) {
			if (this.configurationService.getValue<IDebugConfiguration>('debug').openDebug === 'openOnDebugBreak') {
				this.viewletService.openViewlet(VIEWLET_ID);
			}
			this.windowService.focusWindow();
			aria.alert(nls.localize('debuggingPaused', "Debugging paused, reason {0}, {1} {2}", thread.stoppedDetails.reason, stackFrameToFocus.source ? stackFrameToFocus.source.name : '', stackFrameToFocus.range.startLineNumber));
		}

		return stackFrameToFocus.openInEditor(this.editorService, true);
	}

775
	focusStackFrame(stackFrame: IStackFrame, thread?: IThread, session?: IDebugSession, explicit?: boolean): void {
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
		if (!session) {
			if (stackFrame || thread) {
				session = stackFrame ? stackFrame.thread.session : thread.session;
			} else {
				const sessions = this.model.getSessions();
				session = sessions.length ? sessions[0] : undefined;
			}
		}

		if (!thread) {
			if (stackFrame) {
				thread = stackFrame.thread;
			} else {
				const threads = session ? session.getAllThreads() : undefined;
				thread = threads && threads.length ? threads[0] : undefined;
			}
		}

		if (!stackFrame) {
			if (thread) {
				const callStack = thread.getCallStack();
				stackFrame = callStack && callStack.length ? callStack[0] : null;
			}
		}

		this.viewModel.setFocus(stackFrame, thread, session, explicit);
	}

	//---- REPL

	addReplExpression(name: string): TPromise<void> {
		return this.model.addReplExpression(this.viewModel.focusedSession, this.viewModel.focusedStackFrame, name)
			// Evaluate all watch expressions and fetch variables again since repl evaluation might have changed some.
			.then(() => this.focusStackFrame(this.viewModel.focusedStackFrame, this.viewModel.focusedThread, this.viewModel.focusedSession));
	}

	removeReplExpressions(): void {
		this.model.removeReplExpressions();
	}

816
	private addToRepl(session: IDebugSession, extensionOutput: IRemoteConsoleLog) {
817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833

		let sev = extensionOutput.severity === 'warn' ? severity.Warning : extensionOutput.severity === 'error' ? severity.Error : severity.Info;

		const { args, stack } = parse(extensionOutput);
		let source: IReplElementSource;
		if (stack) {
			const frame = getFirstFrame(stack);
			if (frame) {
				source = {
					column: frame.column,
					lineNumber: frame.line,
					source: session.getSource({
						name: resources.basenameOrAuthority(frame.uri),
						path: frame.uri.fsPath
					})
				};
			}
E
Erich Gamma 已提交
834
		}
835 836 837 838 839 840 841 842 843

		// add output for each argument logged
		let simpleVals: any[] = [];
		for (let i = 0; i < args.length; i++) {
			let a = args[i];

			// undefined gets printed as 'undefined'
			if (typeof a === 'undefined') {
				simpleVals.push('undefined');
E
Erich Gamma 已提交
844 845
			}

846 847 848
			// null gets printed as 'null'
			else if (a === null) {
				simpleVals.push('null');
849
			}
850 851 852 853 854 855 856 857

			// objects & arrays are special because we want to inspect them in the REPL
			else if (isObject(a) || Array.isArray(a)) {

				// flush any existing simple values logged
				if (simpleVals.length) {
					this.logToRepl(simpleVals.join(' '), sev, source);
					simpleVals = [];
I
isidor 已提交
858
				}
E
Erich Gamma 已提交
859

860 861 862
				// show object
				this.logToRepl(new RawObjectReplElement((<any>a).prototype, a, undefined, nls.localize('snapshotObj', "Only primitive values are shown for this object.")), sev, source);
			}
863

864 865 866 867
			// string: watch out for % replacement directive
			// string substitution and formatting @ https://developer.chrome.com/devtools/docs/console
			else if (typeof a === 'string') {
				let buf = '';
868

869 870 871 872 873 874 875
				for (let j = 0, len = a.length; j < len; j++) {
					if (a[j] === '%' && (a[j + 1] === 's' || a[j + 1] === 'i' || a[j + 1] === 'd' || a[j + 1] === 'O')) {
						i++; // read over substitution
						buf += !isUndefinedOrNull(args[i]) ? args[i] : ''; // replace
						j++; // read over directive
					} else {
						buf += a[j];
876
					}
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
				}

				simpleVals.push(buf);
			}

			// number or boolean is joined together
			else {
				simpleVals.push(a);
			}
		}

		// flush simple values
		// always append a new line for output coming from an extension such that separate logs go to separate lines #23695
		if (simpleVals.length) {
			this.logToRepl(simpleVals.join(' ') + '\n', sev, source);
		}
E
Erich Gamma 已提交
893 894
	}

895 896 897 898 899 900 901 902 903 904
	logToRepl(value: string | IExpression, sev = severity.Info, source?: IReplElementSource): void {
		const clearAnsiSequence = '\u001b[2J';
		if (typeof value === 'string' && value.indexOf(clearAnsiSequence) >= 0) {
			// [2J is the ansi escape sequence for clearing the display http://ascii-table.com/ansi-escape-sequences.php
			this.model.removeReplExpressions();
			this.model.appendToRepl(nls.localize('consoleCleared', "Console was cleared"), severity.Ignore);
			value = value.substr(value.lastIndexOf(clearAnsiSequence) + clearAnsiSequence.length);
		}

		this.model.appendToRepl(value, sev, source);
I
isidor 已提交
905 906
	}

907
	//---- watches
908

909 910 911 912
	addWatchExpression(name: string): void {
		const we = this.model.addWatchExpression(name);
		this.viewModel.setSelectedExpression(we);
	}
913

914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934
	renameWatchExpression(id: string, newName: string): void {
		return this.model.renameWatchExpression(id, newName);
	}

	moveWatchExpression(id: string, position: number): void {
		this.model.moveWatchExpression(id, position);
	}

	removeWatchExpressions(id?: string): void {
		this.model.removeWatchExpressions(id);
	}

	//---- breakpoints

	enableOrDisableBreakpoints(enable: boolean, breakpoint?: IEnablement): TPromise<void> {
		if (breakpoint) {
			this.model.setEnablement(breakpoint, enable);
			if (breakpoint instanceof Breakpoint) {
				return this.sendBreakpoints(breakpoint.uri);
			} else if (breakpoint instanceof FunctionBreakpoint) {
				return this.sendFunctionBreakpoints();
I
isidor 已提交
935 936
			}

937 938
			return this.sendExceptionBreakpoints();
		}
939

940 941 942
		this.model.enableOrDisableAllBreakpoints(enable);
		return this.sendAllBreakpoints();
	}
943

944 945 946 947 948
	addBreakpoints(uri: uri, rawBreakpoints: IBreakpointData[]): TPromise<IBreakpoint[]> {
		const breakpoints = this.model.addBreakpoints(uri, rawBreakpoints);
		breakpoints.forEach(bp => aria.status(nls.localize('breakpointAdded', "Added breakpoint, line {0}, file {1}", bp.lineNumber, uri.fsPath)));

		return this.sendBreakpoints(uri).then(() => breakpoints);
E
Erich Gamma 已提交
949 950
	}

951 952 953 954 955 956
	updateBreakpoints(uri: uri, data: { [id: string]: DebugProtocol.Breakpoint }, sendOnResourceSaved: boolean): void {
		this.model.updateBreakpoints(data);
		if (sendOnResourceSaved) {
			this.breakpointsToSendOnResourceSaved.add(uri.toString());
		} else {
			this.sendBreakpoints(uri);
957
		}
958
	}
959

960 961 962 963
	removeBreakpoints(id?: string): TPromise<any> {
		const toRemove = this.model.getBreakpoints().filter(bp => !id || bp.getId() === id);
		toRemove.forEach(bp => aria.status(nls.localize('breakpointRemoved', "Removed breakpoint, line {0}, file {1}", bp.lineNumber, bp.uri.fsPath)));
		const urisToClear = distinct(toRemove, bp => bp.uri.toString()).map(bp => bp.uri);
964

965 966 967
		this.model.removeBreakpoints(toRemove);

		return TPromise.join(urisToClear.map(uri => this.sendBreakpoints(uri)));
968 969
	}

970 971 972
	setBreakpointsActivated(activated: boolean): TPromise<void> {
		this.model.setBreakpointsActivated(activated);
		return this.sendAllBreakpoints();
E
Erich Gamma 已提交
973 974
	}

975 976 977
	addFunctionBreakpoint(name?: string, id?: string): void {
		const newFunctionBreakpoint = this.model.addFunctionBreakpoint(name || '', id);
		this.viewModel.setSelectedFunctionBreakpoint(newFunctionBreakpoint);
E
Erich Gamma 已提交
978 979
	}

980 981 982 983 984 985 986 987
	renameFunctionBreakpoint(id: string, newFunctionName: string): TPromise<void> {
		this.model.renameFunctionBreakpoint(id, newFunctionName);
		return this.sendFunctionBreakpoints();
	}

	removeFunctionBreakpoints(id?: string): TPromise<void> {
		this.model.removeFunctionBreakpoints(id);
		return this.sendFunctionBreakpoints();
988 989
	}

990
	sendAllBreakpoints(session?: IDebugSession): TPromise<any> {
I
isidor 已提交
991 992
		return TPromise.join(distinct(this.model.getBreakpoints(), bp => bp.uri.toString()).map(bp => this.sendBreakpoints(bp.uri, false, session)))
			.then(() => this.sendFunctionBreakpoints(session))
I
isidor 已提交
993
			// send exception breakpoints at the end since some debug adapters rely on the order
I
isidor 已提交
994
			.then(() => this.sendExceptionBreakpoints(session));
E
Erich Gamma 已提交
995 996
	}

997
	private sendBreakpoints(modelUri: uri, sourceModified = false, session?: IDebugSession): TPromise<void> {
998

A
Andre Weinand 已提交
999
		const breakpointsToSend = this.model.getBreakpoints({ uri: modelUri, enabledOnly: true });
1000

A
Andre Weinand 已提交
1001 1002 1003 1004
		return this.sendToOneOrAllSessions(session, s => {
			return s.sendBreakpoints(modelUri, breakpointsToSend, sourceModified).then(data => {
				if (data) {
					this.model.setBreakpointSessionData(s.getId(), data);
I
isidor 已提交
1005 1006
				}
			});
A
Andre Weinand 已提交
1007
		});
E
Erich Gamma 已提交
1008 1009
	}

1010
	private sendFunctionBreakpoints(session?: IDebugSession): TPromise<void> {
1011

A
Andre Weinand 已提交
1012
		const breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated());
I
isidor 已提交
1013

A
Andre Weinand 已提交
1014 1015 1016 1017
		return this.sendToOneOrAllSessions(session, s => {
			return s.sendFunctionBreakpoints(breakpointsToSend).then(data => {
				if (data) {
					this.model.setBreakpointSessionData(s.getId(), data);
I
isidor 已提交
1018 1019
				}
			});
A
Andre Weinand 已提交
1020
		});
I
isidor 已提交
1021 1022
	}

1023
	private sendExceptionBreakpoints(session?: IDebugSession): TPromise<void> {
I
isidor 已提交
1024

A
Andre Weinand 已提交
1025
		const enabledExceptionBps = this.model.getExceptionBreakpoints().filter(exb => exb.enabled);
I
isidor 已提交
1026

A
Andre Weinand 已提交
1027 1028 1029
		return this.sendToOneOrAllSessions(session, s => {
			return s.sendExceptionBreakpoints(enabledExceptionBps);
		});
I
isidor 已提交
1030 1031
	}

1032
	private sendToOneOrAllSessions(session: IDebugSession, send: (session: IDebugSession) => TPromise<void>): TPromise<void> {
I
isidor 已提交
1033 1034
		if (session) {
			return send(session);
I
isidor 已提交
1035
		}
I
isidor 已提交
1036
		return TPromise.join(this.model.getSessions().map(s => send(s))).then(() => void 0);
E
Erich Gamma 已提交
1037 1038 1039
	}

	private onFileChanges(fileChangesEvent: FileChangesEvent): void {
I
isidor 已提交
1040 1041 1042 1043 1044
		const toRemove = this.model.getBreakpoints().filter(bp =>
			fileChangesEvent.contains(bp.uri, FileChangeType.DELETED));
		if (toRemove.length) {
			this.model.removeBreakpoints(toRemove);
		}
1045 1046

		fileChangesEvent.getUpdated().forEach(event => {
1047

1048
			if (this.breakpointsToSendOnResourceSaved.delete(event.resource.toString())) {
1049
				this.sendBreakpoints(event.resource, true);
1050 1051
			}
		});
E
Erich Gamma 已提交
1052 1053
	}

1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
	private loadBreakpoints(): Breakpoint[] {
		let result: Breakpoint[];
		try {
			result = JSON.parse(this.storageService.get(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((breakpoint: any) => {
				return new Breakpoint(uri.parse(breakpoint.uri.external || breakpoint.source.uri.external), breakpoint.lineNumber, breakpoint.column, breakpoint.enabled, breakpoint.condition, breakpoint.hitCondition, breakpoint.logMessage, breakpoint.adapterData, this.textFileService);
			});
		} catch (e) { }

		return result || [];
	}

	private loadFunctionBreakpoints(): FunctionBreakpoint[] {
		let result: FunctionBreakpoint[];
		try {
			result = JSON.parse(this.storageService.get(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((fb: any) => {
				return new FunctionBreakpoint(fb.name, fb.enabled, fb.hitCondition, fb.condition, fb.logMessage);
			});
		} catch (e) { }

		return result || [];
	}

	private loadExceptionBreakpoints(): ExceptionBreakpoint[] {
		let result: ExceptionBreakpoint[];
		try {
			result = JSON.parse(this.storageService.get(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((exBreakpoint: any) => {
				return new ExceptionBreakpoint(exBreakpoint.filter, exBreakpoint.label, exBreakpoint.enabled);
			});
		} catch (e) { }

		return result || [];
	}

	private loadWatchExpressions(): Expression[] {
		let result: Expression[];
		try {
			result = JSON.parse(this.storageService.get(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE, '[]')).map((watchStoredData: { name: string, id: string }) => {
				return new Expression(watchStoredData.name, watchStoredData.id);
			});
		} catch (e) { }

		return result || [];
	}

E
Erich Gamma 已提交
1098
	private store(): void {
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
		const breakpoints = this.model.getBreakpoints();
		if (breakpoints.length) {
			this.storageService.store(DEBUG_BREAKPOINTS_KEY, JSON.stringify(breakpoints), StorageScope.WORKSPACE);
		} else {
			this.storageService.remove(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE);
		}

		if (!this.model.areBreakpointsActivated()) {
			this.storageService.store(DEBUG_BREAKPOINTS_ACTIVATED_KEY, 'false', StorageScope.WORKSPACE);
		} else {
			this.storageService.remove(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE);
		}

		const functionBreakpoints = this.model.getFunctionBreakpoints();
		if (functionBreakpoints.length) {
			this.storageService.store(DEBUG_FUNCTION_BREAKPOINTS_KEY, JSON.stringify(functionBreakpoints), StorageScope.WORKSPACE);
		} else {
			this.storageService.remove(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE);
		}

		const exceptionBreakpoints = this.model.getExceptionBreakpoints();
		if (exceptionBreakpoints.length) {
			this.storageService.store(DEBUG_EXCEPTION_BREAKPOINTS_KEY, JSON.stringify(exceptionBreakpoints), StorageScope.WORKSPACE);
		} else {
			this.storageService.remove(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE);
		}

		const watchExpressions = this.model.getWatchExpressions();
		if (watchExpressions.length) {
			this.storageService.store(DEBUG_WATCH_EXPRESSIONS_KEY, JSON.stringify(watchExpressions.map(we => ({ name: we.name, id: we.getId() }))), StorageScope.WORKSPACE);
		} else {
			this.storageService.remove(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE);
		}
E
Erich Gamma 已提交
1132 1133
	}

1134
	//---- telemetry
A
Andre Weinand 已提交
1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158

	private telemetryDebugSessionStart(root: IWorkspaceFolder, type: string, extension: IExtensionDescription): TPromise<any> {
		/* __GDPR__
			"debugSessionStart" : {
				"type": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
				"breakpointCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
				"exceptionBreakpoints": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
				"watchExpressionsCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
				"extensionName": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" },
				"isBuiltin": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true},
				"launchJsonExists": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
			}
		*/
		return this.telemetryService.publicLog('debugSessionStart', {
			type: type,
			breakpointCount: this.model.getBreakpoints().length,
			exceptionBreakpoints: this.model.getExceptionBreakpoints(),
			watchExpressionsCount: this.model.getWatchExpressions().length,
			extensionName: extension.id,
			isBuiltin: extension.isBuiltin,
			launchJsonExists: root && !!this.configurationService.getValue<IGlobalConfig>('launch', { resource: root.uri })
		});
	}

A
Andre Weinand 已提交
1159
	private telemetryDebugSessionStop(session: IDebugSession, adapterExitEvent: AdapterEndEvent): TPromise<any> {
A
Andre Weinand 已提交
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173

		const breakpoints = this.model.getBreakpoints();

		/* __GDPR__
			"debugSessionStop" : {
				"type" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
				"success": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
				"sessionLengthInSeconds": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
				"breakpointCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
				"watchExpressionsCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
			}
		*/
		return this.telemetryService.publicLog('debugSessionStop', {
			type: session && session.configuration.type,
A
Andre Weinand 已提交
1174 1175
			success: adapterExitEvent.emittedStopped || breakpoints.length === 0,
			sessionLengthInSeconds: adapterExitEvent.sessionLengthInSeconds,
A
Andre Weinand 已提交
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
			breakpointCount: breakpoints.length,
			watchExpressionsCount: this.model.getWatchExpressions().length
		});
	}

	private telemetryDebugMisconfiguration(debugType: string, message: string): TPromise<any> {
		/* __GDPR__
			"debugMisconfiguration" : {
				"type" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
				"error": { "classification": "CallstackOrException", "purpose": "FeatureInsight" }
			}
		*/
		return this.telemetryService.publicLog('debugMisconfiguration', {
			type: debugType,
			error: message
		});
	}
E
Erich Gamma 已提交
1193
}