callStackView.ts 33.7 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 { TreeResourceNavigator, 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';
38
import { IViewDescriptorService } from 'vs/workbench/common/views';
I
isidor 已提交
39

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

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

I
isidor 已提交
44
export function getContext(element: CallStackItem | null): any {
I
isidor 已提交
45 46 47 48 49 50 51 52 53 54 55 56
	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;
}

I
isidor 已提交
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
// Extensions depend on this context, should not be changed even though it is not fully deterministic
export function getContextForContributedActions(element: CallStackItem | null): string | number {
	if (element instanceof StackFrame) {
		if (element.source.inMemory) {
			return element.source.raw.path || element.source.reference || '';
		}

		return element.source.uri.toString();
	}
	if (element instanceof Thread) {
		return element.threadId;
	}
	if (isDebugSession(element)) {
		return element.getId();
	}

	return '';
}

S
SteVen Batten 已提交
76
export class CallStackView extends ViewPane {
I
isidor 已提交
77 78
	private pauseMessage!: HTMLSpanElement;
	private pauseMessageLabel!: HTMLSpanElement;
I
isidor 已提交
79
	private onCallStackChangeScheduler: RunOnceScheduler;
I
isidor 已提交
80 81 82
	private needsRefresh = false;
	private ignoreSelectionChangedEvent = false;
	private ignoreFocusStackFrameEvent = false;
83
	private callStackItemType: IContextKey<string>;
I
isidor 已提交
84 85
	private dataSource!: CallStackDataSource;
	private tree!: WorkbenchAsyncDataTree<CallStackItem | IDebugModel, CallStackItem, FuzzyScore>;
I
isidor 已提交
86
	private contributedContextMenu: IMenu;
I
isidor 已提交
87
	private parentSessionToExpand = new Set<IDebugSession>();
I
isidor 已提交
88
	private selectionNeedsUpdate = false;
I
isidor 已提交
89 90 91 92

	constructor(
		private options: IViewletViewOptions,
		@IContextMenuService contextMenuService: IContextMenuService,
93
		@IDebugService private readonly debugService: IDebugService,
I
isidor 已提交
94
		@IKeybindingService keybindingService: IKeybindingService,
95
		@IInstantiationService instantiationService: IInstantiationService,
96
		@IViewDescriptorService viewDescriptorService: IViewDescriptorService,
97
		@IEditorService private readonly editorService: IEditorService,
98
		@IConfigurationService configurationService: IConfigurationService,
I
isidor 已提交
99
		@IMenuService menuService: IMenuService,
100
		@IContextKeyService readonly contextKeyService: IContextKeyService,
I
isidor 已提交
101
	) {
102
		super({ ...(options as IViewPaneOptions), ariaHeaderLabel: nls.localize('callstackSection', "Call Stack Section") }, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService);
103
		this.callStackItemType = CONTEXT_CALLSTACK_ITEM_TYPE.bindTo(contextKeyService);
I
isidor 已提交
104

I
isidor 已提交
105
		this.contributedContextMenu = menuService.createMenu(MenuId.DebugCallStackContext, contextKeyService);
M
Matt Bierner 已提交
106
		this._register(this.contributedContextMenu);
I
isidor 已提交
107

I
isidor 已提交
108 109 110 111
		// 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 已提交
112
			const sessions = this.debugService.getModel().getSessions();
I
isidor 已提交
113 114
			const thread = sessions.length === 1 && sessions[0].getAllThreads().length === 1 ? sessions[0].getAllThreads()[0] : undefined;
			if (thread && thread.stoppedDetails) {
I
isidor 已提交
115 116
				this.pauseMessageLabel.textContent = thread.stoppedDetails.description || nls.localize('debugStopped', "Paused on {0}", thread.stoppedDetails.reason || '');
				this.pauseMessageLabel.title = thread.stoppedDetails.text || '';
I
isidor 已提交
117
				dom.toggleClass(this.pauseMessageLabel, 'exception', thread.stoppedDetails.reason === 'exception');
118
				this.pauseMessage.hidden = false;
I
isidor 已提交
119 120 121 122
				if (this.toolbar) {
					this.toolbar.setActions([])();
				}

I
isidor 已提交
123
			} else {
124
				this.pauseMessage.hidden = true;
I
isidor 已提交
125
				if (this.toolbar) {
M
Miguel Solorio 已提交
126
					const collapseAction = new CollapseAction(this.tree, true, 'explorer-action codicon-collapse-all');
I
isidor 已提交
127 128
					this.toolbar.setActions([collapseAction])();
				}
I
isidor 已提交
129 130
			}

131
			this.needsRefresh = false;
I
isidor 已提交
132
			this.dataSource.deemphasizedStackFramesToShow = [];
I
isidor 已提交
133 134 135
			this.tree.updateChildren().then(() => {
				this.parentSessionToExpand.forEach(s => this.tree.expand(s));
				this.parentSessionToExpand.clear();
I
isidor 已提交
136 137 138 139
				if (this.selectionNeedsUpdate) {
					this.selectionNeedsUpdate = false;
					this.updateTreeSelection();
				}
I
isidor 已提交
140
			});
I
isidor 已提交
141 142 143
		}, 50);
	}

