/
handler.ts
484 lines (427 loc) · 13.4 KB
/
handler.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import { JupyterFrontEnd } from '@jupyterlab/application';
import {
ISessionContext,
SessionContext,
ToolbarButton
} from '@jupyterlab/apputils';
import { ConsolePanel } from '@jupyterlab/console';
import { IChangedArgs } from '@jupyterlab/coreutils';
import { DocumentWidget } from '@jupyterlab/docregistry';
import { FileEditor } from '@jupyterlab/fileeditor';
import { NotebookPanel } from '@jupyterlab/notebook';
import { Kernel, KernelMessage, Session } from '@jupyterlab/services';
import { ITranslator, nullTranslator } from '@jupyterlab/translation';
import { bugIcon, Switch } from '@jupyterlab/ui-components';
import { Debugger } from './debugger';
import { IDebugger } from './tokens';
import { ConsoleHandler } from './handlers/console';
import { FileHandler } from './handlers/file';
import { NotebookHandler } from './handlers/notebook';
/**
* Add a bug icon to the widget toolbar to enable and disable debugging.
*
* @param widget The widget to add the debug toolbar button to.
* @param onClick The callback when the toolbar button is clicked.
*/
function updateIconButton(
widget: DebuggerHandler.SessionWidget[DebuggerHandler.SessionType],
onClick: () => void,
translator?: ITranslator
): ToolbarButton {
translator = translator || nullTranslator;
const trans = translator.load('jupyterlab');
const icon = new ToolbarButton({
className: 'jp-DebuggerBugButton',
icon: bugIcon,
tooltip: trans.__('Enable / Disable Debugger'),
onClick
});
widget.toolbar.addItem('debugger-icon', icon);
return icon;
}
/**
* Add a toggle button to the widget toolbar to enable and disable debugging.
*
* @param widget The widget to add the debug toolbar button to.
* @param onClick The callback when the toolbar button is clicked.
*/
function updateToggleButton(
widget: DebuggerHandler.SessionWidget[DebuggerHandler.SessionType],
sessionStarted: boolean,
onClick: () => void,
translator?: ITranslator
): Switch {
translator = translator || nullTranslator;
const trans = translator.load('jupyterlab');
const button = new Switch();
button.id = 'jp-debugger';
button.value = sessionStarted;
button.caption = trans.__('Enable / Disable Debugger');
button.handleEvent = (event: Event) => {
event.preventDefault();
switch (event.type) {
case 'click':
onClick();
break;
default:
break;
}
};
widget.toolbar.addItem('debugger-button', button);
return button;
}
/**
* A handler for debugging a widget.
*/
export class DebuggerHandler {
/**
* Instantiate a new DebuggerHandler.
*
* @param options The instantiation options for a DebuggerHandler.
*/
constructor(options: DebuggerHandler.IOptions) {
this._type = options.type;
this._shell = options.shell;
this._service = options.service;
}
/**
* Update a debug handler for the given widget, and
* handle kernel changed events.
*
* @param widget The widget to update.
* @param connection The session connection.
*/
async update(
widget: DebuggerHandler.SessionWidget[DebuggerHandler.SessionType],
connection: Session.ISessionConnection | null
): Promise<void> {
if (!connection) {
delete this._kernelChangedHandlers[widget.id];
delete this._statusChangedHandlers[widget.id];
delete this._iopubMessageHandlers[widget.id];
return this.updateWidget(widget, connection);
}
const kernelChanged = (): void => {
void this.updateWidget(widget, connection);
};
const kernelChangedHandler = this._kernelChangedHandlers[widget.id];
if (kernelChangedHandler) {
connection.kernelChanged.disconnect(kernelChangedHandler);
}
this._kernelChangedHandlers[widget.id] = kernelChanged;
connection.kernelChanged.connect(kernelChanged);
const statusChanged = (
_: Session.ISessionConnection,
status: Kernel.Status
): void => {
// FIXME-TRANS: Localizable?
if (status.endsWith('restarting')) {
void this.updateWidget(widget, connection);
}
};
const statusChangedHandler = this._statusChangedHandlers[widget.id];
if (statusChangedHandler) {
connection.statusChanged.disconnect(statusChangedHandler);
}
connection.statusChanged.connect(statusChanged);
this._statusChangedHandlers[widget.id] = statusChanged;
const iopubMessage = (
_: Session.ISessionConnection,
msg: KernelMessage.IIOPubMessage
): void => {
if (
msg.parent_header != {} &&
(msg.parent_header as KernelMessage.IHeader).msg_type ==
'execute_request' &&
this._service.isStarted &&
!this._service.hasStoppedThreads()
) {
void this._service.displayDefinedVariables();
}
};
const iopubMessageHandler = this._iopubMessageHandlers[widget.id];
if (iopubMessageHandler) {
connection.iopubMessage.disconnect(iopubMessageHandler);
}
connection.iopubMessage.connect(iopubMessage);
this._iopubMessageHandlers[widget.id] = iopubMessage;
return this.updateWidget(widget, connection);
}
/**
* Update a debug handler for the given widget, and
* handle connection kernel changed events.
*
* @param widget The widget to update.
* @param sessionContext The session context.
*/
async updateContext(
widget: DebuggerHandler.SessionWidget[DebuggerHandler.SessionType],
sessionContext: ISessionContext
): Promise<void> {
const connectionChanged = (): void => {
const { session: connection } = sessionContext;
void this.update(widget, connection);
};
const contextKernelChangedHandlers = this._contextKernelChangedHandlers[
widget.id
];
if (contextKernelChangedHandlers) {
sessionContext.kernelChanged.disconnect(contextKernelChangedHandlers);
}
this._contextKernelChangedHandlers[widget.id] = connectionChanged;
sessionContext.kernelChanged.connect(connectionChanged);
return this.update(widget, sessionContext.session);
}
/**
* Update a debug handler for the given widget.
*
* @param widget The widget to update.
* @param connection The session connection.
*/
async updateWidget(
widget: DebuggerHandler.SessionWidget[DebuggerHandler.SessionType],
connection: Session.ISessionConnection | null
): Promise<void> {
if (!this._service.model || !connection) {
return;
}
const hasFocus = (): boolean => {
return this._shell.currentWidget === widget;
};
const updateAttribute = (): void => {
if (!this._handlers[widget.id]) {
widget.node.removeAttribute('data-jp-debugger');
return;
}
widget.node.setAttribute('data-jp-debugger', 'true');
};
const createHandler = (): void => {
if (this._handlers[widget.id]) {
return;
}
switch (this._type) {
case 'notebook':
this._handlers[widget.id] = new NotebookHandler({
debuggerService: this._service,
widget: widget as NotebookPanel
});
break;
case 'console':
this._handlers[widget.id] = new ConsoleHandler({
debuggerService: this._service,
widget: widget as ConsolePanel
});
break;
case 'file':
this._handlers[widget.id] = new FileHandler({
debuggerService: this._service,
widget: widget as DocumentWidget<FileEditor>
});
break;
default:
throw Error(`No handler for the type ${this._type}`);
}
updateAttribute();
};
const removeHandlers = (): void => {
const handler = this._handlers[widget.id];
if (!handler) {
return;
}
handler.dispose();
delete this._handlers[widget.id];
delete this._kernelChangedHandlers[widget.id];
delete this._statusChangedHandlers[widget.id];
delete this._iopubMessageHandlers[widget.id];
delete this._contextKernelChangedHandlers[widget.id];
// Clear the model if the handler being removed corresponds
// to the current active debug session, or if the connection
// does not have a kernel.
if (
this._service.session?.connection?.path === connection?.path ||
!this._service.session?.connection?.kernel
) {
const model = this._service.model;
model.clear();
}
updateAttribute();
};
const addToolbarButton = (): void => {
if (!this._iconButtons[widget.id]) {
this._iconButtons[widget.id] = updateIconButton(
widget,
toggleDebugging
);
}
if (!this._toggleButtons[widget.id]) {
this._toggleButtons[widget.id] = updateToggleButton(
widget,
this._service.isStarted,
toggleDebugging
);
}
this._toggleButtons[widget.id]!.value = this._service.isStarted;
};
const removeToolbarButton = (): void => {
if (!this._iconButtons[widget.id]) {
return;
} else {
this._iconButtons[widget.id]!.dispose();
delete this._iconButtons[widget.id];
}
if (!this._toggleButtons[widget.id]) {
return;
} else {
this._toggleButtons[widget.id]!.dispose();
delete this._toggleButtons[widget.id];
}
};
const toggleDebugging = async (): Promise<void> => {
// bail if the widget doesn't have focus
if (!hasFocus()) {
return;
}
if (
this._service.isStarted &&
this._previousConnection?.id === connection?.id
) {
if (this._toggleButtons[widget.id]) {
this._toggleButtons[widget.id]!.value = false;
}
this._service.session!.connection = connection;
await this._service.stop();
removeHandlers();
} else {
if (this._toggleButtons[widget.id]) {
this._toggleButtons[widget.id]!.value = true;
}
this._service.session!.connection = connection;
this._previousConnection = connection;
await this._service.restoreState(true);
await this._service.displayDefinedVariables();
createHandler();
}
};
const debuggingEnabled = await this._service.isAvailable(connection);
if (!debuggingEnabled) {
removeHandlers();
removeToolbarButton();
return;
}
// update the active debug session
if (!this._service.session) {
this._service.session = new Debugger.Session({ connection });
} else {
this._previousConnection = this._service.session!.connection?.kernel
? this._service.session.connection
: null;
this._service.session.connection = connection;
}
await this._service.restoreState(false);
if (this._service.isStarted && !this._service.hasStoppedThreads()) {
await this._service.displayDefinedVariables();
}
addToolbarButton();
// check the state of the debug session
if (!this._service.isStarted) {
removeHandlers();
this._service.session.connection = this._previousConnection ?? connection;
await this._service.restoreState(false);
return;
}
// if the debugger is started but there is no handler, create a new one
createHandler();
this._previousConnection = connection;
// listen to the disposed signals
widget.disposed.connect(removeHandlers);
}
private _type: DebuggerHandler.SessionType;
private _shell: JupyterFrontEnd.IShell;
private _service: IDebugger;
private _previousConnection: Session.ISessionConnection | null;
private _handlers: {
[id: string]: DebuggerHandler.SessionHandler[DebuggerHandler.SessionType];
} = {};
private _contextKernelChangedHandlers: {
[id: string]: (
sender: SessionContext,
args: IChangedArgs<
Kernel.IKernelConnection,
Kernel.IKernelConnection,
'kernel'
>
) => void;
} = {};
private _kernelChangedHandlers: {
[id: string]: (
sender: Session.ISessionConnection,
args: IChangedArgs<
Kernel.IKernelConnection,
Kernel.IKernelConnection,
'kernel'
>
) => void;
} = {};
private _statusChangedHandlers: {
[id: string]: (
sender: Session.ISessionConnection,
status: Kernel.Status
) => void;
} = {};
private _iopubMessageHandlers: {
[id: string]: (
sender: Session.ISessionConnection,
msg: KernelMessage.IIOPubMessage
) => void;
} = {};
private _iconButtons: {
[id: string]: ToolbarButton | undefined;
} = {};
private _toggleButtons: {
[id: string]: Switch | undefined;
} = {};
}
/**
* A namespace for DebuggerHandler `statics`
*/
export namespace DebuggerHandler {
/**
* Instantiation options for a DebuggerHandler.
*/
export interface IOptions {
/**
* The type of session.
*/
type: SessionType;
/**
* The application shell.
*/
shell: JupyterFrontEnd.IShell;
/**
* The debugger service.
*/
service: IDebugger;
}
/**
* The types of sessions that can be debugged.
*/
export type SessionType = keyof SessionHandler;
/**
* The types of handlers.
*/
export type SessionHandler = {
notebook: NotebookHandler;
console: ConsoleHandler;
file: FileHandler;
};
/**
* The types of widgets that can be debugged.
*/
export type SessionWidget = {
notebook: NotebookPanel;
console: ConsolePanel;
file: DocumentWidget;
};
}