debugService.ts 32.0 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6 7 8 9 10 11
/*---------------------------------------------------------------------------------------------
 *  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';
import arrays = require('vs/base/common/arrays');
12
import types = require('vs/base/common/types');
E
Erich Gamma 已提交
13 14 15 16 17 18 19 20 21 22 23
import errors = require('vs/base/common/errors');
import severity from 'vs/base/common/severity';
import { Promise, TPromise } from 'vs/base/common/winjs.base';
import editor = require('vs/editor/common/editorCommon');
import editorbrowser = require('vs/editor/browser/editorBrowser');
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');
import debuginputs = require('vs/workbench/parts/debug/browser/debugEditorInputs');
import viewmodel = require('vs/workbench/parts/debug/common/debugViewModel');
24
import debugactions = require('vs/workbench/parts/debug/electron-browser/debugActions');
25
import { ConfigurationManager } from 'vs/workbench/parts/debug/node/debugConfigurationManager';
E
Erich Gamma 已提交
26
import { Repl } from 'vs/workbench/parts/debug/browser/replEditor';
I
isidor 已提交
27
import { Source } from 'vs/workbench/parts/debug/common/debugSource';
E
Erich Gamma 已提交
28 29 30 31
import { Position } from 'vs/platform/editor/common/editor';
import { ITaskService , TaskEvent, TaskType, TaskServiceEvents} from 'vs/workbench/parts/tasks/common/taskService';
import { IViewletService } from 'vs/workbench/services/viewlet/common/viewletService';
import { IPartService } from 'vs/workbench/services/part/common/partService';
32
import { ITextFileService } from 'vs/workbench/parts/files/common/files';
E
Erich Gamma 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45
import { IWorkspaceContextService } from 'vs/workbench/services/workspace/common/contextService';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
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';
import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService';
import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle';
import { IPluginService, IPluginDescription } from 'vs/platform/plugins/common/plugins';
import { IOutputService } from 'vs/workbench/parts/output/common/output';
import { IKeybindingService, IKeybindingContextKey } from 'vs/platform/keybinding/common/keybindingService';
46
import { IWindowService, IBroadcast } from 'vs/workbench/services/window/electron-browser/windowService';
47
import { ILogEntry, PLUGIN_LOG_BROADCAST_CHANNEL, PLUGIN_ATTACH_BROADCAST_CHANNEL } from 'vs/workbench/services/thread/electron-browser/threadService';
E
Erich Gamma 已提交
48 49 50

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

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

59
	private taskService: ITaskService;
E
Erich Gamma 已提交
60
	private state: debug.State;
I
isidor 已提交
61
	private session: session.RawDebugSession;
E
Erich Gamma 已提交
62 63
	private model: model.Model;
	private viewModel: viewmodel.ViewModel;
64
	private configurationManager: ConfigurationManager;
E
Erich Gamma 已提交
65 66
	private debugStringEditorInputs: debuginputs.DebugStringEditorInput[];
	private lastTaskEvent: TaskEvent;
67
	private toDispose: lifecycle.IDisposable[];
E
Erich Gamma 已提交
68 69 70 71 72
	private inDebugMode: IKeybindingContextKey<boolean>;

	constructor(
		@IStorageService private storageService: IStorageService,
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
73 74
		@ITextFileService private textFileService: ITextFileService,
		@IViewletService private viewletService: IViewletService,
E
Erich Gamma 已提交
75 76 77 78 79 80
		@IFileService private fileService: IFileService,
		@IMessageService private messageService: IMessageService,
		@IPartService private partService: IPartService,
		@IWindowService private windowService: IWindowService,
		@ITelemetryService private telemetryService: ITelemetryService,
		@IWorkspaceContextService private contextService: IWorkspaceContextService,
81 82
		@IKeybindingService keybindingService: IKeybindingService,
		@IEventService eventService: IEventService,
E
Erich Gamma 已提交
83 84 85
		@ILifecycleService private lifecycleService: ILifecycleService,
		@IInstantiationService private instantiationService:IInstantiationService,
		@IPluginService private pluginService: IPluginService,
86
		@IOutputService private outputService: IOutputService
E
Erich Gamma 已提交
87 88 89 90 91 92 93
	) {
		super();

		this.toDispose = [];
		this.debugStringEditorInputs = [];
		this.session = null;
		this.state = debug.State.Inactive;
94 95
		// There is a cycle if taskService gets injected, use a workaround.
		this.taskService = this.instantiationService.getInstance(ITaskService);
E
Erich Gamma 已提交
96

97
		if (!this.contextService.getWorkspace()) {
E
Erich Gamma 已提交
98 99
			this.state = debug.State.Disabled;
		}
100
		this.configurationManager = this.instantiationService.createInstance(ConfigurationManager, this.storageService.get(DEBUG_SELECTED_CONFIG_NAME_KEY, StorageScope.WORKSPACE, 'null'));
E
Erich Gamma 已提交
101 102
		this.inDebugMode = keybindingService.createKey(debug.CONTEXT_IN_DEBUG_MODE, false);

I
isidor 已提交
103
		this.model = new model.Model(this.loadBreakpoints(), this.storageService.getBoolean(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE, true), this.loadFunctionBreakpoints(),
E
Erich Gamma 已提交
104 105
			this.loadExceptionBreakpoints(), this.loadWatchExpressions());
		this.viewModel = new viewmodel.ViewModel();
106

E
Erich Gamma 已提交
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
		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;
			}));
		}

128 129
		lifecycleService.onShutdown(this.store, this);
		lifecycleService.onShutdown(this.dispose, this);
130

131
		this.windowService.onBroadcast(this.onBroadcast, this);
132 133 134
	}

	private onBroadcast(broadcast: IBroadcast): void {
135 136 137

		// Attach: PH is ready to be attached to
		if (broadcast.channel === PLUGIN_ATTACH_BROADCAST_CHANNEL) {
138
			this.rawAttach(broadcast.payload.port);
139 140 141 142 143

			return;
		}

		// From this point on we require an active session
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
		let session = this.getActiveSession();
		if (!session || session.getType() !== 'extensionHost') {
			return; // we are only intersted if we have an active debug session for extensionHost
		}

		// A plugin logged output, show it inside the REPL
		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);
			}

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

				// Undefined gets printed as 'undefined'
				if (typeof a === 'undefined') {
					simpleVals.push('undefined');
				}

				// Null gets printed as 'null'
				else if (a === null) {
					simpleVals.push('null');
				}

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

					// Flush any existing simple values logged
					if (simpleVals.length) {
						this.logToRepl(simpleVals.join(' '), sev);
						simpleVals = [];
					}

					// Show object
					this.logToRepl(a, sev);
				}

				// String: watch out for % replacement directive
				// String substitution and formatting @ https://developer.chrome.com/devtools/docs/console
				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);
				}
			}

			// Flush simple values
			if (simpleVals.length) {
				this.logToRepl(simpleVals.join(' '), sev);
			}

			// Show repl
			this.revealRepl(true /* in background */).done(null, errors.onUnexpectedError);
		}
