callStackView.ts 33.3 KB
Newer Older
I
isidor 已提交
1 2 3 4 5 6
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

import * as nls from 'vs/nls';
I
isidor 已提交
7
import { RunOnceScheduler, ignoreErrors, sequence } from 'vs/base/common/async';
I
isidor 已提交
8
import * as dom from 'vs/base/browser/dom';
I
isidor 已提交
9
import { IViewletViewOptions } from 'vs/workbench/browser/parts/views/viewsViewlet';
10 11
import { IDebugService, State, IStackFrame, IDebugSession, IThread, CONTEXT_CALLSTACK_ITEM_TYPE, IDebugModel } from 'vs/workbench/contrib/debug/common/debug';
import { Thread, StackFrame, ThreadAndSessionIds } from 'vs/workbench/contrib/debug/common/debugModel';
I
isidor 已提交
12 13
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
I
isidor 已提交
14
import { MenuId, IMenu, IMenuService } from 'vs/platform/actions/common/actions';
I
isidor 已提交
15
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
16
import { renderViewTree } from 'vs/workbench/contrib/debug/browser/baseDebugView';
17
import { IAction, Action } from 'vs/base/common/actions';
18
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
19
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
20
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
S
SteVen Batten 已提交
21
import { IViewPaneOptions, ViewPane } from 'vs/workbench/browser/parts/views/viewPaneContainer';
I
isidor 已提交
22
import { ILabelService } from 'vs/platform/label/common/label';
I
isidor 已提交
23
import { IAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget';
24
import { createAndFillInContextMenuActions } from 'vs/platform/actions/browser/menuEntryActionViewItem';
I
isidor 已提交
25
import { IListVirtualDelegate } from 'vs/base/browser/ui/list/list';
J
Joao Moreno 已提交
26
import { ITreeRenderer, ITreeNode, ITreeContextMenuEvent, IAsyncDataSource } from 'vs/base/browser/ui/tree/tree';
27
import { TreeResourceNavigator2, WorkbenchAsyncDataTree } from 'vs/platform/list/browser/listService';
I
isidor 已提交
28 29
import { HighlightedLabel } from 'vs/base/browser/ui/highlightedlabel/highlightedLabel';
import { createMatches, FuzzyScore } from 'vs/base/common/filters';
I
isidor 已提交
30
import { Event } from 'vs/base/common/event';
31
import { dispose } from 'vs/base/common/lifecycle';
32 33 34 35
import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar';
import { isSessionAttach } from 'vs/workbench/contrib/debug/common/debugUtils';
import { STOP_ID, STOP_LABEL, DISCONNECT_ID, DISCONNECT_LABEL, RESTART_SESSION_ID, RESTART_LABEL, STEP_OVER_ID, STEP_OVER_LABEL, STEP_INTO_LABEL, STEP_INTO_ID, STEP_OUT_LABEL, STEP_OUT_ID, PAUSE_ID, PAUSE_LABEL, CONTINUE_ID, CONTINUE_LABEL } from 'vs/workbench/contrib/debug/browser/debugCommands';
import { ICommandService } from 'vs/platform/commands/common/commands';
I
isidor 已提交
36
import { CollapseAction } from 'vs/workbench/browser/viewlet';
37
import { SIDE_BAR_BACKGROUND } from 'vs/workbench/common/theme';
I
isidor 已提交
38

39
const $ = dom.$;
I
isidor 已提交
40

I
isidor 已提交
41 42
type CallStackItem = IStackFrame | IThread | IDebugSession | string | ThreadAndSessionIds | IStackFrame[];

I
isidor 已提交
43 44 45 46 47 48 49 50 51 52 53 54 55
function getContext(element: CallStackItem | null): any {
	return element instanceof StackFrame ? {
		sessionId: element.thread.session.getId(),
		threadId: element.thread.getId(),
		frameId: element.getId()
	} : element instanceof Thread ? {
		sessionId: element.session.getId(),
		threadId: element.getId()
	} : isDebugSession(element) ? {
		sessionId: element.getId()
	} : undefined;
}

S
SteVen Batten 已提交
56
export class CallStackView extends ViewPane {
I
isidor 已提交
57 58
	private pauseMessage!: HTMLSpanElement;
	private pauseMessageLabel!: HTMLSpanElement;
I
isidor 已提交
59
	private onCallStackChangeScheduler: RunOnceScheduler;
I
isidor 已提交
60 61 62
	private needsRefresh = false;
	private ignoreSelectionChangedEvent = false;
	private ignoreFocusStackFrameEvent = false;
63
	private callStackItemType: IContextKey<string>;
I
isidor 已提交
64 65
	private dataSource!: CallStackDataSource;
	private tree!: WorkbenchAsyncDataTree<CallStackItem | IDebugModel, CallStackItem, FuzzyScore>;
I
isidor 已提交
66
	private contributedContextMenu: IMenu;
I
isidor 已提交
67
	private parentSessionToExpand = new Set<IDebugSession>();
I
isidor 已提交
68
	private selectionNeedsUpdate = false;
I
isidor 已提交
69 70 71 72

	constructor(
		private options: IViewletViewOptions,
		@IContextMenuService contextMenuService: IContextMenuService,
73
		@IDebugService private readonly debugService: IDebugService,
I
isidor 已提交
74
		@IKeybindingService keybindingService: IKeybindingService,
75 76
		@IInstantiationService private readonly instantiationService: IInstantiationService,
		@IEditorService private readonly editorService: IEditorService,
77
		@IConfigurationService configurationService: IConfigurationService,
I
isidor 已提交
78
		@IMenuService menuService: IMenuService,
79
		@IContextKeyService readonly contextKeyService: IContextKeyService,
I
isidor 已提交
80
	) {
S
SteVen Batten 已提交
81
		super({ ...(options as IViewPaneOptions), ariaHeaderLabel: nls.localize('callstackSection', "Call Stack Section") }, keybindingService, contextMenuService, configurationService, contextKeyService);
82
		this.callStackItemType = CONTEXT_CALLSTACK_ITEM_TYPE.bindTo(contextKeyService);
I
isidor 已提交
83

I
isidor 已提交
84
		this.contributedContextMenu = menuService.createMenu(MenuId.DebugCallStackContext, contextKeyService);
M
Matt Bierner 已提交
85
		this._register(this.contributedContextMenu);
I
isidor 已提交
86

I
isidor 已提交
87 88 89 90
		// Create scheduler to prevent unnecessary flashing of tree when reacting to changes
		this.onCallStackChangeScheduler = new RunOnceScheduler(() => {
			// Only show the global pause message if we do not display threads.
			// Otherwise there will be a pause message per thread and there is no need for a global one.
I
isidor 已提交
91
			const sessions = this.debugService.getModel().getSessions();
I
isidor 已提交
92 93
			const thread = sessions.length === 1 && sessions[0].getAllThreads().length === 1 ? sessions[0].getAllThreads()[0] : undefined;
			if (thread && thread.stoppedDetails) {
I
isidor 已提交
94 95
				this.pauseMessageLabel.textContent = thread.stoppedDetails.description || nls.localize('debugStopped', "Paused on {0}", thread.stoppedDetails.reason || '');
				this.pauseMessageLabel.title = thread.stoppedDetails.text || '';
I
isidor 已提交
96
				dom.toggleClass(this.pauseMessageLabel, 'exception', thread.stoppedDetails.reason === 'exception');
97
				this.pauseMessage.hidden = false;
I
isidor 已提交
98 99 100 101
				if (this.toolbar) {
					this.toolbar.setActions([])();
				}

I
isidor 已提交
102
			} else {
103
				this.pauseMessage.hidden = true;
I
isidor 已提交
104
				if (this.toolbar) {
M
Miguel Solorio 已提交
105
					const collapseAction = new CollapseAction(this.tree, true, 'explorer-action codicon-collapse-all');
I
isidor 已提交
106 107
					this.toolbar.setActions([collapseAction])();
				}
I
isidor 已提交
108 109
			}

110
			this.needsRefresh = false;
I
isidor 已提交
111
			this.dataSource.deemphasizedStackFramesToShow = [];
I
isidor 已提交
112 113 114
			this.tree.updateChildren().then(() => {
				this.parentSessionToExpand.forEach(s => this.tree.expand(s));
				this.parentSessionToExpand.clear();
I
isidor 已提交
115 116 117 118
				if (this.selectionNeedsUpdate) {
					this.selectionNeedsUpdate = false;
					this.updateTreeSelection();
				}
I
isidor 已提交
119
			});
I
isidor 已提交
120 121 122
		}, 50);
	}

J
Jackson Kearl 已提交
123
	protected renderHeaderTitle(container: HTMLElement): void {
I
isidor 已提交
124
		const titleContainer = dom.append(container, $('.debug-call-stack-title'));
J
Jackson Kearl 已提交
125 126 127
		super.renderHeaderTitle(titleContainer, this.options.title);

		this.pauseMessage = dom.append(titleContainer, $('span.pause-message'));
128 129
		this.pauseMessage.hidden = true;
		this.pauseMessageLabel = dom.append(this.pauseMessage, $('span.label'));
I
isidor 已提交
130 131
	}

I
isidor 已提交
132
	renderBody(container: HTMLElement): void {
I
isidor 已提交
133
		dom.addClass(container, 'debug-call-stack');
I
isidor 已提交
134 135
		const treeContainer = renderViewTree(container);

I
isidor 已提交
136
		this.dataSource = new CallStackDataSource(this.debugService);
137
		this.tree = this.instantiationService.createInstance<typeof WorkbenchAsyncDataTree, WorkbenchAsyncDataTree<CallStackItem | IDebugModel, CallStackItem, FuzzyScore>>(WorkbenchAsyncDataTree, 'CallStackView', treeContainer, new CallStackDelegate(), [
I
isidor 已提交
138
			new SessionsRenderer(this.instantiationService, this.debugService),
139
			new ThreadsRenderer(this.instantiationService),
I
isidor 已提交
140 141 142 143 144
			this.instantiationService.createInstance(StackFramesRenderer),
			new ErrorsRenderer(),
			new LoadMoreRenderer(),
			new ShowMoreRenderer()
		], this.dataSource, {
M
Matt Bierner 已提交
145 146 147 148 149 150
			accessibilityProvider: new CallStackAccessibilityProvider(),
			ariaLabel: nls.localize({ comment: ['Debug is a noun in this context, not a verb.'], key: 'callStackAriaLabel' }, "Debug Call Stack"),
			identityProvider: {
				getId: (element: CallStackItem) => {
					if (typeof element === 'string') {
						return element;
151
					}
M
Matt Bierner 已提交
152 153
					if (element instanceof Array) {
						return `showMore ${element[0].getId()}`;
I
isidor 已提交
154
					}
M
Matt Bierner 已提交
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176

					return element.getId();
				}
			},
			keyboardNavigationLabelProvider: {
				getKeyboardNavigationLabel: (e: CallStackItem) => {
					if (isDebugSession(e)) {
						return e.getLabel();
					}
					if (e instanceof Thread) {
						return `${e.name} ${e.stateLabel}`;
					}
					if (e instanceof StackFrame || typeof e === 'string') {
						return e;
					}
					if (e instanceof ThreadAndSessionIds) {
						return LoadMoreRenderer.LABEL;
					}

					return nls.localize('showMoreStackFrames2', "Show More Stack Frames");
				}
			},
177 178 179 180
			expandOnlyOnTwistieClick: true,
			overrideStyles: {
				listBackground: SIDE_BAR_BACKGROUND
			}
M
Matt Bierner 已提交
181
		});
I
isidor 已提交
182

183
		this.tree.setInput(this.debugService.getModel());
J
Joao Moreno 已提交
184

I
isidor 已提交
185
		const callstackNavigator = new TreeResourceNavigator2(this.tree);
M
Matt Bierner 已提交
186 187
		this._register(callstackNavigator);
		this._register(callstackNavigator.onDidOpenResource(e => {
I
isidor 已提交
188 189 190 191
			if (this.ignoreSelectionChangedEvent) {
				return;
			}

I
isidor 已提交
192
			const focusStackFrame = (stackFrame: IStackFrame | undefined, thread: IThread | undefined, session: IDebugSession) => {
I
isidor 已提交
193 194 195 196 197 198 199 200
				this.ignoreFocusStackFrameEvent = true;
				try {
					this.debugService.focusStackFrame(stackFrame, thread, session, true);
				} finally {
					this.ignoreFocusStackFrameEvent = false;
				}
			};

I
isidor 已提交
201 202
			const element = e.element;
			if (element instanceof StackFrame) {
I
isidor 已提交
203
				focusStackFrame(element, element.thread, element.thread.session);
I
isidor 已提交
204 205 206
				element.openInEditor(this.editorService, e.editorOptions.preserveFocus, e.sideBySide, e.editorOptions.pinned);
			}
			if (element instanceof Thread) {
I
isidor 已提交
207
				focusStackFrame(undefined, element, element.session);
I
isidor 已提交
208
			}
I
isidor 已提交
209
			if (isDebugSession(element)) {
I
isidor 已提交
210
				focusStackFrame(undefined, undefined, element);
I
isidor 已提交
211 212
			}
			if (element instanceof ThreadAndSessionIds) {
213
				const session = this.debugService.getModel().getSession(element.sessionId);
I
isidor 已提交
214 215 216
				const thread = session && session.getThread(element.threadId);
				if (thread) {
					(<Thread>thread).fetchCallStack()
217
						.then(() => this.tree.updateChildren());
I
isidor 已提交
218 219 220 221
				}
			}
			if (element instanceof Array) {
				this.dataSource.deemphasizedStackFramesToShow.push(...element);
222
				this.tree.updateChildren();
I
isidor 已提交
223 224
			}
		}));
I
isidor 已提交
225

M
Matt Bierner 已提交
226
		this._register(this.debugService.getModel().onDidChangeCallStack(() => {
227
			if (!this.isBodyVisible()) {
228 229 230 231
				this.needsRefresh = true;
				return;
			}

I
isidor 已提交
232 233 234 235
			if (!this.onCallStackChangeScheduler.isScheduled()) {
				this.onCallStackChangeScheduler.schedule();
			}
		}));
I
isidor 已提交
236 237
		const onFocusChange = Event.any<any>(this.debugService.getViewModel().onDidFocusStackFrame, this.debugService.getViewModel().onDidFocusSession);
		this._register(onFocusChange(() => {
I
isidor 已提交
238 239 240
			if (this.ignoreFocusStackFrameEvent) {
				return;
			}
241
			if (!this.isBodyVisible()) {
242 243 244
				this.needsRefresh = true;
				return;
			}
I
isidor 已提交
245 246 247 248
			if (this.onCallStackChangeScheduler.isScheduled()) {
				this.selectionNeedsUpdate = true;
				return;
			}
249

250
			this.updateTreeSelection();
251
		}));
M
Matt Bierner 已提交
252
		this._register(this.tree.onContextMenu(e => this.onContextMenu(e)));
I
isidor 已提交
253 254 255

		// Schedule the update of the call stack tree if the viewlet is opened after a session started #14684
		if (this.debugService.state === State.Stopped) {
I
isidor 已提交
256
			this.onCallStackChangeScheduler.schedule(0);
I
isidor 已提交
257
		}
258

M
Matt Bierner 已提交
259
		this._register(this.onDidChangeBodyVisibility(visible => {
260 261 262 263
			if (visible && this.needsRefresh) {
				this.onCallStackChangeScheduler.schedule();
			}
		}));
I
isidor 已提交
264

M
Matt Bierner 已提交
265
		this._register(this.debugService.onDidNewSession(s => {
266
			this._register(s.onDidChangeName(() => this.tree.rerender(s)));
I
isidor 已提交
267 268 269 270 271
			if (s.parentSession) {
				// Auto expand sessions that have sub sessions
				this.parentSessionToExpand.add(s.parentSession);
			}
		}));
I
isidor 已提交
272 273
	}

274 275
	layoutBody(height: number, width: number): void {
		this.tree.layout(height, width);
S
Sandeep Somavarapu 已提交
276 277
	}

I
isidor 已提交
278 279 280 281
	focus(): void {
		this.tree.domFocus();
	}

I
isidor 已提交
282
	private updateTreeSelection(): void {
I
isidor 已提交
283
		if (!this.tree || !this.tree.getInput()) {
I
isidor 已提交
284
			// Tree not initialized yet
I
isidor 已提交
285
			return;
I
isidor 已提交
286 287
		}

I
isidor 已提交
288
		const updateSelectionAndReveal = (element: IStackFrame | IDebugSession) => {
289 290 291
			this.ignoreSelectionChangedEvent = true;
			try {
				this.tree.setSelection([element]);
I
isidor 已提交
292 293 294
				this.tree.reveal(element);
			} catch (e) { }
			finally {
295 296 297 298
				this.ignoreSelectionChangedEvent = false;
			}
		};

I
isidor 已提交
299 300 301
		const thread = this.debugService.getViewModel().focusedThread;
		const session = this.debugService.getViewModel().focusedSession;
		const stackFrame = this.debugService.getViewModel().focusedStackFrame;
I
isidor 已提交
302
		if (!thread) {
I
isidor 已提交
303
			if (!session) {
I
isidor 已提交
304 305
				this.tree.setSelection([]);
			} else {
I
isidor 已提交
306
				updateSelectionAndReveal(session);
I
isidor 已提交
307
			}
I
isidor 已提交
308
		} else {
I
isidor 已提交
309 310 311 312 313 314
			const expandPromises = [() => ignoreErrors(this.tree.expand(thread))];
			let s: IDebugSession | undefined = thread.session;
			while (s) {
				const sessionToExpand = s;
				expandPromises.push(() => ignoreErrors(this.tree.expand(sessionToExpand)));
				s = s.parentSession;
I
isidor 已提交
315
			}
I
isidor 已提交
316 317 318 319 320 321 322

			sequence(expandPromises.reverse()).then(() => {
				const toReveal = stackFrame || session;
				if (toReveal) {
					updateSelectionAndReveal(toReveal);
				}
			});
I
isidor 已提交
323
		}
I
isidor 已提交
324 325
	}

I
isidor 已提交
326 327
	private onContextMenu(e: ITreeContextMenuEvent<CallStackItem>): void {
		const element = e.element;
I
isidor 已提交
328
		if (isDebugSession(element)) {
I
isidor 已提交
329
			this.callStackItemType.set('session');
330
		} else if (element instanceof Thread) {
I
isidor 已提交
331
			this.callStackItemType.set('thread');
332
		} else if (element instanceof StackFrame) {
I
isidor 已提交
333 334 335
			this.callStackItemType.set('stackFrame');
		} else {
			this.callStackItemType.reset();
336 337
		}

338
		const actions: IAction[] = [];
I
isidor 已提交
339
		const actionsDisposable = createAndFillInContextMenuActions(this.contributedContextMenu, { arg: this.getContextForContributedActions(element), shouldForwardArgs: true }, actions, this.contextMenuService);
340

I
isidor 已提交
341 342
		this.contextMenuService.showContextMenu({
			getAnchor: () => e.anchor,
343
			getActions: () => actions,
I
isidor 已提交
344
			getActionsContext: () => getContext(element),
345
			onHide: () => dispose(actionsDisposable)
I
isidor 已提交
346
		});
347 348
	}

I
isidor 已提交
349
	private getContextForContributedActions(element: CallStackItem | null): string | number {
I
isidor 已提交
350 351
		if (element instanceof StackFrame) {
			if (element.source.inMemory) {
I
isidor 已提交
352
				return element.source.raw.path || element.source.reference || '';
I
isidor 已提交
353
			}
I
isidor 已提交
354

I
isidor 已提交
355
			return element.source.uri.toString();
I
isidor 已提交
356
		}
357
		if (element instanceof Thread) {
I
isidor 已提交
358
			return element.threadId;
359
		}
360 361 362
		if (isDebugSession(element)) {
			return element.getId();
		}
363

I
isidor 已提交
364
		return '';
365 366 367 368 369 370 371 372
	}
}

interface IThreadTemplateData {
	thread: HTMLElement;
	name: HTMLElement;
	state: HTMLElement;
	stateLabel: HTMLSpanElement;
I
isidor 已提交
373
	label: HighlightedLabel;
374
	actionBar: ActionBar;
375 376
}

I
isidor 已提交
377 378
interface ISessionTemplateData {
	session: HTMLElement;
379 380 381
	name: HTMLElement;
	state: HTMLElement;
	stateLabel: HTMLSpanElement;
I
isidor 已提交
382
	label: HighlightedLabel;
383
	actionBar: ActionBar;
384 385 386 387 388 389
}

interface IErrorTemplateData {
	label: HTMLElement;
}

I
isidor 已提交
390
interface ILabelTemplateData {
391 392 393 394 395 396 397 398
	label: HTMLElement;
}

interface IStackFrameTemplateData {
	stackFrame: HTMLElement;
	file: HTMLElement;
	fileName: HTMLElement;
	lineNumber: HTMLElement;
I
isidor 已提交
399
	label: HighlightedLabel;
I
isidor 已提交
400
	actionBar: ActionBar;
401 402
}

I
isidor 已提交
403
class SessionsRenderer implements ITreeRenderer<IDebugSession, FuzzyScore, ISessionTemplateData> {
I
isidor 已提交
404
	static readonly ID = 'session';
405

406
	constructor(
I
isidor 已提交
407 408
		private readonly instantiationService: IInstantiationService,
		private readonly debugService: IDebugService
409 410
	) { }

I
isidor 已提交
411 412
	get templateId(): string {
		return SessionsRenderer.ID;
413 414
	}

I
isidor 已提交
415
	renderTemplate(container: HTMLElement): ISessionTemplateData {
416 417 418 419 420
		const session = dom.append(container, $('.session'));
		const name = dom.append(session, $('.name'));
		const state = dom.append(session, $('.state'));
		const stateLabel = dom.append(state, $('span.label'));
		const label = new HighlightedLabel(name, false);
421
		const actionBar = new ActionBar(session);
422

423
		return { session, name, state, stateLabel, label, actionBar };
424 425
	}

426
	renderElement(element: ITreeNode<IDebugSession, FuzzyScore>, _: number, data: ISessionTemplateData): void {
I
isidor 已提交
427 428
		const session = element.element;
		data.session.title = nls.localize({ key: 'session', comment: ['Session is a noun'] }, "Session");
I
isidor 已提交
429
		data.label.set(session.getLabel(), createMatches(element.filterData));
I
isidor 已提交
430
		const thread = session.getAllThreads().filter(t => t.stopped).pop();
431

432 433 434
		data.actionBar.clear();
		const actions = getActions(this.instantiationService, element.element);
		data.actionBar.push(actions, { icon: true, label: false });
I
isidor 已提交
435
		data.stateLabel.hidden = false;
436

I
isidor 已提交
437 438 439 440 441 442 443 444 445 446
		if (thread && thread.stoppedDetails) {
			data.stateLabel.textContent = thread.stoppedDetails.description || nls.localize('debugStopped', "Paused on {0}", thread.stoppedDetails.reason || '');
		} else {
			const hasChildSessions = this.debugService.getModel().getSessions().filter(s => s.parentSession === session).length > 0;
			if (!hasChildSessions) {
				data.stateLabel.textContent = nls.localize({ key: 'running', comment: ['indicates state'] }, "Running");
			} else {
				data.stateLabel.hidden = true;
			}
		}
I
isidor 已提交
447
	}
448

I
isidor 已提交
449
	disposeTemplate(templateData: ISessionTemplateData): void {
450
		templateData.actionBar.dispose();
451
	}
I
isidor 已提交
452
}
453

I
isidor 已提交
454
class ThreadsRenderer implements ITreeRenderer<IThread, FuzzyScore, IThreadTemplateData> {
I
isidor 已提交
455 456
	static readonly ID = 'thread';

457 458
	constructor(private readonly instantiationService: IInstantiationService) { }

I
isidor 已提交
459 460
	get templateId(): string {
		return ThreadsRenderer.ID;
461 462
	}

I
isidor 已提交
463
	renderTemplate(container: HTMLElement): IThreadTemplateData {
464 465 466 467 468
		const thread = dom.append(container, $('.thread'));
		const name = dom.append(thread, $('.name'));
		const state = dom.append(thread, $('.state'));
		const stateLabel = dom.append(state, $('span.label'));
		const label = new HighlightedLabel(name, false);
469
		const actionBar = new ActionBar(thread);
470

471
		return { thread, name, state, stateLabel, label, actionBar };
472 473
	}

I
isidor 已提交
474
	renderElement(element: ITreeNode<IThread, FuzzyScore>, index: number, data: IThreadTemplateData): void {
I
isidor 已提交
475
		const thread = element.element;
476
		data.thread.title = nls.localize('thread', "Thread");
I
isidor 已提交
477
		data.label.set(thread.name, createMatches(element.filterData));
478
		data.stateLabel.textContent = thread.stateLabel;
479 480 481 482

		data.actionBar.clear();
		const actions = getActions(this.instantiationService, thread);
		data.actionBar.push(actions, { icon: true, label: false });
483 484
	}

I
isidor 已提交
485
	disposeTemplate(templateData: IThreadTemplateData): void {
486
		templateData.actionBar.dispose();
487
	}
I
isidor 已提交
488
}
489

I
isidor 已提交
490
class StackFramesRenderer implements ITreeRenderer<IStackFrame, FuzzyScore, IStackFrameTemplateData> {
I
isidor 已提交
491 492
	static readonly ID = 'stackFrame';

493
	constructor(@ILabelService private readonly labelService: ILabelService) { }
I
isidor 已提交
494 495 496 497 498 499

	get templateId(): string {
		return StackFramesRenderer.ID;
	}

	renderTemplate(container: HTMLElement): IStackFrameTemplateData {
500 501 502 503 504 505 506
		const stackFrame = dom.append(container, $('.stack-frame'));
		const labelDiv = dom.append(stackFrame, $('span.label.expression'));
		const file = dom.append(stackFrame, $('.file'));
		const fileName = dom.append(file, $('span.file-name'));
		const wrapper = dom.append(file, $('span.line-number-wrapper'));
		const lineNumber = dom.append(wrapper, $('span.line-number'));
		const label = new HighlightedLabel(labelDiv, false);
I
isidor 已提交
507
		const actionBar = new ActionBar(stackFrame);
I
isidor 已提交
508

I
isidor 已提交
509
		return { file, fileName, label, lineNumber, stackFrame, actionBar };
I
isidor 已提交
510 511
	}

I
isidor 已提交
512
	renderElement(element: ITreeNode<IStackFrame, FuzzyScore>, index: number, data: IStackFrameTemplateData): void {
I
isidor 已提交
513
		const stackFrame = element.element;
I
isidor 已提交
514 515 516
		dom.toggleClass(data.stackFrame, 'disabled', !stackFrame.source || !stackFrame.source.available || isDeemphasized(stackFrame));
		dom.toggleClass(data.stackFrame, 'label', stackFrame.presentationHint === 'label');
		dom.toggleClass(data.stackFrame, 'subtle', stackFrame.presentationHint === 'subtle');
I
isidor 已提交
517
		const hasActions = !!stackFrame.thread.session.capabilities.supportsRestartFrame && stackFrame.presentationHint !== 'label' && stackFrame.presentationHint !== 'subtle';
I
isidor 已提交
518
		dom.toggleClass(data.stackFrame, 'has-actions', hasActions);
519

I
isidor 已提交
520
		data.file.title = stackFrame.source.inMemory ? stackFrame.source.uri.path : this.labelService.getUriLabel(stackFrame.source.uri);
521 522 523
		if (stackFrame.source.raw.origin) {
			data.file.title += `\n${stackFrame.source.raw.origin}`;
		}
I
isidor 已提交
524
		data.label.set(stackFrame.name, createMatches(element.filterData), stackFrame.name);
I
isidor 已提交
525
		data.fileName.textContent = stackFrame.getSpecificSourceName();
526 527 528 529 530 531 532 533 534
		if (stackFrame.range.startLineNumber !== undefined) {
			data.lineNumber.textContent = `${stackFrame.range.startLineNumber}`;
			if (stackFrame.range.startColumn) {
				data.lineNumber.textContent += `:${stackFrame.range.startColumn}`;
			}
			dom.removeClass(data.lineNumber, 'unavailable');
		} else {
			dom.addClass(data.lineNumber, 'unavailable');
		}
I
isidor 已提交
535 536 537

		data.actionBar.clear();
		if (hasActions) {
538
			const action = new Action('debug.callStack.restartFrame', nls.localize('restartFrame', "Restart Frame"), 'codicon-debug-restart-frame', true, () => {
I
isidor 已提交
539 540 541 542
				return stackFrame.restart();
			});
			data.actionBar.push(action, { icon: true, label: false });
		}
543 544
	}

I
isidor 已提交
545
	disposeTemplate(templateData: IStackFrameTemplateData): void {
I
isidor 已提交
546
		templateData.actionBar.dispose();
I
isidor 已提交
547 548 549
	}
}

I
isidor 已提交
550
class ErrorsRenderer implements ITreeRenderer<string, FuzzyScore, IErrorTemplateData> {
I
isidor 已提交
551 552 553 554 555 556 557
	static readonly ID = 'error';

	get templateId(): string {
		return ErrorsRenderer.ID;
	}

	renderTemplate(container: HTMLElement): IErrorTemplateData {
558
		const label = dom.append(container, $('.error'));
I
isidor 已提交
559

560
		return { label };
I
isidor 已提交
561 562
	}

I
isidor 已提交
563
	renderElement(element: ITreeNode<string, FuzzyScore>, index: number, data: IErrorTemplateData): void {
I
isidor 已提交
564 565 566 567 568 569 570 571 572 573
		const error = element.element;
		data.label.textContent = error;
		data.label.title = error;
	}

	disposeTemplate(templateData: IErrorTemplateData): void {
		// noop
	}
}

I
isidor 已提交
574
class LoadMoreRenderer implements ITreeRenderer<ThreadAndSessionIds, FuzzyScore, ILabelTemplateData> {
I
isidor 已提交
575
	static readonly ID = 'loadMore';
I
isidor 已提交
576
	static readonly LABEL = nls.localize('loadMoreStackFrames', "Load More Stack Frames");
I
isidor 已提交
577 578 579 580 581 582

	get templateId(): string {
		return LoadMoreRenderer.ID;
	}

	renderTemplate(container: HTMLElement): IErrorTemplateData {
583
		const label = dom.append(container, $('.load-more'));
I
isidor 已提交
584

585
		return { label };
I
isidor 已提交
586 587
	}

I
isidor 已提交
588
	renderElement(element: ITreeNode<ThreadAndSessionIds, FuzzyScore>, index: number, data: ILabelTemplateData): void {
I
isidor 已提交
589
		data.label.textContent = LoadMoreRenderer.LABEL;
I
isidor 已提交
590 591 592 593 594 595 596
	}

	disposeTemplate(templateData: ILabelTemplateData): void {
		// noop
	}
}

I
isidor 已提交
597
class ShowMoreRenderer implements ITreeRenderer<IStackFrame[], FuzzyScore, ILabelTemplateData> {
I
isidor 已提交
598 599 600 601 602 603 604
	static readonly ID = 'showMore';

	get templateId(): string {
		return ShowMoreRenderer.ID;
	}

	renderTemplate(container: HTMLElement): IErrorTemplateData {
605
		const label = dom.append(container, $('.show-more'));
I
isidor 已提交
606

607
		return { label };
I
isidor 已提交
608 609
	}

I
isidor 已提交
610
	renderElement(element: ITreeNode<IStackFrame[], FuzzyScore>, index: number, data: ILabelTemplateData): void {
I
isidor 已提交
611
		const stackFrames = element.element;
612
		if (stackFrames.every(sf => !!(sf.source && sf.source.origin && sf.source.origin === stackFrames[0].source.origin))) {
I
isidor 已提交
613 614 615 616 617 618 619
			data.label.textContent = nls.localize('showMoreAndOrigin', "Show {0} More: {1}", stackFrames.length, stackFrames[0].source.origin);
		} else {
			data.label.textContent = nls.localize('showMoreStackFrames', "Show {0} More Stack Frames", stackFrames.length);
		}
	}

	disposeTemplate(templateData: ILabelTemplateData): void {
620 621 622 623
		// noop
	}
}

I
isidor 已提交
624 625 626 627 628 629 630
class CallStackDelegate implements IListVirtualDelegate<CallStackItem> {

	getHeight(element: CallStackItem): number {
		return 22;
	}

	getTemplateId(element: CallStackItem): string {
I
isidor 已提交
631
		if (isDebugSession(element)) {
I
isidor 已提交
632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
			return SessionsRenderer.ID;
		}
		if (element instanceof Thread) {
			return ThreadsRenderer.ID;
		}
		if (element instanceof StackFrame) {
			return StackFramesRenderer.ID;
		}
		if (typeof element === 'string') {
			return ErrorsRenderer.ID;
		}
		if (element instanceof ThreadAndSessionIds) {
			return LoadMoreRenderer.ID;
		}

I
isidor 已提交
647 648
		// element instanceof Array
		return ShowMoreRenderer.ID;
I
isidor 已提交
649 650 651
	}
}

J
Joao Moreno 已提交
652 653 654
function isDebugModel(obj: any): obj is IDebugModel {
	return typeof obj.getSessions === 'function';
}
I
isidor 已提交
655

I
isidor 已提交
656
function isDebugSession(obj: any): obj is IDebugSession {
I
isidor 已提交
657
	return obj && typeof obj.getAllThreads === 'function';
I
isidor 已提交
658 659
}

660 661 662 663
function isDeemphasized(frame: IStackFrame): boolean {
	return frame.source.presentationHint === 'deemphasize' || frame.presentationHint === 'deemphasize';
}

J
Joao Moreno 已提交
664
class CallStackDataSource implements IAsyncDataSource<IDebugModel, CallStackItem> {
I
isidor 已提交
665
	deemphasizedStackFramesToShow: IStackFrame[] = [];
I
isidor 已提交
666

I
isidor 已提交
667 668
	constructor(private debugService: IDebugService) { }

J
Joao Moreno 已提交
669
	hasChildren(element: IDebugModel | CallStackItem): boolean {
670 671 672 673 674 675
		if (isDebugSession(element)) {
			const threads = element.getAllThreads();
			return (threads.length > 1) || (threads.length === 1 && threads[0].stopped) || (this.debugService.getModel().getSessions().filter(s => s.parentSession === element).length > 0);
		}

		return isDebugModel(element) || (element instanceof Thread && element.stopped);
I
isidor 已提交
676 677
	}

678
	async getChildren(element: IDebugModel | CallStackItem): Promise<CallStackItem[]> {
J
Joao Moreno 已提交
679 680
		if (isDebugModel(element)) {
			const sessions = element.getSessions();
681 682 683
			if (sessions.length === 0) {
				return Promise.resolve([]);
			}
684
			if (sessions.length > 1 || this.debugService.getViewModel().isMultiSessionView()) {
I
isidor 已提交
685
				return Promise.resolve(sessions.filter(s => !s.parentSession));
I
isidor 已提交
686 687 688 689 690
			}

			const threads = sessions[0].getAllThreads();
			// Only show the threads in the call stack if there is more than 1 thread.
			return threads.length === 1 ? this.getThreadChildren(<Thread>threads[0]) : Promise.resolve(threads);
I
isidor 已提交
691
		} else if (isDebugSession(element)) {
I
isidor 已提交
692
			const childSessions = this.debugService.getModel().getSessions().filter(s => s.parentSession === element);
I
isidor 已提交
693
			const threads: CallStackItem[] = element.getAllThreads();
694
			if (threads.length === 1) {
695
				// Do not show thread when there is only one to be compact.
696 697
				const children = await this.getThreadChildren(<Thread>threads[0]);
				return children.concat(childSessions);
698
			}
I
isidor 已提交
699

I
isidor 已提交
700
			return Promise.resolve(threads.concat(childSessions));
J
Joao Moreno 已提交
701 702
		} else {
			return this.getThreadChildren(<Thread>element);
I
isidor 已提交
703 704 705
		}
	}

I
isidor 已提交
706
	private getThreadChildren(thread: Thread): Promise<CallStackItem[]> {
I
isidor 已提交
707 708
		return this.getThreadCallstack(thread).then(children => {
			// Check if some stack frames should be hidden under a parent element since they are deemphasized
I
isidor 已提交
709
			const result: CallStackItem[] = [];
I
isidor 已提交
710
			children.forEach((child, index) => {
711
				if (child instanceof StackFrame && child.source && isDeemphasized(child)) {
I
isidor 已提交
712 713
					// Check if the user clicked to show the deemphasized source
					if (this.deemphasizedStackFramesToShow.indexOf(child) === -1) {
I
isidor 已提交
714 715 716 717 718 719 720
						if (result.length) {
							const last = result[result.length - 1];
							if (last instanceof Array) {
								// Collect all the stackframes that will be "collapsed"
								last.push(child);
								return;
							}
I
isidor 已提交
721 722 723
						}

						const nextChild = index < children.length - 1 ? children[index + 1] : undefined;
724
						if (nextChild instanceof StackFrame && nextChild.source && isDeemphasized(nextChild)) {
I
isidor 已提交
725 726 727 728 729 730 731 732 733 734 735 736 737 738
							// Start collecting stackframes that will be "collapsed"
							result.push([child]);
							return;
						}
					}
				}

				result.push(child);
			});

			return result;
		});
	}

739
	private getThreadCallstack(thread: Thread): Promise<Array<IStackFrame | string | ThreadAndSessionIds>> {
I
isidor 已提交
740 741 742 743 744 745 746
		let callStack: any[] = thread.getCallStack();
		let callStackPromise: Promise<any> = Promise.resolve(null);
		if (!callStack || !callStack.length) {
			callStackPromise = thread.fetchCallStack().then(() => callStack = thread.getCallStack());
		}

		return callStackPromise.then(() => {
I
isidor 已提交
747
			if (callStack.length === 1 && thread.session.capabilities.supportsDelayedStackTraceLoading && thread.stoppedDetails && thread.stoppedDetails.totalFrames && thread.stoppedDetails.totalFrames > 1) {
I
isidor 已提交
748 749 750 751 752 753 754 755
				// To reduce flashing of the call stack view simply append the stale call stack
				// once we have the correct data the tree will refresh and we will no longer display it.
				callStack = callStack.concat(thread.getStaleCallStack().slice(1));
			}

			if (thread.stoppedDetails && thread.stoppedDetails.framesErrorMessage) {
				callStack = callStack.concat([thread.stoppedDetails.framesErrorMessage]);
			}
I
isidor 已提交
756
			if (thread.stoppedDetails && thread.stoppedDetails.totalFrames && thread.stoppedDetails.totalFrames > callStack.length && callStack.length > 1) {
I
isidor 已提交
757 758 759 760 761 762 763 764 765 766
				callStack = callStack.concat([new ThreadAndSessionIds(thread.session.getId(), thread.threadId)]);
			}

			return callStack;
		});
	}
}

class CallStackAccessibilityProvider implements IAccessibilityProvider<CallStackItem> {
	getAriaLabel(element: CallStackItem): string {
767 768 769 770
		if (element instanceof Thread) {
			return nls.localize('threadAriaLabel', "Thread {0}, callstack, debug", (<Thread>element).name);
		}
		if (element instanceof StackFrame) {
I
isidor 已提交
771
			return nls.localize('stackFrameAriaLabel', "Stack Frame {0} line {1} {2}, callstack, debug", element.name, element.range.startLineNumber, element.getSpecificSourceName());
772
		}
I
isidor 已提交
773
		if (isDebugSession(element)) {
I
isidor 已提交
774 775 776 777 778 779 780 781
			return nls.localize('sessionLabel', "Debug Session {0}", element.getLabel());
		}
		if (typeof element === 'string') {
			return element;
		}
		if (element instanceof Array) {
			return nls.localize('showMoreStackFrames', "Show {0} More Stack Frames", element.length);
		}
782

I
isidor 已提交
783 784
		// element instanceof ThreadAndSessionIds
		return nls.localize('loadMoreStackFrames', "Load More Stack Frames");
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 817 818 819 820 821 822 823 824 825

function getActions(instantiationService: IInstantiationService, element: IDebugSession | IThread): IAction[] {
	const getThreadActions = (thread: IThread): IAction[] => {
		return [
			thread.stopped ? instantiationService.createInstance(ContinueAction, thread) : instantiationService.createInstance(PauseAction, thread),
			instantiationService.createInstance(StepOverAction, thread),
			instantiationService.createInstance(StepIntoAction, thread),
			instantiationService.createInstance(StepOutAction, thread)
		];
	};

	if (element instanceof Thread) {
		return getThreadActions(element);
	}

	const session = <IDebugSession>element;
	const stopOrDisconectAction = isSessionAttach(session) ? instantiationService.createInstance(DisconnectAction, session) : instantiationService.createInstance(StopAction, session);
	const restartAction = instantiationService.createInstance(RestartAction, session);
	const threads = session.getAllThreads();
	if (threads.length === 1) {
		return getThreadActions(threads[0]).concat([
			restartAction,
			stopOrDisconectAction
		]);
	}

	return [
		restartAction,
		stopOrDisconectAction
	];
}


class StopAction extends Action {

	constructor(
		private readonly session: IDebugSession,
		@ICommandService private readonly commandService: ICommandService
	) {
M
Miguel Solorio 已提交
826
		super(`action.${STOP_ID}`, STOP_LABEL, 'debug-action codicon-debug-stop');
827 828 829
	}

	public run(): Promise<any> {
I
isidor 已提交
830
		return this.commandService.executeCommand(STOP_ID, undefined, getContext(this.session));
831 832 833 834 835 836 837 838 839
	}
}

class DisconnectAction extends Action {

	constructor(
		private readonly session: IDebugSession,
		@ICommandService private readonly commandService: ICommandService
	) {
I
isidor 已提交
840
		super(`action.${DISCONNECT_ID}`, DISCONNECT_LABEL, 'debug-action codicon-debug-disconnect');
841 842 843
	}

	public run(): Promise<any> {
I
isidor 已提交
844
		return this.commandService.executeCommand(DISCONNECT_ID, undefined, getContext(this.session));
845 846 847 848 849 850 851 852 853
	}
}

class RestartAction extends Action {

	constructor(
		private readonly session: IDebugSession,
		@ICommandService private readonly commandService: ICommandService
	) {
M
Miguel Solorio 已提交
854
		super(`action.${RESTART_SESSION_ID}`, RESTART_LABEL, 'debug-action codicon-debug-restart');
855 856 857
	}

	public run(): Promise<any> {
I
isidor 已提交
858
		return this.commandService.executeCommand(RESTART_SESSION_ID, undefined, getContext(this.session));
859 860 861 862 863 864 865 866 867
	}
}

class StepOverAction extends Action {

	constructor(
		private readonly thread: IThread,
		@ICommandService private readonly commandService: ICommandService
	) {
M
Miguel Solorio 已提交
868
		super(`action.${STEP_OVER_ID}`, STEP_OVER_LABEL, 'debug-action codicon-debug-step-over', thread.stopped);
869 870 871
	}

	public run(): Promise<any> {
I
isidor 已提交
872
		return this.commandService.executeCommand(STEP_OVER_ID, undefined, getContext(this.thread));
873 874 875 876 877 878 879 880 881
	}
}

class StepIntoAction extends Action {

	constructor(
		private readonly thread: IThread,
		@ICommandService private readonly commandService: ICommandService
	) {
M
Miguel Solorio 已提交
882
		super(`action.${STEP_INTO_ID}`, STEP_INTO_LABEL, 'debug-action codicon-debug-step-into', thread.stopped);
883 884 885
	}

	public run(): Promise<any> {
I
isidor 已提交
886
		return this.commandService.executeCommand(STEP_INTO_ID, undefined, getContext(this.thread));
887 888 889 890 891 892 893 894 895
	}
}

class StepOutAction extends Action {

	constructor(
		private readonly thread: IThread,
		@ICommandService private readonly commandService: ICommandService
	) {
M
Miguel Solorio 已提交
896
		super(`action.${STEP_OUT_ID}`, STEP_OUT_LABEL, 'debug-action codicon-debug-step-out', thread.stopped);
897 898 899
	}

	public run(): Promise<any> {
I
isidor 已提交
900
		return this.commandService.executeCommand(STEP_OUT_ID, undefined, getContext(this.thread));
901 902 903 904 905 906 907 908 909
	}
}

class PauseAction extends Action {

	constructor(
		private readonly thread: IThread,
		@ICommandService private readonly commandService: ICommandService
	) {
M
Miguel Solorio 已提交
910
		super(`action.${PAUSE_ID}`, PAUSE_LABEL, 'debug-action codicon-debug-pause', !thread.stopped);
911 912 913
	}

	public run(): Promise<any> {
I
isidor 已提交
914
		return this.commandService.executeCommand(PAUSE_ID, undefined, getContext(this.thread));
915 916 917 918 919 920 921 922 923
	}
}

class ContinueAction extends Action {

	constructor(
		private readonly thread: IThread,
		@ICommandService private readonly commandService: ICommandService
	) {
M
Miguel Solorio 已提交
924
		super(`action.${CONTINUE_ID}`, CONTINUE_LABEL, 'debug-action codicon-debug-continue', thread.stopped);
925 926 927
	}

	public run(): Promise<any> {
I
isidor 已提交
928
		return this.commandService.executeCommand(CONTINUE_ID, undefined, getContext(this.thread));
929 930
	}
}