-
Notifications
You must be signed in to change notification settings - Fork 297
/
notebookCommandListener.ts
258 lines (237 loc) · 10.9 KB
/
notebookCommandListener.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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { inject, injectable } from 'inversify';
import {
ConfigurationTarget,
NotebookCellData,
NotebookCellKind,
NotebookEdit,
NotebookRange,
Uri,
commands,
window,
workspace
} from 'vscode';
import { IConfigurationService, IDataScienceCommandListener, IDisposableRegistry } from '../platform/common/types';
import { Commands } from '../platform/common/constants';
import { noop } from '../platform/common/utils/misc';
import { NotebookCellLanguageService } from './languages/cellLanguageService';
import { DisplayOptions } from '../kernels/displayOptions';
import { IKernel, IKernelProvider } from '../kernels/types';
import { getDisplayPath } from '../platform/common/platform/fs-paths';
import { DataScience } from '../platform/common/utils/localize';
import { traceInfo, traceVerbose } from '../platform/logging';
import { INotebookEditorProvider } from './types';
import { IServiceContainer } from '../platform/ioc/types';
import { endCellAndDisplayErrorsInCell } from '../kernels/execution/helpers';
import { chainWithPendingUpdates } from '../kernels/execution/notebookUpdater';
import { IDataScienceErrorHandler } from '../kernels/errors/types';
import { getNotebookMetadata } from '../platform/common/utils';
import { KernelConnector } from './controllers/kernelConnector';
import { IControllerRegistration } from './controllers/types';
/**
* Registers commands specific to the notebook UI
*/
@injectable()
export class NotebookCommandListener implements IDataScienceCommandListener {
private kernelInterruptedDontAskToRestart: boolean = false;
constructor(
@inject(IDisposableRegistry) private disposableRegistry: IDisposableRegistry,
@inject(NotebookCellLanguageService) private readonly languageService: NotebookCellLanguageService,
@inject(IConfigurationService) private configurationService: IConfigurationService,
@inject(IKernelProvider) private kernelProvider: IKernelProvider,
@inject(IControllerRegistration) private controllerRegistration: IControllerRegistration,
@inject(IDataScienceErrorHandler) private errorHandler: IDataScienceErrorHandler,
@inject(INotebookEditorProvider) private notebookEditorProvider: INotebookEditorProvider,
@inject(IServiceContainer) private serviceContainer: IServiceContainer
) {}
public register(): void {
this.disposableRegistry.push(
commands.registerCommand(Commands.NotebookEditorRemoveAllCells, () => this.removeAllCells())
);
this.disposableRegistry.push(
commands.registerCommand(Commands.NotebookEditorRunAllCells, () => this.runAllCells())
);
this.disposableRegistry.push(
commands.registerCommand(Commands.NotebookEditorAddCellBelow, () => this.addCellBelow())
);
this.disposableRegistry.push(
// TODO: if contributed anywhere, add context support
commands.registerCommand(Commands.RestartKernelAndRunUpToSelectedCell, () =>
this.restartKernelAndRunUpToSelectedCell()
)
);
this.disposableRegistry.push(
commands.registerCommand(
Commands.RestartKernel,
(context?: { notebookEditor: { notebookUri: Uri } } | Uri) => {
if (context && 'notebookEditor' in context) {
return this.restartKernel(context?.notebookEditor?.notebookUri).catch(noop);
} else {
return this.restartKernel(context).catch(noop);
}
}
)
);
this.disposableRegistry.push(
commands.registerCommand(Commands.InterruptKernel, (context?: { notebookEditor: { notebookUri: Uri } }) =>
this.interruptKernel(context?.notebookEditor?.notebookUri)
)
);
this.disposableRegistry.push(
commands.registerCommand(
Commands.RestartKernelAndRunAllCells,
(context?: { notebookEditor: { notebookUri: Uri } }) => {
if (context && 'notebookEditor' in context) {
this.restartKernelAndRunAllCells(context?.notebookEditor?.notebookUri).catch(noop);
} else {
this.restartKernelAndRunAllCells(context).catch(noop);
}
}
)
);
}
private runAllCells() {
if (window.activeNotebookEditor) {
commands.executeCommand('notebook.execute').then(noop, noop);
}
}
private addCellBelow() {
if (window.activeNotebookEditor) {
commands.executeCommand('notebook.cell.insertCodeCellBelow').then(noop, noop);
}
}
private removeAllCells() {
const document = window.activeNotebookEditor?.notebook;
if (!document) {
return;
}
const defaultLanguage = this.languageService.getPreferredLanguage(getNotebookMetadata(document));
chainWithPendingUpdates(document, (edit) => {
const nbEdit = NotebookEdit.replaceCells(new NotebookRange(0, document.cellCount), [
new NotebookCellData(NotebookCellKind.Code, '', defaultLanguage)
]);
edit.set(document.uri, [nbEdit]);
}).then(noop, noop);
}
private async interruptKernel(notebookUri: Uri | undefined): Promise<void> {
const uri = notebookUri ?? this.notebookEditorProvider.activeNotebookEditor?.notebook.uri;
const document = workspace.notebookDocuments.find((document) => document.uri.toString() === uri?.toString());
if (document === undefined) {
return;
}
traceVerbose(`Command interrupted kernel for ${getDisplayPath(document.uri)}`);
const kernel = this.kernelProvider.get(document);
if (!kernel) {
traceInfo(`Interrupt requested & no kernel.`);
return;
}
await this.wrapKernelMethod('interrupt', kernel);
}
private async restartKernelAndRunAllCells(notebookUri: Uri | undefined) {
await this.restartKernel(notebookUri);
this.runAllCells();
}
private async restartKernelAndRunUpToSelectedCell() {
const activeNBE = this.notebookEditorProvider.activeNotebookEditor;
if (activeNBE) {
await this.restartKernel(activeNBE.notebook.uri);
commands
.executeCommand('notebook.cell.execute', {
ranges: [{ start: 0, end: activeNBE.selection.end }],
document: activeNBE.notebook.uri
})
.then(noop, noop);
}
}
private async restartKernel(notebookUri: Uri | undefined): Promise<void> {
const uri = notebookUri ?? this.notebookEditorProvider.activeNotebookEditor?.notebook.uri;
const document = workspace.notebookDocuments.find((document) => document.uri.toString() === uri?.toString());
if (document === undefined) {
return;
}
const kernel = this.kernelProvider.get(document);
if (kernel) {
traceVerbose(`Restart kernel command handler for ${getDisplayPath(document.uri)}`);
if (await this.shouldAskForRestart(document.uri)) {
// Ask the user if they want us to restart or not.
const message = DataScience.restartKernelMessage;
const yes = DataScience.restartKernelMessageYes;
const dontAskAgain = DataScience.restartKernelMessageDontAskAgain;
const response = await window.showInformationMessage(message, { modal: true }, yes, dontAskAgain);
if (response === dontAskAgain) {
await this.disableAskForRestart(document.uri);
this.wrapKernelMethod('restart', kernel).catch(noop);
} else if (response === yes) {
this.wrapKernelMethod('restart', kernel).catch(noop);
}
} else {
this.wrapKernelMethod('restart', kernel).catch(noop);
}
}
}
private readonly pendingRestartInterrupt = new WeakMap<IKernel, Promise<void>>();
private async wrapKernelMethod(currentContext: 'interrupt' | 'restart', kernel: IKernel) {
const notebook = kernel.notebook;
// We don't want to create multiple restarts/interrupt requests for the same kernel.
const pendingPromise = this.pendingRestartInterrupt.get(kernel);
if (pendingPromise) {
return pendingPromise;
}
const promise = (async () => {
// Get currently executing cell and controller
const currentCell = this.kernelProvider.getKernelExecution(kernel).pendingCells[0];
const controller = this.controllerRegistration.getSelected(notebook);
try {
if (!controller) {
throw new Error('No kernel associated with the notebook');
}
// Wrap the restart/interrupt in a loop that allows the user to switch
await KernelConnector.wrapKernelMethod(
controller.connection,
currentContext,
kernel.creator,
this.serviceContainer,
{ resource: kernel.resourceUri, notebook, controller: controller.controller },
new DisplayOptions(false),
this.disposableRegistry
);
} catch (ex) {
if (currentCell) {
await endCellAndDisplayErrorsInCell(
currentCell,
kernel.controller,
await this.errorHandler.getErrorMessageForDisplayInCell(ex, currentContext, kernel.resourceUri),
false
);
} else {
window.showErrorMessage(ex.toString()).then(noop, noop);
}
}
})();
promise
.finally(() => {
if (this.pendingRestartInterrupt.get(kernel) === promise) {
this.pendingRestartInterrupt.delete(kernel);
}
})
.catch(noop);
this.pendingRestartInterrupt.set(kernel, promise);
return promise;
}
private async shouldAskForRestart(notebookUri: Uri): Promise<boolean> {
if (this.kernelInterruptedDontAskToRestart) {
return false;
}
const settings = this.configurationService.getSettings(notebookUri);
return settings && settings.askForKernelRestart === true;
}
private async disableAskForRestart(notebookUri: Uri): Promise<void> {
const settings = this.configurationService.getSettings(notebookUri);
if (settings) {
this.configurationService
.updateSetting('askForKernelRestart', false, undefined, ConfigurationTarget.Global)
.catch(noop);
}
}
}