debugService.ts 48.6 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';
I
isidor 已提交
19
import { IExtensionService } 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';
25
import { DebugModel, 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';
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, IDebugModel, 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

59 60 61 62 63 64 65 66 67 68 69 70
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;
	};
}

I
isidor 已提交
71 72 73 74 75
const enum TaskRunResult {
	Failure,
	Success
}

I
isidor 已提交
76 77
export class DebugService implements IDebugService {
	_serviceBrand: any;
E
Erich Gamma 已提交
78

I
isidor 已提交
79
	private readonly _onDidChangeState: Emitter<State>;
80 81 82
	private readonly _onDidNewSession: Emitter<IDebugSession>;
	private readonly _onWillNewSession: Emitter<IDebugSession>;
	private readonly _onDidEndSession: Emitter<IDebugSession>;
83
	private model: DebugModel;
I
isidor 已提交
84
	private viewModel: ViewModel;
85
	private configurationManager: ConfigurationManager;
86
	private allSessions = new Map<string, IDebugSession>();
I
isidor 已提交
87
	private toDispose: IDisposable[];
I
isidor 已提交
88
	private debugType: IContextKey<string>;
I
isidor 已提交
89
	private debugState: IContextKey<string>;
I
isidor 已提交
90
	private inDebugMode: IContextKey<boolean>;
I
isidor 已提交
91
	private breakpointsToSendOnResourceSaved: Set<string>;
I
isidor 已提交
92
	private initializing = false;
I
isidor 已提交
93
	private previousState: State;
E
Erich Gamma 已提交
94 95 96

