notebookEditor.ts 42.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.
 *--------------------------------------------------------------------------------------------*/

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

const $ = DOM.$;
R
rebornix 已提交
50 51
const NOTEBOOK_EDITOR_VIEW_STATE_PREFERENCE_KEY = 'NotebookEditorViewState';

52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
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 已提交
67
export class NotebookCodeEditors implements ICompositeCodeEditor {
68

69
	private readonly _disposables = new DisposableStore();
70 71 72 73
	private readonly _onDidChangeActiveEditor = new Emitter<this>();
	readonly onDidChangeActiveEditor: Event<this> = this._onDidChangeActiveEditor.event;

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

	dispose(): void {
		this._onDidChangeActiveEditor.dispose();
		this._disposables.dispose();
	}
84 85 86

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

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

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

		this.editorMemento = this.getEditorMemento<INotebookEditorViewState>(editorGroupService, NOTEBOOK_EDITOR_VIEW_STATE_PREFERENCE_KEY);
R
rebornix 已提交
129
		this.outputRenderer = new OutputRenderer(this, this.instantiationService);
R
rebornix 已提交
130
		this._contributions = {};
R
rebornix 已提交
131 132 133 134 135 136 137 138 139 140
		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 已提交
141 142 143 144 145 146 147 148 149
	}

	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 已提交
150 151
	}

R
rebornix 已提交
152 153 154 155
	get viewModel() {
		return this.notebookViewModel;
	}

P
Peng Lyu 已提交
156 157 158 159 160 161 162 163
	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 已提交
164
	//#region Editor Core
R
rebornix 已提交
165

R
rebornix 已提交
166 167 168 169 170

	public get isNotebookEditor() {
		return true;
	}

P
Peng Lyu 已提交
171
	protected createEditor(parent: HTMLElement): void {
R
rebornix 已提交
172 173
		this._rootElement = DOM.append(parent, $('.notebook-editor'));
		this.createBody(this._rootElement);
174
		this.generateFontInfo();
R
rebornix 已提交
175
		this.editorFocus = NOTEBOOK_EDITOR_FOCUSED.bindTo(this.contextKeyService);
176
		this.editorFocus.set(true);
R
rebornix 已提交
177 178 179 180 181 182 183
		this._register(this.onDidFocus(() => {
			this.editorFocus?.set(true);
		}));

		this._register(this.onDidBlur(() => {
			this.editorFocus?.set(false);
		}));
R
rebornix 已提交
184 185 186

		this.editorEditable = NOTEBOOK_EDITOR_EDITABLE.bindTo(this.contextKeyService);
		this.editorEditable.set(true);
187 188
		this.editorRunnable = NOTEBOOK_EDITOR_RUNNABLE.bindTo(this.contextKeyService);
		this.editorRunnable.set(true);
189
		this.editorExecutingNotebook = NOTEBOOK_EDITOR_EXECUTING_NOTEBOOK.bindTo(this.contextKeyService);
R
rebornix 已提交
190 191 192 193 194 195 196 197 198 199 200

		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);
			}
		}
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
	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';
		}
	}

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

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

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

R
Rob Lourens 已提交
255
		const dndController = new CellDragAndDropController(this);
P
Peng Lyu 已提交
256
		const renders = [
R
Rob Lourens 已提交
257 258
			this.instantiationService.createInstance(CodeCellRenderer, this, this.contextKeyService, this.renderedEditors, dndController),
			this.instantiationService.createInstance(MarkdownCellRenderer, this.contextKeyService, this, dndController),
P
Peng Lyu 已提交
259 260
		];

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

306
		this.control = new NotebookCodeEditors(this.list, this.renderedEditors);
307
		this.webview = this.instantiationService.createInstance(BackLayerWebView, this);
308 309 310 311 312
		this._register(this.webview.onMessage(message => {
			if (this.viewModel) {
				this.notebookService.onDidReceiveMessage(this.viewModel.viewType, this.viewModel.uri, message);
			}
		}));
R
rebornix 已提交
313
		this.list.rowsContainer.appendChild(this.webview.element);
R
rebornix 已提交
314

P
Peng Lyu 已提交
315
		this._register(this.list);
316
		this._register(combinedDisposable(...renders));
