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

I
isidor 已提交
6
import { TPromise } from 'vs/base/common/winjs.base';
E
Erich Gamma 已提交
7 8
import nls = require('vs/nls');
import lifecycle = require('vs/base/common/lifecycle');
9
import Event, { Emitter } from 'vs/base/common/event';
E
Erich Gamma 已提交
10 11 12 13 14
import uuid = require('vs/base/common/uuid');
import severity from 'vs/base/common/severity';
import types = require('vs/base/common/types');
import arrays = require('vs/base/common/arrays');
import debug = require('vs/workbench/parts/debug/common/debug');
I
isidor 已提交
15
import { Source } from 'vs/workbench/parts/debug/common/debugSource';
E
Erich Gamma 已提交
16

17 18
const MAX_REPL_LENGTH = 10000;

E
Erich Gamma 已提交
19
function resolveChildren(debugService: debug.IDebugService, parent: debug.IExpressionContainer): TPromise<Variable[]> {
I
isidor 已提交
20 21
	const session = debugService.getActiveSession();
	// only variables with reference > 0 have children.
E
Erich Gamma 已提交
22 23 24 25
	if (!session || parent.reference <= 0) {
		return TPromise.as([]);
	}

26
	return session.variables({ variablesReference: parent.reference }).then(response => {
27
		return arrays.distinct(response.body.variables.filter(v => !!v), v => v.name).map(
E
Erich Gamma 已提交
28 29
			v => new Variable(parent, v.variablesReference, v.name, v.value)
		);
30
	}, (e: Error) => [new Variable(parent, 0, null, e.message, false)]);
E
Erich Gamma 已提交
31 32 33 34 35 36
}

function massageValue(value: string): string {
	return value ? value.replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t') : value;
}

I
isidor 已提交
37 38 39 40 41
export function evaluateExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, expression: Expression, context: string): TPromise<Expression> {
	if (!session) {
		expression.value = context === 'repl' ? nls.localize('startDebugFirst', "Please start a debug session to evaluate") : Expression.DEFAULT_VALUE;
		expression.available = false;
		expression.reference = 0;
A
Alex Dima 已提交
42
		return TPromise.as(expression);
I
isidor 已提交
43 44 45 46 47 48 49
	}

	return session.evaluate({
		expression: expression.name,
		frameId: stackFrame ? stackFrame.frameId : undefined,
		context
	}).then(response => {
I
isidor 已提交
50 51 52 53 54
		expression.available = !!response.body;
		if (response.body) {
			expression.value = response.body.result;
			expression.reference = response.body.variablesReference;
		}
I
isidor 已提交
55 56 57 58 59 60 61 62 63 64 65

		return expression;
	}, err => {
		expression.value = err.message;
		expression.available = false;
		expression.reference = 0;

		return expression;
	});
}

I
isidor 已提交
66 67
const notPropertySyntax = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
const arrayElementSyntax = /\[.*\]$/;
I
isidor 已提交
68

69 70 71
export function getFullExpressionName(expression: debug.IExpression, sessionType: string): string {
	let names = [expression.name];
	if (expression instanceof Variable) {
I
isidor 已提交
72
		let v = (<Variable> expression).parent;
73 74 75 76 77 78 79 80 81 82 83
		while (v instanceof Variable || v instanceof Expression) {
			names.push((<Variable> v).name);
			v = (<Variable> v).parent;
		}
	}
	names = names.reverse();

	let result = null;
	names.forEach(name => {
		if (!result) {
			result = name;
I
isidor 已提交
84
		} else if (arrayElementSyntax.test(name) || (sessionType === 'node' && !notPropertySyntax.test(name))) {
I
isidor 已提交
85
			// use safe way to access node properties a['property_name']. Also handles array elements.
86 87 88 89 90 91 92 93 94
			result = name && name.indexOf('[') === 0 ? `${ result }${ name }` : `${ result }['${ name }']`;
		} else {
			result = `${ result }.${ name }`;
		}
	});

	return result;
}

