@jupyterlab/apputils 4.0.0-alpha.2 → 4.0.0-alpha.21

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 (92) hide show
  1. package/lib/clipboard.d.ts +1 -1
  2. package/lib/dialog.d.ts +73 -4
  3. package/lib/dialog.js +143 -30
  4. package/lib/dialog.js.map +1 -1
  5. package/lib/domutils.js.map +1 -1
  6. package/lib/index.d.ts +6 -5
  7. package/lib/index.js +6 -5
  8. package/lib/index.js.map +1 -1
  9. package/lib/inputdialog.d.ts +35 -3
  10. package/lib/inputdialog.js +122 -12
  11. package/lib/inputdialog.js.map +1 -1
  12. package/lib/kernelstatuses.d.ts +74 -2
  13. package/lib/kernelstatuses.js +142 -2
  14. package/lib/kernelstatuses.js.map +1 -1
  15. package/lib/mainareawidget.d.ts +9 -0
  16. package/lib/mainareawidget.js +29 -4
  17. package/lib/mainareawidget.js.map +1 -1
  18. package/lib/menufactory.js +14 -15
  19. package/lib/menufactory.js.map +1 -1
  20. package/lib/notification.d.ts +336 -0
  21. package/lib/notification.js +310 -0
  22. package/lib/notification.js.map +1 -0
  23. package/lib/runningSessions.d.ts +72 -0
  24. package/lib/runningSessions.js +119 -0
  25. package/lib/runningSessions.js.map +1 -0
  26. package/lib/sanitizer.d.ts +20 -7
  27. package/lib/sanitizer.js +47 -12
  28. package/lib/sanitizer.js.map +1 -1
  29. package/lib/semanticCommand.js +11 -2
  30. package/lib/semanticCommand.js.map +1 -1
  31. package/lib/sessioncontext.d.ts +2 -3
  32. package/lib/sessioncontext.js +46 -27
  33. package/lib/sessioncontext.js.map +1 -1
  34. package/lib/testutils.d.ts +5 -0
  35. package/lib/testutils.js +46 -0
  36. package/lib/testutils.js.map +1 -0
  37. package/lib/thememanager.js +25 -5
  38. package/lib/thememanager.js.map +1 -1
  39. package/lib/tokens.d.ts +34 -42
  40. package/lib/tokens.js +1 -6
  41. package/lib/tokens.js.map +1 -1
  42. package/lib/toolbar/factory.d.ts +12 -2
  43. package/lib/toolbar/factory.js +237 -145
  44. package/lib/toolbar/factory.js.map +1 -1
  45. package/lib/toolbar/index.js +4 -0
  46. package/lib/toolbar/index.js.map +1 -1
  47. package/lib/toolbar/registry.d.ts +11 -0
  48. package/lib/toolbar/registry.js +20 -3
  49. package/lib/toolbar/registry.js.map +1 -1
  50. package/lib/toolbar/widget.d.ts +3 -0
  51. package/lib/toolbar/widget.js +3 -0
  52. package/lib/toolbar/widget.js.map +1 -1
  53. package/lib/widgettracker.d.ts +13 -1
  54. package/lib/widgettracker.js +29 -2
  55. package/lib/widgettracker.js.map +1 -1
  56. package/package.json +30 -30
  57. package/src/clipboard.ts +107 -0
  58. package/src/commandlinker.ts +209 -0
  59. package/src/commandpalette.ts +175 -0
  60. package/src/dialog.tsx +1133 -0
  61. package/src/domutils.ts +53 -0
  62. package/src/index.ts +78 -0
  63. package/src/inputdialog.ts +551 -0
  64. package/src/kernelstatuses.tsx +279 -0
  65. package/src/mainareawidget.ts +362 -0
  66. package/src/menufactory.ts +201 -0
  67. package/src/notification.ts +559 -0
  68. package/src/printing.ts +180 -0
  69. package/src/runningSessions.tsx +233 -0
  70. package/src/sanitizer.ts +986 -0
  71. package/src/semanticCommand.ts +77 -0
  72. package/src/sessioncontext.tsx +1712 -0
  73. package/src/testutils.ts +49 -0
  74. package/src/thememanager.ts +530 -0
  75. package/src/tokens.ts +351 -0
  76. package/src/toolbar/factory.ts +422 -0
  77. package/src/toolbar/index.ts +8 -0
  78. package/src/toolbar/registry.ts +158 -0
  79. package/src/toolbar/widget.tsx +243 -0
  80. package/src/widgettracker.ts +391 -0
  81. package/src/windowresolver.ts +218 -0
  82. package/style/base.css +0 -1
  83. package/style/commandpalette.css +7 -10
  84. package/style/dialog.css +23 -7
  85. package/style/index.css +1 -0
  86. package/style/index.js +1 -0
  87. package/style/inputdialog.css +5 -0
  88. package/style/materialcolors.css +8 -21
  89. package/lib/hoverbox.d.ts +0 -82
  90. package/lib/hoverbox.js +0 -100
  91. package/lib/hoverbox.js.map +0 -1
  92. package/style/hoverbox.css +0 -13
