mainThreadWebview.ts 30.5 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.getWebviewResolvedFailedContent(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.getWebviewResolvedFailedContent(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 347 348 349 350
				let modelRef: IReference<ICustomEditorModel>;
				try {
					modelRef = await this.getOrCreateCustomEditorModel(modelType, resource, viewType, cancellation);
				} catch (error) {
					onUnexpectedError(error);
					webviewInput.webview.html = MainThreadWebviews.getWebviewResolvedFailedContent(viewType);
					return;
				}

351 352 353 354
				if (cancellation.isCancellationRequested) {
					modelRef.dispose();
					return;
				}
M
Matt Bierner 已提交
355

356
				webviewInput.webview.onDispose(() => {
357 358
					modelRef.dispose();
				});
359

360 361 362
				if (capabilities.supportsMove) {
					webviewInput.onMove(async (newResource: URI) => {
						const oldModel = modelRef;
363
						modelRef = await this.getOrCreateCustomEditorModel(modelType, newResource, viewType, CancellationToken.None);
364 365 366 367 368
						this._proxy.$onMoveCustomEditor(handle, newResource, viewType);
						oldModel.dispose();
					});
				}

369
				try {
370
					await this._proxy.$resolveWebviewEditor(resource, handle, viewType, webviewInput.getTitle(), editorGroupToViewColumn(this._editorGroupService, webviewInput.group || 0), webviewInput.webview.options, cancellation);
371 372
				} catch (error) {
					onUnexpectedError(error);
373 374
					webviewInput.webview.html = MainThreadWebviews.getWebviewResolvedFailedContent(viewType);
					modelRef.dispose();
M
Matt Bierner 已提交
375
					return;
376 377 378
				}
			}
		}));
379 380 381 382

		this._editorProviders.set(viewType, disposables);

		return disposables;
383 384 385 386 387 388 389 390 391 392
	}

	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);
393 394

		this._customEditorService.models.disposeAllModelsForView(viewType);
395 396
	}

397 398 399 400
	private async getOrCreateCustomEditorModel(
		modelType: ModelType,
		resource: URI,
		viewType: string,
401
		cancellation: CancellationToken,
402
	): Promise<IReference<ICustomEditorModel>> {
403
		const existingModel = this._customEditorService.models.tryRetain(resource, viewType);
404 405
		if (existingModel) {
			return existingModel;
406
		}
407

408 409
		const model = modelType === ModelType.Text
			? CustomTextEditorModel.create(this._instantiationService, viewType, resource)
410 411 412 413
			: 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);
414

415
		return this._customEditorService.models.add(resource, viewType, model);
416 417
	}

418
	public async $onDidEdit(resourceComponents: UriComponents, viewType: string, editId: number, label: string | undefined): Promise<void> {
419 420
		const resource = URI.revive(resourceComponents);
		const model = await this._customEditorService.models.get(resource, viewType);
421
		if (!model || !(model instanceof MainThreadCustomEditorModel)) {
422 423
			throw new Error('Could not find model for webview editor');
		}
424

425
		model.pushEdit(editId, label);
426 427
	}

428
	private hookupWebviewEventDelegate(handle: extHostProtocol.WebviewPanelHandle, input: WebviewInput) {
429 430
		const disposables = new DisposableStore();

431
		disposables.add(input.webview.onDidClickLink((uri) => this.onDidClickLink(handle, uri)));
432 433 434
		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)));

435
		disposables.add(input.webview.onDispose(() => {
436
			disposables.dispose();
437

438 439 440
			this._proxy.$onDidDisposeWebviewPanel(handle).finally(() => {
				this._webviewInputs.delete(handle);
			});
441
		}));
A
Alex Dima 已提交
442
	}
443