	constructor(
		@IStorageService private storageService: IStorageService,
97
		@IEditorService private editorService: IEditorService,
98 99
		@ITextFileService private textFileService: ITextFileService,
		@IViewletService private viewletService: IViewletService,
I
isidor 已提交
100
		@IPanelService private panelService: IPanelService,
101
		@INotificationService private notificationService: INotificationService,
102
		@IDialogService private dialogService: IDialogService,
E
Erich Gamma 已提交
103
		@IPartService private partService: IPartService,
104 105
		@IWindowService private windowService: IWindowService,
		@IBroadcastService private broadcastService: IBroadcastService,
E
Erich Gamma 已提交
106 107
		@ITelemetryService private telemetryService: ITelemetryService,
		@IWorkspaceContextService private contextService: IWorkspaceContextService,
108
		@IContextKeyService contextKeyService: IContextKeyService,
109
		@ILifecycleService private lifecycleService: ILifecycleService,
I
isidor 已提交
110
		@IInstantiationService private instantiationService: IInstantiationService,
A
Alex Dima 已提交
111
		@IExtensionService private extensionService: IExtensionService,
112
		@IMarkerService private markerService: IMarkerService,
113
		@ITaskService private taskService: ITaskService,
114
		@IFileService private fileService: IFileService,
I
isidor 已提交
115
		@IConfigurationService private configurationService: IConfigurationService,
E
Erich Gamma 已提交
116 117
	) {
		this.toDispose = [];
118

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

I
isidor 已提交
121
		this._onDidChangeState = new Emitter<State>();
122 123 124
		this._onDidNewSession = new Emitter<IDebugSession>();
		this._onWillNewSession = new Emitter<IDebugSession>();
		this._onDidEndSession = new Emitter<IDebugSession>();
E
Erich Gamma 已提交
125

126
		this.configurationManager = this.instantiationService.createInstance(ConfigurationManager);
127
		this.toDispose.push(this.configurationManager);
128

I
isidor 已提交
129 130 131
		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 已提交
132

133
		this.model = new DebugModel(this.loadBreakpoints(), this.storageService.getBoolean(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE, true), this.loadFunctionBreakpoints(),
134
			this.loadExceptionBreakpoints(), this.loadWatchExpressions(), this.textFileService);
I
isidor 已提交
135
		this.toDispose.push(this.model);
136

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

139
		this.toDispose.push(this.fileService.onFileChanges(e => this.onFileChanges(e)));
140 141
		this.lifecycleService.onShutdown(this.store, this);
		this.lifecycleService.onShutdown(this.dispose, this);
142

143
		this.toDispose.push(this.broadcastService.onBroadcast(broadcast => {
A
Andre Weinand 已提交
144
			const session = this.getSession(broadcast.payload.debugId);
145 146
			if (session) {
				switch (broadcast.channel) {
147

148 149
					case EXTENSION_ATTACH_BROADCAST_CHANNEL:
						// EH was started in debug mode -> attach to it
I
isidor 已提交
150 151 152
						session.configuration.request = 'attach';
						session.configuration.port = broadcast.payload.port;
						this.launchOrAttachToSession(session);
153
						break;
154

155
					case EXTENSION_TERMINATE_BROADCAST_CHANNEL:
A
Andre Weinand 已提交
156 157
						// EH was terminated
						session.disconnect();
158
						break;
159

160 161 162 163
					case EXTENSION_LOG_BROADCAST_CHANNEL:
						// extension logged output -> show it in REPL
						this.addToRepl(session, broadcast.payload.logEntry);
						break;
164 165
				}
			}
166
		}, this));
167

168 169 170 171 172
		this.toDispose.push(this.viewModel.onDidFocusStackFrame(() => {
			this.onStateChange();
		}));
		this.toDispose.push(this.viewModel.onDidFocusSession(session => {
			const id = session ? session.getId() : undefined;
173 174 175
			this.model.setBreakpointsSessionId(id);
			this.onStateChange();
		}));
E
Erich Gamma 已提交
176 177
	}

178
	getSession(sessionId: string): IDebugSession {
A
Andre Weinand 已提交
179 180 181
		return this.allSessions.get(sessionId);
	}

182
	getModel(): IDebugModel {
183
		return this.model;
I
isidor 已提交
184 185
	}

186 187
	getViewModel(): IViewModel {
		return this.viewModel;
E
Erich Gamma 已提交
188 189
	}

190 191
	getConfigurationManager(): IConfigurationManager {
		return this.configurationManager;
I
isidor 已提交
192 193
	}

194 195
	sourceIsNotAvailable(uri: uri): void {
		this.model.sourceIsNotAvailable(uri);
E
Erich Gamma 已提交
196 197
	}

198 199
	dispose(): void {
		this.toDispose = dispose(this.toDispose);
E
Erich Gamma 已提交
200 201
	}

202 203
	//---- state management

I
isidor 已提交
204
	get state(): State {
I
isidor 已提交
205
		const focusedSession = this.viewModel.focusedSession;
I
isidor 已提交
206 207
		if (focusedSession) {
			return focusedSession.state;
I
isidor 已提交
208
		}
209 210 211 212

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

A
Andre Weinand 已提交
213
	private startInitializingState() {
214 215 216 217 218 219
		if (!this.initializing) {
			this.initializing = true;
			this.onStateChange();
		}
	}

A
Andre Weinand 已提交
220
	private endInitializingState() {
I
isidor 已提交
221
		if (this.initializing) {
222 223
			this.initializing = false;
			this.onStateChange();
I
isidor 已提交
224
		}
225
	}
I
isidor 已提交
226

227 228 229 230 231 232 233 234 235 236 237
	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 已提交
238 239
	}

I
isidor 已提交
240
	get onDidChangeState(): Event<State> {
241 242 243
		return this._onDidChangeState.event;
	}

244
	get onDidNewSession(): Event<IDebugSession> {
I
isidor 已提交
245
		return this._onDidNewSession.event;
246 247
	}

248
	get onWillNewSession(): Event<IDebugSession> {
I
isidor 已提交
249 250 251
		return this._onWillNewSession.event;
	}

252
	get onDidEndSession(): Event<IDebugSession> {
I
isidor 已提交
253
		return this._onDidEndSession.event;
I
isidor 已提交
254 255
	}

256
	//---- life cycle management
E
Erich Gamma 已提交
257

A
Andre Weinand 已提交
258 259
	/**
	 * main entry point
I
isidor 已提交
260
	 * properly manages compounds, checks for errors and handles the initializing state.
A
Andre Weinand 已提交
261
	 */
262
	startDebugging(launch: ILaunch, configOrName?: IConfig | string, noDebug = false, unresolvedConfig?: IConfig, ): TPromise<boolean> {
263

264
		this.startInitializingState();
265
		// make sure to save all files and that the configuration is up to date
A
Andre Weinand 已提交
266
		return this.extensionService.activateByEvent('onDebug').then(() =>
I
isidor 已提交
267 268 269
			this.textFileService.saveAll().then(() => this.configurationService.reloadConfiguration(launch ? launch.workspace : undefined).then(() =>
				this.extensionService.whenInstalledExtensionsRegistered().then(() => {

I
isidor 已提交
270
					// If it is the very first start debugging we need to clear the repl and our sessions map
I
isidor 已提交
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
					if (this.model.getSessions().length === 0) {
						this.removeReplExpressions();
						this.allSessions.clear();
					}

					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()))) {
287
							return Promise.reject(new Error(alreadyRunningMessage));
I
isidor 已提交
288
						}
I
isidor 已提交
289
						if (compound && compound.configurations && sessions.some(p => compound.configurations.indexOf(p.getName(false)) !== -1)) {
290
							return Promise.reject(new Error(alreadyRunningMessage));
A
Andre Weinand 已提交
291
						}
I
isidor 已提交
292 293 294 295 296
					} else if (typeof configOrName !== 'string') {
						config = configOrName;
					}

					if (compound) {
I
isidor 已提交
297
						// we are starting a compound debug, first do some error checking and than start each configuration in the compound
I
isidor 已提交
298
						if (!compound.configurations) {
299
							return Promise.reject(new Error(nls.localize({ key: 'compoundMustHaveConfigurations', comment: ['compound indicates a "compounds" configuration item', '"configurations" is an attribute and should not be localized'] },
I
isidor 已提交
300
								"Compound must have \"configurations\" attribute set in order to start multiple configurations.")));
I
isidor 已提交
301 302
						}

I
isidor 已提交
303
						return Promise.all(compound.configurations.map(configData => {
I
isidor 已提交
304 305
							const name = typeof configData === 'string' ? configData : configData.name;
							if (name === compound.name) {
I
isidor 已提交
306
								return Promise.resolve(false);
A
Andre Weinand 已提交
307
							}
I
isidor 已提交
308

I
isidor 已提交
309 310 311 312 313 314 315 316 317
							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 {
318
									return Promise.reject(new Error(launchesContainingName.length === 0 ? nls.localize('noConfigurationNameInWorkspace', "Could not find launch configuration '{0}' in the workspace.", name)
I
isidor 已提交
319
										: nls.localize('multipleConfigurationNamesInWorkspace', "There are multiple launch configurations '{0}' in the workspace. Use folder name to qualify the configuration.", name)));
A
Andre Weinand 已提交
320
								}
I
isidor 已提交
321 322 323 324 325
							} 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 {
326
									return Promise.reject(new Error(nls.localize('noFolderWithName', "Can not find folder with name '{0}' for configuration '{1}' in compound '{2}'.", configData.folder, configData.name, compound.name)));
A
Andre Weinand 已提交
327
								}
I
isidor 已提交
328
							}
I
isidor 已提交
329

330
							return this.createSession(launchForName, launchForName.getConfiguration(name), unresolvedConfig, noDebug);
I
isidor 已提交
331
						})).then(values => values.every(success => !!success)); // Compound launch is a success only if each configuration launched successfully
I
isidor 已提交
332
					}
333

I
isidor 已提交
334 335 336
					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.");
337
						return Promise.reject(new Error(message));
I
isidor 已提交
338 339
					}

