Skip to content

Commit 6562c15

Browse files
author
Akos Kitta
committed
fix: Prompt sketch move when opening an invalid outside from IDE2
Closes #964 Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
1 parent 99b1094 commit 6562c15

File tree

6 files changed

+284
-50
lines changed

6 files changed

+284
-50
lines changed

arduino-ide-extension/src/browser/contributions/contribution.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ import { MaybePromise } from '@theia/core/lib/common/types';
1212
import { LabelProvider } from '@theia/core/lib/browser/label-provider';
1313
import { EditorManager } from '@theia/editor/lib/browser/editor-manager';
1414
import { MessageService } from '@theia/core/lib/common/message-service';
15-
import { WorkspaceService } from '@theia/workspace/lib/browser/workspace-service';
1615
import { open, OpenerService } from '@theia/core/lib/browser/opener-service';
1716

1817
import {
@@ -61,6 +60,7 @@ import { BoardsServiceProvider } from '../boards/boards-service-provider';
6160
import { BoardsDataStore } from '../boards/boards-data-store';
6261
import { NotificationManager } from '../theia/messages/notifications-manager';
6362
import { MessageType } from '@theia/core/lib/common/message-service-protocol';
63+
import { WorkspaceService } from '../theia/workspace/workspace-service';
6464

6565
export {
6666
Command,

arduino-ide-extension/src/browser/contributions/open-sketch-files.ts

+98-3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { nls } from '@theia/core/lib/common/nls';
2-
import { injectable } from '@theia/core/shared/inversify';
2+
import { inject, injectable } from '@theia/core/shared/inversify';
33
import type { EditorOpenerOptions } from '@theia/editor/lib/browser/editor-manager';
44
import { Later } from '../../common/nls';
55
import { SketchesError } from '../../common/protocol';
@@ -10,9 +10,19 @@ import {
1010
URI,
1111
} from './contribution';
1212
import { SaveAsSketch } from './save-as-sketch';
13+
import { promptMoveSketch } from './open-sketch';
14+
import { ApplicationError } from '@theia/core/lib/common/application-error';
15+
import { Deferred, wait } from '@theia/core/lib/common/promise-util';
16+
import { EditorWidget } from '@theia/editor/lib/browser/editor-widget';
17+
import { DisposableCollection } from '@theia/core/lib/common/disposable';
18+
import { MonacoEditor } from '@theia/monaco/lib/browser/monaco-editor';
19+
import { ContextKeyService as VSCodeContextKeyService } from '@theia/monaco-editor-core/esm/vs/platform/contextkey/browser/contextKeyService';
1320

1421
@injectable()
1522
export class OpenSketchFiles extends SketchContribution {
23+
@inject(VSCodeContextKeyService)
24+
private readonly contextKeyService: VSCodeContextKeyService;
25+
1626
override registerCommands(registry: CommandRegistry): void {
1727
registry.registerCommand(OpenSketchFiles.Commands.OPEN_SKETCH_FILES, {
1828
execute: (uri: URI) => this.openSketchFiles(uri),
@@ -55,9 +65,17 @@ export class OpenSketchFiles extends SketchContribution {
5565
}
5666
});
5767
}
68+
const { workspaceError } = this.workspaceService;
69+
if (SketchesError.InvalidName.is(workspaceError)) {
70+
return this.promptMove(workspaceError);
71+
}
5872
} catch (err) {
73+
if (SketchesError.InvalidName.is(err)) {
74+
return this.promptMove(err);
75+
}
76+
5977
if (SketchesError.NotFound.is(err)) {
60-
this.openFallbackSketch();
78+
return this.openFallbackSketch();
6179
} else {
6280
console.error(err);
6381
const message =
@@ -71,6 +89,29 @@ export class OpenSketchFiles extends SketchContribution {
7189
}
7290
}
7391

92+
private async promptMove(
93+
err: ApplicationError<
94+
number,
95+
{
96+
invalidMainSketchUri: string;
97+
}
98+
>
99+
): Promise<void> {
100+
const { invalidMainSketchUri } = err.data;
101+
requestAnimationFrame(() => this.messageService.error(err.message));
102+
await wait(10); // let IDE2 toast the error message.
103+
const movedSketch = await promptMoveSketch(invalidMainSketchUri, {
104+
fileService: this.fileService,
105+
sketchService: this.sketchService,
106+
labelProvider: this.labelProvider,
107+
});
108+
if (movedSketch) {
109+
return this.workspaceService.open(new URI(movedSketch.uri), {
110+
preserveWindow: true,
111+
});
112+
}
113+
}
114+
74115
private async openFallbackSketch(): Promise<void> {
75116
const sketch = await this.sketchService.createNewSketch();
76117
this.workspaceService.open(new URI(sketch.uri), { preserveWindow: true });
@@ -84,15 +125,69 @@ export class OpenSketchFiles extends SketchContribution {
84125
const widget = this.editorManager.all.find(
85126
(widget) => widget.editor.uri.toString() === uri
86127
);
128+
const disposables = new DisposableCollection();
87129
if (!widget || forceOpen) {
88-
return this.editorManager.open(
130+
const deferred = new Deferred<EditorWidget>();
131+
disposables.push(
132+
this.editorManager.onCreated((editor) => {
133+
if (editor.editor.uri.toString() === uri) {
134+
if (editor.isVisible) {
135+
disposables.dispose();
136+
deferred.resolve(editor);
137+
} else {
138+
// In Theia, the promise resolves after opening the editor, but the editor is neither attached to the DOM, nor visible.
139+
// This is a hack to first get an event from monaco after the widget update request, then IDE2 waits for the next monaco context key event.
140+
// Here, the monaco context key event is not used, but this is the first event after the editor is visible in the UI.
141+
disposables.push(
142+
(editor.editor as MonacoEditor).onDidResize((dimension) => {
143+
if (dimension) {
144+
const isKeyOwner = (
145+
arg: unknown
146+
): arg is { key: string } => {
147+
if (typeof arg === 'object') {
148+
const object = arg as Record<string, unknown>;
149+
return typeof object['key'] === 'string';
150+
}
151+
return false;
152+
};
153+
disposables.push(
154+
this.contextKeyService.onDidChangeContext((e) => {
155+
// `commentIsEmpty` is the first context key change event received from monaco after the editor is for real visible in the UI.
156+
if (isKeyOwner(e) && e.key === 'commentIsEmpty') {
157+
deferred.resolve(editor);
158+
disposables.dispose();
159+
}
160+
})
161+
);
162+
}
163+
})
164+
);
165+
}
166+
}
167+
})
168+
);
169+
this.editorManager.open(
89170
new URI(uri),
90171
options ?? {
91172
mode: 'reveal',
92173
preview: false,
93174
counter: 0,
94175
}
95176
);
177+
const timeout = 5_000; // number of ms IDE2 waits for the editor to show up in the UI
178+
const result = await Promise.race([
179+
deferred.promise,
180+
wait(timeout).then(() => {
181+
disposables.dispose();
182+
return 'timeout';
183+
}),
184+
]);
185+
if (result === 'timeout') {
186+
console.warn(
187+
`Timeout after ${timeout} millis. The editor has not shown up in time. URI: ${uri}`
188+
);
189+
}
190+
return result;
96191
}
97192
}
98193
}

arduino-ide-extension/src/browser/contributions/open-sketch.ts

+63-39
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,13 @@
11
import * as remote from '@theia/core/electron-shared/@electron/remote';
22
import { nls } from '@theia/core/lib/common/nls';
33
import { injectable } from '@theia/core/shared/inversify';
4-
import { SketchesError, SketchRef } from '../../common/protocol';
4+
import { FileService } from '@theia/filesystem/lib/browser/file-service';
5+
import { LabelProvider } from '@theia/core/lib/browser/label-provider';
6+
import {
7+
SketchesError,
8+
SketchesService,
9+
SketchRef,
10+
} from '../../common/protocol';
511
import { ArduinoMenus } from '../menu/arduino-menus';
612
import {
713
Command,
@@ -108,45 +114,11 @@ export class OpenSketch extends SketchContribution {
108114
return sketch;
109115
}
110116
if (Sketch.isSketchFile(sketchFileUri)) {
111-
const name = new URI(sketchFileUri).path.name;
112-
const nameWithExt = this.labelProvider.getName(new URI(sketchFileUri));
113-
const { response } = await remote.dialog.showMessageBox({
114-
title: nls.localize('arduino/sketch/moving', 'Moving'),
115-
type: 'question',
116-
buttons: [
117-
nls.localize('vscode/issueMainService/cancel', 'Cancel'),
118-
nls.localize('vscode/issueMainService/ok', 'OK'),
119-
],
120-
message: nls.localize(
121-
'arduino/sketch/movingMsg',
122-
'The file "{0}" needs to be inside a sketch folder named "{1}".\nCreate this folder, move the file, and continue?',
123-
nameWithExt,
124-
name
125-
),
117+
return promptMoveSketch(sketchFileUri, {
118+
fileService: this.fileService,
119+
sketchService: this.sketchService,
120+
labelProvider: this.labelProvider,
126121
});
127-
if (response === 1) {
128-
// OK
129-
const newSketchUri = new URI(sketchFileUri).parent.resolve(name);
130-
const exists = await this.fileService.exists(newSketchUri);
131-
if (exists) {
132-
await remote.dialog.showMessageBox({
133-
type: 'error',
134-
title: nls.localize('vscode/dialog/dialogErrorMessage', 'Error'),
135-
message: nls.localize(
136-
'arduino/sketch/cantOpen',
137-
'A folder named "{0}" already exists. Can\'t open sketch.',
138-
name
139-
),
140-
});
141-
return undefined;
142-
}
143-
await this.fileService.createFolder(newSketchUri);
144-
await this.fileService.move(
145-
new URI(sketchFileUri),
146-
new URI(newSketchUri.resolve(nameWithExt).toString())
147-
);
148-
return this.sketchService.getSketchFolder(newSketchUri.toString());
149-
}
150122
}
151123
}
152124
}
@@ -158,3 +130,55 @@ export namespace OpenSketch {
158130
};
159131
}
160132
}
133+
134+
export async function promptMoveSketch(
135+
sketchFileUri: string | URI,
136+
options: {
137+
fileService: FileService;
138+
sketchService: SketchesService;
139+
labelProvider: LabelProvider;
140+
}
141+
): Promise<Sketch | undefined> {
142+
const { fileService, sketchService, labelProvider } = options;
143+
const uri =
144+
sketchFileUri instanceof URI ? sketchFileUri : new URI(sketchFileUri);
145+
const name = uri.path.name;
146+
const nameWithExt = labelProvider.getName(uri);
147+
const { response } = await remote.dialog.showMessageBox({
148+
title: nls.localize('arduino/sketch/moving', 'Moving'),
149+
type: 'question',
150+
buttons: [
151+
nls.localize('vscode/issueMainService/cancel', 'Cancel'),
152+
nls.localize('vscode/issueMainService/ok', 'OK'),
153+
],
154+
message: nls.localize(
155+
'arduino/sketch/movingMsg',
156+
'The file "{0}" needs to be inside a sketch folder named "{1}".\nCreate this folder, move the file, and continue?',
157+
nameWithExt,
158+
name
159+
),
160+
});
161+
if (response === 1) {
162+
// OK
163+
const newSketchUri = uri.parent.resolve(name);
164+
const exists = await fileService.exists(newSketchUri);
165+
if (exists) {
166+
await remote.dialog.showMessageBox({
167+
type: 'error',
168+
title: nls.localize('vscode/dialog/dialogErrorMessage', 'Error'),
169+
message: nls.localize(
170+
'arduino/sketch/cantOpen',
171+
'A folder named "{0}" already exists. Can\'t open sketch.',
172+
name
173+
),
174+
});
175+
return undefined;
176+
}
177+
await fileService.createFolder(newSketchUri);
178+
await fileService.move(
179+
uri,
180+
new URI(newSketchUri.resolve(nameWithExt).toString())
181+
);
182+
return sketchService.getSketchFolder(newSketchUri.toString());
183+
}
184+
}

arduino-ide-extension/src/browser/theia/workspace/workspace-service.ts

+31
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import {
1616
import {
1717
SketchesService,
1818
Sketch,
19+
SketchesError,
1920
} from '../../../common/protocol/sketches-service';
2021
import { FileStat } from '@theia/filesystem/lib/common/files';
2122
import {
@@ -38,6 +39,7 @@ export class WorkspaceService extends TheiaWorkspaceService {
3839
private readonly providers: ContributionProvider<StartupTaskProvider>;
3940

4041
private version?: string;
42+
private _workspaceError: Error | undefined;
4143

4244
async onStart(application: FrontendApplication): Promise<void> {
4345
const info = await this.applicationServer.getApplicationInfo();
@@ -51,6 +53,10 @@ export class WorkspaceService extends TheiaWorkspaceService {
5153
this.onCurrentWidgetChange({ newValue, oldValue: null });
5254
}
5355

56+
get workspaceError(): Error | undefined {
57+
return this._workspaceError;
58+
}
59+
5460
protected override async toFileStat(
5561
uri: string | URI | undefined
5662
): Promise<FileStat | undefined> {
@@ -59,6 +65,31 @@ export class WorkspaceService extends TheiaWorkspaceService {
5965
const newSketchUri = await this.sketchService.createNewSketch();
6066
return this.toFileStat(newSketchUri.uri);
6167
}
68+
// When opening a file instead of a directory, IDE2 (and Theia) expects a workspace JSON file.
69+
// Nothing will work if the workspace file is invalid. Users tend to start (see #964) IDE2 from the `.ino` files,
70+
// so here, IDE2 tries to load the sketch via the CLI from the main sketch file URI.
71+
// If loading the sketch is OK, IDE2 starts and uses that the sketch folder as the workspace root instead of the sketch file.
72+
// If loading fails due to invalid name error, IDE2 loads a temp sketch and preserves the startup error, and offers the sketch move to the user later.
73+
// If loading the sketch fails, create a fallback sketch and open the new temp sketch folder as the workspace root.
74+
if (stat.isFile && stat.resource.path.ext === '.ino') {
75+
try {
76+
const sketch = await this.sketchService.loadSketch(
77+
stat.resource.toString()
78+
);
79+
return this.toFileStat(sketch.uri);
80+
} catch (err) {
81+
if (SketchesError.InvalidName.is(err)) {
82+
this._workspaceError = err;
83+
const newSketchUri = await this.sketchService.createNewSketch();
84+
return this.toFileStat(newSketchUri.uri);
85+
} else if (SketchesError.NotFound.is(err)) {
86+
this._workspaceError = err;
87+
const newSketchUri = await this.sketchService.createNewSketch();
88+
return this.toFileStat(newSketchUri.uri);
89+
}
90+
throw err;
91+
}
92+
}
6293
return stat;
6394
}
6495

arduino-ide-extension/src/common/protocol/sketches-service.ts

+10
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import URI from '@theia/core/lib/common/uri';
44
export namespace SketchesError {
55
export const Codes = {
66
NotFound: 5001,
7+
InvalidName: 5002,
78
};
89
export const NotFound = ApplicationError.declare(
910
Codes.NotFound,
@@ -14,6 +15,15 @@ export namespace SketchesError {
1415
};
1516
}
1617
);
18+
export const InvalidName = ApplicationError.declare(
19+
Codes.InvalidName,
20+
(message: string, invalidMainSketchUri: string) => {
21+
return {
22+
message,
23+
data: { invalidMainSketchUri },
24+
};
25+
}
26+
);
1727
}
1828

1929
export const SketchesServicePath = '/services/sketches-service';

0 commit comments

Comments
 (0)