@theia/debug 1.53.0-next.5 → 1.53.0-next.55

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/README.md +62 -62
  2. package/lib/browser/debug-configuration-manager.js +6 -6
  3. package/lib/browser/debug-frontend-application-contribution.d.ts.map +1 -1
  4. package/lib/browser/debug-frontend-application-contribution.js.map +1 -1
  5. package/lib/common/inline-debug-adapter.d.ts +1 -0
  6. package/lib/common/inline-debug-adapter.d.ts.map +1 -1
  7. package/package.json +16 -16
  8. package/src/browser/breakpoint/breakpoint-manager.ts +369 -369
  9. package/src/browser/breakpoint/breakpoint-marker.ts +104 -104
  10. package/src/browser/console/debug-console-contribution.tsx +240 -240
  11. package/src/browser/console/debug-console-items.tsx +384 -384
  12. package/src/browser/console/debug-console-session.ts +205 -205
  13. package/src/browser/debug-call-stack-item-type-key.ts +20 -20
  14. package/src/browser/debug-configuration-manager.ts +591 -591
  15. package/src/browser/debug-configuration-model.ts +100 -100
  16. package/src/browser/debug-contribution.ts +43 -43
  17. package/src/browser/debug-frontend-application-contribution.ts +1551 -1551
  18. package/src/browser/debug-frontend-module.ts +133 -133
  19. package/src/browser/debug-package.spec.ts +20 -20
  20. package/src/browser/debug-preferences.ts +98 -98
  21. package/src/browser/debug-prefix-configuration.ts +195 -195
  22. package/src/browser/debug-resource.ts +59 -59
  23. package/src/browser/debug-schema-updater.ts +149 -149
  24. package/src/browser/debug-session-connection.ts +357 -357
  25. package/src/browser/debug-session-contribution.ts +157 -157
  26. package/src/browser/debug-session-manager.ts +683 -683
  27. package/src/browser/debug-session-options.ts +120 -120
  28. package/src/browser/debug-session.tsx +974 -974
  29. package/src/browser/debug-tab-bar-decorator.ts +57 -57
  30. package/src/browser/debug-watch-manager.ts +93 -93
  31. package/src/browser/disassembly-view/disassembly-view-accessibility-provider.ts +43 -43
  32. package/src/browser/disassembly-view/disassembly-view-breakpoint-renderer.ts +119 -119
  33. package/src/browser/disassembly-view/disassembly-view-contribution.ts +109 -109
  34. package/src/browser/disassembly-view/disassembly-view-instruction-renderer.ts +245 -245
  35. package/src/browser/disassembly-view/disassembly-view-table-delegate.ts +39 -39
  36. package/src/browser/disassembly-view/disassembly-view-utilities.ts +55 -55
  37. package/src/browser/disassembly-view/disassembly-view-widget.ts +463 -463
  38. package/src/browser/editor/debug-breakpoint-widget.tsx +293 -293
  39. package/src/browser/editor/debug-editor-model.ts +529 -529
  40. package/src/browser/editor/debug-editor-service.ts +192 -192
  41. package/src/browser/editor/debug-editor.ts +20 -20
  42. package/src/browser/editor/debug-exception-widget.tsx +122 -122
  43. package/src/browser/editor/debug-expression-provider.ts +78 -78
  44. package/src/browser/editor/debug-hover-source.tsx +105 -105
  45. package/src/browser/editor/debug-hover-widget.ts +298 -298
  46. package/src/browser/editor/debug-inline-value-decorator.ts +373 -373
  47. package/src/browser/model/debug-breakpoint.tsx +151 -151
  48. package/src/browser/model/debug-function-breakpoint.tsx +101 -101
  49. package/src/browser/model/debug-instruction-breakpoint.tsx +68 -68
  50. package/src/browser/model/debug-source-breakpoint.tsx +237 -237
  51. package/src/browser/model/debug-source.ts +93 -93
  52. package/src/browser/model/debug-stack-frame.tsx +177 -177
  53. package/src/browser/model/debug-thread.tsx +292 -292
  54. package/src/browser/preferences/launch-preferences.ts +38 -38
  55. package/src/browser/style/index.css +453 -453
  56. package/src/browser/view/debug-action.tsx +57 -57
  57. package/src/browser/view/debug-breakpoints-source.tsx +53 -53
  58. package/src/browser/view/debug-breakpoints-widget.ts +71 -71
  59. package/src/browser/view/debug-configuration-select.tsx +269 -269
  60. package/src/browser/view/debug-configuration-widget.tsx +121 -121
  61. package/src/browser/view/debug-exception-breakpoint.tsx +68 -68
  62. package/src/browser/view/debug-session-widget.ts +124 -124
  63. package/src/browser/view/debug-stack-frames-source.tsx +75 -75
  64. package/src/browser/view/debug-stack-frames-widget.ts +135 -135
  65. package/src/browser/view/debug-threads-source.tsx +48 -48
  66. package/src/browser/view/debug-threads-widget.ts +126 -126
  67. package/src/browser/view/debug-toolbar-widget.tsx +145 -145
  68. package/src/browser/view/debug-variables-source.ts +43 -43
  69. package/src/browser/view/debug-variables-widget.ts +61 -61
  70. package/src/browser/view/debug-view-model.ts +230 -230
  71. package/src/browser/view/debug-watch-expression.tsx +88 -88
  72. package/src/browser/view/debug-watch-source.ts +41 -41
  73. package/src/browser/view/debug-watch-widget.ts +61 -61
  74. package/src/browser/view/debug-widget.ts +97 -97
  75. package/src/common/debug-adapter-contribution-registry.ts +206 -206
  76. package/src/common/debug-adapter-session.ts +102 -102
  77. package/src/common/debug-common.ts +19 -19
  78. package/src/common/debug-compound.ts +33 -33
  79. package/src/common/debug-configuration.ts +112 -112
  80. package/src/common/debug-model.ts +200 -200
  81. package/src/common/debug-service.ts +184 -184
  82. package/src/common/debug-uri-utils.ts +24 -24
  83. package/src/common/inline-debug-adapter.ts +47 -47
  84. package/src/node/debug-adapter-factory.ts +107 -107
  85. package/src/node/debug-adapter-session-manager.ts +106 -106
  86. package/src/node/debug-backend-module.ts +57 -57
  87. package/src/node/debug-service-impl.ts +119 -119
  88. package/src/node/stream-debug-adapter.ts +126 -126
