notebookEditorModel.ts 9.5 KB
Newer Older
1 2 3 4 5 6 7
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

import { EditorModel, IRevertOptions } from 'vs/workbench/common/editor';
import { Emitter, Event } from 'vs/base/common/event';
R
rebornix 已提交
8
import { INotebookEditorModel } from 'vs/workbench/contrib/notebook/common/notebookCommon';
9 10 11 12 13 14
import { NotebookTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookTextModel';
import { Disposable, IDisposable, dispose } from 'vs/base/common/lifecycle';
import { ResourceMap } from 'vs/base/common/map';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService';
import { URI } from 'vs/base/common/uri';
15
import { IWorkingCopyService, IWorkingCopy, IWorkingCopyBackup } from 'vs/workbench/services/workingCopy/common/workingCopyService';
16
import { basename } from 'vs/base/common/resources';
R
rebornix 已提交
17
import { CancellationTokenSource } from 'vs/base/common/cancellation';
R
rebornix 已提交
18 19
import { IBackupFileService } from 'vs/workbench/services/backup/common/backup';
import { DefaultEndOfLine, ITextBuffer, EndOfLinePreference } from 'vs/editor/common/model';
20 21 22 23 24 25 26 27 28

export interface INotebookEditorModelManager {
	models: NotebookEditorModel[];

	resolve(resource: URI, viewType: string): Promise<NotebookEditorModel>;

	get(resource: URI): NotebookEditorModel | undefined;
}

R
revert.  
rebornix 已提交
29 30 31 32 33 34 35
export interface INotebookRevertOptions {
	/**
	 * Go to disk bypassing any cache of the model if any.
	 */
	forceReadFromDisk?: boolean;
}

36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57

export class NotebookEditorModel extends EditorModel implements IWorkingCopy, INotebookEditorModel {
	private _dirty = false;
	protected readonly _onDidChangeDirty = this._register(new Emitter<void>());
	readonly onDidChangeDirty = this._onDidChangeDirty.event;
	private readonly _onDidChangeContent = this._register(new Emitter<void>());
	readonly onDidChangeContent: Event<void> = this._onDidChangeContent.event;
	private _notebook!: NotebookTextModel;

	get notebook() {
		return this._notebook;
	}

	private _name!: string;

	get name() {
		return this._name;
	}
	constructor(
		public readonly resource: URI,
		public readonly viewType: string,
		@INotebookService private readonly notebookService: INotebookService,
R
rebornix 已提交
58 59
		@IWorkingCopyService private readonly workingCopyService: IWorkingCopyService,
		@IBackupFileService private readonly backupFileService: IBackupFileService
60 61
	) {
		super();
R
rebornix 已提交
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77

		const input = this;
		const workingCopyUri = resource.with({ scheme: 'vscode-notebook' });
		const workingCopyAdapter = new class implements IWorkingCopy {
			readonly resource = workingCopyUri;
			get name() { return input.name; }
			readonly capabilities = input.capabilities;
			readonly onDidChangeDirty = input.onDidChangeDirty;
			readonly onDidChangeContent = input.onDidChangeContent;
			isDirty(): boolean { return input.isDirty(); }
			backup(): Promise<IWorkingCopyBackup> { return input.backup(); }
			save(): Promise<boolean> { return input.save(); }
			revert(options?: IRevertOptions): Promise<void> { return input.revert(options); }
		};

		this._register(this.workingCopyService.registerWorkingCopy(workingCopyAdapter));
78 79
	}

R
rebornix 已提交
80
	capabilities = 0;
81 82

	async backup(): Promise<IWorkingCopyBackup> {
R
rebornix 已提交
83
		return { content: this._notebook.createSnapshot(true) };
84 85 86
	}

	async revert(options?: IRevertOptions | undefined): Promise<void> {
R
rebornix 已提交
87 88 89 90 91
		if (options?.soft) {
			await this.backupFileService.discardBackup(this.resource);
			return;
		}

R
revert.  
rebornix 已提交
92 93 94
		await this.load({ forceReadFromDisk: true });
		this._dirty = false;
		this._onDidChangeDirty.fire();
95 96 97
		return;
	}

R
revert.  
rebornix 已提交
98 99 100 101
	async load(options?: INotebookRevertOptions): Promise<NotebookEditorModel> {
		if (options?.forceReadFromDisk) {
			return this.loadFromProvider(true);
		}
R
rebornix 已提交
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
		if (this.isResolved()) {
			return this;
		}

		const backup = await this.backupFileService.resolve(this.resource);

		if (this.isResolved()) {
			return this; // Make sure meanwhile someone else did not succeed in loading
		}

		if (backup) {
			try {
				return await this.loadFromBackup(backup.value.create(DefaultEndOfLine.LF));
			} catch (error) {
				// this.logService.error('[text file model] load() from backup', error); // ignore error and continue to load as file below
			}
		}

R
revert.  
rebornix 已提交
120
		return this.loadFromProvider(false);
R
rebornix 已提交
121 122 123 124 125 126
	}

	private async loadFromBackup(content: ITextBuffer): Promise<NotebookEditorModel> {
		const fullRange = content.getRangeAt(0, content.getLength());
		const data = JSON.parse(content.getValueInRange(fullRange, EndOfLinePreference.LF));

R
rebornix 已提交
127
		const notebook = await this.notebookService.createNotebookFromBackup(this.viewType!, this.resource, data.metadata, data.languages, data.cells);
R
rebornix 已提交
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
		this._notebook = notebook!;

		this._name = basename(this._notebook!.uri);

		this._register(this._notebook.onDidChangeContent(() => {
			this.setDirty(true);
			this._onDidChangeContent.fire();
		}));

		await this.backupFileService.discardBackup(this.resource);
		this.setDirty(true);

		return this;
	}

R
revert.  
rebornix 已提交
143 144
	private async loadFromProvider(forceReloadFromDisk: boolean) {
		const notebook = await this.notebookService.resolveNotebook(this.viewType!, this.resource, forceReloadFromDisk);
145 146 147 148
		this._notebook = notebook!;

		this._name = basename(this._notebook!.uri);

149
		this._register(this._notebook.onDidChangeContent(() => {
R
rebornix 已提交
150
			this.setDirty(true);
151 152 153
			this._onDidChangeContent.fire();
		}));

154 155 156
		return this;
	}

R
rebornix 已提交
157 158 159 160 161 162 163 164 165 166 167
	isResolved(): boolean {
		return !!this._notebook;
	}

	setDirty(newState: boolean) {
		if (this._dirty !== newState) {
			this._dirty = newState;
			this._onDidChangeDirty.fire();
		}
	}

168 169 170 171 172
	isDirty() {
		return this._dirty;
	}

	async save(): Promise<boolean> {
R
rebornix 已提交
173 174
		const tokenSource = new CancellationTokenSource();
		await this.notebookService.save(this.notebook.viewType, this.notebook.uri, tokenSource.token);
175 176 177 178
		this._dirty = false;
		this._onDidChangeDirty.fire();
		return true;
	}
R
revert.  
rebornix 已提交
179 180 181

	async saveAs(targetResource: URI): Promise<boolean> {
		const tokenSource = new CancellationTokenSource();
R
saveAs  
rebornix 已提交
182
		await this.notebookService.saveAs(this.notebook.viewType, this.notebook.uri, targetResource, tokenSource.token);
R
revert.  
rebornix 已提交
183 184 185 186
		this._dirty = false;
		this._onDidChangeDirty.fire();
		return true;
	}
187 188 189 190 191 192 193 194 195 196 197 198
}

export class NotebookEditorModelManager extends Disposable implements INotebookEditorModelManager {

	private readonly mapResourceToModel = new ResourceMap<NotebookEditorModel>();
	private readonly mapResourceToModelListeners = new ResourceMap<IDisposable>();
	private readonly mapResourceToDisposeListener = new ResourceMap<IDisposable>();
	private readonly mapResourceToPendingModelLoaders = new ResourceMap<Promise<NotebookEditorModel>>();

	// private readonly modelLoadQueue = this._register(new ResourceQueue());

	get models(): NotebookEditorModel[] {
199
		return [...this.mapResourceToModel.values()];
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
	}
	constructor(
		@IInstantiationService readonly instantiationService: IInstantiationService
	) {
		super();
	}

	async resolve(resource: URI, viewType: string): Promise<NotebookEditorModel> {
		// Return early if model is currently being loaded
		const pendingLoad = this.mapResourceToPendingModelLoaders.get(resource);
		if (pendingLoad) {
			return pendingLoad;
		}

		let modelPromise: Promise<NotebookEditorModel>;
		let model = this.get(resource);
		// let didCreateModel = false;

		// Model exists
		if (model) {
			// if (options?.reload) {
			// } else {
			modelPromise = Promise.resolve(model);
			// }
		}

		// Model does not exist
		else {
			// didCreateModel = true;
			const newModel = model = this.instantiationService.createInstance(NotebookEditorModel, resource, viewType);
			modelPromise = model.load();

			this.registerModel(newModel);
		}

		// Store pending loads to avoid race conditions
		this.mapResourceToPendingModelLoaders.set(resource, modelPromise);

		// Make known to manager (if not already known)
		this.add(resource, model);

		// dispose and bind new listeners

		try {
			const resolvedModel = await modelPromise;

			// Remove from pending loads
			this.mapResourceToPendingModelLoaders.delete(resource);
			return resolvedModel;
		} catch (error) {
			// Free resources of this invalid model
			if (model) {
				model.dispose();
			}

			// Remove from pending loads
			this.mapResourceToPendingModelLoaders.delete(resource);

			throw error;
		}
	}

	add(resource: URI, model: NotebookEditorModel): void {
		const knownModel = this.mapResourceToModel.get(resource);
		if (knownModel === model) {
			return; // already cached
		}

		// dispose any previously stored dispose listener for this resource
		const disposeListener = this.mapResourceToDisposeListener.get(resource);
		if (disposeListener) {
			disposeListener.dispose();
		}

		// store in cache but remove when model gets disposed
		this.mapResourceToModel.set(resource, model);
		this.mapResourceToDisposeListener.set(resource, model.onDispose(() => this.remove(resource)));
	}

	remove(resource: URI): void {
		this.mapResourceToModel.delete(resource);

		const disposeListener = this.mapResourceToDisposeListener.get(resource);
		if (disposeListener) {
			dispose(disposeListener);
			this.mapResourceToDisposeListener.delete(resource);
		}

		const modelListener = this.mapResourceToModelListeners.get(resource);
		if (modelListener) {
			dispose(modelListener);
			this.mapResourceToModelListeners.delete(resource);
		}
	}


	private registerModel(model: NotebookEditorModel): void {

	}

	get(resource: URI): NotebookEditorModel | undefined {
		return this.mapResourceToModel.get(resource);
	}
}