notebookViewModel.ts 28.4 KB
Newer Older
R
rebornix 已提交
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 { CancellationTokenSource } from 'vs/base/common/cancellation';
R
rebornix 已提交
7
import { onUnexpectedError } from 'vs/base/common/errors';
R
rebornix 已提交
8
import { Emitter, Event } from 'vs/base/common/event';
R
rebornix 已提交
9
import { Disposable, DisposableStore } from 'vs/base/common/lifecycle';
R
rebornix 已提交
10
import * as strings from 'vs/base/common/strings';
R
rebornix 已提交
11
import { URI } from 'vs/base/common/uri';
R
rebornix 已提交
12 13
import { IBulkEditService } from 'vs/editor/browser/services/bulkEditService';
import { Range } from 'vs/editor/common/core/range';
R
rebornix 已提交
14
import * as editorCommon from 'vs/editor/common/editorCommon';
R
rebornix 已提交
15 16 17
import { IModelDecorationOptions, IModelDeltaDecoration, TrackedRangeStickiness } from 'vs/editor/common/model';
import { IntervalNode, IntervalTree } from 'vs/editor/common/model/intervalTree';
import { ModelDecorationOptions } from 'vs/editor/common/model/textModel';
R
rebornix 已提交
18
import { WorkspaceTextEdit } from 'vs/editor/common/modes';
R
rebornix 已提交
19
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
R
rebornix 已提交
20
import { IUndoRedoService } from 'vs/platform/undoRedo/common/undoRedo';
R
rebornix 已提交
21
import { CellEditState, CellFindMatch, ICellRange, ICellViewModel, NotebookLayoutInfo } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
R
rebornix 已提交
22
import { NotebookEditorModel } from 'vs/workbench/contrib/notebook/browser/notebookEditorInput';
23
import { DeleteCellEdit, InsertCellEdit, MoveCellEdit, SpliceCellsEdit } from 'vs/workbench/contrib/notebook/browser/viewModel/cellEdit';
R
rebornix 已提交
24
import { CodeCellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel';
R
rebornix 已提交
25
import { NotebookEventDispatcher, NotebookMetadataChangedEvent } from 'vs/workbench/contrib/notebook/browser/viewModel/eventDispatcher';
R
rebornix 已提交
26
import { CellFoldingState, EditorFoldingStateDelegate } from 'vs/workbench/contrib/notebook/browser/contrib/fold/foldingModel';
R
rebornix 已提交
27
import { MarkdownCellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/markdownCellViewModel';
R
rebornix 已提交
28
import { NotebookCellTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookCellTextModel';
29
import { CellKind } from 'vs/workbench/contrib/notebook/common/notebookCommon';
R
rebornix 已提交
30
import { FoldingRegions } from 'vs/editor/contrib/folding/foldingRanges';
R
rebornix 已提交
31 32 33

export interface INotebookEditorViewState {
	editingCells: { [key: number]: boolean };
R
rebornix 已提交
34
	editorViewStates: { [key: number]: editorCommon.ICodeEditorViewState | null };
R
rebornix 已提交
35
	hiddenFoldingRanges?: ICellRange[];
36
	cellTotalHeights?: { [key: number]: number };
R
rebornix 已提交
37
	scrollPosition?: { left: number; top: number; };
38
	focus?: number;
39
	editorFocused?: boolean;
R
rebornix 已提交
40
	contributionsState?: { [id: string]: any };
R
rebornix 已提交
41 42
}

R
rebornix 已提交
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
export interface ICellModelDecorations {
	ownerId: number;
	decorations: string[];
}

export interface ICellModelDeltaDecorations {
	ownerId: number;
	decorations: IModelDeltaDecoration[];
}

export interface IModelDecorationsChangeAccessor {
	deltaDecorations(oldDecorations: ICellModelDecorations[], newDecorations: ICellModelDeltaDecorations[]): ICellModelDecorations[];
}

const invalidFunc = () => { throw new Error(`Invalid change accessor`); };


R
rebornix 已提交
60 61 62 63 64 65 66 67 68 69 70
export type NotebookViewCellsSplice = [
	number /* start */,
	number /* delete count */,
	CellViewModel[]
];

export interface INotebookViewCellsUpdateEvent {
	synchronous: boolean;
	splices: NotebookViewCellsSplice[];
}

R
rebornix 已提交
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129

class DecorationsTree {
	private readonly _decorationsTree: IntervalTree;

	constructor() {
		this._decorationsTree = new IntervalTree();
	}

	public intervalSearch(start: number, end: number, filterOwnerId: number, filterOutValidation: boolean, cachedVersionId: number): IntervalNode[] {
		const r1 = this._decorationsTree.intervalSearch(start, end, filterOwnerId, filterOutValidation, cachedVersionId);
		return r1;
	}

	public search(filterOwnerId: number, filterOutValidation: boolean, overviewRulerOnly: boolean, cachedVersionId: number): IntervalNode[] {
		return this._decorationsTree.search(filterOwnerId, filterOutValidation, cachedVersionId);

	}

	public collectNodesFromOwner(ownerId: number): IntervalNode[] {
		const r1 = this._decorationsTree.collectNodesFromOwner(ownerId);
		return r1;
	}

	public collectNodesPostOrder(): IntervalNode[] {
		const r1 = this._decorationsTree.collectNodesPostOrder();
		return r1;
	}

	public insert(node: IntervalNode): void {
		this._decorationsTree.insert(node);
	}

	public delete(node: IntervalNode): void {
		this._decorationsTree.delete(node);
	}

	public resolveNode(node: IntervalNode, cachedVersionId: number): void {
		this._decorationsTree.resolveNode(node, cachedVersionId);
	}

	public acceptReplace(offset: number, length: number, textLength: number, forceMoveMarkers: boolean): void {
		this._decorationsTree.acceptReplace(offset, length, textLength, forceMoveMarkers);
	}
}

const TRACKED_RANGE_OPTIONS = [
	ModelDecorationOptions.register({ stickiness: TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges }),
	ModelDecorationOptions.register({ stickiness: TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges }),
	ModelDecorationOptions.register({ stickiness: TrackedRangeStickiness.GrowsOnlyWhenTypingBefore }),
	ModelDecorationOptions.register({ stickiness: TrackedRangeStickiness.GrowsOnlyWhenTypingAfter }),
];

function _normalizeOptions(options: IModelDecorationOptions): ModelDecorationOptions {
	if (options instanceof ModelDecorationOptions) {
		return options;
	}
	return ModelDecorationOptions.createDynamic(options);
}

R
rebornix 已提交
130 131 132 133 134 135 136 137 138 139 140 141 142 143
function selectionsEqual(a: number[], b: number[]) {
	if (a.length !== b.length) {
		return false;
	}

	for (let i = 0; i < a.length; i++) {
		if (a[i] !== b[i]) {
			return false;
		}
	}

	return true;
}

R
rebornix 已提交
144 145 146
let MODEL_ID = 0;


R
rebornix 已提交
147
export class NotebookViewModel extends Disposable implements EditorFoldingStateDelegate {
R
rebornix 已提交
148 149
	private _localStore: DisposableStore = this._register(new DisposableStore());
	private _viewCells: CellViewModel[] = [];
R
rebornix 已提交
150
	private _handleToViewCellMapping = new Map<number, CellViewModel>();
R
rebornix 已提交
151

152 153 154 155 156 157 158 159 160 161
	private _currentTokenSource: CancellationTokenSource | undefined;

	get currentTokenSource(): CancellationTokenSource | undefined {
		return this._currentTokenSource;
	}

	set currentTokenSource(v: CancellationTokenSource | undefined) {
		this._currentTokenSource = v;
	}

R
rebornix 已提交
162
	get viewCells(): ICellViewModel[] {
R
rebornix 已提交
163 164 165
		return this._viewCells;
	}

R
rebornix 已提交
166 167 168 169 170 171 172 173
	set viewCells(_: ICellViewModel[]) {
		throw new Error('NotebookViewModel.viewCells is readonly');
	}

	get length(): number {
		return this._viewCells.length;
	}

R
rebornix 已提交
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
	get notebookDocument() {
		return this._model.notebook;
	}

	get renderers() {
		return this._model.notebook!.renderers;
	}

	get handle() {
		return this._model.notebook.handle;
	}

	get languages() {
		return this._model.notebook.languages;
	}

	get uri() {
		return this._model.notebook.uri;
	}

R
rebornix 已提交
194 195 196 197
	get metadata() {
		return this._model.notebook.metadata;
	}

R
rebornix 已提交
198 199
	private readonly _onDidChangeViewCells = new Emitter<INotebookViewCellsUpdateEvent>();
	get onDidChangeViewCells(): Event<INotebookViewCellsUpdateEvent> { return this._onDidChangeViewCells.event; }
R
rebornix 已提交
200

R
rebornix 已提交
201 202 203 204 205 206 207 208 209
	private _lastNotebookEditResource: URI[] = [];

	get lastNotebookEditResource(): URI | null {
		if (this._lastNotebookEditResource.length) {
			return this._lastNotebookEditResource[this._lastNotebookEditResource.length - 1];
		}
		return null;
	}

210 211 212 213
	get layoutInfo(): NotebookLayoutInfo | null {
		return this._layoutInfo;
	}

R
rebornix 已提交
214 215 216
	private readonly _onDidChangeSelection = new Emitter<void>();
	get onDidChangeSelection(): Event<void> { return this._onDidChangeSelection.event; }

R
rebornix 已提交
217 218
	private _selections: number[] = [];

R
rebornix 已提交
219
	get selectionHandles() {
R
rebornix 已提交
220 221 222
		return this._selections;
	}

R
rebornix 已提交
223 224 225 226 227 228
	set selectionHandles(selections: number[]) {
		selections = selections.sort();
		if (selectionsEqual(selections, this.selectionHandles)) {
			return;
		}

R
rebornix 已提交
229 230
		this._selections = selections;
		this._model.notebook.selections = selections;
R
rebornix 已提交
231
		this._onDidChangeSelection.fire();
R
rebornix 已提交
232 233
	}

R
rebornix 已提交
234 235 236 237 238
	private _decorationsTree = new DecorationsTree();
	private _decorations: { [decorationId: string]: IntervalNode; } = Object.create(null);
	private _lastDecorationId: number = 0;
	private readonly _instanceId: string;
	public readonly id: string;
R
rebornix 已提交
239
	private _foldingRanges: FoldingRegions | null = null;
R
rebornix 已提交
240 241
	private _hiddenRanges: ICellRange[] = [];

R
rebornix 已提交
242 243 244
	constructor(
		public viewType: string,
		private _model: NotebookEditorModel,
R
rebornix 已提交
245
		readonly eventDispatcher: NotebookEventDispatcher,
246
		private _layoutInfo: NotebookLayoutInfo | null,
R
rebornix 已提交
247
		@IInstantiationService private readonly instantiationService: IInstantiationService,
R
rebornix 已提交
248 249
		@IBulkEditService private readonly bulkEditService: IBulkEditService,
		@IUndoRedoService private readonly undoService: IUndoRedoService
R
rebornix 已提交
250 251 252
	) {
		super();

R
rebornix 已提交
253 254 255 256
		MODEL_ID++;
		this.id = '$notebookViewModel' + MODEL_ID;
		this._instanceId = strings.singleLetterHash(MODEL_ID);

R
rebornix 已提交
257 258 259 260 261 262 263
		this._register(this._model.onDidChangeCells(e => {
			const diffs = e.map(splice => {
				return [splice[0], splice[1], splice[2].map(cell => {
					return createCellViewModel(this.instantiationService, this, cell as NotebookCellTextModel);
				})] as [number, number, CellViewModel[]];
			});

264 265 266 267 268 269
			const undoDiff = diffs.map(diff => {
				const deletedCells = this.viewCells.slice(diff[0], diff[0] + diff[1]);

				return [diff[0], deletedCells, diff[2]] as [number, CellViewModel[], CellViewModel[]];
			});

R
rebornix 已提交
270 271 272 273 274 275 276 277 278 279 280 281
			diffs.reverse().forEach(diff => {
				this._viewCells.splice(diff[0], diff[1], ...diff[2]);
				diff[2].forEach(cell => {
					this._handleToViewCellMapping.set(cell.handle, cell);
					this._localStore.add(cell);
				});
			});

			this._onDidChangeViewCells.fire({
				synchronous: true,
				splices: diffs
			});
282

R
rebornix 已提交
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
			let endSelectionHandles: number[] = [];
			if (this.selectionHandles.length) {
				const primaryHandle = this.selectionHandles[0];
				const primarySelectionIndex = this._viewCells.indexOf(this.getCellByHandle(primaryHandle)!);
				endSelectionHandles = [primaryHandle];
				let delta = 0;

				for (let i = 0; i < diffs.length; i++) {
					const diff = diffs[0];
					if (diff[0] + diff[1] <= primarySelectionIndex) {
						delta += diff[2].length - diff[1];
						continue;
					}

					if (diff[0] > primarySelectionIndex) {
						endSelectionHandles = [primaryHandle];
						break;
					}

					if (diff[0] + diff[1] > primaryHandle) {
						endSelectionHandles = [this._viewCells[diff[0] + delta].handle];
						break;
					}
				}
			}

309 310
			this.undoService.pushElement(new SpliceCellsEdit(this.uri, undoDiff, {
				insertCell: this._insertCellDelegate.bind(this),
R
rebornix 已提交
311 312 313 314 315
				deleteCell: this._deleteCellDelegate.bind(this),
				setSelections: this._setSelectionsDelegate.bind(this)
			}, this.selectionHandles, endSelectionHandles));

			this.selectionHandles = endSelectionHandles;
R
rebornix 已提交
316
		}));
R
rebornix 已提交
317

R
rebornix 已提交
318 319 320 321
		this._register(this._model.notebook.onDidChangeMetadata(e => {
			this.eventDispatcher.emit([new NotebookMetadataChangedEvent(e)]);
		}));

322 323
		this._register(this.eventDispatcher.onDidChangeLayout((e) => {
			this._layoutInfo = e.value;
R
rebornix 已提交
324 325 326 327 328 329 330 331 332 333 334 335

			this._viewCells.forEach(cell => {
				if (cell.cellKind === CellKind.Markdown) {
					if (e.source.width || e.source.fontInfo) {
						cell.layoutChange({ outerWidth: e.value.width, font: e.value.fontInfo });
					}
				} else {
					if (e.source.width !== undefined) {
						cell.layoutChange({ outerWidth: e.value.width, font: e.value.fontInfo });
					}
				}
			});
336 337
		}));

R
rebornix 已提交
338
		this._viewCells = this._model!.notebook!.cells.map(cell => {
R
rebornix 已提交
339
			return createCellViewModel(this.instantiationService, this, cell);
R
rebornix 已提交
340
		});
R
rebornix 已提交
341

R
rebornix 已提交
342 343 344
		this._viewCells.forEach(cell => {
			this._handleToViewCellMapping.set(cell.handle, cell);
		});
R
rebornix 已提交
345 346
	}

R
rebornix 已提交
347
	getFoldingStartIndex(index: number): number {
R
rebornix 已提交
348 349 350 351 352 353
		if (!this._foldingRanges) {
			return -1;
		}

		const range = this._foldingRanges.findRange(index + 1);
		const startIndex = this._foldingRanges.getStartLineNumber(range) - 1;
R
rebornix 已提交
354 355 356
		return startIndex;
	}

R
rebornix 已提交
357
	getFoldingState(index: number): CellFoldingState {
R
rebornix 已提交
358
		if (!this._foldingRanges) {
R
rebornix 已提交
359 360 361
			return CellFoldingState.None;
		}

R
rebornix 已提交
362 363
		const range = this._foldingRanges.findRange(index + 1);
		const startIndex = this._foldingRanges.getStartLineNumber(range) - 1;
R
rebornix 已提交
364

R
rebornix 已提交
365
		if (startIndex !== index) {
R
rebornix 已提交
366
			return CellFoldingState.None;
R
rebornix 已提交
367 368
		}

R
rebornix 已提交
369
		return this._foldingRanges.isCollapsed(range) ? CellFoldingState.Collapsed : CellFoldingState.Expanded;
R
rebornix 已提交
370 371
	}

R
rebornix 已提交
372 373
	updateFoldingRanges(ranges: FoldingRegions) {
		this._foldingRanges = ranges;
R
rebornix 已提交
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
		let updateHiddenAreas = false;
		let newHiddenAreas: ICellRange[] = [];

		let i = 0; // index into hidden
		let k = 0;

		let lastCollapsedStart = Number.MAX_VALUE;
		let lastCollapsedEnd = -1;

		for (; i < ranges.length; i++) {
			if (!ranges.isCollapsed(i)) {
				continue;
			}

			let startLineNumber = ranges.getStartLineNumber(i) + 1; // the first line is not hidden
			let endLineNumber = ranges.getEndLineNumber(i);
			if (lastCollapsedStart <= startLineNumber && endLineNumber <= lastCollapsedEnd) {
				// ignore ranges contained in collapsed regions
				continue;
			}

R
rebornix 已提交
395
			if (!updateHiddenAreas && k < this._hiddenRanges.length && this._hiddenRanges[k].start + 1 === startLineNumber && (this._hiddenRanges[k].end + 1) === endLineNumber) {
R
rebornix 已提交
396 397 398 399 400
				// reuse the old ranges
				newHiddenAreas.push(this._hiddenRanges[k]);
				k++;
			} else {
				updateHiddenAreas = true;
R
rebornix 已提交
401
				newHiddenAreas.push({ start: startLineNumber - 1, end: endLineNumber - 1 });
R
rebornix 已提交
402 403 404 405 406 407 408 409
			}
			lastCollapsedStart = startLineNumber;
			lastCollapsedEnd = endLineNumber;
		}

		if (updateHiddenAreas || k < this._hiddenRanges.length) {
			this._hiddenRanges = newHiddenAreas;
		}
410 411 412 413 414 415

		this._viewCells.forEach(cell => {
			if (cell.cellKind === CellKind.Markdown) {
				cell.triggerfoldingStateChange();
			}
		});
R
rebornix 已提交
416 417 418 419
	}

	getHiddenRanges() {
		return this._hiddenRanges;
R
rebornix 已提交
420 421 422 423 424 425 426
	}

	isDirty() {
		return this._model.isDirty();
	}

	hide() {
R
rebornix 已提交
427
		this._viewCells.forEach(cell => {
R
rebornix 已提交
428
			if (cell.getText() !== '') {
429
				cell.editState = CellEditState.Preview;
R
rebornix 已提交
430 431 432 433
			}
		});
	}

R
rebornix 已提交
434 435 436 437
	getCellByHandle(handle: number) {
		return this._handleToViewCellMapping.get(handle);
	}

R
rebornix 已提交
438
	getCellIndex(cell: ICellViewModel) {
R
rebornix 已提交
439
		return this._viewCells.indexOf(cell as CellViewModel);
R
rebornix 已提交
440 441
	}

R
rebornix 已提交
442 443 444 445
	hasCell(cell: ICellViewModel) {
		return this._handleToViewCellMapping.has(cell.handle);
	}

R
rebornix 已提交
446 447 448 449 450
	getVersionId() {
		return this._model.notebook.versionId;
	}

	getTrackedRange(id: string): ICellRange | null {
451
		return this._getDecorationRange(id);
R
rebornix 已提交
452 453
	}

454
	private _getDecorationRange(decorationId: string): ICellRange | null {
R
rebornix 已提交
455 456 457 458 459 460 461 462 463
		const node = this._decorations[decorationId];
		if (!node) {
			return null;
		}
		const versionId = this.getVersionId();
		if (node.cachedVersionId !== versionId) {
			this._decorationsTree.resolveNode(node, versionId);
		}
		if (node.range === null) {
R
rebornix 已提交
464
			return { start: node.cachedAbsoluteStart - 1, end: node.cachedAbsoluteEnd - 1 };
R
rebornix 已提交
465 466
		}

R
rebornix 已提交
467
		return { start: node.range.startLineNumber - 1, end: node.range.endLineNumber - 1 };
R
rebornix 已提交
468 469 470 471 472 473 474 475 476 477
	}

	setTrackedRange(id: string | null, newRange: ICellRange | null, newStickiness: TrackedRangeStickiness): string | null {
		const node = (id ? this._decorations[id] : null);

		if (!node) {
			if (!newRange) {
				return null;
			}

R
rebornix 已提交
478
			return this._deltaCellDecorationsImpl(0, [], [{ range: new Range(newRange.start + 1, 1, newRange.end + 1, 1), options: TRACKED_RANGE_OPTIONS[newStickiness] }])[0];
R
rebornix 已提交
479 480 481 482 483 484 485 486 487 488
		}

		if (!newRange) {
			// node exists, the request is to delete => delete node
			this._decorationsTree.delete(node);
			delete this._decorations[node.id];
			return null;
		}

		this._decorationsTree.delete(node);
R
rebornix 已提交
489
		node.reset(this.getVersionId(), newRange.start, newRange.end + 1, new Range(newRange.start + 1, 1, newRange.end + 1, 1));
R
rebornix 已提交
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
		node.setOptions(TRACKED_RANGE_OPTIONS[newStickiness]);
		this._decorationsTree.insert(node);
		return node.id;
	}

	private _deltaCellDecorationsImpl(ownerId: number, oldDecorationsIds: string[], newDecorations: IModelDeltaDecoration[]): string[] {
		const versionId = this.getVersionId();

		const oldDecorationsLen = oldDecorationsIds.length;
		let oldDecorationIndex = 0;

		const newDecorationsLen = newDecorations.length;
		let newDecorationIndex = 0;

		let result = new Array<string>(newDecorationsLen);
		while (oldDecorationIndex < oldDecorationsLen || newDecorationIndex < newDecorationsLen) {

			let node: IntervalNode | null = null;

			if (oldDecorationIndex < oldDecorationsLen) {
				// (1) get ourselves an old node
				do {
					node = this._decorations[oldDecorationsIds[oldDecorationIndex++]];
				} while (!node && oldDecorationIndex < oldDecorationsLen);

				// (2) remove the node from the tree (if it exists)
				if (node) {
					this._decorationsTree.delete(node);
					// this._onDidChangeDecorations.checkAffectedAndFire(node.options);
				}
			}

			if (newDecorationIndex < newDecorationsLen) {
				// (3) create a new node if necessary
				if (!node) {
					const internalDecorationId = (++this._lastDecorationId);
					const decorationId = `${this._instanceId};${internalDecorationId}`;
					node = new IntervalNode(decorationId, 0, 0);
					this._decorations[decorationId] = node;
				}

				// (4) initialize node
				const newDecoration = newDecorations[newDecorationIndex];
				// const range = this._validateRangeRelaxedNoAllocations(newDecoration.range);
				const range = newDecoration.range;
				const options = _normalizeOptions(newDecoration.options);
				// const startOffset = this._buffer.getOffsetAt(range.startLineNumber, range.startColumn);
				// const endOffset = this._buffer.getOffsetAt(range.endLineNumber, range.endColumn);

				node.ownerId = ownerId;
				node.reset(versionId, range.startLineNumber, range.endLineNumber, Range.lift(range));
				node.setOptions(options);
				// this._onDidChangeDecorations.checkAffectedAndFire(options);

				this._decorationsTree.insert(node);

				result[newDecorationIndex] = node.id;

				newDecorationIndex++;
			} else {
				if (node) {
					delete this._decorations[node.id];
				}
			}
		}

		return result;
	}

559 560
	private _insertCellDelegate(insertIndex: number, insertCell: CellViewModel) {
		this._viewCells!.splice(insertIndex, 0, insertCell);
R
rebornix 已提交
561
		this._handleToViewCellMapping.set(insertCell.handle, insertCell);
R
rebornix 已提交
562
		this._model.insertCell(insertCell.model, insertIndex);
563 564 565 566
		this._localStore.add(insertCell);
		this._onDidChangeViewCells.fire({ synchronous: true, splices: [[insertIndex, 0, [insertCell]]] });
	}

567
	private _deleteCellDelegate(deleteIndex: number) {
R
rebornix 已提交
568
		const deleteCell = this._viewCells[deleteIndex];
569
		this._viewCells.splice(deleteIndex, 1);
R
rebornix 已提交
570 571
		this._handleToViewCellMapping.delete(deleteCell.handle);

572
		this._model.deleteCell(deleteIndex);
573 574 575
		this._onDidChangeViewCells.fire({ synchronous: true, splices: [[deleteIndex, 1, []]] });
	}

R
rebornix 已提交
576 577 578 579
	private _setSelectionsDelegate(selections: number[]) {
		this.selectionHandles = selections;
	}

R
rebornix 已提交
580 581 582 583
	createCell(index: number, source: string[], language: string, type: CellKind, synchronous: boolean) {
		const cell = this._model.notebook.createCellTextModel(source, language, type, [], undefined);
		let newCell: CellViewModel = createCellViewModel(this.instantiationService, this, cell);
		this._viewCells!.splice(index, 0, newCell);
R
rebornix 已提交
584
		this._handleToViewCellMapping.set(newCell.handle, newCell);
R
rebornix 已提交
585 586
		this._model.insertCell(cell, index);
		this._localStore.add(newCell);
R
rebornix 已提交
587

R
rebornix 已提交
588 589
		this.undoService.pushElement(new InsertCellEdit(this.uri, index, newCell, {
			insertCell: this._insertCellDelegate.bind(this),
R
rebornix 已提交
590 591 592
			deleteCell: this._deleteCellDelegate.bind(this),
			setSelections: this._setSelectionsDelegate.bind(this)
		}, this.selectionHandles, this.selectionHandles));
R
rebornix 已提交
593

R
rebornix 已提交
594
		this._decorationsTree.acceptReplace(index, 0, 1, true);
R
rebornix 已提交
595 596 597 598
		this._onDidChangeViewCells.fire({ synchronous: synchronous, splices: [[index, 0, [newCell]]] });
		return newCell;
	}

R
rebornix 已提交
599
	insertCell(index: number, cell: NotebookCellTextModel, synchronous: boolean): CellViewModel {
R
rebornix 已提交
600
		let newCell: CellViewModel = createCellViewModel(this.instantiationService, this, cell);
R
rebornix 已提交
601
		this._viewCells!.splice(index, 0, newCell);
R
rebornix 已提交
602 603
		this._handleToViewCellMapping.set(newCell.handle, newCell);

R
rebornix 已提交
604
		this._model.insertCell(newCell.model, index);
605
		this._localStore.add(newCell);
R
rebornix 已提交
606
		this.undoService.pushElement(new InsertCellEdit(this.uri, index, newCell, {
607
			insertCell: this._insertCellDelegate.bind(this),
R
rebornix 已提交
608 609 610
			deleteCell: this._deleteCellDelegate.bind(this),
			setSelections: this._setSelectionsDelegate.bind(this)
		}, this.selectionHandles, this.selectionHandles));
R
rebornix 已提交
611

R
rebornix 已提交
612
		this._decorationsTree.acceptReplace(index, 0, 1, true);
R
rebornix 已提交
613
		this._onDidChangeViewCells.fire({ synchronous: synchronous, splices: [[index, 0, [newCell]]] });
614
		return newCell;
R
rebornix 已提交
615 616
	}

R
rebornix 已提交
617
	deleteCell(index: number, synchronous: boolean) {
R
rebornix 已提交
618 619
		const primarySelectionIndex = this.selectionHandles.length ? this._viewCells.indexOf(this.getCellByHandle(this.selectionHandles[0])!) : null;

R
rebornix 已提交
620 621
		let viewCell = this._viewCells[index];
		this._viewCells.splice(index, 1);
R
rebornix 已提交
622 623
		this._handleToViewCellMapping.delete(viewCell.handle);

624
		this._model.deleteCell(index);
R
rebornix 已提交
625

R
rebornix 已提交
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
		let endSelections: number[] = [];
		if (this.selectionHandles.length) {
			const primarySelectionHandle = this.selectionHandles[0];

			if (index === primarySelectionIndex) {
				if (primarySelectionIndex < this.length - 1) {
					endSelections = [this._viewCells[primarySelectionIndex + 1].handle];
				} else if (primarySelectionIndex === this.length - 1 && this.length > 1) {
					endSelections = [this._viewCells[primarySelectionIndex - 1].handle];
				} else {
					endSelections = [];
				}
			} else {
				endSelections = [primarySelectionHandle];
			}
		}

R
rebornix 已提交
643
		this.undoService.pushElement(new DeleteCellEdit(this.uri, index, viewCell, {
644
			insertCell: this._insertCellDelegate.bind(this),
R
rebornix 已提交
645
			deleteCell: this._deleteCellDelegate.bind(this),
R
rebornix 已提交
646
			createCellViewModel: (cell: NotebookCellTextModel) => {
R
rebornix 已提交
647
				return createCellViewModel(this.instantiationService, this, cell);
R
rebornix 已提交
648 649 650
			},
			setSelections: this._setSelectionsDelegate.bind(this)
		}, this.selectionHandles, endSelections));
R
rebornix 已提交
651

R
rebornix 已提交
652
		this.selectionHandles = endSelections;
R
rebornix 已提交
653 654 655

		this._decorationsTree.acceptReplace(index, 1, 0, true);

R
rebornix 已提交
656
		this._onDidChangeViewCells.fire({ synchronous: synchronous, splices: [[index, 1, []]] });
657
		viewCell.dispose();
R
rebornix 已提交
658 659
	}

R
rebornix 已提交
660
	moveCellToIdx(index: number, newIdx: number, synchronous: boolean, pushedToUndoStack: boolean = true): boolean {
R
rebornix 已提交
661
		const viewCell = this.viewCells[index] as CellViewModel;
662 663 664 665 666 667
		if (!viewCell) {
			return false;
		}

		this.viewCells.splice(index, 1);
		this.viewCells!.splice(newIdx, 0, viewCell);
R
rebornix 已提交
668
		this._model.moveCellToIdx(index, newIdx);
669

R
rebornix 已提交
670 671 672 673
		if (pushedToUndoStack) {
			this.undoService.pushElement(new MoveCellEdit(this.uri, index, newIdx, {
				moveCell: (fromIndex: number, toIndex: number) => {
					this.moveCellToIdx(fromIndex, toIndex, true, false);
R
rebornix 已提交
674 675 676
				},
				setSelections: this._setSelectionsDelegate.bind(this)
			}, this.selectionHandles, this.selectionHandles));
R
rebornix 已提交
677 678
		}

R
rebornix 已提交
679 680
		this.selectionHandles = this.selectionHandles;

R
rebornix 已提交
681 682 683
		this._onDidChangeViewCells.fire({ synchronous: synchronous, splices: [[index, 1, []]] });
		this._onDidChangeViewCells.fire({ synchronous: synchronous, splices: [[newIdx, 0, [viewCell]]] });

684 685 686
		return true;
	}

R
rebornix 已提交
687
	geteEditorViewState(): INotebookEditorViewState {
688 689
		const editingCells: { [key: number]: boolean } = {};
		this._viewCells.filter(cell => cell.editState === CellEditState.Editing).forEach(cell => editingCells[cell.model.handle] = true);
R
rebornix 已提交
690
		const editorViewStates: { [key: number]: editorCommon.ICodeEditorViewState } = {};
R
rebornix 已提交
691
		this._viewCells.map(cell => ({ handle: cell.model.handle, state: cell.saveEditorViewState() })).forEach(viewState => {
R
rebornix 已提交
692 693 694 695 696 697
			if (viewState.state) {
				editorViewStates[viewState.handle] = viewState.state;
			}
		});

		return {
698
			editingCells,
R
rebornix 已提交
699
			editorViewStates,
R
rebornix 已提交
700 701 702 703 704 705 706 707
		};
	}

	restoreEditorViewState(viewState: INotebookEditorViewState | undefined): void {
		if (!viewState) {
			return;
		}

708
		this._viewCells.forEach((cell, index) => {
R
rebornix 已提交
709 710 711
			const isEditing = viewState.editingCells && viewState.editingCells[cell.handle];
			const editorViewState = viewState.editorViewStates && viewState.editorViewStates[cell.handle];

712
			cell.editState = isEditing ? CellEditState.Editing : CellEditState.Preview;
713 714
			const cellHeight = viewState.cellTotalHeights ? viewState.cellTotalHeights[index] : undefined;
			cell.restoreEditorViewState(editorViewState, cellHeight);
R
rebornix 已提交
715 716 717
		});
	}

R
rebornix 已提交
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
	/**
	 * Editor decorations across cells. For example, find decorations for multiple code cells
	 * The reason that we can't completely delegate this to CodeEditorWidget is most of the time, the editors for cells are not created yet but we already have decorations for them.
	 */
	changeDecorations<T>(callback: (changeAccessor: IModelDecorationsChangeAccessor) => T): T | null {
		const changeAccessor: IModelDecorationsChangeAccessor = {
			deltaDecorations: (oldDecorations: ICellModelDecorations[], newDecorations: ICellModelDeltaDecorations[]): ICellModelDecorations[] => {
				return this.deltaDecorationsImpl(oldDecorations, newDecorations);
			}
		};

		let result: T | null = null;
		try {
			result = callback(changeAccessor);
		} catch (e) {
			onUnexpectedError(e);
		}

		changeAccessor.deltaDecorations = invalidFunc;

		return result;
	}

	deltaDecorationsImpl(oldDecorations: ICellModelDecorations[], newDecorations: ICellModelDeltaDecorations[]): ICellModelDecorations[] {

R
rebornix 已提交
743
		const mapping = new Map<number, { cell: CellViewModel; oldDecorations: string[]; newDecorations: IModelDeltaDecoration[] }>();
R
rebornix 已提交
744 745 746 747
		oldDecorations.forEach(oldDecoration => {
			const ownerId = oldDecoration.ownerId;

			if (!mapping.has(ownerId)) {
R
rebornix 已提交
748
				const cell = this._viewCells.find(cell => cell.handle === ownerId);
749 750 751
				if (cell) {
					mapping.set(ownerId, { cell: cell, oldDecorations: [], newDecorations: [] });
				}
R
rebornix 已提交
752 753 754
			}

			const data = mapping.get(ownerId)!;
R
rebornix 已提交
755 756 757
			if (data) {
				data.oldDecorations = oldDecoration.decorations;
			}
R
rebornix 已提交
758 759 760 761 762 763
		});

		newDecorations.forEach(newDecoration => {
			const ownerId = newDecoration.ownerId;

			if (!mapping.has(ownerId)) {
R
rebornix 已提交
764
				const cell = this._viewCells.find(cell => cell.handle === ownerId);
765 766 767 768

				if (cell) {
					mapping.set(ownerId, { cell: cell, oldDecorations: [], newDecorations: [] });
				}
R
rebornix 已提交
769 770 771
			}

			const data = mapping.get(ownerId)!;
R
rebornix 已提交
772 773 774
			if (data) {
				data.newDecorations = newDecoration.decorations;
			}
R
rebornix 已提交
775 776 777 778 779 780 781 782 783 784 785 786 787 788
		});

		const ret: ICellModelDecorations[] = [];
		mapping.forEach((value, ownerId) => {
			const cellRet = value.cell.deltaDecorations(value.oldDecorations, value.newDecorations);
			ret.push({
				ownerId: ownerId,
				decorations: cellRet
			});
		});

		return ret;
	}

R
rebornix 已提交
789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839

	/**
	 * Search in notebook text model
	 * @param value
	 */
	find(value: string): CellFindMatch[] {
		const matches: CellFindMatch[] = [];
		this._viewCells.forEach(cell => {
			const cellMatches = cell.startFind(value);
			if (cellMatches) {
				matches.push(cellMatches);
			}
		});

		return matches;
	}

	replaceOne(cell: ICellViewModel, range: Range, text: string): Promise<void> {
		const viewCell = cell as CellViewModel;
		this._lastNotebookEditResource.push(viewCell.uri);
		return viewCell.resolveTextModel().then(() => {
			this.bulkEditService.apply({ edits: [{ edit: { range: range, text: text }, resource: cell.uri }] }, { quotableLabel: 'Notebook Replace' });
		});
	}

	async replaceAll(matches: CellFindMatch[], text: string): Promise<void> {
		if (!matches.length) {
			return;
		}

		let textEdits: WorkspaceTextEdit[] = [];
		this._lastNotebookEditResource.push(matches[0].cell.uri);

		matches.forEach(match => {
			match.matches.forEach(singleMatch => {
				textEdits.push({
					edit: { range: singleMatch.range, text: text },
					resource: match.cell.uri
				});
			});
		});

		return Promise.all(matches.map(match => {
			return match.cell.resolveTextModel();
		})).then(async () => {
			this.bulkEditService.apply({ edits: textEdits }, { quotableLabel: 'Notebook Replace All' });
			return;
		});
	}

	canUndo(): boolean {
R
rebornix 已提交
840
		return this.undoService.canUndo(this.uri);
R
rebornix 已提交
841 842 843
	}

	undo() {
R
rebornix 已提交
844 845
		this.undoService.undo(this.uri);
	}
R
rebornix 已提交
846

R
rebornix 已提交
847 848
	redo() {
		this.undoService.redo(this.uri);
R
rebornix 已提交
849 850
	}

R
rebornix 已提交
851 852 853 854 855 856 857 858
	equal(model: NotebookEditorModel) {
		return this._model === model;
	}

	dispose() {
		this._localStore.clear();
		this._viewCells.forEach(cell => {
			cell.save();
R
rebornix 已提交
859
			cell.dispose();
R
rebornix 已提交
860 861 862 863 864
		});

		super.dispose();
	}
}
R
rebornix 已提交
865 866 867

export type CellViewModel = CodeCellViewModel | MarkdownCellViewModel;

R
rebornix 已提交
868
export function createCellViewModel(instantiationService: IInstantiationService, notebookViewModel: NotebookViewModel, cell: NotebookCellTextModel) {
R
rebornix 已提交
869
	if (cell.cellKind === CellKind.Code) {
870
		return instantiationService.createInstance(CodeCellViewModel, notebookViewModel.viewType, notebookViewModel.handle, cell, notebookViewModel.layoutInfo, notebookViewModel.eventDispatcher);
R
rebornix 已提交
871
	} else {
872
		return instantiationService.createInstance(MarkdownCellViewModel, notebookViewModel.viewType, notebookViewModel.handle, cell, notebookViewModel.layoutInfo, notebookViewModel, notebookViewModel.eventDispatcher);
R
rebornix 已提交
873 874
	}
}