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

import nls = require('vs/nls');
import lifecycle = require('vs/base/common/lifecycle');
import mime = require('vs/base/common/mime');
import ee = require('vs/base/common/eventEmitter');
import uri from 'vs/base/common/uri';
11
import { Action } from 'vs/base/common/actions';
E
Erich Gamma 已提交
12
import arrays = require('vs/base/common/arrays');
13
import types = require('vs/base/common/types');
E
Erich Gamma 已提交
14 15
import errors = require('vs/base/common/errors');
import severity from 'vs/base/common/severity';
I
isidor 已提交
16
import { TPromise } from 'vs/base/common/winjs.base';
E
Erich Gamma 已提交
17
import editor = require('vs/editor/common/editorCommon');
I
isidor 已提交
18
import aria = require('vs/base/browser/ui/aria/aria');
19
import { AIAdapter } from 'vs/base/node/aiAdapter';
E
Erich Gamma 已提交
20
import editorbrowser = require('vs/editor/browser/editorBrowser');
21 22 23
import { IKeybindingService, IKeybindingContextKey } from 'vs/platform/keybinding/common/keybindingService';
import {IMarkerService} from 'vs/platform/markers/common/markers';
import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle';
A
Alex Dima 已提交
24
import { IExtensionService } from 'vs/platform/extensions/common/extensions';
25 26 27 28 29 30
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IFileService, FileChangesEvent, FileChangeType, EventType } from 'vs/platform/files/common/files';
import { IEventService } from 'vs/platform/event/common/event';
import { IMessageService, CloseAction } from 'vs/platform/message/common/message';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
E
Erich Gamma 已提交
31 32 33 34
import wbeditorcommon = require('vs/workbench/common/editor');
import debug = require('vs/workbench/parts/debug/common/debug');
import session = require('vs/workbench/parts/debug/node/rawDebugSession');
import model = require('vs/workbench/parts/debug/common/debugModel');
35
import { DebugStringEditorInput } from 'vs/workbench/parts/debug/browser/debugEditorInputs';
E
Erich Gamma 已提交
36
import viewmodel = require('vs/workbench/parts/debug/common/debugViewModel');
37
import debugactions = require('vs/workbench/parts/debug/electron-browser/debugActions');
I
isidor 已提交
38
import { Repl } from 'vs/workbench/parts/debug/browser/repl';
I
isidor 已提交
39
import { BreakpointWidget } from 'vs/workbench/parts/debug/browser/breakpointWidget';
40
import { ConfigurationManager } from 'vs/workbench/parts/debug/node/debugConfigurationManager';
I
isidor 已提交
41
import { Source } from 'vs/workbench/parts/debug/common/debugSource';
42 43
import { ITaskService, TaskEvent, TaskType, TaskServiceEvents, ITaskSummary} from 'vs/workbench/parts/tasks/common/taskService';
import { TaskError, TaskErrors } from 'vs/workbench/parts/tasks/common/taskSystem';
E
Erich Gamma 已提交
44
import { IViewletService } from 'vs/workbench/services/viewlet/common/viewletService';
I
isidor 已提交
45
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';
E
Erich Gamma 已提交
46
import { IPartService } from 'vs/workbench/services/part/common/partService';
47
import { ITextFileService } from 'vs/workbench/parts/files/common/files';
E
Erich Gamma 已提交
48 49
import { IWorkspaceContextService } from 'vs/workbench/services/workspace/common/contextService';
import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService';
50
import { IWindowService, IBroadcast } from 'vs/workbench/services/window/electron-browser/windowService';
51
import { ILogEntry, PLUGIN_LOG_BROADCAST_CHANNEL, PLUGIN_ATTACH_BROADCAST_CHANNEL } from 'vs/workbench/services/thread/electron-browser/threadService';
52
import { ipcRenderer as ipc } from 'electron';
E
Erich Gamma 已提交
53

I
isidor 已提交
54 55 56 57 58 59
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';
const DEBUG_SELECTED_CONFIG_NAME_KEY = 'debug.selectedconfigname';
60
const HIDE_REPL_TIMEOUT = 1000;
E
Erich Gamma 已提交
61 62 63 64

export class DebugService extends ee.EventEmitter implements debug.IDebugService {
	public serviceId = debug.IDebugService;

65
	private taskService: ITaskService;
E
Erich Gamma 已提交
66
	private state: debug.State;
I
isidor 已提交
67
	private session: session.RawDebugSession;
E
Erich Gamma 已提交
68 69
	private model: model.Model;
	private viewModel: viewmodel.ViewModel;
70
	private configurationManager: ConfigurationManager;
71
	private debugStringEditorInputs: DebugStringEditorInput[];
72
	private telemetryAdapter: AIAdapter;
E
Erich Gamma 已提交
73
	private lastTaskEvent: TaskEvent;
74
	private toDispose: lifecycle.IDisposable[];
E
Erich Gamma 已提交
75 76 77 78 79
	private inDebugMode: IKeybindingContextKey<boolean>;

