Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 37c30d5

Browse files
author
Akos Kitta
committedOct 19, 2022
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 99b1094 commit 37c30d5

File tree

8 files changed

+394
-90
lines changed

8 files changed

+394
-90
lines changed
 

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

Lines changed: 1 addition & 1 deletion
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

Lines changed: 110 additions & 4 deletions
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
}

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

Lines changed: 63 additions & 39 deletions
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

Lines changed: 31 additions & 0 deletions
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

Lines changed: 10 additions & 0 deletions
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';

‎arduino-ide-extension/src/electron-main/theia/electron-main-application.ts

Lines changed: 97 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ import {
88
} from '@theia/core/electron-shared/electron';
99
import { fork } from 'child_process';
1010
import { AddressInfo } from 'net';
11-
import { join, dirname } from 'path';
12-
import * as fs from 'fs-extra';
11+
import { join, isAbsolute, resolve } from 'path';
12+
import { promises as fs, Stats } from 'fs';
1313
import { MaybePromise } from '@theia/core/lib/common/types';
1414
import { ElectronSecurityToken } from '@theia/core/lib/electron-common/electron-token';
1515
import { FrontendApplicationConfig } from '@theia/application-package/lib/application-props';
@@ -69,8 +69,10 @@ export class ElectronMainApplication extends TheiaElectronMainApplication {
6969
// Explicitly set the app name to have better menu items on macOS. ("About", "Hide", and "Quit")
7070
// See: https://github.com/electron-userland/electron-builder/issues/2468
7171
// Regression in Theia: https://github.com/eclipse-theia/theia/issues/8701
72+
console.log(`${config.applicationName} ${app.getVersion()}`);
7273
app.on('ready', () => app.setName(config.applicationName));
73-
this.attachFileAssociations();
74+
const cwd = process.cwd();
75+
this.attachFileAssociations(cwd);
7476
this.useNativeWindowFrame = this.getTitleBarStyle(config) === 'native';
7577
this._config = config;
7678
this.hookApplicationEvents();
@@ -84,7 +86,7 @@ export class ElectronMainApplication extends TheiaElectronMainApplication {
8486
return this.launch({
8587
secondInstance: false,
8688
argv: this.processArgv.getProcessArgvWithoutBin(process.argv),
87-
cwd: process.cwd(),
89+
cwd,
8890
});
8991
}
9092

@@ -119,7 +121,7 @@ export class ElectronMainApplication extends TheiaElectronMainApplication {
119121
let traceFile: string | undefined;
120122
if (appPath) {
121123
const tracesPath = join(appPath, 'traces');
122-
await fs.promises.mkdir(tracesPath, { recursive: true });
124+
await fs.mkdir(tracesPath, { recursive: true });
123125
traceFile = join(tracesPath, `trace-${new Date().toISOString()}.trace`);
124126
}
125127
console.log('>>> Content tracing has started...');
@@ -135,14 +137,16 @@ export class ElectronMainApplication extends TheiaElectronMainApplication {
135137
})();
136138
}
137139