@@ -1,974 +1,974 @@
1
- // *****************************************************************************
2
- // Copyright (C) 2018 Red Hat, Inc. and others.
3
- //
4
- // This program and the accompanying materials are made available under the
5
- // terms of the Eclipse Public License v. 2.0 which is available at
6
- // http://www.eclipse.org/legal/epl-2.0.
7
- //
8
- // This Source Code may also be made available under the following Secondary
9
- // Licenses when the conditions for such availability set forth in the Eclipse
10
- // Public License v. 2.0 are satisfied: GNU General Public License, version 2
11
- // with the GNU Classpath Exception which is available at
12
- // https://www.gnu.org/software/classpath/license.html.
13
- //
14
- // SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0
15
- // *****************************************************************************
16
-
17
- /* eslint-disable @typescript-eslint/no-explicit-any */
18
-
19
- import * as React from '@theia/core/shared/react';
20
- import { LabelProvider } from '@theia/core/lib/browser';
21
- import { DebugProtocol } from '@vscode/debugprotocol';
22
- import { Emitter, Event, DisposableCollection, Disposable, MessageClient, MessageType, Mutable, ContributionProvider } from '@theia/core/lib/common';
23
- import { TerminalService } from '@theia/terminal/lib/browser/base/terminal-service';
24
- import { EditorManager } from '@theia/editor/lib/browser';
25
- import { CompositeTreeElement } from '@theia/core/lib/browser/source-tree';
26
- import { DebugSessionConnection, DebugRequestTypes, DebugEventTypes } from './debug-session-connection';
27
- import { DebugThread, StoppedDetails, DebugThreadData } from './model/debug-thread';
28
- import { DebugScope } from './console/debug-console-items';
29
- import { DebugStackFrame } from './model/debug-stack-frame';
30
- import { DebugSource } from './model/debug-source';
31
- import { DebugBreakpoint, DebugBreakpointOptions } from './model/debug-breakpoint';
32
- import { DebugSourceBreakpoint } from './model/debug-source-breakpoint';
33
- import debounce = require('p-debounce');
34
- import URI from '@theia/core/lib/common/uri';
35
- import { BreakpointManager } from './breakpoint/breakpoint-manager';
36
- import { DebugConfigurationSessionOptions, InternalDebugSessionOptions, TestRunReference } from './debug-session-options';
37
- import { DebugConfiguration, DebugConsoleMode } from '../common/debug-common';
38
- import { SourceBreakpoint, ExceptionBreakpoint } from './breakpoint/breakpoint-marker';
39
- import { TerminalWidgetOptions, TerminalWidget } from '@theia/terminal/lib/browser/base/terminal-widget';
40
- import { DebugFunctionBreakpoint } from './model/debug-function-breakpoint';
41
- import { FileService } from '@theia/filesystem/lib/browser/file-service';
42
- import { DebugContribution } from './debug-contribution';
43
- import { Deferred, waitForEvent } from '@theia/core/lib/common/promise-util';
44
- import { WorkspaceService } from '@theia/workspace/lib/browser';
45
- import { DebugInstructionBreakpoint } from './model/debug-instruction-breakpoint';
46
- import { nls } from '@theia/core';
47
- import { TestService, TestServices } from '@theia/test/lib/browser/test-service';
48
- import { DebugSessionManager } from './debug-session-manager';
49
-
50
- export enum DebugState {
51
- Inactive,
52
- Initializing,
53
- Running,
54
- Stopped
55
- }
56
- /**
57
- * The mapped string values must not change as they are used for the `debugState` when context closure.
58
- * For more details see the `Debugger contexts` section of the [official doc](https://code.visualstudio.com/api/references/when-clause-contexts#available-contexts).
59
- */
60
- export function debugStateContextValue(state: DebugState): string {
61
- switch (state) {
62
- case DebugState.Initializing: return 'initializing';
63
- case DebugState.Stopped: return 'stopped';
64
- case DebugState.Running: return 'running';
65
- default: return 'inactive';
66
- }
67
- }
68
-
69
- // FIXME: make injectable to allow easily inject services
70
- export class DebugSession implements CompositeTreeElement {
71
- protected readonly deferredOnDidConfigureCapabilities = new Deferred<void>();
72
-
73
- protected readonly onDidChangeEmitter = new Emitter<void>();
74
- readonly onDidChange: Event<void> = this.onDidChangeEmitter.event;
75
- protected fireDidChange(): void {
76
- this.onDidChangeEmitter.fire(undefined);
77
- }
78
- protected readonly onDidFocusStackFrameEmitter = new Emitter<DebugStackFrame | undefined>();
79
- get onDidFocusStackFrame(): Event<DebugStackFrame | undefined> {
80
- return this.onDidFocusStackFrameEmitter.event;
81
- }
82
-
83
- protected readonly onDidFocusThreadEmitter = new Emitter<DebugThread | undefined>();
84
- get onDidFocusThread(): Event<DebugThread | undefined> {
85
- return this.onDidFocusThreadEmitter.event;
86
- }
87
-
88
- protected readonly onDidChangeBreakpointsEmitter = new Emitter<URI>();
89
- readonly onDidChangeBreakpoints: Event<URI> = this.onDidChangeBreakpointsEmitter.event;
90
- protected fireDidChangeBreakpoints(uri: URI): void {
91
- this.onDidChangeBreakpointsEmitter.fire(uri);
92
- }
93
-
94
- protected readonly childSessions = new Map<string, DebugSession>();
95
- protected readonly toDispose = new DisposableCollection();
96
-
97
- protected isStopping: boolean = false;
98
-
99
- constructor(
100
- readonly id: string,
101
- readonly options: DebugConfigurationSessionOptions,
102
- readonly parentSession: DebugSession | undefined,
103
- testService: TestService,
104
- testRun: TestRunReference | undefined,
105
- sessionManager: DebugSessionManager,
106
- protected readonly connection: DebugSessionConnection,
107
- protected readonly terminalServer: TerminalService,
108
- protected readonly editorManager: EditorManager,
109
- protected readonly breakpoints: BreakpointManager,
110
- protected readonly labelProvider: LabelProvider,
111
- protected readonly messages: MessageClient,
112
- protected readonly fileService: FileService,
113
- protected readonly debugContributionProvider: ContributionProvider<DebugContribution>,
114
- protected readonly workspaceService: WorkspaceService,
115
- /**
116
- * Number of millis after a `stop` request times out. It's 5 seconds by default.
117
- */
118
- protected readonly stopTimeout = 5_000,
119
- ) {
120
- this.connection.onRequest('runInTerminal', (request: DebugProtocol.RunInTerminalRequest) => this.runInTerminal(request));
121
- this.connection.onDidClose(() => {
122
- this.toDispose.dispose();
123
- });
124
- this.registerDebugContributions(options.configuration.type, this.connection);
125
-
126
- if (parentSession) {
127
- parentSession.childSessions.set(id, this);
128
- this.toDispose.push(Disposable.create(() => {
129
- this.parentSession?.childSessions?.delete(id);
130
- }));
131
- }
132
- if (testRun) {
133
- try {
134
- const run = TestServices.withTestRun(testService, testRun.controllerId, testRun.runId);
135
- run.onDidChangeProperty(evt => {
136
- if (evt.isRunning === false) {
137
- sessionManager.terminateSession(this);
138
- }
139
- });
140
- } catch (err) {
141
- console.error(err);
142
- }
143
- }
144
-
145
- this.connection.onDidClose(() => this.toDispose.dispose());
146
- this.toDispose.pushAll([
147
- this.onDidChangeEmitter,
148
- this.onDidChangeBreakpointsEmitter,
149
- Disposable.create(() => {
150
- this.clearBreakpoints();
151
- this.doUpdateThreads([]);
152
- }),
153
- this.connection,
154
- this.connection.on('initialized', () => this.configure()),
155
- this.connection.on('breakpoint', ({ body }) => this.updateBreakpoint(body)),
156
- this.connection.on('continued', e => this.handleContinued(e)),
157
- this.connection.on('stopped', e => this.handleStopped(e)),
158
- this.connection.on('thread', e => this.handleThread(e)),
159
- this.connection.on('capabilities', event => this.updateCapabilities(event.body.capabilities)),
160
- this.breakpoints.onDidChangeMarkers(uri => this.updateBreakpoints({ uri, sourceModified: true }))
161
- ]);
162
- }
163
-
164
- get onDispose(): Event<void> {
165
- return this.toDispose.onDispose;
166
- }
167
-
168
- get configuration(): DebugConfiguration {
169
- return this.options.configuration;
170
- }
171
-
172
- protected _capabilities: DebugProtocol.Capabilities = {};
173
- get capabilities(): DebugProtocol.Capabilities {
174
- return this._capabilities;
175
- }
176
-
177
- protected readonly sources = new Map<string, DebugSource>();
178
- getSource(raw: DebugProtocol.Source): DebugSource {
179
- const uri = DebugSource.toUri(raw).toString();
180
- const source = this.sources.get(uri) || new DebugSource(this, this.editorManager, this.labelProvider);
181
- source.update({ raw });
182
- this.sources.set(uri, source);
183
- return source;
184
- }
185
-
186
- getSourceForUri(uri: URI): DebugSource | undefined {
187
- return this.sources.get(uri.toString());
188
- }
189
-
190
- async toSource(uri: URI): Promise<DebugSource> {
191
- const source = this.getSourceForUri(uri);
192
- if (source) {
193
- return source;
194
- }
195
-
196
- return this.getSource(await this.toDebugSource(uri));
197
- }
198
-
199
- async toDebugSource(uri: URI): Promise<DebugProtocol.Source> {
200
- if (uri.scheme === DebugSource.SCHEME) {
201
- return {
202
- name: uri.path.toString(),
203
- sourceReference: Number(uri.query)
204
- };
205
- }
206
- const name = uri.displayName;
207
- let path;
208
- const underlying = await this.fileService.toUnderlyingResource(uri);
209
- if (underlying.scheme === 'file') {
210
- path = await this.fileService.fsPath(underlying);
211
- } else {
212
- path = uri.toString();
213
- }
214
- return { name, path };
215
- }
216
-
217
- protected _threads = new Map<number, DebugThread>();
218
- get threads(): IterableIterator<DebugThread> {
219
- return this._threads.values();
220
- }
221
-
222
- get threadCount(): number {
223
- return this._threads.size;
224
- }
225
-
226
- *getThreads(filter: (thread: DebugThread) => boolean): IterableIterator<DebugThread> {
227
- for (const thread of this.threads) {
228
- if (filter(thread)) {
229
- yield thread;
230
- }
231
- }
232
- }
233
-
234
- get runningThreads(): IterableIterator<DebugThread> {
235
- return this.getThreads(thread => !thread.stopped);
236
- }
237
-
238
- get stoppedThreads(): IterableIterator<DebugThread> {
239
- return this.getThreads(thread => thread.stopped);
240
- }
241
-
242
- async pauseAll(): Promise<void> {
243
- const promises: Promise<void>[] = [];
244
- for (const thread of this.runningThreads) {
245
- promises.push((async () => {
246
- try {
247
- await thread.pause();
248
- } catch (e) {
249
- console.error('pauseAll failed:', e);
250
- }
251
- })());
252
- }
253
- await Promise.all(promises);
254
- }
255
-
256
- async continueAll(): Promise<void> {
257
- const promises: Promise<void>[] = [];
258
- for (const thread of this.stoppedThreads) {
259
- promises.push((async () => {
260
- try {
261
- await thread.continue();
262
- } catch (e) {
263
- console.error('continueAll failed:', e);
264
- }
265
- })());
266
- }
267
- await Promise.all(promises);
268
- }
269
-
270
- get currentFrame(): DebugStackFrame | undefined {
271
- return this.currentThread && this.currentThread.currentFrame;
272
- }
273
-
274
- protected _currentThread: DebugThread | undefined;
275
- protected readonly toDisposeOnCurrentThread = new DisposableCollection();
276
- get currentThread(): DebugThread | undefined {
277
- return this._currentThread;
278
- }
279
- set currentThread(thread: DebugThread | undefined) {
280
- if (this._currentThread?.id === thread?.id) {
281
- return;
282
- }
283
- this.toDisposeOnCurrentThread.dispose();
284
- this._currentThread = thread;
285
- this.onDidFocusThreadEmitter.fire(thread);
286
- this.fireDidChange();
287
- if (thread) {
288
- this.toDisposeOnCurrentThread.push(thread.onDidChanged(() => this.fireDidChange()));
289
- this.toDisposeOnCurrentThread.push(thread.onDidFocusStackFrame(frame => this.onDidFocusStackFrameEmitter.fire(frame)));
290
-
291
- // If this thread is missing stack frame information, then load that.
292
- this.updateFrames();
293
- }
294
- }
295
-
296
- get state(): DebugState {
297
- if (this.connection.disposed) {
298
- return DebugState.Inactive;
299
- }
300
- if (!this.initialized) {
301
- return DebugState.Initializing;
302
- }
303
- const thread = this.currentThread;
304
- if (thread) {
305
- return thread.stopped ? DebugState.Stopped : DebugState.Running;
306
- }
307
- return !!this.stoppedThreads.next().value ? DebugState.Stopped : DebugState.Running;
308
- }
309
-
310
- async getScopes(): Promise<DebugScope[]> {
311
- const { currentFrame } = this;
312
- return currentFrame ? currentFrame.getScopes() : [];
313
- }
314
-
315
- async start(): Promise<void> {
316
- await this.initialize();
317
- await this.launchOrAttach();
318
- }
319
-
320
- protected async initialize(): Promise<void> {
321
- try {
322
- const response = await this.connection.sendRequest('initialize', {
323
- clientID: 'Theia',
324
- clientName: 'Theia IDE',
325
- adapterID: this.configuration.type,
326
- locale: 'en-US',
327
- linesStartAt1: true,
328
- columnsStartAt1: true,
329
- pathFormat: 'path',
330
- supportsVariableType: false,
331
- supportsVariablePaging: false,
332
- supportsRunInTerminalRequest: true
333
- });
334
- this.updateCapabilities(response?.body || {});
335
- this.didReceiveCapabilities.resolve();
336
- } catch (err) {
337
- this.didReceiveCapabilities.reject(err);
338
- throw err;
339
- }
340
- }
341
-
342
- protected async launchOrAttach(): Promise<void> {
343
- try {
344
- await this.sendRequest((this.configuration.request as keyof DebugRequestTypes), this.configuration);
345
- } catch (reason) {
346
- this.messages.showMessage({
347
- type: MessageType.Error,
348
- text: reason.message || 'Debug session initialization failed. See console for details.',
349
- options: {
350
- timeout: 10000
351
- }
352
- });
353
- throw reason;
354
- }
355
- }
356
-
357
- /**
358
- * The `send('initialize')` request could resolve later than `on('initialized')` emits the event.
359
- * Hence, the `configure` would use the empty object `capabilities`.
360
- * Using the empty `capabilities` could result in missing exception breakpoint filters, as
361
- * always `capabilities.exceptionBreakpointFilters` is falsy. This deferred promise works
362
- * around this timing issue. https://github.com/eclipse-theia/theia/issues/11886
363
- */
364
- protected didReceiveCapabilities = new Deferred<void>();
365
- protected initialized = false;
366
- protected async configure(): Promise<void> {
367
- await this.didReceiveCapabilities.promise;
368
- if (this.capabilities.exceptionBreakpointFilters) {
369
- const exceptionBreakpoints = [];
370
- for (const filter of this.capabilities.exceptionBreakpointFilters) {
371
- const origin = this.breakpoints.getExceptionBreakpoint(filter.filter);
372
- exceptionBreakpoints.push(ExceptionBreakpoint.create(filter, origin));
373
- }
374
- this.breakpoints.setExceptionBreakpoints(exceptionBreakpoints);
375
- }
376
- await this.updateBreakpoints({ sourceModified: false });
377
- if (this.capabilities.supportsConfigurationDoneRequest) {
378
- await this.sendRequest('configurationDone', {});
379
- }
380
- this.initialized = true;
381
- await this.updateThreads(undefined);
382
- }
383
-
384
- canTerminate(): boolean {
385
- return !!this.capabilities.supportsTerminateRequest;
386
- }
387
-
388
- canRestart(): boolean {
389
- return !!this.capabilities.supportsRestartRequest;
390
- }
391
-
392
- async restart(): Promise<void> {
393
- if (this.canRestart()) {
394
- await this.sendRequest('restart', {});
395
- }
396
- }
397
-
398
- async stop(isRestart: boolean, callback: () => void): Promise<void> {
399
- if (!this.isStopping) {
400
- this.isStopping = true;
401
- if (this.canTerminate()) {
402
- const terminated = this.waitFor('terminated', this.stopTimeout);
403
- try {
404
- await this.connection.sendRequest('terminate', { restart: isRestart }, this.stopTimeout);
405
- await terminated;
406
- } catch (e) {
407
- this.handleTerminateError(e);
408
- }
409
- } else {
410
- const terminateDebuggee = this.initialized && this.capabilities.supportTerminateDebuggee;
411
- try {
412
- await this.sendRequest('disconnect', { restart: isRestart, terminateDebuggee }, this.stopTimeout);
413
- } catch (e) {
414
- this.handleDisconnectError(e);
415
- }
416
- }
417
- callback();
418
- }
419
- }
420
-
421
- /**
422
- * Invoked when sending the `terminate` request to the debugger is rejected or timed out.
423
- */
424
- protected handleTerminateError(err: unknown): void {
425
- console.error('Did not receive terminated event in time', err);
426
- }
427
-
428
- /**
429
- * Invoked when sending the `disconnect` request to the debugger is rejected or timed out.
430
- */
431
- protected handleDisconnectError(err: unknown): void {
432
- console.error('Error on disconnect', err);
433
- }
434
-
435
- async disconnect(isRestart: boolean, callback: () => void): Promise<void> {
436
- if (!this.isStopping) {
437
- this.isStopping = true;
438
- await this.sendRequest('disconnect', { restart: isRestart });
439
- callback();
440
- }
441
- }
442
-
443
- async completions(text: string, column: number, line: number): Promise<DebugProtocol.CompletionItem[]> {
444
- const frameId = this.currentFrame && this.currentFrame.raw.id;
445
- const response = await this.sendRequest('completions', { frameId, text, column, line });
446
- return response.body.targets;
447
- }
448
-
449
- async evaluate(expression: string, context?: string): Promise<DebugProtocol.EvaluateResponse['body']> {
450
- const frameId = this.currentFrame && this.currentFrame.raw.id;
451
- const response = await this.sendRequest('evaluate', { expression, frameId, context });
452
- return response.body;
453
- }
454
-
455
- sendRequest<K extends keyof DebugRequestTypes>(command: K, args: DebugRequestTypes[K][0], timeout?: number): Promise<DebugRequestTypes[K][1]> {
456
- return this.connection.sendRequest(command, args, timeout);
457
- }
458
-
459
- sendCustomRequest<T extends DebugProtocol.Response>(command: string, args?: any): Promise<T> {
460
- return this.connection.sendCustomRequest(command, args);
461
- }
462
-
463
- on<K extends keyof DebugEventTypes>(kind: K, listener: (e: DebugEventTypes[K]) => any): Disposable {
464
- return this.connection.on(kind, listener);
465
- }
466
-
467
- waitFor<K extends keyof DebugEventTypes>(kind: K, ms: number): Promise<void> {
468
- return waitForEvent(this.connection.onEvent(kind), ms).then();
469
- }
470
-
471
- get onDidCustomEvent(): Event<DebugProtocol.Event> {
472
- return this.connection.onDidCustomEvent;
473
- }
474
-
475
- protected async runInTerminal({ arguments: { title, cwd, args, env } }: DebugProtocol.RunInTerminalRequest): Promise<DebugProtocol.RunInTerminalResponse['body']> {
476
- const terminal = await this.doCreateTerminal({ title, cwd, env, useServerTitle: false });
477
- const { processId } = terminal;
478
- await terminal.executeCommand({ cwd, args, env });
479
- return { processId: await processId };
480
- }
481
-
482
- protected async doCreateTerminal(options: TerminalWidgetOptions): Promise<TerminalWidget> {
483
- let terminal = undefined;
484
- for (const t of this.terminalServer.all) {
485
- if ((t.title.label === options.title || t.title.caption === options.title) && (await t.hasChildProcesses()) === false) {
486
- terminal = t;
487
- break;
488
- }
489
- }
490
-
491
- if (!terminal) {
492
- terminal = await this.terminalServer.newTerminal(options);
493
- await terminal.start();
494
- }
495
- this.terminalServer.open(terminal);
496
- return terminal;
497
- }
498
-
499
- protected clearThreads(): void {
500
- for (const thread of this.threads) {
501
- thread.clear();
502
- }
503
- this.updateCurrentThread();
504
- }
505
-
506
- protected clearThread(threadId: number): void {
507
- const thread = this._threads.get(threadId);
508
- if (thread) {
509
- thread.clear();
510
- }
511
- this.updateCurrentThread();
512
- }
513
-
514
- protected readonly scheduleUpdateThreads = debounce(() => this.updateThreads(undefined), 100);
515
- protected pendingThreads = Promise.resolve();
516
-
517
- updateThreads(stoppedDetails: StoppedDetails | undefined): Promise<void> {
518
- return this.pendingThreads = this.pendingThreads.then(async () => {
519
- try {
520
- const response = await this.sendRequest('threads', {});
521
- // java debugger returns an empty body sometimes
522
- const threads = response && response.body && response.body.threads || [];
523
- this.doUpdateThreads(threads, stoppedDetails);
524
- } catch (e) {
525
- console.error('updateThreads failed:', e);
526
- }
527
- });
528
- }
529
-
530
- protected doUpdateThreads(threads: DebugProtocol.Thread[], stoppedDetails?: StoppedDetails): void {
531
- const existing = this._threads;
532
- this._threads = new Map();
533
- for (const raw of threads) {
534
- const id = raw.id;
535
- const thread = existing.get(id) || new DebugThread(this);
536
- this._threads.set(id, thread);
537
- const data: Partial<Mutable<DebugThreadData>> = { raw };
538
- if (stoppedDetails) {
539
- if (stoppedDetails.threadId === id) {
540
- data.stoppedDetails = stoppedDetails;
541
- } else if (stoppedDetails.allThreadsStopped) {
542
- data.stoppedDetails = {
543
- // When a debug adapter notifies us that all threads are stopped,
544
- // we do not know why the others are stopped, so we should default
545
- // to something generic.
546
- reason: '',
547
- };
548
- }
549
- }
550
- thread.update(data);
551
- }
552
- this.updateCurrentThread(stoppedDetails);
553
- }
554
-
555
- protected updateCurrentThread(stoppedDetails?: StoppedDetails): void {
556
- const { currentThread } = this;
557
- let threadId = currentThread && currentThread.raw.id;
558
- if (stoppedDetails && !stoppedDetails.preserveFocusHint && !!stoppedDetails.threadId) {
559
- threadId = stoppedDetails.threadId;
560
- }
561
- this.currentThread = typeof threadId === 'number' && this._threads.get(threadId)
562
- || this._threads.values().next().value;
563
- }
564
-
565
- protected async updateFrames(): Promise<void> {
566
- const thread = this._currentThread;
567
- if (!thread || thread.pendingFrameCount || thread.frameCount) {
568
- return;
569
- }
570
- if (this.capabilities.supportsDelayedStackTraceLoading) {
571
- await thread.fetchFrames(1);
572
- await thread.fetchFrames(19);
573
- } else {
574
- await thread.fetchFrames();
575
- }
576
- }
577
-
578
- protected updateCapabilities(capabilities: DebugProtocol.Capabilities): void {
579
- Object.assign(this._capabilities, capabilities);
580
- this.deferredOnDidConfigureCapabilities.resolve();
581
- }
582
-
583
- protected readonly _breakpoints = new Map<string, DebugBreakpoint[]>();
584
- get breakpointUris(): IterableIterator<string> {
585
- return this._breakpoints.keys();
586
- }
587
-
588
- getSourceBreakpoints(uri?: URI): DebugSourceBreakpoint[] {
589
- const breakpoints = [];
590
- for (const breakpoint of this.getBreakpoints(uri)) {
591
- if (breakpoint instanceof DebugSourceBreakpoint) {
592
- breakpoints.push(breakpoint);
593
- }
594
- }
595
- return breakpoints;
596
- }
597
-
598
- getFunctionBreakpoints(): DebugFunctionBreakpoint[] {
599
- return this.getBreakpoints(BreakpointManager.FUNCTION_URI).filter((breakpoint): breakpoint is DebugFunctionBreakpoint => breakpoint instanceof DebugFunctionBreakpoint);
600
- }
601
-
602
- getInstructionBreakpoints(): DebugInstructionBreakpoint[] {
603
- if (this.capabilities.supportsInstructionBreakpoints) {
604
- return this.getBreakpoints(BreakpointManager.INSTRUCTION_URI)
605
- .filter((breakpoint): breakpoint is DebugInstructionBreakpoint => breakpoint instanceof DebugInstructionBreakpoint);
606
- }
607
- return this.breakpoints.getInstructionBreakpoints().map(origin => new DebugInstructionBreakpoint(origin, this.asDebugBreakpointOptions()));
608
- }
609
-
610
- getBreakpoints(uri?: URI): DebugBreakpoint[] {
611
- if (uri) {
612
- return this._breakpoints.get(uri.toString()) || [];
613
- }
614
- const result = [];
615
- for (const breakpoints of this._breakpoints.values()) {
616
- result.push(...breakpoints);
617
- }
618
- return result;
619
- }
620
-
621
- getBreakpoint(id: string): DebugBreakpoint | undefined {
622
- for (const breakpoints of this._breakpoints.values()) {
623
- const breakpoint = breakpoints.find(b => b.id === id);
624
- if (breakpoint) {
625
- return breakpoint;
626
- }
627
-
628
- }
629
- return undefined;
630
- }
631
-
632
- protected clearBreakpoints(): void {
633
- const uris = [...this._breakpoints.keys()];
634
- this._breakpoints.clear();
635
- for (const uri of uris) {
636
- this.fireDidChangeBreakpoints(new URI(uri));
637
- }
638
- }
639
-
640
- protected updatingBreakpoints = false;
641
-
642
- protected updateBreakpoint(body: DebugProtocol.BreakpointEvent['body']): void {
643
- this.updatingBreakpoints = true;
644
- try {
645
- const raw = body.breakpoint;
646
- if (body.reason === 'new') {
647
- if (raw.source && typeof raw.line === 'number') {
648
- const uri = DebugSource.toUri(raw.source);
649
- const origin = SourceBreakpoint.create(uri, { line: raw.line, column: raw.column });
650
- if (this.breakpoints.addBreakpoint(origin)) {
651
- const breakpoints = this.getSourceBreakpoints(uri);
652
- const breakpoint = new DebugSourceBreakpoint(origin, this.asDebugBreakpointOptions());
653
- breakpoint.update({ raw });
654
- breakpoints.push(breakpoint);
655
- this.setSourceBreakpoints(uri, breakpoints);
656
- }
657
- }
658
- }
659
- if (body.reason === 'removed' && raw.id) {
660
- const toRemove = this.findBreakpoint(b => b.idFromAdapter === raw.id);
661
- if (toRemove) {
662
- toRemove.remove();
663
- const breakpoints = this.getBreakpoints(toRemove.uri);
664
- const index = breakpoints.indexOf(toRemove);
665
- if (index !== -1) {
666
- breakpoints.splice(index, 1);
667
- this.setBreakpoints(toRemove.uri, breakpoints);
668
- }
669
- }
670
- }
671
- if (body.reason === 'changed' && raw.id) {
672
- const toUpdate = this.findBreakpoint(b => b.idFromAdapter === raw.id);
673
- if (toUpdate) {
674
- toUpdate.update({ raw });
675
- if (toUpdate instanceof DebugSourceBreakpoint) {
676
- const sourceBreakpoints = this.getSourceBreakpoints(toUpdate.uri);
677
- // in order to dedup again if a debugger converted line breakpoint to inline breakpoint
678
- // i.e. assigned a column to a line breakpoint
679
- this.setSourceBreakpoints(toUpdate.uri, sourceBreakpoints);
680
- } else {
681
- this.fireDidChangeBreakpoints(toUpdate.uri);
682
- }
683
- }
684
- }
685
- } finally {
686
- this.updatingBreakpoints = false;
687
- }
688
- }
689
- protected findBreakpoint(match: (breakpoint: DebugBreakpoint) => boolean): DebugBreakpoint | undefined {
690
- for (const [, breakpoints] of this._breakpoints) {
691
- for (const breakpoint of breakpoints) {
692
- if (match(breakpoint)) {
693
- return breakpoint;
694
- }
695
- }
696
- }
697
- return undefined;
698
- }
699
-
700
- protected async updateBreakpoints(options: {
701
- uri?: URI,
702
- sourceModified: boolean
703
- }): Promise<void> {
704
- if (this.updatingBreakpoints) {
705
- return;
706
- }
707
- const { uri, sourceModified } = options;
708
- await this.deferredOnDidConfigureCapabilities.promise;
709
- for (const affectedUri of this.getAffectedUris(uri)) {
710
- if (affectedUri.toString() === BreakpointManager.EXCEPTION_URI.toString()) {
711
- await this.sendExceptionBreakpoints();
712
- } else if (affectedUri.toString() === BreakpointManager.FUNCTION_URI.toString()) {
713
- await this.sendFunctionBreakpoints(affectedUri);
714
- } else if (affectedUri.toString() === BreakpointManager.INSTRUCTION_URI.toString()) {
715
- await this.sendInstructionBreakpoints();
716
- } else {
717
- await this.sendSourceBreakpoints(affectedUri, sourceModified);
718
- }
719
- }
720
- }
721
-
722
- protected async sendExceptionBreakpoints(): Promise<void> {
723
- const filters: string[] = [];
724
- const filterOptions: DebugProtocol.ExceptionFilterOptions[] | undefined = this.capabilities.supportsExceptionFilterOptions ? [] : undefined;
725
- for (const breakpoint of this.breakpoints.getExceptionBreakpoints()) {
726
- if (breakpoint.enabled) {
727
- if (filterOptions) {
728
- filterOptions.push({
729
- filterId: breakpoint.raw.filter,
730
- condition: breakpoint.condition
731
- });
732
- } else {
733
- filters.push(breakpoint.raw.filter);
734
- }
735
- }
736
- }
737
- await this.sendRequest('setExceptionBreakpoints', { filters, filterOptions });
738
- }
739
-
740
- protected async sendFunctionBreakpoints(affectedUri: URI): Promise<void> {
741
- const all = this.breakpoints.getFunctionBreakpoints().map(origin =>
742
- new DebugFunctionBreakpoint(origin, this.asDebugBreakpointOptions())
743
- );
744
- const enabled = all.filter(b => b.enabled);
745
- if (this.capabilities.supportsFunctionBreakpoints) {
746
- try {
747
- const response = await this.sendRequest('setFunctionBreakpoints', {
748
- breakpoints: enabled.map(b => b.origin.raw)
749
- });
750
- // Apparently, `body` and `breakpoints` can be missing.
751
- // https://github.com/eclipse-theia/theia/issues/11885
752
- // https://github.com/microsoft/vscode/blob/80004351ccf0884b58359f7c8c801c91bb827d83/src/vs/workbench/contrib/debug/browser/debugSession.ts#L448-L449
753
- if (response && response.body) {
754
- response.body.breakpoints.forEach((raw, index) => {
755
- // node debug adapter returns more breakpoints sometimes
756
- if (enabled[index]) {
757
- enabled[index].update({ raw });
758
- }
759
- });
760
- }
761
- } catch (error) {
762
- // could be error or promise rejection of DebugProtocol.SetFunctionBreakpoints
763
- if (error instanceof Error) {
764
- console.error(`Error setting breakpoints: ${error.message}`);
765
- } else {
766
- // handle adapters that send failed DebugProtocol.SetFunctionBreakpoints for invalid breakpoints
767
- const genericMessage: string = 'Function breakpoint not valid for current debug session';
768
- const message: string = error.message ? `${error.message}` : genericMessage;
769
- console.warn(`Could not handle function breakpoints: ${message}, disabling...`);
770
- enabled.forEach(b => b.update({
771
- raw: {
772
- verified: false,
773
- message
774
- }
775
- }));
776
- }
777
- }
778
- }
779
- this.setBreakpoints(affectedUri, all);
780
- }
781
-
782
- protected async sendSourceBreakpoints(affectedUri: URI, sourceModified?: boolean): Promise<void> {
783
- const source = await this.toSource(affectedUri);
784
- const all = this.breakpoints.findMarkers({ uri: affectedUri }).map(({ data }) =>
785
- new DebugSourceBreakpoint(data, this.asDebugBreakpointOptions())
786
- );
787
- const enabled = all.filter(b => b.enabled);
788
- try {
789
- const breakpoints = enabled.map(({ origin }) => origin.raw);
790
- const response = await this.sendRequest('setBreakpoints', {
791
- source: source.raw,
792
- sourceModified,
793
- breakpoints,
794
- lines: breakpoints.map(({ line }) => line)
795
- });
796
- response.body.breakpoints.forEach((raw, index) => {
797
- // node debug adapter returns more breakpoints sometimes
798
- if (enabled[index]) {
799
- enabled[index].update({ raw });
800
- }
801
- });
802
- } catch (error) {
803
- // could be error or promise rejection of DebugProtocol.SetBreakpointsResponse
804
- if (error instanceof Error) {
805
- console.error(`Error setting breakpoints: ${error.message}`);
806
- } else {
807
- // handle adapters that send failed DebugProtocol.SetBreakpointsResponse for invalid breakpoints
808
- const genericMessage: string = 'Breakpoint not valid for current debug session';
809
- const message: string = error.message ? `${error.message}` : genericMessage;
810
- console.warn(`Could not handle breakpoints for ${affectedUri}: ${message}, disabling...`);
811
- enabled.forEach(b => b.update({
812
- raw: {
813
- verified: false,
814
- message
815
- }
816
- }));
817
- }
818
- }
819
- this.setSourceBreakpoints(affectedUri, all);
820
- }
821
-
822
- protected async sendInstructionBreakpoints(): Promise<void> {
823
- if (!this.capabilities.supportsInstructionBreakpoints) {
824
- return;
825
- }
826
- const all = this.breakpoints.getInstructionBreakpoints().map(breakpoint => new DebugInstructionBreakpoint(breakpoint, this.asDebugBreakpointOptions()));
827
- const enabled = all.filter(breakpoint => breakpoint.enabled);
828
- try {
829
- const response = await this.sendRequest('setInstructionBreakpoints', {
830
- breakpoints: enabled.map(renderable => renderable.origin),
831
- });
832
- response.body.breakpoints.forEach((raw, index) => enabled[index]?.update({ raw }));
833
- } catch {
834
- enabled.forEach(breakpoint => breakpoint.update({ raw: { verified: false } }));
835
- }
836
- this.setBreakpoints(BreakpointManager.INSTRUCTION_URI, all);
837
- }
838
-
839
- protected setBreakpoints(uri: URI, breakpoints: DebugBreakpoint[]): void {
840
- this._breakpoints.set(uri.toString(), breakpoints);
841
- this.fireDidChangeBreakpoints(uri);
842
- }
843
-
844
- protected setSourceBreakpoints(uri: URI, breakpoints: DebugSourceBreakpoint[]): void {
845
- const distinct = this.dedupSourceBreakpoints(breakpoints);
846
- this.setBreakpoints(uri, distinct);
847
- }
848
-
849
- protected dedupSourceBreakpoints(all: DebugSourceBreakpoint[]): DebugSourceBreakpoint[] {
850
- const positions = new Map<string, DebugSourceBreakpoint>();
851
- for (const breakpoint of all) {
852
- let primary = positions.get(breakpoint.renderPosition()) || breakpoint;
853
- if (primary !== breakpoint) {
854
- let secondary = breakpoint;
855
- if (secondary.raw && secondary.raw.line === secondary.origin.raw.line && secondary.raw.column === secondary.origin.raw.column) {
856
- [primary, secondary] = [breakpoint, primary];
857
- }
858
- primary.origins.push(...secondary.origins);
859
- }
860
- positions.set(primary.renderPosition(), primary);
861
- }
862
- return [...positions.values()];
863
- }
864
-
865
- protected *getAffectedUris(uri?: URI): IterableIterator<URI> {
866
- if (uri) {
867
- yield uri;
868
- } else {
869
- for (const uriString of this.breakpoints.getUris()) {
870
- yield new URI(uriString);
871
- }
872
- yield BreakpointManager.FUNCTION_URI;
873
- yield BreakpointManager.EXCEPTION_URI;
874
- }
875
- }
876
-
877
- protected asDebugBreakpointOptions(): DebugBreakpointOptions {
878
- const { labelProvider, breakpoints, editorManager } = this;
879
- return { labelProvider, breakpoints, editorManager, session: this };
880
- }
881
-
882
- get label(): string {
883
- const suffixes = [];
884
- if (InternalDebugSessionOptions.is(this.options) && this.options.id) {
885
- suffixes.push(String(this.options.id + 1));
886
- }
887
- if (this.workspaceService.isMultiRootWorkspaceOpened && this.options.workspaceFolderUri) {
888
- suffixes.push(this.labelProvider.getName(new URI(this.options.workspaceFolderUri)));
889
- }
890
- return suffixes.length === 0 ? this.configuration.name : this.configuration.name + ` (${suffixes.join(' - ')})`;
891
- }
892
-
893
- get visible(): boolean {
894
- return this.state > DebugState.Inactive;
895
- }
896
-
897
- render(): React.ReactNode {
898
- let label = '';
899
- const state = this.state === DebugState.Stopped ? nls.localizeByDefault('Paused') : nls.localizeByDefault('Running');
900
- const child = this.getSingleChildSession();
901
- if (child && child.configuration.compact) {
902
- // Inlines the name of the child debug session
903
- label = `: ${child.label}`;
904
- }
905
- return <div className='theia-debug-session' title='Session'>
906
- <span className='label'>{this.label + label}</span>
907
- <span className='status'>{state}</span>
908
- </div>;
909
- }
910
-
911
- *getElements(): IterableIterator<DebugThread | DebugSession> {
912
- const child = this.getSingleChildSession();
913
- if (child && child.configuration.compact) {
914
- // Inlines the elements of the child debug session
915
- return yield* child.getElements();
916
- }
917
- yield* this.threads;
918
- yield* this.childSessions.values();
919
- }
920
-
921
- protected getSingleChildSession(): DebugSession | undefined {
922
- if (this._threads.size === 0 && this.childSessions.size === 1) {
923
- const child = this.childSessions.values().next().value as DebugSession;
924
- return child;
925
- }
926
- return undefined;
927
- }
928
-
929
- protected async handleContinued({ body: { allThreadsContinued, threadId } }: DebugProtocol.ContinuedEvent): Promise<void> {
930
- if (allThreadsContinued !== false) {
931
- this.clearThreads();
932
- } else {
933
- this.clearThread(threadId);
934
- }
935
- };
936
-
937
- protected async handleStopped({ body }: DebugProtocol.StoppedEvent): Promise<void> {
938
- // Update thread list
939
- await this.updateThreads(body);
940
-
941
- // Update current thread's frames immediately
942
- await this.updateFrames();
943
- };
944
-
945
- protected async handleThread({ body: { reason, threadId } }: DebugProtocol.ThreadEvent): Promise<void> {
946
- if (reason === 'started') {
947
- this.scheduleUpdateThreads();
948
- } else if (reason === 'exited') {
949
- this._threads.delete(threadId);
950
- this.updateCurrentThread();
951
- }
952
- };
953
-
954
- protected registerDebugContributions(configType: string, connection: DebugSessionConnection): void {
955
- for (const contrib of this.debugContributionProvider.getContributions()) {
956
- contrib.register(configType, connection);
957
- }
958
- };
959
-
960
- /**
961
- * Returns the top-most parent session that is responsible for the console. If this session uses a {@link DebugConsoleMode.Separate separate console}
962
- * or does not have any parent session, undefined is returned.
963
- */
964
- public findConsoleParent(): DebugSession | undefined {
965
- if (this.configuration.consoleMode !== DebugConsoleMode.MergeWithParent) {
966
- return undefined;
967
- }
968
- let debugSession: DebugSession | undefined = this;
969
- do {
970
- debugSession = debugSession.parentSession;
971
- } while (debugSession?.parentSession && debugSession.configuration.consoleMode === DebugConsoleMode.MergeWithParent);
972
- return debugSession;
973
- }
974
- }
1
+ // *****************************************************************************
2
+ // Copyright (C) 2018 Red Hat, Inc. and others.
3
+ //
4
+ // This program and the accompanying materials are made available under the
5
+ // terms of the Eclipse Public License v. 2.0 which is available at
6
+ // http://www.eclipse.org/legal/epl-2.0.
7
+ //
8
+ // This Source Code may also be made available under the following Secondary
9
+ // Licenses when the conditions for such availability set forth in the Eclipse
10
+ // Public License v. 2.0 are satisfied: GNU General Public License, version 2
11
+ // with the GNU Classpath Exception which is available at
12
+ // https://www.gnu.org/software/classpath/license.html.
13
+ //
14
+ // SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0
15
+ // *****************************************************************************
16
+
17
+ /* eslint-disable @typescript-eslint/no-explicit-any */
18
+
19
+ import * as React from '@theia/core/shared/react';
20
+ import { LabelProvider } from '@theia/core/lib/browser';
21
+ import { DebugProtocol } from '@vscode/debugprotocol';
22
+ import { Emitter, Event, DisposableCollection, Disposable, MessageClient, MessageType, Mutable, ContributionProvider } from '@theia/core/lib/common';
23
+ import { TerminalService } from '@theia/terminal/lib/browser/base/terminal-service';
24
+ import { EditorManager } from '@theia/editor/lib/browser';
25
+ import { CompositeTreeElement } from '@theia/core/lib/browser/source-tree';
26
+ import { DebugSessionConnection, DebugRequestTypes, DebugEventTypes } from './debug-session-connection';
27
+ import { DebugThread, StoppedDetails, DebugThreadData } from './model/debug-thread';
28
+ import { DebugScope } from './console/debug-console-items';
29
+ import { DebugStackFrame } from './model/debug-stack-frame';
30
+ import { DebugSource } from './model/debug-source';
31
+ import { DebugBreakpoint, DebugBreakpointOptions } from './model/debug-breakpoint';
32
+ import { DebugSourceBreakpoint } from './model/debug-source-breakpoint';
33
+ import debounce = require('p-debounce');
34
+ import URI from '@theia/core/lib/common/uri';
35
+ import { BreakpointManager } from './breakpoint/breakpoint-manager';
36
+ import { DebugConfigurationSessionOptions, InternalDebugSessionOptions, TestRunReference } from './debug-session-options';
37
+ import { DebugConfiguration, DebugConsoleMode } from '../common/debug-common';
38
+ import { SourceBreakpoint, ExceptionBreakpoint } from './breakpoint/breakpoint-marker';
39
+ import { TerminalWidgetOptions, TerminalWidget } from '@theia/terminal/lib/browser/base/terminal-widget';
40
+ import { DebugFunctionBreakpoint } from './model/debug-function-breakpoint';
41
+ import { FileService } from '@theia/filesystem/lib/browser/file-service';
42
+ import { DebugContribution } from './debug-contribution';
43
+ import { Deferred, waitForEvent } from '@theia/core/lib/common/promise-util';
44
+ import { WorkspaceService } from '@theia/workspace/lib/browser';
45
+ import { DebugInstructionBreakpoint } from './model/debug-instruction-breakpoint';
46
+ import { nls } from '@theia/core';
47
+ import { TestService, TestServices } from '@theia/test/lib/browser/test-service';
48
+ import { DebugSessionManager } from './debug-session-manager';
49
+
50
+ export enum DebugState {
51
+ Inactive,
52
+ Initializing,
53
+ Running,
54
+ Stopped
55
+ }
56
+ /**
57
+ * The mapped string values must not change as they are used for the `debugState` when context closure.
58
+ * For more details see the `Debugger contexts` section of the [official doc](https://code.visualstudio.com/api/references/when-clause-contexts#available-contexts).
59
+ */
60
+ export function debugStateContextValue(state: DebugState): string {
61
+ switch (state) {
62
+ case DebugState.Initializing: return 'initializing';
63
+ case DebugState.Stopped: return 'stopped';
64
+ case DebugState.Running: return 'running';
65
+ default: return 'inactive';
66
+ }
67
+ }
68
+
69
+ // FIXME: make injectable to allow easily inject services
70
+ export class DebugSession implements CompositeTreeElement {
71
+ protected readonly deferredOnDidConfigureCapabilities = new Deferred<void>();
72
+
73
+ protected readonly onDidChangeEmitter = new Emitter<void>();
74
+ readonly onDidChange: Event<void> = this.onDidChangeEmitter.event;
75
+ protected fireDidChange(): void {
76
+ this.onDidChangeEmitter.fire(undefined);
77
+ }
78
+ protected readonly onDidFocusStackFrameEmitter = new Emitter<DebugStackFrame | undefined>();
79
+ get onDidFocusStackFrame(): Event<DebugStackFrame | undefined> {
80
+ return this.onDidFocusStackFrameEmitter.event;
81
+ }
82
+
83
+ protected readonly onDidFocusThreadEmitter = new Emitter<DebugThread | undefined>();
84
+ get onDidFocusThread(): Event<DebugThread | undefined> {
85
+ return this.onDidFocusThreadEmitter.event;
86
+ }
87
+
88
+ protected readonly onDidChangeBreakpointsEmitter = new Emitter<URI>();
89
+ readonly onDidChangeBreakpoints: Event<URI> = this.onDidChangeBreakpointsEmitter.event;
90
+ protected fireDidChangeBreakpoints(uri: URI): void {
91
+ this.onDidChangeBreakpointsEmitter.fire(uri);
92
+ }
93
+
94
+ protected readonly childSessions = new Map<string, DebugSession>();
95
+ protected readonly toDispose = new DisposableCollection();
96
+
97
+ protected isStopping: boolean = false;
98
+
99
+ constructor(
100
+ readonly id: string,
101
+ readonly options: DebugConfigurationSessionOptions,
102
+ readonly parentSession: DebugSession | undefined,
103
+ testService: TestService,
104
+ testRun: TestRunReference | undefined,
105
+ sessionManager: DebugSessionManager,
106
+ protected readonly connection: DebugSessionConnection,
107
+ protected readonly terminalServer: TerminalService,
108
+ protected readonly editorManager: EditorManager,
109
+ protected readonly breakpoints: BreakpointManager,
110
+ protected readonly labelProvider: LabelProvider,
111
+ protected readonly messages: MessageClient,
112
+ protected readonly fileService: FileService,
113
+ protected readonly debugContributionProvider: ContributionProvider<DebugContribution>,
114
+ protected readonly workspaceService: WorkspaceService,
115
+ /**
116
+ * Number of millis after a `stop` request times out. It's 5 seconds by default.
117
+ */
118
+ protected readonly stopTimeout = 5_000,
119
+ ) {
120
+ this.connection.onRequest('runInTerminal', (request: DebugProtocol.RunInTerminalRequest) => this.runInTerminal(request));
121
+ this.connection.onDidClose(() => {
122
+ this.toDispose.dispose();
123
+ });
124
+ this.registerDebugContributions(options.configuration.type, this.connection);
125
+
126
+ if (parentSession) {
127
+ parentSession.childSessions.set(id, this);
128
+ this.toDispose.push(Disposable.create(() => {
129
+ this.parentSession?.childSessions?.delete(id);
130
+ }));
131
+ }
132
+ if (testRun) {
133
+ try {
134
+ const run = TestServices.withTestRun(testService, testRun.controllerId, testRun.runId);
135
+ run.onDidChangeProperty(evt => {
136
+ if (evt.isRunning === false) {
137
+ sessionManager.terminateSession(this);
138
+ }
139
+ });
140
+ } catch (err) {
141
+ console.error(err);
142
+ }
143
+ }
144
+
145
+ this.connection.onDidClose(() => this.toDispose.dispose());
146
+ this.toDispose.pushAll([
147
+ this.onDidChangeEmitter,
148
+ this.onDidChangeBreakpointsEmitter,
149
+ Disposable.create(() => {
150
+ this.clearBreakpoints();
151
+ this.doUpdateThreads([]);
152
+ }),
153
+ this.connection,
154
+ this.connection.on('initialized', () => this.configure()),
155
+ this.connection.on('breakpoint', ({ body }) => this.updateBreakpoint(body)),
156
+ this.connection.on('continued', e => this.handleContinued(e)),
157
+ this.connection.on('stopped', e => this.handleStopped(e)),
158
+ this.connection.on('thread', e => this.handleThread(e)),
159
+ this.connection.on('capabilities', event => this.updateCapabilities(event.body.capabilities)),
160
+ this.breakpoints.onDidChangeMarkers(uri => this.updateBreakpoints({ uri, sourceModified: true }))
161
+ ]);
162
+ }
163
+
164
+ get onDispose(): Event<void> {
165
+ return this.toDispose.onDispose;
166
+ }
167
+
168
+ get configuration(): DebugConfiguration {
169
+ return this.options.configuration;
170
+ }
171
+
172
+ protected _capabilities: DebugProtocol.Capabilities = {};
173
+ get capabilities(): DebugProtocol.Capabilities {
174
+ return this._capabilities;
175
+ }
176
+
177
+ protected readonly sources = new Map<string, DebugSource>();
178
+ getSource(raw: DebugProtocol.Source): DebugSource {
179
+ const uri = DebugSource.toUri(raw).toString();
180
+ const source = this.sources.get(uri) || new DebugSource(this, this.editorManager, this.labelProvider);
181
+ source.update({ raw });
182
+ this.sources.set(uri, source);
183
+ return source;
184
+ }
185
+
186
+ getSourceForUri(uri: URI): DebugSource | undefined {
187
+ return this.sources.get(uri.toString());
188
+ }
189
+
190
+ async toSource(uri: URI): Promise<DebugSource> {
191
+ const source = this.getSourceForUri(uri);
192
+ if (source) {
193
+ return source;
194
+ }
195
+
196
+ return this.getSource(await this.toDebugSource(uri));
197
+ }
198
+
199
+ async toDebugSource(uri: URI): Promise<DebugProtocol.Source> {
200
+ if (uri.scheme === DebugSource.SCHEME) {
201
+ return {
202
+ name: uri.path.toString(),
203
+ sourceReference: Number(uri.query)
204
+ };
205
+ }
206
+ const name = uri.displayName;
207
+ let path;
208
+ const underlying = await this.fileService.toUnderlyingResource(uri);
209
+ if (underlying.scheme === 'file') {
210
+ path = await this.fileService.fsPath(underlying);
211
+ } else {
212
+ path = uri.toString();
213
+ }
214
+ return { name, path };
215
+ }
216
+
217
+ protected _threads = new Map<number, DebugThread>();
218
+ get threads(): IterableIterator<DebugThread> {
219
+ return this._threads.values();
220
+ }
221
+
222
+ get threadCount(): number {
223
+ return this._threads.size;
224
+ }
225
+
226
+ *getThreads(filter: (thread: DebugThread) => boolean): IterableIterator<DebugThread> {
227
+ for (const thread of this.threads) {
228
+ if (filter(thread)) {
229
+ yield thread;
230
+ }
231
+ }
232
+ }
233
+
234
+ get runningThreads(): IterableIterator<DebugThread> {
235
+ return this.getThreads(thread => !thread.stopped);
236
+ }
237
+
238
+ get stoppedThreads(): IterableIterator<DebugThread> {
239
+ return this.getThreads(thread => thread.stopped);
240
+ }
241
+
242
+ async pauseAll(): Promise<void> {
243
+ const promises: Promise<void>[] = [];
244
+ for (const thread of this.runningThreads) {
245
+ promises.push((async () => {
246
+ try {
247
+ await thread.pause();
248
+ } catch (e) {
249
+ console.error('pauseAll failed:', e);
250
+ }
251
+ })());
252
+ }
253
+ await Promise.all(promises);
254
+ }
255
+
256
+ async continueAll(): Promise<void> {
257
+ const promises: Promise<void>[] = [];
258
+ for (const thread of this.stoppedThreads) {
259
+ promises.push((async () => {
260
+ try {
261
+ await thread.continue();
262
+ } catch (e) {
263
+ console.error('continueAll failed:', e);
264
+ }
265
+ })());
266
+ }
267
+ await Promise.all(promises);
268
+ }
269
+
270
+ get currentFrame(): DebugStackFrame | undefined {
271
+ return this.currentThread && this.currentThread.currentFrame;
272
+ }
273
+
274
+ protected _currentThread: DebugThread | undefined;
275
+ protected readonly toDisposeOnCurrentThread = new DisposableCollection();
276
+ get currentThread(): DebugThread | undefined {
277
+ return this._currentThread;
278
+ }
279
+ set currentThread(thread: DebugThread | undefined) {
280
+ if (this._currentThread?.id === thread?.id) {
281
+ return;
282
+ }
283
+ this.toDisposeOnCurrentThread.dispose();
284
+ this._currentThread = thread;
285
+ this.onDidFocusThreadEmitter.fire(thread);
286
+ this.fireDidChange();
287
+ if (thread) {
288
+ this.toDisposeOnCurrentThread.push(thread.onDidChanged(() => this.fireDidChange()));
289
+ this.toDisposeOnCurrentThread.push(thread.onDidFocusStackFrame(frame => this.onDidFocusStackFrameEmitter.fire(frame)));
290
+
291
+ // If this thread is missing stack frame information, then load that.
292
+ this.updateFrames();
293
+ }
294
+ }
295
+
296
+ get state(): DebugState {
297
+ if (this.connection.disposed) {
298
+ return DebugState.Inactive;
299
+ }
300
+ if (!this.initialized) {
301
+ return DebugState.Initializing;
302
+ }
303
+ const thread = this.currentThread;
304
+ if (thread) {
305
+ return thread.stopped ? DebugState.Stopped : DebugState.Running;
306
+ }
307
+ return !!this.stoppedThreads.next().value ? DebugState.Stopped : DebugState.Running;
308
+ }
309
+
310
+ async getScopes(): Promise<DebugScope[]> {
311
+ const { currentFrame } = this;
312
+ return currentFrame ? currentFrame.getScopes() : [];
313
+ }
314
+
315
+ async start(): Promise<void> {
316
+ await this.initialize();
317
+ await this.launchOrAttach();
318
+ }
319
+
320
+ protected async initialize(): Promise<void> {
321
+ try {
322
+ const response = await this.connection.sendRequest('initialize', {
323
+ clientID: 'Theia',
324
+ clientName: 'Theia IDE',
325
+ adapterID: this.configuration.type,
326
+ locale: 'en-US',
327
+ linesStartAt1: true,
328
+ columnsStartAt1: true,
329
+ pathFormat: 'path',
330
+ supportsVariableType: false,
331
+ supportsVariablePaging: false,
332
+ supportsRunInTerminalRequest: true
333
+ });
334
+ this.updateCapabilities(response?.body || {});
335
+ this.didReceiveCapabilities.resolve();
336
+ } catch (err) {
337
+ this.didReceiveCapabilities.reject(err);
338
+ throw err;
339
+ }
340
+ }
341
+
342
+ protected async launchOrAttach(): Promise<void> {
343
+ try {
344
+ await this.sendRequest((this.configuration.request as keyof DebugRequestTypes), this.configuration);
345
+ } catch (reason) {
346
+ this.messages.showMessage({
347
+ type: MessageType.Error,
348
+ text: reason.message || 'Debug session initialization failed. See console for details.',
349
+ options: {
350
+ timeout: 10000
351
+ }
352
+ });
353
+ throw reason;
354
+ }
355
+ }
356
+
357
+ /**
358
+ * The `send('initialize')` request could resolve later than `on('initialized')` emits the event.
359
+ * Hence, the `configure` would use the empty object `capabilities`.
360
+ * Using the empty `capabilities` could result in missing exception breakpoint filters, as
361
+ * always `capabilities.exceptionBreakpointFilters` is falsy. This deferred promise works
362
+ * around this timing issue. https://github.com/eclipse-theia/theia/issues/11886
363
+ */
364
+ protected didReceiveCapabilities = new Deferred<void>();
365
+ protected initialized = false;
366
+ protected async configure(): Promise<void> {
367
+ await this.didReceiveCapabilities.promise;
368
+ if (this.capabilities.exceptionBreakpointFilters) {
369
+ const exceptionBreakpoints = [];
370
+ for (const filter of this.capabilities.exceptionBreakpointFilters) {
371
+ const origin = this.breakpoints.getExceptionBreakpoint(filter.filter);
372
+ exceptionBreakpoints.push(ExceptionBreakpoint.create(filter, origin));
373
+ }
374
+ this.breakpoints.setExceptionBreakpoints(exceptionBreakpoints);
375
+ }
376
+ await this.updateBreakpoints({ sourceModified: false });
377
+ if (this.capabilities.supportsConfigurationDoneRequest) {
378
+ await this.sendRequest('configurationDone', {});
379
+ }
380
+ this.initialized = true;
381
+ await this.updateThreads(undefined);
382
+ }
383
+
384
+ canTerminate(): boolean {
385
+ return !!this.capabilities.supportsTerminateRequest;
386
+ }
387
+
388
+ canRestart(): boolean {
389
+ return !!this.capabilities.supportsRestartRequest;
390
+ }
391
+
392
+ async restart(): Promise<void> {
393
+ if (this.canRestart()) {
394
+ await this.sendRequest('restart', {});
395
+ }
396
+ }
397
+
398
+ async stop(isRestart: boolean, callback: () => void): Promise<void> {
399
+ if (!this.isStopping) {
400
+ this.isStopping = true;
401
+ if (this.canTerminate()) {
402
+ const terminated = this.waitFor('terminated', this.stopTimeout);
403
+ try {
404
+ await this.connection.sendRequest('terminate', { restart: isRestart }, this.stopTimeout);
405
+ await terminated;
406
+ } catch (e) {
407
+ this.handleTerminateError(e);
408
+ }
409
+ } else {
410
+ const terminateDebuggee = this.initialized && this.capabilities.supportTerminateDebuggee;
411
+ try {
412
+ await this.sendRequest('disconnect', { restart: isRestart, terminateDebuggee }, this.stopTimeout);
413
+ } catch (e) {
414
+ this.handleDisconnectError(e);
415
+ }
416
+ }
417
+ callback();
418
+ }
419
+ }
420
+
421
+ /**
422
+ * Invoked when sending the `terminate` request to the debugger is rejected or timed out.
423
+ */
424
+ protected handleTerminateError(err: unknown): void {
425
+ console.error('Did not receive terminated event in time', err);
426
+ }
427
+
428
+ /**
429
+ * Invoked when sending the `disconnect` request to the debugger is rejected or timed out.
430
+ */
431
+ protected handleDisconnectError(err: unknown): void {
432
+ console.error('Error on disconnect', err);
433
+ }
434
+
435
+ async disconnect(isRestart: boolean, callback: () => void): Promise<void> {
436
+ if (!this.isStopping) {
437
+ this.isStopping = true;
438
+ await this.sendRequest('disconnect', { restart: isRestart });
439
+ callback();
440
+ }
441
+ }
442
+
443
+ async completions(text: string, column: number, line: number): Promise<DebugProtocol.CompletionItem[]> {
444
+ const frameId = this.currentFrame && this.currentFrame.raw.id;
445
+ const response = await this.sendRequest('completions', { frameId, text, column, line });
446
+ return response.body.targets;
447
+ }
448
+
449
+ async evaluate(expression: string, context?: string): Promise<DebugProtocol.EvaluateResponse['body']> {
450
+ const frameId = this.currentFrame && this.currentFrame.raw.id;
451
+ const response = await this.sendRequest('evaluate', { expression, frameId, context });
452
+ return response.body;
453
+ }
454
+
455
+ sendRequest<K extends keyof DebugRequestTypes>(command: K, args: DebugRequestTypes[K][0], timeout?: number): Promise<DebugRequestTypes[K][1]> {
456
+ return this.connection.sendRequest(command, args, timeout);
457
+ }
458
+
459
+ sendCustomRequest<T extends DebugProtocol.Response>(command: string, args?: any): Promise<T> {
460
+ return this.connection.sendCustomRequest(command, args);
461
+ }
462
+
463
+ on<K extends keyof DebugEventTypes>(kind: K, listener: (e: DebugEventTypes[K]) => any): Disposable {
464
+ return this.connection.on(kind, listener);
465
+ }
466
+
467
+ waitFor<K extends keyof DebugEventTypes>(kind: K, ms: number): Promise<void> {
468
+ return waitForEvent(this.connection.onEvent(kind), ms).then();
469
+ }
470
+
471
+ get onDidCustomEvent(): Event<DebugProtocol.Event> {
472
+ return this.connection.onDidCustomEvent;
473
+ }
474
+
475
+ protected async runInTerminal({ arguments: { title, cwd, args, env } }: DebugProtocol.RunInTerminalRequest): Promise<DebugProtocol.RunInTerminalResponse['body']> {
476
+ const terminal = await this.doCreateTerminal({ title, cwd, env, useServerTitle: false });
477
+ const { processId } = terminal;
478
+ await terminal.executeCommand({ cwd, args, env });
479
+ return { processId: await processId };
480
+ }
481
+
482
+ protected async doCreateTerminal(options: TerminalWidgetOptions): Promise<TerminalWidget> {
483
+ let terminal = undefined;
484
+ for (const t of this.terminalServer.all) {
485
+ if ((t.title.label === options.title || t.title.caption === options.title) && (await t.hasChildProcesses()) === false) {
486
+ terminal = t;
487
+ break;
488
+ }
489
+ }
490
+
491
+ if (!terminal) {
492
+ terminal = await this.terminalServer.newTerminal(options);
493
+ await terminal.start();
494
+ }
495
+ this.terminalServer.open(terminal);
496
+ return terminal;
497
+ }
498
+
499
+ protected clearThreads(): void {
500
+ for (const thread of this.threads) {
501
+ thread.clear();
502
+ }
503
+ this.updateCurrentThread();
504
+ }
505
+
506
+ protected clearThread(threadId: number): void {
507
+ const thread = this._threads.get(threadId);
508
+ if (thread) {
509
+ thread.clear();
510
+ }
511
+ this.updateCurrentThread();
512
+ }
513
+
514
+ protected readonly scheduleUpdateThreads = debounce(() => this.updateThreads(undefined), 100);
515
+ protected pendingThreads = Promise.resolve();
516
+
517
+ updateThreads(stoppedDetails: StoppedDetails | undefined): Promise<void> {
518
+ return this.pendingThreads = this.pendingThreads.then(async () => {
519
+ try {
520
+ const response = await this.sendRequest('threads', {});
521
+ // java debugger returns an empty body sometimes
522
+ const threads = response && response.body && response.body.threads || [];
523
+ this.doUpdateThreads(threads, stoppedDetails);
524
+ } catch (e) {
525
+ console.error('updateThreads failed:', e);
526
+ }
527
+ });
528
+ }
529
+
530
+ protected doUpdateThreads(threads: DebugProtocol.Thread[], stoppedDetails?: StoppedDetails): void {
531
+ const existing = this._threads;
532
+ this._threads = new Map();
533
+ for (const raw of threads) {
534
+ const id = raw.id;
535
+ const thread = existing.get(id) || new DebugThread(this);
536
+ this._threads.set(id, thread);
537
+ const data: Partial<Mutable<DebugThreadData>> = { raw };
538
+ if (stoppedDetails) {
539
+ if (stoppedDetails.threadId === id) {
540
+ data.stoppedDetails = stoppedDetails;
541
+ } else if (stoppedDetails.allThreadsStopped) {
542
+ data.stoppedDetails = {
543
+ // When a debug adapter notifies us that all threads are stopped,
544
+ // we do not know why the others are stopped, so we should default
545
+ // to something generic.
546
+ reason: '',
547
+ };
548
+ }
549
+ }
550
+ thread.update(data);
551
+ }
552
+ this.updateCurrentThread(stoppedDetails);
553
+ }
554
+
555
+ protected updateCurrentThread(stoppedDetails?: StoppedDetails): void {
556
+ const { currentThread } = this;
557
+ let threadId = currentThread && currentThread.raw.id;
558
+ if (stoppedDetails && !stoppedDetails.preserveFocusHint && !!stoppedDetails.threadId) {
559
+ threadId = stoppedDetails.threadId;
560
+ }
561
+ this.currentThread = typeof threadId === 'number' && this._threads.get(threadId)
562
+ || this._threads.values().next().value;
563
+ }
564
+
565
+ protected async updateFrames(): Promise<void> {
566
+ const thread = this._currentThread;
567
+ if (!thread || thread.pendingFrameCount || thread.frameCount) {
568
+ return;
569
+ }
570
+ if (this.capabilities.supportsDelayedStackTraceLoading) {
571
+ await thread.fetchFrames(1);
572
+ await thread.fetchFrames(19);
573
+ } else {
574
+ await thread.fetchFrames();
575
+ }
576
+ }
577
+
578
+ protected updateCapabilities(capabilities: DebugProtocol.Capabilities): void {
579
+ Object.assign(this._capabilities, capabilities);
580
+ this.deferredOnDidConfigureCapabilities.resolve();
581
+ }
582
+
583
+ protected readonly _breakpoints = new Map<string, DebugBreakpoint[]>();
584
+ get breakpointUris(): IterableIterator<string> {
585
+ return this._breakpoints.keys();
586
+ }
587
+
588
+ getSourceBreakpoints(uri?: URI): DebugSourceBreakpoint[] {
589
+ const breakpoints = [];
590
+ for (const breakpoint of this.getBreakpoints(uri)) {
591
+ if (breakpoint instanceof DebugSourceBreakpoint) {
592
+ breakpoints.push(breakpoint);
593
+ }
594
+ }
595
+ return breakpoints;
596
+ }
597
+
598
+ getFunctionBreakpoints(): DebugFunctionBreakpoint[] {
599
+ return this.getBreakpoints(BreakpointManager.FUNCTION_URI).filter((breakpoint): breakpoint is DebugFunctionBreakpoint => breakpoint instanceof DebugFunctionBreakpoint);
600
+ }
601
+
602
+ getInstructionBreakpoints(): DebugInstructionBreakpoint[] {
603
+ if (this.capabilities.supportsInstructionBreakpoints) {
604
+ return this.getBreakpoints(BreakpointManager.INSTRUCTION_URI)
605
+ .filter((breakpoint): breakpoint is DebugInstructionBreakpoint => breakpoint instanceof DebugInstructionBreakpoint);
606
+ }
607
+ return this.breakpoints.getInstructionBreakpoints().map(origin => new DebugInstructionBreakpoint(origin, this.asDebugBreakpointOptions()));
608
+ }
609
+
610
+ getBreakpoints(uri?: URI): DebugBreakpoint[] {
611
+ if (uri) {
612
+ return this._breakpoints.get(uri.toString()) || [];
613
+ }
614
+ const result = [];
615
+ for (const breakpoints of this._breakpoints.values()) {
616
+ result.push(...breakpoints);
617
+ }
618
+ return result;
619
+ }
620
+
621
+ getBreakpoint(id: string): DebugBreakpoint | undefined {
622
+ for (const breakpoints of this._breakpoints.values()) {
623
+ const breakpoint = breakpoints.find(b => b.id === id);
624
+ if (breakpoint) {
625
+ return breakpoint;
626
+ }
627
+
628
+ }
629
+ return undefined;
630
+ }
631
+
632
+ protected clearBreakpoints(): void {
633
+ const uris = [...this._breakpoints.keys()];
634
+ this._breakpoints.clear();
635
+ for (const uri of uris) {
636
+ this.fireDidChangeBreakpoints(new URI(uri));
637
+ }
638
+ }
639
+
640
+ protected updatingBreakpoints = false;
641
+
642
+ protected updateBreakpoint(body: DebugProtocol.BreakpointEvent['body']): void {
643
+ this.updatingBreakpoints = true;
644
+ try {
645
+ const raw = body.breakpoint;
646
+ if (body.reason === 'new') {
647
+ if (raw.source && typeof raw.line === 'number') {
648
+ const uri = DebugSource.toUri(raw.source);
649
+ const origin = SourceBreakpoint.create(uri, { line: raw.line, column: raw.column });
650
+ if (this.breakpoints.addBreakpoint(origin)) {
651
+ const breakpoints = this.getSourceBreakpoints(uri);
652
+ const breakpoint = new DebugSourceBreakpoint(origin, this.asDebugBreakpointOptions());
653
+ breakpoint.update({ raw });
654
+ breakpoints.push(breakpoint);
655
+ this.setSourceBreakpoints(uri, breakpoints);
656
+ }
657
+ }
658
+ }
659
+ if (body.reason === 'removed' && raw.id) {
660
+ const toRemove = this.findBreakpoint(b => b.idFromAdapter === raw.id);
661
+ if (toRemove) {
662
+ toRemove.remove();
663
+ const breakpoints = this.getBreakpoints(toRemove.uri);
664
+ const index = breakpoints.indexOf(toRemove);
665
+ if (index !== -1) {
666
+ breakpoints.splice(index, 1);
667
+ this.setBreakpoints(toRemove.uri, breakpoints);
668
+ }
669
+ }
670
+ }
671
+ if (body.reason === 'changed' && raw.id) {
672
+ const toUpdate = this.findBreakpoint(b => b.idFromAdapter === raw.id);
673
+ if (toUpdate) {
674
+ toUpdate.update({ raw });
675
+ if (toUpdate instanceof DebugSourceBreakpoint) {
676
+ const sourceBreakpoints = this.getSourceBreakpoints(toUpdate.uri);
677
+ // in order to dedup again if a debugger converted line breakpoint to inline breakpoint
678
+ // i.e. assigned a column to a line breakpoint
679
+ this.setSourceBreakpoints(toUpdate.uri, sourceBreakpoints);
680
+ } else {
681
+ this.fireDidChangeBreakpoints(toUpdate.uri);
682
+ }
683
+ }
684
+ }
685
+ } finally {
686
+ this.updatingBreakpoints = false;
687
+ }
688
+ }
689
+ protected findBreakpoint(match: (breakpoint: DebugBreakpoint) => boolean): DebugBreakpoint | undefined {
690
+ for (const [, breakpoints] of this._breakpoints) {
691
+ for (const breakpoint of breakpoints) {
692
+ if (match(breakpoint)) {
693
+ return breakpoint;
694
+ }
695
+ }
696
+ }
697
+ return undefined;
698
+ }
699
+
700
+ protected async updateBreakpoints(options: {
701
+ uri?: URI,
702
+ sourceModified: boolean
703
+ }): Promise<void> {
704
+ if (this.updatingBreakpoints) {
705
+ return;
706
+ }
707
+ const { uri, sourceModified } = options;
708
+ await this.deferredOnDidConfigureCapabilities.promise;
709
+ for (const affectedUri of this.getAffectedUris(uri)) {
710
+ if (affectedUri.toString() === BreakpointManager.EXCEPTION_URI.toString()) {
711
+ await this.sendExceptionBreakpoints();
712
+ } else if (affectedUri.toString() === BreakpointManager.FUNCTION_URI.toString()) {
713
+ await this.sendFunctionBreakpoints(affectedUri);
714
+ } else if (affectedUri.toString() === BreakpointManager.INSTRUCTION_URI.toString()) {
715
+ await this.sendInstructionBreakpoints();
716
+ } else {
717
+ await this.sendSourceBreakpoints(affectedUri, sourceModified);
718
+ }
719
+ }
720
+ }
721
+
722
+ protected async sendExceptionBreakpoints(): Promise<void> {
723
+ const filters: string[] = [];
724
+ const filterOptions: DebugProtocol.ExceptionFilterOptions[] | undefined = this.capabilities.supportsExceptionFilterOptions ? [] : undefined;
725
+ for (const breakpoint of this.breakpoints.getExceptionBreakpoints()) {
726
+ if (breakpoint.enabled) {
727
+ if (filterOptions) {
728
+ filterOptions.push({
729
+ filterId: breakpoint.raw.filter,
730
+ condition: breakpoint.condition
731
+ });
732
+ } else {
733
+ filters.push(breakpoint.raw.filter);
734
+ }
735
+ }
736
+ }
737
+ await this.sendRequest('setExceptionBreakpoints', { filters, filterOptions });
738
+ }
739
+
740
+ protected async sendFunctionBreakpoints(affectedUri: URI): Promise<void> {
741
+ const all = this.breakpoints.getFunctionBreakpoints().map(origin =>
742
+ new DebugFunctionBreakpoint(origin, this.asDebugBreakpointOptions())
743
+ );
744
+ const enabled = all.filter(b => b.enabled);
745
+ if (this.capabilities.supportsFunctionBreakpoints) {
746
+ try {
747
+ const response = await this.sendRequest('setFunctionBreakpoints', {
748
+ breakpoints: enabled.map(b => b.origin.raw)
749
+ });
750
+ // Apparently, `body` and `breakpoints` can be missing.
751
+ // https://github.com/eclipse-theia/theia/issues/11885
752
+ // https://github.com/microsoft/vscode/blob/80004351ccf0884b58359f7c8c801c91bb827d83/src/vs/workbench/contrib/debug/browser/debugSession.ts#L448-L449
753
+ if (response && response.body) {
754
+ response.body.breakpoints.forEach((raw, index) => {
755
+ // node debug adapter returns more breakpoints sometimes
756
+ if (enabled[index]) {
757
+ enabled[index].update({ raw });
758
+ }
759
+ });
760
+ }
761
+ } catch (error) {
762
+ // could be error or promise rejection of DebugProtocol.SetFunctionBreakpoints
763
+ if (error instanceof Error) {
764
+ console.error(`Error setting breakpoints: ${error.message}`);
765
+ } else {
766
+ // handle adapters that send failed DebugProtocol.SetFunctionBreakpoints for invalid breakpoints
767
+ const genericMessage: string = 'Function breakpoint not valid for current debug session';
768
+ const message: string = error.message ? `${error.message}` : genericMessage;
769
+ console.warn(`Could not handle function breakpoints: ${message}, disabling...`);
770
+ enabled.forEach(b => b.update({
771
+ raw: {
772
+ verified: false,
773
+ message
774
+ }
775
+ }));
776
+ }
777
+ }
778
+ }
779
+ this.setBreakpoints(affectedUri, all);
780
+ }
781
+
782
+ protected async sendSourceBreakpoints(affectedUri: URI, sourceModified?: boolean): Promise<void> {
783
+ const source = await this.toSource(affectedUri);
784
+ const all = this.breakpoints.findMarkers({ uri: affectedUri }).map(({ data }) =>
785
+ new DebugSourceBreakpoint(data, this.asDebugBreakpointOptions())
786
+ );
787
+ const enabled = all.filter(b => b.enabled);
788
+ try {
789
+ const breakpoints = enabled.map(({ origin }) => origin.raw);
790
+ const response = await this.sendRequest('setBreakpoints', {
791
+ source: source.raw,
792
+ sourceModified,
793
+ breakpoints,
794
+ lines: breakpoints.map(({ line }) => line)
795
+ });
796
+ response.body.breakpoints.forEach((raw, index) => {
797
+ // node debug adapter returns more breakpoints sometimes
798
+ if (enabled[index]) {
799
+ enabled[index].update({ raw });
800
+ }
801
+ });
802
+ } catch (error) {
803
+ // could be error or promise rejection of DebugProtocol.SetBreakpointsResponse
804
+ if (error instanceof Error) {
805
+ console.error(`Error setting breakpoints: ${error.message}`);
806
+ } else {
807
+ // handle adapters that send failed DebugProtocol.SetBreakpointsResponse for invalid breakpoints
808
+ const genericMessage: string = 'Breakpoint not valid for current debug session';
809
+ const message: string = error.message ? `${error.message}` : genericMessage;
810
+ console.warn(`Could not handle breakpoints for ${affectedUri}: ${message}, disabling...`);
811
+ enabled.forEach(b => b.update({
812
+ raw: {
813
+ verified: false,
814
+ message
815
+ }
816
+ }));
817
+ }
818
+ }
819
+ this.setSourceBreakpoints(affectedUri, all);
820
+ }
821
+
822
+ protected async sendInstructionBreakpoints(): Promise<void> {
823
+ if (!this.capabilities.supportsInstructionBreakpoints) {
824
+ return;
825
+ }
826
+ const all = this.breakpoints.getInstructionBreakpoints().map(breakpoint => new DebugInstructionBreakpoint(breakpoint, this.asDebugBreakpointOptions()));
827
+ const enabled = all.filter(breakpoint => breakpoint.enabled);
828
+ try {
829
+ const response = await this.sendRequest('setInstructionBreakpoints', {
830
+ breakpoints: enabled.map(renderable => renderable.origin),
831
+ });
832
+ response.body.breakpoints.forEach((raw, index) => enabled[index]?.update({ raw }));
833
+ } catch {
834
+ enabled.forEach(breakpoint => breakpoint.update({ raw: { verified: false } }));
835
+ }
836
+ this.setBreakpoints(BreakpointManager.INSTRUCTION_URI, all);
837
+ }
838
+
839
+ protected setBreakpoints(uri: URI, breakpoints: DebugBreakpoint[]): void {
840
+ this._breakpoints.set(uri.toString(), breakpoints);
841
+ this.fireDidChangeBreakpoints(uri);
842
+ }
843
+
844
+ protected setSourceBreakpoints(uri: URI, breakpoints: DebugSourceBreakpoint[]): void {
845
+ const distinct = this.dedupSourceBreakpoints(breakpoints);
846
+ this.setBreakpoints(uri, distinct);
847
+ }
848
+
849
+ protected dedupSourceBreakpoints(all: DebugSourceBreakpoint[]): DebugSourceBreakpoint[] {
850
+ const positions = new Map<string, DebugSourceBreakpoint>();
851
+ for (const breakpoint of all) {
852
+ let primary = positions.get(breakpoint.renderPosition()) || breakpoint;
853
+ if (primary !== breakpoint) {
854
+ let secondary = breakpoint;
855
+ if (secondary.raw && secondary.raw.line === secondary.origin.raw.line && secondary.raw.column === secondary.origin.raw.column) {
856
+ [primary, secondary] = [breakpoint, primary];
857
+ }
858
+ primary.origins.push(...secondary.origins);
859
+ }
860
+ positions.set(primary.renderPosition(), primary);
861
+ }
862
+ return [...positions.values()];
863
+ }
864
+
865
+ protected *getAffectedUris(uri?: URI): IterableIterator<URI> {
866
+ if (uri) {
867
+ yield uri;
868
+ } else {
869
+ for (const uriString of this.breakpoints.getUris()) {
870
+ yield new URI(uriString);
871
+ }
872
+ yield BreakpointManager.FUNCTION_URI;
873
+ yield BreakpointManager.EXCEPTION_URI;
874
+ }
875
+ }
876
+
877
+ protected asDebugBreakpointOptions(): DebugBreakpointOptions {
878
+ const { labelProvider, breakpoints, editorManager } = this;
879
+ return { labelProvider, breakpoints, editorManager, session: this };
880
+ }
881
+
882
+ get label(): string {
883
+ const suffixes = [];
884
+ if (InternalDebugSessionOptions.is(this.options) && this.options.id) {
885
+ suffixes.push(String(this.options.id + 1));
886
+ }
887
+ if (this.workspaceService.isMultiRootWorkspaceOpened && this.options.workspaceFolderUri) {
888
+ suffixes.push(this.labelProvider.getName(new URI(this.options.workspaceFolderUri)));
889
+ }
890
+ return suffixes.length === 0 ? this.configuration.name : this.configuration.name + ` (${suffixes.join(' - ')})`;
891
+ }
892
+
893
+ get visible(): boolean {
894
+ return this.state > DebugState.Inactive;
895
+ }
896
+
897
+ render(): React.ReactNode {
898
+ let label = '';
899
+ const state = this.state === DebugState.Stopped ? nls.localizeByDefault('Paused') : nls.localizeByDefault('Running');
900
+ const child = this.getSingleChildSession();
901
+ if (child && child.configuration.compact) {
902
+ // Inlines the name of the child debug session
903
+ label = `: ${child.label}`;
904
+ }
905
+ return <div className='theia-debug-session' title='Session'>
906
+ <span className='label'>{this.label + label}</span>
907
+ <span className='status'>{state}</span>
908
+ </div>;
909
+ }
910
+
911
+ *getElements(): IterableIterator<DebugThread | DebugSession> {
912
+ const child = this.getSingleChildSession();
913
+ if (child && child.configuration.compact) {
914
+ // Inlines the elements of the child debug session
915
+ return yield* child.getElements();
916
+ }
917
+ yield* this.threads;
918
+ yield* this.childSessions.values();
919
+ }
920
+
921
+ protected getSingleChildSession(): DebugSession | undefined {
922
+ if (this._threads.size === 0 && this.childSessions.size === 1) {
923
+ const child = this.childSessions.values().next().value as DebugSession;
924
+ return child;
925
+ }
926
+ return undefined;
927
+ }
928
+
929
+ protected async handleContinued({ body: { allThreadsContinued, threadId } }: DebugProtocol.ContinuedEvent): Promise<void> {
930
+ if (allThreadsContinued !== false) {
931
+ this.clearThreads();
932
+ } else {
933
+ this.clearThread(threadId);
934
+ }
935
+ };
936
+
937
+ protected async handleStopped({ body }: DebugProtocol.StoppedEvent): Promise<void> {
938
+ // Update thread list
939
+ await this.updateThreads(body);
940
+
941
+ // Update current thread's frames immediately
942
+ await this.updateFrames();
943
+ };
944
+
945
+ protected async handleThread({ body: { reason, threadId } }: DebugProtocol.ThreadEvent): Promise<void> {
946
+ if (reason === 'started') {
947
+ this.scheduleUpdateThreads();
948
+ } else if (reason === 'exited') {
949
+ this._threads.delete(threadId);
950
+ this.updateCurrentThread();
951
+ }
952
+ };
953
+
954
+ protected registerDebugContributions(configType: string, connection: DebugSessionConnection): void {
955
+ for (const contrib of this.debugContributionProvider.getContributions()) {
956
+ contrib.register(configType, connection);
957
+ }
958
+ };
959
+
960
+ /**
961
+ * Returns the top-most parent session that is responsible for the console. If this session uses a {@link DebugConsoleMode.Separate separate console}
962
+ * or does not have any parent session, undefined is returned.
963
+ */
964
+ public findConsoleParent(): DebugSession | undefined {
965
+ if (this.configuration.consoleMode !== DebugConsoleMode.MergeWithParent) {
966
+ return undefined;
967
+ }
968
+ let debugSession: DebugSession | undefined = this;
969
+ do {
970
+ debugSession = debugSession.parentSession;
971
+ } while (debugSession?.parentSession && debugSession.configuration.consoleMode === DebugConsoleMode.MergeWithParent);
972
+ return debugSession;
973
+ }
974
+ }