	constructor(
		@IStorageService private storageService: IStorageService,
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
80 81
		@ITextFileService private textFileService: ITextFileService,
		@IViewletService private viewletService: IViewletService,
I
isidor 已提交
82
		@IPanelService private panelService: IPanelService,
E
Erich Gamma 已提交
83 84 85 86 87 88
		@IFileService private fileService: IFileService,
		@IMessageService private messageService: IMessageService,
		@IPartService private partService: IPartService,
		@IWindowService private windowService: IWindowService,
		@ITelemetryService private telemetryService: ITelemetryService,
		@IWorkspaceContextService private contextService: IWorkspaceContextService,
89 90
		@IKeybindingService keybindingService: IKeybindingService,
		@IEventService eventService: IEventService,
E
Erich Gamma 已提交
91 92
		@ILifecycleService private lifecycleService: ILifecycleService,
		@IInstantiationService private instantiationService:IInstantiationService,
A
Alex Dima 已提交
93
		@IExtensionService private extensionService: IExtensionService,
94
		@IMarkerService private markerService: IMarkerService
E
Erich Gamma 已提交
95 96 97 98 99 100 101
	) {
		super();

		this.toDispose = [];
		this.debugStringEditorInputs = [];
		this.session = null;
		this.state = debug.State.Inactive;
I
isidor 已提交
102
		// there is a cycle if taskService gets injected, use a workaround.
103
		this.taskService = this.instantiationService.getInstance(ITaskService);
E
Erich Gamma 已提交
104

105
		if (!this.contextService.getWorkspace()) {
E
Erich Gamma 已提交
106 107
			this.state = debug.State.Disabled;
		}
108
		this.configurationManager = this.instantiationService.createInstance(ConfigurationManager, this.storageService.get(DEBUG_SELECTED_CONFIG_NAME_KEY, StorageScope.WORKSPACE, 'null'));
E
Erich Gamma 已提交
109 110
		this.inDebugMode = keybindingService.createKey(debug.CONTEXT_IN_DEBUG_MODE, false);

I
isidor 已提交
111
		this.model = new model.Model(this.loadBreakpoints(), this.storageService.getBoolean(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE, true), this.loadFunctionBreakpoints(),
E
Erich Gamma 已提交
112 113
			this.loadExceptionBreakpoints(), this.loadWatchExpressions());
		this.viewModel = new viewmodel.ViewModel();
114

E
Erich Gamma 已提交
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
		this.registerListeners(eventService, lifecycleService);
	}

	private registerListeners(eventService: IEventService, lifecycleService: ILifecycleService): void {
		this.toDispose.push(eventService.addListener2(EventType.FILE_CHANGES, (e: FileChangesEvent) => this.onFileChanges(e)));

		if (this.taskService) {
			this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Active, (e: TaskEvent) => {
				this.lastTaskEvent = e;
			}));
			this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Inactive, (e: TaskEvent) => {
				if (e.type === TaskType.SingleRun) {
					this.lastTaskEvent = null;
				}
			}));
			this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Terminated, (e: TaskEvent) => {
				this.lastTaskEvent = null;
			}));
		}

135 136
		lifecycleService.onShutdown(this.store, this);
		lifecycleService.onShutdown(this.dispose, this);
137

138
		this.windowService.onBroadcast(this.onBroadcast, this);
139 140 141
	}

	private onBroadcast(broadcast: IBroadcast): void {
142

I
isidor 已提交
143
		// attach: PH is ready to be attached to
144
		if (broadcast.channel === PLUGIN_ATTACH_BROADCAST_CHANNEL) {
145
			this.rawAttach(broadcast.payload.port);
146 147 148 149

			return;
		}

I
isidor 已提交
150
		// from this point on we require an active session
151 152 153 154 155
		let session = this.getActiveSession();
		if (!session || session.getType() !== 'extensionHost') {
			return; // we are only intersted if we have an active debug session for extensionHost
		}

I
isidor 已提交
156
		// a plugin logged output, show it inside the REPL
157 158 159 160 161 162 163 164 165 166 167 168
		if (broadcast.channel === PLUGIN_LOG_BROADCAST_CHANNEL) {
			let extensionOutput: ILogEntry = broadcast.payload;
			let sev = extensionOutput.severity === 'warn' ? severity.Warning : extensionOutput.severity === 'error' ? severity.Error : severity.Info;

			let args: any[] = [];
			try {
				let parsed = JSON.parse(extensionOutput.arguments);
				args.push(...Object.getOwnPropertyNames(parsed).map(o => parsed[o]));
			} catch (error) {
				args.push(extensionOutput.arguments);
			}

I
isidor 已提交
169
			// add output for each argument logged
170 171 172 173
			let simpleVals: any[] = [];
			for (let i = 0; i < args.length; i++) {
				let a = args[i];

I
isidor 已提交
174
				// undefined gets printed as 'undefined'
175 176 177 178
				if (typeof a === 'undefined') {
					simpleVals.push('undefined');
				}

I
isidor 已提交
179
				// null gets printed as 'null'
180 181 182 183
				else if (a === null) {
					simpleVals.push('null');
				}

I
isidor 已提交
184
				// objects & arrays are special because we want to inspect them in the REPL
185 186
				else if (types.isObject(a) || Array.isArray(a)) {

I
isidor 已提交
187
					// flush any existing simple values logged
188 189 190 191 192
					if (simpleVals.length) {
						this.logToRepl(simpleVals.join(' '), sev);
						simpleVals = [];
					}

I
isidor 已提交
193
					// show object
194 195 196
					this.logToRepl(a, sev);
				}

I
isidor 已提交
197 198
				// string: watch out for % replacement directive
				// string substitution and formatting @ https://developer.chrome.com/devtools/docs/console
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
				else if (typeof a === 'string') {
					let buf = '';

					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')) {
							i++; // read over substitution
							buf += !types.isUndefinedOrNull(args[i]) ? args[i] : ''; // replace
							j++; // read over directive
						} else {
							buf += a[j];
						}
					}

					simpleVals.push(buf);
				}

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

I
isidor 已提交
221
			// flush simple values
222 223 224 225
			if (simpleVals.length) {
				this.logToRepl(simpleVals.join(' '), sev);
			}
		}
