forked from microsoft/vscode-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
interactiveBase.ts
1525 lines (1336 loc) · 61.5 KB
/
interactiveBase.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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
'use strict';
import '../../common/extensions';
import type { nbformat } from '@jupyterlab/coreutils';
import type { KernelMessage } from '@jupyterlab/services';
import { injectable, unmanaged } from 'inversify';
import * as os from 'os';
import * as path from 'path';
import * as uuid from 'uuid/v4';
import {
CancellationToken,
commands,
ConfigurationTarget,
Event,
EventEmitter,
Memento,
Position,
Range,
Selection,
TextEditor,
Uri,
ViewColumn
} from 'vscode';
import { Disposable } from 'vscode-jsonrpc';
import { ServerStatus } from '../../../datascience-ui/interactive-common/mainState';
import {
IApplicationShell,
ICommandManager,
IDocumentManager,
ILiveShareApi,
IWebPanelProvider,
IWorkspaceService
} from '../../common/application/types';
import { CancellationError } from '../../common/cancellation';
import { EXTENSION_ROOT_DIR, isTestExecution, PYTHON_LANGUAGE } from '../../common/constants';
import { RemoveKernelToolbarInInteractiveWindow, RunByLine } from '../../common/experiments/groups';
import { traceError, traceInfo, traceWarning } from '../../common/logger';
import { IFileSystem } from '../../common/platform/types';
import {
IConfigurationService,
IDisposableRegistry,
IExperimentService,
IExperimentsManager
} from '../../common/types';
import { createDeferred, Deferred } from '../../common/utils/async';
import * as localize from '../../common/utils/localize';
import { isUntitledFile, noop } from '../../common/utils/misc';
import { StopWatch } from '../../common/utils/stopWatch';
import { PythonInterpreter } from '../../pythonEnvironments/info';
import { captureTelemetry, sendTelemetryEvent } from '../../telemetry';
import { generateCellRangesFromDocument } from '../cellFactory';
import { CellMatcher } from '../cellMatcher';
import { addToUriList, translateKernelLanguageToMonaco } from '../common';
import { Commands, Identifiers, Telemetry } from '../constants';
import { ColumnWarningSize, IDataViewerFactory } from '../data-viewing/types';
import {
IAddedSysInfo,
ICopyCode,
IGotoCode,
IInteractiveWindowMapping,
INotebookIdentity,
InteractiveWindowMessages,
IReExecuteCells,
IRemoteAddCode,
IRemoteReexecuteCode,
IShowDataViewer,
ISubmitNewCell,
SysInfoReason,
VariableExplorerStateKeys
} from '../interactive-common/interactiveWindowTypes';
import { JupyterInvalidKernelError } from '../jupyter/jupyterInvalidKernelError';
import { JupyterKernelPromiseFailedError } from '../jupyter/kernels/jupyterKernelPromiseFailedError';
import { KernelSpecInterpreter } from '../jupyter/kernels/kernelSelector';
import { KernelSwitcher } from '../jupyter/kernels/kernelSwitcher';
import { LiveKernelModel } from '../jupyter/kernels/types';
import { CssMessages, SharedMessages } from '../messages';
import {
CellState,
ICell,
ICodeCssGenerator,
IDataScienceErrorHandler,
IInteractiveBase,
IInteractiveWindowInfo,
IInteractiveWindowListener,
IJupyterDebugger,
IJupyterKernelSpec,
IJupyterVariableDataProviderFactory,
IJupyterVariables,
IJupyterVariablesRequest,
IJupyterVariablesResponse,
IMessageCell,
INotebook,
INotebookExporter,
INotebookProvider,
INotebookProviderConnection,
InterruptResult,
IStatusProvider,
IThemeFinder,
WebViewViewChangeEventArgs
} from '../types';
import { WebViewHost } from '../webViewHost';
import { InteractiveWindowMessageListener } from './interactiveWindowMessageListener';
import { serializeLanguageConfiguration } from './serialization';
@injectable()
export abstract class InteractiveBase extends WebViewHost<IInteractiveWindowMapping> implements IInteractiveBase {
public get notebook(): INotebook | undefined {
return this._notebook;
}
public get id(): string {
return this._id;
}
public get onExecutedCode(): Event<string> {
return this.executeEvent.event;
}
private unfinishedCells: ICell[] = [];
private restartingKernel: boolean = false;
private perceivedJupyterStartupTelemetryCaptured: boolean = false;
private potentiallyUnfinishedStatus: Disposable[] = [];
private addSysInfoPromise: Deferred<boolean> | undefined;
private _notebook: INotebook | undefined;
private _id: string;
private executeEvent: EventEmitter<string> = new EventEmitter<string>();
private connectionAndNotebookPromise: Promise<void> | undefined;
private notebookPromise: Promise<void> | undefined;
private setDarkPromise: Deferred<boolean> | undefined;
constructor(
@unmanaged() private readonly listeners: IInteractiveWindowListener[],
@unmanaged() liveShare: ILiveShareApi,
@unmanaged() protected applicationShell: IApplicationShell,
@unmanaged() protected documentManager: IDocumentManager,
@unmanaged() provider: IWebPanelProvider,
@unmanaged() private disposables: IDisposableRegistry,
@unmanaged() cssGenerator: ICodeCssGenerator,
@unmanaged() themeFinder: IThemeFinder,
@unmanaged() private statusProvider: IStatusProvider,
@unmanaged() protected fileSystem: IFileSystem,
@unmanaged() protected configuration: IConfigurationService,
@unmanaged() protected jupyterExporter: INotebookExporter,
@unmanaged() workspaceService: IWorkspaceService,
@unmanaged() private dataExplorerFactory: IDataViewerFactory,
@unmanaged() private jupyterVariableDataProviderFactory: IJupyterVariableDataProviderFactory,
@unmanaged() private jupyterVariables: IJupyterVariables,
@unmanaged() private jupyterDebugger: IJupyterDebugger,
@unmanaged() protected errorHandler: IDataScienceErrorHandler,
@unmanaged() protected readonly commandManager: ICommandManager,
@unmanaged() protected globalStorage: Memento,
@unmanaged() protected workspaceStorage: Memento,
@unmanaged() rootPath: string,
@unmanaged() scripts: string[],
@unmanaged() title: string,
@unmanaged() viewColumn: ViewColumn,
@unmanaged() experimentsManager: IExperimentsManager,
@unmanaged() private switcher: KernelSwitcher,
@unmanaged() private readonly notebookProvider: INotebookProvider,
@unmanaged() useCustomEditorApi: boolean,
@unmanaged() expService: IExperimentService
) {
super(
configuration,
provider,
cssGenerator,
themeFinder,
workspaceService,
(c, v, d) => new InteractiveWindowMessageListener(liveShare, c, v, d),
rootPath,
scripts,
title,
viewColumn,
useCustomEditorApi,
experimentsManager.inExperiment(RunByLine.experiment),
expService.inExperiment(RemoveKernelToolbarInInteractiveWindow.experiment)
);
// Create our unique id. We use this to skip messages we send to other interactive windows
this._id = uuid();
// Listen for active text editor changes. This is the only way we can tell that we might be needing to gain focus
const handler = this.documentManager.onDidChangeActiveTextEditor(() => this.activating());
this.disposables.push(handler);
// For each listener sign up for their post events
this.listeners.forEach((l) => l.postMessage((e) => this.postMessageInternal(e.message, e.payload)));
// Channel for listeners to send messages to the interactive base.
this.listeners.forEach((l) => {
if (l.postInternalMessage) {
l.postInternalMessage((e) => this.onMessage(e.message, e.payload));
}
});
// Tell each listener our identity. Can't do it here though as were in the constructor for the base class
setTimeout(() => {
this.getNotebookIdentity()
.then((identity) =>
this.listeners.forEach((l) => l.onMessage(InteractiveWindowMessages.NotebookIdentity, identity))
)
.ignoreErrors();
}, 0);
// When a notebook provider first makes its connection check it to see if we should create a notebook
this.disposables.push(notebookProvider.onConnectionMade(this.checkForNotebookProviderConnection.bind(this)));
// When the variable service requests a refresh, refresh our variable list
this.disposables.push(this.jupyterVariables.refreshRequired(this.refreshVariables.bind(this)));
}
public async show(): Promise<void> {
// Verify a server that matches us hasn't started already
this.checkForNotebookProviderConnection().ignoreErrors();
// Show our web panel.
return super.show(true);
}
// tslint:disable-next-line: no-any no-empty cyclomatic-complexity max-func-body-length
public onMessage(message: string, payload: any) {
switch (message) {
case InteractiveWindowMessages.ConvertUriForUseInWebViewRequest:
const request = payload as Uri;
const response = { request, response: this.asWebviewUri(request) };
this.postMessageToListeners(InteractiveWindowMessages.ConvertUriForUseInWebViewResponse, response);
break;
case InteractiveWindowMessages.Started:
// Send the first settings message
this.onDataScienceSettingsChanged().ignoreErrors();
// Send the loc strings (skip during testing as it takes up a lot of memory)
const locStrings = isTestExecution() ? '{}' : localize.getCollectionJSON();
this.postMessageInternal(SharedMessages.LocInit, locStrings).ignoreErrors();
this.variableExplorerHeightRequest()
.then((data) =>
this.postMessageInternal(
InteractiveWindowMessages.VariableExplorerHeightResponse,
data
).ignoreErrors()
)
.catch(); // do nothing
break;
case InteractiveWindowMessages.GotoCodeCell:
this.handleMessage(message, payload, this.gotoCode);
break;
case InteractiveWindowMessages.CopyCodeCell:
this.handleMessage(message, payload, this.copyCode);
break;
case InteractiveWindowMessages.RestartKernel:
this.restartKernel().ignoreErrors();
break;
case InteractiveWindowMessages.Interrupt:
this.interruptKernel().ignoreErrors();
break;
case InteractiveWindowMessages.SendInfo:
this.handleMessage(message, payload, this.updateContexts);
break;
case InteractiveWindowMessages.SubmitNewCell:
this.handleMessage(message, payload, this.submitNewCell);
break;
case InteractiveWindowMessages.ReExecuteCells:
this.handleMessage(message, payload, this.reexecuteCells);
break;
case InteractiveWindowMessages.Undo:
this.logTelemetry(Telemetry.Undo);
break;
case InteractiveWindowMessages.Redo:
this.logTelemetry(Telemetry.Redo);
break;
case InteractiveWindowMessages.ExpandAll:
this.logTelemetry(Telemetry.ExpandAll);
break;
case InteractiveWindowMessages.CollapseAll:
this.logTelemetry(Telemetry.CollapseAll);
break;
case InteractiveWindowMessages.VariableExplorerToggle:
this.variableExplorerToggle(payload);
break;
case InteractiveWindowMessages.SetVariableExplorerHeight:
this.setVariableExplorerHeight(payload).ignoreErrors();
break;
case InteractiveWindowMessages.AddedSysInfo:
this.handleMessage(message, payload, this.onAddedSysInfo);
break;
case InteractiveWindowMessages.RemoteAddCode:
this.handleMessage(message, payload, this.onRemoteAddedCode);
break;
case InteractiveWindowMessages.RemoteReexecuteCode:
this.handleMessage(message, payload, this.onRemoteReexecuteCode);
break;
case InteractiveWindowMessages.ShowDataViewer:
this.handleMessage(message, payload, this.showDataViewer);
break;
case InteractiveWindowMessages.GetVariablesRequest:
this.handleMessage(message, payload, this.requestVariables);
break;
case InteractiveWindowMessages.LoadTmLanguageRequest:
this.handleMessage(message, payload, this.requestTmLanguage);
break;
case InteractiveWindowMessages.LoadOnigasmAssemblyRequest:
this.handleMessage(message, payload, this.requestOnigasm);
break;
case InteractiveWindowMessages.SelectKernel:
this.handleMessage(message, payload, this.selectKernel);
break;
case InteractiveWindowMessages.SelectJupyterServer:
this.handleMessage(message, payload, this.selectServer);
break;
case InteractiveWindowMessages.OpenSettings:
this.handleMessage(message, payload, this.openSettings);
break;
default:
break;
}
// Let our listeners handle the message too
this.postMessageToListeners(message, payload);
// Pass onto our base class.
super.onMessage(message, payload);
// After our base class handles some stuff, handle it ourselves too.
switch (message) {
case CssMessages.GetCssRequest:
// Update the notebook if we have one:
if (this._notebook) {
this.isDark()
.then((d) => (this._notebook ? this._notebook.setMatplotLibStyle(d) : Promise.resolve()))
.ignoreErrors();
}
break;
default:
break;
}
}
public dispose() {
super.dispose();
this.getNotebookIdentity()
.then((r) => {
// Tell listeners we're closing. They can decide if they should dispose themselves or not.
this.listeners.forEach((l) => l.onMessage(InteractiveWindowMessages.NotebookClose, r));
})
.ignoreErrors();
this.updateContexts(undefined);
}
public startProgress() {
this.postMessage(InteractiveWindowMessages.StartProgress).ignoreErrors();
}
public stopProgress() {
this.postMessage(InteractiveWindowMessages.StopProgress).ignoreErrors();
}
@captureTelemetry(Telemetry.Undo)
public undoCells() {
this.postMessage(InteractiveWindowMessages.Undo).ignoreErrors();
}
@captureTelemetry(Telemetry.Redo)
public redoCells() {
this.postMessage(InteractiveWindowMessages.Redo).ignoreErrors();
}
@captureTelemetry(Telemetry.DeleteAllCells)
public removeAllCells() {
this.postMessage(InteractiveWindowMessages.DeleteAllCells).ignoreErrors();
}
@captureTelemetry(Telemetry.RestartKernel)
public async restartKernel(internal: boolean = false): Promise<void> {
// Only log this if it's user requested restart
if (!internal) {
this.logTelemetry(Telemetry.RestartKernelCommand);
}
if (this._notebook && !this.restartingKernel) {
this.restartingKernel = true;
this.startProgress();
try {
if (await this.shouldAskForRestart()) {
// Ask the user if they want us to restart or not.
const message = localize.DataScience.restartKernelMessage();
const yes = localize.DataScience.restartKernelMessageYes();
const dontAskAgain = localize.DataScience.restartKernelMessageDontAskAgain();
const no = localize.DataScience.restartKernelMessageNo();
const v = await this.applicationShell.showInformationMessage(message, yes, dontAskAgain, no);
if (v === dontAskAgain) {
await this.disableAskForRestart();
await this.restartKernelInternal();
} else if (v === yes) {
await this.restartKernelInternal();
}
} else {
await this.restartKernelInternal();
}
} finally {
this.restartingKernel = false;
this.stopProgress();
}
}
}
@captureTelemetry(Telemetry.Interrupt)
public async interruptKernel(): Promise<void> {
if (this._notebook && !this.restartingKernel) {
const status = this.statusProvider.set(
localize.DataScience.interruptKernelStatus(),
true,
undefined,
undefined,
this
);
try {
const settings = this.configuration.getSettings(await this.getOwningResource());
const interruptTimeout = settings.datascience.jupyterInterruptTimeout;
const result = await this._notebook.interruptKernel(interruptTimeout);
status.dispose();
// We timed out, ask the user if they want to restart instead.
if (result === InterruptResult.TimedOut && !this.restartingKernel) {
const message = localize.DataScience.restartKernelAfterInterruptMessage();
const yes = localize.DataScience.restartKernelMessageYes();
const no = localize.DataScience.restartKernelMessageNo();
const v = await this.applicationShell.showInformationMessage(message, yes, no);
if (v === yes) {
await this.restartKernelInternal();
}
} else if (result === InterruptResult.Restarted) {
// Uh-oh, keyboard interrupt crashed the kernel.
this.addSysInfo(SysInfoReason.Interrupt).ignoreErrors();
}
} catch (err) {
status.dispose();
traceError(err);
this.applicationShell.showErrorMessage(err);
}
}
}
@captureTelemetry(Telemetry.CopySourceCode, undefined, false)
public copyCode(args: ICopyCode) {
return this.copyCodeInternal(args.source).catch((err) => {
this.applicationShell.showErrorMessage(err);
});
}
protected onViewStateChanged(args: WebViewViewChangeEventArgs) {
// Only activate if the active editor is empty. This means that
// vscode thinks we are actually supposed to have focus. It would be
// nice if they would more accurrately tell us this, but this works for now.
// Essentially the problem is the webPanel.active state doesn't track
// if the focus is supposed to be in the webPanel or not. It only tracks if
// it's been activated. However if there's no active text editor and we're active, we
// can safely attempt to give ourselves focus. This won't actually give us focus if we aren't
// allowed to have it.
if (args.current.active && !args.previous.active) {
this.activating().ignoreErrors();
}
// Tell our listeners, they may need to know too
this.listeners.forEach((l) => (l.onViewStateChanged ? l.onViewStateChanged(args) : noop()));
}
protected async activating() {
// Only activate if the active editor is empty. This means that
// vscode thinks we are actually supposed to have focus. It would be
// nice if they would more accurrately tell us this, but this works for now.
// Essentially the problem is the webPanel.active state doesn't track
// if the focus is supposed to be in the webPanel or not. It only tracks if
// it's been activated. However if there's no active text editor and we're active, we
// can safely attempt to give ourselves focus. This won't actually give us focus if we aren't
// allowed to have it.
if (this.viewState.active && !this.documentManager.activeTextEditor) {
// Force the webpanel to reveal and take focus.
await super.show(false);
// Send this to the react control
await this.postMessage(InteractiveWindowMessages.Activate);
}
}
// Submits a new cell to the window
protected abstract submitNewCell(info: ISubmitNewCell): void;
// Re-executes cells already in the window
protected reexecuteCells(_info: IReExecuteCells): void {
// Default is not to do anything. This only works in the native editor
}
protected abstract getNotebookMetadata(): Promise<nbformat.INotebookMetadata | undefined>;
protected abstract updateContexts(info: IInteractiveWindowInfo | undefined): void;
protected abstract getNotebookIdentity(): Promise<INotebookIdentity>;
protected abstract closeBecauseOfFailure(exc: Error): Promise<void>;
protected abstract updateNotebookOptions(
kernelSpec: IJupyterKernelSpec,
interpreter: PythonInterpreter | undefined
): Promise<void>;
protected async clearResult(id: string): Promise<void> {
await this.ensureConnectionAndNotebook();
if (this._notebook) {
this._notebook.clear(id);
}
}
protected async setLaunchingFile(file: string): Promise<void> {
if (file !== Identifiers.EmptyFileName && this._notebook) {
await this._notebook.setLaunchingFile(file);
}
}
protected getNotebook(): INotebook | undefined {
return this._notebook;
}
// tslint:disable-next-line: max-func-body-length
protected async submitCode(
code: string,
file: string,
line: number,
id?: string,
data?: nbformat.ICodeCell | nbformat.IRawCell | nbformat.IMarkdownCell,
debugInfo?: { runByLine: boolean; hashFileName?: string },
cancelToken?: CancellationToken
): Promise<boolean> {
traceInfo(`Submitting code for ${this.id}`);
const stopWatch =
this._notebook && !this.perceivedJupyterStartupTelemetryCaptured ? new StopWatch() : undefined;
let result = true;
// Do not execute or render empty code cells
const cellMatcher = new CellMatcher(this.configService.getSettings(await this.getOwningResource()).datascience);
if (cellMatcher.stripFirstMarker(code).length === 0) {
return result;
}
// Start a status item
const status = this.setStatus(localize.DataScience.executingCode(), false);
// Transmit this submission to all other listeners (in a live share session)
if (!id) {
id = uuid();
this.shareMessage(InteractiveWindowMessages.RemoteAddCode, {
code,
file,
line,
id,
originator: this.id,
debug: debugInfo !== undefined ? true : false
});
}
// Create a deferred object that will wait until the status is disposed
const finishedAddingCode = createDeferred<void>();
const actualDispose = status.dispose.bind(status);
status.dispose = () => {
finishedAddingCode.resolve();
actualDispose();
};
try {
// Make sure we're loaded first.
await this.ensureConnectionAndNotebook();
// Make sure we set the dark setting
await this.ensureDarkSet();
// Then show our webpanel
await this.show();
// Add our sys info if necessary
if (file !== Identifiers.EmptyFileName) {
await this.addSysInfo(SysInfoReason.Start);
}
if (this._notebook) {
// Before we try to execute code make sure that we have an initial directory set
// Normally set via the workspace, but we might not have one here if loading a single loose file
await this.setLaunchingFile(file);
if (debugInfo) {
// Attach our debugger based on run by line setting
if (debugInfo.runByLine && debugInfo.hashFileName) {
await this.jupyterDebugger.startRunByLine(this._notebook, debugInfo.hashFileName);
} else if (!debugInfo.runByLine) {
await this.jupyterDebugger.startDebugging(this._notebook);
} else {
throw Error('Missing hash file name when running by line');
}
}
// If the file isn't unknown, set the active kernel's __file__ variable to point to that same file.
if (file !== Identifiers.EmptyFileName) {
await this._notebook.execute(
`__file__ = '${file.replace(/\\/g, '\\\\')}'`,
file,
line,
uuid(),
cancelToken,
true
);
}
if (stopWatch && !this.perceivedJupyterStartupTelemetryCaptured) {
this.perceivedJupyterStartupTelemetryCaptured = true;
sendTelemetryEvent(Telemetry.PerceivedJupyterStartupNotebook, stopWatch?.elapsedTime);
const disposable = this._notebook.onSessionStatusChanged((e) => {
if (e === ServerStatus.Busy) {
sendTelemetryEvent(Telemetry.StartExecuteNotebookCellPerceivedCold, stopWatch?.elapsedTime);
disposable.dispose();
}
});
}
const owningResource = await this.getOwningResource();
const observable = this._notebook.executeObservable(code, file, line, id, false);
// Indicate we executed some code
this.executeEvent.fire(code);
// Sign up for cell changes
observable.subscribe(
(cells: ICell[]) => {
// Combine the cell data with the possible input data (so we don't lose anything that might have already been in the cells)
const combined = cells.map(this.combineData.bind(undefined, data));
// Then send the combined output to the UI
this.sendCellsToWebView(combined);
// Any errors will move our result to false (if allowed)
if (this.configuration.getSettings(owningResource).datascience.stopOnError) {
result = result && cells.find((c) => c.state === CellState.error) === undefined;
}
},
(error) => {
traceError(`Error executing a cell: `, error);
status.dispose();
if (!(error instanceof CancellationError)) {
this.applicationShell.showErrorMessage(error.toString());
}
},
() => {
// Indicate executing until this cell is done.
status.dispose();
}
);
// Wait for the cell to finish
await finishedAddingCode.promise;
traceInfo(`Finished execution for ${id}`);
}
} finally {
status.dispose();
if (debugInfo) {
if (this._notebook) {
await this.jupyterDebugger.stopDebugging(this._notebook);
}
}
}
return result;
}
protected addMessageImpl(message: string): void {
const cell: ICell = {
id: uuid(),
file: Identifiers.EmptyFileName,
line: 0,
state: CellState.finished,
data: {
cell_type: 'messages',
messages: [message],
source: [],
metadata: {}
}
};
// Do the same thing that happens when new code is added.
this.sendCellsToWebView([cell]);
}
protected sendCellsToWebView(cells: ICell[]) {
// Send each cell to the other side
cells.forEach((cell: ICell) => {
switch (cell.state) {
case CellState.init:
// Tell the react controls we have a new cell
this.postMessage(InteractiveWindowMessages.StartCell, cell).ignoreErrors();
// Keep track of this unfinished cell so if we restart we can finish right away.
this.unfinishedCells.push(cell);
break;
case CellState.executing:
// Tell the react controls we have an update
this.postMessage(InteractiveWindowMessages.UpdateCellWithExecutionResults, cell).ignoreErrors();
break;
case CellState.error:
case CellState.finished:
// Tell the react controls we're done
this.postMessage(InteractiveWindowMessages.FinishCell, cell).ignoreErrors();
// Remove from the list of unfinished cells
this.unfinishedCells = this.unfinishedCells.filter((c) => c.id !== cell.id);
break;
default:
break; // might want to do a progress bar or something
}
});
}
protected postMessage<M extends IInteractiveWindowMapping, T extends keyof M>(
type: T,
payload?: M[T]
): Promise<void> {
// First send to our listeners
this.postMessageToListeners(type.toString(), payload);
// Then send it to the webview
return super.postMessage(type, payload);
}
protected handleMessage<M extends IInteractiveWindowMapping, T extends keyof M>(
_message: T,
// tslint:disable-next-line:no-any
payload: any,
handler: (args: M[T]) => void
) {
const args = payload as M[T];
handler.bind(this)(args);
}
protected setStatus = (message: string, showInWebView: boolean): Disposable => {
const result = this.statusProvider.set(message, showInWebView, undefined, undefined, this);
this.potentiallyUnfinishedStatus.push(result);
return result;
};
protected async addSysInfo(reason: SysInfoReason): Promise<void> {
if (!this.addSysInfoPromise || reason !== SysInfoReason.Start) {
traceInfo(`Adding sys info for ${this.id} ${reason}`);
const deferred = createDeferred<boolean>();
this.addSysInfoPromise = deferred;
// Generate a new sys info cell and send it to the web panel.
const sysInfo = await this.generateSysInfoCell(reason);
if (sysInfo) {
this.sendCellsToWebView([sysInfo]);
}
// For anything but start, tell the other sides of a live share session
if (reason !== SysInfoReason.Start && sysInfo) {
this.shareMessage(InteractiveWindowMessages.AddedSysInfo, {
type: reason,
sysInfoCell: sysInfo,
id: this.id
});
}
// For a restart, tell our window to reset
if (reason === SysInfoReason.Restart || reason === SysInfoReason.New) {
this.postMessage(InteractiveWindowMessages.RestartKernel).ignoreErrors();
}
traceInfo(`Sys info for ${this.id} ${reason} complete`);
deferred.resolve(true);
} else if (this.addSysInfoPromise) {
traceInfo(`Wait for sys info for ${this.id} ${reason}`);
await this.addSysInfoPromise.promise;
}
}
protected async ensureConnectionAndNotebook(): Promise<void> {
if (!this.connectionAndNotebookPromise) {
this.connectionAndNotebookPromise = this.ensureConnectionAndNotebookImpl();
}
try {
await this.connectionAndNotebookPromise;
} catch (e) {
// Reset the load promise. Don't want to keep hitting the same error
this.connectionAndNotebookPromise = undefined;
throw e;
}
}
private combineData(
oldData: nbformat.ICodeCell | nbformat.IRawCell | nbformat.IMarkdownCell | undefined,
cell: ICell
): ICell {
if (oldData) {
const result = {
...cell,
data: {
...oldData,
...cell.data,
metadata: {
...oldData.metadata,
...cell.data.metadata
}
}
};
// Workaround the nyc compiler problem.
// tslint:disable-next-line: no-any
return (result as any) as ICell;
}
// tslint:disable-next-line: no-any
return (cell as any) as ICell;
}
private async ensureConnectionAndNotebookImpl(): Promise<void> {
// Make sure we're loaded first.
try {
traceInfo('Waiting for jupyter server and web panel ...');
const serverConnection = await this.notebookProvider.connect({ getOnly: false, disableUI: false });
if (serverConnection) {
await this.ensureNotebook(serverConnection);
}
} catch (exc) {
// We should dispose ourselves if the load fails. Othewise the user
// updates their install and we just fail again because the load promise is the same.
await this.closeBecauseOfFailure(exc);
// Finally throw the exception so the user can do something about it.
throw exc;
}
}
// tslint:disable-next-line: no-any
private postMessageToListeners(message: string, payload: any) {
if (this.listeners) {
this.listeners.forEach((l) => l.onMessage(message, payload));
}
}
private async shouldAskForRestart(): Promise<boolean> {
const settings = this.configuration.getSettings(await this.getOwningResource());
return settings && settings.datascience && settings.datascience.askForKernelRestart === true;
}
private async disableAskForRestart(): Promise<void> {
const settings = this.configuration.getSettings(await this.getOwningResource());
if (settings && settings.datascience) {
settings.datascience.askForKernelRestart = false;
this.configuration
.updateSetting('dataScience.askForKernelRestart', false, undefined, ConfigurationTarget.Global)
.ignoreErrors();
}
}
private async shouldAskForLargeData(): Promise<boolean> {
const settings = this.configuration.getSettings(await this.getOwningResource());
return settings && settings.datascience && settings.datascience.askForLargeDataFrames === true;
}
private async disableAskForLargeData(): Promise<void> {
const settings = this.configuration.getSettings(await this.getOwningResource());
if (settings && settings.datascience) {
settings.datascience.askForLargeDataFrames = false;
this.configuration
.updateSetting('dataScience.askForLargeDataFrames', false, undefined, ConfigurationTarget.Global)
.ignoreErrors();
}
}
private async checkColumnSize(columnSize: number): Promise<boolean> {
if (columnSize > ColumnWarningSize && (await this.shouldAskForLargeData())) {
const message = localize.DataScience.tooManyColumnsMessage();
const yes = localize.DataScience.tooManyColumnsYes();
const no = localize.DataScience.tooManyColumnsNo();
const dontAskAgain = localize.DataScience.tooManyColumnsDontAskAgain();
const result = await this.applicationShell.showWarningMessage(message, yes, no, dontAskAgain);
if (result === dontAskAgain) {
await this.disableAskForLargeData();
}
return result === yes;
}
return true;
}
private async showDataViewer(request: IShowDataViewer): Promise<void> {
try {
if (await this.checkColumnSize(request.columnSize)) {
const jupyterVariableDataProvider = await this.jupyterVariableDataProviderFactory.create(
request.variable,
this._notebook!
);
const title: string = `${localize.DataScience.dataExplorerTitle()} - ${request.variable.name}`;
await this.dataExplorerFactory.create(jupyterVariableDataProvider, title);
}
} catch (e) {
this.applicationShell.showErrorMessage(e.toString());
}
}
private onAddedSysInfo(sysInfo: IAddedSysInfo) {
// See if this is from us or not.
if (sysInfo.id !== this.id) {
// Not from us, must come from a different interactive window. Add to our
// own to keep in sync
if (sysInfo.sysInfoCell) {
this.sendCellsToWebView([sysInfo.sysInfoCell]);
}
}
}
private async onRemoteReexecuteCode(args: IRemoteReexecuteCode) {
// Make sure this is valid
if (args && args.id && args.file && args.originator !== this.id) {
try {
// On a reexecute clear the previous execution
if (this._notebook) {
this._notebook.clear(args.id);
}
// Indicate this in our telemetry.
// Add new telemetry type
sendTelemetryEvent(Telemetry.RemoteReexecuteCode);
// Submit this item as new code.
this.submitCode(
args.code,
args.file,
args.line,
args.id,
undefined,
args.debug ? { runByLine: false } : undefined
).ignoreErrors();
} catch (exc) {
this.errorHandler.handleError(exc).ignoreErrors();
}
}
}
private async onRemoteAddedCode(args: IRemoteAddCode) {
// Make sure this is valid
if (args && args.id && args.file && args.originator !== this.id) {
try {
// Indicate this in our telemetry.
sendTelemetryEvent(Telemetry.RemoteAddCode);
// Submit this item as new code.
await this.submitCode(
args.code,
args.file,
args.line,
args.id,
undefined,
args.debug ? { runByLine: false } : undefined
);
} catch (exc) {
this.errorHandler.handleError(exc).ignoreErrors();
}
}
}
private finishOutstandingCells() {
this.unfinishedCells.forEach((c) => {
c.state = CellState.error;
this.postMessage(InteractiveWindowMessages.FinishCell, c).ignoreErrors();
});
this.unfinishedCells = [];
this.potentiallyUnfinishedStatus.forEach((s) => s.dispose());
this.potentiallyUnfinishedStatus = [];