J
Jackson Kearl 已提交
144
	protected renderHeaderTitle(container: HTMLElement): void {
I
isidor 已提交
145
		const titleContainer = dom.append(container, $('.debug-call-stack-title'));
J
Jackson Kearl 已提交
146 147 148
		super.renderHeaderTitle(titleContainer, this.options.title);

		this.pauseMessage = dom.append(titleContainer, $('span.pause-message'));
149 150
		this.pauseMessage.hidden = true;
		this.pauseMessageLabel = dom.append(this.pauseMessage, $('span.label'));
I
isidor 已提交
151 152
	}

I
isidor 已提交
153
	renderBody(container: HTMLElement): void {
I
isidor 已提交
154
		dom.addClass(container, 'debug-call-stack');
I
isidor 已提交
155 156
		const treeContainer = renderViewTree(container);

I
isidor 已提交
157
		this.dataSource = new CallStackDataSource(this.debugService);
158
		this.tree = this.instantiationService.createInstance<typeof WorkbenchAsyncDataTree, WorkbenchAsyncDataTree<CallStackItem | IDebugModel, CallStackItem, FuzzyScore>>(WorkbenchAsyncDataTree, 'CallStackView', treeContainer, new CallStackDelegate(), [
I
isidor 已提交
159
			new SessionsRenderer(this.instantiationService, this.debugService),
160
			new ThreadsRenderer(this.instantiationService),
I
isidor 已提交
161 162 163 164 165
			this.instantiationService.createInstance(StackFramesRenderer),
			new ErrorsRenderer(),
			new LoadMoreRenderer(),
			new ShowMoreRenderer()
		], this.dataSource, {
M
Matt Bierner 已提交
166 167 168 169 170 171
			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;
172
					}
M
Matt Bierner 已提交
173 174
					if (element instanceof Array) {
						return `showMore ${element[0].getId()}`;
I
isidor 已提交
175
					}
M
Matt Bierner 已提交
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197

					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");
				}
			},
198 199 200 201
			expandOnlyOnTwistieClick: true,
			overrideStyles: {
				listBackground: SIDE_BAR_BACKGROUND
			}
M
Matt Bierner 已提交
202
		});
I
isidor 已提交
203

204
		this.tree.setInput(this.debugService.getModel());
J
Joao Moreno 已提交
205

206
		const callstackNavigator = new TreeResourceNavigator(this.tree);
M
Matt Bierner 已提交
207 208
		this._register(callstackNavigator);
		this._register(callstackNavigator.onDidOpenResource(e => {
I
isidor 已提交
209 210 211 212
			if (this.ignoreSelectionChangedEvent) {
				return;
			}

I
isidor 已提交
213
			const focusStackFrame = (stackFrame: IStackFrame | undefined, thread: IThread | undefined, session: IDebugSession) => {
I
isidor 已提交
214 215 216 217 218 219 220 221
				this.ignoreFocusStackFrameEvent = true;
				try {
					this.debugService.focusStackFrame(stackFrame, thread, session, true);
				} finally {
					this.ignoreFocusStackFrameEvent = false;
				}
			};

I
isidor 已提交
222 223
			const element = e.element;
			if (element instanceof StackFrame) {
I
isidor 已提交
224
				focusStackFrame(element, element.thread, element.thread.session);
I
isidor 已提交
225 226 227
				element.openInEditor(this.editorService, e.editorOptions.preserveFocus, e.sideBySide, e.editorOptions.pinned);
			}
			if (element instanceof Thread) {
I
isidor 已提交
228
				focusStackFrame(undefined, element, element.session);
I
isidor 已提交
229
			}
I
isidor 已提交
230
			if (isDebugSession(element)) {
I
isidor 已提交
231
				focusStackFrame(undefined, undefined, element);
I
isidor 已提交
232 233
			}
			if (element instanceof ThreadAndSessionIds) {
234
				const session = this.debugService.getModel().getSession(element.sessionId);
I
isidor 已提交
235 236 237
				const thread = session && session.getThread(element.threadId);
				if (thread) {
					(<Thread>thread).fetchCallStack()
238
						.then(() => this.tree.updateChildren());
I
isidor 已提交
239 240 241 242
				}
			}
			if (element instanceof Array) {
				this.dataSource.deemphasizedStackFramesToShow.push(...element);
243
				this.tree.updateChildren();
I
isidor 已提交
244 245
			}
		}));