E
Erich Gamma 已提交
226 227 228
	}

	private registerSessionListeners(): void {
I
isidor 已提交
229
		this.toDispose.push(this.session.addListener2(debug.SessionEvents.INITIALIZED, (event: DebugProtocol.InitializedEvent) => {
230
			aria.status(nls.localize('debuggingStarted', "Debugging started."));
I
isidor 已提交
231
			this.sendAllBreakpoints().then(() => {
232
				if (this.session.capabilities.supportsConfigurationDoneRequest) {
I
isidor 已提交
233 234
					this.session.configurationDone().done(null, errors.onUnexpectedError);
				}
I
isidor 已提交
235 236
			});
		}));
E
Erich Gamma 已提交
237 238

		this.toDispose.push(this.session.addListener2(debug.SessionEvents.STOPPED, (event: DebugProtocol.StoppedEvent) => {
239
			this.setStateAndEmit(debug.State.Stopped);
I
isidor 已提交
240
			const threadId = event.body.threadId;
E
Erich Gamma 已提交
241 242 243 244

			this.getThreadData(threadId).then(() => {
				this.session.stackTrace({ threadId: threadId, levels: 20 }).done((result) => {

I
isidor 已提交
245
					this.model.rawUpdate({ threadId: threadId, callStack: result.body.stackFrames, stoppedDetails: event.body });
E
Erich Gamma 已提交
246
					this.windowService.getWindow().focus();
I
isidor 已提交
247
					const callStack = this.model.getThreads()[threadId].callStack;
E
Erich Gamma 已提交
248
					if (callStack.length > 0) {
I
isidor 已提交
249
						aria.alert(nls.localize('debuggingPaused', "Debugging paused, reason {0}, {1} {2}", event.body.reason, callStack[0].source.name, callStack[0].lineNumber));
E
Erich Gamma 已提交
250 251 252 253 254 255 256 257 258 259
						this.setFocusedStackFrameAndEvaluate(callStack[0]);
						this.openOrRevealEditor(callStack[0].source, callStack[0].lineNumber, false, false).done(null, errors.onUnexpectedError);
					} else {
						this.setFocusedStackFrameAndEvaluate(null);
					}
				});
			}, errors.onUnexpectedError);
		}));

		this.toDispose.push(this.session.addListener2(debug.SessionEvents.CONTINUED, () => {
260
			aria.status(nls.localize('debuggingContinued', "Debugging continued."));
E
Erich Gamma 已提交
261 262
			this.model.clearThreads(false);
			this.setFocusedStackFrameAndEvaluate(null);
I
isidor 已提交
263
			this.setStateAndEmit(this.configurationManager.getConfiguration().noDebug ? debug.State.RunningNoDebug : debug.State.Running);
E
Erich Gamma 已提交
264 265 266 267 268
		}));

		this.toDispose.push(this.session.addListener2(debug.SessionEvents.THREAD, (event: DebugProtocol.ThreadEvent) => {
			if (event.body.reason === 'started') {
				this.session.threads().done((result) => {
I
isidor 已提交
269 270
					const thread = result.body.threads.filter(thread => thread.id === event.body.threadId).pop();
					if (thread) {
E
Erich Gamma 已提交
271
						this.model.rawUpdate({
I
isidor 已提交
272 273
							threadId: thread.id,
							thread: thread
E
Erich Gamma 已提交
274 275 276 277 278 279 280 281 282
						});
					}
				}, errors.onUnexpectedError);
			} else if (event.body.reason === 'exited') {
				this.model.clearThreads(true, event.body.threadId);
			}
		}));

		this.toDispose.push(this.session.addListener2(debug.SessionEvents.DEBUGEE_TERMINATED, (event: DebugProtocol.TerminatedEvent) => {
283
			aria.status(nls.localize('debuggingStopped', "Debugging stopped."));
I
isidor 已提交
284
			if (this.session && this.session.getId() === (<any>event).sessionId) {
285
				if (event.body && typeof event.body.restart === 'boolean' && event.body.restart) {
286
					this.restartSession().done(null, err => this.messageService.show(severity.Error, err.message));
287 288 289
				} else {
					this.session.disconnect().done(null, errors.onUnexpectedError);
				}
E
Erich Gamma 已提交
290 291 292 293
			}
		}));

		this.toDispose.push(this.session.addListener2(debug.SessionEvents.OUTPUT, (event: DebugProtocol.OutputEvent) => {
294
			if (event.body && event.body.category === 'telemetry') {
295
				// only log telemetry events from debug adapter if the adapter provided the telemetry key
296 297
				if (this.telemetryAdapter) {
					this.telemetryAdapter.log(event.body.output, event.body.data);
298
				}
299
			} else if (event.body && typeof event.body.output === 'string' && event.body.output.length > 0) {
E
Erich Gamma 已提交
300 301 302 303
				this.onOutput(event);
			}
		}));

I
isidor 已提交
304 305
		this.toDispose.push(this.session.addListener2(debug.SessionEvents.BREAKPOINT, (event: DebugProtocol.BreakpointEvent) => {
			const id = event.body && event.body.breakpoint ? event.body.breakpoint.id : undefined;
306
			const breakpoint = this.model.getBreakpoints().filter(bp => bp.idFromAdapter === id).pop();
I
isidor 已提交
307 308 309
			if (breakpoint) {
				this.model.updateBreakpoints({ [breakpoint.getId()]: event.body.breakpoint });
			} else {
310
				const functionBreakpoint = this.model.getFunctionBreakpoints().filter(bp => bp.idFromAdapter === id).pop();
I
isidor 已提交
311 312 313 314 315 316
				if (functionBreakpoint) {
					this.model.updateFunctionBreakpoints({ [functionBreakpoint.getId()]: event.body.breakpoint });
				}
			}
		}));

317
		this.toDispose.push(this.session.addListener2(debug.SessionEvents.SERVER_EXIT, event => {
318 319 320 321
			// 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905
			if (this.session.getType() === 'extensionHost' && this.state === debug.State.RunningNoDebug) {
				ipc.send('vscode:closeExtensionHostWindow', this.contextService.getWorkspace().resource.fsPath);
			}
322 323 324
			if (this.session && this.session.getId() === event.sessionId) {
				this.onSessionEnd();
			}
E
Erich Gamma 已提交
325 326 327 328
		}));
	}

	private onOutput(event: DebugProtocol.OutputEvent): void {
329
		const outputSeverity = event.body.category === 'stderr' ? severity.Error : event.body.category === 'console' ? severity.Warning : severity.Info;
E
Erich Gamma 已提交
330 331 332
		this.appendReplOutput(event.body.output, outputSeverity);
	}