E
Erich Gamma 已提交
95
export class Thread implements debug.IThread {
96 97
	private promisedCallStack: TPromise<debug.IStackFrame[]>;
	private cachedCallStack: debug.IStackFrame[];
I
isidor 已提交
98
	public stoppedDetails: debug.IRawStoppedDetails;
99
	public stopped: boolean;
E
Erich Gamma 已提交
100

I
isidor 已提交
101
	constructor(public name: string, public threadId: number) {
102
		this.promisedCallStack = undefined;
I
isidor 已提交
103
		this.stoppedDetails = undefined;
104 105
		this.cachedCallStack = undefined;
		this.stopped = false;
E
Erich Gamma 已提交
106 107 108 109 110
	}

	public getId(): string {
		return `thread:${ this.name }:${ this.threadId }`;
	}
111 112 113 114 115 116 117 118 119 120

	public clearCallStack(): void {
		this.promisedCallStack = undefined;
		this.cachedCallStack = undefined;
	}

	public getCachedCallStack(): debug.IStackFrame[] {
		return this.cachedCallStack;
	}

I
isidor 已提交
121
	public getCallStack(debugService: debug.IDebugService, getAdditionalStackFrames = false): TPromise<debug.IStackFrame[]> {
122 123 124
		if (!this.stopped) {
			return TPromise.as([]);
		}
I
isidor 已提交
125

126
		if (!this.promisedCallStack) {
I
isidor 已提交
127 128 129 130 131 132 133 134 135
			this.promisedCallStack = this.getCallStackImpl(debugService, 0).then(callStack => {
				this.cachedCallStack = callStack;
				return callStack;
			});
		} else if (getAdditionalStackFrames) {
			this.promisedCallStack = this.promisedCallStack.then(callStackFirstPart => this.getCallStackImpl(debugService, callStackFirstPart.length).then(callStackSecondPart => {
				this.cachedCallStack = callStackFirstPart.concat(callStackSecondPart);
				return this.cachedCallStack;
			}));
136 137 138 139 140
		}

		return this.promisedCallStack;
	}

I
isidor 已提交
141
	private getCallStackImpl(debugService: debug.IDebugService, startFrame: number): TPromise<debug.IStackFrame[]> {
142
		let session = debugService.getActiveSession();
I
isidor 已提交
143 144
		return session.stackTrace({ threadId: this.threadId, startFrame, levels: 20 }).then(response => {
			this.stoppedDetails.totalFrames = response.body.totalFrames || response.body.stackFrames.length;
145 146
			return response.body.stackFrames.map((rsf, level) => {
				if (!rsf) {
I
isidor 已提交
147
					return new StackFrame(this.threadId, 0, new Source({ name: 'unknown' }, false), nls.localize('unknownStack', "Unknown stack location"), undefined, undefined);
148 149
				}

I
isidor 已提交
150
				return new StackFrame(this.threadId, rsf.id, rsf.source ? new Source(rsf.source) : new Source({ name: 'unknown' }, false), rsf.name, rsf.line, rsf.column);
151 152 153
			});
		});
	}
E
Erich Gamma 已提交
154 155 156 157
}

export class OutputElement implements debug.ITreeElement {

I
isidor 已提交
158 159
	constructor(private id = uuid.generateUuid()) {
		// noop
E
Erich Gamma 已提交
160 161 162 163 164 165 166 167 168
	}

	public getId(): string {
		return this.id;
	}
}

export class ValueOutputElement extends OutputElement {

I
isidor 已提交
169 170
	constructor(public value: string, public severity: severity, public category?: string, public counter:number = 1) {
		super();
E
Erich Gamma 已提交
171 172 173 174 175 176 177 178 179 180
	}
}

export class KeyValueOutputElement extends OutputElement {

	private static MAX_CHILDREN = 1000; // upper bound of children per value

	private children: debug.ITreeElement[];
	private _valueName: string;

I
isidor 已提交
181 182
	constructor(public key: string, public valueObj: any, public annotation?: string) {
		super();
E
Erich Gamma 已提交
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

		this._valueName = null;
	}