138-
private attachFileAssociations(): void {
140+
private attachFileAssociations(cwd: string): void {
139141
// OSX: register open-file event
140142
if (os.isOSX) {
141-
app.on('open-file', async (event, uri) => {
143+
app.on('open-file', async (event, path) => {
142144
event.preventDefault();
143-
if (uri.endsWith('.ino') && (await fs.pathExists(uri))) {
144-
this.openFilePromise.reject();
145-
await this.openSketch(dirname(uri));
145+
const resolvedPath = await this.resolvePath(path, cwd);
146+
const sketchFolderPath = await this.isValidSketchPath(resolvedPath);
147+
if (sketchFolderPath) {
148+
this.openFilePromise.reject(new InterruptWorkspaceRestoreError());
149+
await this.openSketch(sketchFolderPath);
146150
}
147151
});
148152
setTimeout(() => this.openFilePromise.resolve(), 500);
@@ -151,8 +155,51 @@ export class ElectronMainApplication extends TheiaElectronMainApplication {
151155
}
152156
}
153157

154-
private async isValidSketchPath(uri: string): Promise<boolean | undefined> {
155-
return typeof uri === 'string' && (await fs.pathExists(uri));
158+
/**
159+
* The `path` argument is valid, if accessible and either pointing to a `.ino` file,
160+
* or it's a directory, and one of the files in the directory is an `.ino` file.
161+
*
162+
* If `undefined`, `path` was pointing to neither an accessible sketch file nor a sketch folder.
163+
*
164+
* The sketch folder name and sketch file name can be different. This method is not sketch folder name compliant.
165+
* The `path` must be an absolute, resolved path.
166+
*/
167+
private async isValidSketchPath(path: string): Promise<string | undefined> {
168+
let stats: Stats | undefined = undefined;
169+
try {
170+
stats = await fs.stat(path);
171+
} catch (err) {
172+
if ('code' in err && err.code === 'ENOENT') {
173+
return undefined;
174+
}
175+
throw err;
176+
}
177+
if (!stats) {
178+
return undefined;
179+
}
180+
if (stats.isFile() && path.endsWith('.ino')) {
181+
return path;
182+
}
183+
try {
184+
const entries = await fs.readdir(path, { withFileTypes: true });
185+
const sketchFilename = entries
186+
.filter((entry) => entry.isFile() && entry.name.endsWith('.ino'))
187+
.map(({ name }) => name)
188+
.sort((left, right) => left.localeCompare(right))[0];
189+
if (sketchFilename) {
190+
return join(path, sketchFilename);
191+
}
192+
} catch (err) {
193+
throw err;
194+
}
195+
return undefined;
196+
}
197+
198+
private async resolvePath(path: string, cwd: string): Promise<string> {
199+
if (isAbsolute(path)) {
200+
return path;
201+
}
202+
return fs.realpath(resolve(cwd, path));
156203
}
157204

158205
protected override async launch(
@@ -163,12 +210,15 @@ export class ElectronMainApplication extends TheiaElectronMainApplication {
163210
// 1. The `open-file` command has been received by the app, rejecting the promise
164211
// 2. A short timeout resolves the promise automatically, falling back to the usual app launch
165212
await this.openFilePromise.promise;
166-
} catch {
167-
// Application has received the `open-file` event and will skip the default application launch
168-
return;
213+
} catch (err) {
214+
if (err instanceof InterruptWorkspaceRestoreError) {
215+
// Application has received the `open-file` event and will skip the default application launch
216+
return;
217+
}
218+
throw err;
169219
}
170220

171-
if (!os.isOSX && (await this.launchFromArgs(params))) {
221+
if (await this.launchFromArgs(params)) {
172222
// Application has received a file in its arguments and will skip the default application launch
173223
return;
174224
}
@@ -182,7 +232,10 @@ export class ElectronMainApplication extends TheiaElectronMainApplication {
182232
`Restoring workspace roots: ${workspaces.map(({ file }) => file)}`
183233
);
184234
for (const workspace of workspaces) {
185-
if (await this.isValidSketchPath(workspace.file)) {
235+
const resolvedPath = await this.resolvePath(workspace.file, params.cwd);
236+
const sketchFolderPath = await this.isValidSketchPath(resolvedPath);
237+
if (sketchFolderPath) {
238+
workspace.file = sketchFolderPath;
186239
if (this.isTempSketch.is(workspace.file)) {
187240
console.info(
188241
`Skipped opening sketch. The sketch was detected as temporary. Workspace path: ${workspace.file}.`
@@ -205,38 +258,37 @@ export class ElectronMainApplication extends TheiaElectronMainApplication {
205258
): Promise<boolean> {
206259
// Copy to prevent manipulation of original array
207260
const argCopy = [...params.argv];
208-
let uri: string | undefined;
209-
for (const possibleUri of argCopy) {
210-
if (
211-
possibleUri.endsWith('.ino') &&
212-
(await this.isValidSketchPath(possibleUri))
213-
) {
214-
uri = possibleUri;
261+
let path: string | undefined;
262+
for (const maybePath of argCopy) {
263+
const resolvedPath = await this.resolvePath(maybePath, params.cwd);
264+
const sketchFolderPath = await this.isValidSketchPath(resolvedPath);
265+
if (sketchFolderPath) {
266+
path = sketchFolderPath;
215267
break;
216268
}
217269
}
218-
if (uri) {
219-
await this.openSketch(dirname(uri));
270+
if (path) {
271+
await this.openSketch(path);
220272
return true;
221273
}
222274
return false;
223275
}
224276

225277
private async openSketch(
226-
workspace: WorkspaceOptions | string
278+
workspaceOrPath: WorkspaceOptions | string
227279
): Promise<BrowserWindow> {
228280
const options = await this.getLastWindowOptions();
229281
let file: string;
230-
if (typeof workspace === 'object') {
231-
options.x = workspace.x;
232-
options.y = workspace.y;
233-
options.width = workspace.width;
234-
options.height = workspace.height;
235-
options.isMaximized = workspace.isMaximized;
236-
options.isFullScreen = workspace.isFullScreen;
237-
file = workspace.file;
282+
if (typeof workspaceOrPath === 'object') {
283+
options.x = workspaceOrPath.x;
284+
options.y = workspaceOrPath.y;
285+
options.width = workspaceOrPath.width;
286+
options.height = workspaceOrPath.height;
287+
options.isMaximized = workspaceOrPath.isMaximized;
288+
options.isFullScreen = workspaceOrPath.isFullScreen;
289+
file = workspaceOrPath.file;
238290
} else {
239-
file = workspace;
291+
file = workspaceOrPath;
240292
}
241293
const [uri, electronWindow] = await Promise.all([
242294
this.createWindowUri(),
@@ -486,3 +538,12 @@ export class ElectronMainApplication extends TheiaElectronMainApplication {
486538
return this._firstWindowId;
487539
}
488540
}
541+
542+
class InterruptWorkspaceRestoreError extends Error {
543+
constructor() {
544+
super(
545+
"Received 'open-file' event. Interrupting the default launch workflow."
546+
);
547+
Object.setPrototypeOf(this, InterruptWorkspaceRestoreError.prototype);
548+
}
549+
}

‎arduino-ide-extension/src/node/arduino-ide-backend-module.ts

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import {
44
ArduinoFirmwareUploader,
55
ArduinoFirmwareUploaderPath,
66
} from '../common/protocol/arduino-firmware-uploader';
7-
87
import { ILogger } from '@theia/core/lib/common/logger';
98
import {
109
BackendApplicationContribution,
@@ -26,7 +25,7 @@ import { ConnectionContainerModule } from '@theia/core/lib/node/messaging/connec
2625
import { CoreClientProvider } from './core-client-provider';
2726
import { ConnectionHandler, JsonRpcConnectionHandler } from '@theia/core';
2827
import { DefaultWorkspaceServer } from './theia/workspace/default-workspace-server';
29-
import { WorkspaceServer as TheiaWorkspaceServer } from '@theia/workspace/lib/common';
28+
import { WorkspaceServer as TheiaWorkspaceServer } from '@theia/workspace/lib/common/workspace-protocol';
3029
import { SketchesServiceImpl } from './sketches-service-impl';
3130
import {
3231
SketchesService,
@@ -40,7 +39,6 @@ import {
4039
ArduinoDaemon,
4140
ArduinoDaemonPath,
4241
} from '../common/protocol/arduino-daemon';
43-
4442
import { ConfigServiceImpl } from './config-service-impl';
4543
import { EnvVariablesServer as TheiaEnvVariablesServer } from '@theia/core/lib/common/env-variables';
4644
import { EnvVariablesServer } from './theia/env-variables/env-variables-server';

‎arduino-ide-extension/src/node/sketches-service-impl.ts

Lines changed: 81 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -187,11 +187,22 @@ export class SketchesServiceImpl
187187
const sketch = await new Promise<SketchWithDetails>((resolve, reject) => {
188188
client.loadSketch(req, async (err, resp) => {
189189
if (err) {
190-
reject(
191-
isNotFoundError(err)
192-
? SketchesError.NotFound(err.details, uri)
193-
: err
194-
);
190+
let rejectWith: unknown = err;
191+
if (isNotFoundError(err)) {
192+
const invalidMainSketchFilePath = await isInvalidSketchNameError(
193+
err,
194+
requestSketchPath
195+
);
196+
if (invalidMainSketchFilePath) {
197+
rejectWith = SketchesError.InvalidName(
198+
err.details,
199+
FileUri.create(invalidMainSketchFilePath).toString()
200+
);
201+
} else {
202+
rejectWith = SketchesError.NotFound(err.details, uri);
203+
}
204+
}
205+
reject(rejectWith);
195206
return;
196207
}
197208
const responseSketchPath = maybeNormalizeDrive(resp.getLocationPath());
@@ -301,7 +312,10 @@ export class SketchesServiceImpl
301312
)} before marking it as recently opened.`
302313
);
303314
} catch (err) {
304-
if (SketchesError.NotFound.is(err)) {
315+
if (
316+
SketchesError.NotFound.is(err) ||
317+
SketchesError.InvalidName.is(err)
318+
) {
305319
this.logger.debug(
306320
`Could not load sketch from '${uri}'. Not marking as recently opened.`
307321
);
@@ -515,7 +529,7 @@ void loop() {
515529
const sketch = await this.loadSketch(uri);
516530
return sketch;
517531
} catch (err) {
518-
if (SketchesError.NotFound.is(err)) {
532+
if (SketchesError.NotFound.is(err) || SketchesError.InvalidName.is(err)) {
519533
return undefined;
520534
}
521535
throw err;
@@ -647,6 +661,66 @@ function isNotFoundError(err: unknown): err is ServiceError {
647661
return ServiceError.is(err) && err.code === 5; // `NOT_FOUND` https://grpc.github.io/grpc/core/md_doc_statuscodes.html
648662
}
649663

664+
/**
665+
* Tries to detect whether the error was caused by an invalid main sketch file name.
666+
* IDE2 should handle gracefully when there is an invalid sketch folder name. See the [spec](https://arduino.github.io/arduino-cli/latest/sketch-specification/#sketch-root-folder) for details.
667+
* The CLI does not have error codes (https://github.com/arduino/arduino-cli/issues/1762), so IDE2 parses the error message and tries to guess it.
668+
* Nothing guarantees that the invalid existing main sketch file still exits by the time client performs the sketch move.
669+
*/
670+
async function isInvalidSketchNameError(
671+
err: unknown,
672+
requestSketchPath: string
673+
): Promise<string | undefined> {
674+
if (isNotFoundError(err)) {
675+
const ino = requestSketchPath.endsWith('.ino');
676+
if (ino) {
677+
const sketchFolderPath = path.dirname(requestSketchPath);
678+
const sketchName = path.basename(sketchFolderPath);
679+
if (
680+
new RegExp(
681+
`${invalidSketchNameErrorRegExpPrefix}${path.join(
682+
sketchFolderPath,
683+
`${sketchName}.ino`
684+
)}`
685+
).test(err.details)
686+
) {
687+
try {
688+
await fs.access(requestSketchPath);
689+
return requestSketchPath;
690+
} catch {
691+
return undefined;
692+
}
693+
}
694+
} else {
695+
try {
696+
const resources = await fs.readdir(requestSketchPath, {
697+
withFileTypes: true,
698+
});
699+
return (
700+
resources
701+
.filter((resource) => resource.isFile())
702+
.filter((resource) => resource.name.endsWith('.ino'))
703+
// A folder might contain multiple sketches. It's OK to ick the first one as IDE2 cannot do much,
704+
// but ensure a deterministic behavior as `readdir(3)` does not guarantee an order. Sort them.
705+
.sort(({ name: left }, { name: right }) =>
706+
left.localeCompare(right)
707+
)
708+
.map(({ name }) => name)
709+
.map((name) => path.join(requestSketchPath, name))[0]
710+
);
711+
} catch (err) {
712+
if ('code' in err && err.code === 'ENOTDIR') {
713+
return undefined;
714+
}
715+
throw err;
716+
}
717+
}
718+
}
719+
return undefined;
720+
}
721+
const invalidSketchNameErrorRegExpPrefix =
722+
'.*: main file missing from sketch: ';
723+
650724
/*
651725
* When a new sketch is created, add a suffix to distinguish it
652726
* from other new sketches I created today.

0 commit comments

Comments
 (0)
Please sign in to comment.