@@ -0,0 +1,1712 @@
1
+ // Copyright (c) Jupyter Development Team.
2
+ // Distributed under the terms of the Modified BSD License.
3
+
4
+ import { IChangedArgs, PathExt } from '@jupyterlab/coreutils';
5
+ import {
6
+ Kernel,
7
+ KernelMessage,
8
+ KernelSpec,
9
+ ServerConnection,
10
+ Session
11
+ } from '@jupyterlab/services';
12
+ import {
13
+ ITranslator,
14
+ nullTranslator,
15
+ TranslationBundle
16
+ } from '@jupyterlab/translation';
17
+ import { find } from '@lumino/algorithm';
18
+ import { PromiseDelegate, UUID } from '@lumino/coreutils';
19
+ import { IDisposable, IObservableDisposable } from '@lumino/disposable';
20
+ import { ISignal, Signal } from '@lumino/signaling';
21
+ import { Widget } from '@lumino/widgets';
22
+ import * as React from 'react';
23
+ import { Dialog, showDialog } from './dialog';
24
+
25
+ /**
26
+ * A context object to manage a widget's kernel session connection.
27
+ *
28
+ * #### Notes
29
+ * The current session connection is `.session`, the current session's kernel
30
+ * connection is `.session.kernel`. For convenience, we proxy several kernel
31
+ * connection and session connection signals up to the session context so
32
+ * that you do not have to manage slots as sessions and kernels change. For
33
+ * example, to act on whatever the current kernel's iopubMessage signal is
34
+ * producing, connect to the session context `.iopubMessage` signal.
35
+ *
36
+ */
37
+ export interface ISessionContext extends IObservableDisposable {
38
+ /**
39
+ * The current session connection.
40
+ */
41
+ session: Session.ISessionConnection | null;
42
+
43
+ /**
44
+ * Initialize the session context.
45
+ *
46
+ * @returns A promise that resolves with whether to ask the user to select a kernel.
47
+ *
48
+ * #### Notes
49
+ * This includes starting up an initial kernel if needed.
50
+ */
51
+ initialize(): Promise<boolean>;
52
+
53
+ /**
54
+ * Whether the session context is ready.
55
+ */
56
+ readonly isReady: boolean;
57
+
58
+ /**
59
+ * Whether the session context is terminating.
60
+ */
61
+ readonly isTerminating: boolean;
62
+
63
+ /**
64
+ * Whether the session context is restarting.
65
+ */
66
+ readonly isRestarting: boolean;
67
+
68
+ /**
69
+ * A promise that is fulfilled when the session context is ready.
70
+ */
71
+ readonly ready: Promise<void>;
72
+
73
+ /**
74
+ * A signal emitted when the session connection changes.
75
+ */
76
+ readonly sessionChanged: ISignal<
77
+ this,
78
+ IChangedArgs<
79
+ Session.ISessionConnection | null,
80
+ Session.ISessionConnection | null,
81
+ 'session'
82
+ >
83
+ >;
84
+
85
+ // Signals proxied from the session connection for convenience.
86
+
87
+ /**
88
+ * A signal emitted when the kernel changes, proxied from the session connection.
89
+ */
90
+ readonly kernelChanged: ISignal<
91
+ this,
92
+ IChangedArgs<
93
+ Kernel.IKernelConnection | null,
94
+ Kernel.IKernelConnection | null,
95
+ 'kernel'
96
+ >
97
+ >;
98
+
99
+ /**
100
+ * A signal emitted when the kernel status changes, proxied from the session connection.
101
+ */
102
+ readonly statusChanged: ISignal<this, Kernel.Status>;
103
+
104
+ /**
105
+ * A signal emitted when the kernel connection status changes, proxied from the session connection.
106
+ */
107
+ readonly connectionStatusChanged: ISignal<this, Kernel.ConnectionStatus>;
108
+
109
+ /**
110
+ * A flag indicating if session is has pending input, proxied from the session connection.
111
+ */
112
+ readonly pendingInput: boolean;
113
+
114
+ /**
115
+ * A signal emitted for a kernel messages, proxied from the session connection.
116
+ */
117
+ readonly iopubMessage: ISignal<this, KernelMessage.IMessage>;
118
+
119
+ /**
120
+ * A signal emitted for an unhandled kernel message, proxied from the session connection.
121
+ */
122
+ readonly unhandledMessage: ISignal<this, KernelMessage.IMessage>;
123
+
124
+ /**
125
+ * A signal emitted when a session property changes, proxied from the session connection.
126
+ */
127
+ readonly propertyChanged: ISignal<this, 'path' | 'name' | 'type'>;
128
+
129
+ /**
130
+ * The kernel preference for starting new kernels.
131
+ */
132
+ kernelPreference: ISessionContext.IKernelPreference;
133
+
134
+ /**
135
+ * Whether the kernel is "No Kernel" or not.
136
+ *
137
+ * #### Notes
138
+ * As the displayed name is translated, this can be used directly.
139
+ */
140
+ readonly hasNoKernel: boolean;
141
+
142
+ /**
143
+ * The sensible display name for the kernel, or translated "No Kernel"
144
+ *
145
+ * #### Notes
146
+ * This is at this level since the underlying kernel connection does not
147
+ * have access to the kernel spec manager.
148
+ */
149
+ readonly kernelDisplayName: string;
150
+
151
+ /**
152
+ * A sensible status to display
153
+ *
154
+ * #### Notes
155
+ * This combines the status and connection status into a single status for the user.
156
+ */
157
+ readonly kernelDisplayStatus: ISessionContext.KernelDisplayStatus;
158
+
159
+ /**
160
+ * The session path.
161
+ *
162
+ * #### Notes
163
+ * Typically `.session.path` should be used. This attribute is useful if
164
+ * there is no current session.
165
+ */
166
+ readonly path: string;
167
+
168
+ /**
169
+ * The session type.
170
+ *
171
+ * #### Notes
172
+ * Typically `.session.type` should be used. This attribute is useful if
173
+ * there is no current session.
174
+ */
175
+ readonly type: string;
176
+
177
+ /**
178
+ * The session name.
179
+ *
180
+ * #### Notes
181
+ * Typically `.session.name` should be used. This attribute is useful if
182
+ * there is no current session.
183
+ */
184
+ readonly name: string;
185
+
186
+ /**
187
+ * The previous kernel name.
188
+ */
189
+ readonly prevKernelName: string;
190
+
191
+ /**
192
+ * The session manager used by the session.
193
+ */
194
+ readonly sessionManager: Session.IManager;
195
+
196
+ /**
197
+ * The kernel spec manager
198
+ */
199
+ readonly specsManager: KernelSpec.IManager;
200
+
201
+ /**
202
+ * Restart the current Kernel.
203
+ *
204
+ * @returns A promise that resolves when the kernel is restarted.
205
+ */
206
+ restartKernel(): Promise<void>;
207
+
208
+ /**
209
+ * Kill the kernel and shutdown the session.
210
+ *
211
+ * @returns A promise that resolves when the session is shut down.
212
+ */
213
+ shutdown(): Promise<void>;
214
+
215
+ /**
216
+ * Change the kernel associated with the session.
217
+ *
218
+ * @param options The optional kernel model parameters to use for the new kernel.
219
+ *
220
+ * @returns A promise that resolves with the new kernel connection.
221
+ */
222
+ changeKernel(
223
+ options?: Partial<Kernel.IModel>
224
+ ): Promise<Kernel.IKernelConnection | null>;
225
+ }
226
+
227
+ /**
228
+ * The namespace for session context related interfaces.
229
+ */
230
+ export namespace ISessionContext {
231
+ /**
232
+ * A kernel preference.
233
+ *
234
+ * #### Notes
235
+ * Preferences for a kernel are considered in the order `id`, `name`,
236
+ * `language`. If no matching kernels can be found and `autoStartDefault` is
237
+ * `true`, then the default kernel for the server is preferred.
238
+ */
239
+ export interface IKernelPreference {
240
+ /**
241
+ * The name of the kernel.
242
+ */
243
+ readonly name?: string;
244
+
245
+ /**
246
+ * The preferred kernel language.
247
+ */
248
+ readonly language?: string;
249
+
250
+ /**
251
+ * The id of an existing kernel.
252
+ */
253
+ readonly id?: string;
254
+
255
+ /**
256
+ * A kernel should be started automatically (default `true`).
257
+ */
258
+ readonly shouldStart?: boolean;
259
+
260
+ /**
261
+ * A kernel can be started (default `true`).
262
+ */
263
+ readonly canStart?: boolean;
264
+
265
+ /**
266
+ * Shut down the session when session context is disposed (default `false`).
267
+ */
268
+ readonly shutdownOnDispose?: boolean;
269
+
270
+ /**
271
+ * Automatically start the default kernel if no other matching kernel is
272
+ * found (default `true`).
273
+ */
274
+ readonly autoStartDefault?: boolean;
275
+ }
276
+
277
+ export type KernelDisplayStatus =
278
+ | Kernel.Status
279
+ | Kernel.ConnectionStatus
280
+ | 'initializing'
281
+ | '';
282
+
283
+ /**
284
+ * An interface for a session context dialog provider.
285
+ */
286
+ export interface IDialogs {
287
+ /**
288
+ * Select a kernel for the session.
289
+ */
290
+ selectKernel(
291
+ session: ISessionContext,
292
+ translator?: ITranslator
293
+ ): Promise<void>;
294
+
295
+ /**
296
+ * Restart the session context.
297
+ *
298
+ * @returns A promise that resolves with whether the kernel has restarted.
299
+ *
300
+ * #### Notes
301
+ * If there is a running kernel, present a dialog.
302
+ * If there is no kernel, we start a kernel with the last run
303
+ * kernel name and resolves with `true`. If no kernel has been started,
304
+ * this is a no-op, and resolves with `false`.
305
+ */
306
+ restart(
307
+ session: ISessionContext,
308
+ translator?: ITranslator
309
+ ): Promise<boolean>;
310
+ }
311
+ }
312
+
313
+ /**
314
+ * The default implementation for a session context object.
315
+ */
316
+ export class SessionContext implements ISessionContext {
317
+ /**
318
+ * Construct a new session context.
319
+ */
320
+ constructor(options: SessionContext.IOptions) {
321
+ this.sessionManager = options.sessionManager;
322
+ this.specsManager = options.specsManager;
323
+ this.translator = options.translator || nullTranslator;
324
+ this._trans = this.translator.load('jupyterlab');
325
+ this._path = options.path ?? UUID.uuid4();
326
+ this._type = options.type ?? '';
327
+ this._name = options.name ?? '';
328
+ this._setBusy = options.setBusy;
329
+ this._kernelPreference = options.kernelPreference ?? {};
330
+ }
331
+
332
+ /**
333
+ * The current session connection.
334
+ */
335
+ get session(): Session.ISessionConnection | null {
336
+ return this._session ?? null;
337
+ }
338
+
339
+ /**
340
+ * The session path.
341
+ *
342
+ * #### Notes
343
+ * Typically `.session.path` should be used. This attribute is useful if
344
+ * there is no current session.
345
+ */
346
+ get path(): string {
347
+ return this._path;
348
+ }
349
+
350
+ /**
351
+ * The session type.
352
+ *
353
+ * #### Notes
354
+ * Typically `.session.type` should be used. This attribute is useful if
355
+ * there is no current session.
356
+ */
357
+ get type(): string {
358
+ return this._type;
359
+ }
360
+
361
+ /**
362
+ * The session name.
363
+ *
364
+ * #### Notes
365
+ * Typically `.session.name` should be used. This attribute is useful if
366
+ * there is no current session.
367
+ */
368
+ get name(): string {
369
+ return this._name;
370
+ }
371
+
372
+ /**
373
+ * A signal emitted when the kernel connection changes, proxied from the session connection.
374
+ */
375
+ get kernelChanged(): ISignal<
376
+ this,
377
+ Session.ISessionConnection.IKernelChangedArgs
378
+ > {
379
+ return this._kernelChanged;
380
+ }
381
+
382
+ /**
383
+ * A signal emitted when the session connection changes.
384
+ */
385
+ get sessionChanged(): ISignal<
386
+ this,
387
+ IChangedArgs<
388
+ Session.ISessionConnection | null,
389
+ Session.ISessionConnection | null,
390
+ 'session'
391
+ >
392
+ > {
393
+ return this._sessionChanged;
394
+ }
395
+
396
+ /**
397
+ * A signal emitted when the kernel status changes, proxied from the kernel.
398
+ */
399
+ get statusChanged(): ISignal<this, Kernel.Status> {
400
+ return this._statusChanged;
401
+ }
402
+
403
+ /**
404
+ * A flag indicating if the session has ending input, proxied from the kernel.
405
+ */
406
+ get pendingInput(): boolean {
407
+ return this._pendingInput;
408
+ }
409
+
410
+ /**
411
+ * A signal emitted when the kernel status changes, proxied from the kernel.
412
+ */
413
+ get connectionStatusChanged(): ISignal<this, Kernel.ConnectionStatus> {
414
+ return this._connectionStatusChanged;
415
+ }
416
+
417
+ /**
418
+ * A signal emitted for iopub kernel messages, proxied from the kernel.
419
+ */
420
+ get iopubMessage(): ISignal<this, KernelMessage.IIOPubMessage> {
421
+ return this._iopubMessage;
422
+ }
423
+
424
+ /**
425
+ * A signal emitted for an unhandled kernel message, proxied from the kernel.
426
+ */
427
+ get unhandledMessage(): ISignal<this, KernelMessage.IMessage> {
428
+ return this._unhandledMessage;
429
+ }
430
+
431
+ /**
432
+ * A signal emitted when a session property changes, proxied from the current session.
433
+ */
434
+ get propertyChanged(): ISignal<this, 'path' | 'name' | 'type'> {
435
+ return this._propertyChanged;
436
+ }
437
+
438
+ /**
439
+ * The kernel preference of this client session.
440
+ *
441
+ * This is used when selecting a new kernel, and should reflect the sort of
442
+ * kernel the activity prefers.
443
+ */
444
+ get kernelPreference(): ISessionContext.IKernelPreference {
445
+ return this._kernelPreference;
446
+ }
447
+ set kernelPreference(value: ISessionContext.IKernelPreference) {
448
+ this._kernelPreference = value;
449
+ }
450
+
451
+ /**
452
+ * Whether the context is ready.
453
+ */
454
+ get isReady(): boolean {
455
+ return this._isReady;
456
+ }
457
+
458
+ /**
459
+ * A promise that is fulfilled when the context is ready.
460
+ */
461
+ get ready(): Promise<void> {
462
+ return this._ready.promise;
463
+ }
464
+
465
+ /**
466
+ * Whether the context is terminating.
467
+ */
468
+ get isTerminating(): boolean {
469
+ return this._isTerminating;
470
+ }
471
+
472
+ /**
473
+ * Whether the context is restarting.
474
+ */
475
+ get isRestarting(): boolean {
476
+ return this._isRestarting;
477
+ }
478
+
479
+ /**
480
+ * The session manager used by the session.
481
+ */
482
+ readonly sessionManager: Session.IManager;
483
+
484
+ /**
485
+ * The kernel spec manager
486
+ */
487
+ readonly specsManager: KernelSpec.IManager;
488
+
489
+ /**
490
+ * Whether the kernel is "No Kernel" or not.
491
+ *
492
+ * #### Notes
493
+ * As the displayed name is translated, this can be used directly.
494
+ */
495
+ get hasNoKernel(): boolean {
496
+ return this.kernelDisplayName === this.noKernelName;
497
+ }
498
+
499
+ /**
500
+ * The display name of the current kernel, or a sensible alternative.
501
+ *
502
+ * #### Notes
503
+ * This is a convenience function to have a consistent sensible name for the
504
+ * kernel.
505
+ */
506
+ get kernelDisplayName(): string {
507
+ const kernel = this.session?.kernel;
508
+ if (this._pendingKernelName === this.noKernelName) {
509
+ return this.noKernelName;
510
+ }
511
+ if (
512
+ !kernel &&
513
+ !this.isReady &&
514
+ this.kernelPreference.canStart !== false &&
515
+ this.kernelPreference.shouldStart !== false
516
+ ) {
517
+ let name =
518
+ this._pendingKernelName ||
519
+ SessionContext.getDefaultKernel({
520
+ specs: this.specsManager.specs,
521
+ sessions: this.sessionManager.running(),
522
+ preference: this.kernelPreference
523
+ }) ||
524
+ '';
525
+ if (name) {
526
+ name = this.specsManager.specs?.kernelspecs[name]?.display_name ?? name;
527
+ return name;
528
+ }
529
+ return this.noKernelName;
530
+ }
531
+ if (this._pendingKernelName) {
532
+ return (
533
+ this.specsManager.specs?.kernelspecs[this._pendingKernelName]
534
+ ?.display_name ?? this._pendingKernelName
535
+ );
536
+ }
537
+ if (!kernel) {
538
+ return this.noKernelName;
539
+ }
540
+ return (
541
+ this.specsManager.specs?.kernelspecs[kernel.name]?.display_name ??
542
+ kernel.name
543
+ );
544
+ }
545
+
546
+ /**
547
+ * A sensible status to display
548
+ *
549
+ * #### Notes
550
+ * This combines the status and connection status into a single status for
551
+ * the user.
552
+ */
553
+ get kernelDisplayStatus(): ISessionContext.KernelDisplayStatus {
554
+ const kernel = this.session?.kernel;
555
+
556
+ if (this._isTerminating) {
557
+ return 'terminating';
558
+ }
559
+
560
+ if (this._isRestarting) {
561
+ return 'restarting';
562
+ }
563
+
564
+ if (this._pendingKernelName === this.noKernelName) {
565
+ return 'unknown';
566
+ }
567
+
568
+ if (!kernel && this._pendingKernelName) {
569
+ return 'initializing';
570
+ }
571
+
572
+ if (
573
+ !kernel &&
574
+ !this.isReady &&
575
+ this.kernelPreference.canStart !== false &&
576
+ this.kernelPreference.shouldStart !== false
577
+ ) {
578
+ return 'initializing';
579
+ }
580
+
581
+ return (
582
+ (kernel?.connectionStatus === 'connected'
583
+ ? kernel?.status
584
+ : kernel?.connectionStatus) ?? 'unknown'
585
+ );
586
+ }
587
+
588
+ /**
589
+ * The name of the previously started kernel.
590
+ */
591
+ get prevKernelName(): string {
592
+ return this._prevKernelName;
593
+ }
594
+
595
+ /**
596
+ * Test whether the context is disposed.
597
+ */
598
+ get isDisposed(): boolean {
599
+ return this._isDisposed;
600
+ }
601
+
602
+ /**
603
+ * A signal emitted when the poll is disposed.
604
+ */
605
+ get disposed(): ISignal<this, void> {
606
+ return this._disposed;
607
+ }
608
+
609
+ /**
610
+ * Get the constant displayed name for "No Kernel"
611
+ */
612
+ protected get noKernelName(): string {
613
+ return this._trans.__('No Kernel');
614
+ }
615
+
616
+ /**
617
+ * Dispose of the resources held by the context.
618
+ */
619
+ dispose(): void {
620
+ if (this._isDisposed) {
621
+ return;
622
+ }
623
+ this._isDisposed = true;
624
+ this._disposed.emit();
625
+
626
+ if (this._session) {
627
+ if (this.kernelPreference.shutdownOnDispose) {
628
+ // Fire and forget the session shutdown request
629
+ this.sessionManager.shutdown(this._session.id).catch(reason => {
630
+ console.error(`Kernel not shut down ${reason}`);
631
+ });
632
+ }
633
+
634
+ // Dispose the session connection
635
+ this._session.dispose();
636
+ this._session = null;
637
+ }
638
+ if (this._dialog) {
639
+ this._dialog.dispose();
640
+ }
641
+ if (this._busyDisposable) {
642
+ this._busyDisposable.dispose();
643
+ this._busyDisposable = null;
644
+ }
645
+ Signal.clearData(this);
646
+ }
647
+
648
+ /**
649
+ * Restart the current Kernel.
650
+ *
651
+ * @returns A promise that resolves when the kernel is restarted.
652
+ */
653
+ async restartKernel(): Promise<void> {
654
+ const kernel = this.session?.kernel || null;
655
+ if (this._isRestarting) {
656
+ return;
657
+ }
658
+ this._isRestarting = true;
659
+ this._isReady = false;
660
+ this._statusChanged.emit('restarting');
661
+ try {
662
+ await this.session?.kernel?.restart();
663
+ this._isReady = true;
664
+ } catch (e) {
665
+ console.error(e);
666
+ }
667
+ this._isRestarting = false;
668
+ this._statusChanged.emit(this.session?.kernel?.status || 'unknown');
669
+ this._kernelChanged.emit({
670
+ name: 'kernel',
671
+ oldValue: kernel,
672
+ newValue: this.session?.kernel || null
673
+ });
674
+ }
675
+
676
+ /**
677
+ * Change the current kernel associated with the session.
678
+ */
679
+ async changeKernel(
680
+ options: Partial<Kernel.IModel> = {}
681
+ ): Promise<Kernel.IKernelConnection | null> {
682
+ if (this.isDisposed) {
683
+ throw new Error('Disposed');
684
+ }
685
+ // Wait for the initialization method to try
686
+ // and start its kernel first to ensure consistent
687
+ // ordering.
688
+ await this._initStarted.promise;
689
+ return this._changeKernel(options);
690
+ }
691
+
692
+ /**
693
+ * Kill the kernel and shutdown the session.
694
+ *
695
+ * @returns A promise that resolves when the session is shut down.
696
+ */
697
+ async shutdown(): Promise<void> {
698
+ if (this.isDisposed || !this._initializing) {
699
+ return;
700
+ }
701
+ await this._initStarted.promise;
702
+ this._pendingSessionRequest = '';
703
+ this._pendingKernelName = this.noKernelName;
704
+ return this._shutdownSession();
705
+ }
706
+
707
+ /**
708
+ * Initialize the session context
709
+ *
710
+ * @returns A promise that resolves with whether to ask the user to select a kernel.
711
+ *
712
+ * #### Notes
713
+ * If a server session exists on the current path, we will connect to it.
714
+ * If preferences include disabling `canStart` or `shouldStart`, no
715
+ * server session will be started.
716
+ * If a kernel id is given, we attempt to start a session with that id.
717
+ * If a default kernel is available, we connect to it.
718
+ * Otherwise we ask the user to select a kernel.
719
+ */
720
+ async initialize(): Promise<boolean> {
721
+ if (this._initializing) {
722
+ return this._initPromise.promise;
723
+ }
724
+ this._initializing = true;
725
+ const needsSelection = await this._initialize();
726
+ if (!needsSelection) {
727
+ this._isReady = true;
728
+ this._ready.resolve(undefined);
729
+ }
730
+ if (!this._pendingSessionRequest) {
731
+ this._initStarted.resolve(void 0);
732
+ }
733
+ this._initPromise.resolve(needsSelection);
734
+ return needsSelection;
735
+ }
736
+
737
+ /**
738
+ * Inner initialize function that doesn't handle promises.
739
+ * This makes it easier to consolidate promise handling logic.
740
+ */
741
+ async _initialize(): Promise<boolean> {
742
+ const manager = this.sessionManager;
743
+ await manager.ready;
744
+ await manager.refreshRunning();
745
+ const model = find(manager.running(), item => {
746
+ return item.path === this._path;
747
+ });
748
+ if (model) {
749
+ try {
750
+ const session = manager.connectTo({ model });
751
+ this._handleNewSession(session);
752
+ } catch (err) {
753
+ void this._handleSessionError(err);
754
+ return Promise.reject(err);
755
+ }
756
+ }
757
+
758
+ return await this._startIfNecessary();
759
+ }
760
+
761
+ /**
762
+ * Shut down the current session.
763
+ */
764
+ private async _shutdownSession(): Promise<void> {
765
+ const session = this._session;
766
+ // Capture starting values in case an error is raised.
767
+ const isTerminating = this._isTerminating;
768
+ const isReady = this._isReady;
769
+ this._isTerminating = true;
770
+ this._isReady = false;
771
+ this._statusChanged.emit('terminating');
772
+ try {
773
+ await session?.shutdown();
774
+ this._isTerminating = false;
775
+ session?.dispose();
776
+ this._session = null;
777
+ const kernel = session?.kernel || null;
778
+ this._statusChanged.emit('unknown');
779
+ this._kernelChanged.emit({
780
+ name: 'kernel',
781
+ oldValue: kernel,
782
+ newValue: null
783
+ });
784
+ this._sessionChanged.emit({
785
+ name: 'session',
786
+ oldValue: session,
787
+ newValue: null
788
+ });
789
+ } catch (err) {
790
+ this._isTerminating = isTerminating;
791
+ this._isReady = isReady;
792
+ const status = session?.kernel?.status;
793
+ if (status === undefined) {
794
+ this._statusChanged.emit('unknown');
795
+ } else {
796
+ this._statusChanged.emit(status);
797
+ }
798
+ throw err;
799
+ }
800
+ return;
801
+ }
802
+
803
+ /**
804
+ * Start the session if necessary.
805
+ *
806
+ * @returns Whether to ask the user to pick a kernel.
807
+ */
808
+ private async _startIfNecessary(): Promise<boolean> {
809
+ const preference = this.kernelPreference;
810
+ if (
811
+ this.isDisposed ||
812
+ this.session?.kernel ||
813
+ preference.shouldStart === false ||
814
+ preference.canStart === false
815
+ ) {
816
+ // Not necessary to start a kernel
817
+ return false;
818
+ }
819
+
820
+ let options: Partial<Kernel.IModel> | undefined;
821
+ if (preference.id) {
822
+ options = { id: preference.id };
823
+ } else {
824
+ const name = SessionContext.getDefaultKernel({
825
+ specs: this.specsManager.specs,
826
+ sessions: this.sessionManager.running(),
827
+ preference
828
+ });
829
+ if (name) {
830
+ options = { name };
831
+ }
832
+ }
833
+
834
+ if (options) {
835
+ try {
836
+ await this._changeKernel(options);
837
+ return false;
838
+ } catch (err) {
839
+ /* no-op */
840
+ }
841
+ }
842
+
843
+ // Always fall back to selecting a kernel
844
+ return true;
845
+ }
846
+
847
+ /**
848
+ * Change the kernel.
849
+ */
850
+ private async _changeKernel(
851
+ model: Partial<Kernel.IModel> = {}
852
+ ): Promise<Kernel.IKernelConnection | null> {
853
+ if (model.name) {
854
+ this._pendingKernelName = model.name;
855
+ }
856
+
857
+ if (!this._session) {
858
+ this._kernelChanged.emit({
859
+ name: 'kernel',
860
+ oldValue: null,
861
+ newValue: null
862
+ });
863
+ }
864
+
865
+ // Guarantee that the initialized kernel
866
+ // will be started first.
867
+ if (!this._pendingSessionRequest) {
868
+ this._initStarted.resolve(void 0);
869
+ }
870
+
871
+ // If we already have a session, just change the kernel.
872
+ if (this._session && !this._isTerminating) {
873
+ try {
874
+ await this._session.changeKernel(model);
875
+ return this._session.kernel;
876
+ } catch (err) {
877
+ void this._handleSessionError(err);
878
+ throw err;
879
+ }
880
+ }
881
+
882
+ // Use a UUID for the path to overcome a race condition on the server
883
+ // where it will re-use a session for a given path but only after
884
+ // the kernel finishes starting.
885
+ // We later switch to the real path below.
886
+ // Use the correct directory so the kernel will be started in that directory.
887
+ const dirName = PathExt.dirname(this._path);
888
+ const requestId = (this._pendingSessionRequest = PathExt.join(
889
+ dirName,
890
+ UUID.uuid4()
891
+ ));
892
+ try {
893
+ this._statusChanged.emit('starting');
894
+ const session = await this.sessionManager.startNew({
895
+ path: requestId,
896
+ type: this._type,
897
+ name: this._name,
898
+ kernel: model
899
+ });
900
+ // Handle a preempt.
901
+ if (this._pendingSessionRequest !== session.path) {
902
+ await session.shutdown();
903
+ session.dispose();
904
+ return null;
905
+ }
906
+ // Change to the real path.
907
+ await session.setPath(this._path);
908
+
909
+ // Update the name in case it has changed since we launched the session.
910
+ await session.setName(this._name);
911
+
912
+ if (this._session && !this._isTerminating) {
913
+ await this._shutdownSession();
914
+ }
915
+ return this._handleNewSession(session);
916
+ } catch (err) {
917
+ void this._handleSessionError(err);
918
+ throw err;
919
+ }
920
+ }
921
+
922
+ /**
923
+ * Handle a new session object.
924
+ */
925
+ private _handleNewSession(
926
+ session: Session.ISessionConnection | null
927
+ ): Kernel.IKernelConnection | null {
928
+ if (this.isDisposed) {
929
+ throw Error('Disposed');
930
+ }
931
+ if (!this._isReady) {
932
+ this._isReady = true;
933
+ this._ready.resolve(undefined);
934
+ }
935
+ if (this._session) {
936
+ this._session.dispose();
937
+ }
938
+ this._session = session;
939
+ this._pendingKernelName = '';
940
+
941
+ if (session) {
942
+ this._prevKernelName = session.kernel?.name ?? '';
943
+
944
+ session.disposed.connect(this._onSessionDisposed, this);
945
+ session.propertyChanged.connect(this._onPropertyChanged, this);
946
+ session.kernelChanged.connect(this._onKernelChanged, this);
947
+ session.statusChanged.connect(this._onStatusChanged, this);
948
+ session.connectionStatusChanged.connect(
949
+ this._onConnectionStatusChanged,
950
+ this
951
+ );
952
+ session.pendingInput.connect(this._onPendingInput, this);
953
+ session.iopubMessage.connect(this._onIopubMessage, this);
954
+ session.unhandledMessage.connect(this._onUnhandledMessage, this);
955
+
956
+ if (session.path !== this._path) {
957
+ this._onPropertyChanged(session, 'path');
958
+ }
959
+ if (session.name !== this._name) {
960
+ this._onPropertyChanged(session, 'name');
961
+ }
962
+ if (session.type !== this._type) {
963
+ this._onPropertyChanged(session, 'type');
964
+ }
965
+ }
966
+
967
+ // Any existing session/kernel connection was disposed above when the session was
968
+ // disposed, so the oldValue should be null.
969
+ this._sessionChanged.emit({
970
+ name: 'session',
971
+ oldValue: null,
972
+ newValue: session
973
+ });
974
+ this._kernelChanged.emit({
975
+ oldValue: null,
976
+ newValue: session?.kernel || null,
977
+ name: 'kernel'
978
+ });
979
+ this._statusChanged.emit(session?.kernel?.status || 'unknown');
980
+
981
+ return session?.kernel || null;
982
+ }
983
+
984
+ /**
985
+ * Handle an error in session startup.
986
+ */
987
+ private async _handleSessionError(
988
+ err: ServerConnection.ResponseError
989
+ ): Promise<void> {
990
+ this._handleNewSession(null);
991
+ let traceback = '';
992
+ let message = '';
993
+ try {
994
+ traceback = err.traceback;
995
+ message = err.message;
996
+ } catch (err) {
997
+ // no-op
998
+ }
999
+ await this._displayKernelError(message, traceback);
1000
+ }
1001
+
1002
+ /**
1003
+ * Display kernel error
1004
+ */
1005
+ private async _displayKernelError(message: string, traceback: string) {
1006
+ const body = (
1007
+ <div>
1008
+ {message && <pre>{message}</pre>}
1009
+ {traceback && (
1010
+ <details className="jp-mod-wide">
1011
+ <pre>{traceback}</pre>
1012
+ </details>
1013
+ )}
1014
+ </div>
1015
+ );
1016
+
1017
+ const dialog = (this._dialog = new Dialog({
1018
+ title: this._trans.__('Error Starting Kernel'),
1019
+ body,
1020
+ buttons: [Dialog.okButton()]
1021
+ }));
1022
+ await dialog.launch();
1023
+ this._dialog = null;
1024
+ }
1025
+
1026
+ /**
1027
+ * Handle a session termination.
1028
+ */
1029
+ private _onSessionDisposed(): void {
1030
+ if (this._session) {
1031
+ const oldValue = this._session;
1032
+ this._session = null;
1033
+ const newValue = this._session;
1034
+ this._sessionChanged.emit({ name: 'session', oldValue, newValue });
1035
+ }
1036
+ }
1037
+
1038
+ /**
1039
+ * Handle a change to a session property.
1040
+ */
1041
+ private _onPropertyChanged(
1042
+ sender: Session.ISessionConnection,
1043
+ property: 'path' | 'name' | 'type'
1044
+ ) {
1045
+ switch (property) {
1046
+ case 'path':
1047
+ this._path = sender.path;
1048
+ break;
1049
+ case 'name':
1050
+ this._name = sender.name;
1051
+ break;
1052
+ case 'type':
1053
+ this._type = sender.type;
1054
+ break;
1055
+ default:
1056
+ throw new Error(`unrecognized property ${property}`);
1057
+ }
1058
+ this._propertyChanged.emit(property);
1059
+ }
1060
+
1061
+ /**
1062
+ * Handle a change to the kernel.
1063
+ */
1064
+ private _onKernelChanged(
1065
+ sender: Session.ISessionConnection,
1066
+ args: Session.ISessionConnection.IKernelChangedArgs
1067
+ ): void {
1068
+ this._kernelChanged.emit(args);
1069
+ }
1070
+
1071
+ /**
1072
+ * Handle a change to the session status.
1073
+ */
1074
+ private _onStatusChanged(
1075
+ sender: Session.ISessionConnection,
1076
+ status: Kernel.Status
1077
+ ): void {
1078
+ if (status === 'dead') {
1079
+ const model = sender.kernel?.model;
1080
+ if (model?.reason) {
1081
+ const traceback = (model as any).traceback || '';
1082
+ void this._displayKernelError(model.reason, traceback);
1083
+ }
1084
+ }
1085
+
1086
+ // Set that this kernel is busy, if we haven't already
1087
+ // If we have already, and now we aren't busy, dispose
1088
+ // of the busy disposable.
1089
+ if (this._setBusy) {
1090
+ if (status === 'busy') {
1091
+ if (!this._busyDisposable) {
1092
+ this._busyDisposable = this._setBusy();
1093
+ }
1094
+ } else {
1095
+ if (this._busyDisposable) {
1096
+ this._busyDisposable.dispose();
1097
+ this._busyDisposable = null;
1098
+ }
1099
+ }
1100
+ }
1101
+
1102
+ // Proxy the signal
1103
+ this._statusChanged.emit(status);
1104
+ }
1105
+
1106
+ /**
1107
+ * Handle a change to the session status.
1108
+ */
1109
+ private _onConnectionStatusChanged(
1110
+ sender: Session.ISessionConnection,
1111
+ status: Kernel.ConnectionStatus
1112
+ ): void {
1113
+ // Proxy the signal
1114
+ this._connectionStatusChanged.emit(status);
1115
+ }
1116
+
1117
+ /**
1118
+ * Handle a change to the pending input.
1119
+ */
1120
+ private _onPendingInput(
1121
+ sender: Session.ISessionConnection,
1122
+ value: boolean
1123
+ ): void {
1124
+ // Set the signal value
1125
+ this._pendingInput = value;
1126
+ }
1127
+
1128
+ /**
1129
+ * Handle an iopub message.
1130
+ */
1131
+ private _onIopubMessage(
1132
+ sender: Session.ISessionConnection,
1133
+ message: KernelMessage.IIOPubMessage
1134
+ ): void {
1135
+ if (message.header.msg_type === 'shutdown_reply') {
1136
+ this.session!.kernel!.removeInputGuard();
1137
+ }
1138
+ this._iopubMessage.emit(message);
1139
+ }
1140
+
1141
+ /**
1142
+ * Handle an unhandled message.
1143
+ */
1144
+ private _onUnhandledMessage(
1145
+ sender: Session.ISessionConnection,
1146
+ message: KernelMessage.IMessage
1147
+ ): void {
1148
+ this._unhandledMessage.emit(message);
1149
+ }
1150
+
1151
+ private _path = '';
1152
+ private _name = '';
1153
+ private _type = '';
1154
+ private _prevKernelName: string = '';
1155
+ private _kernelPreference: ISessionContext.IKernelPreference;
1156
+ private _isDisposed = false;
1157
+ private _disposed = new Signal<this, void>(this);
1158
+ private _session: Session.ISessionConnection | null = null;
1159
+ private _ready = new PromiseDelegate<void>();
1160
+ private _initializing = false;
1161
+ private _initStarted = new PromiseDelegate<void>();
1162
+ private _initPromise = new PromiseDelegate<boolean>();
1163
+ private _isReady = false;
1164
+ private _isTerminating = false;
1165
+ private _isRestarting = false;
1166
+ private _kernelChanged = new Signal<
1167
+ this,
1168
+ Session.ISessionConnection.IKernelChangedArgs
1169
+ >(this);
1170
+ private _sessionChanged = new Signal<
1171
+ this,
1172
+ IChangedArgs<
1173
+ Session.ISessionConnection | null,
1174
+ Session.ISessionConnection | null,
1175
+ 'session'
1176
+ >
1177
+ >(this);
1178
+ private _statusChanged = new Signal<this, Kernel.Status>(this);
1179
+ private _connectionStatusChanged = new Signal<this, Kernel.ConnectionStatus>(
1180
+ this
1181
+ );
1182
+ private translator: ITranslator;
1183
+ private _trans: TranslationBundle;
1184
+ private _pendingInput = false;
1185
+ private _iopubMessage = new Signal<this, KernelMessage.IIOPubMessage>(this);
1186
+ private _unhandledMessage = new Signal<this, KernelMessage.IMessage>(this);
1187
+ private _propertyChanged = new Signal<this, 'path' | 'name' | 'type'>(this);
1188
+ private _dialog: Dialog<any> | null = null;
1189
+ private _setBusy: (() => IDisposable) | undefined;
1190
+ private _busyDisposable: IDisposable | null = null;
1191
+ private _pendingKernelName = '';
1192
+ private _pendingSessionRequest = '';
1193
+ }
1194
+
1195
+ /**
1196
+ * A namespace for `SessionContext` statics.
1197
+ */
1198
+ export namespace SessionContext {
1199
+ /**
1200
+ * The options used to initialize a context.
1201
+ */
1202
+ export interface IOptions {
1203
+ /**
1204
+ * A session manager instance.
1205
+ */
1206
+ sessionManager: Session.IManager;
1207
+
1208
+ /**
1209
+ * A kernel spec manager instance.
1210
+ */
1211
+ specsManager: KernelSpec.IManager;
1212
+
1213
+ /**
1214
+ * The initial path of the file.
1215
+ */
1216
+ path?: string;
1217
+
1218
+ /**
1219
+ * The name of the session.
1220
+ */
1221
+ name?: string;
1222
+
1223
+ /**
1224
+ * The type of the session.
1225
+ */
1226
+ type?: string;
1227
+
1228
+ /**
1229
+ * A kernel preference.
1230
+ */
1231
+ kernelPreference?: ISessionContext.IKernelPreference;
1232
+
1233
+ /**
1234
+ * The application language translator.
1235
+ */
1236
+ translator?: ITranslator;
1237
+
1238
+ /**
1239
+ * A function to call when the session becomes busy.
1240
+ */
1241
+ setBusy?: () => IDisposable;
1242
+ }
1243
+
1244
+ /**
1245
+ * An interface for populating a kernel selector.
1246
+ */
1247
+ export interface IKernelSearch {
1248
+ /**
1249
+ * The Kernel specs.
1250
+ */
1251
+ specs: KernelSpec.ISpecModels | null;
1252
+
1253
+ /**
1254
+ * The kernel preference.
1255
+ */
1256
+ preference: ISessionContext.IKernelPreference;
1257
+
1258
+ /**
1259
+ * The current running sessions.
1260
+ */
1261
+ sessions?: Iterable<Session.IModel>;
1262
+ }
1263
+
1264
+ /**
1265
+ * Get the default kernel name given select options.
1266
+ */
1267
+ export function getDefaultKernel(options: IKernelSearch): string | null {
1268
+ return Private.getDefaultKernel(options);
1269
+ }
1270
+ }
1271
+
1272
+ /**
1273
+ * The default implementation of the client session dialog provider.
1274
+ */
1275
+ export const sessionContextDialogs: ISessionContext.IDialogs = {
1276
+ /**
1277
+ * Select a kernel for the session.
1278
+ */
1279
+ async selectKernel(
1280
+ sessionContext: ISessionContext,
1281
+ translator?: ITranslator
1282
+ ): Promise<void> {
1283
+ if (sessionContext.isDisposed) {
1284
+ return Promise.resolve();
1285
+ }
1286
+ translator = translator || nullTranslator;
1287
+ const trans = translator.load('jupyterlab');
1288
+
1289
+ // If there is no existing kernel, offer the option
1290
+ // to keep no kernel.
1291
+ let label = trans.__('Cancel');
1292
+ if (sessionContext.hasNoKernel) {
1293
+ label = sessionContext.kernelDisplayName;
1294
+ }
1295
+ const buttons = [
1296
+ Dialog.cancelButton({ label }),
1297
+ Dialog.okButton({ label: trans.__('Select') })
1298
+ ];
1299
+
1300
+ const dialog = new Dialog({
1301
+ title: trans.__('Select Kernel'),
1302
+ body: new Private.KernelSelector(sessionContext, translator),
1303
+ buttons
1304
+ });
1305
+
1306
+ const result = await dialog.launch();
1307
+ if (sessionContext.isDisposed || !result.button.accept) {
1308
+ return;
1309
+ }
1310
+ const model = result.value;
1311
+ if (model === null && !sessionContext.hasNoKernel) {
1312
+ return sessionContext.shutdown();
1313
+ }
1314
+ if (model) {
1315
+ await sessionContext.changeKernel(model);
1316
+ }
1317
+ },
1318
+
1319
+ /**
1320
+ * Restart the session.
1321
+ *
1322
+ * @returns A promise that resolves with whether the kernel has restarted.
1323
+ *
1324
+ * #### Notes
1325
+ * If there is a running kernel, present a dialog.
1326
+ * If there is no kernel, we start a kernel with the last run
1327
+ * kernel name and resolves with `true`.
1328
+ */
1329
+ async restart(
1330
+ sessionContext: ISessionContext,
1331
+ translator?: ITranslator
1332
+ ): Promise<boolean> {
1333
+ translator = translator || nullTranslator;
1334
+ const trans = translator.load('jupyterlab');
1335
+
1336
+ await sessionContext.initialize();
1337
+ if (sessionContext.isDisposed) {
1338
+ throw new Error('session already disposed');
1339
+ }
1340
+ const kernel = sessionContext.session?.kernel;
1341
+ if (!kernel && sessionContext.prevKernelName) {
1342
+ await sessionContext.changeKernel({
1343
+ name: sessionContext.prevKernelName
1344
+ });
1345
+ return true;
1346
+ }
1347
+ // Bail if there is no previous kernel to start.
1348
+ if (!kernel) {
1349
+ throw new Error('No kernel to restart');
1350
+ }
1351
+
1352
+ const restartBtn = Dialog.warnButton({ label: 'Restart' });
1353
+ const result = await showDialog({
1354
+ title: trans.__('Restart Kernel?'),
1355
+ body: trans.__(
1356
+ 'Do you want to restart the kernel of %1? All variables will be lost.',
1357
+ sessionContext.name
1358
+ ),
1359
+ buttons: [Dialog.cancelButton(), restartBtn]
1360
+ });
1361
+
1362
+ if (kernel.isDisposed) {
1363
+ return false;
1364
+ }
1365
+ if (result.button.accept) {
1366
+ await sessionContext.restartKernel();
1367
+ return true;
1368
+ }
1369
+ return false;
1370
+ }
1371
+ };
1372
+
1373
+ /**
1374
+ * The namespace for module private data.
1375
+ */
1376
+ namespace Private {
1377
+ /**
1378
+ * A widget that provides a kernel selection.
1379
+ */
1380
+ export class KernelSelector extends Widget {
1381
+ /**
1382
+ * Create a new kernel selector widget.
1383
+ */
1384
+ constructor(sessionContext: ISessionContext, translator?: ITranslator) {
1385
+ super({ node: createSelectorNode(sessionContext, translator) });
1386
+ }
1387
+
1388
+ /**
1389
+ * Get the value of the kernel selector widget.
1390
+ */
1391
+ getValue(): Kernel.IModel {
1392
+ const selector = this.node.querySelector('select') as HTMLSelectElement;
1393
+ return JSON.parse(selector.value) as Kernel.IModel;
1394
+ }
1395
+ }
1396
+
1397
+ /**
1398
+ * Create a node for a kernel selector widget.
1399
+ */
1400
+ function createSelectorNode(
1401
+ sessionContext: ISessionContext,
1402
+ translator?: ITranslator
1403
+ ) {
1404
+ // Create the dialog body.
1405
+ translator = translator || nullTranslator;
1406
+ const trans = translator.load('jupyterlab');
1407
+
1408
+ const body = document.createElement('div');
1409
+ const text = document.createElement('label');
1410
+ text.textContent = `${trans.__('Select kernel for:')} "${
1411
+ sessionContext.name
1412
+ }"`;
1413
+ body.appendChild(text);
1414
+
1415
+ const options = getKernelSearch(sessionContext);
1416
+ const selector = document.createElement('select');
1417
+ populateKernelSelect(
1418
+ selector,
1419
+ options,
1420
+ translator,
1421
+ !sessionContext.hasNoKernel ? sessionContext.kernelDisplayName : null
1422
+ );
1423
+ body.appendChild(selector);
1424
+ return body;
1425
+ }
1426
+
1427
+ /**
1428
+ * Get the default kernel name given select options.
1429
+ */
1430
+ export function getDefaultKernel(
1431
+ options: SessionContext.IKernelSearch
1432
+ ): string | null {
1433
+ const { specs, preference } = options;
1434
+ const { name, language, shouldStart, canStart, autoStartDefault } =
1435
+ preference;
1436
+
1437
+ if (!specs || shouldStart === false || canStart === false) {
1438
+ return null;
1439
+ }
1440
+
1441
+ const defaultName = autoStartDefault ? specs.default : null;
1442
+
1443
+ if (!name && !language) {
1444
+ return defaultName;
1445
+ }
1446
+
1447
+ // Look for an exact match of a spec name.
1448
+ for (const specName in specs.kernelspecs) {
1449
+ if (specName === name) {
1450
+ return name;
1451
+ }
1452
+ }
1453
+
1454
+ // Bail if there is no language.
1455
+ if (!language) {
1456
+ return defaultName;
1457
+ }
1458
+
1459
+ // Check for a single kernel matching the language.
1460
+ const matches: string[] = [];
1461
+ for (const specName in specs.kernelspecs) {
1462
+ const kernelLanguage = specs.kernelspecs[specName]?.language;
1463
+ if (language === kernelLanguage) {
1464
+ matches.push(specName);
1465
+ }
1466
+ }
1467
+
1468
+ if (matches.length === 1) {
1469
+ const specName = matches[0];
1470
+ console.warn(
1471
+ 'No exact match found for ' +
1472
+ specName +
1473
+ ', using kernel ' +
1474
+ specName +
1475
+ ' that matches ' +
1476
+ 'language=' +
1477
+ language
1478
+ );
1479
+ return specName;
1480
+ }
1481
+
1482
+ // No matches found.
1483
+ return defaultName;
1484
+ }
1485
+
1486
+ /**
1487
+ * Populate a kernel select node for the session.
1488
+ */
1489
+ export function populateKernelSelect(
1490
+ node: HTMLSelectElement,
1491
+ options: SessionContext.IKernelSearch,
1492
+ translator?: ITranslator,
1493
+ currentKernelDisplayName: string | null = null
1494
+ ): void {
1495
+ while (node.firstChild) {
1496
+ node.removeChild(node.firstChild);
1497
+ }
1498
+
1499
+ const { preference, sessions, specs } = options;
1500
+ const { name, id, language, canStart, shouldStart } = preference;
1501
+
1502
+ translator = translator || nullTranslator;
1503
+ const trans = translator.load('jupyterlab');
1504
+
1505
+ if (!specs || canStart === false) {
1506
+ node.appendChild(optionForNone(translator));
1507
+ node.value = 'null';
1508
+ node.disabled = true;
1509
+ return;
1510
+ }
1511
+
1512
+ node.disabled = false;
1513
+
1514
+ // Create mappings of display names and languages for kernel name.
1515
+ const displayNames: { [key: string]: string } = Object.create(null);
1516
+ const languages: { [key: string]: string } = Object.create(null);
1517
+ for (const name in specs.kernelspecs) {
1518
+ const spec = specs.kernelspecs[name]!;
1519
+ displayNames[name] = spec.display_name;
1520
+ languages[name] = spec.language;
1521
+ }
1522
+
1523
+ // Handle a kernel by name.
1524
+ const names: string[] = [];
1525
+ if (name && name in specs.kernelspecs) {
1526
+ names.push(name);
1527
+ }
1528
+
1529
+ // Then look by language.
1530
+ if (language) {
1531
+ for (const specName in specs.kernelspecs) {
1532
+ if (name !== specName && languages[specName] === language) {
1533
+ names.push(specName);
1534
+ }
1535
+ }
1536
+ }
1537
+
1538
+ // Use the default kernel if no kernels were found.
1539
+ if (!names.length) {
1540
+ names.push(specs.default);
1541
+ }
1542
+
1543
+ // Handle a preferred kernels in order of display name.
1544
+ const preferred = document.createElement('optgroup');
1545
+ preferred.label = trans.__('Start Preferred Kernel');
1546
+
1547
+ names.sort((a, b) => displayNames[a].localeCompare(displayNames[b]));
1548
+ for (const name of names) {
1549
+ preferred.appendChild(optionForName(name, displayNames[name]));
1550
+ }
1551
+
1552
+ if (preferred.firstChild) {
1553
+ node.appendChild(preferred);
1554
+ }
1555
+
1556
+ // Add an option for no kernel
1557
+ node.appendChild(optionForNone(translator));
1558
+
1559
+ const other = document.createElement('optgroup');
1560
+ other.label = trans.__('Start Other Kernel');
1561
+
1562
+ // Add the rest of the kernel names in alphabetical order.
1563
+ const otherNames: string[] = [];
1564
+ for (const specName in specs.kernelspecs) {
1565
+ if (names.indexOf(specName) !== -1) {
1566
+ continue;
1567
+ }
1568
+ otherNames.push(specName);
1569
+ }
1570
+ otherNames.sort((a, b) => displayNames[a].localeCompare(displayNames[b]));
1571
+ for (const otherName of otherNames) {
1572
+ other.appendChild(optionForName(otherName, displayNames[otherName]));
1573
+ }
1574
+ // Add a separator option if there were any other names.
1575
+ if (otherNames.length) {
1576
+ node.appendChild(other);
1577
+ }
1578
+
1579
+ // Handle the default value.
1580
+ if (shouldStart === false) {
1581
+ node.value = 'null';
1582
+ } else {
1583
+ let selectedIndex = 0;
1584
+ if (currentKernelDisplayName) {
1585
+ // Select current kernel by default.
1586
+ selectedIndex = [...node.options].findIndex(
1587
+ option => option.text === currentKernelDisplayName
1588
+ );
1589
+ selectedIndex = Math.max(selectedIndex, 0);
1590
+ }
1591
+ node.selectedIndex = selectedIndex;
1592
+ }
1593
+
1594
+ // Bail if there are no sessions.
1595
+ if (!sessions) {
1596
+ return;
1597
+ }
1598
+
1599
+ // Add the sessions using the preferred language first.
1600
+ const matchingSessions: Session.IModel[] = [];
1601
+ const otherSessions: Session.IModel[] = [];
1602
+
1603
+ for (const session of sessions) {
1604
+ if (
1605
+ language &&
1606
+ session.kernel &&
1607
+ languages[session.kernel.name] === language &&
1608
+ session.kernel.id !== id
1609
+ ) {
1610
+ matchingSessions.push(session);
1611
+ } else if (session.kernel?.id !== id) {
1612
+ otherSessions.push(session);
1613
+ }
1614
+ }
1615
+
1616
+ const matching = document.createElement('optgroup');
1617
+ matching.label = trans.__('Use Kernel from Preferred Session');
1618
+ node.appendChild(matching);
1619
+
1620
+ if (matchingSessions.length) {
1621
+ matchingSessions.sort((a, b) => {
1622
+ return a.path.localeCompare(b.path);
1623
+ });
1624
+
1625
+ for (const session of matchingSessions) {
1626
+ const name = session.kernel ? displayNames[session.kernel.name] : '';
1627
+ matching.appendChild(optionForSession(session, name, translator));
1628
+ }
1629
+ }
1630
+
1631
+ const otherSessionsNode = document.createElement('optgroup');
1632
+ otherSessionsNode.label = trans.__('Use Kernel from Other Session');
1633
+ node.appendChild(otherSessionsNode);
1634
+
1635
+ if (otherSessions.length) {
1636
+ otherSessions.sort((a, b) => {
1637
+ return a.path.localeCompare(b.path);
1638
+ });
1639
+
1640
+ for (const session of otherSessions) {
1641
+ const name = session.kernel
1642
+ ? displayNames[session.kernel.name] || session.kernel.name
1643
+ : '';
1644
+ otherSessionsNode.appendChild(
1645
+ optionForSession(session, name, translator)
1646
+ );
1647
+ }
1648
+ }
1649
+ }
1650
+
1651
+ /**
1652
+ * Get the kernel search options given a session context and session manager.
1653
+ */
1654
+ function getKernelSearch(
1655
+ sessionContext: ISessionContext
1656
+ ): SessionContext.IKernelSearch {
1657
+ return {
1658
+ specs: sessionContext.specsManager.specs,
1659
+ sessions: sessionContext.sessionManager.running(),
1660
+ preference: sessionContext.kernelPreference
1661
+ };
1662
+ }
1663
+
1664
+ /**
1665
+ * Create an option element for a kernel name.
1666
+ */
1667
+ function optionForName(name: string, displayName: string): HTMLOptionElement {
1668
+ const option = document.createElement('option');
1669
+ option.text = displayName;
1670
+ option.value = JSON.stringify({ name });
1671
+ return option;
1672
+ }
1673
+
1674
+ /**
1675
+ * Create an option for no kernel.
1676
+ */
1677
+ function optionForNone(translator?: ITranslator): HTMLOptGroupElement {
1678
+ translator = translator || nullTranslator;
1679
+ const trans = translator.load('jupyterlab');
1680
+
1681
+ const group = document.createElement('optgroup');
1682
+ group.label = trans.__('Use No Kernel');
1683
+ const option = document.createElement('option');
1684
+ option.text = trans.__('No Kernel');
1685
+ option.value = 'null';
1686
+ group.appendChild(option);
1687
+ return group;
1688
+ }
1689
+
1690
+ /**
1691
+ * Create an option element for a session.
1692
+ */
1693
+ function optionForSession(
1694
+ session: Session.IModel,
1695
+ displayName: string,
1696
+ translator?: ITranslator
1697
+ ): HTMLOptionElement {
1698
+ translator = translator || nullTranslator;
1699
+ const trans = translator.load('jupyterlab');
1700
+
1701
+ const option = document.createElement('option');
1702
+ const sessionName = session.name || PathExt.basename(session.path);
1703
+ option.text = sessionName;
1704
+ option.value = JSON.stringify({ id: session.kernel?.id });
1705
+ option.title =
1706
+ `${trans.__('Path:')} ${session.path}\n` +
1707
+ `${trans.__('Name:')} ${sessionName}\n` +
1708
+ `${trans.__('Kernel Name:')} ${displayName}\n` +
1709
+ `${trans.__('Kernel Id:')} ${session.kernel?.id}`;
1710
+ return option;
1711
+ }
1712
+ }