Skip to content

Commit 91c7cef

Browse files
author
Akos Kitta
committed
fix: Prompt sketch move when opening an invalid outside from IDE2
Log IDE2 version on start. Closes #964 Closes #1484 Signed-off-by: Akos Kitta <[email protected]>
1 parent 87ebcbe commit 91c7cef

File tree

8 files changed

+397
-90
lines changed

8 files changed

+397
-90
lines changed

Diff for: 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,

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

+110-4
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,28 @@
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';
5-
import { SketchesError } from '../../common/protocol';
5+
import { Sketch, SketchesError } from '../../common/protocol';
66
import {
77
Command,
88
CommandRegistry,
99
SketchContribution,
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,26 @@ export class OpenSketchFiles extends SketchContribution {
5565
}
5666
});
5767
}
68+
const { workspaceError } = this.workspaceService;
69+
// This happens when the IDE2 has been started from a terminal with a /path/to/invalid/sketch. (#964)
70+
// Or user has started the IDE2 from clicking on an `ino` file.
71+
if (SketchesError.InvalidName.is(workspaceError)) {
72+
await this.promptMove(workspaceError);
73+
}
5874
} catch (err) {
75+
// This happens when the user gracefully closed IDE2, all went well
76+
// but the main sketch file was renamed outside of IDE2 and when the user restarts the IDE2
77+
// the workspace path still exists, but the sketch path is not valid anymore. (#964)
78+
if (SketchesError.InvalidName.is(err)) {
79+
const movedSketch = await this.promptMove(err);
80+
if (!movedSketch) {
81+
// If user did not accept the move, or move was not possible, force reload with a fallback.
82+
return this.openFallbackSketch();
83+
}
84+
}
85+
5986
if (SketchesError.NotFound.is(err)) {
60-
this.openFallbackSketch();
87+
return this.openFallbackSketch();
6188
} else {
6289
console.error(err);
6390
const message =
@@ -71,6 +98,31 @@ export class OpenSketchFiles extends SketchContribution {
7198
}
7299
}
73100

101+
private async promptMove(
102+
err: ApplicationError<
103+
number,
104+
{
105+
invalidMainSketchUri: string;
106+
}
107+
>
108+
): Promise<Sketch | undefined> {
109+
const { invalidMainSketchUri } = err.data;
110+
requestAnimationFrame(() => this.messageService.error(err.message));
111+
await wait(10); // let IDE2 toast the error message.
112+
const movedSketch = await promptMoveSketch(invalidMainSketchUri, {
113+
fileService: this.fileService,
114+
sketchService: this.sketchService,
115+
labelProvider: this.labelProvider,
116+
});
117+
if (movedSketch) {
118+
this.workspaceService.open(new URI(movedSketch.uri), {
119+
preserveWindow: true,
120+
});
121+
return movedSketch;
122+
}
123+
return undefined;
124+
}
125+
74126
private async openFallbackSketch(): Promise<void> {
75127
const sketch = await this.sketchService.createNewSketch();
76128
this.workspaceService.open(new URI(sketch.uri), { preserveWindow: true });
@@ -84,15 +136,69 @@ export class OpenSketchFiles extends SketchContribution {
84136
const widget = this.editorManager.all.find(
85137
(widget) => widget.editor.uri.toString() === uri
86138
);
139+
const disposables = new DisposableCollection();
87140
if (!widget || forceOpen) {
88-
return this.editorManager.open(
141+
const deferred = new Deferred<EditorWidget>();
142+
disposables.push(
143+
this.editorManager.onCreated((editor) => {
144+
if (editor.editor.uri.toString() === uri) {
145+
if (editor.isVisible) {
146+
disposables.dispose();
147+
deferred.resolve(editor);
148+
} else {
149+
// In Theia, the promise resolves after opening the editor, but the editor is neither attached to the DOM, nor visible.
150+
// 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.
151+
// Here, the monaco context key event is not used, but this is the first event after the editor is visible in the UI.
152+
disposables.push(
153+
(editor.editor as MonacoEditor).onDidResize((dimension) => {
154+
if (dimension) {
155+
const isKeyOwner = (
156+
arg: unknown
157+
): arg is { key: string } => {
158+
if (typeof arg === 'object') {
159+
const object = arg as Record<string, unknown>;
160+
return typeof object['key'] === 'string';
161+
}
162+
return false;
163+
};
164+
disposables.push(
165+
this.contextKeyService.onDidChangeContext((e) => {
166+
// `commentIsEmpty` is the first context key change event received from monaco after the editor is for real visible in the UI.
167+
if (isKeyOwner(e) && e.key === 'commentIsEmpty') {
168+
deferred.resolve(editor);
169+
disposables.dispose();
170+
}
171+
})
172+
);
173+
}
174+
})
175+
);
176+
}
177+
}
178+
})
179+
);
180+
this.editorManager.open(
89181
new URI(uri),
90182
options ?? {
91183
mode: 'reveal',
92184
preview: false,
93185
counter: 0,
94186
}
95187
);
188+
const timeout = 5_000; // number of ms IDE2 waits for the editor to show up in the UI
189+
const result = await Promise.race([
190+
deferred.promise,
191+
wait(timeout).then(() => {
192+
disposables.dispose();
193+
return 'timeout';
194+
}),
195+
]);
196+
if (result === 'timeout') {
197+
console.warn(
198+
`Timeout after ${timeout} millis. The editor has not shown up in time. URI: ${uri}`
199+
);
200+
}
201+
return result;
96202
}
97203
}
98204
}

Diff for: 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+
}

Diff for: 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

Diff for: 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)