340 341
					return this.createSession(launch, config, unresolvedConfig, noDebug);
				})
342
			))).then(success => {
I
isidor 已提交
343
				// make sure to get out of initializing state, and propagate the result
344
				this.endInitializingState();
345
				return success;
346 347
			}, err => {
				this.endInitializingState();
348
				return Promise.reject(err);
349 350
			});
	}
I
isidor 已提交
351

I
isidor 已提交
352 353 354
	/**
	 * gets the debugger for the type, resolves configurations by providers, substitutes variables and runs prelaunch tasks
	 */
355
	private createSession(launch: ILaunch, config: IConfig, unresolvedConfig: IConfig, noDebug: boolean): TPromise<boolean> {
356 357 358 359 360 361 362 363 364 365
		// 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 = Object.create(null);
		}
		unresolvedConfig = unresolvedConfig || deepClone(config);
I
isidor 已提交
366

367 368 369
		if (noDebug) {
			config.noDebug = true;
		}
A
Andre Weinand 已提交
370

I
isidor 已提交
371 372
		const debuggerThenable: Thenable<void> = type ? Promise.resolve(null) : this.configurationManager.guessDebugger().then(dbgr => { type = dbgr && dbgr.type; });
		return debuggerThenable.then(() =>
373 374 375 376
			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.substituteVariables(launch, config).then(resolvedConfig => {
A
Andre Weinand 已提交
377

378 379
						if (!resolvedConfig) {
							// User canceled resolving of interactive variables, silently return
380
							return false;
381
						}
382

383 384 385 386 387
						if (!this.configurationManager.getDebugger(resolvedConfig.type) || (config.request !== 'attach' && config.request !== 'launch')) {
							let message: string;
							if (config.request !== 'attach' && config.request !== 'launch') {
								message = config.request ? nls.localize('debugRequestNotSupported', "Attribute '{0}' has an unsupported value '{1}' in the chosen debug configuration.", 'request', config.request)
									: nls.localize('debugRequesMissing', "Attribute '{0}' is missing from the chosen debug configuration.", 'request');
A
Andre Weinand 已提交
388

389 390 391 392
							} else {
								message = resolvedConfig.type ? nls.localize('debugTypeNotSupported', "Configured debug type '{0}' is not supported.", resolvedConfig.type) :
									nls.localize('debugTypeMissing', "Missing property 'type' for the chosen launch configuration.");
							}
I
isidor 已提交
393

394
							return this.showError(message).then(() => false);
395
						}
396

397 398 399 400 401
						const workspace = launch ? launch.workspace : undefined;
						return this.runTaskAndCheckErrors(workspace, resolvedConfig.preLaunchTask).then(result => {
							if (result === TaskRunResult.Success) {
								return this.doCreateSession(workspace, { resolved: resolvedConfig, unresolved: unresolvedConfig });
							}
402
							return false;
403 404 405
						});
					}, err => {
						if (err && err.message) {
406
							return this.showError(err.message).then(() => false);
407 408
						}
						if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
409 410
							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."))
								.then(() => false);
411
						}
412

413
						return launch && launch.openConfigFile(false, true).then(() => false);
414
					});