	public get value(): string {
		if (this._valueName === null) {
			if (this.valueObj === null) {
				this._valueName = 'null';
			} else if (Array.isArray(this.valueObj)) {
				this._valueName = `Array[${this.valueObj.length}]`;
			} else if (types.isObject(this.valueObj)) {
				this._valueName = 'Object';
			} else if (types.isString(this.valueObj)) {
				this._valueName = `"${massageValue(this.valueObj)}"`;
			} else {
				this._valueName = String(this.valueObj);
			}

			if (!this._valueName) {
				this._valueName = '';
			}
		}

		return this._valueName;
	}

	public getChildren(): debug.ITreeElement[] {
		if (!this.children) {
			if (Array.isArray(this.valueObj)) {
I
isidor 已提交
212
				this.children = (<any[]>this.valueObj).slice(0, KeyValueOutputElement.MAX_CHILDREN).map((v, index) => new KeyValueOutputElement(String(index), v, null));
E
Erich Gamma 已提交
213
			} else if (types.isObject(this.valueObj)) {
I
isidor 已提交
214
				this.children = Object.getOwnPropertyNames(this.valueObj).slice(0, KeyValueOutputElement.MAX_CHILDREN).map(key => new KeyValueOutputElement(key, this.valueObj[key], null));
E
Erich Gamma 已提交
215 216 217 218 219 220 221 222 223
			} else {
				this.children = [];
			}
		}

		return this.children;
	}
}

224
export class ExpressionContainer implements debug.IExpressionContainer {
E
Erich Gamma 已提交
225 226

	private children: TPromise<debug.IExpression[]>;
227 228
	public valueChanged: boolean;
	public static allValues: { [id: string]: string } = {};
E
Erich Gamma 已提交
229

230
	constructor(public reference: number, private id: string, private cacheChildren: boolean) {
E
Erich Gamma 已提交
231 232 233 234 235 236 237 238 239 240 241 242 243
		this.children = null;
	}

	public getChildren(debugService: debug.IDebugService): TPromise<debug.IExpression[]> {
		if (!this.cacheChildren) {
			return resolveChildren(debugService, this);
		}
		if (!this.children) {
			this.children = resolveChildren(debugService, this);
		}

		return this.children;
	}
244 245 246 247 248

	public getId(): string {
		return this.id;
	}

E
Erich Gamma 已提交
249 250
}

251 252
export class Expression extends ExpressionContainer implements debug.IExpression {
	static DEFAULT_VALUE = 'not available';
E
Erich Gamma 已提交
253

254 255
	public available: boolean;
	private _value: string;
E
Erich Gamma 已提交
256

257 258 259 260
	constructor(public name: string, cacheChildren: boolean, id = uuid.generateUuid()) {
		super(0, id, cacheChildren);
		this.value = Expression.DEFAULT_VALUE;
		this.available = false;
E
Erich Gamma 已提交
261 262
	}

263 264
	public get value(): string {
		return this._value;
E
Erich Gamma 已提交
265 266
	}

267 268 269 270 271 272 273
	public set value(value: string) {
		this._value = massageValue(value);
		this.valueChanged = ExpressionContainer.allValues[this.getId()] &&
			ExpressionContainer.allValues[this.getId()] !== Expression.DEFAULT_VALUE && ExpressionContainer.allValues[this.getId()] !== value;
		ExpressionContainer.allValues[this.getId()] = value;
	}
}
E
Erich Gamma 已提交
274

275 276 277 278 279 280 281 282 283
export class Variable extends ExpressionContainer implements debug.IExpression {

	public value: string;

	constructor(public parent: debug.IExpressionContainer, reference: number, public name: string, value: string, public available = true) {
		super(reference, `variable:${ parent.getId() }:${ name }`, true);
		this.value = massageValue(value);
		this.valueChanged = ExpressionContainer.allValues[this.getId()] && ExpressionContainer.allValues[this.getId()] !== value;
		ExpressionContainer.allValues[this.getId()] = value;
E
Erich Gamma 已提交
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
	}
}

export class Scope implements debug.IScope {

	private children: TPromise<Variable[]>;

	constructor(private threadId: number, public name: string, public reference: number, public expensive: boolean) {
		this.children = null;
	}

	public getId(): string {
		return `scope:${ this.threadId }:${ this.name }:${ this.reference }`;
	}