I
isidor 已提交
246

M
Matt Bierner 已提交
247
		this._register(this.debugService.getModel().onDidChangeCallStack(() => {
248
			if (!this.isBodyVisible()) {
249 250 251 252
				this.needsRefresh = true;
				return;
			}

I
isidor 已提交
253 254 255 256
			if (!this.onCallStackChangeScheduler.isScheduled()) {
				this.onCallStackChangeScheduler.schedule();
			}
		}));
I
isidor 已提交
257 258
		const onFocusChange = Event.any<any>(this.debugService.getViewModel().onDidFocusStackFrame, this.debugService.getViewModel().onDidFocusSession);
		this._register(onFocusChange(() => {
I
isidor 已提交
259 260 261
			if (this.ignoreFocusStackFrameEvent) {
				return;
			}
262
			if (!this.isBodyVisible()) {
263 264 265
				this.needsRefresh = true;
				return;
			}
I
isidor 已提交
266 267 268 269
			if (this.onCallStackChangeScheduler.isScheduled()) {
				this.selectionNeedsUpdate = true;
				return;
			}
270

271
			this.updateTreeSelection();
272
		}));
M
Matt Bierner 已提交
273
		this._register(this.tree.onContextMenu(e => this.onContextMenu(e)));
I
isidor 已提交
274 275 276

		// 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 已提交
277
			this.onCallStackChangeScheduler.schedule(0);
I
isidor 已提交
278
		}
279

M
Matt Bierner 已提交
280
		this._register(this.onDidChangeBodyVisibility(visible => {
281 282 283 284
			if (visible && this.needsRefresh) {
				this.onCallStackChangeScheduler.schedule();
			}
		}));
I
isidor 已提交
285

M
Matt Bierner 已提交
286
		this._register(this.debugService.onDidNewSession(s => {
287
			this._register(s.onDidChangeName(() => this.tree.rerender(s)));
I
isidor 已提交
288 289 290 291 292
			if (s.parentSession) {
				// Auto expand sessions that have sub sessions
				this.parentSessionToExpand.add(s.parentSession);
			}
		}));
I
isidor 已提交
293 294
	}

295 296
	layoutBody(height: number, width: number): void {
		this.tree.layout(height, width);
S
Sandeep Somavarapu 已提交
297 298
	}

I
isidor 已提交
299 300 301 302
	focus(): void {
		this.tree.domFocus();
	}