415
				}
J
Johannes Rieken 已提交
416

417
				if (launch && type && config === null) {	// show launch.json only for "config" being "null".
418
					return launch.openConfigFile(false, true, type).then(() => false);
419
				}
E
Erich Gamma 已提交
420

421
				return false;
422
			})
423
		);
424
	}
425

I
isidor 已提交
426 427 428
	/**
	 * instantiates the new session, initializes the session, registers session listeners and reports telemetry
	 */
429
	private doCreateSession(root: IWorkspaceFolder, configuration: { resolved: IConfig, unresolved: IConfig }): TPromise<boolean> {
430

431
		const session = this.instantiationService.createInstance(DebugSession, configuration, root, this.model);
A
Andre Weinand 已提交
432
		this.allSessions.set(session.getId(), session);
433

434 435 436 437 438
		// 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 已提交
439
		this._onWillNewSession.fire(session);
A
Andre Weinand 已提交
440

I
isidor 已提交
441
		return this.launchOrAttachToSession(session).then(() => {
A
Andre Weinand 已提交
442

I
isidor 已提交
443 444
			// since the initialized response has arrived announce the new Session (including extensions)
			this._onDidNewSession.fire(session);
A
Andre Weinand 已提交
445

I
isidor 已提交
446 447 448 449
			const internalConsoleOptions = session.configuration.internalConsoleOptions || this.configurationService.getValue<IDebugConfiguration>('debug').internalConsoleOptions;
			if (internalConsoleOptions === 'openOnSessionStart' || (this.viewModel.firstSessionStart && internalConsoleOptions === 'openOnFirstSessionStart')) {
				this.panelService.openPanel(REPL_ID, false);
			}
A
Andre Weinand 已提交
450

I
isidor 已提交
451
			const openDebug = this.configurationService.getValue<IDebugConfiguration>('debug').openDebug;
I
isidor 已提交
452 453
			// Open debug viewlet based on the visibility of the side bar and openDebug setting. Do not open for 'run without debug'
			if (!configuration.resolved.noDebug && (openDebug === 'openOnSessionStart' || (openDebug === 'openOnFirstSessionStart' && this.viewModel.firstSessionStart))) {
I
isidor 已提交
454 455 456
				this.viewletService.openViewlet(VIEWLET_ID);
			}
			this.viewModel.firstSessionStart = false;
A
Andre Weinand 已提交
457

I
isidor 已提交
458 459 460 461
			this.debugType.set(session.configuration.type);
			if (this.model.getSessions().length > 1) {
				this.viewModel.setMultiSessionView(true);
			}
462

I
isidor 已提交
463
			return this.telemetryDebugSessionStart(root, session.configuration.type);
464
		}).then(() => true, (error: Error | string) => {
465

466
			if (errors.isPromiseCanceledError(error)) {
A
Andre Weinand 已提交
467
				// don't show 'canceled' error messages to the user #7906
I
isidor 已提交
468
				return Promise.resolve(undefined);
I
isidor 已提交
469 470 471 472 473
			}

			// Show the repl if some error got logged there #5870
			if (this.model.getReplElements().length > 0) {
				this.panelService.openPanel(REPL_ID, false);
474
			}
I
isidor 已提交
475 476 477

			if (session.configuration && session.configuration.request === 'attach' && session.configuration.__autoAttach) {
				// ignore attach timeouts in auto attach mode
I
isidor 已提交
478
				return Promise.resolve(undefined);
I
isidor 已提交
479
			}
I
isidor 已提交
480 481 482

			const errorMessage = error instanceof Error ? error.message : error;
			this.telemetryDebugMisconfiguration(session.configuration ? session.configuration.type : undefined, errorMessage);
483
			return this.showError(errorMessage, errors.isErrorWithActions(error) ? error.actions : []).then(() => false);
E
Erich Gamma 已提交
484 485 486
		});
	}

