Aligned the electron app to the latest Theia APIs.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
This commit is contained in:
Akos Kitta
2020-09-18 12:23:52 +02:00
committed by Akos Kitta
parent def93ea32f
commit e755a1cd7e
11 changed files with 123 additions and 329 deletions

View File

@@ -113,6 +113,9 @@
},
{
"frontend": "lib/browser/boards/quick-open/boards-quick-open-module"
},
{
"electronMain": "lib/electron-main/arduino-electron-main-module"
}
]
}

View File

@@ -1,5 +1,8 @@
// @ts-check
// The version to use.
const version = '1.9.0';
(async () => {
const os = require('os');
@@ -10,14 +13,21 @@
const repository = path.join(os.tmpdir(), `${v4()}-arduino-examples`);
if (shell.mkdir('-p', repository).code !== 0) {
shell.exit(1);
process.exit(1);
}
if (shell.exec(`git clone https://github.com/arduino/arduino.git --depth 1 ${repository}`).code !== 0) {
if (shell.exec(`git clone https://github.com/arduino/arduino-examples.git ${repository}`).code !== 0) {
shell.exit(1);
process.exit(1);
}
if (shell.exec(`git -C ${repository} checkout tags/${version} -b ${version}`).code !== 0) {
shell.exit(1);
process.exit(1);
}
const destination = path.join(__dirname, '..', 'Examples');
shell.mkdir('-p', destination);
shell.cp('-fR', path.join(repository, 'build', 'shared', 'examples', '*'), destination);
shell.cp('-fR', path.join(repository, 'examples', '*'), destination);
})();

View File

@@ -1,7 +1,7 @@
import { inject, injectable, interfaces } from 'inversify';
import URI from '@theia/core/lib/common/uri';
import { ILogger } from '@theia/core/lib/common/logger';
import { FileSystem } from '@theia/filesystem/lib/common';
import { FileService } from '@theia/filesystem/lib/browser/file-service';
import { MaybePromise } from '@theia/core/lib/common/types';
import { LabelProvider } from '@theia/core/lib/browser/label-provider';
import { MessageService } from '@theia/core/lib/common/message-service';
@@ -59,8 +59,8 @@ export abstract class Contribution implements CommandContribution, MenuContribut
@injectable()
export abstract class SketchContribution extends Contribution {
@inject(FileSystem)
protected readonly fileSystem: FileSystem;
@inject(FileService)
protected readonly fileService: FileService;
@inject(FileSystemExt)
protected readonly fileSystemExt: FileSystemExt;

View File

@@ -1,5 +1,6 @@
import { injectable } from 'inversify';
import { remote } from 'electron';
import URI from '@theia/core/lib/common/uri';
import { ArduinoMenus } from '../menu/arduino-menus';
import { SketchContribution, Command, CommandRegistry, MenuModelRegistry, KeybindingRegistry } from './contribution';
@@ -30,9 +31,9 @@ export class OpenSketchExternal extends SketchContribution {
protected async openExternal(): Promise<void> {
const uri = await this.sketchServiceClient.currentSketchFile();
if (uri) {
const exists = this.fileSystem.exists(uri);
const exists = this.fileService.exists(new URI(uri));
if (exists) {
const fsPath = await this.fileSystem.getFsPath(uri);
const fsPath = await this.fileService.fsPath(new URI(uri));
if (fsPath) {
remote.shell.showItemInFolder(fsPath);
}

View File

@@ -115,7 +115,7 @@ export class OpenSketch extends SketchContribution {
protected async selectSketch(): Promise<Sketch | undefined> {
const config = await this.configService.getConfiguration();
const defaultPath = await this.fileSystem.getFsPath(config.sketchDirUri);
const defaultPath = await this.fileService.fsPath(new URI(config.sketchDirUri));
const { filePaths } = await remote.dialog.showOpenDialog({
defaultPath,
properties: ['createDirectory', 'openFile'],
@@ -149,7 +149,7 @@ export class OpenSketch extends SketchContribution {
});
if (response === 1) { // OK
const newSketchUri = new URI(sketchFileUri).parent.resolve(name);
const exists = await this.fileSystem.exists(newSketchUri.toString());
const exists = await this.fileService.exists(newSketchUri);
if (exists) {
await remote.dialog.showMessageBox({
type: 'error',
@@ -158,8 +158,8 @@ export class OpenSketch extends SketchContribution {
});
return undefined;
}
await this.fileSystem.createFolder(newSketchUri.toString());
await this.fileSystem.move(sketchFileUri, newSketchUri.resolve(nameWithExt).toString());
await this.fileService.createFolder(newSketchUri);
await this.fileService.move(new URI(sketchFileUri), new URI(newSketchUri.resolve(nameWithExt).toString()));
return this.sketchService.getSketchFolder(newSketchUri.toString());
}
}

View File

@@ -45,11 +45,11 @@ export class SaveAsSketch extends SketchContribution {
// If target does not exist, propose a `directories.user`/${sketch.name} path
// If target exists, propose `directories.user`/${sketch.name}_copy_${yyyymmddHHMMss}
const sketchDirUri = new URI((await this.configService.getConfiguration()).sketchDirUri);
const exists = await this.fileSystem.exists(sketchDirUri.resolve(sketch.name).toString());
const exists = await this.fileService.exists(sketchDirUri.resolve(sketch.name));
const defaultUri = exists
? sketchDirUri.resolve(sketchDirUri.resolve(`${sketch.name}_copy_${dateFormat(new Date(), 'yyyymmddHHMMss')}`).toString())
: sketchDirUri.resolve(sketch.name);
const defaultPath = await this.fileSystem.getFsPath(defaultUri.toString())!;
const defaultPath = await this.fileService.fsPath(defaultUri);
const { filePath, canceled } = await remote.dialog.showSaveDialog({ title: 'Save sketch folder as...', defaultPath });
if (!filePath || canceled) {
return false;
@@ -61,7 +61,7 @@ export class SaveAsSketch extends SketchContribution {
const workspaceUri = await this.sketchService.copy(sketch, { destinationUri });
if (workspaceUri && openAfterMove) {
if (wipeOriginal) {
await this.fileSystem.delete(sketch.uri);
await this.fileService.delete(new URI(sketch.uri));
}
this.workspaceService.open(new URI(workspaceUri), { preserveWindow: true });
}

View File

@@ -0,0 +1,8 @@
import { ContainerModule } from 'inversify';
import { ElectronMainApplication as TheiaElectronMainApplication } from '@theia/core/lib/electron-main/electron-main-application';
import { ElectronMainApplication } from './theia/electron-main-application';
export default new ContainerModule((bind, unbind, isBound, rebind) => {
bind(ElectronMainApplication).toSelf().inSingletonScope();
rebind(TheiaElectronMainApplication).toService(ElectronMainApplication);
});

View File

@@ -0,0 +1,76 @@
import { injectable } from 'inversify';
import { app } from 'electron';
import { fork } from 'child_process';
import { AddressInfo } from 'net';
import { ElectronSecurityToken } from '@theia/core/lib/electron-common/electron-token';
import { ElectronMainApplication as TheiaElectronMainApplication, TheiaBrowserWindowOptions } from '@theia/core/lib/electron-main/electron-main-application';
@injectable()
export class ElectronMainApplication extends TheiaElectronMainApplication {
protected async getDefaultBrowserWindowOptions(): Promise<TheiaBrowserWindowOptions> {
const options = await super.getDefaultBrowserWindowOptions();
return {
...options,
// Set and use a custom minimum window size: https://github.com/arduino/arduino-pro-ide/issues/337#issuecomment-687017281
minWidth: 900,
minHeight: 800
};
}
protected async startBackend(): Promise<number> {
// Check if we should run everything as one process.
const noBackendFork = process.argv.indexOf('--no-cluster') !== -1;
// We cannot use the `process.cwd()` as the application project path (the location of the `package.json` in other words)
// in a bundled electron application because it depends on the way we start it. For instance, on OS X, these are a differences:
// https://github.com/eclipse-theia/theia/issues/3297#issuecomment-439172274
process.env.THEIA_APP_PROJECT_PATH = this.globals.THEIA_APP_PROJECT_PATH;
// Set the electron version for both the dev and the production mode. (https://github.com/eclipse-theia/theia/issues/3254)
// Otherwise, the forked backend processes will not know that they're serving the electron frontend.
process.env.THEIA_ELECTRON_VERSION = process.versions.electron;
if (noBackendFork) {
process.env[ElectronSecurityToken] = JSON.stringify(this.electronSecurityToken);
// The backend server main file is supposed to export a promise resolving with the port used by the http(s) server.
const address: AddressInfo = await require(this.globals.THEIA_BACKEND_MAIN_PATH);
return address.port;
} else {
let args = this.processArgv.getProcessArgvWithoutBin();
// https://github.com/eclipse-theia/theia/issues/8227
if (process.platform === 'darwin') {
// https://github.com/electron/electron/issues/3657
// https://stackoverflow.com/questions/10242115/os-x-strange-psn-command-line-parameter-when-launched-from-finder#comment102377986_10242200
// macOS appends an extra `-psn_0_someNumber` arg if a file is opened from Finder after downloading from the Internet.
// "AppName" is an app downloaded from the Internet. Are you sure you want to open it?
args = args.filter(arg => !arg.startsWith('-psn'));
}
const backendProcess = fork(
this.globals.THEIA_BACKEND_MAIN_PATH,
args,
await this.getForkOptions(),
);
return new Promise((resolve, reject) => {
// The backend server main file is also supposed to send the resolved http(s) server port via IPC.
backendProcess.on('message', (address: AddressInfo) => {
resolve(address.port);
});
backendProcess.on('error', error => {
reject(error);
});
app.on('quit', () => {
try {
// If we forked the process for the clusters, we need to manually terminate it.
// See: https://github.com/eclipse-theia/theia/issues/835
process.kill(backendProcess.pid);
} catch (e) {
if (e.code === 'ESRCH') {
console.log('Could not terminate the backend process. It was not running.');
return;
}
throw e;
}
});
});
}
}
}

View File

@@ -6,8 +6,8 @@ import { ncp } from 'ncp';
import { Stats } from 'fs';
import * as fs from './fs-extra';
import URI from '@theia/core/lib/common/uri';
import { FileUri } from '@theia/core/lib/node';
import { isWindows } from '@theia/core/lib/common/os';
import { FileUri, BackendApplicationContribution } from '@theia/core/lib/node';
import { ConfigService } from '../common/protocol/config-service';
import { SketchesService, Sketch } from '../common/protocol/sketches-service';
import { firstToLowerCase } from '../common/utils';
@@ -23,17 +23,11 @@ const prefix = '.arduinoProIDE-unsaved';
// TODO: `fs`: use async API
@injectable()
export class SketchesServiceImpl implements SketchesService, BackendApplicationContribution {
protected readonly temp = temp.track();
export class SketchesServiceImpl implements SketchesService {
@inject(ConfigService)
protected readonly configService: ConfigService;
onStop(): void {
this.temp.cleanupSync();
}
async getSketches(uri?: string): Promise<Sketch[]> {
const sketches: Array<Sketch & { mtimeMs: number }> = [];
let fsPath: undefined | string;
@@ -210,7 +204,7 @@ export class SketchesServiceImpl implements SketchesService, BackendApplicationC
async cloneExample(uri: string): Promise<Sketch> {
const sketch = await this.loadSketch(uri);
const parentPath = await new Promise<string>((resolve, reject) => {
this.temp.mkdir({ prefix }, (err, dirPath) => {
temp.mkdir({ prefix }, (err, dirPath) => {
if (err) {
reject(err);
return;
@@ -277,7 +271,7 @@ export class SketchesServiceImpl implements SketchesService, BackendApplicationC
const monthNames = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
const today = new Date();
const parentPath = await new Promise<string>((resolve, reject) => {
this.temp.mkdir({ prefix }, (err, dirPath) => {
temp.mkdir({ prefix }, (err, dirPath) => {
if (err) {
reject(err);
return;
@@ -373,6 +367,11 @@ void loop() {
if (!exists) {
throw new Error(`Sketch does not exist: ${sketch}`);
}
// Nothing to do when source and destination are the same.
if (sketch.uri === destinationUri) {
await this.loadSketch(sketch.uri); // Sanity check.
return sketch.uri;
}
const destination = FileUri.fsPath(destinationUri);
await new Promise<void>((resolve, reject) => {
ncp.ncp(source, destination, async error => {
@@ -384,9 +383,7 @@ void loop() {
try {
const oldPath = path.join(destination, new URI(sketch.mainFileUri).path.base);
const newPath = path.join(destination, `${newName}.ino`);
if (oldPath !== newPath) {
await fs.rename(oldPath, newPath);
}
await fs.rename(oldPath, newPath);
await this.loadSketch(destinationUri); // Sanity check.
resolve();
} catch (e) {