Skip to content

Commit 5edccb9

Browse files
Akos Kittakittaakos
Akos Kitta
authored andcommitted
Avoid opening duplicate editor tabs.
Customized the shell layout restorer: - If a resource is about to open in code editor and preview, do not open the preview. - If a resource is about to open in preview only, open a code editor instead. Signed-off-by: Akos Kitta <[email protected]>
1 parent 555da87 commit 5edccb9

File tree

1 file changed

+152
-68
lines changed

1 file changed

+152
-68
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,78 +1,162 @@
1-
import { inject, injectable } from '@theia/core/shared/inversify';
2-
import { FrontendApplication } from '@theia/core/lib/browser/frontend-application';
1+
import { notEmpty } from '@theia/core';
2+
import { WidgetDescription } from '@theia/core/lib/browser';
33
import { ShellLayoutRestorer as TheiaShellLayoutRestorer } from '@theia/core/lib/browser/shell/shell-layout-restorer';
4-
import { EditorManager } from '@theia/editor/lib/browser';
4+
import { injectable } from '@theia/core/shared/inversify';
5+
import { EditorPreviewWidgetFactory } from '@theia/editor-preview/lib/browser/editor-preview-widget-factory';
6+
import { EditorWidgetFactory } from '@theia/editor/lib/browser/editor-widget-factory';
57