I
isidor 已提交
487 488 489 490 491 492 493 494 495 496
	private launchOrAttachToSession(session: IDebugSession, focus = true): TPromise<void> {
		const dbgr = this.configurationManager.getDebugger(session.configuration.type);
		return session.initialize(dbgr).then(() => {
			return session.launchOrAttach(session.configuration).then(() => {
				if (focus) {
					this.focusStackFrame(undefined, undefined, session);
				}
			});
		}).then(undefined, err => {
			session.shutdown();
497
			return Promise.reject(err);
I
isidor 已提交
498 499 500
		});
	}

A
Andre Weinand 已提交
501
	private registerSessionListeners(session: IDebugSession): void {
502

503 504
		this.toDispose.push(session.onDidChangeState(() => {
			if (session.state === State.Running && this.viewModel.focusedSession && this.viewModel.focusedSession.getId() === session.getId()) {
I
isidor 已提交
505 506 507 508
				this.focusStackFrame(undefined);
			}
		}));

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

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

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

A
Andre Weinand 已提交
523
			this.telemetryDebugSessionStop(session, adapterExitEvent);
I
isidor 已提交
524 525

			if (session.configuration.postDebugTask) {
I
isidor 已提交
526
				this.runTask(session.root, session.configuration.postDebugTask).then(undefined, err =>
I
isidor 已提交
527 528 529
					this.notificationService.error(err)
				);
			}
530
			session.shutdown();
I
isidor 已提交
531 532 533 534
			this._onDidEndSession.fire(session);

			const focusedSession = this.viewModel.focusedSession;
			if (focusedSession && focusedSession.getId() === session.getId()) {
535
				this.focusStackFrame(undefined);
I
isidor 已提交
536 537 538 539 540 541 542
			}

			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) {
543
					this.viewletService.openViewlet(EXPLORER_VIEWLET_ID);
I
isidor 已提交
544 545 546 547 548 549
				}
			}

		}));
	}

