-
Notifications
You must be signed in to change notification settings - Fork 27.9k
/
editorPanes.ts
472 lines (373 loc) · 16.9 KB
/
editorPanes.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { localize } from 'vs/nls';
import { IAction } from 'vs/base/common/actions';
import { Emitter } from 'vs/base/common/event';
import Severity from 'vs/base/common/severity';
import { Disposable, DisposableStore } from 'vs/base/common/lifecycle';
import { EditorExtensions, EditorInputCapabilities, IEditorOpenContext, IVisibleEditorPane, isEditorOpenError } from 'vs/workbench/common/editor';
import { EditorInput } from 'vs/workbench/common/editor/editorInput';
import { Dimension, show, hide, IDomNodePagePosition, isAncestor } from 'vs/base/browser/dom';
import { Registry } from 'vs/platform/registry/common/platform';
import { IEditorPaneRegistry, IEditorPaneDescriptor } from 'vs/workbench/browser/editor';
import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService';
import { EditorPane } from 'vs/workbench/browser/parts/editor/editorPane';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IEditorProgressService, LongRunningOperation } from 'vs/platform/progress/common/progress';
import { IEditorGroupView, DEFAULT_EDITOR_MIN_DIMENSIONS, DEFAULT_EDITOR_MAX_DIMENSIONS } from 'vs/workbench/browser/parts/editor/editor';
import { assertIsDefined } from 'vs/base/common/types';
import { IWorkspaceTrustManagementService } from 'vs/platform/workspace/common/workspaceTrust';
import { ErrorPlaceholderEditor, IErrorEditorPlaceholderOptions, WorkspaceTrustRequiredPlaceholderEditor } from 'vs/workbench/browser/parts/editor/editorPlaceholder';
import { EditorOpenSource, IEditorOptions } from 'vs/platform/editor/common/editor';
import { isCancellationError } from 'vs/base/common/errors';
import { toErrorMessage } from 'vs/base/common/errorMessage';
import { ILogService } from 'vs/platform/log/common/log';
import { IDialogService } from 'vs/platform/dialogs/common/dialogs';
import { IBoundarySashes } from 'vs/base/browser/ui/sash/sash';
export interface IOpenEditorResult {
/**
* The editor pane used for opening. This can be a generic
* placeholder in certain cases, e.g. when workspace trust
* is required, or an editor fails to restore.
*
* Will be `undefined` if an error occurred while trying to
* open the editor and in cases where no placeholder is being
* used.
*/
readonly pane?: EditorPane;
/**
* Whether the editor changed as a result of opening.
*/
readonly changed?: boolean;
/**
* This property is set when an editor fails to restore and
* is shown with a generic place holder. It allows callers
* to still present the error to the user in that case.
*/
readonly error?: Error;
/**
* This property indicates whether the open editor operation was
* cancelled or not. The operation may have been cancelled
* in case another editor open operation was triggered right
* after cancelling this one out.
*/
readonly cancelled?: boolean;
}
export class EditorPanes extends Disposable {
//#region Events
private readonly _onDidFocus = this._register(new Emitter<void>());
readonly onDidFocus = this._onDidFocus.event;
private _onDidChangeSizeConstraints = this._register(new Emitter<{ width: number; height: number } | undefined>());
readonly onDidChangeSizeConstraints = this._onDidChangeSizeConstraints.event;
//#endregion
get minimumWidth() { return this._activeEditorPane?.minimumWidth ?? DEFAULT_EDITOR_MIN_DIMENSIONS.width; }
get minimumHeight() { return this._activeEditorPane?.minimumHeight ?? DEFAULT_EDITOR_MIN_DIMENSIONS.height; }
get maximumWidth() { return this._activeEditorPane?.maximumWidth ?? DEFAULT_EDITOR_MAX_DIMENSIONS.width; }
get maximumHeight() { return this._activeEditorPane?.maximumHeight ?? DEFAULT_EDITOR_MAX_DIMENSIONS.height; }
private _activeEditorPane: EditorPane | null = null;
get activeEditorPane(): IVisibleEditorPane | null { return this._activeEditorPane as IVisibleEditorPane | null; }
private readonly editorPanes: EditorPane[] = [];
private readonly activeEditorPaneDisposables = this._register(new DisposableStore());
private pagePosition: IDomNodePagePosition | undefined;
private boundarySashes: IBoundarySashes | undefined;
private readonly editorOperation = this._register(new LongRunningOperation(this.editorProgressService));
private readonly editorPanesRegistry = Registry.as<IEditorPaneRegistry>(EditorExtensions.EditorPane);
constructor(
private editorGroupParent: HTMLElement,
private editorPanesParent: HTMLElement,
private groupView: IEditorGroupView,
@IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IEditorProgressService private readonly editorProgressService: IEditorProgressService,
@IWorkspaceTrustManagementService private readonly workspaceTrustService: IWorkspaceTrustManagementService,
@ILogService private readonly logService: ILogService,
@IDialogService private readonly dialogService: IDialogService
) {
super();
this.registerListeners();
}
private registerListeners(): void {
this._register(this.workspaceTrustService.onDidChangeTrust(() => this.onDidChangeWorkspaceTrust()));
}
private onDidChangeWorkspaceTrust() {
// If the active editor pane requires workspace trust
// we need to re-open it anytime trust changes to
// account for it.
// For that we explicitly call into the group-view
// to handle errors properly.
const editor = this._activeEditorPane?.input;
const options = this._activeEditorPane?.options;
if (editor?.hasCapability(EditorInputCapabilities.RequiresTrust)) {
this.groupView.openEditor(editor, options);
}
}
async openEditor(editor: EditorInput, options: IEditorOptions | undefined, context: IEditorOpenContext = Object.create(null)): Promise<IOpenEditorResult> {
try {
return await this.doOpenEditor(this.getEditorPaneDescriptor(editor), editor, options, context);
} catch (error) {
// First check if caller instructed us to ignore error handling
if (options?.ignoreError) {
return { error };
}
// In case of an error when opening an editor, we still want to show
// an editor in the desired location to preserve the user intent and
// view state (e.g. when restoring).
//
// For that reason we have place holder editors that can convey a
// message with actions the user can click on.
return this.doShowError(error, editor, options, context);
}
}
private async doShowError(error: Error, editor: EditorInput, options?: IEditorOptions, context?: IEditorOpenContext): Promise<IOpenEditorResult> {
// Always log the error to figure out what is going on
this.logService.error(error);
// Show as modal dialog when explicit user action unless disabled
let errorHandled = false;
if (options?.source === EditorOpenSource.USER && (!isEditorOpenError(error) || error.allowDialog)) {
errorHandled = await this.doShowErrorDialog(error, editor, errorHandled);
}
// Return early if the user dealt with the error already
if (errorHandled) {
return { error };
}
// Show as editor placeholder: pass over the error to display
const editorPlaceholderOptions: IErrorEditorPlaceholderOptions = { ...options };
if (!isCancellationError(error)) {
editorPlaceholderOptions.error = error;
}
return {
...(await this.doOpenEditor(ErrorPlaceholderEditor.DESCRIPTOR, editor, editorPlaceholderOptions, context)),
error
};
}
private async doShowErrorDialog(error: Error, editor: EditorInput, errorHandled: boolean): Promise<boolean> {
let severity = Severity.Error;
let message: string | undefined = undefined;
let detail: string | undefined = toErrorMessage(error);
let errorActions: readonly IAction[] | undefined = undefined;
if (isEditorOpenError(error)) {
errorActions = error.actions;
severity = error.forceSeverity ?? Severity.Error;
if (error.forceMessage) {
message = error.message;
detail = undefined;
}
}
if (!message) {
message = localize('editorOpenErrorDialog', "Unable to open '{0}'", editor.getName());
}
const buttons: string[] = [];
if (errorActions && errorActions.length > 0) {
for (const errorAction of errorActions) {
buttons.push(errorAction.label);
}
} else {
buttons.push(localize({ key: 'ok', comment: ['&& denotes a mnemonic'] }, "&&OK"));
}
let cancelId: number | undefined = undefined;
if (buttons.length === 1) {
buttons.push(localize('cancel', "Cancel"));
cancelId = 1;
}
const result = await this.dialogService.show(
severity,
message,
buttons,
{ detail, cancelId }
);
if (typeof cancelId === 'number' && result.choice === cancelId) {
errorHandled = true; // treat cancel as handled and do not show placeholder
} else if (errorActions) {
const errorAction = errorActions[result.choice];
if (errorAction) {
const result = errorAction.run();
if (result instanceof Promise) {
result.catch(error => this.dialogService.show(Severity.Error, toErrorMessage(error)));
}
errorHandled = true; // treat custom error action as handled and do not show placeholder
}
} else {
errorHandled = false; // show placeholder when generic "OK" is clicked
}
return errorHandled;
}
private async doOpenEditor(descriptor: IEditorPaneDescriptor, editor: EditorInput, options: IEditorOptions | undefined, context: IEditorOpenContext = Object.create(null)): Promise<IOpenEditorResult> {
// Editor pane
const pane = this.doShowEditorPane(descriptor);
// Remember current active element for deciding to restore focus later
const activeElement = document.activeElement;
// Apply input to pane
const { changed, cancelled } = await this.doSetInput(pane, editor, options, context);
// Focus only if not cancelled and not prevented
const focus = !options || !options.preserveFocus;
if (!cancelled && focus && this.shouldRestoreFocus(activeElement)) {
pane.focus();
}
return { pane, changed, cancelled };
}
private shouldRestoreFocus(expectedActiveElement: Element | null): boolean {
if (!this.layoutService.isRestored()) {
return true; // restore focus if we are not restored yet on startup
}
if (!expectedActiveElement) {
return true; // restore focus if nothing was focused
}
const activeElement = document.activeElement;
if (!activeElement || activeElement === document.body) {
return true; // restore focus if nothing is focused currently
}
const same = expectedActiveElement === activeElement;
if (same) {
return true; // restore focus if same element is still active
}
if (activeElement.tagName !== 'INPUT' && activeElement.tagName !== 'TEXTAREA') {
// This is to avoid regressions from not restoring focus as we used to:
// Only allow a different input element (or textarea) to remain focused
// but not other elements that do not accept text input.
return true;
}
if (isAncestor(activeElement, this.editorGroupParent)) {
return true; // restore focus if active element is still inside our editor group
}
return false; // do not restore focus
}
private getEditorPaneDescriptor(editor: EditorInput): IEditorPaneDescriptor {
if (editor.hasCapability(EditorInputCapabilities.RequiresTrust) && !this.workspaceTrustService.isWorkspaceTrusted()) {
// Workspace trust: if an editor signals it needs workspace trust
// but the current workspace is untrusted, we fallback to a generic
// editor descriptor to indicate this an do NOT load the registered
// editor.
return WorkspaceTrustRequiredPlaceholderEditor.DESCRIPTOR;
}
return assertIsDefined(this.editorPanesRegistry.getEditorPane(editor));
}
private doShowEditorPane(descriptor: IEditorPaneDescriptor): EditorPane {
// Return early if the currently active editor pane can handle the input
if (this._activeEditorPane && descriptor.describes(this._activeEditorPane)) {
return this._activeEditorPane;
}
// Hide active one first
this.doHideActiveEditorPane();
// Create editor pane
const editorPane = this.doCreateEditorPane(descriptor);
// Set editor as active
this.doSetActiveEditorPane(editorPane);
// Show editor
const container = assertIsDefined(editorPane.getContainer());
this.editorPanesParent.appendChild(container);
show(container);
// Indicate to editor that it is now visible
editorPane.setVisible(true, this.groupView);
// Layout
if (this.pagePosition) {
editorPane.layout(new Dimension(this.pagePosition.width, this.pagePosition.height), { top: this.pagePosition.top, left: this.pagePosition.left });
}
// Boundary sashes
if (this.boundarySashes) {
editorPane.setBoundarySashes(this.boundarySashes);
}
return editorPane;
}
private doCreateEditorPane(descriptor: IEditorPaneDescriptor): EditorPane {
// Instantiate editor
const editorPane = this.doInstantiateEditorPane(descriptor);
// Create editor container as needed
if (!editorPane.getContainer()) {
const editorPaneContainer = document.createElement('div');
editorPaneContainer.classList.add('editor-instance');
editorPane.create(editorPaneContainer);
}
return editorPane;
}
private doInstantiateEditorPane(descriptor: IEditorPaneDescriptor): EditorPane {
// Return early if already instantiated
const existingEditorPane = this.editorPanes.find(editorPane => descriptor.describes(editorPane));
if (existingEditorPane) {
return existingEditorPane;
}
// Otherwise instantiate new
const editorPane = this._register(descriptor.instantiate(this.instantiationService));
this.editorPanes.push(editorPane);
return editorPane;
}
private doSetActiveEditorPane(editorPane: EditorPane | null) {
this._activeEditorPane = editorPane;
// Clear out previous active editor pane listeners
this.activeEditorPaneDisposables.clear();
// Listen to editor pane changes
if (editorPane) {
this.activeEditorPaneDisposables.add(editorPane.onDidChangeSizeConstraints(e => this._onDidChangeSizeConstraints.fire(e)));
this.activeEditorPaneDisposables.add(editorPane.onDidFocus(() => this._onDidFocus.fire()));
}
// Indicate that size constraints could have changed due to new editor
this._onDidChangeSizeConstraints.fire(undefined);
}
private async doSetInput(editorPane: EditorPane, editor: EditorInput, options: IEditorOptions | undefined, context: IEditorOpenContext): Promise<{ changed: boolean; cancelled: boolean }> {
// If the input did not change, return early and only
// apply the options unless the options instruct us to
// force open it even if it is the same
const inputMatches = editorPane.input?.matches(editor);
if (inputMatches && !options?.forceReload) {
editorPane.setOptions(options);
return { changed: false, cancelled: false };
}
// Start a new editor input operation to report progress
// and to support cancellation. Any new operation that is
// started will cancel the previous one.
const operation = this.editorOperation.start(this.layoutService.isRestored() ? 800 : 3200);
let cancelled = false;
try {
// Clear the current input before setting new input
// This ensures that a slow loading input will not
// be visible for the duration of the new input to
// load (https://github.com/microsoft/vscode/issues/34697)
editorPane.clearInput();
// Set the input to the editor pane
await editorPane.setInput(editor, options, context, operation.token);
if (!operation.isCurrent()) {
cancelled = true;
}
} finally {
operation.stop();
}
return { changed: !inputMatches, cancelled };
}
private doHideActiveEditorPane(): void {
if (!this._activeEditorPane) {
return;
}
// Stop any running operation
this.editorOperation.stop();
// Indicate to editor pane before removing the editor from
// the DOM to give a chance to persist certain state that
// might depend on still being the active DOM element.
this._activeEditorPane.clearInput();
this._activeEditorPane.setVisible(false, this.groupView);
// Remove editor pane from parent
const editorPaneContainer = this._activeEditorPane.getContainer();
if (editorPaneContainer) {
this.editorPanesParent.removeChild(editorPaneContainer);
hide(editorPaneContainer);
}
// Clear active editor pane
this.doSetActiveEditorPane(null);
}
closeEditor(editor: EditorInput): void {
if (this._activeEditorPane?.input && editor.matches(this._activeEditorPane.input)) {
this.doHideActiveEditorPane();
}
}
setVisible(visible: boolean): void {
this._activeEditorPane?.setVisible(visible, this.groupView);
}
layout(pagePosition: IDomNodePagePosition): void {
this.pagePosition = pagePosition;
this._activeEditorPane?.layout(new Dimension(pagePosition.width, pagePosition.height), pagePosition);
}
setBoundarySashes(sashes: IBoundarySashes) {
this.boundarySashes = sashes;
this._activeEditorPane?.setBoundarySashes(sashes);
}
}