R
rebornix 已提交
317 318 319

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

R
rebornix 已提交
322
		this._register(DOM.addStandardDisposableGenericMouseDownListner(this._rootElement, (e: StandardMouseEvent) => {
R
rebornix 已提交
323 324 325 326 327
			if (DOM.hasClass(e.target, 'slider') && this.webviewTransparentCover) {
				this.webviewTransparentCover.style.display = 'block';
			}
		}));

R
rebornix 已提交
328
		this._register(DOM.addStandardDisposableGenericMouseUpListner(this._rootElement, (e: StandardMouseEvent) => {
R
rebornix 已提交
329 330
			if (this.webviewTransparentCover) {
				// no matter when
331
				this.webviewTransparentCover.style.display = 'none';
R
rebornix 已提交
332 333 334
			}
		}));

R
rebornix 已提交
335 336 337 338 339 340 341 342 343 344 345 346
		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 已提交
347 348
	}

R
rebornix 已提交
349 350 351 352
	getDomNode() {
		return this._rootElement;
	}

353 354 355 356
	getControl() {
		return this.control;
	}

R
rebornix 已提交
357 358 359 360
	getInnerWebview(): Webview | undefined {
		return this.webview?.webview;
	}

361 362 363 364 365 366 367 368 369 370
	setVisible(visible: boolean, group?: IEditorGroup): void {
		if (visible) {
			this.increaseEditorTitlebarZindex();
		} else {
			this.clearEditorTitlebarZindex();
		}

		super.setVisible(visible, group);
	}

371 372
	onWillHide() {
		if (this.input && this.input instanceof NotebookEditorInput && !this.input.isDisposed()) {
R
rebornix 已提交
373
			this.saveEditorViewState(this.input);
374 375
		}

R
rebornix 已提交
376
		this.editorFocus?.set(false);
377 378
		if (this.webview) {
			this.localStore.clear();
R
rebornix 已提交
379
			this.list?.rowsContainer.removeChild(this.webview?.element);
380 381 382 383
			this.webview?.dispose();
			this.webview = null;
		}

R
rebornix 已提交
384
		this.list?.clear();
385
		super.onHide();
P
Peng Lyu 已提交
386 387
	}

R
rebornix 已提交
388 389 390 391 392 393 394 395 396 397 398 399
	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) {
400
			this.clearEditorTitlebarZindex();
R
rebornix 已提交
401
			this.saveEditorViewState(editor);
402 403 404
		}
	}

R
rebornix 已提交
405 406 407
	focus() {
		super.focus();
		this.editorFocus?.set(true);
408
		this.list?.domFocus();
R
rebornix 已提交
409 410
	}

R
rebornix 已提交
411
	async setInput(input: NotebookEditorInput, options: EditorOptions | undefined, token: CancellationToken): Promise<void> {
R
rebornix 已提交
412
		if (this.input instanceof NotebookEditorInput) {
R
rebornix 已提交
413
			this.saveEditorViewState(this.input);
R
rebornix 已提交
414 415
		}

R
rebornix 已提交
416 417
		await super.setInput(input, options, token);
		const model = await input.resolve();
P
Peng Lyu 已提交
418

419 420 421
		if (this.notebookViewModel === undefined || !this.notebookViewModel.equal(model) || this.webview === null) {
			this.detachModel();
			await this.attachModel(input, model);
R
rebornix 已提交
422
		}
P
Peng Lyu 已提交
423

424 425 426
		// reveal cell if editor options tell to do so
		if (options instanceof NotebookEditorOptions && options.cellOptions) {
			const cellOptions = options.cellOptions;
R
rebornix 已提交
427
			const cell = this.notebookViewModel!.viewCells.find(cell => cell.uri.toString() === cellOptions.resource.toString());
428
			if (cell) {
429
				this.selectElement(cell);
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
				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();
					}
				}
445 446
			}
		}
R
rebornix 已提交
447
	}
448

R
rebornix 已提交
449 450 451 452
	clearInput(): void {
		super.clearInput();
	}