550
	restartSession(session: IDebugSession, restartData?: any): TPromise<any> {
551 552
		return this.textFileService.saveAll().then(() => {
			// Do not run preLaunch and postDebug tasks for automatic restarts
A
Andre Weinand 已提交
553
			const isAutoRestart = !!restartData;
I
isidor 已提交
554
			const taskThenable: Thenable<TaskRunResult> = isAutoRestart ? Promise.resolve(TaskRunResult.Success) :
I
isidor 已提交
555
				this.runTask(session.root, session.configuration.postDebugTask).then(() => this.runTaskAndCheckErrors(session.root, session.configuration.preLaunchTask));
556

I
isidor 已提交
557
			return taskThenable.then(taskRunResult => {
I
isidor 已提交
558 559 560 561 562 563 564 565 566 567 568 569 570 571
				if (taskRunResult !== TaskRunResult.Success) {
					return;
				}
				if (session.capabilities.supportsRestartRequest) {
					return session.restart().then(() => void 0);
				}

				const shouldFocus = this.viewModel.focusedSession && session.getId() === this.viewModel.focusedSession.getId();
				if (isExtensionHostDebugging(session.configuration) && session.root) {
					return this.broadcastService.broadcast({
						channel: EXTENSION_RELOAD_BROADCAST_CHANNEL,
						payload: [session.root.uri.toString()]
					});
				}
572

I
isidor 已提交
573 574 575
				// If the restart is automatic  -> disconnect, otherwise -> terminate #55064
				return (isAutoRestart ? session.disconnect(true) : session.terminate(true)).then(() => {

I
isidor 已提交
576
					return new Promise<void>((c, e) => {
I
isidor 已提交
577 578 579 580 581 582 583 584 585 586 587 588 589
						setTimeout(() => {
							// Read the configuration again if a launch.json has been changed, if not just use the inmemory configuration
							let needsToSubstitute = false;
							let unresolved: IConfig;
							const launch = session.root ? this.configurationManager.getLaunch(session.root.uri) : undefined;
							if (launch) {
								unresolved = launch.getConfiguration(session.configuration.name);
								if (unresolved && !equals(unresolved, session.unresolvedConfiguration)) {
									// Take the type from the session since the debug extension might overwrite it #21316
									unresolved.type = session.configuration.type;
									unresolved.noDebug = session.configuration.noDebug;
									needsToSubstitute = true;
								}
590
							}
I
isidor 已提交
591

592 593 594 595 596
							let substitutionThenable: Thenable<IConfig> = Promise.resolve(session.configuration);
							if (needsToSubstitute) {
								substitutionThenable = this.configurationManager.resolveConfigurationByProviders(launch.workspace ? launch.workspace.uri : undefined, unresolved.type, unresolved)
									.then(resolved => this.substituteVariables(launch, resolved));
							}
I
isidor 已提交
597
							substitutionThenable.then(resolved => {
I
isidor 已提交
598 599 600
								session.setConfiguration({ resolved, unresolved });
								session.configuration.__restart = restartData;

601 602 603 604
								this.launchOrAttachToSession(session, shouldFocus).then(() => {
									this._onDidNewSession.fire(session);
									c(null);
								}, err => e(err));
I
isidor 已提交
605 606 607
							});
						}, 300);
					});
608 609 610 611 612
				});
			});
		});
	}

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

615
		if (session) {
A
Andre Weinand 已提交
616
			return session.terminate();
617 618 619
		}

		const sessions = this.model.getSessions();
I
isidor 已提交
620
		return Promise.all(sessions.map(s => s.terminate()));
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
	}

	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
			});
		}
I
isidor 已提交
642
		return Promise.resolve(config);
643 644
	}

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

653
			return void 0;
I
isidor 已提交
654 655 656
		});
	}

657 658
	//---- task management

I
isidor 已提交
659
	private runTaskAndCheckErrors(root: IWorkspaceFolder, taskId: string | TaskIdentifier): TPromise<TaskRunResult> {
660

I
isidor 已提交
661
		const debugAnywayAction = new Action('debug.debugAnyway', nls.localize('debugAnyway', "Debug Anyway"), undefined, true, () => Promise.resolve(TaskRunResult.Success));
I
isidor 已提交
662
		return this.runTask(root, taskId).then((taskSummary: ITaskSummary) => {
I
isidor 已提交
663
			const errorCount = taskId ? this.markerService.getStatistics().errors : 0;
664 665 666
			const successExitCode = taskSummary && taskSummary.exitCode === 0;
			const failureExitCode = taskSummary && taskSummary.exitCode !== undefined && taskSummary.exitCode !== 0;
			if (successExitCode || (errorCount === 0 && !failureExitCode)) {
I
isidor 已提交
667
				return <any>TaskRunResult.Success;
668 669
			}

I
isidor 已提交
670
			const taskLabel = typeof taskId === 'string' ? taskId : taskId.name;
671
			const message = errorCount > 1
I
isidor 已提交
672
				? nls.localize('preLaunchTaskErrors', "Build errors have been detected during preLaunchTask '{0}'.", taskLabel)
673
				: errorCount === 1
I
isidor 已提交
674 675
					? nls.localize('preLaunchTaskError', "Build error has been detected during preLaunchTask '{0}'.", taskLabel)
					: nls.localize('preLaunchTaskExitCode', "The preLaunchTask '{0}' terminated with exit code {1}.", taskLabel, taskSummary.exitCode);
676 677

			const showErrorsAction = new Action('debug.showErrors', nls.localize('showErrors', "Show Errors"), undefined, true, () => {
I
isidor 已提交
678
				return this.panelService.openPanel(Constants.MARKERS_PANEL_ID).then(() => TaskRunResult.Failure);
679 680
			});

I
isidor 已提交
681
			return this.showError(message, [debugAnywayAction, showErrorsAction]);
682
		}, (err: TaskError) => {
I
isidor 已提交
683
			return this.showError(err.message, [debugAnywayAction, this.taskService.configureAction()]);
684 685 686
		});
	}