	public getChildren(debugService: debug.IDebugService): TPromise<Variable[]> {
		if (!this.children) {
			this.children = resolveChildren(debugService, this);
		}

		return this.children;
	}
}

export class StackFrame implements debug.IStackFrame {

	private internalId: string;
	private scopes: TPromise<Scope[]>;

I
isidor 已提交
313
	constructor(public threadId: number, public frameId: number, public source: Source, public name: string, public lineNumber: number, public column: number) {
E
Erich Gamma 已提交
314 315 316 317 318 319 320 321 322 323 324 325
		this.internalId = uuid.generateUuid();
		this.scopes = null;
	}

	public getId(): string {
		return this.internalId;
	}

	public getScopes(debugService: debug.IDebugService): TPromise<debug.IScope[]> {
		if (!this.scopes) {
			this.scopes = debugService.getActiveSession().scopes({ frameId: this.frameId }).then(response => {
				return response.body.scopes.map(rs => new Scope(this.threadId, rs.name, rs.variablesReference, rs.expensive));
326
			}, err => []);
E
Erich Gamma 已提交
327 328 329 330 331 332 333 334 335
		}

		return this.scopes;
	}
}

export class Breakpoint implements debug.IBreakpoint {

	public lineNumber: number;
336
	public verified: boolean;
337
	public idFromAdapter: number;
I
isidor 已提交
338
	public message: string;
E
Erich Gamma 已提交
339 340
	private id: string;

I
isidor 已提交
341
	constructor(public source: Source, public desiredLineNumber: number, public enabled: boolean, public condition: string) {
342 343 344
		if (enabled === undefined) {
			this.enabled = true;
		}
E
Erich Gamma 已提交
345
		this.lineNumber = this.desiredLineNumber;
346
		this.verified = false;
E
Erich Gamma 已提交
347 348 349 350 351 352 353 354
		this.id = uuid.generateUuid();
	}

	public getId(): string {
		return this.id;
	}
}

I
isidor 已提交
355 356 357
export class FunctionBreakpoint implements debug.IFunctionBreakpoint {

	private id: string;
I
isidor 已提交
358
	public verified: boolean;
359
	public idFromAdapter: number;
I
isidor 已提交
360

361
	constructor(public name: string, public enabled: boolean) {
I
isidor 已提交
362
		this.verified = false;
I
isidor 已提交
363 364 365 366 367 368 369 370
		this.id = uuid.generateUuid();
	}

	public getId(): string {
		return this.id;
	}
}

E
Erich Gamma 已提交
371 372 373 374
export class ExceptionBreakpoint implements debug.IExceptionBreakpoint {

	private id: string;

375
	constructor(public filter: string, public label: string, public enabled: boolean) {
E
Erich Gamma 已提交
376 377 378 379 380 381 382 383
		this.id = uuid.generateUuid();
	}

	public getId(): string {
		return this.id;
	}
}

384
export class Model implements debug.IModel {
E
Erich Gamma 已提交
385 386 387 388

	private threads: { [reference: number]: debug.IThread; };
	private toDispose: lifecycle.IDisposable[];
	private replElements: debug.ITreeElement[];
389 390 391 392
	private _onDidChangeBreakpoints: Emitter<void>;
	private _onDidChangeCallStack: Emitter<void>;
	private _onDidChangeWatchExpressions: Emitter<debug.IExpression>;
	private _onDidChangeREPLElements: Emitter<void>;
E
Erich Gamma 已提交
393

I
isidor 已提交
394
	constructor(private breakpoints: debug.IBreakpoint[], private breakpointsActivated: boolean, private functionBreakpoints: debug.IFunctionBreakpoint[],
E
Erich Gamma 已提交
395 396 397 398 399
		private exceptionBreakpoints: debug.IExceptionBreakpoint[], private watchExpressions: Expression[]) {

		this.threads = {};
		this.replElements = [];
		this.toDispose = [];
400 401 402 403
		this._onDidChangeBreakpoints = new Emitter<void>();
		this._onDidChangeCallStack = new Emitter<void>();
		this._onDidChangeWatchExpressions = new Emitter<debug.IExpression>();
		this._onDidChangeREPLElements = new Emitter<void>();
E
Erich Gamma 已提交
404 405 406 407 408 409
	}