R
rebornix 已提交
453 454
	private detachModel() {
		this.localStore.clear();
R
rebornix 已提交
455
		this.list?.detachViewModel();
R
rebornix 已提交
456 457
		this.viewModel?.dispose();
		// avoid event
R
rebornix 已提交
458 459 460
		this.notebookViewModel = undefined;
		this.webview?.clearInsets();
		this.webview?.clearPreloadsCache();
R
rebornix 已提交
461
		this.list?.clear();
R
rebornix 已提交
462
	}
R
rebornix 已提交
463

464 465 466 467 468 469
	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 已提交
470 471
	private async attachModel(input: NotebookEditorInput, model: NotebookEditorModel) {
		if (!this.webview) {
472
			this.webview = this.instantiationService.createInstance(BackLayerWebView, this);
R
rebornix 已提交
473 474
			this.list?.rowsContainer.insertAdjacentElement('afterbegin', this.webview!.element);
		}
475

476 477
		await this.webview.waitForInitialization();

R
rebornix 已提交
478
		this.eventDispatcher = new NotebookEventDispatcher();
R
rebornix 已提交
479
		this.viewModel = this.instantiationService.createInstance(NotebookViewModel, input.viewType!, model, this.eventDispatcher, this.getLayoutInfo());
R
rebornix 已提交
480
		this.eventDispatcher.emit([new NotebookLayoutChangedEvent({ width: true, fontInfo: true }, this.getLayoutInfo())]);
481

482
		this.updateForMetadata();
R
rebornix 已提交
483
		this.localStore.add(this.eventDispatcher.onDidChangeMetadata((e) => {
484
			this.updateForMetadata();
R
rebornix 已提交
485 486
		}));

R
rebornix 已提交
487
		// restore view states, including contributions
R
rebornix 已提交
488
		const viewState = this.loadTextEditorViewState(input);
R
rebornix 已提交
489 490 491

		{
			// restore view state
R
rebornix 已提交
492
			this.viewModel.restoreEditorViewState(viewState);
R
rebornix 已提交
493 494

			// contribution state restore
R
rebornix 已提交
495 496 497 498 499 500 501 502 503 504

			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 已提交
505
		}
506

R
rebornix 已提交
507
		this.webview?.updateRendererPreloads(this.viewModel.renderers);
R
rebornix 已提交
508 509 510

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

		this.localStore.add(this.list!.onDidChangeContentHeight(() => {
515 516 517 518 519 520
			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 已提交
521 522
					let updateItems: { cell: CodeCellViewModel, output: IOutput, cellTop: number }[] = [];
					let removedItems: IOutput[] = [];
523 524 525 526 527 528 529 530
					this.webview?.insetMapping.forEach((value, key) => {
						const cell = value.cell;
						const viewIndex = this.list?.getViewIndex(cell);

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

R
rebornix 已提交
531 532 533 534 535
						if (cell.outputs.indexOf(key) < 0) {
							// output is already gone
							removedItems.push(key);
						}

536 537 538 539 540 541 542 543 544 545
						const cellTop = this.list?.getAbsoluteTopOfElement(cell) || 0;
						if (this.webview!.shouldUpdateInset(cell, key, cellTop)) {
							updateItems.push({
								cell: cell,
								output: key,
								cellTop: cellTop
							});
						}
					});

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

548 549
					if (updateItems.length) {
						this.webview?.updateViewScrollTop(-scrollTop, updateItems);
R
rebornix 已提交
550
					}
R
rebornix 已提交
551
				}
552
			});
R
rebornix 已提交
553 554
		}));

R
rebornix 已提交
555
		this.list!.attachViewModel(this.viewModel);
R
rebornix 已提交
556 557 558
		this.localStore.add(this.list!.onDidRemoveOutput(output => {
			this.removeInset(output);
		}));
559 560 561
		this.localStore.add(this.list!.onDidHideOutput(output => {
			this.hideInset(output);
		}));
R
rebornix 已提交
562 563

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

R
rebornix 已提交
565
		// restore list state at last, it must be after list layout
R
rebornix 已提交
566
		this.restoreListViewState(viewState);
567 568
	}

R
rebornix 已提交
569
	private restoreListViewState(viewState: INotebookEditorViewState | undefined): void {
R
rebornix 已提交
570 571 572 573 574 575 576
		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;
		}
577

578
		const focusIdx = typeof viewState?.focus === 'number' ? viewState.focus : 0;