I
isidor 已提交
687
	private runTask(root: IWorkspaceFolder, taskId: string | TaskIdentifier): TPromise<ITaskSummary> {
I
isidor 已提交
688
		if (!taskId) {
I
isidor 已提交
689
			return Promise.resolve(null);
690
		}
I
isidor 已提交
691
		if (!root) {
692
			return Promise.reject(new Error(nls.localize('invalidTaskReference', "Task '{0}' can not be referenced from a launch configuration that is in a different workspace folder.", typeof taskId === 'string' ? taskId : taskId.type)));
I
isidor 已提交
693
		}
694 695 696 697 698 699
		// 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.");
700
				return Promise.reject(errors.create(errorMessage));
701 702 703 704 705 706 707
			}

			// 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.
I
isidor 已提交
708
					return Promise.resolve(null);
709
				}
710 711 712
				once(TaskEventKind.Active, this.taskService.onDidStateChange)((taskEvent) => {
					taskStarted = true;
				});
713 714
				const taskPromise = this.taskService.run(task);
				if (task.isBackground) {
I
isidor 已提交
715
					return new Promise((c, e) => once(TaskEventKind.Inactive, this.taskService.onDidStateChange)(() => {
716 717 718
						taskStarted = true;
						c(null);
					}));
719 720 721 722 723
				}

				return taskPromise;
			});

I
isidor 已提交
724
			return new Promise((c, e) => {
725 726 727 728 729 730 731 732 733
				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.")
734
							: nls.localize('taskNotTracked', "The task '{0}' cannot be tracked.", JSON.stringify(taskId));
735 736 737 738 739 740 741 742 743 744 745 746
						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())) {
I
isidor 已提交
747
			return Promise.resolve(null);
748 749 750 751 752
		}

		// 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) {
I
isidor 已提交
753
			return Promise.resolve(null);
754 755 756 757 758 759 760 761 762 763 764 765 766 767
		}

		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);
	}

768
	focusStackFrame(stackFrame: IStackFrame, thread?: IThread, session?: IDebugSession, explicit?: boolean): void {
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
		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();
	}

809
	private addToRepl(session: IDebugSession, extensionOutput: IRemoteConsoleLog) {
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826

		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 已提交
827
		}
828 829 830 831 832 833 834 835 836

		// 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 已提交
837 838
			}

839 840 841
			// null gets printed as 'null'
			else if (a === null) {
				simpleVals.push('null');
842
			}
843 844 845 846 847 848 849 850

			// 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 已提交
851
				}
E
Erich Gamma 已提交
852

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

857 858 859 860
			// string: watch out for % replacement directive
			// string substitution and formatting @ https://developer.chrome.com/devtools/docs/console
			else if (typeof a === 'string') {
				let buf = '';
861

862 863 864 865 866 867 868
				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];
869
					}
870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885
				}

				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 已提交
886 887
	}

888 889 890 891 892 893 894 895 896 897
	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 已提交
898 899
	}

900
	//---- watches
901

902 903 904 905
	addWatchExpression(name: string): void {
		const we = this.model.addWatchExpression(name);
		this.viewModel.setSelectedExpression(we);
	}
906

907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
	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 已提交
928 929
			}

930 931
			return this.sendExceptionBreakpoints();
		}
932

933 934 935
		this.model.enableOrDisableAllBreakpoints(enable);
		return this.sendAllBreakpoints();
	}
936

937 938 939 940 941
	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 已提交
942 943
	}

944 945 946 947 948 949
	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);
950
		}
951
	}
952

953 954 955 956
	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);
957

958 959
		this.model.removeBreakpoints(toRemove);

I
isidor 已提交
960
		return Promise.all(urisToClear.map(uri => this.sendBreakpoints(uri)));
961 962
	}

963 964 965
	setBreakpointsActivated(activated: boolean): TPromise<void> {
		this.model.setBreakpointsActivated(activated);
		return this.sendAllBreakpoints();
E
Erich Gamma 已提交
966 967
	}