	public getId(): string {
		return 'root';
	}

410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
	public get onDidChangeBreakpoints(): Event<void> {
		return this._onDidChangeBreakpoints.event;
	}

	public get onDidChangeCallStack(): Event<void> {
		return this._onDidChangeCallStack.event;
	}

	public get onDidChangeWatchExpressions(): Event<debug.IExpression> {
		return this._onDidChangeWatchExpressions.event;
	}

	public get onDidChangeREPLElements(): Event<void> {
		return this._onDidChangeREPLElements.event;
	}

E
Erich Gamma 已提交
426 427 428 429 430 431 432 433 434
	public getThreads(): { [reference: number]: debug.IThread; } {
		return this.threads;
	}

	public clearThreads(removeThreads: boolean, reference: number = undefined): void {
		if (reference) {
			if (removeThreads) {
				delete this.threads[reference];
			} else {
435
				this.threads[reference].clearCallStack();
I
isidor 已提交
436
				this.threads[reference].stoppedDetails = undefined;
E
Erich Gamma 已提交
437 438 439 440
			}
		} else {
			if (removeThreads) {
				this.threads = {};
441
				ExpressionContainer.allValues = {};
E
Erich Gamma 已提交
442
			} else {
I
isidor 已提交
443
				for (let ref in this.threads) {
E
Erich Gamma 已提交
444
					if (this.threads.hasOwnProperty(ref)) {
445
						this.threads[ref].clearCallStack();
I
isidor 已提交
446
						this.threads[ref].stoppedDetails = undefined;
E
Erich Gamma 已提交
447 448 449 450 451
					}
				}
			}
		}

452
		this._onDidChangeCallStack.fire();
E
Erich Gamma 已提交
453 454
	}

455 456 457 458 459 460 461 462 463 464
	public continueThreads(): void {
		for (let ref in this.threads) {
			if (this.threads.hasOwnProperty(ref)) {
				this.threads[ref].stopped = false;
			}
		}

		this.clearThreads(false);
	}

E
Erich Gamma 已提交
465 466 467 468
	public getBreakpoints(): debug.IBreakpoint[] {
		return this.breakpoints;
	}

I
isidor 已提交
469 470 471 472
	public getFunctionBreakpoints(): debug.IFunctionBreakpoint[] {
		return this.functionBreakpoints;
	}

E
Erich Gamma 已提交
473 474 475 476
	public getExceptionBreakpoints(): debug.IExceptionBreakpoint[] {
		return this.exceptionBreakpoints;
	}

477
	public setExceptionBreakpoints(data: DebugProtocol.ExceptionBreakpointsFilter[]): void {
478
		if (data) {
479 480 481 482
			this.exceptionBreakpoints = data.map(d => {
				const ebp = this.exceptionBreakpoints.filter(ebp => ebp.filter === d.filter).pop();
				return new ExceptionBreakpoint(d.filter, d.label, ebp ? ebp.enabled : d.default);
			});
483 484 485
		}
	}

E
Erich Gamma 已提交
486 487 488 489 490 491
	public areBreakpointsActivated(): boolean {
		return this.breakpointsActivated;
	}

