debugService.ts 38.7 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, EXTENSION_LOG_BROADCAST_CHANNEL, EXTENSION_ATTACH_BROADCAST_CHANNEL, EXTENSION_TERMINATE_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';
E
Erich Gamma 已提交
60 61 62 63

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

64
	private taskService: ITaskService;
E
Erich Gamma 已提交
65
	private state: debug.State;
I
isidor 已提交
66
	private session: session.RawDebugSession;
E
Erich Gamma 已提交
67 68
	private model: model.Model;
	private viewModel: viewmodel.ViewModel;
69
	private configurationManager: ConfigurationManager;
70
	private debugStringEditorInputs: DebugStringEditorInput[];
71
	private telemetryAdapter: AIAdapter;
E
Erich Gamma 已提交
72
	private lastTaskEvent: TaskEvent;
73
	private toDispose: lifecycle.IDisposable[];
74
	private toDisposeOnSessionEnd: 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
	) {
		super();

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

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

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

E
Erich Gamma 已提交
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
		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;
			}));
		}

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

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

	private onBroadcast(broadcast: IBroadcast): void {
143

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

150 151
		if (broadcast.channel === EXTENSION_TERMINATE_BROADCAST_CHANNEL) {
			this.onSessionEnd();
152 153 154
			return;
		}

I
isidor 已提交
155
		// from this point on we require an active session
156 157 158 159 160
		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 已提交
161
		// a plugin logged output, show it inside the REPL
162
		if (broadcast.channel === EXTENSION_LOG_BROADCAST_CHANNEL) {
163 164 165 166 167 168 169 170 171 172 173
			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 已提交
174
			// add output for each argument logged
175 176 177 178
			let simpleVals: any[] = [];
			for (let i = 0; i < args.length; i++) {
				let a = args[i];

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

I
isidor 已提交
184
				// null gets printed as 'null'
185 186 187 188
				else if (a === null) {
					simpleVals.push('null');
				}

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

I
isidor 已提交
192
					// flush any existing simple values logged
193 194 195 196 197
					if (simpleVals.length) {
						this.logToRepl(simpleVals.join(' '), sev);
						simpleVals = [];
					}

I
isidor 已提交
198
					// show object
199 200 201
					this.logToRepl(a, sev);
				}

I
isidor 已提交
202 203
				// string: watch out for % replacement directive
				// string substitution and formatting @ https://developer.chrome.com/devtools/docs/console
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
				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 已提交
226
			// flush simple values
227 228 229 230
			if (simpleVals.length) {
				this.logToRepl(simpleVals.join(' '), sev);
			}
		}
E
Erich Gamma 已提交
231 232 233
	}

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

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

247 248
			this.getThreadData(threadId).done(() => {
				let thread = this.model.getThreads()[threadId];
E
Erich Gamma 已提交
249

250 251 252 253 254
				this.model.rawUpdate({
					threadId: threadId,
					stoppedDetails: event.body,
					allThreadsStopped: event.body.allThreadsStopped
				});
255

256 257
				thread.getCallStack(this).then(callStack => {
					this.windowService.getWindow().focus();
E
Erich Gamma 已提交
258
					if (callStack.length > 0) {
259
						// focus first stack frame from top that has source location
I
isidor 已提交
260
						const stackFrameToFocus = arrays.first(callStack, sf => sf.source && sf.source.available, callStack[0]);
261 262 263 264
						this.setFocusedStackFrameAndEvaluate(stackFrameToFocus);
						aria.alert(nls.localize('debuggingPaused', "Debugging paused, reason {0}, {1} {2}", event.body.reason, stackFrameToFocus.source ? stackFrameToFocus.source.name : '', stackFrameToFocus.lineNumber));

						return this.openOrRevealEditor(stackFrameToFocus.source, stackFrameToFocus.lineNumber, false, false);
E
Erich Gamma 已提交
265 266 267 268 269 270 271
					} else {
						this.setFocusedStackFrameAndEvaluate(null);
					}
				});
			}, errors.onUnexpectedError);
		}));