J
Jean Pierre 已提交
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
	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) {
466
		if (!this._webviewInputs.size) {
467 468
			return;
		}
469

470
		const viewStates: extHostProtocol.WebviewPanelViewStateData = {};
471

472 473 474 475 476 477 478
		const updateViewStatesForInput = (group: IEditorGroup, topLevelInput: IEditorInput, editorInput: IEditorInput) => {
			if (!(editorInput instanceof WebviewInput)) {
				return;
			}

			editorInput.updateGroup(group.id);

479
			const handle = this._webviewInputs.getHandleForInput(editorInput);
480 481
			if (handle) {
				viewStates[handle] = {
482
					visible: topLevelInput === group.activeEditor,
J
Jean Pierre 已提交
483
					active: editorInput === activeEditorInput,
484 485 486 487
					position: editorGroupToViewColumn(this._editorGroupService, group.id),
				};
			}
		};
488

489 490 491 492 493 494 495
		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);
496 497
				}
			}
498
		}
499 500 501 502

		if (Object.keys(viewStates).length) {
			this._proxy.$onDidChangeWebviewPanelViewStates(viewStates);
		}
503 504
	}

505
	private onDidClickLink(handle: extHostProtocol.WebviewPanelHandle, link: string): void {
506
		const webview = this.getWebviewInput(handle);
507
		if (this.isSupportedLink(webview, URI.parse(link))) {
508
			this._openerService.open(link, { fromUserGesture: true });
509 510 511
		}
	}

512
	private isSupportedLink(webview: WebviewInput, link: URI): boolean {
513 514 515
		if (MainThreadWebviews.standardSupportedLinkSchemes.has(link.scheme)) {
			return true;
		}
516
		if (!isWeb && this._productService.urlProtocol === link.scheme) {
517 518
			return true;
		}
M
Matt Bierner 已提交
519
		return !!webview.webview.contentOptions.enableCommandUris && link.scheme === Schemas.command;
A
Alex Dima 已提交
520
	}
521

522
	private getWebviewInput(handle: extHostProtocol.WebviewPanelHandle): WebviewInput {
523
		const webview = this.tryGetWebviewInput(handle);
524
		if (!webview) {
M
Matt Bierner 已提交
525
			throw new Error(`Unknown webview handle:${handle}`);
526 527 528 529
		}
		return webview;
	}

530
	private tryGetWebviewInput(handle: extHostProtocol.WebviewPanelHandle): WebviewInput | undefined {
531
		return this._webviewInputs.getInputForHandle(handle);
532 533
	}

534
	private static getWebviewResolvedFailedContent(viewType: string) {
535 536 537 538
		return `<!DOCTYPE html>
		<html>
			<head>
				<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
539
				<meta http-equiv="Content-Security-Policy" content="default-src 'none';">
540
			</head>
541
			<body>${localize('errorMessage', "An error occurred while loading view: {0}", escape(viewType))}</body>
542
		</html>`;
A
Alex Dima 已提交
543
	}
544 545
}

546 547
function reviveWebviewExtension(extensionData: extHostProtocol.WebviewExtensionDescription): WebviewExtensionDescription {
	return { id: extensionData.id, location: URI.revive(extensionData.location) };
M
Matt Bierner 已提交
548 549
}

550
function reviveWebviewOptions(options: modes.IWebviewOptions): WebviewInputOptions {
551 552
	return {
		...options,
553
		allowScripts: options.enableScripts,
554 555 556 557 558
		localResourceRoots: Array.isArray(options.localResourceRoots) ? options.localResourceRoots.map(r => URI.revive(r)) : undefined,
	};
}

function reviveWebviewIcon(
M
Matt Bierner 已提交
559
	value: { light: UriComponents, dark: UriComponents; } | undefined
M
Matt Bierner 已提交
560 561 562 563
): WebviewIcons | undefined {
	return value
		? { light: URI.revive(value.light), dark: URI.revive(value.dark) }
		: undefined;
A
Alex Dima 已提交
564
}
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586

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

587

