@theia/debug 1.34.3 → 1.34.4

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