Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: expose the Arduino state to VS Code extensions #2071

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion arduino-ide-extension/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@
"temp-dir": "^2.0.0",
"tree-kill": "^1.2.1",
"util": "^0.12.5",
"vscode-arduino-api": "^0.1.1-alpha.4",
"which": "^1.3.1"
},
"devDependencies": {
Expand Down Expand Up @@ -173,7 +174,7 @@
],
"arduino": {
"cli": {
"version": "0.32.2"
"version": "0.33.0-rc1"
},
"fwuploader": {
"version": "2.2.2"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,7 @@ import { FileResourceResolver as TheiaFileResourceResolver } from '@theia/filesy
import { StylingParticipant } from '@theia/core/lib/browser/styling-service';
import { MonacoEditorMenuContribution } from './theia/monaco/monaco-menu';
import { MonacoEditorMenuContribution as TheiaMonacoEditorMenuContribution } from '@theia/monaco/lib/browser/monaco-menu';
import { UpdateArduinoContext } from './contributions/update-arduino-context';

// Hack to fix copy/cut/paste issue after electron version update in Theia.
// https://github.com/eclipse-theia/theia/issues/12487
Expand Down Expand Up @@ -747,6 +748,7 @@ export default new ContainerModule((bind, unbind, isBound, rebind) => {
Contribution.configure(bind, Account);
Contribution.configure(bind, CloudSketchbookContribution);
Contribution.configure(bind, CreateCloudCopy);
Contribution.configure(bind, UpdateArduinoContext);

bindContributionProvider(bind, StartupTaskProvider);
bind(StartupTaskProvider).toService(BoardsServiceProvider); // to reuse the boards config in another window
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
import { DisposableCollection } from '@theia/core/lib/common/disposable';
import URI from '@theia/core/lib/common/uri';
import { inject, injectable } from '@theia/core/shared/inversify';
import { HostedPluginSupport } from '@theia/plugin-ext/lib/hosted/browser/hosted-plugin';
import type { ArduinoState } from 'vscode-arduino-api';
import {
BoardsService,
CompileSummary,
Port,
isCompileSummary,
} from '../../common/protocol';
import {
toApiBoardDetails,
toApiCompileSummary,
toApiPort,
} from '../../common/protocol/arduino-context-mapper';
import type { BoardsConfig } from '../boards/boards-config';
import { BoardsDataStore } from '../boards/boards-data-store';
import { BoardsServiceProvider } from '../boards/boards-service-provider';
import { CurrentSketch } from '../sketches-service-client-impl';
import { SketchContribution } from './contribution';

interface UpdateWorkspaceStateParams<T extends ArduinoState> {
readonly key: keyof T;
readonly value: T[keyof T];
}

/**
* Contribution for setting the VS Code [`workspaceState`](https://code.visualstudio.com/api/references/vscode-api#workspace) on Arduino IDE context changes, such as FQBN, selected port, and sketch path changes via commands.
* See [`vscode-arduino-api`](https://www.npmjs.com/package/vscode-arduino-api) for more details.
*/
@injectable()
export class UpdateArduinoContext extends SketchContribution {
@inject(BoardsService)
private readonly boardsService: BoardsService;
@inject(BoardsServiceProvider)
private readonly boardsServiceProvider: BoardsServiceProvider;
@inject(BoardsDataStore)
private readonly boardsDataStore: BoardsDataStore;
@inject(HostedPluginSupport)
private readonly hostedPluginSupport: HostedPluginSupport;

private readonly toDispose = new DisposableCollection();

override onStart(): void {
this.toDispose.pushAll([
this.boardsServiceProvider.onBoardsConfigChanged((config) =>
this.updateBoardsConfig(config)
),
this.sketchServiceClient.onCurrentSketchDidChange((sketch) =>
this.updateSketchPath(sketch)
),
this.configService.onDidChangeDataDirUri((dataDirUri) =>
this.updateDataDirPath(dataDirUri)
),
this.configService.onDidChangeSketchDirUri((userDirUri) =>
this.updateUserDirPath(userDirUri)
),
this.commandService.onDidExecuteCommand(({ commandId, args }) => {
if (
commandId === 'arduino.languageserver.notifyBuildDidComplete' &&
isCompileSummary(args[0])
) {
this.updateCompileSummary(args[0]);
}
}),
this.boardsDataStore.onChanged((fqbn) => {
const selectedFqbn =
this.boardsServiceProvider.boardsConfig.selectedBoard?.fqbn;
if (selectedFqbn && fqbn.includes(selectedFqbn)) {
this.updateBoardDetails(selectedFqbn);
}
}),
]);
}

override onReady(): void {
this.boardsServiceProvider.reconciled.then(() => {
this.updateBoardsConfig(this.boardsServiceProvider.boardsConfig);
});
this.updateSketchPath(this.sketchServiceClient.tryGetCurrentSketch());
this.updateUserDirPath(this.configService.tryGetSketchDirUri());
this.updateDataDirPath(this.configService.tryGetDataDirUri());
}

onStop(): void {
this.toDispose.dispose();
}

private async updateSketchPath(
sketch: CurrentSketch | undefined
): Promise<void> {
const sketchPath = CurrentSketch.isValid(sketch)
? new URI(sketch.uri).path.fsPath()
: undefined;
return this.updateWorkspaceState({ key: 'sketchPath', value: sketchPath });
}

private async updateCompileSummary(
compileSummary: CompileSummary
): Promise<void> {
const apiCompileSummary = toApiCompileSummary(compileSummary);
return this.updateWorkspaceState({
key: 'compileSummary',
value: apiCompileSummary,
});
}

private async updateBoardsConfig(
boardsConfig: BoardsConfig.Config
): Promise<void> {
const fqbn = boardsConfig.selectedBoard?.fqbn;
const port = boardsConfig.selectedPort;
await this.updateFqbn(fqbn);
await this.updateBoardDetails(fqbn);
await this.updatePort(port);
}

private async updateFqbn(fqbn: string | undefined): Promise<void> {
await this.updateWorkspaceState({ key: 'fqbn', value: fqbn });
}

private async updateBoardDetails(fqbn: string | undefined): Promise<void> {
const unset = () =>
this.updateWorkspaceState({ key: 'boardDetails', value: undefined });
if (!fqbn) {
return unset();
}
const [details, persistedData] = await Promise.all([
this.boardsService.getBoardDetails({ fqbn }),
this.boardsDataStore.getData(fqbn),
]);
if (!details) {
return unset();
}
const apiBoardDetails = toApiBoardDetails({
...details,
configOptions:
BoardsDataStore.Data.EMPTY === persistedData
? details.configOptions
: persistedData.configOptions.slice(),
});
return this.updateWorkspaceState({
key: 'boardDetails',
value: apiBoardDetails,
});
}

private async updatePort(port: Port | undefined): Promise<void> {
const apiPort = port && toApiPort(port);
return this.updateWorkspaceState({ key: 'port', value: apiPort });
}

private async updateUserDirPath(userDirUri: URI | undefined): Promise<void> {
const userDirPath = userDirUri?.path.fsPath();
return this.updateWorkspaceState({
key: 'userDirPath',
value: userDirPath,
});
}

private async updateDataDirPath(dataDirUri: URI | undefined): Promise<void> {
const dataDirPath = dataDirUri?.path.fsPath();
return this.updateWorkspaceState({
key: 'dataDirPath',
value: dataDirPath,
});
}

private async updateWorkspaceState<T extends ArduinoState>(
params: UpdateWorkspaceStateParams<T>
): Promise<void> {
await this.hostedPluginSupport.didStart;
return this.commandService.executeCommand(
'vscodeArduinoAPI.updateState',
params
);
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import { Emitter, Event, JsonRpcProxy } from '@theia/core';
import { DisposableCollection } from '@theia/core/lib/common/disposable';
import { Emitter, Event } from '@theia/core/lib/common/event';
import { injectable, interfaces } from '@theia/core/shared/inversify';
import { HostedPluginServer } from '@theia/plugin-ext/lib/common/plugin-protocol';
import { HostedPluginSupport as TheiaHostedPluginSupport } from '@theia/plugin-ext/lib/hosted/browser/hosted-plugin';
import {
PluginContributions,
HostedPluginSupport as TheiaHostedPluginSupport,
} from '@theia/plugin-ext/lib/hosted/browser/hosted-plugin';

@injectable()
export class HostedPluginSupport extends TheiaHostedPluginSupport {
Expand All @@ -10,7 +13,7 @@ export class HostedPluginSupport extends TheiaHostedPluginSupport {

override onStart(container: interfaces.Container): void {
super.onStart(container);
this.hostedPluginServer.onDidCloseConnection(() =>
this['server'].onDidCloseConnection(() =>
this.onDidCloseConnectionEmitter.fire()
);
}
Expand All @@ -28,8 +31,38 @@ export class HostedPluginSupport extends TheiaHostedPluginSupport {
return this.onDidCloseConnectionEmitter.event;
}

private get hostedPluginServer(): JsonRpcProxy<HostedPluginServer> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return (this as any).server;
protected override startPlugins(
contributionsByHost: Map<string, PluginContributions[]>,
toDisconnect: DisposableCollection
): Promise<void> {
reorderPlugins(contributionsByHost);
return super.startPlugins(contributionsByHost, toDisconnect);
}
}

/**
* Force the `vscode-arduino-ide` API to activate before any Arduino IDE tool VSIX.
*
* Arduino IDE tool VISXs are not forced to declare the `vscode-arduino-api` as a `extensionDependencies`,
* but the API must activate before any tools. This in place sorting helps to bypass Theia's plugin resolution
* without forcing tools developers to add `vscode-arduino-api` to the `extensionDependencies`.
*/
function reorderPlugins(
contributionsByHost: Map<string, PluginContributions[]>
): void {
for (const [, contributions] of contributionsByHost) {
const apiPluginIndex = contributions.findIndex(isArduinoAPI);
if (apiPluginIndex >= 0) {
const apiPlugin = contributions[apiPluginIndex];
contributions.splice(apiPluginIndex, 1);
contributions.unshift(apiPlugin);
}
}
}

function isArduinoAPI(pluginContribution: PluginContributions): boolean {
return (
pluginContribution.plugin.metadata.model.id ===
'dankeboy36.vscode-arduino-api'
);
}
Loading