588 589 590
class MainThreadCustomEditorModel extends Disposable implements ICustomEditorModel, IWorkingCopy {

	private _hotExitState: HotExitState.State = HotExitState.Allowed;
591 592 593
	private _currentEditIndex: number = -1;
	private _savePoint: number = -1;
	private readonly _edits: Array<number> = [];
594
	private _fromBackup: boolean = false;
595

M
Matt Bierner 已提交
596 597 598 599
	public static async create(
		instantiationService: IInstantiationService,
		proxy: extHostProtocol.ExtHostWebviewsShape,
		viewType: string,
600
		resource: URI,
601
		getEditors: () => CustomEditorInput[],
602
		cancellation: CancellationToken,
M
Matt Bierner 已提交
603
	) {
604
		const { editable } = await proxy.$createWebviewCustomEditorDocument(resource, viewType, cancellation);
605 606 607
		const model = instantiationService.createInstance(MainThreadCustomEditorModel, proxy, viewType, resource, editable, getEditors);
		await model.init();
		return model;
608 609 610 611
	}

	constructor(
		private readonly _proxy: extHostProtocol.ExtHostWebviewsShape,
M
Matt Bierner 已提交
612
		private readonly _viewType: string,
613
		private readonly _editorResource: URI,
614
		private readonly _editable: boolean,
615
		private readonly _getEditors: () => CustomEditorInput[],
616 617 618
		@IWorkingCopyService workingCopyService: IWorkingCopyService,
		@ILabelService private readonly _labelService: ILabelService,
		@IFileService private readonly _fileService: IFileService,
619
		@IUndoRedoService private readonly _undoService: IUndoRedoService,
620
		@IBackupFileService private readonly _backupFileService: IBackupFileService,
621 622
	) {
		super();
623

624 625 626
		if (_editable) {
			this._register(workingCopyService.registerWorkingCopy(this));
		}
627 628
	}

629 630 631 632
	get editorResource() {
		return this._editorResource;
	}

633 634 635 636 637
	async init(): Promise<void> {
		const backup = await this._backupFileService.resolve<CustomDocumentBackupData>(this.resource);
		this._fromBackup = !!backup;
	}

638
	dispose() {
639
		if (this._editable) {
640
			this._undoService.removeElements(this._editorResource);
641
		}
642
		this._proxy.$disposeWebviewCustomEditorDocument(this._editorResource, this._viewType);
643 644 645 646 647
		super.dispose();
	}

	//#region IWorkingCopy

648 649 650
	public get resource() {
		// Make sure each custom editor has a unique resource for backup and edits
		return URI.from({
651
			scheme: Schemas.vscodeCustomEditor,
652
			authority: this._viewType,
653 654
			path: this._editorResource.path,
			query: JSON.stringify(this._editorResource.toJSON()),
655 656
		});
	}
657 658

	public get name() {
659
		return basename(this._labelService.getUriLabel(this._editorResource));
660 661 662 663 664 665 666
	}

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

	public isDirty(): boolean {
667 668 669 670
		if (this._edits.length > 0) {
			return this._savePoint !== this._currentEditIndex;
		}
		return this._fromBackup;
671 672 673 674 675 676 677 678 679
	}

	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 已提交
680

681 682 683 684
	public isReadonly() {
		return this._editable;
	}

M
Matt Bierner 已提交
685 686 687 688
	public get viewType() {
		return this._viewType;
	}

689
	public pushEdit(editId: number, label: string | undefined) {
690 691 692 693 694 695 696 697 698 699 700
		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,
701
			resource: this._editorResource,
702
			label: label ?? localize('defaultEditLabel', "Edit"),
M
Matt Bierner 已提交
703 704 705 706
			undo: () => this.undo(),
			redo: () => this.redo(),
		});
	}
707

