notebookEditor.ts 48.8 KB
Newer Older
P
Peng Lyu 已提交
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

R
rebornix 已提交
6
import { getZoomLevel } from 'vs/base/browser/browser';
P
Peng Lyu 已提交
7
import * as DOM from 'vs/base/browser/dom';
R
rebornix 已提交
8
import { IMouseWheelEvent, StandardMouseEvent } from 'vs/base/browser/mouseEvent';
9 10
import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation';
import { Color, RGBA } from 'vs/base/common/color';
11
import { onUnexpectedError } from 'vs/base/common/errors';
12
import { Emitter, Event } from 'vs/base/common/event';
13 14
import { combinedDisposable, DisposableStore, MutableDisposable } from 'vs/base/common/lifecycle';
import 'vs/css!./media/notebook';
15
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
16
import { IEditorOptions } from 'vs/editor/common/config/editorOptions';
R
rebornix 已提交
17
import { BareFontInfo } from 'vs/editor/common/config/fontInfo';
18
import { IPosition, Position } from 'vs/editor/common/core/position';
19 20
import { Range } from 'vs/editor/common/core/range';
import { ICompositeCodeEditor, IEditor } from 'vs/editor/common/editorCommon';
21
import { IReadonlyTextBuffer } from 'vs/editor/common/model';
22
import * as nls from 'vs/nls';
23
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
R
Rob Lourens 已提交
24
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
25
import { IResourceEditorInput } from 'vs/platform/editor/common/editor';
R
rebornix 已提交
26 27 28
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IStorageService } from 'vs/platform/storage/common/storage';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
29
import { contrastBorder, editorBackground, focusBorder, foreground, registerColor, textBlockQuoteBackground, textBlockQuoteBorder, textLinkActiveForeground, textLinkForeground, textPreformatForeground } from 'vs/platform/theme/common/colorRegistry';
R
rebornix 已提交
30 31
import { IThemeService, registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { BaseEditor } from 'vs/workbench/browser/parts/editor/baseEditor';
32 33
import { IEditorGroupView } from 'vs/workbench/browser/parts/editor/editor';
import { EditorOptions, IEditorCloseEvent, IEditorMemento } from 'vs/workbench/common/editor';
34 35 36
import { CELL_MARGIN, CELL_RUN_GUTTER, EDITOR_BOTTOM_PADDING, EDITOR_TOP_MARGIN, EDITOR_TOP_PADDING } from 'vs/workbench/contrib/notebook/browser/constants';
import { CellEditState, CellFocusMode, ICellRange, ICellViewModel, IEditableCellViewModel, INotebookCellList, INotebookEditor, INotebookEditorContribution, INotebookEditorMouseEvent, NotebookLayoutInfo, NOTEBOOK_EDITOR_EDITABLE, NOTEBOOK_EDITOR_EXECUTING_NOTEBOOK, NOTEBOOK_EDITOR_FOCUSED, NOTEBOOK_EDITOR_RUNNABLE } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { NotebookEditorExtensionsRegistry } from 'vs/workbench/contrib/notebook/browser/notebookEditorExtensions';
37
import { NotebookEditorInput } from 'vs/workbench/contrib/notebook/browser/notebookEditorInput';
38
import { NotebookCellList } from 'vs/workbench/contrib/notebook/browser/view/notebookCellList';
R
rebornix 已提交
39 40
import { OutputRenderer } from 'vs/workbench/contrib/notebook/browser/view/output/outputRenderer';
import { BackLayerWebView } from 'vs/workbench/contrib/notebook/browser/view/renderers/backLayerWebView';
41
import { CellDragAndDropController, CodeCellRenderer, MarkdownCellRenderer, NotebookCellListDelegate } from 'vs/workbench/contrib/notebook/browser/view/renderers/cellRenderer';
R
rebornix 已提交
42
import { CodeCellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel';
R
rebornix 已提交
43
import { NotebookEventDispatcher, NotebookLayoutChangedEvent } from 'vs/workbench/contrib/notebook/browser/viewModel/eventDispatcher';
44 45
import { CellViewModel, IModelDecorationsChangeAccessor, INotebookEditorViewState, NotebookViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/notebookViewModel';
import { CellKind, CellUri, IOutput } from 'vs/workbench/contrib/notebook/common/notebookCommon';
46 47
import { NotebookEditorModel } from 'vs/workbench/contrib/notebook/common/notebookEditorModel';
import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService';
R
rebornix 已提交
48
import { Webview } from 'vs/workbench/contrib/webview/browser/webview';
49 50
import { getExtraColor } from 'vs/workbench/contrib/welcome/walkThrough/common/walkThroughUtils';
import { IEditorGroup, IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
P
Peng Lyu 已提交
51 52

const $ = DOM.$;
R
rebornix 已提交
53 54
const NOTEBOOK_EDITOR_VIEW_STATE_PREFERENCE_KEY = 'NotebookEditorViewState';

55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
export class NotebookEditorOptions extends EditorOptions {

	readonly cellOptions?: IResourceEditorInput;

	constructor(options: Partial<NotebookEditorOptions>) {
		super();
		this.overwrite(options);
		this.cellOptions = options.cellOptions;
	}

	with(options: Partial<NotebookEditorOptions>): NotebookEditorOptions {
		return new NotebookEditorOptions({ ...this, ...options });
	}
}

R
rebornix 已提交
70
export class NotebookCodeEditors implements ICompositeCodeEditor {
71

72
	private readonly _disposables = new DisposableStore();
73 74 75 76
	private readonly _onDidChangeActiveEditor = new Emitter<this>();
	readonly onDidChangeActiveEditor: Event<this> = this._onDidChangeActiveEditor.event;

	constructor(
R
rebornix 已提交
77
		private _list: INotebookCellList,
R
rebornix 已提交
78
		private _renderedEditors: Map<ICellViewModel, ICodeEditor | undefined>
79
	) {
80
		_list.onDidChangeFocus(_e => this._onDidChangeActiveEditor.fire(this), undefined, this._disposables);
81 82 83 84 85 86
	}

	dispose(): void {
		this._onDidChangeActiveEditor.dispose();
		this._disposables.dispose();
	}
87 88 89

	get activeCodeEditor(): IEditor | undefined {
		const [focused] = this._list.getFocusedElements();
R
rebornix 已提交
90
		return this._renderedEditors.get(focused);
91 92 93
	}
}

R
rebornix 已提交
94
export class NotebookEditor extends BaseEditor implements INotebookEditor {
P
Peng Lyu 已提交
95
	static readonly ID: string = 'workbench.editor.notebook';
R
rebornix 已提交
96
	private _rootElement!: HTMLElement;
P
Peng Lyu 已提交
97
	private body!: HTMLElement;
98
	private titleBar: HTMLElement | null = null;
P
Peng Lyu 已提交
99
	private webview: BackLayerWebView | null = null;
R
rebornix 已提交
100
	private webviewTransparentCover: HTMLElement | null = null;
R
rebornix 已提交
101
	private list: INotebookCellList | undefined;
102
	private control: ICompositeCodeEditor | undefined;
R
rebornix 已提交
103
	private renderedEditors: Map<ICellViewModel, ICodeEditor | undefined> = new Map();
R
rebornix 已提交
104
	private eventDispatcher: NotebookEventDispatcher | undefined;
R
rebornix 已提交
105
	private notebookViewModel: NotebookViewModel | undefined;
106
	private localStore: DisposableStore = this._register(new DisposableStore());
R
rebornix 已提交
107
	private editorMemento: IEditorMemento<INotebookEditorViewState>;
R
rebornix 已提交
108
	private readonly groupListener = this._register(new MutableDisposable());
109
	private fontInfo: BareFontInfo | undefined;
110
	private dimension: DOM.Dimension | null = null;
R
rebornix 已提交
111
	private editorFocus: IContextKey<boolean> | null = null;
R
rebornix 已提交
112
	private editorEditable: IContextKey<boolean> | null = null;
113
	private editorRunnable: IContextKey<boolean> | null = null;
114
	private editorExecutingNotebook: IContextKey<boolean> | null = null;
R
rebornix 已提交
115
	private outputRenderer: OutputRenderer;
R
rebornix 已提交
116
	protected readonly _contributions: { [key: string]: INotebookEditorContribution; };
R
rebornix 已提交
117
	private scrollBeyondLastLine: boolean;
P
Peng Lyu 已提交
118 119 120 121 122

	constructor(
		@ITelemetryService telemetryService: ITelemetryService,
		@IThemeService themeService: IThemeService,
		@IInstantiationService private readonly instantiationService: IInstantiationService,
P
Peng Lyu 已提交
123
		@IStorageService storageService: IStorageService,
R
rebornix 已提交
124
		@INotebookService private notebookService: INotebookService,
125
		@IEditorGroupsService editorGroupService: IEditorGroupsService,
R
rebornix 已提交
126
		@IConfigurationService private readonly configurationService: IConfigurationService,
R
rebornix 已提交
127
		@IContextKeyService private readonly contextKeyService: IContextKeyService
P
Peng Lyu 已提交
128 129
	) {
		super(NotebookEditor.ID, telemetryService, themeService, storageService);
R
rebornix 已提交
130 131

		this.editorMemento = this.getEditorMemento<INotebookEditorViewState>(editorGroupService, NOTEBOOK_EDITOR_VIEW_STATE_PREFERENCE_KEY);
R
rebornix 已提交
132
		this.outputRenderer = new OutputRenderer(this, this.instantiationService);
R
rebornix 已提交
133
		this._contributions = {};
R
rebornix 已提交
134 135 136 137 138 139 140 141 142 143
		this.scrollBeyondLastLine = this.configurationService.getValue<boolean>('editor.scrollBeyondLastLine');

		this.configurationService.onDidChangeConfiguration(e => {
			if (e.affectsConfiguration('editor.scrollBeyondLastLine')) {
				this.scrollBeyondLastLine = this.configurationService.getValue<boolean>('editor.scrollBeyondLastLine');
				if (this.dimension) {
					this.layout(this.dimension);
				}
			}
		});
R
rebornix 已提交
144 145 146 147 148 149 150 151 152
	}

	private readonly _onDidChangeModel = new Emitter<void>();
	readonly onDidChangeModel: Event<void> = this._onDidChangeModel.event;


	set viewModel(newModel: NotebookViewModel | undefined) {
		this.notebookViewModel = newModel;
		this._onDidChangeModel.fire();
R
rebornix 已提交
153 154
	}

R
rebornix 已提交
155 156 157 158
	get viewModel() {
		return this.notebookViewModel;
	}

P
Peng Lyu 已提交
159 160 161 162 163 164 165 166
	get minimumWidth(): number { return 375; }
	get maximumWidth(): number { return Number.POSITIVE_INFINITY; }

	// these setters need to exist because this extends from BaseEditor
	set minimumWidth(value: number) { /*noop*/ }
	set maximumWidth(value: number) { /*noop*/ }


R
rebornix 已提交
167
	//#region Editor Core
R
rebornix 已提交
168

R
rebornix 已提交
169 170 171 172 173

	public get isNotebookEditor() {
		return true;
	}

174 175 176 177 178 179
	private updateEditorFocus() {
		// Note - focus going to the webview will fire 'blur', but the webview element will be
		// a descendent of the notebook editor root.
		this.editorFocus?.set(DOM.isAncestor(document.activeElement, this.getDomNode()));
	}

P
Peng Lyu 已提交
180
	protected createEditor(parent: HTMLElement): void {
R
rebornix 已提交
181 182
		this._rootElement = DOM.append(parent, $('.notebook-editor'));
		this.createBody(this._rootElement);
183
		this.generateFontInfo();
R
rebornix 已提交
184
		this.editorFocus = NOTEBOOK_EDITOR_FOCUSED.bindTo(this.contextKeyService);
185
		this.editorFocus.set(true);
186 187
		this._register(this.onDidFocus(() => this.updateEditorFocus()));
		this._register(this.onDidBlur(() => this.updateEditorFocus()));
R
rebornix 已提交
188 189 190

		this.editorEditable = NOTEBOOK_EDITOR_EDITABLE.bindTo(this.contextKeyService);
		this.editorEditable.set(true);
191 192
		this.editorRunnable = NOTEBOOK_EDITOR_RUNNABLE.bindTo(this.contextKeyService);
		this.editorRunnable.set(true);
193
		this.editorExecutingNotebook = NOTEBOOK_EDITOR_EXECUTING_NOTEBOOK.bindTo(this.contextKeyService);
R
rebornix 已提交
194 195 196 197 198 199 200 201 202 203 204

		const contributions = NotebookEditorExtensionsRegistry.getEditorContributions();

		for (const desc of contributions) {
			try {
				const contribution = this.instantiationService.createInstance(desc.ctor, this);
				this._contributions[desc.id] = contribution;
			} catch (err) {
				onUnexpectedError(err);
			}
		}
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
	populateEditorTitlebar() {
		for (let element: HTMLElement | null = this._rootElement.parentElement; element; element = element.parentElement) {
			if (DOM.hasClass(element, 'editor-group-container')) {
				// elemnet is editor group container
				for (let i = 0; i < element.childElementCount; i++) {
					const child = element.childNodes.item(i) as HTMLElement;

					if (DOM.hasClass(child, 'title')) {
						this.titleBar = child;
						break;
					}
				}
				break;
			}
		}
	}

	clearEditorTitlebarZindex() {
		if (this.titleBar === null) {
			this.populateEditorTitlebar();
		}

		if (this.titleBar) {
			this.titleBar.style.zIndex = 'auto';
		}
	}

	increaseEditorTitlebarZindex() {
		if (this.titleBar === null) {
			this.populateEditorTitlebar();
		}

		if (this.titleBar) {
			this.titleBar.style.zIndex = '500';
		}
	}

244 245 246
	private generateFontInfo(): void {
		const editorOptions = this.configurationService.getValue<IEditorOptions>('editor');
		this.fontInfo = BareFontInfo.createFromRawSettings(editorOptions, getZoomLevel());
P
Peng Lyu 已提交
247 248 249
	}

	private createBody(parent: HTMLElement): void {
P
Peng Lyu 已提交
250
		this.body = document.createElement('div');
P
Peng Lyu 已提交
251 252 253
		DOM.addClass(this.body, 'cell-list-container');
		this.createCellList();
		DOM.append(parent, this.body);
P
Peng Lyu 已提交
254 255
	}

P
Peng Lyu 已提交
256 257
	private createCellList(): void {
		DOM.addClass(this.body, 'cell-list-container');
P
Peng Lyu 已提交
258

R
Rob Lourens 已提交
259
		const dndController = this._register(new CellDragAndDropController(this));
P
Peng Lyu 已提交
260
		const renders = [
261
			this.instantiationService.createInstance(CodeCellRenderer, this, this.renderedEditors, dndController),
262
			this.instantiationService.createInstance(MarkdownCellRenderer, this.contextKeyService, this, dndController, this.renderedEditors),
P
Peng Lyu 已提交
263 264
		];

J
João Moreno 已提交
265
		this.list = this.instantiationService.createInstance(
R
rebornix 已提交
266
			NotebookCellList,
P
Peng Lyu 已提交
267 268 269 270
			'NotebookCellList',
			this.body,
			this.instantiationService.createInstance(NotebookCellListDelegate),
			renders,
R
rebornix 已提交
271
			this.contextKeyService,
P
Peng Lyu 已提交
272 273
			{
				setRowLineHeight: false,
R
rebornix 已提交
274
				setRowHeight: false,
P
Peng Lyu 已提交
275 276 277
				supportDynamicHeights: true,
				horizontalScrolling: false,
				keyboardSupport: false,
R
rebornix 已提交
278
				mouseSupport: true,
P
Peng Lyu 已提交
279
				multipleSelectionSupport: false,
R
rebornix 已提交
280
				enableKeyboardNavigation: true,
281
				additionalScrollHeight: 0,
282
				transformOptimization: false,
283
				styleController: (_suffix: string) => { return this.list!; },
P
Peng Lyu 已提交
284 285 286 287 288 289 290 291 292 293
				overrideStyles: {
					listBackground: editorBackground,
					listActiveSelectionBackground: editorBackground,
					listActiveSelectionForeground: foreground,
					listFocusAndSelectionBackground: editorBackground,
					listFocusAndSelectionForeground: foreground,
					listFocusBackground: editorBackground,
					listFocusForeground: foreground,
					listHoverForeground: foreground,
					listHoverBackground: editorBackground,
294 295
					listHoverOutline: focusBorder,
					listFocusOutline: focusBorder,
296 297 298 299
					listInactiveSelectionBackground: editorBackground,
					listInactiveSelectionForeground: foreground,
					listInactiveFocusBackground: editorBackground,
					listInactiveFocusOutline: editorBackground,
J
João Moreno 已提交
300 301
				},
				accessibilityProvider: {
R
rebornix 已提交
302 303 304 305
					getAriaLabel() { return null; },
					getWidgetAriaLabel() {
						return nls.localize('notebookTreeAriaLabel', "Notebook");
					}
P
Peng Lyu 已提交
306
				}
R
rebornix 已提交
307
			},
P
Peng Lyu 已提交
308
		);
P
Peng Lyu 已提交
309

310
		this.control = new NotebookCodeEditors(this.list, this.renderedEditors);
311
		this.webview = this.instantiationService.createInstance(BackLayerWebView, this);
312 313
		this.webview.webview.onDidBlur(() => this.updateEditorFocus());
		this.webview.webview.onDidFocus(() => this.updateEditorFocus());
314 315 316 317 318
		this._register(this.webview.onMessage(message => {
			if (this.viewModel) {
				this.notebookService.onDidReceiveMessage(this.viewModel.viewType, this.viewModel.uri, message);
			}
		}));
R
rebornix 已提交
319
		this.list.rowsContainer.appendChild(this.webview.element);
R
rebornix 已提交
320

P
Peng Lyu 已提交
321
		this._register(this.list);
322
		this._register(combinedDisposable(...renders));
R
rebornix 已提交
323 324 325

		// transparent cover
		this.webviewTransparentCover = DOM.append(this.list.rowsContainer, $('.webview-cover'));
326
		this.webviewTransparentCover.style.display = 'none';
R
rebornix 已提交
327

R
rebornix 已提交
328
		this._register(DOM.addStandardDisposableGenericMouseDownListner(this._rootElement, (e: StandardMouseEvent) => {
R
rebornix 已提交
329 330 331 332 333
			if (DOM.hasClass(e.target, 'slider') && this.webviewTransparentCover) {
				this.webviewTransparentCover.style.display = 'block';
			}
		}));

R
rebornix 已提交
334
		this._register(DOM.addStandardDisposableGenericMouseUpListner(this._rootElement, (e: StandardMouseEvent) => {
R
rebornix 已提交
335 336
			if (this.webviewTransparentCover) {
				// no matter when
337
				this.webviewTransparentCover.style.display = 'none';
R
rebornix 已提交
338 339 340
			}
		}));

R
rebornix 已提交
341 342 343 344 345 346 347 348 349 350 351 352
		this._register(this.list.onMouseDown(e => {
			if (e.element) {
				this._onMouseDown.fire({ event: e.browserEvent, target: e.element });
			}
		}));

		this._register(this.list.onMouseUp(e => {
			if (e.element) {
				this._onMouseUp.fire({ event: e.browserEvent, target: e.element });
			}
		}));

P
Peng Lyu 已提交
353 354
	}

R
rebornix 已提交
355 356 357 358
	getDomNode() {
		return this._rootElement;
	}

359 360 361 362
	getControl() {
		return this.control;
	}

R
rebornix 已提交
363 364 365 366
	getInnerWebview(): Webview | undefined {
		return this.webview?.webview;
	}

367 368 369 370 371 372 373 374 375 376
	setVisible(visible: boolean, group?: IEditorGroup): void {
		if (visible) {
			this.increaseEditorTitlebarZindex();
		} else {
			this.clearEditorTitlebarZindex();
		}

		super.setVisible(visible, group);
	}

377 378
	onWillHide() {
		if (this.input && this.input instanceof NotebookEditorInput && !this.input.isDisposed()) {
R
rebornix 已提交
379
			this.saveEditorViewState(this.input);
380 381
		}

R
rebornix 已提交
382
		this.editorFocus?.set(false);
383 384
		if (this.webview) {
			this.localStore.clear();
R
rebornix 已提交
385
			this.list?.rowsContainer.removeChild(this.webview?.element);
386 387 388 389
			this.webview?.dispose();
			this.webview = null;
		}

R
rebornix 已提交
390
		this.list?.clear();
391
		super.onHide();
P
Peng Lyu 已提交
392 393
	}

R
rebornix 已提交
394 395 396 397 398 399 400 401 402 403 404 405
	setEditorVisible(visible: boolean, group: IEditorGroup | undefined): void {
		super.setEditorVisible(visible, group);
		this.groupListener.value = ((group as IEditorGroupView).onWillCloseEditor(e => this.onWillCloseEditorInGroup(e)));
	}

	private onWillCloseEditorInGroup(e: IEditorCloseEvent): void {
		const editor = e.editor;
		if (!(editor instanceof NotebookEditorInput)) {
			return; // only handle files
		}

		if (editor === this.input) {
406
			this.clearEditorTitlebarZindex();
R
rebornix 已提交
407
			this.saveEditorViewState(editor);
408 409 410
		}
	}

R
rebornix 已提交
411 412 413
	focus() {
		super.focus();
		this.editorFocus?.set(true);
414
		this.list?.domFocus();
R
rebornix 已提交
415 416
	}

R
rebornix 已提交
417
	async setInput(input: NotebookEditorInput, options: EditorOptions | undefined, token: CancellationToken): Promise<void> {
R
rebornix 已提交
418
		if (this.input instanceof NotebookEditorInput) {
R
rebornix 已提交
419
			this.saveEditorViewState(this.input);
R
rebornix 已提交
420 421
		}

R
rebornix 已提交
422 423
		await super.setInput(input, options, token);
		const model = await input.resolve();
P
Peng Lyu 已提交
424

425
		if (this.notebookViewModel === undefined || !this.notebookViewModel.equal(model.notebook) || this.webview === null) {
426 427
			this.detachModel();
			await this.attachModel(input, model);
R
rebornix 已提交
428
		}
P
Peng Lyu 已提交
429

430 431 432
		// reveal cell if editor options tell to do so
		if (options instanceof NotebookEditorOptions && options.cellOptions) {
			const cellOptions = options.cellOptions;
R
rebornix 已提交
433
			const cell = this.notebookViewModel!.viewCells.find(cell => cell.uri.toString() === cellOptions.resource.toString());
434
			if (cell) {
435
				this.selectElement(cell);
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
				this.revealInCenterIfOutsideViewport(cell);
				const editor = this.renderedEditors.get(cell)!;
				if (editor) {
					if (cellOptions.options?.selection) {
						const { selection } = cellOptions.options;
						editor.setSelection({
							...selection,
							endLineNumber: selection.endLineNumber || selection.startLineNumber,
							endColumn: selection.endColumn || selection.startColumn
						});
					}
					if (!cellOptions.options?.preserveFocus) {
						editor.focus();
					}
				}
451 452
			}
		}
R
rebornix 已提交
453
	}
454

R
rebornix 已提交
455 456 457 458
	clearInput(): void {
		super.clearInput();
	}

R
rebornix 已提交
459 460
	private detachModel() {
		this.localStore.clear();
R
rebornix 已提交
461
		this.list?.detachViewModel();
R
rebornix 已提交
462 463
		this.viewModel?.dispose();
		// avoid event
R
rebornix 已提交
464 465 466
		this.notebookViewModel = undefined;
		this.webview?.clearInsets();
		this.webview?.clearPreloadsCache();
R
rebornix 已提交
467
		this.list?.clear();
R
rebornix 已提交
468
	}
R
rebornix 已提交
469

470 471 472 473 474 475
	private updateForMetadata(): void {
		this.editorEditable?.set(!!this.viewModel!.metadata?.editable);
		this.editorRunnable?.set(!!this.viewModel!.metadata?.runnable);
		DOM.toggleClass(this.getDomNode(), 'notebook-editor-editable', !!this.viewModel!.metadata?.editable);
	}

R
rebornix 已提交
476 477
	private async attachModel(input: NotebookEditorInput, model: NotebookEditorModel) {
		if (!this.webview) {
478
			this.webview = this.instantiationService.createInstance(BackLayerWebView, this);
R
rebornix 已提交
479 480
			this.list?.rowsContainer.insertAdjacentElement('afterbegin', this.webview!.element);
		}
481

482 483
		await this.webview.waitForInitialization();

R
rebornix 已提交
484
		this.eventDispatcher = new NotebookEventDispatcher();
485
		this.viewModel = this.instantiationService.createInstance(NotebookViewModel, input.viewType!, model.notebook, this.eventDispatcher, this.getLayoutInfo());
R
rebornix 已提交
486
		this.eventDispatcher.emit([new NotebookLayoutChangedEvent({ width: true, fontInfo: true }, this.getLayoutInfo())]);
487

488
		this.updateForMetadata();
R
rebornix 已提交
489
		this.localStore.add(this.eventDispatcher.onDidChangeMetadata((e) => {
490
			this.updateForMetadata();
R
rebornix 已提交
491 492
		}));

R
rebornix 已提交
493
		// restore view states, including contributions
R
rebornix 已提交
494
		const viewState = this.loadTextEditorViewState(input);
R
rebornix 已提交
495 496 497

		{
			// restore view state
R
rebornix 已提交
498
			this.viewModel.restoreEditorViewState(viewState);
R
rebornix 已提交
499 500

			// contribution state restore
R
rebornix 已提交
501 502 503 504 505 506 507 508 509 510

			const contributionsState = viewState?.contributionsState || {};
			const keys = Object.keys(this._contributions);
			for (let i = 0, len = keys.length; i < len; i++) {
				const id = keys[i];
				const contribution = this._contributions[id];
				if (typeof contribution.restoreViewState === 'function') {
					contribution.restoreViewState(contributionsState[id]);
				}
			}
R
rebornix 已提交
511
		}
512

R
rebornix 已提交
513
		this.webview?.updateRendererPreloads(this.viewModel.renderers);
R
rebornix 已提交
514 515 516

		this.localStore.add(this.list!.onWillScroll(e => {
			this.webview!.updateViewScrollTop(-e.scrollTop, []);
R
rebornix 已提交
517
			this.webviewTransparentCover!.style.top = `${e.scrollTop}px`;
R
rebornix 已提交
518 519 520
		}));

		this.localStore.add(this.list!.onDidChangeContentHeight(() => {
521 522 523 524 525 526
			DOM.scheduleAtNextAnimationFrame(() => {
				const scrollTop = this.list?.scrollTop || 0;
				const scrollHeight = this.list?.scrollHeight || 0;
				this.webview!.element.style.height = `${scrollHeight}px`;

				if (this.webview?.insetMapping) {
R
rebornix 已提交
527 528
					let updateItems: { cell: CodeCellViewModel, output: IOutput, cellTop: number }[] = [];
					let removedItems: IOutput[] = [];
529 530 531 532 533 534 535 536
					this.webview?.insetMapping.forEach((value, key) => {
						const cell = value.cell;
						const viewIndex = this.list?.getViewIndex(cell);

						if (viewIndex === undefined) {
							return;
						}

R
rebornix 已提交
537 538 539 540 541
						if (cell.outputs.indexOf(key) < 0) {
							// output is already gone
							removedItems.push(key);
						}

542 543 544 545 546 547 548 549 550 551
						const cellTop = this.list?.getAbsoluteTopOfElement(cell) || 0;
						if (this.webview!.shouldUpdateInset(cell, key, cellTop)) {
							updateItems.push({
								cell: cell,
								output: key,
								cellTop: cellTop
							});
						}
					});

R
rebornix 已提交
552 553
					removedItems.forEach(output => this.webview?.removeInset(output));

554 555
					if (updateItems.length) {
						this.webview?.updateViewScrollTop(-scrollTop, updateItems);
R
rebornix 已提交
556
					}
R
rebornix 已提交
557
				}
558
			});
R
rebornix 已提交
559 560
		}));

R
rebornix 已提交
561
		this.list!.attachViewModel(this.viewModel);
R
rebornix 已提交
562 563 564
		this.localStore.add(this.list!.onDidRemoveOutput(output => {
			this.removeInset(output);
		}));
565 566 567
		this.localStore.add(this.list!.onDidHideOutput(output => {
			this.hideInset(output);
		}));
R
rebornix 已提交
568 569

		this.list!.layout();
R
rebornix 已提交
570

R
rebornix 已提交
571
		// restore list state at last, it must be after list layout
R
rebornix 已提交
572
		this.restoreListViewState(viewState);
573 574
	}

R
rebornix 已提交
575
	private restoreListViewState(viewState: INotebookEditorViewState | undefined): void {
R
rebornix 已提交
576 577 578 579 580 581 582
		if (viewState?.scrollPosition !== undefined) {
			this.list!.scrollTop = viewState!.scrollPosition.top;
			this.list!.scrollLeft = viewState!.scrollPosition.left;
		} else {
			this.list!.scrollTop = 0;
			this.list!.scrollLeft = 0;
		}
583

584
		const focusIdx = typeof viewState?.focus === 'number' ? viewState.focus : 0;
R
rebornix 已提交
585 586 587 588 589 590
		if (focusIdx < this.list!.length) {
			this.list!.setFocus([focusIdx]);
			this.list!.setSelection([focusIdx]);
		} else if (this.list!.length > 0) {
			this.list!.setFocus([0]);
		}
591 592 593 594 595 596 597

		if (viewState?.editorFocused) {
			this.list?.focusView();
			const cell = this.notebookViewModel?.viewCells[focusIdx];
			if (cell) {
				cell.focusMode = CellFocusMode.Editor;
			}
598
		}
P
Peng Lyu 已提交
599 600
	}

R
rebornix 已提交
601
	private saveEditorViewState(input: NotebookEditorInput): void {
R
npe  
rebornix 已提交
602
		if (this.group && this.notebookViewModel) {
R
rebornix 已提交
603
			const state = this.notebookViewModel.geteEditorViewState();
R
rebornix 已提交
604 605
			if (this.list) {
				state.scrollPosition = { left: this.list.scrollLeft, top: this.list.scrollTop };
606
				let cellHeights: { [key: number]: number } = {};
R
rebornix 已提交
607
				for (let i = 0; i < this.viewModel!.length; i++) {
R
rebornix 已提交
608
					const elm = this.viewModel!.viewCells[i] as CellViewModel;
609 610 611 612 613 614 615 616
					if (elm.cellKind === CellKind.Code) {
						cellHeights[i] = elm.layoutInfo.totalHeight;
					} else {
						cellHeights[i] = 0;
					}
				}

				state.cellTotalHeights = cellHeights;
617 618 619

				const focus = this.list.getFocus()[0];
				if (focus) {
620 621 622 623 624 625 626 627
					const element = this.notebookViewModel!.viewCells[focus];
					const itemDOM = this.list?.domElementOfElement(element!);
					let editorFocused = false;
					if (document.activeElement && itemDOM && itemDOM.contains(document.activeElement)) {
						editorFocused = true;
					}

					state.editorFocused = editorFocused;
628 629
					state.focus = focus;
				}
R
rebornix 已提交
630 631
			}

R
rebornix 已提交
632
			// Save contribution view states
R
rebornix 已提交
633 634 635 636 637 638 639 640
			const contributionsState: { [key: string]: any } = {};

			const keys = Object.keys(this._contributions);
			for (const id of keys) {
				const contribution = this._contributions[id];
				if (typeof contribution.saveViewState === 'function') {
					contributionsState[id] = contribution.saveViewState();
				}
R
rebornix 已提交
641 642
			}

R
rebornix 已提交
643
			state.contributionsState = contributionsState;
R
rebornix 已提交
644
			this.editorMemento.saveEditorState(this.group, input.resource, state);
R
rebornix 已提交
645 646 647 648 649
		}
	}

	private loadTextEditorViewState(input: NotebookEditorInput): INotebookEditorViewState | undefined {
		if (this.group) {
R
rebornix 已提交
650
			return this.editorMemento.loadEditorState(this.group, input.resource);
R
rebornix 已提交
651 652 653 654 655 656 657
		}

		return;
	}

	layout(dimension: DOM.Dimension): void {
		this.dimension = new DOM.Dimension(dimension.width, dimension.height);
R
rebornix 已提交
658 659
		DOM.toggleClass(this._rootElement, 'mid-width', dimension.width < 1000 && dimension.width >= 600);
		DOM.toggleClass(this._rootElement, 'narrow-width', dimension.width < 600);
R
rebornix 已提交
660
		DOM.size(this.body, dimension.width, dimension.height);
R
rebornix 已提交
661
		this.list?.updateOptions({ additionalScrollHeight: this.scrollBeyondLastLine ? dimension.height : 0 });
R
rebornix 已提交
662
		this.list?.layout(dimension.height, dimension.width);
R
rebornix 已提交
663 664 665 666 667 668

		if (this.webviewTransparentCover) {
			this.webviewTransparentCover.style.height = `${dimension.height}px`;
			this.webviewTransparentCover.style.width = `${dimension.width}px`;
		}

R
rebornix 已提交
669
		this.eventDispatcher?.emit([new NotebookLayoutChangedEvent({ width: true, fontInfo: true }, this.getLayoutInfo())]);
R
rebornix 已提交
670 671 672 673
	}

	protected saveState(): void {
		if (this.input instanceof NotebookEditorInput) {
R
rebornix 已提交
674
			this.saveEditorViewState(this.input);
R
rebornix 已提交
675 676 677 678 679 680 681
		}

		super.saveState();
	}

	//#endregion

R
rebornix 已提交
682 683
	//#region Editor Features

R
rebornix 已提交
684
	selectElement(cell: ICellViewModel) {
R
rebornix 已提交
685 686
		this.list?.selectElement(cell);
		// this.viewModel!.selectionHandles = [cell.handle];
R
rebornix 已提交
687 688
	}

R
rebornix 已提交
689
	revealInView(cell: ICellViewModel) {
R
rebornix 已提交
690
		this.list?.revealElementInView(cell);
R
rebornix 已提交
691 692
	}

R
rebornix 已提交
693
	revealInCenterIfOutsideViewport(cell: ICellViewModel) {
R
rebornix 已提交
694
		this.list?.revealElementInCenterIfOutsideViewport(cell);
R
rebornix 已提交
695 696
	}

R
rebornix 已提交
697
	revealInCenter(cell: ICellViewModel) {
R
rebornix 已提交
698
		this.list?.revealElementInCenter(cell);
R
rebornix 已提交
699 700
	}

R
rebornix 已提交
701
	revealLineInView(cell: ICellViewModel, line: number): void {
R
rebornix 已提交
702
		this.list?.revealElementLineInView(cell, line);
R
rebornix 已提交
703
	}
R
rebornix 已提交
704

R
rebornix 已提交
705
	revealLineInCenter(cell: ICellViewModel, line: number) {
R
rebornix 已提交
706
		this.list?.revealElementLineInCenter(cell, line);
R
rebornix 已提交
707 708
	}

R
rebornix 已提交
709
	revealLineInCenterIfOutsideViewport(cell: ICellViewModel, line: number) {
R
rebornix 已提交
710
		this.list?.revealElementLineInCenterIfOutsideViewport(cell, line);
R
rebornix 已提交
711 712
	}

R
rebornix 已提交
713
	revealRangeInView(cell: ICellViewModel, range: Range): void {
R
rebornix 已提交
714
		this.list?.revealElementRangeInView(cell, range);
R
rebornix 已提交
715 716
	}

R
rebornix 已提交
717
	revealRangeInCenter(cell: ICellViewModel, range: Range): void {
R
rebornix 已提交
718
		this.list?.revealElementRangeInCenter(cell, range);
R
rebornix 已提交
719 720
	}

R
rebornix 已提交
721
	revealRangeInCenterIfOutsideViewport(cell: ICellViewModel, range: Range): void {
R
rebornix 已提交
722
		this.list?.revealElementRangeInCenterIfOutsideViewport(cell, range);
R
rebornix 已提交
723 724
	}

R
rebornix 已提交
725
	setCellSelection(cell: ICellViewModel, range: Range): void {
R
rebornix 已提交
726
		this.list?.setCellSelection(cell, range);
R
rebornix 已提交
727 728
	}

R
rebornix 已提交
729 730 731 732
	changeDecorations(callback: (changeAccessor: IModelDecorationsChangeAccessor) => any): any {
		return this.notebookViewModel?.changeDecorations(callback);
	}

R
rebornix 已提交
733
	setHiddenAreas(_ranges: ICellRange[]): boolean {
R
rebornix 已提交
734
		return this.list!.setHiddenAreas(_ranges, true);
R
rebornix 已提交
735 736
	}

R
rebornix 已提交
737 738
	//#endregion

R
rebornix 已提交
739 740 741 742 743 744 745 746 747
	//#region Mouse Events
	private readonly _onMouseUp: Emitter<INotebookEditorMouseEvent> = this._register(new Emitter<INotebookEditorMouseEvent>());
	public readonly onMouseUp: Event<INotebookEditorMouseEvent> = this._onMouseUp.event;

	private readonly _onMouseDown: Emitter<INotebookEditorMouseEvent> = this._register(new Emitter<INotebookEditorMouseEvent>());
	public readonly onMouseDown: Event<INotebookEditorMouseEvent> = this._onMouseDown.event;

	//#endregion

R
rebornix 已提交
748
	//#region Cell operations
749
	async layoutNotebookCell(cell: ICellViewModel, height: number): Promise<void> {
750 751 752 753 754 755
		const viewIndex = this.list!.getViewIndex(cell);
		if (viewIndex === undefined) {
			// the cell is hidden
			return;
		}

R
rebornix 已提交
756
		let relayout = (cell: ICellViewModel, height: number) => {
R
rebornix 已提交
757
			this.list?.updateElementHeight2(cell, height);
R
rebornix 已提交
758 759
		};

760
		let r: () => void;
R
rebornix 已提交
761
		DOM.scheduleAtNextAnimationFrame(() => {
R
rebornix 已提交
762
			relayout(cell, height);
763
			r();
R
rebornix 已提交
764
		});
765 766

		return new Promise(resolve => { r = resolve; });
767 768
	}

R
rebornix 已提交
769
	insertNotebookCell(cell: ICellViewModel | undefined, type: CellKind, direction: 'above' | 'below' = 'above', initialText: string = '', ui: boolean = false): CellViewModel | null {
770 771 772 773
		if (!this.notebookViewModel!.metadata.editable) {
			return null;
		}

R
rebornix 已提交
774
		const newLanguages = this.notebookViewModel!.languages;
775
		const language = (type === CellKind.Code && newLanguages && newLanguages.length) ? newLanguages[0] : 'markdown';
776
		const index = cell ? this.notebookViewModel!.getCellIndex(cell) : 0;
R
rebornix 已提交
777
		const nextIndex = ui ? this.notebookViewModel!.getNextVisibleCellIndex(index) : index + 1;
778
		const insertIndex = cell ?
R
rebornix 已提交
779
			(direction === 'above' ? index : nextIndex) :
780
			index;
R
rebornix 已提交
781
		const newCell = this.notebookViewModel!.createCell(insertIndex, initialText.split(/\r?\n/g), language, type, true);
782
		return newCell;
P
Peng Lyu 已提交
783 784
	}

K
kieferrm 已提交
785 786 787 788 789 790 791 792 793 794 795 796
	private pushIfAbsent(positions: IPosition[], p: IPosition) {
		const last = positions.length > 0 ? positions[positions.length - 1] : undefined;
		if (!last || last.lineNumber !== p.lineNumber || last.column !== p.column) {
			positions.push(p);
		}
	}

	/**
	 * Add split point at the beginning and the end;
	 * Move end of line split points to the beginning of the next line;
	 * Avoid duplicate split points
	 */
R
rebornix 已提交
797
	private splitPointsToBoundaries(splitPoints: IPosition[], textBuffer: IReadonlyTextBuffer): IPosition[] | null {
K
kieferrm 已提交
798
		const boundaries: IPosition[] = [];
R
rebornix 已提交
799 800 801 802
		const lineCnt = textBuffer.getLineCount();
		const getLineLen = (lineNumber: number) => {
			return textBuffer.getLineLength(lineNumber);
		};
K
kieferrm 已提交
803 804 805 806 807 808 809 810 811 812 813 814

		// split points need to be sorted
		splitPoints = splitPoints.sort((l, r) => {
			const lineDiff = l.lineNumber - r.lineNumber;
			const columnDiff = l.column - r.column;
			return lineDiff !== 0 ? lineDiff : columnDiff;
		});

		// eat-up any split point at the beginning, i.e. we ignore the split point at the very beginning
		this.pushIfAbsent(boundaries, new Position(1, 1));

		for (let sp of splitPoints) {
R
rebornix 已提交
815
			if (getLineLen(sp.lineNumber) + 1 === sp.column && sp.lineNumber < lineCnt) {
K
kieferrm 已提交
816 817 818 819 820 821
				sp = new Position(sp.lineNumber + 1, 1);
			}
			this.pushIfAbsent(boundaries, sp);
		}

		// eat-up any split point at the beginning, i.e. we ignore the split point at the very end
R
rebornix 已提交
822
		this.pushIfAbsent(boundaries, new Position(lineCnt, getLineLen(lineCnt) + 1));
K
kieferrm 已提交
823 824 825 826 827

		// if we only have two then they describe the whole range and nothing needs to be split
		return boundaries.length > 2 ? boundaries : null;
	}

828
	private computeCellLinesContents(cell: IEditableCellViewModel, splitPoints: IPosition[]): string[] | null {
R
rebornix 已提交
829
		const rangeBoundaries = this.splitPointsToBoundaries(splitPoints, cell.textBuffer);
K
kieferrm 已提交
830 831 832
		if (!rangeBoundaries) {
			return null;
		}
833
		const newLineModels: string[] = [];
K
kieferrm 已提交
834 835 836 837
		for (let i = 1; i < rangeBoundaries.length; i++) {
			const start = rangeBoundaries[i - 1];
			const end = rangeBoundaries[i];

838
			newLineModels.push(cell.textModel.getValueInRange(new Range(start.lineNumber, start.column, end.lineNumber, end.column)));
K
kieferrm 已提交
839
		}
840

K
kieferrm 已提交
841 842 843
		return newLineModels;
	}

844
	async splitNotebookCell(cell: ICellViewModel): Promise<CellViewModel[] | null> {
K
kieferrm 已提交
845 846 847 848
		if (!this.notebookViewModel!.metadata.editable) {
			return null;
		}

K
kieferrm 已提交
849
		let splitPoints = cell.getSelectionsStartPosition();
K
kieferrm 已提交
850
		if (splitPoints && splitPoints.length > 0) {
851 852 853 854 855 856
			await cell.resolveTextModel();

			if (!cell.hasModel()) {
				return null;
			}

K
kieferrm 已提交
857 858 859 860
			let newLinesContents = this.computeCellLinesContents(cell, splitPoints);
			if (newLinesContents) {

				// update the contents of the first cell
861 862
				cell.textModel.applyEdits([
					{ range: cell.textModel.getFullModelRange(), text: newLinesContents[0] }
R
rebornix 已提交
863
				], true);
K
kieferrm 已提交
864 865 866 867 868 869 870 871 872 873

				// create new cells based on the new text models
				const language = cell.model.language;
				const kind = cell.cellKind;
				let insertIndex = this.notebookViewModel!.getCellIndex(cell) + 1;
				const newCells = [];
				for (let j = 1; j < newLinesContents.length; j++, insertIndex++) {
					newCells.push(this.notebookViewModel!.createCell(insertIndex, newLinesContents[j], language, kind, true));
				}
				return newCells;
K
kieferrm 已提交
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
			}
		}

		return null;
	}

	async joinNotebookCells(cell: ICellViewModel, direction: 'above' | 'below', constraint?: CellKind): Promise<ICellViewModel | null> {
		if (!this.notebookViewModel!.metadata.editable) {
			return null;
		}

		if (constraint && cell.cellKind !== constraint) {
			return null;
		}

		const index = this.notebookViewModel!.getCellIndex(cell);
		if (index === 0 && direction === 'above') {
			return null;
		}

		if (index === this.notebookViewModel!.length - 1 && direction === 'below') {
			return null;
		}

		if (direction === 'above') {
			const above = this.notebookViewModel!.viewCells[index - 1];
			if (constraint && above.cellKind !== constraint) {
				return null;
			}
903 904 905 906 907 908 909 910 911 912 913 914 915

			await above.resolveTextModel();
			if (!above.hasModel()) {
				return null;
			}

			const insertContent = cell.getText();
			const aboveCellLineCount = above.textModel.getLineCount();
			const aboveCellLastLineEndColumn = above.textModel.getLineLength(aboveCellLineCount);
			above.textModel.applyEdits([
				{ range: new Range(aboveCellLineCount, aboveCellLastLineEndColumn + 1, aboveCellLineCount, aboveCellLastLineEndColumn + 1), text: insertContent }
			]);

K
kieferrm 已提交
916 917 918 919 920 921 922
			await this.deleteNotebookCell(cell);
			return above;
		} else {
			const below = this.notebookViewModel!.viewCells[index + 1];
			if (constraint && below.cellKind !== constraint) {
				return null;
			}
923 924 925 926 927 928 929 930 931 932 933 934 935 936

			await cell.resolveTextModel();
			if (!cell.hasModel()) {
				return null;
			}

			const insertContent = below.getText();

			const cellLineCount = cell.textModel.getLineCount();
			const cellLastLineEndColumn = cell.textModel.getLineLength(cellLineCount);
			cell.textModel.applyEdits([
				{ range: new Range(cellLineCount, cellLastLineEndColumn + 1, cellLineCount, cellLastLineEndColumn + 1), text: insertContent }
			]);

K
kieferrm 已提交
937 938 939 940 941
			await this.deleteNotebookCell(below);
			return cell;
		}
	}

942
	async deleteNotebookCell(cell: ICellViewModel): Promise<boolean> {
943 944 945 946
		if (!this.notebookViewModel!.metadata.editable) {
			return false;
		}

R
rebornix 已提交
947
		const index = this.notebookViewModel!.getCellIndex(cell);
R
rebornix 已提交
948
		this.notebookViewModel!.deleteCell(index, true);
949
		return true;
R
rebornix 已提交
950 951
	}

952
	async moveCellDown(cell: ICellViewModel): Promise<boolean> {
953 954 955 956
		if (!this.notebookViewModel!.metadata.editable) {
			return false;
		}

R
rebornix 已提交
957
		const index = this.notebookViewModel!.getCellIndex(cell);
R
rebornix 已提交
958
		if (index === this.notebookViewModel!.length - 1) {
959
			return false;
R
rebornix 已提交
960 961
		}

962
		const newIdx = index + 1;
963
		return this.moveCellToIndex(index, newIdx);
964 965
	}

966
	async moveCellUp(cell: ICellViewModel): Promise<boolean> {
967 968 969 970
		if (!this.notebookViewModel!.metadata.editable) {
			return false;
		}

R
rebornix 已提交
971
		const index = this.notebookViewModel!.getCellIndex(cell);
R
rebornix 已提交
972
		if (index === 0) {
973
			return false;
R
rebornix 已提交
974 975
		}

976
		const newIdx = index - 1;
977
		return this.moveCellToIndex(index, newIdx);
978 979
	}

980
	async moveCell(cell: ICellViewModel, relativeToCell: ICellViewModel, direction: 'above' | 'below'): Promise<boolean> {
981 982 983 984
		if (!this.notebookViewModel!.metadata.editable) {
			return false;
		}

R
Rob Lourens 已提交
985
		if (cell === relativeToCell) {
986
			return false;
R
Rob Lourens 已提交
987 988 989 990 991
		}

		const originalIdx = this.notebookViewModel!.getCellIndex(cell);
		const relativeToIndex = this.notebookViewModel!.getCellIndex(relativeToCell);

R
Rob Lourens 已提交
992 993 994 995 996
		let newIdx = direction === 'above' ? relativeToIndex : relativeToIndex + 1;
		if (originalIdx < newIdx) {
			newIdx--;
		}

R
Rob Lourens 已提交
997 998 999
		return this.moveCellToIndex(originalIdx, newIdx);
	}

1000
	private async moveCellToIndex(index: number, newIdx: number): Promise<boolean> {
R
Rob Lourens 已提交
1001 1002 1003 1004
		if (index === newIdx) {
			return false;
		}

R
rebornix 已提交
1005
		if (!this.notebookViewModel!.moveCellToIdx(index, newIdx, true)) {
1006
			throw new Error('Notebook Editor move cell, index out of range');
1007 1008
		}

1009
		let r: (val: boolean) => void;
1010
		DOM.scheduleAtNextAnimationFrame(() => {
1011
			this.list?.revealElementInView(this.notebookViewModel!.viewCells[newIdx]);
1012
			r(true);
1013
		});
1014 1015

		return new Promise(resolve => { r = resolve; });
1016 1017
	}

R
rebornix 已提交
1018
	editNotebookCell(cell: CellViewModel): void {
1019 1020 1021 1022
		if (!cell.getEvaluatedMetadata(this.notebookViewModel!.metadata).editable) {
			return;
		}

1023
		cell.editState = CellEditState.Editing;
R
rebornix 已提交
1024 1025

		this.renderedEditors.get(cell)?.focus();
P
Peng Lyu 已提交
1026 1027
	}

R
rebornix 已提交
1028
	saveNotebookCell(cell: ICellViewModel): void {
1029
		cell.editState = CellEditState.Preview;
P
Peng Lyu 已提交
1030 1031
	}

R
rebornix 已提交
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
	getActiveCell() {
		let elements = this.list?.getFocusedElements();

		if (elements && elements.length) {
			return elements[0];
		}

		return undefined;
	}

1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
	cancelNotebookExecution(): void {
		if (!this.notebookViewModel!.currentTokenSource) {
			throw new Error('Notebook is not executing');
		}


		this.notebookViewModel!.currentTokenSource.cancel();
		this.notebookViewModel!.currentTokenSource = undefined;
	}

	async executeNotebook(): Promise<void> {
1053 1054 1055 1056
		if (!this.notebookViewModel!.metadata.runnable) {
			return;
		}

1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
		// return this.progressService.showWhile(this._executeNotebook());
		return this._executeNotebook();
	}

	async _executeNotebook(): Promise<void> {
		if (this.notebookViewModel!.currentTokenSource) {
			return;
		}

		const tokenSource = new CancellationTokenSource();
		try {
			this.editorExecutingNotebook!.set(true);
			this.notebookViewModel!.currentTokenSource = tokenSource;

			for (let cell of this.notebookViewModel!.viewCells) {
				if (cell.cellKind === CellKind.Code) {
					await this._executeNotebookCell(cell, tokenSource);
				}
			}
		} finally {
			this.editorExecutingNotebook!.set(false);
			this.notebookViewModel!.currentTokenSource = undefined;
			tokenSource.dispose();
		}
	}

	cancelNotebookCellExecution(cell: ICellViewModel): void {
		if (!cell.currentTokenSource) {
			throw new Error('Cell is not executing');
		}

		cell.currentTokenSource.cancel();
		cell.currentTokenSource = undefined;
	}

1092
	async executeNotebookCell(cell: ICellViewModel): Promise<void> {
1093 1094 1095 1096
		if (!cell.getEvaluatedMetadata(this.notebookViewModel!.metadata).runnable) {
			return;
		}

1097
		const tokenSource = new CancellationTokenSource();
1098 1099 1100 1101 1102 1103 1104
		try {
			this._executeNotebookCell(cell, tokenSource);
		} finally {
			tokenSource.dispose();
		}
	}

R
Rob Lourens 已提交
1105
	private async _executeNotebookCell(cell: ICellViewModel, tokenSource: CancellationTokenSource): Promise<void> {
1106
		try {
1107
			cell.currentTokenSource = tokenSource;
R
rebornix 已提交
1108
			const provider = this.notebookService.getContributedNotebookProviders(this.viewModel!.uri)[0];
1109 1110 1111 1112
			if (provider) {
				const viewType = provider.id;
				const notebookUri = CellUri.parse(cell.uri)?.notebook;
				if (notebookUri) {
1113
					return await this.notebookService.executeNotebookCell(viewType, notebookUri, cell.handle, tokenSource.token);
1114 1115 1116
				}
			}
		} finally {
1117
			cell.currentTokenSource = undefined;
1118 1119 1120
		}
	}

C
Christopher Maynard 已提交
1121 1122
	focusNotebookCell(cell: ICellViewModel, focusItem: 'editor' | 'container' | 'output') {
		if (focusItem === 'editor') {
R
rebornix 已提交
1123
			this.selectElement(cell);
R
rebornix 已提交
1124
			this.list?.focusView();
R
rebornix 已提交
1125

1126
			cell.editState = CellEditState.Editing;
R
rebornix 已提交
1127
			cell.focusMode = CellFocusMode.Editor;
1128
			this.revealInCenterIfOutsideViewport(cell);
C
Christopher Maynard 已提交
1129
		} else if (focusItem === 'output') {
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
			this.selectElement(cell);
			this.list?.focusView();

			if (!this.webview) {
				return;
			}
			this.webview.focusOutput(cell.id);

			cell.editState = CellEditState.Preview;
			cell.focusMode = CellFocusMode.Container;
			this.revealInCenterIfOutsideViewport(cell);
R
rebornix 已提交
1141
		} else {
R
rebornix 已提交
1142
			let itemDOM = this.list?.domElementOfElement(cell);
R
rebornix 已提交
1143 1144 1145
			if (document.activeElement && itemDOM && itemDOM.contains(document.activeElement)) {
				(document.activeElement as HTMLElement).blur();
			}
1146

1147
			cell.editState = CellEditState.Preview;
1148
			cell.focusMode = CellFocusMode.Container;
R
rebornix 已提交
1149

R
rebornix 已提交
1150
			this.selectElement(cell);
1151
			this.revealInCenterIfOutsideViewport(cell);
R
rebornix 已提交
1152
			this.list?.focusView();
R
rebornix 已提交
1153 1154 1155
		}
	}

R
rebornix 已提交
1156 1157 1158 1159
	//#endregion

	//#region MISC

R
rebornix 已提交
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
	getLayoutInfo(): NotebookLayoutInfo {
		if (!this.list) {
			throw new Error('Editor is not initalized successfully');
		}

		return {
			width: this.dimension!.width,
			height: this.dimension!.height,
			fontInfo: this.fontInfo!
		};
	}
R
rebornix 已提交
1171

R
rebornix 已提交
1172 1173
	triggerScroll(event: IMouseWheelEvent) {
		this.list?.triggerScrollFromMouseWheelEvent(event);
R
rebornix 已提交
1174 1175
	}

R
rebornix 已提交
1176
	createInset(cell: CodeCellViewModel, output: IOutput, shadowContent: string, offset: number) {
R
rebornix 已提交
1177 1178
		if (!this.webview) {
			return;
R
rebornix 已提交
1179 1180
		}

R
rebornix 已提交
1181
		let preloads = this.notebookViewModel!.renderers;
R
rebornix 已提交
1182

1183
		if (!this.webview!.insetMapping.has(output)) {
R
rebornix 已提交
1184
			let cellTop = this.list?.getAbsoluteTopOfElement(cell) || 0;
1185
			this.webview!.createInset(cell, output, cellTop, offset, shadowContent, preloads);
R
rebornix 已提交
1186
		} else {
R
rebornix 已提交
1187
			let cellTop = this.list?.getAbsoluteTopOfElement(cell) || 0;
R
rebornix 已提交
1188 1189
			let scrollTop = this.list?.scrollTop || 0;

1190
			this.webview!.updateViewScrollTop(-scrollTop, [{ cell: cell, output: output, cellTop: cellTop }]);
R
rebornix 已提交
1191
		}
R
rebornix 已提交
1192
	}
R
rebornix 已提交
1193

R
rebornix 已提交
1194 1195 1196 1197 1198 1199 1200 1201
	removeInset(output: IOutput) {
		if (!this.webview) {
			return;
		}

		this.webview!.removeInset(output);
	}

1202 1203 1204 1205 1206 1207 1208 1209
	hideInset(output: IOutput) {
		if (!this.webview) {
			return;
		}

		this.webview!.hideInset(output);
	}

R
rebornix 已提交
1210 1211
	getOutputRenderer(): OutputRenderer {
		return this.outputRenderer;
R
rebornix 已提交
1212
	}
1213

1214 1215 1216 1217
	postMessage(message: any) {
		this.webview?.webview.sendMessage(message);
	}

R
rebornix 已提交
1218
	//#endregion
1219

R
rebornix 已提交
1220 1221 1222 1223 1224 1225
	//#region Editor Contributions
	public getContribution<T extends INotebookEditorContribution>(id: string): T {
		return <T>(this._contributions[id] || null);
	}

	//#endregion
R
rebornix 已提交
1226

R
rebornix 已提交
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
	dispose() {
		const keys = Object.keys(this._contributions);
		for (let i = 0, len = keys.length; i < len; i++) {
			const contributionId = keys[i];
			this._contributions[contributionId].dispose();
		}

		super.dispose();
	}

1237 1238 1239 1240 1241
	toJSON(): any {
		return {
			notebookHandle: this.viewModel?.handle
		};
	}
P
Peng Lyu 已提交
1242 1243 1244 1245
}

const embeddedEditorBackground = 'walkThrough.embeddedEditorBackground';

1246 1247 1248 1249 1250 1251
export const focusedCellIndicator = registerColor('notebook.focusedCellIndicator', {
	light: new Color(new RGBA(102, 175, 224)),
	dark: new Color(new RGBA(12, 125, 157)),
	hc: new Color(new RGBA(0, 73, 122))
}, nls.localize('notebook.focusedCellIndicator', "The color of the focused notebook cell indicator."));

1252 1253
export const notebookOutputContainerColor = registerColor('notebook.outputContainerBackgroundColor', {
	dark: new Color(new RGBA(255, 255, 255, 0.06)),
M
Miguel Solorio 已提交
1254
	light: new Color(new RGBA(237, 239, 249)),
1255 1256 1257 1258
	hc: null
}
	, nls.localize('notebook.outputContainerBackgroundColor', "The Color of the notebook output container background."));

R
Rob Lourens 已提交
1259
// TODO currently also used for toolbar border, if we keep all of this, pick a generic name
R
rebornix 已提交
1260 1261 1262 1263 1264 1265
export const CELL_TOOLBAR_SEPERATOR = registerColor('notebook.cellToolbarSeperator', {
	dark: Color.fromHex('#808080').transparent(0.35),
	light: Color.fromHex('#808080').transparent(0.35),
	hc: contrastBorder
}, nls.localize('cellToolbarSeperator', "The color of seperator in Cell bottom toolbar"));

1266

P
Peng Lyu 已提交
1267 1268 1269
registerThemingParticipant((theme, collector) => {
	const color = getExtraColor(theme, embeddedEditorBackground, { dark: 'rgba(0, 0, 0, .4)', extra_dark: 'rgba(200, 235, 255, .064)', light: '#f4f4f4', hc: null });
	if (color) {
R
rebornix 已提交
1270
		collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .cell .monaco-editor-background,
R
Rob Lourens 已提交
1271 1272
			.monaco-workbench .part.editor > .content .notebook-editor .cell .margin-view-overlays,
			.monaco-workbench .part.editor > .content .notebook-editor .cell .cell-statusbar-container { background: ${color}; }`);
1273
		collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .cell-drag-image .cell-editor-container > div { background: ${color} !important; }`);
P
Peng Lyu 已提交
1274 1275 1276
	}
	const link = theme.getColor(textLinkForeground);
	if (link) {
R
rebornix 已提交
1277
		collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .output a,
M
Miguel Solorio 已提交
1278
			.monaco-workbench .part.editor > .content .notebook-editor .cell.markdown a { color: ${link};} `);
P
Peng Lyu 已提交
1279 1280 1281
	}
	const activeLink = theme.getColor(textLinkActiveForeground);
	if (activeLink) {
R
rebornix 已提交
1282
		collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .output a:hover,
R
Rob Lourens 已提交
1283
			.monaco-workbench .part.editor > .content .notebook-editor .cell .output a:active { color: ${activeLink}; }`);
P
Peng Lyu 已提交
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
	}
	const shortcut = theme.getColor(textPreformatForeground);
	if (shortcut) {
		collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor code,
			.monaco-workbench .part.editor > .content .notebook-editor .shortcut { color: ${shortcut}; }`);
	}
	const border = theme.getColor(contrastBorder);
	if (border) {
		collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .monaco-editor { border-color: ${border}; }`);
	}
	const quoteBackground = theme.getColor(textBlockQuoteBackground);
	if (quoteBackground) {
		collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor blockquote { background: ${quoteBackground}; }`);
	}
	const quoteBorder = theme.getColor(textBlockQuoteBorder);
	if (quoteBorder) {
		collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor blockquote { border-color: ${quoteBorder}; }`);
	}
1302

1303 1304 1305
	const containerBackground = theme.getColor(notebookOutputContainerColor);
	if (containerBackground) {
		collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .output { background-color: ${containerBackground}; }`);
1306
	}
1307

R
Rob Lourens 已提交
1308 1309 1310
	const editorBackgroundColor = theme.getColor(editorBackground);
	if (editorBackgroundColor) {
		collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .cell-statusbar-container { border-top: solid 1px ${editorBackgroundColor}; }`);
R
Rob Lourens 已提交
1311
		collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .monaco-list-row > .monaco-toolbar { background-color: ${editorBackgroundColor}; }`);
R
Rob Lourens 已提交
1312
		collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .monaco-list-row.cell-drag-image { background-color: ${editorBackgroundColor}; }`);
1313 1314
	}

R
rebornix 已提交
1315 1316 1317 1318
	const cellToolbarSeperator = theme.getColor(CELL_TOOLBAR_SEPERATOR);
	if (cellToolbarSeperator) {
		collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .cell-bottom-toolbar-container .seperator { background-color: ${cellToolbarSeperator} }`);
		collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .cell-bottom-toolbar-container .seperator-short { background-color: ${cellToolbarSeperator} }`);
R
Rob Lourens 已提交
1319
		collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .monaco-list-row > .monaco-toolbar { border: solid 1px ${cellToolbarSeperator}; }`);
1320 1321
		collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .monaco-list-row:hover .notebook-cell-focus-indicator,
			.monaco-workbench .part.editor > .content .notebook-editor .monaco-list-row.cell-output-hover .notebook-cell-focus-indicator { border-color: ${cellToolbarSeperator}; }`);