968 969 970
	addFunctionBreakpoint(name?: string, id?: string): void {
		const newFunctionBreakpoint = this.model.addFunctionBreakpoint(name || '', id);
		this.viewModel.setSelectedFunctionBreakpoint(newFunctionBreakpoint);
E
Erich Gamma 已提交
971 972
	}

973 974 975 976 977 978 979 980
	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();
981 982
	}

983
	sendAllBreakpoints(session?: IDebugSession): TPromise<any> {
I
isidor 已提交
984
		return Promise.all(distinct(this.model.getBreakpoints(), bp => bp.uri.toString()).map(bp => this.sendBreakpoints(bp.uri, false, session)))
I
isidor 已提交
985
			.then(() => this.sendFunctionBreakpoints(session))
I
isidor 已提交
986
			// send exception breakpoints at the end since some debug adapters rely on the order
I
isidor 已提交
987
			.then(() => this.sendExceptionBreakpoints(session));
E
Erich Gamma 已提交
988 989
	}

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

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

A
Andre Weinand 已提交
994 995 996 997
		return this.sendToOneOrAllSessions(session, s => {
			return s.sendBreakpoints(modelUri, breakpointsToSend, sourceModified).then(data => {
				if (data) {
					this.model.setBreakpointSessionData(s.getId(), data);
I
isidor 已提交
998 999
				}
			});
A
Andre Weinand 已提交
1000
		});
E
Erich Gamma 已提交
1001 1002
	}

1003
	private sendFunctionBreakpoints(session?: IDebugSession): TPromise<void> {
1004

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

A
Andre Weinand 已提交
1007
		return this.sendToOneOrAllSessions(session, s => {
1008
			return s.capabilities.supportsFunctionBreakpoints ? s.sendFunctionBreakpoints(breakpointsToSend).then(data => {
A
Andre Weinand 已提交
1009 1010
				if (data) {
					this.model.setBreakpointSessionData(s.getId(), data);
I
isidor 已提交
1011
				}
I
isidor 已提交
1012
			}) : Promise.resolve(undefined);
A
Andre Weinand 已提交
1013
		});
I
isidor 已提交
1014 1015
	}

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

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

A
Andre Weinand 已提交
1020 1021 1022
		return this.sendToOneOrAllSessions(session, s => {
			return s.sendExceptionBreakpoints(enabledExceptionBps);
		});
I
isidor 已提交
1023 1024
	}

1025
	private sendToOneOrAllSessions(session: IDebugSession, send: (session: IDebugSession) => TPromise<void>): TPromise<void> {
I
isidor 已提交
1026 1027
		if (session) {
			return send(session);
I
isidor 已提交
1028
		}
I
isidor 已提交
1029
		return Promise.all(this.model.getSessions().map(s => send(s))).then(() => void 0);
E
Erich Gamma 已提交
1030 1031 1032
	}

	private onFileChanges(fileChangesEvent: FileChangesEvent): void {
I
isidor 已提交
1033 1034 1035 1036 1037
		const toRemove = this.model.getBreakpoints().filter(bp =>
			fileChangesEvent.contains(bp.uri, FileChangeType.DELETED));
		if (toRemove.length) {
			this.model.removeBreakpoints(toRemove);
		}
1038 1039

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

1041
			if (this.breakpointsToSendOnResourceSaved.delete(event.resource.toString())) {
1042
				this.sendBreakpoints(event.resource, true);
1043 1044
			}
		});
E
Erich Gamma 已提交
1045 1046
	}

1047 1048 1049 1050 1051 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
	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 已提交
1091
	private store(): void {
1092 1093 1094 1095 1096 1097 1098 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
		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 已提交
1125 1126
	}

1127
	//---- telemetry
A
Andre Weinand 已提交
1128

I
isidor 已提交
1129 1130
	private telemetryDebugSessionStart(root: IWorkspaceFolder, type: string): TPromise<any> {
		const extension = this.configurationManager.getDebugger(type).extensionDescription;
A
Andre Weinand 已提交
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
		/* __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 已提交
1153
	private telemetryDebugSessionStop(session: IDebugSession, adapterExitEvent: AdapterEndEvent): TPromise<any> {
A
Andre Weinand 已提交
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167

		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 已提交
1168 1169
			success: adapterExitEvent.emittedStopped || breakpoints.length === 0,
			sessionLengthInSeconds: adapterExitEvent.sessionLengthInSeconds,
A
Andre Weinand 已提交
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
			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 已提交
1187
}