I
isidor 已提交
303
	private updateTreeSelection(): void {
I
isidor 已提交
304
		if (!this.tree || !this.tree.getInput()) {
I
isidor 已提交
305
			// Tree not initialized yet
I
isidor 已提交
306
			return;
I
isidor 已提交
307 308
		}

I
isidor 已提交
309
		const updateSelectionAndReveal = (element: IStackFrame | IDebugSession) => {
310 311 312
			this.ignoreSelectionChangedEvent = true;
			try {
				this.tree.setSelection([element]);
313 314 315 316 317 318 319
				// If the element is outside of the screen bounds,
				// position it in the middle
				if (this.tree.getRelativeTop(element) === null) {
					this.tree.reveal(element, 0.5);
				} else {
					this.tree.reveal(element);
				}
I
isidor 已提交
320 321
			} catch (e) { }
			finally {
322 323 324 325
				this.ignoreSelectionChangedEvent = false;
			}
		};

I
isidor 已提交
326 327 328
		const thread = this.debugService.getViewModel().focusedThread;
		const session = this.debugService.getViewModel().focusedSession;
		const stackFrame = this.debugService.getViewModel().focusedStackFrame;
I
isidor 已提交
329
		if (!thread) {
I
isidor 已提交
330
			if (!session) {
I
isidor 已提交
331 332
				this.tree.setSelection([]);
			} else {
I
isidor 已提交
333
				updateSelectionAndReveal(session);
I
isidor 已提交
334
			}
I
isidor 已提交
335
		} else {
I
isidor 已提交
336 337 338 339 340 341
			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 已提交
342
			}
I
isidor 已提交
343 344 345 346 347 348 349

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

I
isidor 已提交
353 354
	private onContextMenu(e: ITreeContextMenuEvent<CallStackItem>): void {
		const element = e.element;
I
isidor 已提交
355
		if (isDebugSession(element)) {
I
isidor 已提交
356
			this.callStackItemType.set('session');
357
		} else if (element instanceof Thread) {
I
isidor 已提交
358
			this.callStackItemType.set('thread');
359
		} else if (element instanceof StackFrame) {
I
isidor 已提交
360 361 362
			this.callStackItemType.set('stackFrame');
		} else {
			this.callStackItemType.reset();
363 364
		}

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

I
isidor 已提交
368 369
		this.contextMenuService.showContextMenu({
			getAnchor: () => e.anchor,
370
			getActions: () => actions,
I
isidor 已提交
371
			getActionsContext: () => getContext(element),
372
			onHide: () => dispose(actionsDisposable)
I
isidor 已提交
373
		});
374 375 376 377 378 379 380 381
	}
}

interface IThreadTemplateData {
	thread: HTMLElement;
	name: HTMLElement;
	state: HTMLElement;
	stateLabel: HTMLSpanElement;
I
isidor 已提交
382
	label: HighlightedLabel;
383
	actionBar: ActionBar;
384 385
}

I
isidor 已提交
386 387
interface ISessionTemplateData {
	session: HTMLElement;
388 389 390
	name: HTMLElement;
	state: HTMLElement;
	stateLabel: HTMLSpanElement;
I
isidor 已提交
391
	label: HighlightedLabel;
392
	actionBar: ActionBar;
393 394 395 396 397 398
}

interface IErrorTemplateData {
	label: HTMLElement;
}

I
isidor 已提交
399
interface ILabelTemplateData {
400 401 402 403 404 405 406 407
	label: HTMLElement;
}

interface IStackFrameTemplateData {
	stackFrame: HTMLElement;
	file: HTMLElement;
	fileName: HTMLElement;
	lineNumber: HTMLElement;
I
isidor 已提交
408
	label: HighlightedLabel;
I
isidor 已提交
409
	actionBar: ActionBar;
410 411
}

I
isidor 已提交
412
class SessionsRenderer implements ITreeRenderer<IDebugSession, FuzzyScore, ISessionTemplateData> {
I
isidor 已提交
413
	static readonly ID = 'session';
414

415
	constructor(
I
isidor 已提交
416 417
		private readonly instantiationService: IInstantiationService,
		private readonly debugService: IDebugService
418 419
	) { }

I
isidor 已提交
420 421
	get templateId(): string {
		return SessionsRenderer.ID;
422 423
	}

I
isidor 已提交
424
	renderTemplate(container: HTMLElement): ISessionTemplateData {
425 426 427 428 429
		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);
430
		const actionBar = new ActionBar(session);
431

432
		return { session, name, state, stateLabel, label, actionBar };
433 434
	}

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

441 442 443
		data.actionBar.clear();
		const actions = getActions(this.instantiationService, element.element);
		data.actionBar.push(actions, { icon: true, label: false });
I
isidor 已提交
444
		data.stateLabel.hidden = false;
445

I
isidor 已提交
446 447 448 449 450 451 452 453 454 455
		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 已提交
456
	}
457

I
isidor 已提交
458
	disposeTemplate(templateData: ISessionTemplateData): void {
459
		templateData.actionBar.dispose();
460
	}
I
isidor 已提交
461
}
462

I
isidor 已提交
463
class ThreadsRenderer implements ITreeRenderer<IThread, FuzzyScore, IThreadTemplateData> {
I
isidor 已提交
464 465
	static readonly ID = 'thread';

466 467
	constructor(private readonly instantiationService: IInstantiationService) { }

I
isidor 已提交
468 469
	get templateId(): string {
		return ThreadsRenderer.ID;
470 471
	}

I
isidor 已提交
472
	renderTemplate(container: HTMLElement): IThreadTemplateData {
473 474 475 476 477
		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);
478
		const actionBar = new ActionBar(thread);
479

480
		return { thread, name, state, stateLabel, label, actionBar };
481 482
	}