R
rebornix 已提交
579 580 581 582 583 584
		if (focusIdx < this.list!.length) {
			this.list!.setFocus([focusIdx]);
			this.list!.setSelection([focusIdx]);
		} else if (this.list!.length > 0) {
			this.list!.setFocus([0]);
		}
585 586 587 588 589 590 591

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

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

				state.cellTotalHeights = cellHeights;
611 612 613

				const focus = this.list.getFocus()[0];
				if (focus) {
614 615 616 617 618 619 620 621
					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;
622 623
					state.focus = focus;
				}
R
rebornix 已提交
624 625
			}

R
rebornix 已提交
626
			// Save contribution view states
R
rebornix 已提交
627 628 629 630 631 632 633 634
			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 已提交
635 636
			}

R
rebornix 已提交
637
			state.contributionsState = contributionsState;
R
rebornix 已提交
638
			this.editorMemento.saveEditorState(this.group, input.resource, state);
R
rebornix 已提交
639 640 641 642 643
		}
	}

	private loadTextEditorViewState(input: NotebookEditorInput): INotebookEditorViewState | undefined {
		if (this.group) {
R
rebornix 已提交
644
			return this.editorMemento.loadEditorState(this.group, input.resource);
R
rebornix 已提交
645 646 647 648 649 650 651
		}

		return;
	}

	layout(dimension: DOM.Dimension): void {
		this.dimension = new DOM.Dimension(dimension.width, dimension.height);
R
rebornix 已提交
652 653
		DOM.toggleClass(this._rootElement, 'mid-width', dimension.width < 1000 && dimension.width >= 600);
		DOM.toggleClass(this._rootElement, 'narrow-width', dimension.width < 600);
R
rebornix 已提交
654
		DOM.size(this.body, dimension.width, dimension.height);
R
rebornix 已提交
655
		this.list?.updateOptions({ additionalScrollHeight: this.scrollBeyondLastLine ? dimension.height : 0 });
R
rebornix 已提交
656
		this.list?.layout(dimension.height, dimension.width);
R
rebornix 已提交
657 658 659 660 661 662

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

R
rebornix 已提交
663
		this.eventDispatcher?.emit([new NotebookLayoutChangedEvent({ width: true, fontInfo: true }, this.getLayoutInfo())]);
R
rebornix 已提交
664 665 666 667
	}

	protected saveState(): void {
		if (this.input instanceof NotebookEditorInput) {
R
rebornix 已提交
668
			this.saveEditorViewState(this.input);
R
rebornix 已提交
669 670 671 672 673 674 675
		}

		super.saveState();
	}

	//#endregion

R
rebornix 已提交
676 677
	//#region Editor Features

R
rebornix 已提交
678
	selectElement(cell: ICellViewModel) {
R
rebornix 已提交
679
		this.list?.selectElement(cell);
R
rebornix 已提交
680 681
	}

R
rebornix 已提交
682
	revealInView(cell: ICellViewModel) {
R
rebornix 已提交
683
		this.list?.revealElementInView(cell);
R
rebornix 已提交
684 685
	}

R
rebornix 已提交
686
	revealInCenterIfOutsideViewport(cell: ICellViewModel) {
R
rebornix 已提交
687
		this.list?.revealElementInCenterIfOutsideViewport(cell);
R
rebornix 已提交
688 689
	}

R
rebornix 已提交
690
	revealInCenter(cell: ICellViewModel) {
R
rebornix 已提交
691
		this.list?.revealElementInCenter(cell);
R
rebornix 已提交
692 693
	}

R
rebornix 已提交
694
	revealLineInView(cell: ICellViewModel, line: number): void {
R
rebornix 已提交
695
		this.list?.revealElementLineInView(cell, line);
R
rebornix 已提交
696
	}
R
rebornix 已提交
697

R
rebornix 已提交
698
	revealLineInCenter(cell: ICellViewModel, line: number) {
R
rebornix 已提交
699
		this.list?.revealElementLineInCenter(cell, line);
R
rebornix 已提交
700 701
	}

R
rebornix 已提交
702
	revealLineInCenterIfOutsideViewport(cell: ICellViewModel, line: number) {
R
rebornix 已提交
703
		this.list?.revealElementLineInCenterIfOutsideViewport(cell, line);
R
rebornix 已提交
704 705
	}

