mainThreadWebview.ts 30.3 KB
Newer Older
A
Alex Dima 已提交
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.
 *--------------------------------------------------------------------------------------------*/

6
import { CancelablePromise, createCancelablePromise } from 'vs/base/common/async';
7
import { CancellationToken } from 'vs/base/common/cancellation';
8
import { onUnexpectedError } from 'vs/base/common/errors';
9
import { Emitter, Event } from 'vs/base/common/event';
10
import { Disposable, DisposableStore, dispose, IDisposable, IReference } from 'vs/base/common/lifecycle';
11
import { Schemas } from 'vs/base/common/network';
12
import { basename } from 'vs/base/common/path';
13
import { isWeb } from 'vs/base/common/platform';
14
import { isEqual, isEqualOrParent } from 'vs/base/common/resources';
M
Matt Bierner 已提交
15
import { escape } from 'vs/base/common/strings';
16
import { URI, UriComponents } from 'vs/base/common/uri';
A
Alex Dima 已提交
17
import * as modes from 'vs/editor/common/modes';
18
import { localize } from 'vs/nls';
A
Alex Dima 已提交
19
import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions';
20
import { IFileService } from 'vs/platform/files/common/files';
21 22
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ILabelService } from 'vs/platform/label/common/label';
23
import { IOpenerService } from 'vs/platform/opener/common/opener';
24
import { IProductService } from 'vs/platform/product/common/productService';
25
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
26
import { IUndoRedoService, UndoRedoElementType } from 'vs/platform/undoRedo/common/undoRedo';
27
import * as extHostProtocol from 'vs/workbench/api/common/extHost.protocol';
28
import { editorGroupToViewColumn, EditorViewColumn, viewColumnToEditorGroup } from 'vs/workbench/api/common/shared/editor';
29
import { IEditorInput, IRevertOptions, ISaveOptions } from 'vs/workbench/common/editor';
30
import { DiffEditorInput } from 'vs/workbench/common/editor/diffEditorInput';
31
import { CustomEditorInput } from 'vs/workbench/contrib/customEditor/browser/customEditorInput';
32
import { CustomDocumentBackupData } from 'vs/workbench/contrib/customEditor/browser/customEditorInputFactory';
33
import { ICustomEditorModel, ICustomEditorService } from 'vs/workbench/contrib/customEditor/common/customEditor';
34
import { CustomTextEditorModel } from 'vs/workbench/contrib/customEditor/common/customTextEditorModel';
M
Matt Bierner 已提交
35
import { WebviewExtensionDescription, WebviewIcons } from 'vs/workbench/contrib/webview/browser/webview';
36
import { WebviewInput } from 'vs/workbench/contrib/webview/browser/webviewEditorInput';
37
import { ICreateWebViewShowOptions, IWebviewWorkbenchService, WebviewInputOptions } from 'vs/workbench/contrib/webview/browser/webviewWorkbenchService';
38
import { IBackupFileService } from 'vs/workbench/services/backup/common/backup';
39
import { IEditorGroup, IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
40
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
41
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
42
import { IWorkingCopyFileService } from 'vs/workbench/services/workingCopy/common/workingCopyFileService';
43
import { IWorkingCopy, IWorkingCopyBackup, IWorkingCopyService, WorkingCopyCapabilities } from 'vs/workbench/services/workingCopy/common/workingCopyService';
A
Alex Dima 已提交
44 45
import { extHostNamedCustomer } from '../common/extHostCustomers';

46 47 48
/**
 * Bi-directional map between webview handles and inputs.
 */
49
class WebviewInputStore {
50 51
	private readonly _handlesToInputs = new Map<string, WebviewInput>();
	private readonly _inputsToHandles = new Map<WebviewInput, string>();
52

53
	public add(handle: string, input: WebviewInput): void {
54 55 56 57
		this._handlesToInputs.set(handle, input);
		this._inputsToHandles.set(input, handle);
	}

58
	public getHandleForInput(input: WebviewInput): string | undefined {
59 60 61
		return this._inputsToHandles.get(input);
	}

62
	public getInputForHandle(handle: string): WebviewInput | undefined {
63 64 65 66 67 68 69 70 71 72 73 74 75 76
		return this._handlesToInputs.get(handle);
	}

	public delete(handle: string): void {
		const input = this.getInputForHandle(handle);
		this._handlesToInputs.delete(handle);
		if (input) {
			this._inputsToHandles.delete(input);
		}
	}

	public get size(): number {
		return this._handlesToInputs.size;
	}
77 78 79 80

	[Symbol.iterator](): Iterator<WebviewInput> {
		return this._handlesToInputs.values();
	}
81 82
}

M
Matt Bierner 已提交
83 84 85 86
class WebviewViewTypeTransformer {
	public constructor(
		public readonly prefix: string,
	) { }
M
Matt Bierner 已提交
87

M
Matt Bierner 已提交
88 89
	public fromExternal(viewType: string): string {
		return this.prefix + viewType;
M
Matt Bierner 已提交
90 91
	}

M
Matt Bierner 已提交
92
	public toExternal(viewType: string): string | undefined {
M
Matt Bierner 已提交
93
		return viewType.startsWith(this.prefix)
M
Matt Bierner 已提交
94
			? viewType.substr(this.prefix.length)
M
Matt Bierner 已提交
95 96 97 98
			: undefined;
	}
}

99 100 101 102 103
const enum ModelType {
	Custom,
	Text,
}

M
Matt Bierner 已提交
104 105
const webviewPanelViewType = new WebviewViewTypeTransformer('mainThreadWebview-');

106 107
@extHostNamedCustomer(extHostProtocol.MainContext.MainThreadWebviews)
export class MainThreadWebviews extends Disposable implements extHostProtocol.MainThreadWebviewsShape {
108 109

	private static readonly standardSupportedLinkSchemes = new Set([
M
Matt Bierner 已提交
110 111 112 113
		Schemas.http,
		Schemas.https,
		Schemas.mailto,
		Schemas.vscode,
114 115 116
		'vscode-insider',
	]);

117
	private readonly _proxy: extHostProtocol.ExtHostWebviewsShape;
118
	private readonly _webviewInputs = new WebviewInputStore();
119
	private readonly _revivers = new Map<string, IDisposable>();
120
	private readonly _editorProviders = new Map<string, IDisposable>();
J
Jean Pierre 已提交
121
	private readonly _webviewFromDiffEditorHandles = new Set<string>();
122 123

	constructor(
124
		context: extHostProtocol.IExtHostContext,
125
		@IExtensionService extensionService: IExtensionService,
126 127
		@IWorkingCopyService workingCopyService: IWorkingCopyService,
		@IWorkingCopyFileService workingCopyFileService: IWorkingCopyFileService,
128
		@ICustomEditorService private readonly _customEditorService: ICustomEditorService,
129 130 131 132
		@IEditorGroupsService private readonly _editorGroupService: IEditorGroupsService,
		@IEditorService private readonly _editorService: IEditorService,
		@IOpenerService private readonly _openerService: IOpenerService,
		@IProductService private readonly _productService: IProductService,
133 134
		@ITelemetryService private readonly _telemetryService: ITelemetryService,
		@IWebviewWorkbenchService private readonly _webviewWorkbenchService: IWebviewWorkbenchService,
135
		@IInstantiationService private readonly _instantiationService: IInstantiationService,
136 137 138
	) {
		super();

139
		this._proxy = context.getProxy(extHostProtocol.ExtHostContext.ExtHostWebviews);
M
Matt Bierner 已提交
140

J
Jean Pierre 已提交
141
		this._register(_editorService.onDidActiveEditorChange(() => {
M
Matt Bierner 已提交
142
			const activeInput = this._editorService.activeEditor;
J
Jean Pierre 已提交
143 144 145 146 147 148
			if (activeInput instanceof DiffEditorInput && activeInput.master instanceof WebviewInput && activeInput.details instanceof WebviewInput) {
				this.registerWebviewFromDiffEditorListeners(activeInput);
			}

			this.updateWebviewViewStates(activeInput);
		}));
M
Matt Bierner 已提交
149 150 151 152

		this._register(_editorService.onDidVisibleEditorsChange(() => {
			this.updateWebviewViewStates(this._editorService.activeEditor);
		}));
153

154
		// This reviver's only job is to activate webview panel extensions
155
		// This should trigger the real reviver to be registered from the extension host side.
156
		this._register(_webviewWorkbenchService.registerResolver({
157
			canResolve: (webview: WebviewInput) => {
158
				if (webview instanceof CustomEditorInput) {
159
					extensionService.activateByEvent(`onCustomEditor:${webview.viewType}`);
M
Matt Bierner 已提交
160 161 162
					return false;
				}

M
Matt Bierner 已提交
163
				const viewType = webviewPanelViewType.toExternal(webview.viewType);
M
Matt Bierner 已提交
164
				if (typeof viewType === 'string') {
165 166 167 168
					extensionService.activateByEvent(`onWebviewPanel:${viewType}`);
				}
				return false;
			},
169
			resolveWebview: () => { throw new Error('not implemented'); }
170
		}));
171 172 173 174 175 176 177 178 179 180 181 182 183 184

		workingCopyFileService.registerWorkingCopyProvider((editorResource) => {
			const matchedWorkingCopies: IWorkingCopy[] = [];

			for (const workingCopy of workingCopyService.workingCopies) {
				if (workingCopy instanceof MainThreadCustomEditorModel) {
					if (isEqualOrParent(editorResource, workingCopy.editorResource)) {
						matchedWorkingCopies.push(workingCopy);
					}
				}
			}
			return matchedWorkingCopies;

		});
185 186 187
	}

	public $createWebviewPanel(
188 189
		extensionData: extHostProtocol.WebviewExtensionDescription,
		handle: extHostProtocol.WebviewPanelHandle,
190 191
		viewType: string,
		title: string,
M
Matt Bierner 已提交
192
		showOptions: { viewColumn?: EditorViewColumn, preserveFocus?: boolean; },
193
		options: WebviewInputOptions
194 195 196 197 198 199 200
	): void {
		const mainThreadShowOptions: ICreateWebViewShowOptions = Object.create(null);
		if (showOptions) {
			mainThreadShowOptions.preserveFocus = !!showOptions.preserveFocus;
			mainThreadShowOptions.group = viewColumnToEditorGroup(this._editorGroupService, showOptions.viewColumn);
		}

201
		const extension = reviveWebviewExtension(extensionData);
202
		const webview = this._webviewWorkbenchService.createWebview(handle, webviewPanelViewType.fromExternal(viewType), title, mainThreadShowOptions, reviveWebviewOptions(options), extension);
203
		this.hookupWebviewEventDelegate(handle, webview);
204

205
		this._webviewInputs.add(handle, webview);
206 207 208 209 210 211

		/* __GDPR__
			"webviews:createWebviewPanel" : {
				"extensionId" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
			}
		*/
212
		this._telemetryService.publicLog('webviews:createWebviewPanel', { extensionId: extension.id.value });
213 214
	}

215
	public $disposeWebview(handle: extHostProtocol.WebviewPanelHandle): void {
216
		const webview = this.getWebviewInput(handle);
217 218 219
		webview.dispose();
	}

220
	public $setTitle(handle: extHostProtocol.WebviewPanelHandle, value: string): void {
221
		const webview = this.getWebviewInput(handle);
222 223 224
		webview.setName(value);
	}

225
	public $setIconPath(handle: extHostProtocol.WebviewPanelHandle, value: { light: UriComponents, dark: UriComponents; } | undefined): void {
226
		const webview = this.getWebviewInput(handle);
227 228 229
		webview.iconPath = reviveWebviewIcon(value);
	}

230
	public $setHtml(handle: extHostProtocol.WebviewPanelHandle, value: string): void {
231
		const webview = this.getWebviewInput(handle);
232
		webview.webview.html = value;
233 234
	}

235
	public $setOptions(handle: extHostProtocol.WebviewPanelHandle, options: modes.IWebviewOptions): void {
236
		const webview = this.getWebviewInput(handle);
M
Matt Bierner 已提交
237
		webview.webview.contentOptions = reviveWebviewOptions(options);
238 239
	}

240
	public $reveal(handle: extHostProtocol.WebviewPanelHandle, showOptions: extHostProtocol.WebviewPanelShowOptions): void {
241
		const webview = this.getWebviewInput(handle);
242 243 244 245 246 247
		if (webview.isDisposed()) {
			return;
		}

		const targetGroup = this._editorGroupService.getGroup(viewColumnToEditorGroup(this._editorGroupService, showOptions.viewColumn)) || this._editorGroupService.getGroup(webview.group || 0);
		if (targetGroup) {
248
			this._webviewWorkbenchService.revealWebview(webview, targetGroup, !!showOptions.preserveFocus);
249 250 251
		}
	}

252
	public async $postMessage(handle: extHostProtocol.WebviewPanelHandle, message: any): Promise<boolean> {
253
		const webview = this.getWebviewInput(handle);
254
		webview.webview.sendMessage(message);
255
		return true;
A
Alex Dima 已提交
256
	}
257 258 259 260 261 262

	public $registerSerializer(viewType: string): void {
		if (this._revivers.has(viewType)) {
			throw new Error(`Reviver for ${viewType} already registered`);
		}

263
		this._revivers.set(viewType, this._webviewWorkbenchService.registerResolver({
264 265
			canResolve: (webviewInput) => {
				return webviewInput.viewType === webviewPanelViewType.fromExternal(viewType);
266
			},
267 268
			resolveWebview: async (webviewInput): Promise<void> => {
				const viewType = webviewPanelViewType.toExternal(webviewInput.viewType);
M
Matt Bierner 已提交
269
				if (!viewType) {
270
					webviewInput.webview.html = MainThreadWebviews.getDeserializationFailedContents(webviewInput.viewType);
M
Matt Bierner 已提交
271 272 273
					return;
				}

274 275 276
				const handle = webviewInput.id;
				this._webviewInputs.add(handle, webviewInput);
				this.hookupWebviewEventDelegate(handle, webviewInput);
277

278
				let state = undefined;
279
				if (webviewInput.webview.state) {
280
					try {
281
						state = JSON.parse(webviewInput.webview.state);
282 283 284 285 286 287
					} catch {
						// noop
					}
				}

				try {
288
					await this._proxy.$deserializeWebviewPanel(handle, viewType, webviewInput.getTitle(), state, editorGroupToViewColumn(this._editorGroupService, webviewInput.group || 0), webviewInput.webview.options);
289 290
				} catch (error) {
					onUnexpectedError(error);
291
					webviewInput.webview.html = MainThreadWebviews.getDeserializationFailedContents(viewType);
292 293 294
				}
			}
		}));
A
Alex Dima 已提交
295
	}
296 297 298 299 300 301 302 303 304

	public $unregisterSerializer(viewType: string): void {
		const reviver = this._revivers.get(viewType);
		if (!reviver) {
			throw new Error(`No reviver for ${viewType} registered`);
		}

		reviver.dispose();
		this._revivers.delete(viewType);
A
Alex Dima 已提交
305
	}
306

307 308
	public $registerTextEditorProvider(extensionData: extHostProtocol.WebviewExtensionDescription, viewType: string, options: modes.IWebviewPanelOptions, capabilities: extHostProtocol.CustomTextEditorCapabilities): void {
		this.registerEditorProvider(ModelType.Text, extensionData, viewType, options, capabilities);
309 310 311
	}

	public $registerCustomEditorProvider(extensionData: extHostProtocol.WebviewExtensionDescription, viewType: string, options: modes.IWebviewPanelOptions): void {
312
		this.registerEditorProvider(ModelType.Custom, extensionData, viewType, options, {});
313 314
	}

315
	private registerEditorProvider(
316 317 318 319
		modelType: ModelType,
		extensionData: extHostProtocol.WebviewExtensionDescription,
		viewType: string,
		options: modes.IWebviewPanelOptions,
320 321
		capabilities: extHostProtocol.CustomTextEditorCapabilities,
	): DisposableStore {
322 323 324 325
		if (this._editorProviders.has(viewType)) {
			throw new Error(`Provider for ${viewType} already registered`);
		}

326
		const extension = reviveWebviewExtension(extensionData);
M
Matt Bierner 已提交
327

328 329
		const disposables = new DisposableStore();
		disposables.add(this._webviewWorkbenchService.registerResolver({
330
			canResolve: (webviewInput) => {
331
				return webviewInput instanceof CustomEditorInput && webviewInput.viewType === viewType;
332
			},
333
			resolveWebview: async (webviewInput: CustomEditorInput, cancellation: CancellationToken) => {
334
				const handle = webviewInput.id;
335
				const resource = webviewInput.resource;
336

337
				this._webviewInputs.add(handle, webviewInput);
338
				this.hookupWebviewEventDelegate(handle, webviewInput);
339
				webviewInput.webview.options = options;
340
				webviewInput.webview.extension = extension;
341

342 343 344 345 346
				let modelRef = await this.getOrCreateCustomEditorModel(modelType, resource, viewType, cancellation);
				if (cancellation.isCancellationRequested) {
					modelRef.dispose();
					return;
				}
M
Matt Bierner 已提交
347

348
				webviewInput.webview.onDispose(() => {
349 350
					modelRef.dispose();
				});
351

352 353 354
				if (capabilities.supportsMove) {
					webviewInput.onMove(async (newResource: URI) => {
						const oldModel = modelRef;
355
						modelRef = await this.getOrCreateCustomEditorModel(modelType, newResource, viewType, CancellationToken.None);
356 357 358 359 360
						this._proxy.$onMoveCustomEditor(handle, newResource, viewType);
						oldModel.dispose();
					});
				}

361
				try {
362
					await this._proxy.$resolveWebviewEditor(resource, handle, viewType, webviewInput.getTitle(), editorGroupToViewColumn(this._editorGroupService, webviewInput.group || 0), webviewInput.webview.options, cancellation);
363 364
				} catch (error) {
					onUnexpectedError(error);
365
					webviewInput.webview.html = MainThreadWebviews.getDeserializationFailedContents(viewType);
M
Matt Bierner 已提交
366
					return;
367 368 369
				}
			}
		}));
370 371 372 373

		this._editorProviders.set(viewType, disposables);

		return disposables;
374 375 376 377 378 379 380 381 382 383
	}

	public $unregisterEditorProvider(viewType: string): void {
		const provider = this._editorProviders.get(viewType);
		if (!provider) {
			throw new Error(`No provider for ${viewType} registered`);
		}

		provider.dispose();
		this._editorProviders.delete(viewType);
384 385

		this._customEditorService.models.disposeAllModelsForView(viewType);
386 387
	}

388 389 390 391
	private async getOrCreateCustomEditorModel(
		modelType: ModelType,
		resource: URI,
		viewType: string,
392
		cancellation: CancellationToken,
393
	): Promise<IReference<ICustomEditorModel>> {
394
		const existingModel = this._customEditorService.models.tryRetain(resource, viewType);
395 396
		if (existingModel) {
			return existingModel;
397
		}
398

399 400
		const model = modelType === ModelType.Text
			? CustomTextEditorModel.create(this._instantiationService, viewType, resource)
401 402 403 404
			: MainThreadCustomEditorModel.create(this._instantiationService, this._proxy, viewType, resource, () => {
				return Array.from(this._webviewInputs)
					.filter(editor => editor instanceof CustomEditorInput && isEqual(editor.resource, resource)) as CustomEditorInput[];
			}, cancellation);
405

406
		return this._customEditorService.models.add(resource, viewType, model);
407 408
	}

409
	public async $onDidEdit(resourceComponents: UriComponents, viewType: string, editId: number, label: string | undefined): Promise<void> {
410 411
		const resource = URI.revive(resourceComponents);
		const model = await this._customEditorService.models.get(resource, viewType);
412
		if (!model || !(model instanceof MainThreadCustomEditorModel)) {
413 414
			throw new Error('Could not find model for webview editor');
		}
415

416
		model.pushEdit(editId, label);
417 418
	}

419
	private hookupWebviewEventDelegate(handle: extHostProtocol.WebviewPanelHandle, input: WebviewInput) {
420 421
		const disposables = new DisposableStore();

422
		disposables.add(input.webview.onDidClickLink((uri) => this.onDidClickLink(handle, uri)));
423 424 425
		disposables.add(input.webview.onMessage((message: any) => { this._proxy.$onMessage(handle, message); }));
		disposables.add(input.webview.onMissingCsp((extension: ExtensionIdentifier) => this._proxy.$onMissingCsp(handle, extension.value)));

426
		disposables.add(input.webview.onDispose(() => {
427
			disposables.dispose();
428

429 430 431
			this._proxy.$onDidDisposeWebviewPanel(handle).finally(() => {
				this._webviewInputs.delete(handle);
			});
432
		}));
A
Alex Dima 已提交
433
	}
434

J
Jean Pierre 已提交
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
	private registerWebviewFromDiffEditorListeners(diffEditorInput: DiffEditorInput): void {
		const master = diffEditorInput.master as WebviewInput;
		const details = diffEditorInput.details as WebviewInput;

		if (this._webviewFromDiffEditorHandles.has(master.id) || this._webviewFromDiffEditorHandles.has(details.id)) {
			return;
		}

		this._webviewFromDiffEditorHandles.add(master.id);
		this._webviewFromDiffEditorHandles.add(details.id);

		const disposables = new DisposableStore();
		disposables.add(master.webview.onDidFocus(() => this.updateWebviewViewStates(master)));
		disposables.add(details.webview.onDidFocus(() => this.updateWebviewViewStates(details)));
		disposables.add(diffEditorInput.onDispose(() => {
			this._webviewFromDiffEditorHandles.delete(master.id);
			this._webviewFromDiffEditorHandles.delete(details.id);
			dispose(disposables);
		}));
	}

	private updateWebviewViewStates(activeEditorInput: IEditorInput | undefined) {
457
		if (!this._webviewInputs.size) {
458 459
			return;
		}
460

461
		const viewStates: extHostProtocol.WebviewPanelViewStateData = {};
462

463 464 465 466 467 468 469
		const updateViewStatesForInput = (group: IEditorGroup, topLevelInput: IEditorInput, editorInput: IEditorInput) => {
			if (!(editorInput instanceof WebviewInput)) {
				return;
			}

			editorInput.updateGroup(group.id);

470
			const handle = this._webviewInputs.getHandleForInput(editorInput);
471 472
			if (handle) {
				viewStates[handle] = {
473
					visible: topLevelInput === group.activeEditor,
J
Jean Pierre 已提交
474
					active: editorInput === activeEditorInput,
475 476 477 478
					position: editorGroupToViewColumn(this._editorGroupService, group.id),
				};
			}
		};
479

480 481 482 483 484 485 486
		for (const group of this._editorGroupService.groups) {
			for (const input of group.editors) {
				if (input instanceof DiffEditorInput) {
					updateViewStatesForInput(group, input, input.master);
					updateViewStatesForInput(group, input, input.details);
				} else {
					updateViewStatesForInput(group, input, input);
487 488
				}
			}
489
		}
490 491 492 493

		if (Object.keys(viewStates).length) {
			this._proxy.$onDidChangeWebviewPanelViewStates(viewStates);
		}
494 495
	}

496
	private onDidClickLink(handle: extHostProtocol.WebviewPanelHandle, link: string): void {
497
		const webview = this.getWebviewInput(handle);
498
		if (this.isSupportedLink(webview, URI.parse(link))) {
499
			this._openerService.open(link, { fromUserGesture: true });
500 501 502
		}
	}

503
	private isSupportedLink(webview: WebviewInput, link: URI): boolean {
504 505 506
		if (MainThreadWebviews.standardSupportedLinkSchemes.has(link.scheme)) {
			return true;
		}
507
		if (!isWeb && this._productService.urlProtocol === link.scheme) {
508 509
			return true;
		}
M
Matt Bierner 已提交
510
		return !!webview.webview.contentOptions.enableCommandUris && link.scheme === Schemas.command;
A
Alex Dima 已提交
511
	}
512

513
	private getWebviewInput(handle: extHostProtocol.WebviewPanelHandle): WebviewInput {
514
		const webview = this.tryGetWebviewInput(handle);
515
		if (!webview) {
M
Matt Bierner 已提交
516
			throw new Error(`Unknown webview handle:${handle}`);
517 518 519 520
		}
		return webview;
	}

521
	private tryGetWebviewInput(handle: extHostProtocol.WebviewPanelHandle): WebviewInput | undefined {
522
		return this._webviewInputs.getInputForHandle(handle);
523 524
	}

525 526 527 528 529
	private static getDeserializationFailedContents(viewType: string) {
		return `<!DOCTYPE html>
		<html>
			<head>
				<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
530
				<meta http-equiv="Content-Security-Policy" content="default-src 'none';">
531
			</head>
M
Matt Bierner 已提交
532
			<body>${localize('errorMessage', "An error occurred while restoring view:{0}", escape(viewType))}</body>
533
		</html>`;
A
Alex Dima 已提交
534
	}
535 536
}

537 538
function reviveWebviewExtension(extensionData: extHostProtocol.WebviewExtensionDescription): WebviewExtensionDescription {
	return { id: extensionData.id, location: URI.revive(extensionData.location) };
M
Matt Bierner 已提交
539 540
}

541
function reviveWebviewOptions(options: modes.IWebviewOptions): WebviewInputOptions {
542 543
	return {
		...options,
544
		allowScripts: options.enableScripts,
545 546 547 548 549
		localResourceRoots: Array.isArray(options.localResourceRoots) ? options.localResourceRoots.map(r => URI.revive(r)) : undefined,
	};
}

function reviveWebviewIcon(
M
Matt Bierner 已提交
550
	value: { light: UriComponents, dark: UriComponents; } | undefined
M
Matt Bierner 已提交
551 552 553 554
): WebviewIcons | undefined {
	return value
		? { light: URI.revive(value.light), dark: URI.revive(value.dark) }
		: undefined;
A
Alex Dima 已提交
555
}
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577

namespace HotExitState {
	export const enum Type {
		Allowed,
		NotAllowed,
		Pending,
	}

	export const Allowed = Object.freeze({ type: Type.Allowed } as const);
	export const NotAllowed = Object.freeze({ type: Type.NotAllowed } as const);

	export class Pending {
		readonly type = Type.Pending;

		constructor(
			public readonly operation: CancelablePromise<void>,
		) { }
	}

	export type State = typeof Allowed | typeof NotAllowed | Pending;
}

578

579 580 581
class MainThreadCustomEditorModel extends Disposable implements ICustomEditorModel, IWorkingCopy {

	private _hotExitState: HotExitState.State = HotExitState.Allowed;
582 583 584
	private _currentEditIndex: number = -1;
	private _savePoint: number = -1;
	private readonly _edits: Array<number> = [];
585
	private _fromBackup: boolean = false;
586

M
Matt Bierner 已提交
587 588 589 590
	public static async create(
		instantiationService: IInstantiationService,
		proxy: extHostProtocol.ExtHostWebviewsShape,
		viewType: string,
591
		resource: URI,
592
		getEditors: () => CustomEditorInput[],
593
		cancellation: CancellationToken,
M
Matt Bierner 已提交
594
	) {
595
		const { editable } = await proxy.$createWebviewCustomEditorDocument(resource, viewType, cancellation);
596 597 598
		const model = instantiationService.createInstance(MainThreadCustomEditorModel, proxy, viewType, resource, editable, getEditors);
		await model.init();
		return model;
599 600 601 602
	}

	constructor(
		private readonly _proxy: extHostProtocol.ExtHostWebviewsShape,
M
Matt Bierner 已提交
603
		private readonly _viewType: string,
604
		private readonly _editorResource: URI,
605
		private readonly _editable: boolean,
606
		private readonly _getEditors: () => CustomEditorInput[],
607 608 609
		@IWorkingCopyService workingCopyService: IWorkingCopyService,
		@ILabelService private readonly _labelService: ILabelService,
		@IFileService private readonly _fileService: IFileService,
610
		@IUndoRedoService private readonly _undoService: IUndoRedoService,
611
		@IBackupFileService private readonly _backupFileService: IBackupFileService,
612 613
	) {
		super();
614

615 616 617
		if (_editable) {
			this._register(workingCopyService.registerWorkingCopy(this));
		}
618 619
	}

620 621 622 623
	get editorResource() {
		return this._editorResource;
	}

624 625 626 627 628
	async init(): Promise<void> {
		const backup = await this._backupFileService.resolve<CustomDocumentBackupData>(this.resource);
		this._fromBackup = !!backup;
	}

629
	dispose() {
630
		if (this._editable) {
631
			this._undoService.removeElements(this._editorResource);
632
		}
633
		this._proxy.$disposeWebviewCustomEditorDocument(this._editorResource, this._viewType);
634 635 636 637 638
		super.dispose();
	}

	//#region IWorkingCopy

639 640 641
	public get resource() {
		// Make sure each custom editor has a unique resource for backup and edits
		return URI.from({
642
			scheme: Schemas.vscodeCustomEditor,
643
			authority: this._viewType,
644 645
			path: this._editorResource.path,
			query: JSON.stringify(this._editorResource.toJSON()),
646 647
		});
	}
648 649

	public get name() {
650
		return basename(this._labelService.getUriLabel(this._editorResource));
651 652 653 654 655 656 657
	}

	public get capabilities(): WorkingCopyCapabilities {
		return 0;
	}

	public isDirty(): boolean {
658 659 660 661
		if (this._edits.length > 0) {
			return this._savePoint !== this._currentEditIndex;
		}
		return this._fromBackup;
662 663 664 665 666 667 668 669 670
	}

	private readonly _onDidChangeDirty: Emitter<void> = this._register(new Emitter<void>());
	readonly onDidChangeDirty: Event<void> = this._onDidChangeDirty.event;

	private readonly _onDidChangeContent: Emitter<void> = this._register(new Emitter<void>());
	readonly onDidChangeContent: Event<void> = this._onDidChangeContent.event;

	//#endregion
M
Matt Bierner 已提交
671

672 673 674 675
	public isReadonly() {
		return this._editable;
	}

M
Matt Bierner 已提交
676 677 678 679
	public get viewType() {
		return this._viewType;
	}

680
	public pushEdit(editId: number, label: string | undefined) {
681 682 683 684 685 686 687 688 689 690 691
		if (!this._editable) {
			throw new Error('Document is not editable');
		}

		this.change(() => {
			this.spliceEdits(editId);
			this._currentEditIndex = this._edits.length - 1;
		});

		this._undoService.pushElement({
			type: UndoRedoElementType.Resource,
692
			resource: this._editorResource,
693
			label: label ?? localize('defaultEditLabel', "Edit"),
M
Matt Bierner 已提交
694 695 696 697
			undo: () => this.undo(),
			redo: () => this.redo(),
		});
	}
698

M
Matt Bierner 已提交
699 700 701 702
	private async undo(): Promise<void> {
		if (!this._editable) {
			return;
		}
703

M
Matt Bierner 已提交
704 705 706 707
		if (this._currentEditIndex < 0) {
			// nothing to undo
			return;
		}
708

M
Matt Bierner 已提交
709 710 711 712
		const undoneEdit = this._edits[this._currentEditIndex];
		this.change(() => {
			--this._currentEditIndex;
		});
713
		await this._proxy.$undo(this._editorResource, this.viewType, undoneEdit, this.getEditState());
M
Matt Bierner 已提交
714
	}
715

M
Matt Bierner 已提交
716 717 718 719 720 721 722 723
	private getEditState(): extHostProtocol.CustomDocumentEditState {
		return {
			allEdits: this._edits,
			currentIndex: this._currentEditIndex,
			saveIndex: this._savePoint,
		};
	}

M
Matt Bierner 已提交
724 725 726 727 728 729 730 731 732 733 734 735 736
	private async redo(): Promise<void> {
		if (!this._editable) {
			return;
		}

		if (this._currentEditIndex >= this._edits.length - 1) {
			// nothing to redo
			return;
		}

		const redoneEdit = this._edits[this._currentEditIndex + 1];
		this.change(() => {
			++this._currentEditIndex;
737
		});
738
		await this._proxy.$redo(this._editorResource, this.viewType, redoneEdit, this.getEditState());
739 740 741 742 743 744 745 746 747 748 749
	}

	private spliceEdits(editToInsert?: number) {
		const start = this._currentEditIndex + 1;
		const toRemove = this._edits.length - this._currentEditIndex;

		const removedEdits = typeof editToInsert === 'number'
			? this._edits.splice(start, toRemove, editToInsert)
			: this._edits.splice(start, toRemove);

		if (removedEdits.length) {
750
			this._proxy.$disposeEdits(this._editorResource, this._viewType, removedEdits);
751 752 753 754 755 756
		}
	}

	private change(makeEdit: () => void): void {
		const wasDirty = this.isDirty();
		makeEdit();
757 758
		this._onDidChangeContent.fire();

759
		if (this.isDirty() !== wasDirty) {
760 761 762 763 764
			this._onDidChangeDirty.fire();
		}
	}

	public async revert(_options?: IRevertOptions) {
765 766
		if (!this._editable) {
			return;
767
		}
768

769 770
		if (this._currentEditIndex === this._savePoint) {
			return;
771
		}
772

773 774 775 776 777 778 779
		let editsToUndo: number[] = [];
		let editsToRedo: number[] = [];

		if (this._currentEditIndex >= this._savePoint) {
			editsToUndo = this._edits.slice(this._savePoint, this._currentEditIndex).reverse();
		} else if (this._currentEditIndex < this._savePoint) {
			editsToRedo = this._edits.slice(this._currentEditIndex, this._savePoint);
780
		}
781

782
		this._proxy.$revert(this._editorResource, this.viewType, { undoneEdits: editsToUndo, redoneEdits: editsToRedo }, this.getEditState());
783 784 785 786
		this.change(() => {
			this._currentEditIndex = this._savePoint;
			this.spliceEdits();
		});
787 788
	}

789 790 791 792 793
	public async save(options?: ISaveOptions): Promise<boolean> {
		return !!await this.saveCustomEditor(options);
	}

	public async saveCustomEditor(_options?: ISaveOptions): Promise<URI | undefined> {
794
		if (!this._editable) {
795
			return undefined;
796
		}
797
		// TODO: handle save untitled case
M
Matt Bierner 已提交
798
		// TODO: handle cancellation
799
		await createCancelablePromise(token => this._proxy.$onSave(this._editorResource, this.viewType, token));
800 801 802
		this.change(() => {
			this._savePoint = this._currentEditIndex;
		});
803
		return this._editorResource;
804 805
	}

806
	public async saveCustomEditorAs(resource: URI, targetResource: URI, _options?: ISaveOptions): Promise<boolean> {
M
Matt Bierner 已提交
807
		if (this._editable) {
M
Matt Bierner 已提交
808 809
			// TODO: handle cancellation
			await createCancelablePromise(token => this._proxy.$onSaveAs(this._editorResource, this.viewType, targetResource, token));
810 811 812
			this.change(() => {
				this._savePoint = this._currentEditIndex;
			});
M
Matt Bierner 已提交
813 814
			return true;
		} else {
815 816 817 818 819 820 821
			// Since the editor is readonly, just copy the file over
			await this._fileService.copy(resource, targetResource, false /* overwrite */);
			return true;
		}
	}

	public async backup(): Promise<IWorkingCopyBackup> {
822 823 824 825 826 827 828
		const editors = this._getEditors();
		if (!editors.length) {
			throw new Error('No editors found for resource, cannot back up');
		}
		const primaryEditor = editors[0];

		const backupData: IWorkingCopyBackup<CustomDocumentBackupData> = {
829 830
			meta: {
				viewType: this.viewType,
831 832 833 834 835 836 837 838 839 840
				editorResource: this._editorResource,
				extension: primaryEditor.extension ? {
					id: primaryEditor.extension.id.value,
					location: primaryEditor.extension.location,
				} : undefined,
				webview: {
					id: primaryEditor.id,
					options: primaryEditor.webview.options,
					state: primaryEditor.webview.state,
				}
841 842 843 844 845 846 847
			}
		};

		if (!this._editable) {
			return backupData;
		}

848 849 850 851 852 853
		if (this._hotExitState.type === HotExitState.Type.Pending) {
			this._hotExitState.operation.cancel();
		}

		const pendingState = new HotExitState.Pending(
			createCancelablePromise(token =>
854
				this._proxy.$backup(this._editorResource.toJSON(), this.viewType, token)));
855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870
		this._hotExitState = pendingState;

		try {
			await pendingState.operation;
			// Make sure state has not changed in the meantime
			if (this._hotExitState === pendingState) {
				this._hotExitState = HotExitState.Allowed;
			}
		} catch (e) {
			// Make sure state has not changed in the meantime
			if (this._hotExitState === pendingState) {
				this._hotExitState = HotExitState.NotAllowed;
			}
		}

		if (this._hotExitState === HotExitState.Allowed) {
871
			return backupData;
872 873 874 875 876
		}

		throw new Error('Cannot back up in this state');
	}
}