R
Rob Lourens 已提交
1322 1323 1324 1325 1326
	}

	const focusedCellIndicatorColor = theme.getColor(focusedCellIndicator);
	if (focusedCellIndicatorColor) {
		collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .monaco-list-row.focused .notebook-cell-focus-indicator { border-color: ${focusedCellIndicatorColor}; }`);
1327
		collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .monaco-list-row .notebook-cell-focus-indicator { border-color: ${focusedCellIndicatorColor}; }`);
R
Rob Lourens 已提交
1328
		collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .monaco-list-row .cell-insertion-indicator { background-color: ${focusedCellIndicatorColor}; }`);
R
Rob Lourens 已提交
1329
		collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .monaco-list-row.cell-editor-focus .cell-editor-part:before { outline: solid 1px ${focusedCellIndicatorColor}; }`);
R
rebornix 已提交
1330 1331
	}

R
rebornix 已提交
1332 1333 1334 1335 1336 1337 1338
	// const widgetShadowColor = theme.getColor(widgetShadow);
	// if (widgetShadowColor) {
	// 	collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row > .monaco-toolbar {
	// 		box-shadow:  0 0 8px 4px ${widgetShadowColor}
	// 	}`)
	// }

1339
	// Cell Margin
M
Miguel Solorio 已提交
1340
	collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row  > div.cell { margin: 0px ${CELL_MARGIN}px 0px ${CELL_MARGIN}px; }`);
R
rebornix 已提交
1341
	collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row { padding-top: ${EDITOR_TOP_MARGIN}px; }`);