I
isidor 已提交
483
	renderElement(element: ITreeNode<IThread, FuzzyScore>, index: number, data: IThreadTemplateData): void {
I
isidor 已提交
484
		const thread = element.element;
485
		data.thread.title = nls.localize('thread', "Thread");
I
isidor 已提交
486
		data.label.set(thread.name, createMatches(element.filterData));
487
		data.stateLabel.textContent = thread.stateLabel;
488 489 490 491

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

I
isidor 已提交
494
	disposeTemplate(templateData: IThreadTemplateData): void {
495
		templateData.actionBar.dispose();
496
	}
I
isidor 已提交
497
}
498

I
isidor 已提交
499
class StackFramesRenderer implements ITreeRenderer<IStackFrame, FuzzyScore, IStackFrameTemplateData> {
I
isidor 已提交
500 501
	static readonly ID = 'stackFrame';

502
	constructor(@ILabelService private readonly labelService: ILabelService) { }
I
isidor 已提交
503 504 505 506 507 508

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

	renderTemplate(container: HTMLElement): IStackFrameTemplateData {
509 510 511 512 513 514 515
		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 已提交
516
		const actionBar = new ActionBar(stackFrame);
I
isidor 已提交
517

I
isidor 已提交
518
		return { file, fileName, label, lineNumber, stackFrame, actionBar };
I
isidor 已提交
519 520
	}

I
isidor 已提交
521
	renderElement(element: ITreeNode<IStackFrame, FuzzyScore>, index: number, data: IStackFrameTemplateData): void {
I
isidor 已提交
522
		const stackFrame = element.element;
I
isidor 已提交
523 524 525
		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 已提交
526
		const hasActions = !!stackFrame.thread.session.capabilities.supportsRestartFrame && stackFrame.presentationHint !== 'label' && stackFrame.presentationHint !== 'subtle';
I
isidor 已提交
527
		dom.toggleClass(data.stackFrame, 'has-actions', hasActions);
528

I
isidor 已提交
529
		data.file.title = stackFrame.source.inMemory ? stackFrame.source.uri.path : this.labelService.getUriLabel(stackFrame.source.uri);
530 531 532
		if (stackFrame.source.raw.origin) {
			data.file.title += `\n${stackFrame.source.raw.origin}`;
		}
I
isidor 已提交
533
		data.label.set(stackFrame.name, createMatches(element.filterData), stackFrame.name);
I
isidor 已提交
534
		data.fileName.textContent = stackFrame.getSpecificSourceName();
535 536 537 538 539 540 541 542 543
		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 已提交
544 545 546

		data.actionBar.clear();
		if (hasActions) {
547
			const action = new Action('debug.callStack.restartFrame', nls.localize('restartFrame', "Restart Frame"), 'codicon-debug-restart-frame', true, () => {
I
isidor 已提交
548 549 550 551
				return stackFrame.restart();
			});
			data.actionBar.push(action, { icon: true, label: false });
		}
552 553
	}

I
isidor 已提交
554
	disposeTemplate(templateData: IStackFrameTemplateData): void {
I
isidor 已提交
555
		templateData.actionBar.dispose();
I
isidor 已提交
556 557 558
	}
}

I
isidor 已提交
559
class ErrorsRenderer implements ITreeRenderer<string, FuzzyScore, IErrorTemplateData> {
I
isidor 已提交
560 561 562 563 564 565 566
	static readonly ID = 'error';

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

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

569
		return { label };
I
isidor 已提交
570 571
	}

I
isidor 已提交
572
	renderElement(element: ITreeNode<string, FuzzyScore>, index: number, data: IErrorTemplateData): void {
I
isidor 已提交
573 574 575 576 577 578 579 580 581 582
		const error = element.element;
		data.label.textContent = error;
		data.label.title = error;
	}

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

I
isidor 已提交
583
class LoadMoreRenderer implements ITreeRenderer<ThreadAndSessionIds, FuzzyScore, ILabelTemplateData> {
I
isidor 已提交
584
	static readonly ID = 'loadMore';
I
isidor 已提交
585
	static readonly LABEL = nls.localize('loadMoreStackFrames', "Load More Stack Frames");
I
isidor 已提交
586 587 588 589 590 591

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

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

594
		return { label };
I
isidor 已提交
595 596
	}