272
		this.toDisposeOnSessionEnd.push(this.session.addListener2(debug.SessionEvents.CONTINUED, () => {
273
			aria.status(nls.localize('debuggingContinued', "Debugging continued."));
274
			this.model.continueThreads();
E
Erich Gamma 已提交
275
			this.setFocusedStackFrameAndEvaluate(null);
I
isidor 已提交
276
			this.setStateAndEmit(this.configurationManager.getConfiguration().noDebug ? debug.State.RunningNoDebug : debug.State.Running);
E
Erich Gamma 已提交
277 278
		}));

279
		this.toDisposeOnSessionEnd.push(this.session.addListener2(debug.SessionEvents.THREAD, (event: DebugProtocol.ThreadEvent) => {
E
Erich Gamma 已提交
280 281
			if (event.body.reason === 'started') {
				this.session.threads().done((result) => {
I
isidor 已提交
282 283
					const thread = result.body.threads.filter(thread => thread.id === event.body.threadId).pop();
					if (thread) {
E
Erich Gamma 已提交
284
						this.model.rawUpdate({
I
isidor 已提交
285 286
							threadId: thread.id,
							thread: thread
E
Erich Gamma 已提交
287 288 289 290 291 292 293 294
						});
					}
				}, errors.onUnexpectedError);
			} else if (event.body.reason === 'exited') {
				this.model.clearThreads(true, event.body.threadId);
			}
		}));

295
		this.toDisposeOnSessionEnd.push(this.session.addListener2(debug.SessionEvents.DEBUGEE_TERMINATED, (event: DebugProtocol.TerminatedEvent) => {
296
			aria.status(nls.localize('debuggingStopped', "Debugging stopped."));
I
isidor 已提交
297
			if (this.session && this.session.getId() === (<any>event).sessionId) {
298
				if (event.body && typeof event.body.restart === 'boolean' && event.body.restart) {
299
					this.restartSession().done(null, err => this.messageService.show(severity.Error, err.message));
300 301 302
				} else {
					this.session.disconnect().done(null, errors.onUnexpectedError);
				}
E
Erich Gamma 已提交
303 304 305
			}
		}));

306
		this.toDisposeOnSessionEnd.push(this.session.addListener2(debug.SessionEvents.OUTPUT, (event: DebugProtocol.OutputEvent) => {
307
			if (event.body && event.body.category === 'telemetry') {
308
				// only log telemetry events from debug adapter if the adapter provided the telemetry key
309 310
				if (this.telemetryAdapter) {
					this.telemetryAdapter.log(event.body.output, event.body.data);
311
				}
312
			} else if (event.body && typeof event.body.output === 'string' && event.body.output.length > 0) {
E
Erich Gamma 已提交
313 314 315 316
				this.onOutput(event);
			}
		}));

317
		this.toDisposeOnSessionEnd.push(this.session.addListener2(debug.SessionEvents.BREAKPOINT, (event: DebugProtocol.BreakpointEvent) => {
I
isidor 已提交
318
			const id = event.body && event.body.breakpoint ? event.body.breakpoint.id : undefined;
319
			const breakpoint = this.model.getBreakpoints().filter(bp => bp.idFromAdapter === id).pop();
I
isidor 已提交
320 321 322
			if (breakpoint) {
				this.model.updateBreakpoints({ [breakpoint.getId()]: event.body.breakpoint });
			} else {
323
				const functionBreakpoint = this.model.getFunctionBreakpoints().filter(bp => bp.idFromAdapter === id).pop();
I
isidor 已提交
324 325 326 327 328 329
				if (functionBreakpoint) {
					this.model.updateFunctionBreakpoints({ [functionBreakpoint.getId()]: event.body.breakpoint });
				}
			}
		}));

330
		this.toDisposeOnSessionEnd.push(this.session.addListener2(debug.SessionEvents.SERVER_EXIT, event => {
331 332 333 334
			// '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);
			}
335 336 337
			if (this.session && this.session.getId() === event.sessionId) {
				this.onSessionEnd();
			}
E
Erich Gamma 已提交
338 339 340 341
		}));
	}

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