68
@injectable()
79
export class ShellLayoutRestorer extends TheiaShellLayoutRestorer {
8-
// The editor manager is unused in the layout restorer.
9-
// We inject the editor manager to achieve better logging when filtering duplicate editor tabs.
10-
// Feel free to remove it in later IDE2 releases if the duplicate editor tab issues do not occur anymore.
11-
@inject(EditorManager)
12-
private readonly editorManager: EditorManager;
13-
14-
// Workaround for https://github.com/eclipse-theia/theia/issues/6579.
15-
async storeLayoutAsync(app: FrontendApplication): Promise<void> {
16-
if (this.shouldStoreLayout) {
17-
try {
18-
this.logger.info('>>> Storing the layout...');
19-
const layoutData = app.shell.getLayoutData();
20-
const serializedLayoutData = this.deflate(layoutData);
21-
await this.storageService.setData(
22-
this.storageKey,
23-
serializedLayoutData
24-
);
25-
this.logger.info('<<< The layout has been successfully stored.');
26-
} catch (error) {
27-
await this.storageService.setData(this.storageKey, undefined);
28-
this.logger.error('Error during serialization of layout data', error);
10+
/**
11+
* Customized to filter out duplicate editor tabs.
12+
*/
13+
protected override parse<T>(
14+
layoutData: string,
15+
parseContext: TheiaShellLayoutRestorer.ParseContext
16+
): T {
17+
return JSON.parse(layoutData, (property: string, value) => {
18+
if (this.isWidgetsProperty(property)) {
19+
const widgets = parseContext.filteredArray();
20+
const descs = this.filterDescriptions(value); // <--- customization to filter out editor preview construction options.
21+
for (let i = 0; i < descs.length; i++) {
22+
parseContext.push(async (context) => {
23+
widgets[i] = await this.convertToWidget(descs[i], context);
24+
});
25+
}
26+
return widgets;
27+
} else if (value && typeof value === 'object' && !Array.isArray(value)) {
28+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
29+
const copy: any = {};
30+
for (const p in value) {
31+
if (this.isWidgetProperty(p)) {
32+
parseContext.push(async (context) => {
33+
copy[p] = await this.convertToWidget(value[p], context);
34+
});
35+
} else {
36+
copy[p] = value[p];
37+
}
38+
}
39+
return copy;
2940
}
30-
}
41+
return value;
42+
});
3143
}
3244

33-
override async restoreLayout(app: FrontendApplication): Promise<boolean> {
34-
this.logger.info('>>> Restoring the layout state...');
35-
const serializedLayoutData = await this.storageService.getData<string>(
36-
this.storageKey
37-
);
38-
if (serializedLayoutData === undefined) {
39-
this.logger.info('<<< Nothing to restore.');
40-
return false;
41-
}
42-
43-
const layoutData = await this.inflate(serializedLayoutData);
44-
// workaround to remove duplicated tabs
45-
console.log(
46-
'>>> Filtering persisted layout data to eliminate duplicate editor tabs...'
47-
);
48-
const filesUri: string[] = [];
49-
if ((layoutData as any)?.mainPanel?.main?.widgets) {
50-
(layoutData as any).mainPanel.main.widgets = (
51-
layoutData as any
52-
).mainPanel.main.widgets.filter((widget: any) => {
53-
const uri = widget.getResourceUri().toString();
54-
if (filesUri.includes(uri)) {
55-
console.log(`[SKIP]: Already visited editor URI: '${uri}'.`);
56-
return false;
45+
/**
46+
* Workaround to avoid duplicate editor tabs on IDE2 startup.
47+
*
48+
* This function filters all widget construction options with `editor-preview-widget`
49+
* factory ID if another option has the same URI and `code-editor-opener` factory ID.
50+
* In other words, if a resource is about to open in the Code editor, the same resource won't open as a preview widget.
51+
*
52+
* The other bogus state that this function is fixes when there is a resource registered to open with the `editor-preview-widget`,
53+
* but there is no `code-editor-opener` counterpart for the same resource URI. In this case, the `editor-preview-widget` will be replaced
54+
* with the `code-editor-opener` and the `innerWidgetState` will be dropped.
55+
*
56+
* OK, but why is this happening? The breaking change was [here](https://github.com/eclipse-theia/theia/commit/e8e88b76673a6151d1fc12501dbe598be2358350#diff-7e1bdbcf59009518f9f3b76fe22cc8ab82d13ffa5e5e0a4262e492f25e505d98R29-R30)
57+
* in Theia when the editor manager of the code editor was bound to the preview editor.
58+
* For whatever reasons, the IDE2 started to use `@theia/editor-preview` extension from [this](https://github.com/arduino/arduino-ide/commit/fc0f67493b728f9202c9a04c7243d03b0d6ea0c7) commit. From this point, when an editor was opened,
59+
* but the `preview` option was not set to explicit `false` the preview editor manager has created the widgets instead of the manager of the regular code editor.
60+
* This code must stay to be backward compatible.
61+
*
62+
* Example of resource with multiple opener:
63+
* ```json
64+
* [
65+
* {
66+
* "constructionOptions": {
67+
* "factoryId": "editor-preview-widget",
68+
* "options": {
69+
* "kind": "navigatable",
70+
* "uri": "file:///Users/a.kitta/Documents/Arduino/sketch_jun3b/sketch_jun3b.ino",
71+
* "counter": 1,
72+
* "preview": false
73+
* }
74+
* },
75+
* "innerWidgetState": "{\"isPreview\":false,\"editorState\":{\"cursorState\":[{\"inSelectionMode\":false,\"selectionStart\":{\"lineNumber\":10,\"column\":1},\"position\":{\"lineNumber\":10,\"column\":1}}],\"viewState\":{\"scrollLeft\":0,\"firstPosition\":{\"lineNumber\":1,\"column\":1},\"firstPositionDeltaTop\":0},\"contributionsState\":{\"editor.contrib.folding\":{\"lineCount\":10,\"provider\":\"indent\",\"foldedImports\":false},\"editor.contrib.wordHighlighter\":false}}}"
76+
* },
77+
* {
78+
* "constructionOptions": {
79+
* "factoryId": "code-editor-opener",
80+
* "options": {
81+
* "kind": "navigatable",
82+
* "uri": "file:///Users/a.kitta/Documents/Arduino/sketch_jun3b/sketch_jun3b.ino",
83+
* "counter": 0
84+
* }
85+
* },
86+
* "innerWidgetState": "{\"cursorState\":[{\"inSelectionMode\":false,\"selectionStart\":{\"lineNumber\":1,\"column\":1},\"position\":{\"lineNumber\":1,\"column\":1}}],\"viewState\":{\"scrollLeft\":0,\"firstPosition\":{\"lineNumber\":1,\"column\":1},\"firstPositionDeltaTop\":0},\"contributionsState\":{\"editor.contrib.folding\":{\"lineCount\":10,\"provider\":\"indent\",\"foldedImports\":false},\"editor.contrib.wordHighlighter\":false}}"
87+
* }
88+
* ]
89+
* ```
90+
*
91+
* Example with resource only with preview opener:
92+
*
93+
* ```json
94+
* [
95+
* {
96+
* "constructionOptions": {
97+
* "factoryId": "editor-preview-widget",
98+
* "options": {
99+
* "kind": "navigatable",
100+
* "uri": "file:///c%3A/Users/per/Documents/Arduino/duptabs/duptabs.ino",
101+
* "counter": 1,
102+
* "preview": false
103+
* }
104+
* },
105+
* "innerWidgetState": "{\"isPreview\":false,\"editorState\":{\"cursorState\":[{\"inSelectionMode\":false,\"selectionStart\":{\"lineNumber\":1,\"column\":1},\"position\":{\"lineNumber\":1,\"column\":1}}],\"viewState\":{\"scrollLeft\":0,\"firstPosition\":{\"lineNumber\":1,\"column\":1},\"firstPositionDeltaTop\":0},\"contributionsState\":{\"editor.contrib.wordHighlighter\":false,\"editor.contrib.folding\":{\"lineCount\":11,\"provider\":\"indent\"}}}}"
106+
* }
107+
* ]
108+
* ```
109+
*/
110+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
111+
private filterDescriptions(value: any): WidgetDescription[] {
112+
const descriptions = value as WidgetDescription[];
113+
const codeEditorUris = new Set<string>();
114+
descriptions.forEach(({ constructionOptions }) => {
115+
const { options, factoryId } = constructionOptions;
116+
if (isResourceWidgetOptions(options)) {
117+
const { uri } = options;
118+
// resource about to open in code editor
119+
if (factoryId === EditorWidgetFactory.ID) {
120+
codeEditorUris.add(uri);
57121
}
58-
console.log(`[OK]: Visited editor URI: '${uri}'.`);
59-
filesUri.push(uri);
60-
return true;
61-
});
62-
}
63-
console.log('<<< Filtered the layout data before restoration.');
64-
65-
await app.shell.setLayoutData(layoutData);
66-
const allOpenedEditors = this.editorManager.all;
67-
// If any editor was visited during the layout data filtering,
68-
// but the editor manager does not know about opened editors, then
69-
// the IDE2 will show duplicate editors.
70-
if (filesUri.length && !allOpenedEditors.length) {
71-
console.warn(
72-
'Inconsistency detected between the editor manager and the restored layout data. Editors were detected to be open in the layout data from the previous session, but the editor manager does not know about the opened editor.'
73-
);
74-
}
75-
this.logger.info('<<< The layout has been successfully restored.');
76-
return true;
122+
}
123+
});
124+
return descriptions
125+
.map((desc) => {
126+
const { constructionOptions } = desc;
127+
const { options, factoryId } = constructionOptions;
128+
if (factoryId === EditorPreviewWidgetFactory.ID) {
129+
// resource about to open in preview editor
130+
if (isResourceWidgetOptions(options)) {
131+
const { uri } = options;
132+
// if the resource is about to open in the code editor anyway, do not open the resource in a preview widget too.
133+
if (codeEditorUris.has(uri)) {
134+
console.log(
135+
`Filtered a widget construction options to avoid duplicate editor tab. URI: ${options.uri}, factory ID: ${factoryId}.`
136+
);
137+
return undefined;
138+
} else {
139+
// if the preview construction options does not have the code editor counterpart, instead of dropping the preview construction option, a code editor option will be created on the fly.
140+
return {
141+
constructionOptions: {
142+
factoryId: EditorWidgetFactory.ID,
143+
options: {
144+
uri,
145+
kind: 'navigatable',
146+
counter: 0,
147+
},
148+
},
149+
};
150+
}
151+
}
152+
}
153+
return desc;
154+
})
155+
.filter(notEmpty);
77156
}
78157
}
158+
159+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
160+
function isResourceWidgetOptions(options: any): options is { uri: string } {
161+
return !!options && 'uri' in options && typeof options.uri === 'string';
162+
}

0 commit comments

Comments
 (0)