I
isidor 已提交
597
	renderElement(element: ITreeNode<ThreadAndSessionIds, FuzzyScore>, index: number, data: ILabelTemplateData): void {
I
isidor 已提交
598
		data.label.textContent = LoadMoreRenderer.LABEL;
I
isidor 已提交
599 600 601 602 603 604 605
	}

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

I
isidor 已提交
606
class ShowMoreRenderer implements ITreeRenderer<IStackFrame[], FuzzyScore, ILabelTemplateData> {
I
isidor 已提交
607 608 609 610 611 612 613
	static readonly ID = 'showMore';

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

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

616
		return { label };
I
isidor 已提交
617 618
	}

I
isidor 已提交
619
	renderElement(element: ITreeNode<IStackFrame[], FuzzyScore>, index: number, data: ILabelTemplateData): void {
I
isidor 已提交
620
		const stackFrames = element.element;
621
		if (stackFrames.every(sf => !!(sf.source && sf.source.origin && sf.source.origin === stackFrames[0].source.origin))) {
I
isidor 已提交
622 623 624 625 626 627 628
			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 {
629 630 631 632
		// noop
	}
}

I
isidor 已提交
633 634 635 636 637 638 639
class CallStackDelegate implements IListVirtualDelegate<CallStackItem> {

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

	getTemplateId(element: CallStackItem): string {
I
isidor 已提交
640
		if (isDebugSession(element)) {
I
isidor 已提交
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
			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 已提交
656 657
		// element instanceof Array
		return ShowMoreRenderer.ID;
I
isidor 已提交
658 659 660
	}
}

J
Joao Moreno 已提交
661 662 663
function isDebugModel(obj: any): obj is IDebugModel {
	return typeof obj.getSessions === 'function';
}
I
isidor 已提交
664

I
isidor 已提交
665
function isDebugSession(obj: any): obj is IDebugSession {
I
isidor 已提交
666
	return obj && typeof obj.getAllThreads === 'function';
I
isidor 已提交
667 668
}

669 670 671 672
function isDeemphasized(frame: IStackFrame): boolean {
	return frame.source.presentationHint === 'deemphasize' || frame.presentationHint === 'deemphasize';
}

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

I
isidor 已提交
676 677
	constructor(private debugService: IDebugService) { }

J
Joao Moreno 已提交
678
	hasChildren(element: IDebugModel | CallStackItem): boolean {
679 680 681 682 683 684
		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 已提交
685 686
	}

687
	async getChildren(element: IDebugModel | CallStackItem): Promise<CallStackItem[]> {
J
Joao Moreno 已提交
688 689
		if (isDebugModel(element)) {
			const sessions = element.getSessions();
690 691 692
			if (sessions.length === 0) {
				return Promise.resolve([]);
			}
693
			if (sessions.length > 1 || this.debugService.getViewModel().isMultiSessionView()) {
I
isidor 已提交
694
				return Promise.resolve(sessions.filter(s => !s.parentSession));
I
isidor 已提交
695 696 697 698 699
			}

			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 已提交
700
		} else if (isDebugSession(element)) {
I
isidor 已提交
701
			const childSessions = this.debugService.getModel().getSessions().filter(s => s.parentSession === element);
I
isidor 已提交
702
			const threads: CallStackItem[] = element.getAllThreads();
703
			if (threads.length === 1) {
704
				// Do not show thread when there is only one to be compact.
705 706
				const children = await this.getThreadChildren(<Thread>threads[0]);
				return children.concat(childSessions);
707
			}
I
isidor 已提交
708

I
isidor 已提交
709
			return Promise.resolve(threads.concat(childSessions));
J
Joao Moreno 已提交
710 711
		} else {
			return this.getThreadChildren(<Thread>element);
I
isidor 已提交
712 713 714
		}
	}

I
isidor 已提交
715
	private getThreadChildren(thread: Thread): Promise<CallStackItem[]> {
I
isidor 已提交
716 717
		return this.getThreadCallstack(thread).then(children => {
			// Check if some stack frames should be hidden under a parent element since they are deemphasized
I
isidor 已提交
718
			const result: CallStackItem[] = [];
I
isidor 已提交
719
			children.forEach((child, index) => {
720
				if (child instanceof StackFrame && child.source && isDeemphasized(child)) {
I
isidor 已提交
721 722
					// Check if the user clicked to show the deemphasized source
					if (this.deemphasizedStackFramesToShow.indexOf(child) === -1) {
I
isidor 已提交
723 724 725 726 727 728 729
						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 已提交
730 731 732
						}

						const nextChild = index < children.length - 1 ? children[index + 1] : undefined;
733
						if (nextChild instanceof StackFrame && nextChild.source && isDeemphasized(nextChild)) {
I
isidor 已提交
734 735 736 737 738 739 740 741 742 743 744 745 746 747
							// Start collecting stackframes that will be "collapsed"
							result.push([child]);
							return;
						}
					}
				}

				result.push(child);
			});

			return result;
		});
	}

748
	private getThreadCallstack(thread: Thread): Promise<Array<IStackFrame | string | ThreadAndSessionIds>> {
I
isidor 已提交
749 750 751 752 753 754 755
		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 已提交
756
			if (callStack.length === 1 && thread.session.capabilities.supportsDelayedStackTraceLoading && thread.stoppedDetails && thread.stoppedDetails.totalFrames && thread.stoppedDetails.totalFrames > 1) {
I
isidor 已提交
757 758 759 760 761 762 763 764
				// 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 已提交
765
			if (thread.stoppedDetails && thread.stoppedDetails.totalFrames && thread.stoppedDetails.totalFrames > callStack.length && callStack.length > 1) {
I
isidor 已提交
766 767 768 769 770 771 772 773 774 775
				callStack = callStack.concat([new ThreadAndSessionIds(thread.session.getId(), thread.threadId)]);
			}

			return callStack;
		});
	}
}