R
rebornix 已提交
706
	revealRangeInView(cell: ICellViewModel, range: Range): void {
R
rebornix 已提交
707
		this.list?.revealElementRangeInView(cell, range);
R
rebornix 已提交
708 709
	}

R
rebornix 已提交
710
	revealRangeInCenter(cell: ICellViewModel, range: Range): void {
R
rebornix 已提交
711
		this.list?.revealElementRangeInCenter(cell, range);
R
rebornix 已提交
712 713
	}

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

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

R
rebornix 已提交
722 723 724 725
	changeDecorations(callback: (changeAccessor: IModelDecorationsChangeAccessor) => any): any {
		return this.notebookViewModel?.changeDecorations(callback);
	}

R
rebornix 已提交
726
	setHiddenAreas(_ranges: ICellRange[]): boolean {
R
rebornix 已提交
727
		return this.list!.setHiddenAreas(_ranges, true);
R
rebornix 已提交
728 729
	}

R
rebornix 已提交
730 731
	//#endregion

R
rebornix 已提交
732 733 734 735 736 737 738 739 740
	//#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 已提交
741
	//#region Cell operations
742
	async layoutNotebookCell(cell: ICellViewModel, height: number): Promise<void> {
743 744 745 746 747 748
		const viewIndex = this.list!.getViewIndex(cell);
		if (viewIndex === undefined) {
			// the cell is hidden
			return;
		}

R
rebornix 已提交
749
		let relayout = (cell: ICellViewModel, height: number) => {
R
rebornix 已提交
750
			this.list?.updateElementHeight2(cell, height);
R
rebornix 已提交
751 752
		};

753
		let r: () => void;
R
rebornix 已提交
754
		DOM.scheduleAtNextAnimationFrame(() => {
R
rebornix 已提交
755
			relayout(cell, height);
756
			r();
R
rebornix 已提交
757
		});
758 759

		return new Promise(resolve => { r = resolve; });
760 761
	}

762 763 764 765 766
	insertNotebookCell(cell: ICellViewModel | undefined, type: CellKind, direction: 'above' | 'below' = 'above', initialText: string = ''): CellViewModel | null {
		if (!this.notebookViewModel!.metadata.editable) {
			return null;
		}

R
rebornix 已提交
767
		const newLanguages = this.notebookViewModel!.languages;
768
		const language = (type === CellKind.Code && newLanguages && newLanguages.length) ? newLanguages[0] : 'markdown';
769 770 771 772
		const index = cell ? this.notebookViewModel!.getCellIndex(cell) : 0;
		const insertIndex = cell ?
			(direction === 'above' ? index : index + 1) :
			index;
R
rebornix 已提交
773
		const newCell = this.notebookViewModel!.createCell(insertIndex, initialText.split(/\r?\n/g), language, type, true);
P
Peng Lyu 已提交
774

R
rebornix 已提交
775
		if (type === CellKind.Markdown) {
776
			newCell.editState = CellEditState.Editing;
P
Peng Lyu 已提交
777
		}
R
rebornix 已提交
778

779
		return newCell;
P
Peng Lyu 已提交
780 781
	}

782
	async deleteNotebookCell(cell: ICellViewModel): Promise<boolean> {
783 784 785 786
		if (!this.notebookViewModel!.metadata.editable) {
			return false;
		}

787
		(cell as CellViewModel).save();
R
rebornix 已提交
788
		const index = this.notebookViewModel!.getCellIndex(cell);
R
rebornix 已提交
789
		this.notebookViewModel!.deleteCell(index, true);
790
		return true;
R
rebornix 已提交
791 792
	}

793
	async moveCellDown(cell: ICellViewModel): Promise<boolean> {
794 795 796 797
		if (!this.notebookViewModel!.metadata.editable) {
			return false;
		}

R
rebornix 已提交
798
		const index = this.notebookViewModel!.getCellIndex(cell);
R
rebornix 已提交
799
		if (index === this.notebookViewModel!.length - 1) {
800
			return false;
R
rebornix 已提交
801 802
		}

803
		const newIdx = index + 1;
804
		return this.moveCellToIndex(index, newIdx);
805 806
	}