R
Rob Lourens 已提交
1342
	collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .output { margin: 0px ${CELL_MARGIN}px 0px ${CELL_MARGIN + CELL_RUN_GUTTER}px }`);
R
rebornix 已提交
1343
	collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .cell-bottom-toolbar-container { width: calc(100% - ${CELL_MARGIN * 2 + CELL_RUN_GUTTER}px); margin: 0px ${CELL_MARGIN}px 0px ${CELL_MARGIN + CELL_RUN_GUTTER}px }`);
R
Rob Lourens 已提交
1344

1345
	collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .markdown-cell-row .cell .cell-editor-part { margin-left: ${CELL_RUN_GUTTER}px; }`);
R
rebornix 已提交
1346
	collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row  > div.cell.markdown { padding-left: ${CELL_RUN_GUTTER}px; }`);
R
Rob Lourens 已提交
1347
	collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .cell .run-button-container { width: ${CELL_RUN_GUTTER}px; }`);
R
Rob Lourens 已提交
1348
	collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .monaco-list .monaco-list-row .cell-insertion-indicator { left: ${CELL_MARGIN + CELL_RUN_GUTTER}px; right: ${CELL_MARGIN}px; }`);
1349
	collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .cell-drag-image .cell-editor-container > div { padding: ${EDITOR_TOP_PADDING}px 16px ${EDITOR_BOTTOM_PADDING}px 16px; }`);
R
Rob Lourens 已提交
1350
	collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .monaco-list .monaco-list-row .notebook-cell-focus-indicator { left: ${CELL_MARGIN}px; }`);
P
Peng Lyu 已提交
1351
});