M
Matt Bierner 已提交
708 709 710 711
	private async undo(): Promise<void> {
		if (!this._editable) {
			return;
		}
712

M
Matt Bierner 已提交
713 714 715 716
		if (this._currentEditIndex < 0) {
			// nothing to undo
			return;
		}
717

M
Matt Bierner 已提交
718 719 720 721
		const undoneEdit = this._edits[this._currentEditIndex];
		this.change(() => {
			--this._currentEditIndex;
		});
722
		await this._proxy.$undo(this._editorResource, this.viewType, undoneEdit, this.getEditState());
M
Matt Bierner 已提交
723
	}
724

M
Matt Bierner 已提交
725 726 727 728 729 730 731 732
	private getEditState(): extHostProtocol.CustomDocumentEditState {
		return {
			allEdits: this._edits,
			currentIndex: this._currentEditIndex,
			saveIndex: this._savePoint,
		};
	}

M
Matt Bierner 已提交
733 734 735 736 737 738 739 740 741 742 743 744 745
	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;
746
		});
747
		await this._proxy.$redo(this._editorResource, this.viewType, redoneEdit, this.getEditState());
748 749 750 751 752 753 754 755 756 757 758
	}

	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) {
759
			this._proxy.$disposeEdits(this._editorResource, this._viewType, removedEdits);
760 761 762 763 764 765
		}
	}

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

768
		if (this.isDirty() !== wasDirty) {
769 770 771 772 773
			this._onDidChangeDirty.fire();
		}
	}

	public async revert(_options?: IRevertOptions) {
774 775
		if (!this._editable) {
			return;
776
		}
777

778 779
		if (this._currentEditIndex === this._savePoint) {
			return;
780
		}
781

782 783 784 785 786 787 788
		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);
789
		}
790

791
		this._proxy.$revert(this._editorResource, this.viewType, { undoneEdits: editsToUndo, redoneEdits: editsToRedo }, this.getEditState());
792 793 794 795
		this.change(() => {
			this._currentEditIndex = this._savePoint;
			this.spliceEdits();
		});
796 797
	}

798 799 800 801 802
	public async save(options?: ISaveOptions): Promise<boolean> {
		return !!await this.saveCustomEditor(options);
	}

	public async saveCustomEditor(_options?: ISaveOptions): Promise<URI | undefined> {
803
		if (!this._editable) {
804
			return undefined;
805
		}
806
		// TODO: handle save untitled case
M
Matt Bierner 已提交
807
		// TODO: handle cancellation
808
		await createCancelablePromise(token => this._proxy.$onSave(this._editorResource, this.viewType, token));
809 810 811
		this.change(() => {
			this._savePoint = this._currentEditIndex;
		});
812
		return this._editorResource;
813 814
	}

815
	public async saveCustomEditorAs(resource: URI, targetResource: URI, _options?: ISaveOptions): Promise<boolean> {
M
Matt Bierner 已提交
816
		if (this._editable) {
M
Matt Bierner 已提交
817 818
			// TODO: handle cancellation
			await createCancelablePromise(token => this._proxy.$onSaveAs(this._editorResource, this.viewType, targetResource, token));
819 820 821
			this.change(() => {
				this._savePoint = this._currentEditIndex;
			});
M
Matt Bierner 已提交
822 823
			return true;
		} else {
824 825 826 827 828 829 830
			// 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> {
831 832 833 834 835 836 837
		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> = {
838 839
			meta: {
				viewType: this.viewType,
840 841 842 843 844 845 846 847 848 849
				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,
				}
850 851 852 853 854 855 856
			}
		};

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

857 858 859 860 861 862
		if (this._hotExitState.type === HotExitState.Type.Pending) {
			this._hotExitState.operation.cancel();
		}

		const pendingState = new HotExitState.Pending(
			createCancelablePromise(token =>
863
				this._proxy.$backup(this._editorResource.toJSON(), this.viewType, token)));
864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879
		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) {
880
			return backupData;
881 882 883 884 885
		}

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