807
	async moveCellUp(cell: ICellViewModel): Promise<boolean> {
808 809 810 811
		if (!this.notebookViewModel!.metadata.editable) {
			return false;
		}

R
rebornix 已提交
812
		const index = this.notebookViewModel!.getCellIndex(cell);
R
rebornix 已提交
813
		if (index === 0) {
814
			return false;
R
rebornix 已提交
815 816
		}

817
		const newIdx = index - 1;
818
		return this.moveCellToIndex(index, newIdx);
819 820
	}

821
	async moveCell(cell: ICellViewModel, relativeToCell: ICellViewModel, direction: 'above' | 'below'): Promise<boolean> {
822 823 824 825
		if (!this.notebookViewModel!.metadata.editable) {
			return false;
		}

R
Rob Lourens 已提交
826
		if (cell === relativeToCell) {
827
			return false;
R
Rob Lourens 已提交
828 829 830 831 832
		}

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

R
Rob Lourens 已提交
833 834 835 836 837
		let newIdx = direction === 'above' ? relativeToIndex : relativeToIndex + 1;
		if (originalIdx < newIdx) {
			newIdx--;
		}

R
Rob Lourens 已提交
838 839 840
		return this.moveCellToIndex(originalIdx, newIdx);
	}

841
	private async moveCellToIndex(index: number, newIdx: number): Promise<boolean> {
R
Rob Lourens 已提交
842 843 844 845
		if (index === newIdx) {
			return false;
		}

R
rebornix 已提交
846
		if (!this.notebookViewModel!.moveCellToIdx(index, newIdx, true)) {
847
			throw new Error('Notebook Editor move cell, index out of range');
848 849
		}

850
		let r: (val: boolean) => void;
851
		DOM.scheduleAtNextAnimationFrame(() => {
852
			this.list?.revealElementInView(this.notebookViewModel!.viewCells[newIdx]);
853
			r(true);
854
		});
855 856

		return new Promise(resolve => { r = resolve; });
857 858
	}

