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 Arduino state to VS Code extensions #2110

Merged
merged 3 commits into from
Jul 5, 2023
Merged
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 @@ -104,7 +104,8 @@
"temp": "^0.9.1",
"temp-dir": "^2.0.0",
"tree-kill": "^1.2.1",
"util": "^0.12.5"
"util": "^0.12.5",
"vscode-arduino-api": "^0.1.2"
},
"devDependencies": {
"@octokit/rest": "^18.12.0",
Expand Down
11 changes: 11 additions & 0 deletions arduino-ide-extension/src/browser/arduino-ide-frontend-module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,11 @@ 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 { UpdateArduinoState } from './contributions/update-arduino-state';
import { TerminalWidgetImpl } from './theia/terminal/terminal-widget-impl';
import { TerminalWidget } from '@theia/terminal/lib/browser/base/terminal-widget';
import { TerminalFrontendContribution } from './theia/terminal/terminal-frontend-contribution';
import { TerminalFrontendContribution as TheiaTerminalFrontendContribution } from '@theia/terminal/lib/browser/terminal-frontend-contribution'

// 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 +752,7 @@ export default new ContainerModule((bind, unbind, isBound, rebind) => {
Contribution.configure(bind, Account);
Contribution.configure(bind, CloudSketchbookContribution);
Contribution.configure(bind, CreateCloudCopy);
Contribution.configure(bind, UpdateArduinoState);

bindContributionProvider(bind, StartupTaskProvider);
bind(StartupTaskProvider).toService(BoardsServiceProvider); // to reuse the boards config in another window
Expand Down Expand Up @@ -1024,4 +1030,9 @@ export default new ContainerModule((bind, unbind, isBound, rebind) => {
rebind(TheiaMonacoEditorMenuContribution).toService(
MonacoEditorMenuContribution
);

// Patch terminal issues.
rebind(TerminalWidget).to(TerminalWidgetImpl).inTransientScope();
bind(TerminalFrontendContribution).toSelf().inSingletonScope();
rebind(TheiaTerminalFrontendContribution).toService(TerminalFrontendContribution);
});
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 UpdateStateParams<T extends ArduinoState> {
readonly key: keyof T;
readonly value: T[keyof T];
}

/**
* Contribution for updating the Arduino state, such as the FQBN, selected port, and sketch path changes via commands, so other VS Code extensions can access it.
* See [`vscode-arduino-api`](https://github.com/dankeboy36/vscode-arduino-api#api) for more details.
*/
@injectable()
export class UpdateArduinoState 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.updateState({ key: 'sketchPath', value: sketchPath });
}

private async updateCompileSummary(
compileSummary: CompileSummary
): Promise<void> {
const apiCompileSummary = toApiCompileSummary(compileSummary);
return this.updateState({
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.updateState({ key: 'fqbn', value: fqbn });
}

private async updateBoardDetails(fqbn: string | undefined): Promise<void> {
const unset = () =>
this.updateState({ 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.updateState({
key: 'boardDetails',
value: apiBoardDetails,
});
}

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

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

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

private async updateState<T extends ArduinoState>(
params: UpdateStateParams<T>
): Promise<void> {
await this.hostedPluginSupport.didStart;
return this.commandService.executeCommand(
'arduinoAPI.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'
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { TabBarToolbarRegistry } from '@theia/core/lib/browser/shell/tab-bar-toolbar';
import { CommandRegistry } from '@theia/core/lib/common/command';
import { Widget } from '@theia/core/shared/@phosphor/widgets';
import { injectable } from '@theia/core/shared/inversify';
import { TerminalWidget } from '@theia/terminal/lib/browser/base/terminal-widget';
import {
TerminalCommands,
TerminalFrontendContribution as TheiaTerminalFrontendContribution,
} from '@theia/terminal/lib/browser/terminal-frontend-contribution';

// Patch for https://github.com/eclipse-theia/theia/pull/12626
@injectable()
export class TerminalFrontendContribution extends TheiaTerminalFrontendContribution {
override registerCommands(commands: CommandRegistry): void {
super.registerCommands(commands);
commands.unregisterCommand(TerminalCommands.SPLIT);
commands.registerCommand(TerminalCommands.SPLIT, {
execute: () => this.splitTerminal(),
isEnabled: (w) => this.withWidget(w, () => true),
isVisible: (w) => this.withWidget(w, () => true),
});
}

override registerToolbarItems(toolbar: TabBarToolbarRegistry): void {
super.registerToolbarItems(toolbar);
toolbar.unregisterItem(TerminalCommands.SPLIT.id);
}

private withWidget<T>(
widget: Widget | undefined,
fn: (widget: TerminalWidget) => T
): T | false {
if (widget instanceof TerminalWidget) {
return fn(widget);
}
return false;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { injectable } from '@theia/core/shared/inversify';
import { TerminalWidgetImpl as TheiaTerminalWidgetImpl } from '@theia/terminal/lib/browser/terminal-widget-impl';
import debounce from 'p-debounce';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I noticed that in most files in the project we're using lodash.debounce, while only in one other file than this one we are using p-debounce. Maybe it makes sense to stick to one of them and remove a dependency from the project.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for noticing it; I did not. It's because the change is the "cherry-pick" of the upstream fix, which uses p-debounce. See here: eclipse-theia/theia@6ab16d5#diff-da3ea75041150eb2403247c5ed84542210774c326c0e3b334029f4e3afb51fc0R45.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.


// Patch for https://github.com/eclipse-theia/theia/pull/12587
@injectable()
export class TerminalWidgetImpl extends TheiaTerminalWidgetImpl {
private readonly debouncedResizeTerminal = debounce(
() => this.doResizeTerminal(),
50
);

protected override resizeTerminal(): void {
this.debouncedResizeTerminal();
}

private doResizeTerminal(): void {
const geo = this.fitAddon.proposeDimensions();
const cols = geo.cols;
const rows = geo.rows - 1; // subtract one row for margin
this.term.resize(cols, rows);
}
}
Loading