	public toggleBreakpointsActivated(): void {
		this.breakpointsActivated = !this.breakpointsActivated;
492
		this._onDidChangeBreakpoints.fire();
E
Erich Gamma 已提交
493 494
	}

495
	public addBreakpoints(rawData: debug.IRawBreakpoint[]): void {
496 497
		this.breakpoints = this.breakpoints.concat(rawData.map(rawBp =>
			new Breakpoint(new Source(Source.toRawSource(rawBp.uri, this)), rawBp.lineNumber, rawBp.enabled, rawBp.condition)));
498
		this.breakpointsActivated = true;
499
		this._onDidChangeBreakpoints.fire();
500
	}
E
Erich Gamma 已提交
501

502 503
	public removeBreakpoints(toRemove: debug.IBreakpoint[]): void {
		this.breakpoints = this.breakpoints.filter(bp => !toRemove.some(toRemove => toRemove.getId() === bp.getId()));
504
		this._onDidChangeBreakpoints.fire();
E
Erich Gamma 已提交
505 506
	}

I
isidor 已提交
507
	public updateBreakpoints(data: { [id: string]: DebugProtocol.Breakpoint }): void {
508 509 510
		this.breakpoints.forEach(bp => {
			const bpData = data[bp.getId()];
			if (bpData) {
511
				bp.lineNumber = bpData.line ? bpData.line : bp.lineNumber;
512
				bp.verified = bpData.verified;
513
				bp.idFromAdapter = bpData.id;
I
isidor 已提交
514
				bp.message = bpData.message;
515 516
			}
		});
517
		this._onDidChangeBreakpoints.fire();
518 519
	}

E
Erich Gamma 已提交
520 521 522 523 524
	public toggleEnablement(element: debug.IEnablement): void {
		element.enabled = !element.enabled;
		if (element instanceof Breakpoint && !element.enabled) {
			var breakpoint = <Breakpoint> element;
			breakpoint.lineNumber = breakpoint.desiredLineNumber;
525
			breakpoint.verified = false;
E
Erich Gamma 已提交
526 527
		}

528
		this._onDidChangeBreakpoints.fire();
E
Erich Gamma 已提交
529 530 531 532 533 534 535
	}

	public enableOrDisableAllBreakpoints(enabled: boolean): void {
		this.breakpoints.forEach(bp => {
			bp.enabled = enabled;
			if (!enabled) {
				bp.lineNumber = bp.desiredLineNumber;
536
				bp.verified = false;
E
Erich Gamma 已提交
537 538
			}
		});
I
isidor 已提交
539 540
		this.exceptionBreakpoints.forEach(ebp => ebp.enabled = enabled);
		this.functionBreakpoints.forEach(fbp => fbp.enabled = enabled);
E
Erich Gamma 已提交
541

542
		this._onDidChangeBreakpoints.fire();
E
Erich Gamma 已提交
543 544
	}

I
isidor 已提交
545 546
	public addFunctionBreakpoint(functionName: string): void {
		this.functionBreakpoints.push(new FunctionBreakpoint(functionName, true));
547
		this._onDidChangeBreakpoints.fire();
I
isidor 已提交
548 549
	}

550
	public updateFunctionBreakpoints(data: { [id: string]: { name?: string, verified?: boolean; id?: number } }): void {
I
isidor 已提交
551 552 553 554 555
		this.functionBreakpoints.forEach(fbp => {
			const fbpData = data[fbp.getId()];
			if (fbpData) {
				fbp.name = fbpData.name || fbp.name;
				fbp.verified = fbpData.verified;
556
				fbp.idFromAdapter = fbpData.id;
I
isidor 已提交
557 558 559
			}
		});

560
		this._onDidChangeBreakpoints.fire();
I
isidor 已提交
561 562
	}

563
	public removeFunctionBreakpoints(id?: string): void {
I
isidor 已提交
564
		this.functionBreakpoints = id ? this.functionBreakpoints.filter(fbp => fbp.getId() !== id) : [];
565
		this._onDidChangeBreakpoints.fire();
566 567
	}

E
Erich Gamma 已提交
568 569 570 571
	public getReplElements(): debug.ITreeElement[] {
		return this.replElements;
	}

I
isidor 已提交
572
	public addReplExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, name: string): TPromise<void> {
I
isidor 已提交
573
		const expression = new Expression(name, true);
574
		this.addReplElements([expression]);
575 576
		return evaluateExpression(session, stackFrame, expression, 'repl')
			.then(() => this._onDidChangeREPLElements.fire());
E
Erich Gamma 已提交
577 578 579 580 581 582 583 584
	}

	public logToRepl(value: string, severity?: severity): void;
	public logToRepl(value: { [key: string]: any }, severity?: severity): void;
	public logToRepl(value: any, severity?: severity): void {
		let elements:OutputElement[] = [];
		let previousOutput = this.replElements.length && (<ValueOutputElement>this.replElements[this.replElements.length - 1]);

I
isidor 已提交
585
		// string message
E
Erich Gamma 已提交
586 587 588 589
		if (typeof value === 'string') {
			if (value && value.trim() && previousOutput && previousOutput.value === value && previousOutput.severity === severity) {
				previousOutput.counter++; // we got the same output (but not an empty string when trimmed) so we just increment the counter
			} else {
I
isidor 已提交
590
				let lines = value.trim().split('\n');
E
Erich Gamma 已提交
591
				lines.forEach((line, index) => {
I
isidor 已提交
592
					elements.push(new ValueOutputElement(line, severity));
E
Erich Gamma 已提交
593 594 595 596
				});
			}
		}

I
isidor 已提交
597
		// key-value output
E
Erich Gamma 已提交
598
		else {
I
isidor 已提交
599
			elements.push(new KeyValueOutputElement(value.prototype, value, nls.localize('snapshotObj', "Only primitive values are shown for this object.")));
E
Erich Gamma 已提交
600 601 602
		}

		if (elements.length) {
603
			this.addReplElements(elements);
604
			this._onDidChangeREPLElements.fire();
E
Erich Gamma 已提交
605 606 607 608
		}
	}

	public appendReplOutput(value: string, severity?: severity): void {
I
isidor 已提交
609
		const elements: OutputElement[] = [];
E
Erich Gamma 已提交
610
		let previousOutput = this.replElements.length && (<ValueOutputElement>this.replElements[this.replElements.length - 1]);
611 612
		let lines = value.split('\n');
		let groupTogether = !!previousOutput && (previousOutput.category === 'output' && severity === previousOutput.severity);
E
Erich Gamma 已提交
613 614

		if (groupTogether) {
615 616 617 618 619
			// append to previous line if same group
			previousOutput.value += lines.shift();
		} else if (previousOutput && previousOutput.value === '') {
			// remove potential empty lines between different output types
			this.replElements.pop();
E
Erich Gamma 已提交
620 621 622 623
		}

		// fill in lines as output value elements
		lines.forEach((line, index) => {
I
isidor 已提交
624
			elements.push(new ValueOutputElement(line, severity, 'output'));
E
Erich Gamma 已提交
625 626
		});

627
		this.addReplElements(elements);
628
		this._onDidChangeREPLElements.fire();
E
Erich Gamma 已提交
629 630
	}