R
rebornix 已提交
859
	editNotebookCell(cell: CellViewModel): void {
860 861 862 863
		if (!cell.getEvaluatedMetadata(this.notebookViewModel!.metadata).editable) {
			return;
		}

864
		cell.editState = CellEditState.Editing;
R
rebornix 已提交
865 866

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

R
rebornix 已提交
869
	saveNotebookCell(cell: ICellViewModel): void {
870
		cell.editState = CellEditState.Preview;
P
Peng Lyu 已提交
871 872
	}

R
rebornix 已提交
873 874 875 876 877 878 879 880 881 882
	getActiveCell() {
		let elements = this.list?.getFocusedElements();

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

		return undefined;
	}

883 884 885 886 887 888 889 890 891 892 893
	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> {
894 895 896 897
		if (!this.notebookViewModel!.metadata.runnable) {
			return;
		}

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
		// 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;
	}

933
	async executeNotebookCell(cell: ICellViewModel): Promise<void> {
934 935 936 937
		if (!cell.getEvaluatedMetadata(this.notebookViewModel!.metadata).runnable) {
			return;
		}

938
		const tokenSource = new CancellationTokenSource();
939 940 941 942 943 944 945
		try {
			this._executeNotebookCell(cell, tokenSource);
		} finally {
			tokenSource.dispose();
		}
	}

R
Rob Lourens 已提交
946
	private async _executeNotebookCell(cell: ICellViewModel, tokenSource: CancellationTokenSource): Promise<void> {
947
		try {
948
			cell.currentTokenSource = tokenSource;
R
rebornix 已提交
949
			const provider = this.notebookService.getContributedNotebookProviders(this.viewModel!.uri)[0];
950 951 952 953
			if (provider) {
				const viewType = provider.id;
				const notebookUri = CellUri.parse(cell.uri)?.notebook;
				if (notebookUri) {
954
					return await this.notebookService.executeNotebookCell(viewType, notebookUri, cell.handle, tokenSource.token);
955 956 957
				}
			}
		} finally {
958
			cell.currentTokenSource = undefined;
959 960 961
		}
	}

R
rebornix 已提交
962
	focusNotebookCell(cell: ICellViewModel, focusEditor: boolean) {
R
rebornix 已提交
963
		if (focusEditor) {
R
rebornix 已提交
964
			this.selectElement(cell);
R
rebornix 已提交
965
			this.list?.focusView();
R
rebornix 已提交
966

967
			cell.editState = CellEditState.Editing;
R
rebornix 已提交
968
			cell.focusMode = CellFocusMode.Editor;
969
			this.revealInCenterIfOutsideViewport(cell);
R
rebornix 已提交
970
		} else {
R
rebornix 已提交
971
			let itemDOM = this.list?.domElementOfElement(cell);
R
rebornix 已提交
972 973 974
			if (document.activeElement && itemDOM && itemDOM.contains(document.activeElement)) {
				(document.activeElement as HTMLElement).blur();
			}
975

976
			cell.editState = CellEditState.Preview;
977
			cell.focusMode = CellFocusMode.Container;
R
rebornix 已提交
978

R
rebornix 已提交
979
			this.selectElement(cell);
980
			this.revealInCenterIfOutsideViewport(cell);
R
rebornix 已提交
981
			this.list?.focusView();
R
rebornix 已提交
982 983 984
		}
	}

R
rebornix 已提交
985 986 987 988
	//#endregion

	//#region MISC

R
rebornix 已提交
989 990 991 992 993 994 995 996 997 998 999
	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 已提交
1000

R
rebornix 已提交
1001 1002
	triggerScroll(event: IMouseWheelEvent) {
		this.list?.triggerScrollFromMouseWheelEvent(event);
R
rebornix 已提交
1003 1004
	}

R
rebornix 已提交
1005
	createInset(cell: CodeCellViewModel, output: IOutput, shadowContent: string, offset: number) {
R
rebornix 已提交
1006 1007
		if (!this.webview) {
			return;
R
rebornix 已提交
1008 1009
		}

R
rebornix 已提交
1010
		let preloads = this.notebookViewModel!.renderers;
R
rebornix 已提交
1011

1012
		if (!this.webview!.insetMapping.has(output)) {
R
rebornix 已提交
1013
			let cellTop = this.list?.getAbsoluteTopOfElement(cell) || 0;
1014
			this.webview!.createInset(cell, output, cellTop, offset, shadowContent, preloads);
R
rebornix 已提交
1015
		} else {
R
rebornix 已提交
1016
			let cellTop = this.list?.getAbsoluteTopOfElement(cell) || 0;
R
rebornix 已提交
1017 1018
			let scrollTop = this.list?.scrollTop || 0;

1019
			this.webview!.updateViewScrollTop(-scrollTop, [{ cell: cell, output: output, cellTop: cellTop }]);
R
rebornix 已提交
1020
		}
R
rebornix 已提交
1021
	}
R
rebornix 已提交
1022

R
rebornix 已提交
1023 1024 1025 1026 1027 1028 1029 1030
	removeInset(output: IOutput) {
		if (!this.webview) {
			return;
		}

		this.webview!.removeInset(output);
	}

1031 1032 1033 1034 1035 1036 1037 1038
	hideInset(output: IOutput) {
		if (!this.webview) {
			return;
		}

		this.webview!.hideInset(output);
	}

R
rebornix 已提交
1039 1040
	getOutputRenderer(): OutputRenderer {
		return this.outputRenderer;
R
rebornix 已提交
1041
	}
1042

1043 1044 1045 1046
	postMessage(message: any) {
		this.webview?.webview.sendMessage(message);
	}

R
rebornix 已提交
1047
	//#endregion
1048

R
rebornix 已提交
1049 1050 1051 1052 1053 1054
	//#region Editor Contributions
	public getContribution<T extends INotebookEditorContribution>(id: string): T {
		return <T>(this._contributions[id] || null);
	}

	//#endregion
R
rebornix 已提交
1055

R
rebornix 已提交
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
	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();
	}

1066 1067 1068 1069 1070
	toJSON(): any {
		return {
			notebookHandle: this.viewModel?.handle
		};
	}
P
Peng Lyu 已提交
1071 1072 1073 1074
}

const embeddedEditorBackground = 'walkThrough.embeddedEditorBackground';

1075 1076 1077 1078 1079 1080
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."));