I
isidor 已提交
333 334
	private getThreadData(threadId: number): TPromise<void> {
		return this.model.getThreads()[threadId] ? TPromise.as(undefined) :
E
Erich Gamma 已提交
335
			this.session.threads().then((response: DebugProtocol.ThreadsResponse) => {
I
isidor 已提交
336 337
				const thread = response.body.threads.filter(t => t.id === threadId).pop();
				if (!thread) {
I
isidor 已提交
338
					throw new Error(nls.localize('debugNoThread', "Did not get a thread from debug adapter with id {0}.", threadId));
E
Erich Gamma 已提交
339 340 341
				}

				this.model.rawUpdate({
I
isidor 已提交
342 343
					threadId: thread.id,
					thread: thread
E
Erich Gamma 已提交
344 345 346 347 348 349 350
				});
			});
	}

	private loadBreakpoints(): debug.IBreakpoint[] {
		try {
			return JSON.parse(this.storageService.get(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((breakpoint: any) => {
351
				return new model.Breakpoint(new Source(breakpoint.source.raw ? breakpoint.source.raw : { path: uri.parse(breakpoint.source.uri).fsPath, name: breakpoint.source.name }),
352
					breakpoint.desiredLineNumber || breakpoint.lineNumber, breakpoint.enabled, breakpoint.condition);
E
Erich Gamma 已提交
353 354 355 356 357 358
			});
		} catch (e) {
			return [];
		}
	}

I
isidor 已提交
359 360 361
	private loadFunctionBreakpoints(): debug.IFunctionBreakpoint[] {
		try {
			return JSON.parse(this.storageService.get(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((fb: any) => {
362
				return new model.FunctionBreakpoint(fb.name, fb.enabled);
I
isidor 已提交
363 364 365 366 367 368
			});
		} catch (e) {
			return [];
		}
	}

E
Erich Gamma 已提交
369
	private loadExceptionBreakpoints(): debug.IExceptionBreakpoint[] {
I
isidor 已提交
370
		let result: debug.IExceptionBreakpoint[] = null;
E
Erich Gamma 已提交
371 372
		try {
			result = JSON.parse(this.storageService.get(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((exBreakpoint: any) => {
373
				return new model.ExceptionBreakpoint(exBreakpoint.filter || exBreakpoint.name, exBreakpoint.label, exBreakpoint.enabled);
E
Erich Gamma 已提交
374 375 376 377 378
			});
		} catch (e) {
			result = [];
		}

379
		return result;
E
Erich Gamma 已提交
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
	}

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

	public getState(): debug.State {
		return this.state;
	}

396
	private setStateAndEmit(newState: debug.State): void {
E
Erich Gamma 已提交
397
		this.state = newState;
398
		this.emit(debug.ServiceEvents.STATE_CHANGED);
E
Erich Gamma 已提交
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
	}

	public get enabled(): boolean {
		return !!this.contextService.getWorkspace();
	}

	public setFocusedStackFrameAndEvaluate(focusedStackFrame: debug.IStackFrame): void {
		this.viewModel.setFocusedStackFrame(focusedStackFrame);
		if (focusedStackFrame) {
			this.model.evaluateWatchExpressions(this.session, focusedStackFrame);
		} else {
			this.model.clearWatchExpressionValues();
		}
	}

414
	public setBreakpointsForModel(modelUri: uri, rawData: debug.IRawBreakpoint[]): void {
415 416 417
		this.model.removeBreakpoints(
			this.model.getBreakpoints().filter(bp => bp.source.uri.toString() === modelUri.toString()));
		this.model.addBreakpoints(rawData);
E
Erich Gamma 已提交
418 419
	}

I
isidor 已提交
420
	public toggleBreakpoint(rawBreakpoint: debug.IRawBreakpoint): TPromise<void> {
421
		const breakpoint = this.model.getBreakpoints().filter(bp => bp.lineNumber === rawBreakpoint.lineNumber && bp.source.uri.toString() === rawBreakpoint.uri.toString()).pop();
422
		if (breakpoint) {
423
			this.model.removeBreakpoints([breakpoint]);
424
		} else {
425
			this.model.addBreakpoints([rawBreakpoint]);
426 427
		}

428
		return this.sendBreakpoints(rawBreakpoint.uri);
E
Erich Gamma 已提交
429 430
	}

I
isidor 已提交
431
	public enableOrDisableAllBreakpoints(enabled: boolean): TPromise<void>{
E
Erich Gamma 已提交
432 433 434 435
		this.model.enableOrDisableAllBreakpoints(enabled);
		return this.sendAllBreakpoints();
	}

I
isidor 已提交
436
	public toggleEnablement(element: debug.IEnablement): TPromise<void> {
E
Erich Gamma 已提交
437 438
		this.model.toggleEnablement(element);
		if (element instanceof model.Breakpoint) {
I
isidor 已提交
439
			const breakpoint = <model.Breakpoint> element;
E
Erich Gamma 已提交
440
			return this.sendBreakpoints(breakpoint.source.uri);
441
		} else if (element instanceof model.FunctionBreakpoint) {
I
isidor 已提交
442
			return this.sendFunctionBreakpoints();
E
Erich Gamma 已提交
443 444 445 446 447
		}

		return this.sendExceptionBreakpoints();
	}

I
isidor 已提交
448
	public removeAllBreakpoints(): TPromise<any> {
449 450
		const urisToClear = arrays.distinct(this.model.getBreakpoints(), bp => bp.source.uri.toString()).map(bp => bp.source.uri);
		this.model.removeBreakpoints(this.model.getBreakpoints());
E
Erich Gamma 已提交
451

I
isidor 已提交
452
		return TPromise.join(urisToClear.map(uri => this.sendBreakpoints(uri)));
E
Erich Gamma 已提交
453 454
	}

I
isidor 已提交
455
	public toggleBreakpointsActivated(): TPromise<void> {
E
Erich Gamma 已提交
456 457 458 459
		this.model.toggleBreakpointsActivated();
		return this.sendAllBreakpoints();
	}

I
isidor 已提交
460
	public editBreakpoint(editor: editorbrowser.ICodeEditor, lineNumber: number): TPromise<void> {
461 462
		if (BreakpointWidget.INSTANCE) {
			BreakpointWidget.INSTANCE.dispose();
463
		}
464 465 466

		this.instantiationService.createInstance(BreakpointWidget, editor, lineNumber);
		BreakpointWidget.INSTANCE.show({ lineNumber, column: 1 }, 2);
I
isidor 已提交
467

I
isidor 已提交
468
		return TPromise.as(null);
469 470
	}

I
isidor 已提交
471 472
	public addFunctionBreakpoint(): void {
		this.model.addFunctionBreakpoint('');
473 474
	}

I
isidor 已提交
475
	public renameFunctionBreakpoint(id: string, newFunctionName: string): TPromise<void> {
I
isidor 已提交
476
		this.model.updateFunctionBreakpoints({ [id]: { name: newFunctionName } });
I
isidor 已提交
477
		return this.sendFunctionBreakpoints();
I
isidor 已提交
478 479
	}

I
isidor 已提交
480
	public removeFunctionBreakpoints(id?: string): TPromise<void> {
481
		this.model.removeFunctionBreakpoints(id);
I
isidor 已提交
482
		return this.sendFunctionBreakpoints();
I
isidor 已提交
483 484
	}

I
isidor 已提交
485
	public addReplExpression(name: string): TPromise<void> {
P
Pierson Lee 已提交
486
		this.telemetryService.publicLog('debugService/addReplExpression');
E
Erich Gamma 已提交
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
		return this.model.addReplExpression(this.session, this.viewModel.getFocusedStackFrame(), name);
	}

	public logToRepl(value: string, severity?: severity): void;
	public logToRepl(value: { [key: string]: any }, severity?: severity): void;
	public logToRepl(value: any, severity?: severity): void {
		this.model.logToRepl(value, severity);
	}

	public appendReplOutput(value: string, severity?: severity): void {
		this.model.appendReplOutput(value, severity);
	}

	public clearReplExpressions(): void {
		this.model.clearReplExpressions();
	}

I
isidor 已提交
504
	public addWatchExpression(name: string): TPromise<void> {
E
Erich Gamma 已提交
505 506 507
		return this.model.addWatchExpression(this.session, this.viewModel.getFocusedStackFrame(), name);
	}

I
isidor 已提交
508
	public renameWatchExpression(id: string, newName: string): TPromise<void> {
E
Erich Gamma 已提交
509 510 511 512 513 514 515
		return this.model.renameWatchExpression(this.session, this.viewModel.getFocusedStackFrame(), id, newName);
	}

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

516
	public createSession(noDebug: boolean, changeViewState = !this.partService.isSideBarHidden()): TPromise<any> {
517
		this.clearReplExpressions();
E
Erich Gamma 已提交
518

A
Alex Dima 已提交
519
		return this.textFileService.saveAll().then(() => this.extensionService.onReady()).then(() => this.configurationManager.setConfiguration(this.configurationManager.getConfigurationName())).then(() => {
520

521 522 523
			const configuration = this.configurationManager.getConfiguration();
			if (!configuration) {
				return this.configurationManager.openConfigFile(false).then(openend => {
524
					if (openend) {
I
isidor 已提交
525
						this.messageService.show(severity.Info, nls.localize('NewLaunchConfig', "Please set up the launch configuration file for your application."));
526 527
					}
				});
E
Erich Gamma 已提交
528
			}
529

530
			configuration.noDebug = noDebug;
I
isidor 已提交
531
			if (!this.configurationManager.getAdapter()) {
532
				this.emit(debug.ServiceEvents.TYPE_NOT_SUPPORTED, configuration.type);
533 534 535
				return configuration.type ? TPromise.wrapError(new Error(nls.localize('debugTypeNotSupported', "Configured debug type '{0}' is not supported.", configuration.type)))
					: TPromise.wrapError(errors.create(nls.localize('debugTypeMissing', "Missing property 'type' for the selected configuration in launch.json."),
						{ actions: [CloseAction, this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL)] }));
E
Erich Gamma 已提交
536 537
			}

I
isidor 已提交
538
			return this.runPreLaunchTask(configuration.preLaunchTask).then((taskSummary: ITaskSummary) => {
539
				const errorCount = configuration.preLaunchTask ? this.markerService.getStatistics().errors : 0;
I
isidor 已提交
540 541
				const failureExitCode = taskSummary && taskSummary.exitCode !== undefined && taskSummary.exitCode !== 0;
				if (errorCount === 0 && !failureExitCode) {
I
isidor 已提交
542
					return this.doCreateSession(configuration, changeViewState);
543
				}
I
isidor 已提交
544 545

				this.messageService.show(severity.Error, {
I
isidor 已提交
546 547
					message: errorCount > 1 ? nls.localize('preLaunchTaskErrors', "Errors detected while running the preLaunchTask '{0}'.", configuration.preLaunchTask) :
						errorCount === 1 ?  nls.localize('preLaunchTaskError', "Error detected while running the preLaunchTask '{0}'.", configuration.preLaunchTask) :
I
isidor 已提交
548
						nls.localize('preLaunchTaskExitCode', "The preLaunchTask '{0}' terminated with exit code {1}.", configuration.preLaunchTask, taskSummary.exitCode),
I
isidor 已提交
549
					actions: [CloseAction, new Action('debug.continue', nls.localize('continue', "Continue"), null, true, () => {
I
isidor 已提交
550
						this.messageService.hideAll();
I
isidor 已提交
551
						return this.doCreateSession(configuration, changeViewState);
I
isidor 已提交
552 553
					})]
				});
554 555
			}, (err: TaskError) => {
				if (err.code !== TaskErrors.NotConfigured) {
556
					throw err;
557 558 559 560 561 562
				}

				this.messageService.show(err.severity, {
					message: err.message,
					actions: [CloseAction, this.taskService.configureAction()]
				});
563
			});
I
isidor 已提交
564 565
		});
	}
E
Erich Gamma 已提交
566

I
isidor 已提交
567
	private doCreateSession(configuration: debug.IConfig, changeViewState: boolean): TPromise<any> {
568 569 570 571 572 573 574 575 576
		const key = this.configurationManager.getAdapter().aiKey;
		const telemetryInfo = Object.create(null);
		this.telemetryService.getTelemetryInfo().then(info => {
			telemetryInfo['common.vscodemachineid'] = info.machineId;
			telemetryInfo['common.vscodesessionid'] = info.sessionId;
		}, errors.onUnexpectedError);
		this.telemetryAdapter = new AIAdapter(key, this.configurationManager.getAdapter().type, null, telemetryInfo);
		this.session = new session.RawDebugSession(this.messageService, this.telemetryService, configuration.debugServer, this.configurationManager.getAdapter(), this.telemetryAdapter);

I
isidor 已提交
577 578 579 580
		this.registerSessionListeners();

		return this.session.initialize({
			adapterID: configuration.type,
581
			pathFormat: 'path',
I
isidor 已提交
582
			linesStartAt1: true,
583
			columnsStartAt1: true
I
isidor 已提交
584
		}).then((result: DebugProtocol.InitializeResponse) => {
585
			if (!this.session) {
I
isidor 已提交
586
				return TPromise.wrapError(new Error(nls.localize('debugAdapterCrash', "Debug adapter process has terminated unexpectedly")));
587 588
			}

I
isidor 已提交
589
			this.setStateAndEmit(debug.State.Initializing);
590
			this.model.setExceptionBreakpoints(this.session.capabilities.exceptionBreakpointFilters);
I
isidor 已提交
591 592
			return configuration.request === 'attach' ? this.session.attach(configuration) : this.session.launch(configuration);
		}).then((result: DebugProtocol.Response) => {
I
isidor 已提交
593
			if (changeViewState) {
I
isidor 已提交
594
				this.viewletService.openViewlet(debug.VIEWLET_ID);
I
isidor 已提交
595
				this.revealRepl(false).done(undefined, errors.onUnexpectedError);
I
isidor 已提交
596 597 598 599
			}
			this.partService.addClass('debugging');
			this.contextService.updateOptions('editor', {
				glyphMargin: true
E
Erich Gamma 已提交
600
			});
I
isidor 已提交
601 602
			this.inDebugMode.set(true);

P
Pierson Lee 已提交
603
			this.telemetryService.publicLog('debugSessionStart', { type: configuration.type, breakpointCount: this.model.getBreakpoints().length, exceptionBreakpoints: this.model.getExceptionBreakpoints(), watchExpressionsCount: this.model.getWatchExpressions().length });
604
		}).then(undefined, (error: any) => {
I
isidor 已提交
605 606 607 608 609
			this.telemetryService.publicLog('debugMisconfiguration', { type: configuration ? configuration.type : undefined });
			if (this.session) {
				this.session.disconnect();
			}

I
isidor 已提交
610 611
			const configureAction = this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL);
			const actions = (error.actions && error.actions.length) ? error.actions.concat([configureAction]) : [CloseAction, configureAction];
612
			return TPromise.wrapError(errors.create(error.message, { actions }));
E
Erich Gamma 已提交
613 614 615
		});
	}

I
isidor 已提交
616
	private runPreLaunchTask(taskName: string): TPromise<ITaskSummary> {
617
		if (!taskName) {
I
isidor 已提交
618
			return TPromise.as(null);
E
Erich Gamma 已提交
619 620
		}

621
		// run a task before starting a debug session
E
Erich Gamma 已提交
622
		return this.taskService.tasks().then(descriptions => {
623
			const filteredTasks = descriptions.filter(task => task.name === taskName);
E
Erich Gamma 已提交
624
			if (filteredTasks.length !== 1) {
625 626 627 628 629 630 631
				return TPromise.wrapError(errors.create(nls.localize('DebugTaskNotFound', "Could not find the preLaunchTask \'{0}\'.", taskName), {
					actions: [
						CloseAction,
						this.taskService.configureAction(),
						this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL)
					]
				}));
E
Erich Gamma 已提交
632 633
			}

I
isidor 已提交
634
			// task is already running - nothing to do.
635
			if (this.lastTaskEvent && this.lastTaskEvent.taskName === taskName) {
I
isidor 已提交
636
				return TPromise.as(null);
E
Erich Gamma 已提交
637 638 639
			}

			if (this.lastTaskEvent) {
I
isidor 已提交
640
				// there is a different task running currently.
I
isidor 已提交
641
				return TPromise.wrapError(errors.create(nls.localize('differentTaskRunning', "There is a task {0} running. Can not run pre launch task {1}.", this.lastTaskEvent.taskName, taskName)));
E
Erich Gamma 已提交
642 643
			}

I
isidor 已提交
644
			// no task running, execute the preLaunchTask.
645
			const taskPromise = this.taskService.run(filteredTasks[0].id).then(result => {
E
Erich Gamma 已提交
646
				this.lastTaskEvent = null;
I
isidor 已提交
647
				return result;
E
Erich Gamma 已提交
648 649 650
			}, err => {
				this.lastTaskEvent = null;
			});
651

652 653
			if (filteredTasks[0].isWatching) {
				return new TPromise((c, e) => {
654
					this.taskService.addOneTimeListener(TaskServiceEvents.Inactive, () => c(taskPromise));
655 656 657 658
				});
			}

			return taskPromise;
E
Erich Gamma 已提交
659 660 661
		});
	}

I
isidor 已提交
662
	private rawAttach(port: number): TPromise<any> {
I
isidor 已提交
663
		if (this.session) {
664 665 666 667 668
			if (!this.session.isAttach) {
				return this.session.attach({ port });
			}

			this.session.disconnect().done(null, errors.onUnexpectedError);
I
isidor 已提交
669 670
		}

671
		const configuration = this.configurationManager.getConfiguration();
I
isidor 已提交
672
		return this.doCreateSession({
673
			type: configuration.type,
I
isidor 已提交
674
			request: 'attach',
675 676
			port,
			sourceMaps: configuration.sourceMaps,
677 678
			outDir: configuration.outDir,
			debugServer: configuration.debugServer
679
		}, false);
I
isidor 已提交
680 681
	}

I
isidor 已提交
682
	public restartSession(): TPromise<any> {
I
isidor 已提交
683
		return this.session ? this.session.disconnect(true).then(() =>
684
			new TPromise<void>((c, e) => {
E
Erich Gamma 已提交
685
				setTimeout(() => {
I
isidor 已提交
686
					this.createSession(false, false).then(() => c(null), err => e(err));
E
Erich Gamma 已提交
687
				}, 300);
I
isidor 已提交
688
			})
I
isidor 已提交
689
		) : this.createSession(false, false);
E
Erich Gamma 已提交
690 691 692 693 694 695 696 697 698 699
	}

	public getActiveSession(): debug.IRawDebugSession {
		return this.session;
	}

	private onSessionEnd(): void {
		try {
			this.debugStringEditorInputs = lifecycle.disposeAll(this.debugStringEditorInputs);
		} catch (e) {
I
isidor 已提交
700
			// an internal module might be open so the dispose can throw -> ignore and continue with stop session.
E
Erich Gamma 已提交
701 702 703
		}

		if (this.session) {
I
isidor 已提交
704
			const bpsExist = this.model.getBreakpoints().length > 0;
P
Pierson Lee 已提交
705
			this.telemetryService.publicLog('debugSessionStop', { type: this.session.getType(), success: this.session.emittedStopped || !bpsExist, sessionLengthInSeconds: this.session.getLengthInSeconds(), breakpointCount: this.model.getBreakpoints().length, watchExpressionsCount: this.model.getWatchExpressions().length });
706 707 708 709 710 711 712
			if (!this.session.restarted) {
				setTimeout(() => {
					const panel = this.panelService.getActivePanel();
					if (panel && panel.getId() === debug.REPL_ID) {
						this.partService.setPanelHidden(true);
					}
				}, HIDE_REPL_TIMEOUT);
713
			}
E
Erich Gamma 已提交
714 715 716 717 718
		}
		this.session = null;
		this.partService.removeClass('debugging');
		this.editorService.focusEditor();

719 720 721 722
		this.model.clearThreads(true);
		this.setFocusedStackFrameAndEvaluate(null);
		this.setStateAndEmit(debug.State.Inactive);

I
isidor 已提交
723
		// set breakpoints back to unverified since the session ended.
724
		// source reference changes across sessions, so we do not use it to persist the source.
725
		const data: {[id: string]: { line: number, verified: boolean } } = { };
726 727 728 729
		this.model.getBreakpoints().forEach(bp => {
			delete bp.source.raw.sourceReference;
			data[bp.getId()] = { line: bp.lineNumber, verified: false };
		});
730 731
		this.model.updateBreakpoints(data);

732 733 734 735
		if (this.telemetryAdapter) {
			this.telemetryAdapter.dispose();
			this.telemetryAdapter = null;
		}
E
Erich Gamma 已提交
736 737 738 739 740 741 742 743 744 745 746
		this.inDebugMode.reset();
	}

	public getModel(): debug.IModel {
		return this.model;
	}

	public getViewModel(): debug.IViewModel {
		return this.viewModel;
	}

I
isidor 已提交
747
	public openOrRevealEditor(source: Source, lineNumber: number, preserveFocus: boolean, sideBySide: boolean): TPromise<any> {
E
Erich Gamma 已提交
748
		const visibleEditors = this.editorService.getVisibleEditors();
I
isidor 已提交
749
		for (let i = 0; i < visibleEditors.length; i++) {
750
			const fileInput = wbeditorcommon.asFileEditorInput(visibleEditors[i].input);
751 752 753
			if ((fileInput && fileInput.getResource().toString() === source.uri.toString()) ||
				(visibleEditors[i].input instanceof DebugStringEditorInput && (<DebugStringEditorInput>visibleEditors[i].input).getResource().toString() === source.uri.toString())) {

754 755 756 757 758
				const control = <editorbrowser.ICodeEditor>visibleEditors[i].getControl();
				if (control) {
					control.revealLineInCenterIfOutsideViewport(lineNumber);
					control.setSelection({ startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 });
					return this.editorService.openEditor(visibleEditors[i].input, wbeditorcommon.TextEditorOptions.create({ preserveFocus: preserveFocus, forceActive: true }), visibleEditors[i].position);
E
Erich Gamma 已提交
759
				}
760

A
Alex Dima 已提交
761
				return TPromise.as(null);
E
Erich Gamma 已提交
762 763 764 765
			}
		}

		if (source.inMemory) {
I
isidor 已提交
766
			// internal module
E
Erich Gamma 已提交
767
			if (source.reference !== 0 && this.session) {
768
				return this.session.source({ sourceReference: source.reference }).then(response => {
E
Erich Gamma 已提交
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
					const editorInput = this.getDebugStringEditorInput(source, response.body.content, mime.guessMimeTypes(source.name)[0]);
					return this.editorService.openEditor(editorInput, wbeditorcommon.TextEditorOptions.create({
						selection: {
							startLineNumber: lineNumber,
							startColumn: 1,
							endLineNumber: lineNumber,
							endColumn: 1
						},
						preserveFocus: preserveFocus
					}), sideBySide);
				});
			}

			return this.sourceIsUnavailable(source, sideBySide);
		}

		return this.fileService.resolveFile(source.uri).then(() =>
			this.editorService.openEditor({
				resource: source.uri,
				options: {
					selection: {
						startLineNumber: lineNumber,
						startColumn: 1,
						endLineNumber: lineNumber,
						endColumn: 1
					},
					preserveFocus: preserveFocus
				}
			}, sideBySide), err => this.sourceIsUnavailable(source, sideBySide)
		);
	}

I
isidor 已提交
801
	private sourceIsUnavailable(source: Source, sideBySide: boolean): TPromise<any> {
E
Erich Gamma 已提交
802
		this.model.sourceIsUnavailable(source);
803
		const editorInput = this.getDebugStringEditorInput(source, nls.localize('debugSourceNotAvailable', "Source {0} is not available.", source.uri.fsPath), 'text/plain');
E
Erich Gamma 已提交
804 805 806 807

		return this.editorService.openEditor(editorInput, wbeditorcommon.TextEditorOptions.create({ preserveFocus: true }), sideBySide);
	}

808 809
	public revealRepl(focus = true): TPromise<void> {
		return this.panelService.openPanel(debug.REPL_ID, focus).then((repl: Repl) => {
E
Erich Gamma 已提交
810
			const elements = this.model.getReplElements();
811
			if (elements.length > 0) {
I
isidor 已提交
812
				return repl.reveal(elements[elements.length - 1]);
E
Erich Gamma 已提交
813 814 815 816
			}
		});
	}

I
isidor 已提交
817 818
	public canSetBreakpointsIn(model: editor.IModel): boolean {
		return this.configurationManager.canSetBreakpointsIn(model);
819 820
	}

821 822
	public getConfigurationName(): string {
		return this.configurationManager.getConfigurationName();
823 824
	}

I
isidor 已提交
825
	public setConfiguration(name: string): TPromise<void> {
826 827 828 829 830 831 832 833 834 835 836
		return this.configurationManager.setConfiguration(name);
	}

	public openConfigFile(sideBySide: boolean): TPromise<boolean> {
		return this.configurationManager.openConfigFile(sideBySide);
	}

	public loadLaunchConfig(): TPromise<debug.IGlobalConfig> {
		return this.configurationManager.loadLaunchConfig();
	}

837
	private getDebugStringEditorInput(source: Source, value: string, mtype: string): DebugStringEditorInput {
I
isidor 已提交
838
		const filtered = this.debugStringEditorInputs.filter(input => input.getResource().toString() === source.uri.toString());
E
Erich Gamma 已提交
839 840

		if (filtered.length === 0) {
841
			const result = this.instantiationService.createInstance(DebugStringEditorInput, source.name, source.uri, source.origin, value, mtype, void 0);
E
Erich Gamma 已提交
842 843 844 845 846 847 848
			this.debugStringEditorInputs.push(result);
			return result;
		} else {
			return filtered[0];
		}
	}

I
isidor 已提交
849
	public sendAllBreakpoints(): TPromise<any> {
I
isidor 已提交
850 851 852 853
		return TPromise.join(arrays.distinct(this.model.getBreakpoints(), bp => bp.source.uri.toString()).map(bp => this.sendBreakpoints(bp.source.uri)))
			.then(() => this.sendFunctionBreakpoints())
			// send exception breakpoints at the end since some debug adapters rely on the order
			.then(() => this.sendExceptionBreakpoints());
E
Erich Gamma 已提交
854 855
	}

I
isidor 已提交
856
	private sendBreakpoints(modelUri: uri): TPromise<void> {
857
		if (!this.session || !this.session.readyForBreakpoints) {
I
isidor 已提交
858
			return TPromise.as(null);
859 860
		}

861 862
		const breakpointsToSend = arrays.distinct(
			this.model.getBreakpoints().filter(bp => this.model.areBreakpointsActivated() && bp.enabled && bp.source.uri.toString() === modelUri.toString()),
863
			bp => `${ bp.desiredLineNumber }`
864
		);
865
		const rawSource = breakpointsToSend.length > 0 ? breakpointsToSend[0].source.raw : Source.toRawSource(modelUri, null);
866

867
		return this.session.setBreakpoints({ source: rawSource, lines: breakpointsToSend.map(bp => bp.desiredLineNumber),
868
			breakpoints: breakpointsToSend.map(bp => ({ line: bp.desiredLineNumber, condition: bp.condition })) }).then(response => {
869

870
			const data: {[id: string]: { line?: number, verified: boolean } } = { };
871 872 873 874 875
			for (let i = 0; i < breakpointsToSend.length; i++) {
				data[breakpointsToSend[i].getId()] = response.body.breakpoints[i];
			}

			this.model.updateBreakpoints(data);
E
Erich Gamma 已提交
876 877 878
		});
	}

I
isidor 已提交
879
	private sendFunctionBreakpoints(): TPromise<void> {
I
isidor 已提交
880
		if (!this.session || !this.session.readyForBreakpoints || !this.session.capabilities.supportsFunctionBreakpoints) {
I
isidor 已提交
881 882 883
			return TPromise.as(null);
		}

I
isidor 已提交
884 885 886 887 888 889 890 891
		const breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled);
		return this.session.setFunctionBreakpoints({ breakpoints: breakpointsToSend }).then(response => {
			const data: {[id: string]: { name?: string, verified?: boolean } } = { };
			for (let i = 0; i < breakpointsToSend.length; i++) {
				data[breakpointsToSend[i].getId()] = response.body.breakpoints[i];
			}

			this.model.updateFunctionBreakpoints(data);
I
isidor 已提交
892 893 894
		});
	}

I
isidor 已提交
895
	private sendExceptionBreakpoints(): TPromise<any> {
896
		if (!this.session || !this.session.readyForBreakpoints || this.model.getExceptionBreakpoints().length === 0) {
I
isidor 已提交
897
			return TPromise.as(null);
I
isidor 已提交
898
		}
I
isidor 已提交
899

I
isidor 已提交
900
		const enabledExceptionBps = this.model.getExceptionBreakpoints().filter(exb => exb.enabled);
901
		return this.session.setExceptionBreakpoints({ filters: enabledExceptionBps.map(exb => exb.filter) });
E
Erich Gamma 已提交
902 903 904
	}

	private onFileChanges(fileChangesEvent: FileChangesEvent): void {
905 906
		this.model.removeBreakpoints(this.model.getBreakpoints().filter(bp =>
			fileChangesEvent.contains(bp.source.uri, FileChangeType.DELETED)));
E
Erich Gamma 已提交
907 908 909 910 911
	}

	private store(): void {
		this.storageService.store(DEBUG_BREAKPOINTS_KEY, JSON.stringify(this.model.getBreakpoints()), StorageScope.WORKSPACE);
		this.storageService.store(DEBUG_BREAKPOINTS_ACTIVATED_KEY, this.model.areBreakpointsActivated() ? 'true' : 'false', StorageScope.WORKSPACE);
912
		this.storageService.store(DEBUG_FUNCTION_BREAKPOINTS_KEY, JSON.stringify(this.model.getFunctionBreakpoints()), StorageScope.WORKSPACE);
E
Erich Gamma 已提交
913
		this.storageService.store(DEBUG_EXCEPTION_BREAKPOINTS_KEY, JSON.stringify(this.model.getExceptionBreakpoints()), StorageScope.WORKSPACE);
914
		this.storageService.store(DEBUG_SELECTED_CONFIG_NAME_KEY, this.configurationManager.getConfigurationName(), StorageScope.WORKSPACE);
E
Erich Gamma 已提交
915 916 917 918 919
		this.storageService.store(DEBUG_WATCH_EXPRESSIONS_KEY, JSON.stringify(this.model.getWatchExpressions()), StorageScope.WORKSPACE);
	}

	public dispose(): void {
		if (this.session) {
I
isidor 已提交
920
			this.session.disconnect();
E
Erich Gamma 已提交
921 922 923 924 925 926
			this.session = null;
		}
		this.model.dispose();
		this.toDispose = lifecycle.disposeAll(this.toDispose);
	}
}