631 632 633 634 635 636 637
	private addReplElements(newElements: debug.ITreeElement[]): void {
		this.replElements.push(...newElements);
		if (this.replElements.length > MAX_REPL_LENGTH) {
			this.replElements.splice(0, this.replElements.length - MAX_REPL_LENGTH);
		}
	}

E
Erich Gamma 已提交
638
	public clearReplExpressions(): void {
639 640
		if (this.replElements.length > 0) {
			this.replElements = [];
641
			this._onDidChangeREPLElements.fire();
642
		}
E
Erich Gamma 已提交
643 644 645 646 647 648
	}

	public getWatchExpressions(): Expression[] {
		return this.watchExpressions;
	}

I
isidor 已提交
649
	public addWatchExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, name: string): TPromise<void> {
I
isidor 已提交
650
		const we = new Expression(name, false);
E
Erich Gamma 已提交
651 652
		this.watchExpressions.push(we);
		if (!name) {
653
			this._onDidChangeWatchExpressions.fire(we);
A
Alex Dima 已提交
654
			return TPromise.as(null);
E
Erich Gamma 已提交
655 656 657 658 659
		}

		return this.evaluateWatchExpressions(session, stackFrame, we.getId());
	}

I
isidor 已提交
660
	public renameWatchExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, id: string, newName: string): TPromise<void> {
I
isidor 已提交
661
		const filtered = this.watchExpressions.filter(we => we.getId() === id);
E
Erich Gamma 已提交
662 663
		if (filtered.length === 1) {
			filtered[0].name = newName;
I
isidor 已提交
664
			return evaluateExpression(session, stackFrame, filtered[0], 'watch').then(() => {
665
				this._onDidChangeWatchExpressions.fire(filtered[0]);
E
Erich Gamma 已提交
666 667 668
			});
		}

A
Alex Dima 已提交
669
		return TPromise.as(null);
E
Erich Gamma 已提交
670 671
	}