1081 1082
export const notebookOutputContainerColor = registerColor('notebook.outputContainerBackgroundColor', {
	dark: new Color(new RGBA(255, 255, 255, 0.06)),
M
Miguel Solorio 已提交
1083
	light: new Color(new RGBA(237, 239, 249)),
1084 1085 1086 1087
	hc: null
}
	, nls.localize('notebook.outputContainerBackgroundColor', "The Color of the notebook output container background."));

R
Rob Lourens 已提交
1088
// TODO currently also used for toolbar border, if we keep all of this, pick a generic name
R
rebornix 已提交
1089 1090 1091 1092 1093 1094
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"));

1095

P
Peng Lyu 已提交
1096 1097 1098
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 已提交
1099
		collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .cell .monaco-editor-background,
R
Rob Lourens 已提交
1100 1101
			.monaco-workbench .part.editor > .content .notebook-editor .cell .margin-view-overlays,
			.monaco-workbench .part.editor > .content .notebook-editor .cell .cell-statusbar-container { background: ${color}; }`);
1102
		collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .cell-drag-image .cell-editor-container > div { background: ${color} !important; }`);
P
Peng Lyu 已提交
1103 1104 1105
	}
	const link = theme.getColor(textLinkForeground);
	if (link) {
R
rebornix 已提交
1106
		collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .output a,
M
Miguel Solorio 已提交
1107
			.monaco-workbench .part.editor > .content .notebook-editor .cell.markdown a { color: ${link};} `);
P
Peng Lyu 已提交
1108 1109 1110
	}
	const activeLink = theme.getColor(textLinkActiveForeground);
	if (activeLink) {
R
rebornix 已提交
1111
		collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .output a:hover,
R
Rob Lourens 已提交
1112
			.monaco-workbench .part.editor > .content .notebook-editor .cell .output a:active { color: ${activeLink}; }`);
P
Peng Lyu 已提交
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
	}
	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}; }`);
	}
1131

1132 1133 1134
	const containerBackground = theme.getColor(notebookOutputContainerColor);
	if (containerBackground) {
		collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .output { background-color: ${containerBackground}; }`);
1135
	}
1136

R
Rob Lourens 已提交
1137 1138 1139
	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 已提交
1140
		collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .monaco-list-row > .monaco-toolbar { background-color: ${editorBackgroundColor}; }`);
R
Rob Lourens 已提交
1141
		collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .monaco-list-row.cell-drag-image { background-color: ${editorBackgroundColor}; }`);
1142 1143
	}

R
rebornix 已提交
1144 1145 1146 1147
	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 已提交
1148
		collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .monaco-list-row > .monaco-toolbar { border: solid 1px ${cellToolbarSeperator}; }`);
1149 1150
		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 已提交
1151 1152 1153 1154 1155
	}

	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}; }`);
1156
		collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .monaco-list-row .notebook-cell-focus-indicator { border-color: ${focusedCellIndicatorColor}; }`);
R
Rob Lourens 已提交
1157
		collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .monaco-list-row .notebook-cell-insertion-indicator-top { background-color: ${focusedCellIndicatorColor}; }`);
R
Rob Lourens 已提交
1158
		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 已提交
1159 1160
	}

R
rebornix 已提交
1161 1162 1163 1164 1165 1166 1167
	// 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}
	// 	}`)
	// }

1168
	// Cell Margin
M
Miguel Solorio 已提交
1169
	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 已提交
1170
	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 已提交
1171
	collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .output { margin: 0px ${CELL_MARGIN}px 0px ${CELL_MARGIN + CELL_RUN_GUTTER}px }`);
R
rebornix 已提交
1172
	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 已提交
1173

1174
	collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .markdown-cell-row .cell .cell-editor-part { margin-left: ${CELL_RUN_GUTTER}px; }`);
R
rebornix 已提交
1175
	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 已提交
1176
	collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .cell .run-button-container { width: ${CELL_RUN_GUTTER}px; }`);
R
Rob Lourens 已提交
1177
	collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .monaco-list .monaco-list-row .notebook-cell-insertion-indicator-top { left: ${CELL_MARGIN + CELL_RUN_GUTTER}px; right: ${CELL_MARGIN}px; }`);
1178
	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 已提交
1179
	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 已提交
1180
});