I
isidor 已提交
346 347
	private getThreadData(threadId: number): TPromise<void> {
		return this.model.getThreads()[threadId] ? TPromise.as(undefined) :
E
Erich Gamma 已提交
348
			this.session.threads().then((response: DebugProtocol.ThreadsResponse) => {
I
isidor 已提交
349 350
				const thread = response.body.threads.filter(t => t.id === threadId).pop();
				if (!thread) {
I
isidor 已提交
351
					throw new Error(nls.localize('debugNoThread', "Did not get a thread from debug adapter with id {0}.", threadId));
E
Erich Gamma 已提交
352 353 354
				}

				this.model.rawUpdate({
I
isidor 已提交
355 356
					threadId: thread.id,
					thread: thread
E
Erich Gamma 已提交
357 358 359 360 361 362 363
				});
			});
	}

	private loadBreakpoints(): debug.IBreakpoint[] {
		try {
			return JSON.parse(this.storageService.get(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((breakpoint: any) => {
364
				return new model.Breakpoint(new Source(breakpoint.source.raw ? breakpoint.source.raw : { path: uri.parse(breakpoint.source.uri).fsPath, name: breakpoint.source.name }),
365
					breakpoint.desiredLineNumber || breakpoint.lineNumber, breakpoint.enabled, breakpoint.condition);
E
Erich Gamma 已提交
366 367 368 369 370 371
			});
		} catch (e) {
			return [];
		}
	}

I
isidor 已提交
372 373 374
	private loadFunctionBreakpoints(): debug.IFunctionBreakpoint[] {
		try {
			return JSON.parse(this.storageService.get(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((fb: any) => {
375
				return new model.FunctionBreakpoint(fb.name, fb.enabled);
I
isidor 已提交
376 377 378 379 380 381
			});
		} catch (e) {
			return [];
		}
	}

E
Erich Gamma 已提交
382
	private loadExceptionBreakpoints(): debug.IExceptionBreakpoint[] {
I
isidor 已提交
383
		let result: debug.IExceptionBreakpoint[] = null;
E
Erich Gamma 已提交
384 385
		try {
			result = JSON.parse(this.storageService.get(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((exBreakpoint: any) => {
386
				return new model.ExceptionBreakpoint(exBreakpoint.filter || exBreakpoint.name, exBreakpoint.label, exBreakpoint.enabled);
E
Erich Gamma 已提交
387 388 389 390 391
			});
		} catch (e) {
			result = [];
		}

392
		return result;
E
Erich Gamma 已提交
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
	}

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

409
	private setStateAndEmit(newState: debug.State): void {
E
Erich Gamma 已提交
410
		this.state = newState;
411
		this.emit(debug.ServiceEvents.STATE_CHANGED);
E
Erich Gamma 已提交
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
	}

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

427
	public setBreakpointsForModel(modelUri: uri, rawData: debug.IRawBreakpoint[]): void {
428 429 430
		this.model.removeBreakpoints(
			this.model.getBreakpoints().filter(bp => bp.source.uri.toString() === modelUri.toString()));
		this.model.addBreakpoints(rawData);
E
Erich Gamma 已提交
431 432
	}

I
isidor 已提交
433
	public toggleBreakpoint(rawBreakpoint: debug.IRawBreakpoint): TPromise<void> {
434
		const breakpoint = this.model.getBreakpoints().filter(bp => bp.lineNumber === rawBreakpoint.lineNumber && bp.source.uri.toString() === rawBreakpoint.uri.toString()).pop();
435
		if (breakpoint) {
436
			this.model.removeBreakpoints([breakpoint]);
437
		} else {
438
			this.model.addBreakpoints([rawBreakpoint]);
439 440
		}

441
		return this.sendBreakpoints(rawBreakpoint.uri);
E
Erich Gamma 已提交
442 443
	}

I
isidor 已提交
444
	public enableOrDisableAllBreakpoints(enabled: boolean): TPromise<void>{
E
Erich Gamma 已提交
445 446 447 448
		this.model.enableOrDisableAllBreakpoints(enabled);
		return this.sendAllBreakpoints();
	}

I
isidor 已提交
449
	public toggleEnablement(element: debug.IEnablement): TPromise<void> {
E
Erich Gamma 已提交
450 451
		this.model.toggleEnablement(element);
		if (element instanceof model.Breakpoint) {
I
isidor 已提交
452
			const breakpoint = <model.Breakpoint> element;
E
Erich Gamma 已提交
453
			return this.sendBreakpoints(breakpoint.source.uri);
454
		} else if (element instanceof model.FunctionBreakpoint) {
I
isidor 已提交
455
			return this.sendFunctionBreakpoints();
E
Erich Gamma 已提交
456 457 458 459 460
		}

		return this.sendExceptionBreakpoints();
	}

I
isidor 已提交
461
	public removeAllBreakpoints(): TPromise<any> {
462 463
		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 已提交
464

I
isidor 已提交
465
		return TPromise.join(urisToClear.map(uri => this.sendBreakpoints(uri)));
E
Erich Gamma 已提交
466 467
	}

I
isidor 已提交
468
	public toggleBreakpointsActivated(): TPromise<void> {
E
Erich Gamma 已提交
469 470 471 472
		this.model.toggleBreakpointsActivated();
		return this.sendAllBreakpoints();
	}

I
isidor 已提交
473
	public editBreakpoint(editor: editorbrowser.ICodeEditor, lineNumber: number): TPromise<void> {
474 475
		if (BreakpointWidget.INSTANCE) {
			BreakpointWidget.INSTANCE.dispose();
476
		}
477 478 479

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

I
isidor 已提交
481
		return TPromise.as(null);
482 483
	}

I
isidor 已提交
484 485
	public addFunctionBreakpoint(): void {
		this.model.addFunctionBreakpoint('');
486 487
	}

I
isidor 已提交
488
	public renameFunctionBreakpoint(id: string, newFunctionName: string): TPromise<void> {
I
isidor 已提交
489
		this.model.updateFunctionBreakpoints({ [id]: { name: newFunctionName } });
I
isidor 已提交
490
		return this.sendFunctionBreakpoints();
I
isidor 已提交
491 492
	}

I
isidor 已提交
493
	public removeFunctionBreakpoints(id?: string): TPromise<void> {
494
		this.model.removeFunctionBreakpoints(id);
I
isidor 已提交
495
		return this.sendFunctionBreakpoints();
I
isidor 已提交
496 497
	}

I
isidor 已提交
498
	public addReplExpression(name: string): TPromise<void> {
P
Pierson Lee 已提交
499
		this.telemetryService.publicLog('debugService/addReplExpression');
E
Erich Gamma 已提交
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
		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 已提交
517
	public addWatchExpression(name: string): TPromise<void> {
E
Erich Gamma 已提交
518 519 520
		return this.model.addWatchExpression(this.session, this.viewModel.getFocusedStackFrame(), name);
	}

I
isidor 已提交
521
	public renameWatchExpression(id: string, newName: string): TPromise<void> {
E
Erich Gamma 已提交
522 523 524 525 526 527 528
		return this.model.renameWatchExpression(this.session, this.viewModel.getFocusedStackFrame(), id, newName);
	}

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

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

532 533 534 535
		return this.textFileService.saveAll()
		.then(() => this.extensionService.onReady()
		.then(() => this.setConfiguration(this.configurationManager.getConfigurationName())
		.then(() => {
536 537 538
			const configuration = this.configurationManager.getConfiguration();
			if (!configuration) {
				return this.configurationManager.openConfigFile(false).then(openend => {
539
					if (openend) {
I
isidor 已提交
540
						this.messageService.show(severity.Info, nls.localize('NewLaunchConfig', "Please set up the launch configuration file for your application."));
541 542
					}
				});
E
Erich Gamma 已提交
543
			}
544

545
			configuration.noDebug = noDebug;
I
isidor 已提交
546
			if (!this.configurationManager.getAdapter()) {
547
				this.emit(debug.ServiceEvents.TYPE_NOT_SUPPORTED, configuration.type);
548 549 550
				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 已提交
551 552
			}

I
isidor 已提交
553
			return this.runPreLaunchTask(configuration.preLaunchTask).then((taskSummary: ITaskSummary) => {
554
				const errorCount = configuration.preLaunchTask ? this.markerService.getStatistics().errors : 0;
I
isidor 已提交
555 556
				const failureExitCode = taskSummary && taskSummary.exitCode !== undefined && taskSummary.exitCode !== 0;
				if (errorCount === 0 && !failureExitCode) {
I
isidor 已提交
557
					return this.doCreateSession(configuration, changeViewState);
558
				}
I
isidor 已提交
559 560

				this.messageService.show(severity.Error, {
I
isidor 已提交
561 562
					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 已提交
563
						nls.localize('preLaunchTaskExitCode', "The preLaunchTask '{0}' terminated with exit code {1}.", configuration.preLaunchTask, taskSummary.exitCode),
I
isidor 已提交
564
					actions: [CloseAction, new Action('debug.continue', nls.localize('continue', "Continue"), null, true, () => {
I
isidor 已提交
565
						this.messageService.hideAll();
I
isidor 已提交
566
						return this.doCreateSession(configuration, changeViewState);
I
isidor 已提交
567 568
					})]
				});
569 570
			}, (err: TaskError) => {
				if (err.code !== TaskErrors.NotConfigured) {
571
					throw err;
572 573 574 575 576 577
				}

				this.messageService.show(err.severity, {
					message: err.message,
					actions: [CloseAction, this.taskService.configureAction()]
				});
578
			});
I
isidor 已提交
579
		})));
I
isidor 已提交
580
	}
E
Erich Gamma 已提交
581

I
isidor 已提交
582
	private doCreateSession(configuration: debug.IConfig, changeViewState: boolean): TPromise<any> {
583
		this.setStateAndEmit(debug.State.Initializing);
584 585 586 587 588 589 590 591 592
		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 已提交
593 594 595 596
		this.registerSessionListeners();

		return this.session.initialize({
			adapterID: configuration.type,
597
			pathFormat: 'path',
I
isidor 已提交
598
			linesStartAt1: true,
599
			columnsStartAt1: true
I
isidor 已提交
600
		}).then((result: DebugProtocol.InitializeResponse) => {
601
			if (!this.session) {
I
isidor 已提交
602
				return TPromise.wrapError(new Error(nls.localize('debugAdapterCrash', "Debug adapter process has terminated unexpectedly")));
603 604
			}

605
			this.model.setExceptionBreakpoints(this.session.capabilities.exceptionBreakpointFilters);
I
isidor 已提交
606 607
			return configuration.request === 'attach' ? this.session.attach(configuration) : this.session.launch(configuration);
		}).then((result: DebugProtocol.Response) => {
I
isidor 已提交
608
			if (changeViewState) {
I
isidor 已提交
609
				this.viewletService.openViewlet(debug.VIEWLET_ID);
I
isidor 已提交
610
				this.revealRepl(false).done(undefined, errors.onUnexpectedError);
I
isidor 已提交
611 612 613 614
			}
			this.partService.addClass('debugging');
			this.contextService.updateOptions('editor', {
				glyphMargin: true
E
Erich Gamma 已提交
615
			});
I
isidor 已提交
616 617
			this.inDebugMode.set(true);

P
Pierson Lee 已提交
618
			this.telemetryService.publicLog('debugSessionStart', { type: configuration.type, breakpointCount: this.model.getBreakpoints().length, exceptionBreakpoints: this.model.getExceptionBreakpoints(), watchExpressionsCount: this.model.getWatchExpressions().length });
619
		}).then(undefined, (error: any) => {
I
isidor 已提交
620
			this.telemetryService.publicLog('debugMisconfiguration', { type: configuration ? configuration.type : undefined });
I
isidor 已提交
621
			this.setStateAndEmit(debug.State.Inactive);
I
isidor 已提交
622 623 624 625
			if (this.session) {
				this.session.disconnect();
			}

I
isidor 已提交
626 627
			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];
628
			return TPromise.wrapError(errors.create(error.message, { actions }));
E
Erich Gamma 已提交
629 630 631
		});
	}

I
isidor 已提交
632
	private runPreLaunchTask(taskName: string): TPromise<ITaskSummary> {
633
		if (!taskName) {
I
isidor 已提交
634
			return TPromise.as(null);
E
Erich Gamma 已提交
635 636
		}

637
		// run a task before starting a debug session
E
Erich Gamma 已提交
638
		return this.taskService.tasks().then(descriptions => {
639
			const filteredTasks = descriptions.filter(task => task.name === taskName);
E
Erich Gamma 已提交
640
			if (filteredTasks.length !== 1) {
641 642 643 644 645 646 647
				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 已提交
648 649
			}

I
isidor 已提交
650
			// task is already running - nothing to do.
651
			if (this.lastTaskEvent && this.lastTaskEvent.taskName === taskName) {
I
isidor 已提交
652
				return TPromise.as(null);
E
Erich Gamma 已提交
653 654 655
			}

			if (this.lastTaskEvent) {
I
isidor 已提交
656
				// there is a different task running currently.
I
isidor 已提交
657
				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 已提交
658 659
			}

I
isidor 已提交
660
			// no task running, execute the preLaunchTask.
661
			const taskPromise = this.taskService.run(filteredTasks[0].id).then(result => {
E
Erich Gamma 已提交
662
				this.lastTaskEvent = null;
I
isidor 已提交
663
				return result;
E
Erich Gamma 已提交
664 665 666
			}, err => {
				this.lastTaskEvent = null;
			});
667

668
			if (filteredTasks[0].isWatching) {
I
isidor 已提交
669
				return new TPromise((c, e) => this.taskService.addOneTimeListener(TaskServiceEvents.Inactive, () => c(null)));
670 671 672
			}

			return taskPromise;
E
Erich Gamma 已提交
673 674 675
		});
	}

I
isidor 已提交
676
	private rawAttach(port: number): TPromise<any> {
I
isidor 已提交
677
		if (this.session) {
678 679 680 681 682
			if (!this.session.isAttach) {
				return this.session.attach({ port });
			}

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

685
		const configuration = this.configurationManager.getConfiguration();
I
isidor 已提交
686
		this.setStateAndEmit(debug.State.Initializing);
I
isidor 已提交
687
		return this.doCreateSession({
688
			type: configuration.type,
I
isidor 已提交
689
			request: 'attach',
690 691
			port,
			sourceMaps: configuration.sourceMaps,
692 693
			outDir: configuration.outDir,
			debugServer: configuration.debugServer
694
		}, false);
I
isidor 已提交
695 696
	}

I
isidor 已提交
697
	public restartSession(): TPromise<any> {
I
isidor 已提交
698
		return this.session ? this.session.disconnect(true).then(() =>
699
			new TPromise<void>((c, e) => {
E
Erich Gamma 已提交
700
				setTimeout(() => {
I
isidor 已提交
701
					this.createSession(false, false).then(() => c(null), err => e(err));
E
Erich Gamma 已提交
702
				}, 300);
I
isidor 已提交
703
			})
I
isidor 已提交
704
		) : this.createSession(false, false);
E
Erich Gamma 已提交
705 706 707 708 709 710 711 712
	}

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

	private onSessionEnd(): void {
		try {
J
Joao Moreno 已提交
713
			this.debugStringEditorInputs = lifecycle.dispose(this.debugStringEditorInputs);
E
Erich Gamma 已提交
714
		} catch (e) {
I
isidor 已提交
715
			// an internal module might be open so the dispose can throw -> ignore and continue with stop session.
E
Erich Gamma 已提交
716 717 718
		}

		if (this.session) {
I
isidor 已提交
719
			const bpsExist = this.model.getBreakpoints().length > 0;
720
			this.session.dispose();
I
isidor 已提交
721 722 723 724 725 726 727
			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
			});
E
Erich Gamma 已提交
728
		}
729

E
Erich Gamma 已提交
730
		this.session = null;
J
Joao Moreno 已提交
731
		this.toDisposeOnSessionEnd = lifecycle.dispose(this.toDisposeOnSessionEnd);
E
Erich Gamma 已提交
732 733 734
		this.partService.removeClass('debugging');
		this.editorService.focusEditor();

735 736 737 738
		this.model.clearThreads(true);
		this.setFocusedStackFrameAndEvaluate(null);
		this.setStateAndEmit(debug.State.Inactive);

I
isidor 已提交
739
		// set breakpoints back to unverified since the session ended.
740
		// source reference changes across sessions, so we do not use it to persist the source.
741
		const data: {[id: string]: { line: number, verified: boolean } } = { };
742 743 744 745
		this.model.getBreakpoints().forEach(bp => {
			delete bp.source.raw.sourceReference;
			data[bp.getId()] = { line: bp.lineNumber, verified: false };
		});
746 747
		this.model.updateBreakpoints(data);

748 749 750 751
		if (this.telemetryAdapter) {
			this.telemetryAdapter.dispose();
			this.telemetryAdapter = null;
		}
E
Erich Gamma 已提交
752 753 754 755 756 757 758 759 760 761 762
		this.inDebugMode.reset();
	}

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

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

I
isidor 已提交
763
	public openOrRevealEditor(source: Source, lineNumber: number, preserveFocus: boolean, sideBySide: boolean): TPromise<any> {
E
Erich Gamma 已提交
764
		const visibleEditors = this.editorService.getVisibleEditors();
I
isidor 已提交
765
		for (let i = 0; i < visibleEditors.length; i++) {
766
			const fileInput = wbeditorcommon.asFileEditorInput(visibleEditors[i].input);
767 768 769
			if ((fileInput && fileInput.getResource().toString() === source.uri.toString()) ||
				(visibleEditors[i].input instanceof DebugStringEditorInput && (<DebugStringEditorInput>visibleEditors[i].input).getResource().toString() === source.uri.toString())) {

770 771 772 773 774
				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 已提交
775
				}
776

A
Alex Dima 已提交
777
				return TPromise.as(null);
E
Erich Gamma 已提交
778 779 780 781
			}
		}

		if (source.inMemory) {
I
isidor 已提交
782
			// internal module
E
Erich Gamma 已提交
783
			if (source.reference !== 0 && this.session) {
784
				return this.session.source({ sourceReference: source.reference }).then(response => {
E
Erich Gamma 已提交
785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816
					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 已提交
817
	private sourceIsUnavailable(source: Source, sideBySide: boolean): TPromise<any> {
E
Erich Gamma 已提交
818
		this.model.sourceIsUnavailable(source);
819
		const editorInput = this.getDebugStringEditorInput(source, nls.localize('debugSourceNotAvailable', "Source {0} is not available.", source.uri.fsPath), 'text/plain');
E
Erich Gamma 已提交
820 821 822 823

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

824 825
	public revealRepl(focus = true): TPromise<void> {
		return this.panelService.openPanel(debug.REPL_ID, focus).then((repl: Repl) => {
E
Erich Gamma 已提交
826
			const elements = this.model.getReplElements();
827
			if (elements.length > 0) {
I
isidor 已提交
828
				return repl.reveal(elements[elements.length - 1]);
E
Erich Gamma 已提交
829 830 831 832
			}
		});
	}

I
isidor 已提交
833 834
	public canSetBreakpointsIn(model: editor.IModel): boolean {
		return this.configurationManager.canSetBreakpointsIn(model);
835 836
	}

837 838
	public getConfigurationName(): string {
		return this.configurationManager.getConfigurationName();
839 840
	}

I
isidor 已提交
841
	public setConfiguration(name: string): TPromise<void> {
842
		return this.configurationManager.setConfiguration(name).then(() => this.emit(debug.ServiceEvents.CONFIGURATION_CHANGED));
843 844 845 846 847 848 849 850 851 852
	}

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

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

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

		if (filtered.length === 0) {
857
			const result = this.instantiationService.createInstance(DebugStringEditorInput, source.name, source.uri, source.origin, value, mtype, void 0);
E
Erich Gamma 已提交
858 859 860 861 862 863 864
			this.debugStringEditorInputs.push(result);
			return result;
		} else {
			return filtered[0];
		}
	}

I
isidor 已提交
865
	public sendAllBreakpoints(): TPromise<any> {
I
isidor 已提交
866 867 868 869
		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 已提交
870 871
	}

I
isidor 已提交
872
	private sendBreakpoints(modelUri: uri): TPromise<void> {
873
		if (!this.session || !this.session.readyForBreakpoints) {
I
isidor 已提交
874
			return TPromise.as(null);
875 876
		}

877 878
		const breakpointsToSend = arrays.distinct(
			this.model.getBreakpoints().filter(bp => this.model.areBreakpointsActivated() && bp.enabled && bp.source.uri.toString() === modelUri.toString()),
879
			bp => `${ bp.desiredLineNumber }`
880
		);
I
isidor 已提交
881
		const rawSource = breakpointsToSend.length > 0 ? breakpointsToSend[0].source.raw : Source.toRawSource(modelUri, this.model);
882

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

886
			const data: {[id: string]: { line?: number, verified: boolean } } = { };
887 888 889 890 891
			for (let i = 0; i < breakpointsToSend.length; i++) {
				data[breakpointsToSend[i].getId()] = response.body.breakpoints[i];
			}

			this.model.updateBreakpoints(data);
E
Erich Gamma 已提交
892 893 894
		});
	}

I
isidor 已提交
895
	private sendFunctionBreakpoints(): TPromise<void> {
I
isidor 已提交
896
		if (!this.session || !this.session.readyForBreakpoints || !this.session.capabilities.supportsFunctionBreakpoints) {
I
isidor 已提交
897 898 899
			return TPromise.as(null);
		}

I
isidor 已提交
900
		const breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated());
I
isidor 已提交
901 902 903 904 905 906 907
		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 已提交
908 909 910
		});
	}

I
isidor 已提交
911
	private sendExceptionBreakpoints(): TPromise<any> {
912
		if (!this.session || !this.session.readyForBreakpoints || this.model.getExceptionBreakpoints().length === 0) {
I
isidor 已提交
913
			return TPromise.as(null);
I
isidor 已提交
914
		}
I
isidor 已提交
915

I
isidor 已提交
916
		const enabledExceptionBps = this.model.getExceptionBreakpoints().filter(exb => exb.enabled);
917
		return this.session.setExceptionBreakpoints({ filters: enabledExceptionBps.map(exb => exb.filter) });
E
Erich Gamma 已提交
918 919 920
	}

	private onFileChanges(fileChangesEvent: FileChangesEvent): void {
921 922
		this.model.removeBreakpoints(this.model.getBreakpoints().filter(bp =>
			fileChangesEvent.contains(bp.source.uri, FileChangeType.DELETED)));
E
Erich Gamma 已提交
923 924 925 926 927
	}

	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);
928
		this.storageService.store(DEBUG_FUNCTION_BREAKPOINTS_KEY, JSON.stringify(this.model.getFunctionBreakpoints()), StorageScope.WORKSPACE);
E
Erich Gamma 已提交
929
		this.storageService.store(DEBUG_EXCEPTION_BREAKPOINTS_KEY, JSON.stringify(this.model.getExceptionBreakpoints()), StorageScope.WORKSPACE);
930
		this.storageService.store(DEBUG_SELECTED_CONFIG_NAME_KEY, this.configurationManager.getConfigurationName(), StorageScope.WORKSPACE);
E
Erich Gamma 已提交
931 932 933 934 935
		this.storageService.store(DEBUG_WATCH_EXPRESSIONS_KEY, JSON.stringify(this.model.getWatchExpressions()), StorageScope.WORKSPACE);
	}

	public dispose(): void {
		if (this.session) {
I
isidor 已提交
936
			this.session.disconnect();
E
Erich Gamma 已提交
937 938 939
			this.session = null;
		}
		this.model.dispose();
J
Joao Moreno 已提交
940 941
		this.toDispose = lifecycle.dispose(this.toDispose);
		this.toDisposeOnSessionEnd = lifecycle.dispose(this.toDisposeOnSessionEnd);
E
Erich Gamma 已提交
942 943
	}
}