class CallStackAccessibilityProvider implements IAccessibilityProvider<CallStackItem> {
	getAriaLabel(element: CallStackItem): string {
776 777 778 779
		if (element instanceof Thread) {
			return nls.localize('threadAriaLabel', "Thread {0}, callstack, debug", (<Thread>element).name);
		}
		if (element instanceof StackFrame) {
I
isidor 已提交
780
			return nls.localize('stackFrameAriaLabel', "Stack Frame {0} line {1} {2}, callstack, debug", element.name, element.range.startLineNumber, element.getSpecificSourceName());
781
		}
I
isidor 已提交
782
		if (isDebugSession(element)) {
I
isidor 已提交
783 784 785 786 787 788 789 790
			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);
		}
791

I
isidor 已提交
792 793
		// element instanceof ThreadAndSessionIds
		return nls.localize('loadMoreStackFrames', "Load More Stack Frames");
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 826 827 828 829 830 831 832 833 834

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 已提交
835
		super(`action.${STOP_ID}`, STOP_LABEL, 'debug-action codicon-debug-stop');
836 837 838
	}

	public run(): Promise<any> {
I
isidor 已提交
839
		return this.commandService.executeCommand(STOP_ID, undefined, getContext(this.session));
840 841 842 843 844 845 846 847 848
	}
}

class DisconnectAction extends Action {

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

	public run(): Promise<any> {
I
isidor 已提交
853
		return this.commandService.executeCommand(DISCONNECT_ID, undefined, getContext(this.session));
854 855 856 857 858 859 860 861 862
	}
}

class RestartAction extends Action {

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

	public run(): Promise<any> {
I
isidor 已提交
867
		return this.commandService.executeCommand(RESTART_SESSION_ID, undefined, getContext(this.session));
868 869 870 871 872 873 874 875 876
	}
}

class StepOverAction extends Action {

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

	public run(): Promise<any> {
I
isidor 已提交
881
		return this.commandService.executeCommand(STEP_OVER_ID, undefined, getContext(this.thread));
882 883 884 885 886 887 888 889 890
	}
}

class StepIntoAction extends Action {

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

	public run(): Promise<any> {
I
isidor 已提交
895
		return this.commandService.executeCommand(STEP_INTO_ID, undefined, getContext(this.thread));
896 897 898 899 900 901 902 903 904
	}
}

class StepOutAction extends Action {

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

	public run(): Promise<any> {
I
isidor 已提交
909
		return this.commandService.executeCommand(STEP_OUT_ID, undefined, getContext(this.thread));
910 911 912 913 914 915 916 917 918
	}
}

class PauseAction extends Action {

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

	public run(): Promise<any> {
I
isidor 已提交
923
		return this.commandService.executeCommand(PAUSE_ID, undefined, getContext(this.thread));
924 925 926 927 928 929 930 931 932
	}
}

class ContinueAction extends Action {

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

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