Skip to content

Commit 6b9e3b6

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 Co-authored-by: Alberto Iannaccone <[email protected]> Co-authored-by: Akos Kitta <[email protected]> Signed-off-by: Akos Kitta <[email protected]>
1 parent b55cfc2 commit 6b9e3b6

File tree

10 files changed

+422
-90
lines changed

10 files changed

+422
-90
lines changed

Diff for: arduino-ide-extension/package.json

+1
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@
4545
"@types/deepmerge": "^2.2.0",
4646
"@types/glob": "^7.2.0",
4747
"@types/google-protobuf": "^3.7.2",
48+
"@types/is-valid-path": "^0.1.0",
4849
"@types/js-yaml": "^3.12.2",
4950
"@types/keytar": "^4.4.0",
5051
"@types/lodash.debounce": "^4.0.6",

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

+109-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,25 @@ export class OpenSketchFiles extends SketchContribution {
5565
}
5666
});
5767
}
68+
const { workspaceError } = this.workspaceService;
69+
// This happens when the IDE2 has been started (from either a terminal or clicking on an `ino` file) with a /path/to/invalid/sketch. (#964)
70+
if (SketchesError.InvalidName.is(workspaceError)) {
71+
await this.promptMove(workspaceError);
72+
}
5873
} catch (err) {
74+
// This happens when the user gracefully closed IDE2, all went well
75+
// but the main sketch file was renamed outside of IDE2 and when the user restarts the IDE2
76+
// the workspace path still exists, but the sketch path is not valid anymore. (#964)
77+
if (SketchesError.InvalidName.is(err)) {
78+
const movedSketch = await this.promptMove(err);
79+
if (!movedSketch) {
80+
// If user did not accept the move, or move was not possible, force reload with a fallback.
81+
return this.openFallbackSketch();
82+
}
83+
}
84+
5985
if (SketchesError.NotFound.is(err)) {
60-
this.openFallbackSketch();
86+
return this.openFallbackSketch();
6187
} else {
6288
console.error(err);
6389
const message =
@@ -71,6 +97,31 @@ export class OpenSketchFiles extends SketchContribution {
7197
}
7298
}
7399

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

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 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)