I
isidor 已提交
672
	public evaluateWatchExpressions(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, id: string = null): TPromise<void> {
E
Erich Gamma 已提交
673
		if (id) {
I
isidor 已提交
674
			const filtered = this.watchExpressions.filter(we => we.getId() === id);
E
Erich Gamma 已提交
675
			if (filtered.length !== 1) {
A
Alex Dima 已提交
676
				return TPromise.as(null);
E
Erich Gamma 已提交
677 678
			}

I
isidor 已提交
679
			return evaluateExpression(session, stackFrame, filtered[0], 'watch').then(() => {
680
				this._onDidChangeWatchExpressions.fire(filtered[0]);
E
Erich Gamma 已提交
681 682 683
			});
		}

I
isidor 已提交
684
		return TPromise.join(this.watchExpressions.map(we => evaluateExpression(session, stackFrame, we, 'watch'))).then(() => {
685
			this._onDidChangeWatchExpressions.fire();
E
Erich Gamma 已提交
686 687 688 689 690 691 692 693 694 695
		});
	}

	public clearWatchExpressionValues(): void {
		this.watchExpressions.forEach(we => {
			we.value = Expression.DEFAULT_VALUE;
			we.available = false;
			we.reference = 0;
		});

696
		this._onDidChangeWatchExpressions.fire();
E
Erich Gamma 已提交
697 698 699
	}

	public clearWatchExpressions(id: string = null): void {
700
		this.watchExpressions = id ? this.watchExpressions.filter(we => we.getId() !== id) : [];
701
		this._onDidChangeWatchExpressions.fire();
E
Erich Gamma 已提交
702 703
	}

I
isidor 已提交
704
	public sourceIsUnavailable(source: Source): void {
705
		Object.keys(this.threads).forEach(key => {
706 707 708 709 710 711 712
			if (this.threads[key].getCachedCallStack()) {
				this.threads[key].getCachedCallStack().forEach(stackFrame => {
					if (stackFrame.source.uri.toString() === source.uri.toString()) {
						stackFrame.source.available = false;
					}
				});
			}
713 714
		});

715
		this._onDidChangeCallStack.fire();
E
Erich Gamma 已提交
716 717 718 719
	}

	public rawUpdate(data: debug.IRawModelUpdate): void {
		if (data.thread) {
720
			this.threads[data.threadId] = new Thread(data.thread.name, data.thread.id);
E
Erich Gamma 已提交
721 722
		}

723 724 725 726 727 728 729 730 731 732
		if (data.stoppedDetails) {
			// Set the availability of the threads' callstacks depending on
			// whether the thread is stopped or not
			for (let ref in this.threads) {
				if (this.threads.hasOwnProperty(ref)) {
					if (data.allThreadsStopped) {
						// Only update the details if all the threads are stopped
						// because we don't want to overwrite the details of other
						// threads that have stopped for a different reason
						this.threads[ref].stoppedDetails = data.stoppedDetails;
E
Erich Gamma 已提交
733
					}
734

735 736 737 738
					this.threads[ref].stopped = data.allThreadsStopped;
					this.threads[ref].clearCallStack();
				}
			}
E
Erich Gamma 已提交
739

I
isidor 已提交
740
			this.threads[data.threadId].stoppedDetails = data.stoppedDetails;
741
			this.threads[data.threadId].stopped = true;
E
Erich Gamma 已提交
742 743
		}

744
		this._onDidChangeCallStack.fire();
E
Erich Gamma 已提交
745 746 747 748 749 750
	}

	public dispose(): void {
		this.threads = null;
		this.breakpoints = null;
		this.exceptionBreakpoints = null;
I
isidor 已提交
751
		this.functionBreakpoints = null;
E
Erich Gamma 已提交
752 753
		this.watchExpressions = null;
		this.replElements = null;
J
Joao Moreno 已提交
754
		this.toDispose = lifecycle.dispose(this.toDispose);
E
Erich Gamma 已提交
755 756
	}
}