E
Erich Gamma 已提交
222 223 224 225
	}

	private registerSessionListeners(): void {
		this.toDispose.push(this.session.addListener2(debug.SessionEvents.INITIALIZED, (event: DebugProtocol.InitializedEvent) => {
226 227
			this.sendAllBreakpoints().done(null, errors.onUnexpectedError);
			this.sendExceptionBreakpoints().done(null, errors.onUnexpectedError);
E
Erich Gamma 已提交
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
		}));

		this.toDispose.push(this.session.addListener2(debug.SessionEvents.STOPPED, (event: DebugProtocol.StoppedEvent) => {
			this.setStateAndEmit(debug.State.Stopped, event.body.reason);
			var threadId = event.body.threadId;

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

					this.model.rawUpdate({ threadId: threadId, callStack: result.body.stackFrames, exception: event.body && event.body.reason === 'exception' });
					this.windowService.getWindow().focus();
					var callStack = this.model.getThreads()[threadId].callStack;
					if (callStack.length > 0) {
						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, () => {
			this.model.clearThreads(false);
			this.setFocusedStackFrameAndEvaluate(null);
			this.setStateAndEmit(debug.State.Running);
		}));

		this.toDispose.push(this.session.addListener2(debug.SessionEvents.THREAD, (event: DebugProtocol.ThreadEvent) => {
			if (event.body.reason === 'started') {
				this.session.threads().done((result) => {
I
isidor 已提交
259 260
					const thread = result.body.threads.filter(thread => thread.id === event.body.threadId).pop();
					if (thread) {
E
Erich Gamma 已提交
261
						this.model.rawUpdate({
I
isidor 已提交
262 263
							threadId: thread.id,
							thread: thread
E
Erich Gamma 已提交
264 265 266 267 268 269 270 271 272
						});
					}
				}, 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) => {
I
isidor 已提交
273
			if (this.session && this.session.getId() === (<any>event).sessionId) {
I
isidor 已提交
274
				this.session.disconnect().done(null, errors.onUnexpectedError);
E
Erich Gamma 已提交
275 276 277 278 279 280 281 282 283
			}
		}));

		this.toDispose.push(this.session.addListener2(debug.SessionEvents.OUTPUT, (event: DebugProtocol.OutputEvent) => {
			if (event.body && typeof event.body.output === 'string' && event.body.output.length > 0) {
				this.onOutput(event);
			}
		}));

284 285 286 287
		this.toDispose.push(this.session.addListener2(debug.SessionEvents.SERVER_EXIT, event => {
			if (this.session && this.session.getId() === event.sessionId) {
				this.onSessionEnd();
			}
E
Erich Gamma 已提交
288 289 290 291 292 293 294 295 296 297 298 299
		}));
	}

	private onOutput(event: DebugProtocol.OutputEvent): void {
		const outputSeverity = event.body.category === 'stderr' ? severity.Error : severity.Info;
		this.appendReplOutput(event.body.output, outputSeverity);
		this.revealRepl(true /* in background */).done(null, errors.onUnexpectedError);
	}

	private getThreadData(threadId: number): Promise {
		return this.model.getThreads()[threadId] ? Promise.as(true) :
			this.session.threads().then((response: DebugProtocol.ThreadsResponse) => {
I
isidor 已提交
300 301 302
				const thread = response.body.threads.filter(t => t.id === threadId).pop();
				if (!thread) {
					throw new Error('Did not get a thread from debug adapter with id ' + threadId);
E
Erich Gamma 已提交
303 304 305
				}

				this.model.rawUpdate({
I
isidor 已提交
306 307
					threadId: thread.id,
					thread: thread
E
Erich Gamma 已提交
308 309 310 311 312 313 314
				});
			});
	}

	private loadBreakpoints(): debug.IBreakpoint[] {
		try {
			return JSON.parse(this.storageService.get(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((breakpoint: any) => {
I
isidor 已提交
315
				return new model.Breakpoint(new Source(breakpoint.source.name, breakpoint.source.uri, breakpoint.source.reference), breakpoint.desiredLineNumber || breakpoint.lineNumber, breakpoint.enabled, breakpoint.condition);
E
Erich Gamma 已提交
316 317 318 319 320 321
			});
		} catch (e) {
			return [];
		}
	}

I
isidor 已提交
322 323 324
	private loadFunctionBreakpoints(): debug.IFunctionBreakpoint[] {
		try {
			return JSON.parse(this.storageService.get(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((fb: any) => {
325
				return new model.FunctionBreakpoint(fb.name, fb.enabled);
I
isidor 已提交
326 327 328 329 330 331
			});
		} catch (e) {
			return [];
		}
	}

E
Erich Gamma 已提交
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
	private loadExceptionBreakpoints(): debug.IExceptionBreakpoint[] {
		var result: debug.IExceptionBreakpoint[] = null;
		try {
			result = JSON.parse(this.storageService.get(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((exBreakpoint: any) => {
				return new model.ExceptionBreakpoint(exBreakpoint.name, exBreakpoint.enabled);
			});
		} catch (e) {
			result = [];
		}

		return result.length > 0 ? result : [new model.ExceptionBreakpoint('all', false), new model.ExceptionBreakpoint('uncaught', true)];
	}

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

	private setStateAndEmit(newState: debug.State, data?: any): void {
		this.state = newState;
		this.emit(debug.ServiceEvents.STATE_CHANGED, data);
	}

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

377 378 379 380 381
	public setBreakpointsForModel(modelUri: uri, rawData: debug.IRawBreakpoint[]): Promise {
		this.model.removeBreakpoints(
			this.model.getBreakpoints().filter(bp => bp.source.uri.toString() === modelUri.toString()));
		this.model.addBreakpoints(rawData);

E
Erich Gamma 已提交
382 383 384
		return this.sendBreakpoints(modelUri);
	}

385 386
	public toggleBreakpoint(rawBreakpoint: debug.IRawBreakpoint): Promise {
		const breakpoint = this.model.getBreakpoints().filter(bp => bp.lineNumber === rawBreakpoint.lineNumber && bp.source.uri.toString() === rawBreakpoint.uri.toString()).pop();
387
		if (breakpoint) {
388
			this.model.removeBreakpoints([breakpoint]);
389
		} else {
390
			this.model.addBreakpoints([rawBreakpoint]);
391 392
		}

393
		return this.sendBreakpoints(rawBreakpoint.uri);
E
Erich Gamma 已提交
394 395 396 397 398 399 400 401 402 403 404 405
	}

	public enableOrDisableAllBreakpoints(enabled: boolean): Promise {
		this.model.enableOrDisableAllBreakpoints(enabled);
		return this.sendAllBreakpoints();
	}

	public toggleEnablement(element: debug.IEnablement): Promise {
		this.model.toggleEnablement(element);
		if (element instanceof model.Breakpoint) {
			var breakpoint = <model.Breakpoint> element;
			return this.sendBreakpoints(breakpoint.source.uri);
406 407
		} else if (element instanceof model.FunctionBreakpoint) {
			// TODO@Isidor send function breakpoints and return
E
Erich Gamma 已提交
408 409 410 411 412
		}

		return this.sendExceptionBreakpoints();
	}

413 414 415
	public removeAllBreakpoints(): Promise {
		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 已提交
416 417 418 419 420 421 422 423 424

		return Promise.join(urisToClear.map(uri => this.sendBreakpoints(uri)));
	}

	public toggleBreakpointsActivated(): Promise {
		this.model.toggleBreakpointsActivated();
		return this.sendAllBreakpoints();
	}

425
	public addFunctionBreakpoint(functionName?: string): Promise {
I
isidor 已提交
426
		this.model.addFunctionBreakpoint(functionName);
427 428 429 430
		// TODO@Isidor send updated function breakpoints
		return Promise.as(true);
	}

I
isidor 已提交
431 432 433 434 435 436
	public renameFunctionBreakpoint(id: string, newFunctionName: string): Promise {
		this.model.renameFunctionBreakpoint(id, newFunctionName);
		// TODO@Isidor send updated function breakpoints
		return Promise.as(true);
	}

437 438
	public removeFunctionBreakpoints(id?: string): Promise {
		this.model.removeFunctionBreakpoints(id);
439 440
		// TODO@Isidor send updated function breakpoints
		return Promise.as(true);
I
isidor 已提交
441 442
	}

E
Erich Gamma 已提交
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
	public addReplExpression(name: string): Promise {
		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();
	}

	public addWatchExpression(name: string): Promise {
		return this.model.addWatchExpression(this.session, this.viewModel.getFocusedStackFrame(), name);
	}

	public renameWatchExpression(id: string, newName: string): Promise {
		return this.model.renameWatchExpression(this.session, this.viewModel.getFocusedStackFrame(), id, newName);
	}

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

473
	public createSession(openViewlet = true): Promise {
E
Erich Gamma 已提交
474
		this.textFileService.saveAll().done(null, errors.onUnexpectedError);
475
		this.clearReplExpressions();
E
Erich Gamma 已提交
476

477
		return this.pluginService.onReady().then(() => this.configurationManager.setConfiguration(this.configurationManager.getConfigurationName())).then(() => {
478 479 480
			const configuration = this.configurationManager.getConfiguration();
			if (!configuration) {
				return this.configurationManager.openConfigFile(false).then(openend => {
481 482 483 484
					if (openend) {
						this.messageService.show(severity.Info, nls.localize('NewLaunchConfig', "Please set up the launch configuration file to debug your application."));
					}
				});
E
Erich Gamma 已提交
485
			}
I
isidor 已提交
486
			if (!this.configurationManager.getAdapter()) {
487
				return Promise.wrapError(new Error(`Configured debug type '${ configuration.type }' is not supported.`));
E
Erich Gamma 已提交
488 489
			}

I
isidor 已提交
490 491 492
			return this.runPreLaunchTask(configuration).then(() => this.doCreateSession(configuration, openViewlet));
		});
	}
E
Erich Gamma 已提交
493

I
isidor 已提交
494 495 496 497 498 499 500 501 502
	private doCreateSession(configuration: debug.IConfig, openViewlet: boolean): Promise {
		this.session = new session.RawDebugSession(this.messageService, this.telemetryService, configuration.debugServer, this.configurationManager.getAdapter());
		this.registerSessionListeners();

		return this.session.initialize({
			adapterID: configuration.type,
			linesStartAt1: true,
			pathFormat: 'path'
		}).then((result: DebugProtocol.InitializeResponse) => {
503 504 505 506
			if (!this.session) {
				return Promise.wrapError(new Error(nls.localize('debugAdapterCrash', "Debug adapter process has terminated unexpectedly")));
			}

I
isidor 已提交
507 508 509 510 511 512 513 514 515
			this.setStateAndEmit(debug.State.Initializing);
			return configuration.request === 'attach' ? this.session.attach(configuration) : this.session.launch(configuration);
		}).then((result: DebugProtocol.Response) => {
			if (openViewlet) {
				this.viewletService.openViewlet(debug.VIEWLET_ID);
			}
			this.partService.addClass('debugging');
			this.contextService.updateOptions('editor', {
				glyphMargin: true
E
Erich Gamma 已提交
516
			});
I
isidor 已提交
517 518 519 520 521 522 523 524 525 526
			this.inDebugMode.set(true);

			this.telemetryService.publicLog('debugSessionStart', { type: configuration.type, breakpointCount: this.model.getBreakpoints().length, exceptionBreakpoints: this.model.getExceptionBreakpoints() });
		}).then(undefined, (error: Error) => {
			this.telemetryService.publicLog('debugMisconfiguration', { type: configuration ? configuration.type : undefined });
			if (this.session) {
				this.session.disconnect();
			}

			return Promise.wrapError(errors.create(error.message, { actions: [CloseAction, this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL)] }));
E
Erich Gamma 已提交
527 528 529 530
		});
	}

	private runPreLaunchTask(config: debug.IConfig): Promise {
531
		if (!config.preLaunchTask) {
E
Erich Gamma 已提交
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
			return Promise.as(true);
		}

		// Run a build task before starting a debug session
		return this.taskService.tasks().then(descriptions => {
			let filteredTasks = descriptions.filter(task => task.name === config.preLaunchTask);
			if (filteredTasks.length !== 1) {
				this.messageService.show(severity.Warning, nls.localize('DebugTaskNotFound', "Could not find a unique task \'{0}\'. Make sure the task exists and that it has a unique name.", config.preLaunchTask));
				return Promise.as(true);
			}

			// Task is already running - nothing to do.
			if (this.lastTaskEvent && this.lastTaskEvent.taskName === config.preLaunchTask) {
				return Promise.as(true);
			}

			if (this.lastTaskEvent) {
				// There is a different task running currently.
				return Promise.wrapError(errors.create(nls.localize('differentTaskRunning', "There is a task {0} running. Can not run pre launch task {1}.", this.lastTaskEvent.taskName, config.preLaunchTask)));
			}

			// No task running, execute the preLaunchTask.
			this.outputService.showOutput('Tasks', true, true);
555 556

			const taskPromise = this.taskService.run(filteredTasks[0].id).then(result => {
E
Erich Gamma 已提交
557 558 559 560
				this.lastTaskEvent = null;
			}, err => {
				this.lastTaskEvent = null;
			});
561 562

			return filteredTasks[0].isWatching ? Promise.as(true) : taskPromise;
E
Erich Gamma 已提交
563 564 565
		});
	}

566
	public rawAttach(port: number): Promise {
I
isidor 已提交
567
		if (this.session) {
568 569 570 571 572
			if (!this.session.isAttach) {
				return this.session.attach({ port });
			}

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

575
		const configuration = this.configurationManager.getConfiguration();
I
isidor 已提交
576
		return this.doCreateSession({
577
			type: configuration.type,
I
isidor 已提交
578
			request: 'attach',
579 580
			port,
			sourceMaps: configuration.sourceMaps,
581 582
			outDir: configuration.outDir,
			debugServer: configuration.debugServer
I
isidor 已提交
583 584 585
		}, true);
	}

586
	public restartSession(): Promise {
I
isidor 已提交
587
		return this.session ? this.session.disconnect(true).then(() => {
E
Erich Gamma 已提交
588 589
			new Promise(c => {
				setTimeout(() => {
590
					this.createSession(false).then(() => c(true));
E
Erich Gamma 已提交
591 592
				}, 300);
			});
593
		}) : this.createSession(false);
E
Erich Gamma 已提交
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
	}

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

	private onSessionEnd(): void {
		try {
			this.debugStringEditorInputs = lifecycle.disposeAll(this.debugStringEditorInputs);
		} catch (e) {
			// An internal module might be open so the dispose can throw -> ignore and continue with stop session.
		}

		if (this.session) {
			var bpsExist = this.model.getBreakpoints().length > 0;
			this.telemetryService.publicLog('debugSessionStop', { type: this.session.getType(), success: this.session.emittedStopped || !bpsExist, sessionLengthInSeconds: this.session.getLengthInSeconds(), breakpointCount: this.model.getBreakpoints().length });
		}
		this.session = null;
		this.partService.removeClass('debugging');
		this.editorService.focusEditor();

615 616 617 618
		this.model.clearThreads(true);
		this.setFocusedStackFrameAndEvaluate(null);
		this.setStateAndEmit(debug.State.Inactive);

619 620 621 622 623
		// Set breakpoints back to unverified since the session ended.
		const data: {[id: string]: { line: number, verified: boolean } } = { };
		this.model.getBreakpoints().forEach(bp => data[bp.getId()] = { line: bp.lineNumber, verified: false });
		this.model.updateBreakpoints(data);

E
Erich Gamma 已提交
624 625 626 627 628 629 630 631 632 633 634
		this.inDebugMode.reset();
	}

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

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

I
isidor 已提交
635
	public openOrRevealEditor(source: Source, lineNumber: number, preserveFocus: boolean, sideBySide: boolean): Promise {
E
Erich Gamma 已提交
636
		const visibleEditors = this.editorService.getVisibleEditors();
637 638 639 640 641 642 643 644
		for (var i = 0; i < visibleEditors.length; i++) {
			const fileInput = wbeditorcommon.asFileEditorInput(visibleEditors[i].input);
			if (fileInput && fileInput.getResource().toString() === source.uri.toString()) {
				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 已提交
645
				}
646 647

				return Promise.as(null);
E
Erich Gamma 已提交
648 649 650 651 652 653
			}
		}

		if (source.inMemory) {
			// Internal module
			if (source.reference !== 0 && this.session) {
654
				return this.session.source({ sourceReference: source.reference }).then(response => {
E
Erich Gamma 已提交
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
					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 已提交
687
	private sourceIsUnavailable(source: Source, sideBySide: boolean): Promise {
E
Erich Gamma 已提交
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
		this.model.sourceIsUnavailable(source);
		const editorInput = this.getDebugStringEditorInput(source, 'Source is not available.', 'text/plain');

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

	public revealRepl(inBackground: boolean = false): Promise {
		let editors = this.editorService.getVisibleEditors();

		// First check if repl is already opened
		for (let i = 0; i < editors.length; i++) {
			let editor = editors[i];
			if (editor.input instanceof debuginputs.ReplEditorInput) {
				if (!inBackground) {
					return this.editorService.focusEditor(editor);
				}

				return Promise.as(null);
			}
		}

		// Then find a position but try to not replace an existing file editor in any of the positions
		let position = Position.LEFT;
		let lastIndex = editors.length - 1;
		if (editors.length === 3) {
			position = wbeditorcommon.asFileEditorInput(editors[lastIndex].input, true) ? null : Position.RIGHT;
		} else if (editors.length === 2) {
			position = wbeditorcommon.asFileEditorInput(editors[lastIndex].input, true) ? Position.RIGHT : Position.CENTER;
		} else if (editors.length) {
			position = wbeditorcommon.asFileEditorInput(editors[lastIndex].input, true) ? Position.CENTER : Position.LEFT;
		}

		if (position === null) {
			return Promise.as(null); // could not find a good position, return
		}

		// open repl
		return this.editorService.openEditor(debuginputs.ReplEditorInput.getInstance(), wbeditorcommon.TextEditorOptions.create({ preserveFocus: inBackground }), position).then((editor: Repl) => {
			const elements = this.model.getReplElements();
			if (!inBackground && elements.length > 0) {
				return editor.reveal(elements[elements.length - 1]);
			}
		});
	}

733 734 735 736
	public canSetBreakpointsIn(model: editor.IModel, lineNumber: number): boolean {
		return this.configurationManager.canSetBreakpointsIn(model, lineNumber);
	}

737 738
	public getConfigurationName(): string {
		return this.configurationManager.getConfigurationName();
739 740 741 742 743 744 745 746 747 748 749 750 751 752
	}

	public setConfiguration(name: string): Promise {
		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();
	}

I
isidor 已提交
753
	private getDebugStringEditorInput(source: Source, value: string, mtype: string): debuginputs.DebugStringEditorInput {
E
Erich Gamma 已提交
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773
		var filtered = this.debugStringEditorInputs.filter(input => input.getResource().toString() === source.uri.toString());

		if (filtered.length === 0) {
			var result = this.instantiationService.createInstance(debuginputs.DebugStringEditorInput, source.name, source.uri, 'internal module', value, mtype, void 0);
			this.debugStringEditorInputs.push(result);
			return result;
		} else {
			return filtered[0];
		}
	}

	public sendAllBreakpoints(): Promise {
		return Promise.join(arrays.distinct(this.model.getBreakpoints(), bp => bp.source.uri.toString()).map(bp => this.sendBreakpoints(bp.source.uri)));
	}

	private sendBreakpoints(modelUri: uri): Promise {
		if (!this.session) {
			return Promise.as(null);
		}

774 775 776 777
		const breakpointsToSend = arrays.distinct(
			this.model.getBreakpoints().filter(bp => this.model.areBreakpointsActivated() && bp.enabled && bp.source.uri.toString() === modelUri.toString()),
			bp =>  `${ bp.desiredLineNumber }`
		);
778

779 780

		return this.session.setBreakpoints({ source: Source.toRawSource(modelUri, this.model), lines: breakpointsToSend.map(bp => bp.desiredLineNumber) }).then(response => {
781 782 783 784 785 786
			const data: {[id: string]: { line: number, verified: boolean } } = { };
			for (let i = 0; i < breakpointsToSend.length; i++) {
				data[breakpointsToSend[i].getId()] = response.body.breakpoints[i];
			}

			this.model.updateBreakpoints(data);
E
Erich Gamma 已提交
787 788 789 790
		});
	}

	private sendExceptionBreakpoints(): Promise {
I
isidor 已提交
791 792 793
		if (!this.session) {
			return Promise.as(null);
		}
I
isidor 已提交
794 795 796

		var enabledExBreakpoints = this.model.getExceptionBreakpoints().filter(exb => exb.enabled);
		return this.session.setExceptionBreakpoints({ filters: enabledExBreakpoints.map(exb => exb.name) });
E
Erich Gamma 已提交
797 798 799
	}

	private onFileChanges(fileChangesEvent: FileChangesEvent): void {
800 801
		this.model.removeBreakpoints(this.model.getBreakpoints().filter(bp =>
			fileChangesEvent.contains(bp.source.uri, FileChangeType.DELETED)));
E
Erich Gamma 已提交
802 803 804 805 806
	}

	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);
807
		this.storageService.store(DEBUG_FUNCTION_BREAKPOINTS_KEY, JSON.stringify(this.model.getFunctionBreakpoints()), StorageScope.WORKSPACE);
E
Erich Gamma 已提交
808
		this.storageService.store(DEBUG_EXCEPTION_BREAKPOINTS_KEY, JSON.stringify(this.model.getExceptionBreakpoints()), StorageScope.WORKSPACE);
809
		this.storageService.store(DEBUG_SELECTED_CONFIG_NAME_KEY, this.configurationManager.getConfigurationName(), StorageScope.WORKSPACE);
E
Erich Gamma 已提交
810 811 812 813 814
		this.storageService.store(DEBUG_WATCH_EXPRESSIONS_KEY, JSON.stringify(this.model.getWatchExpressions()), StorageScope.WORKSPACE);
	}

	public dispose(): void {
		if (this.session) {
I
isidor 已提交
815
			this.session.disconnect();
E
Erich Gamma 已提交
816 817 818 819 820 821
			this.session = null;
		}
		this.model.dispose();
		this.toDispose = lifecycle.disposeAll(this.toDispose);
	}
}