Compare commits

..

554 Commits

Author SHA1 Message Date
Akos Kitta
f34f594653 Use 0.16.0 CLI. Bumped version to 2.0.0-beta.2
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-02-15 14:37:27 +01:00
Akos Kitta
1dc7a89dd9 ATL-935: Better support for opening large projects
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-02-12 13:06:11 +01:00
Akos Kitta
1280a344a7 ATL-806: Fixed always_export_binaries CLI config
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-02-12 13:06:11 +01:00
Akos Kitta
f1c80041fe GH-432: Made compile/verify work on dirty editors
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-02-12 13:06:11 +01:00
Akos Kitta
ec1abcc989 Fixed the build status badge in the main README.
Closes arduino/arduino-ide#7

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-02-12 13:06:11 +01:00
Akos Kitta
1c03d12165 GH-423: Do not copy copyright from about dialog
Closes arduino/arduino-pro-ide#423

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-02-12 13:06:11 +01:00
Akos Kitta
9180f4e378 Removed the 'Beta' status from title and about.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-02-12 13:06:11 +01:00
Akos Kitta
516c79276c GH-430: Fixed 'Close' confirmation is ignored.
Updated to lates Theia: `1.11.0-next.c9db9754`.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-02-12 13:06:11 +01:00
Akos Kitta
e639d7da06 GH-422: Changed the default verbose mode.
From now on, compile/upload is not verbose.

Closes arduino/arduino-pro-ide#422.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-02-12 13:06:11 +01:00
per1234
754097877b Make the example values in the bug report template more relevant
The bug report template provides some example values for OS and version. The previous examples were completely
irrelevant to this project due to using an unsupported OS and a different versioning scheme. This might cause confusion,
or at least seem odd, to the contributor.
2021-02-11 23:21:57 -08:00
per1234
b847cff615 Add issue templates
At the first step of creating an issue, a menu of issue types will be presented:

- Bug report
- Feature request
- Report a security vulnerability

If one of the first two are selected, the issue body field will be pre-filled with the template Markdown.

"Report a security vulnerability" will take them to Arduino's global security disclosure policy, which provides further guidance.

If none of the categories in the issue type chooser are applicable, the "Open a blank issue." link at the bottom of the
page can be selected, which will provide the non-templated issue creation experience.

These templates are copies of https://github.com/arduino/arduino-pro-ide/tree/master/.github/ISSUE_TEMPLATE
2021-02-11 23:21:57 -08:00
Akos Kitta
b3deb2fd34 Aligned workflow/docs with the default branch name
This is required after switching the default from `master` to `main`.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-02-11 15:12:23 +01:00
Sebastian Romero
b2641f56be Remove underscore from product name 2021-02-11 11:03:36 +01:00
Akos Kitta
ba8885c8c8 ATL-938: Added menu group categories.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-02-11 09:59:46 +01:00
Akos Kitta
3e92567d52 GH-421: Cleaned up the _Output_ channel UI.
- Merged the Arduino channels into one,
 - Removed the channel selector dropdown from the UI.

Closes arduino/arduino-pro-ide#421.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-02-11 09:59:46 +01:00
Akos Kitta
19613de1b4 ATL-936: Fixed the theme dropdown in the settings.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-02-11 09:59:46 +01:00
Akos Kitta
01ef138d9a ATL-551: Removed the _Advanced Mode_ toggle.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-02-11 09:59:46 +01:00
Akos Kitta
39b8a602c7 [UX]: Fixed button styles with the HC theme.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-02-11 09:59:46 +01:00
Akos Kitta
57c50fefe3 ATL-885: Refined the 'Close' behavior.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-02-11 09:59:46 +01:00
Akos Kitta
23877f162c ATL-879: Avoid reopening the same sketch.
Instead of reopening it, focus the existing window.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-02-11 09:59:46 +01:00
Akos Kitta
96f0722d56 Removed the arduino-debugger-extension extension
We use the `cortex-debug` VSX.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-02-11 09:59:46 +01:00
Sebastian Romero
48c6c53b9b Add rebranded icons 2021-02-11 09:59:46 +01:00
Akos Kitta
b8647f16ad Renamed the application. Updated links and version
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-02-11 09:59:46 +01:00
Akos Kitta
cfe9e8ec95 Bumped version to 0.1.4. Use CLI 0.15.2.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-02-11 09:59:46 +01:00
Akos Kitta
291179489f Reenabled the nightly build.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-02-03 18:33:44 +01:00
Akos Kitta
71cfa06fc2 ATL-878: Fixed boards dropdown with the HC theme.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-02-03 17:44:36 +01:00
Akos Kitta
68b1f8d4f2 Implemented the Network tab.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-02-03 17:44:36 +01:00
Akos Kitta
e957ac4331 ATL-74: Added Export compiled Binary.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-02-03 17:44:36 +01:00
Akos Kitta
b65867d2f4 ATL-58: Archive sketch.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-02-03 17:44:36 +01:00
Akos Kitta
a8e60698a8 ATL-836: Implemented 'Add File...'.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-02-03 17:44:36 +01:00
Akos Kitta
52b0fd35a3 ATL-93: Added Support for .pde sketch file format.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-02-03 17:44:36 +01:00
Akos Kitta
b1ab6df8b7 Reimplemented sketchbook watcher.
Moved it to the frontend.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-02-03 17:44:36 +01:00
Akos Kitta
911875665d Do not bail when wiping the temp sketch has failed
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-02-03 17:44:36 +01:00
Akos Kitta
113fe38850 Fixed the Views menu registration.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-02-03 17:44:36 +01:00
Akos Kitta
770e0b592a Log sketchbook watch.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-02-03 17:44:36 +01:00
Akos Kitta
79bf0a123f Fixed the C++ extension download link.
It was a 404 due to some changes in Open VSX.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-02-03 17:44:36 +01:00
Akos Kitta
8eaf03a299 Fixed the app packager on Windows.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-02-03 17:44:36 +01:00
Akos Kitta
f36d261dcd [debug]: No await for the watcher in sketchbook.
This seems to block the workspace init on Windows in bundled electron.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-02-03 17:44:36 +01:00
Akos Kitta
a99093624f Updated to 0.15.0-rc1 CLI and 12.x snapshot clangd.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-02-03 17:44:36 +01:00
Akos Kitta
1f544b2656 ATL-546: Added UI for settings.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-02-03 17:44:36 +01:00
Akos Kitta
1742c53015 ATL-812: Enhanced the Help menu.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-01-26 14:07:07 +01:00
Akos Kitta
e33af0d78a Use init instead of dump for config fallback.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-01-26 14:07:07 +01:00
Akos Kitta
24dfffa976 ATL-835: Support for JSON file type.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-01-26 14:07:07 +01:00
Akos Kitta
6626701bc9 ATL-815: Implemented Open Recent.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-01-26 14:07:07 +01:00
Akos Kitta
66b711f43c Made the CLI schema validation bit more relaxed.
Both `metrics` and `telemetry` are generated by `config dump`.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-01-26 14:07:07 +01:00
Akos Kitta
c6b125011e ATL-814: Show boards and ports under Tools menu.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-01-26 14:07:07 +01:00
Akos Kitta
f6b5dd24e2 Patched the Theia menu factory.
eclipse-theia/theia#8977

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-01-26 14:07:07 +01:00
Akos Kitta
14919bba1b Fixed whitespace issue in About dialog.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-01-26 14:07:07 +01:00
Akos Kitta
0b89cc4a3b Updated to the HEAD CLI.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-01-26 14:07:07 +01:00
Akos Kitta
284181b874 ATL-811: Removed Run menu item from the app menu
It came from the `@theia/debug` extension.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-01-26 14:07:07 +01:00
Akos Kitta
db2967084f Added the Sketchbook menu with FS event tracking
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-01-18 13:22:38 +01:00
Akos Kitta
1b6d9eccdc Disabled the CRON (nightly build) job.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-12-17 17:32:51 +01:00
Akos Kitta
258b1e903e GH-393: Do not use clangd from the $PATH.
Closes: arduino/arduino-pro-ide#393

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-12-15 12:43:11 +01:00
Akos Kitta
00a3ee34c8 Added a script to update the versions.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-12-14 15:33:06 +01:00
Akos Kitta
f1bffaab2d Fixed Save As when overwriting existing sketch.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-12-11 12:56:27 +01:00
Akos Kitta
3191a09562 [ci]: Fixed the GH release action.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-12-10 20:15:40 +01:00
Akos Kitta
40905a058c Bumped version to 0.1.3.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-12-10 16:41:01 +01:00
Akos Kitta
e7b1a27401 ATL-730: Refactored the debug extension.
Wired in the `cortex.debug` VSXE.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-12-10 16:41:01 +01:00
Akos Kitta
4d5a046aa8 Switched to the '0.14.0' CLI.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-12-10 16:41:01 +01:00
Akos Kitta
c024a8d3d1 ATL-750: Handle board name change after install.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-12-10 16:41:01 +01:00
Akos Kitta
7696e2c4c9 ATL-723: Show the build time in the about dialog.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-12-10 16:41:01 +01:00
Akos Kitta
1acf13c397 ATL-732: Support for static splash screen.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-12-10 16:41:01 +01:00
Akos Kitta
cff2c95684 ATL-667: Warn the user when could not save sketch.
- Log the PID of the backend process.
 - Aligned the dev startup mode with the production: `--no-cluster`.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-12-10 16:41:01 +01:00
Akos Kitta
1a531db0b7 Disabled the badge decoration in the Explorer.
Ref: eclipse-theia/theia#8709
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-12-10 16:41:01 +01:00
Akos Kitta
2e00e2db35 Added a workaround for Theia's auto-save issue.
Ref: eclipse-theia/theia#8722
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-12-10 16:41:01 +01:00
Akos Kitta
ca1b288706 ATL-667: Show dirty indicator on unclosable widget
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-12-10 16:41:01 +01:00
Akos Kitta
41eeb337f9 ATL-675: Use the upstream GH Action for the upload
Ref: svenstaro/upload-release-action#25
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-11-17 08:26:52 +01:00
per1234
39b2e49edb Add EULA to Windows interactive installer
Reference: https://www.electron.build/configuration/nsis#NsisOptions-license
2020-11-13 01:05:55 -08:00
Akos Kitta
138afbf7fd ATL-469: Fixed various serial-monitor issues.
- Fixed a monitor reconnecting issue after upload.
 - Serial monitor connection was not disposed when the widget was closed
from the toolbar with the magnifier (🔍) icon. It worked only iff the
user closed the view with the `X`.
 - This commit also fixes a warning that was related to the incorrect focus
handling of the widget.
 - Switched to `board list -w` instead of polling.
 - Added a singleton for the board discovery to spare the CPU.
 - Fixed DI scopes on the backend. Each frontend gets its own service.
 - Switched to the `20201112` nightly CLI.
 - Fixed the Monitor view's image when the view is on the side-bar.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-11-12 18:53:58 +01:00
Akos Kitta
01e42dafde ATL-666: Added graphics for the Windows installer.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-11-12 11:53:00 +01:00
Akos Kitta
2831acc5b5 ATL-530: No checks before upload/verify/burn
Made the port/fqbn/programmer optional for upload, verify,
and burn bootloader. From now on, the IDE does not warn the user before
performing the desired CLI command.

Closes arduino/arduino-pro-ide#364

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-11-06 10:20:52 +01:00
Akos Kitta
acbb7d32b2 ATL-428: Fixed the semver ordering for installable
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-11-06 10:20:52 +01:00
Akos Kitta
781747fe80 Fixed the application name on macOS.
Patch for eclipse-theia/theia#8701.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-11-06 10:20:52 +01:00
Akos Kitta
874c3efa2c ATL-663: Indicate alpha status. Updated the About dialog.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-11-06 10:20:52 +01:00
Akos Kitta
7b364ebe60 Use the CLI API from the 20201104 nightly.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-11-06 10:20:52 +01:00
Akos Kitta
a96449f557 ATL-658: IDE can use any pinned version of CLI.
- Pinned the CLI to the `20201104` nightly.
 - Updated the TS/JS API generator to fall back to forks if configured.
 - Updated the CLI JSON schema.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-11-06 10:20:52 +01:00
per1234
c78e474790 Fix certificate check CI workflow's crontab
An error in the crontab configuration resulted in the `schedule` event triggered workflow running every 6-9 minutes (the minimum interval GitHub Actions provides) for the duration of every tenth hour.

The updated crontab causes the workflow to run once every 10 hours, as intended.
2020-10-26 02:39:14 -07:00
Akos Kitta
30136b0ef2 Capture and swallow unhandled SIGPIPE signal.
To be able to work around the backend process crash and offline status.

Ref: eclipse-theia/theia#8660
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-10-23 09:05:11 +02:00
per1234
53b06aef67 Add workflow to check for problems with certificates
If the macOS or Windows signing certificates fail verification, a notification will be posted on the #team_tooling Slack channel.

If the certificates expire in less than 30 days, a notification will be posted on the #team_tooling Slack channel.
2020-10-22 07:59:49 -07:00
per1234
6535c70686 Add signed MSI package to the "Arduino Pro IDE" workflow 2020-10-20 14:19:04 -07:00
per1234
6ff58ebe7c Use the windows-latest runner in the Arduino Pro IDE workflow
It was previously required to use the `windows-2016` runner to build Arduino Pro IDE. That is no longer necessary and
Windows signing fails when using that runner.
2020-10-20 14:19:04 -07:00
per1234
7068b9b1d3 Add signed Windows installer package to the "Arduino Pro IDE" workflow
The previous "zip" Windows package is retained, but an installer is also produced.
2020-10-20 14:19:04 -07:00
Akos Kitta
e755a1cd7e Aligned the electron app to the latest Theia APIs.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-10-12 16:28:07 +02:00
Akos Kitta
def93ea32f GH-354: Moved the Outline to the left-hand side.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-10-12 16:28:07 +02:00
Akos Kitta
5f5193932f ATL-374: Refactored the Output services.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-10-12 16:28:07 +02:00
Akos Kitta
f26dae185b ATL-222: Moved the language feature to a VS Code extension.
Updated to next Theia: 1.6.0-next.b43a1623.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-10-12 16:28:07 +02:00
Akos Kitta
fbebfc7cca Use 0.13.0 CLI. Updated version to 0.1.2.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-09-14 14:14:37 +02:00
Akos Kitta
c3eb3e4622 arduino/arduino-pro-ide#337: Use bigger min window
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-09-10 10:45:38 +02:00
Akos Kitta
30421f0de4 Enabled file logging for the backend process.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-09-10 10:45:38 +02:00
Akos Kitta
daa25794ef Better error handling when killing the BE process.
Catch the ESRCH error when terminating non-existing backend process.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-09-10 10:45:38 +02:00
Akos Kitta
ec8df37c2d Fixed the output channel registry for extensions.
See: eclipse-theia/theia#8122

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-09-10 10:45:38 +02:00
Akos Kitta
cb24571eeb Customized channel to cancel the queue on dispose.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-09-10 10:45:38 +02:00
Akos Kitta
2f8e28b296 Patched the menu ordering. (Workaround for eclipse-theia/theia#8377)
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-09-07 13:42:11 +02:00
Akos Kitta
524fbbdf40 arduino/arduino-pro-ide#336: Fixed 'Save As...'
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-09-07 13:42:11 +02:00
Akos Kitta
7a37aa2e2f ATL-78: Implemented include library.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-09-07 13:42:11 +02:00
Akos Kitta
56ff86629c ATL-73: Added library examples to the app.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-09-07 13:42:11 +02:00
Akos Kitta
1c9fcd0cdf ATL-302: Added built-in examples to the app.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-09-07 13:42:11 +02:00
Akos Kitta
b5d7c3b45d ATL-61: Implemented burn bootloader.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-09-07 13:42:11 +02:00
Akos Kitta
525e688d70 Use git log as of the body for the GH release.
There is no need to prepend any other info to the release body.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-09-04 13:12:41 +02:00
Akos Kitta
d7f4d0c18e Fixed the tag name of the GH releases.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-09-04 13:12:41 +02:00
Akos Kitta
6ae7404092 ATL-439: Create the GH release in the public repo.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-09-02 21:05:46 +02:00
Akos Kitta
6b1b9c0524 Use docker://plugins/s3 action for the S3 upload
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-09-02 21:05:46 +02:00
Akos Kitta
717db95c90 ATL-424: Generate a changelog for the nightlies.
Configure generated changelog output from `changelog` job so it can be used in the `release` job of the workflow

It is necessary to define job outputs to make them accessible via the `needs` context in other jobs.

Reference: https://docs.github.com/en/actions/reference/workflow-syntax-for-github-actions#jobsjob_idneeds

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-09-02 21:05:46 +02:00
Akos Kitta
7536c3a485 ATL-423: Can execute the nightly manually.
We consider a build as nightly, if was started by the
CRON job, or was manually triggered from the master
branch.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-09-02 21:05:46 +02:00
Akos Kitta
ec7df884ee Merge pull request #143 from bcmi-labs/0.1.1
0.1.1
2020-08-26 16:22:34 +02:00
Akos Kitta
24b6d84d27 Updated the CLI to 0.12.1.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-26 15:23:24 +02:00
Akos Kitta
4435696949 Updated the versions from 0.1.0 to 0.1.1.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-26 15:13:04 +02:00
Akos Kitta
6aa3ff8044 Merge pull request #141 from bcmi-labs/arduino/arduino-pro-ide#311
GH-311: Fixed FS path to URI conversion issue.
2020-08-25 18:10:10 +02:00
Akos Kitta
4b44113f2c GH-311: Fixed FS path to URI conversion issue.
Instead of passing the FS path (`string`) to the `LoadSketch` method,
we have to convert it into a proper URI string.

Closes arduino/arduino-pro-ide#311

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-25 16:03:49 +02:00
Akos Kitta
c6ad0f582a Merge pull request #139 from bcmi-labs/build-on-ubuntu
Added steps to build the app from source
2020-08-24 20:37:27 +02:00
Akos Kitta
4b8b468e53 Added steps to build the app from source
Verified on 18.04.4

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-24 18:52:25 +02:00
Akos Kitta
ba319b23d9 Merge pull request #133 from bcmi-labs/per1234/name-snapshot-archive-with-commit
Use short commit hash in "snapshot" build artifact archive filename
2020-08-24 16:43:27 +02:00
per1234
70278fed6f Use short commit hash in "snapshot" build artifact archive filename
When you have multiple snapshot builds on your computer for testing purposes, it's difficult to keep track of which is which. The commit hash is shown by the running application, but it's more convenient to have the installation also identified by its folder name.

Adding the short commit hash to the build archive filename (and thus the extracted folder name) provides a clear identifier for each build.

Before this change, the archive is named like:
arduino-pro-ide_snapshot_Linux_64bit.zip

after:
arduino-pro-ide_0.0.7-snapshot.1b8c510_Linux_64bit.zip
2020-08-24 05:12:10 -07:00
Akos Kitta
d5c7d3a8ed Merge pull request #140 from bcmi-labs/0.1.0-rc
0.1.0 rc
2020-08-24 12:45:24 +02:00
Akos Kitta
0ddfa1cfdc Use the 0.12.0 CLI.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-24 11:36:07 +02:00
Akos Kitta
d13a43668e Made the port optional for upload using programmer
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-24 10:27:36 +02:00
Akos Kitta
5f515f0597 fixup: made the Output view not closeable.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-21 17:15:28 +02:00
Akos Kitta
1078f6fa96 Updated the version from 0.0.7 to 0.1.0.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-21 11:51:03 +02:00
Akos Kitta
5ac7fe1446 Use 0.12.0-rc3 CLI.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-21 11:50:22 +02:00
Akos Kitta
0363041b39 Merge pull request #130 from bcmi-labs/cli-0.11.0-rc1-62-g72c9655f
0.0.7 RC build
2020-08-20 16:26:13 +02:00
Akos Kitta
4c4043b73c Updated to 0.12.0-rc2 CLI.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-20 14:45:32 +02:00
Akos Kitta
fc0fe2196f Merge pull request #138 from bcmi-labs/ci--increase-workflow-timeout
Increased the timeout to 90 minutes
2020-08-19 12:50:20 +02:00
Akos Kitta
82a3b01c0b increased the timeout to 90.
notarization can run more than expected, we rely on Apple services.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 12:14:19 +02:00
Akos Kitta
7754cf6334 increased the timeout to 90.
notarization can run more than expected, we rely on Apple services.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 11:30:06 +02:00
Akos Kitta
cb1c16fb26 made the linter happy: removed unused imports
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:52 +02:00
Akos Kitta
d07763a854 Updated to 0.12.0-rc1 CLI.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:52 +02:00
Akos Kitta
f605994d7d fixed duplicate preferences menu item.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:52 +02:00
Akos Kitta
e72e794266 aligned the bindings for windwos.
quit and close.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:52 +02:00
Akos Kitta
ee327eff18 patched to fix the window reloading on windows
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:52 +02:00
Akos Kitta
960d8dba2e removed that uses a more recent version of the CLI from the PATH
from now on, we always use the one from the IDE. Documented how to replace it on demand.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:51 +02:00
Akos Kitta
17de5e1a35 ATL-312: Fixed output resize issue.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:51 +02:00
Akos Kitta
af21f07f84 set the default tab size to 2 spaces.
closes ATL-379.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:51 +02:00
Akos Kitta
2e729fc29e workaround for theia-ide/theia#7828
instead otf reloaading the current window, we open a new one
and close the current.

reloading the current window hangs on electron in Windows env.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:51 +02:00
Akos Kitta
bc4c3e04f5 fixed issue when checking if a sketch is temp
convert all windows drive letters to lower case. [ATL-380]

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:51 +02:00
Akos Kitta
aa2bed8d39 fixed sketch opening. This was the happy path.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:51 +02:00
Akos Kitta
3806d56e94 queued the menu updates.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:51 +02:00
Akos Kitta
f0015e3fb4 ignored out failing port is in use tests.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:51 +02:00
Akos Kitta
650230a571 refined open logic when sketch name is invalid
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:51 +02:00
Akos Kitta
aadd403cdb refined label provide for unsaved sketches
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:51 +02:00
Akos Kitta
6da702abd5 styled the sketch-control
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:51 +02:00
Akos Kitta
4cad068e8d styled the sketch control.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:51 +02:00
Akos Kitta
bb705620c0 made the editor focusing a bit more relaxed at startup.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:51 +02:00
Akos Kitta
e36e42910c fixed delete -> cancel
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:51 +02:00
Akos Kitta
a49ba05d5e wipe the entire sketch when deleting the main file
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:51 +02:00
Akos Kitta
b87782ed05 re-enabled decorators in output.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:51 +02:00
Akos Kitta
e4e6217153 finished the output styling.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:51 +02:00
Akos Kitta
bcc715e11c [theme]: made the output stylable.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:51 +02:00
Akos Kitta
7f0bdfd45e check if we need output adjustments.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:51 +02:00
Akos Kitta
efd1be3e85 wipe original after sketch rename.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:51 +02:00
Akos Kitta
eb2161cc6e changed the default ref behavior.
instead of opening the widget next to current, open it after the last.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:51 +02:00
Akos Kitta
9ee5fc097c fixed closeable state.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:51 +02:00
Akos Kitta
f375202c5d set focus on main sketch.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:51 +02:00
Akos Kitta
fc09dc3613 aligned api visibility with theia.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:51 +02:00
Akos Kitta
3d55aaa875 generalized which widgets are closeable.
instead of a whitelisting, we blacklist the files those belong to sketch

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:51 +02:00
Akos Kitta
fc866464ad removed unused code.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:51 +02:00
Akos Kitta
ada0f4c7ed aligned rename with the java IDE.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:51 +02:00
Akos Kitta
111ba7fef3 allow multiple dots.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:51 +02:00
Akos Kitta
1f7e06f990 aligned new file creation to the java ide.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:51 +02:00
Akos Kitta
f503ef0fcf [revert]: skip the failing daemon test on win32.
it's with the latest CLI. Some error message must have changed.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:51 +02:00
Akos Kitta
43abbf6fb8 removed the YAML extension from the app
See: arduino/arduino-pro-ide#293
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:51 +02:00
Akos Kitta
5aae800a4e when switching serial monitor on/off
open/dispose the monitor widget instead of toggling it.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:51 +02:00
Akos Kitta
a2b3d9b314 zen mode for the output
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:51 +02:00
Akos Kitta
06c3015158 updated to 1.14.0 theia.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:51 +02:00
Akos Kitta
8ab70f48f8 fixed save-as. added sketchload
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:51 +02:00
Akos Kitta
528f4150d3 ATL-318: Fixed monitor reconnection after upload
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:51 +02:00
Akos Kitta
696048b5d9 do not reveal the output for daemon messages
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:51 +02:00
Akos Kitta
722f8d7534 programmer was removed from compilereqSigned-off-by: Akos Kitta <kittaakos@typefox.io> 2020-08-19 10:50:51 +02:00
Akos Kitta
4a9a975dca ATL-301: Made port optional when using programmer
When uploading using a programmer, the port is ignored by the CLI.
Also removed `programmer` from compile request [arduino/arduino-cli#861]

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:51 +02:00
Akos Kitta
6661f661c7 Updated to 0.11.0-rc1-62-g72c9655f CLI.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:51 +02:00
Akos Kitta
a54c860dbb dispose the tool ouput when the window closes.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-08-19 10:50:51 +02:00
Akos Kitta
84016f4e1e Merge pull request #136 from bcmi-labs/per1234/sign-in-gh-hosted-runner
Use GitHub hosted macOS GitHub Actions runner instead of self hosted runner
2020-08-19 10:47:46 +02:00
per1234
fd2b03e286 Use GitHub hosted macOS GitHub Actions runner instead of self hosted runner
The self hosted runner was used because the electron-builder signing process was hanging when the workflow was run on the GitHub hosted macOS runner. Now that the electron-builder signing certificate import procedure can be used, the GitHub hosted runner can be used without any problems so there is no longer any need for a self hosted runner.
2020-08-17 09:22:39 -07:00
per1234
ce58590c0e Use electron-builder to import macOS signing certificate
The previous certificate import system causes electron-builder's code signing process to hang when the GitHub hosted macOS runner is used.

electron-builder has a built-in system for importing the code signing certificate into the keychain. This requires the certificate to have been exported using a specific procedure, which is described vaguely in the electron-builder documentation:

https://www.electron.build/code-signing

And more thoroughly in this article:

https://www.kencochrane.com/2020/08/01/build-and-sign-golang-binaries-for-macos-with-github-actions/#exporting-the-developer-certificate

The "KEYCHAIN" secret that was previously in use was apparently produced by some other procedure. The use of that secret results in a "security: SecKeychainItemImport: Unknown format in import." error during the electron-builder's certificate import process. The APPLE_SIGNING_CERTIFICATE_P12 secret was generated by following the instructions in the article at the link above and works fine with the electron-builder certificate import system.
2020-08-17 09:22:39 -07:00
Akos Kitta
1b8c510f33 Merge pull request #128 from bcmi-labs/external-programmer
[ATL-119]: Rework the menu organization for IDE 2.0, [ATL-75]: External programmer
2020-07-23 16:13:18 +02:00
Akos Kitta
5d8fbcd437 patched the electron-maindropped -psn arg on macOS.Signed-off-by: Akos Kitta <kittaakos@typefox.io> 2020-07-23 08:55:56 +02:00
Akos Kitta
747f5d6a14 fixed the save-as contribution.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-22 16:08:13 +02:00
Akos Kitta
d9f4adfb78 fixed menu updater.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-22 14:32:35 +02:00
Akos Kitta
d51bf9fb40 warn when uploading with programmer but not set
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-22 13:54:17 +02:00
Akos Kitta
f4097b5b24 upload with programmer when it's explicitly asked
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-22 13:16:43 +02:00
Akos Kitta
491e0cb6d0 fixed the current editor issue.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-22 12:06:33 +02:00
Akos Kitta
e95f00466f disabled linter errors.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-22 11:54:20 +02:00
Akos Kitta
e1f74d94a7 fixed hoisting. updated to next Theia.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-22 11:54:04 +02:00
Akos Kitta
01c21266e5 filter out no match.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-22 11:45:32 +02:00
Akos Kitta
8aa08cbf6e fixed fuzzy. added proper boost.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-22 11:33:28 +02:00
Akos Kitta
fdc5814e66 make sure the sketch file has the focus after the ws open.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-21 20:44:37 +02:00
Akos Kitta
87b383f57e use programmer id for upload/verify
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-21 20:12:51 +02:00
Akos Kitta
cc76f2bbc8 clear the output before upload/verify
use the same channel for stdout and and stderr

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-21 19:52:59 +02:00
Akos Kitta
deea43008d toast compile/verify
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-21 19:40:02 +02:00
Akos Kitta
42d2285fa8 style outline.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-21 19:39:49 +02:00
Akos Kitta
8b27cd7bb9 switch to the corresponding channel on message.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-21 19:34:43 +02:00
Akos Kitta
230bacfd01 fix sketch uri issue.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-21 18:49:23 +02:00
Akos Kitta
e1d86d0bda fixed the programmer menu.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-21 18:20:19 +02:00
Akos Kitta
e77c9721cd init: programmers
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-21 17:39:22 +02:00
Akos Kitta
07692fe368 removed unused injection.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-21 12:46:39 +02:00
Akos Kitta
3465407b5a fixed too early disposal when hiding context menu
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-21 12:46:02 +02:00
Akos Kitta
89c348baac styled the sketch control contribution.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-21 11:41:57 +02:00
Akos Kitta
824d1df4bd aligned the title with the Java IDE.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-21 10:54:31 +02:00
Akos Kitta
445ffedf02 patched the keybinding registry
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-21 09:31:45 +02:00
Akos Kitta
bbf880d187 redesigned the settings menu group.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-20 22:02:54 +02:00
Akos Kitta
12a13b869c added sketch control.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-20 19:28:27 +02:00
Akos Kitta
271b06d98a Added quit app for windows and linux
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-20 17:20:38 +02:00
Akos Kitta
587eb87416 added quit app.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-20 17:09:23 +02:00
Akos Kitta
2f8ac44152 fixed the issue with the terminal.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-20 16:59:06 +02:00
Akos Kitta
47fb5105c5 removed unused styles.
for the output we use a monaco editor.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-20 16:44:38 +02:00
Akos Kitta
673c61506e GH-262: Added workaround for duplicate board names
Non-unique board names per core caused an issue in the boards config.

Closes: arduino/arduino-pro-ide#262
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-20 15:40:58 +02:00
Akos Kitta
79a5d2272f fixed grpc client issue with the CLI config.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-20 15:38:49 +02:00
Akos Kitta
537291b494 Pulled in @theia/preferences, removed @theia/cpp
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-20 14:24:17 +02:00
Akos Kitta
23450ce863 removed auto-save.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-20 13:58:47 +02:00
Akos Kitta
c9dfc68911 no validation when appending core settings to fqbn
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-20 12:11:20 +02:00
Akos Kitta
0ee9d16b40 fuzzy board search.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-20 11:29:05 +02:00
Akos Kitta
2f3fe27da3 Port: is.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-20 10:30:21 +02:00
Akos Kitta
dfed2350bd pimped the status bar: boards+port. Fixed HC theme
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-20 10:28:50 +02:00
Akos Kitta
a74b159366 renamed customization folder to theia.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-18 21:09:08 +02:00
Akos Kitta
5788ca3761 aligned items under tools.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-18 21:02:46 +02:00
Akos Kitta
5d23cb5270 Implemented font size mod.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-18 20:57:15 +02:00
Akos Kitta
95dfd3920c aligned tools and sketch menu. added auto-format
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-18 18:08:24 +02:00
Akos Kitta
89faa9d45c Open in external.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-18 18:00:26 +02:00
Akos Kitta
42d5a08c3b cloned the editor menu.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-18 17:30:54 +02:00
Akos Kitta
88631a318b aligned track to current theia.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-18 15:54:08 +02:00
Akos Kitta
540a6215e4 implemented a few more edit contributions.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-18 15:43:55 +02:00
Akos Kitta
c0cadf2b9b comment/uncomment line
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-18 14:57:25 +02:00
Akos Kitta
939a905a6b go to line.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-18 14:43:46 +02:00
Akos Kitta
33af9b6005 implemented copy to forum.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-18 14:22:54 +02:00
Akos Kitta
e0d4634f32 cleaned up save group.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-18 13:59:52 +02:00
Akos Kitta
83e074e895 aligned module names.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-18 13:35:50 +02:00
Akos Kitta
7873e492d4 fixed close sketch
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-18 13:34:36 +02:00
Akos Kitta
e8c3abd2ec Resrtuctured browser code.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-18 12:51:07 +02:00
Akos Kitta
3a6b2f2bc8 More refactoring. Splitting up code.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-17 18:04:38 +02:00
Akos Kitta
cfde197198 Use CLI 0.11.0.
- LS does not work,
 - Cannot reconnect to the daemon on browser refresh.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-17 16:23:45 +02:00
Akos Kitta
20f44fe072 more refactoring.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-17 16:10:02 +02:00
Akos Kitta
5abfc2c1aa chopped up the FE contribution
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-17 15:00:49 +02:00
Akos Kitta
b6df6b57a1 Aligned the IDE with gRPC server startup message.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-17 10:21:40 +02:00
Akos Kitta
218aaf64c7 updated to latest Theia, CLI, electron and node 12
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-17 09:41:02 +02:00
Akos Kitta
a0bbfe0b5c init
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-16 16:33:49 +02:00
Akos Kitta
4326c5f9f2 Merge pull request #124 from bcmi-labs/build-on-arm
Documented how to build from sources on ARM Linux.
2020-07-16 14:16:24 +02:00
Akos Kitta
d29141aff6 Made the CLI config closeable in classic mode.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-15 16:30:14 +02:00
Akos Kitta
55ce04fe3f From now on the user can toggle the bottom panel.
It was disabled in classic mode.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-15 16:29:40 +02:00
Akos Kitta
2eab9a0792 Do not automatically reveal the Output view.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-15 16:28:37 +02:00
Akos Kitta
88dcaba3ae From now on, the Output toolbar is visible in classic mode.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-15 16:27:52 +02:00
Akos Kitta
f392ce752d Make sure the files from the sketch folder are opened at startup.
Previously, we opened the files only in classic mode.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-15 16:26:56 +02:00
Akos Kitta
2bd9eef146 Aligned the New and Save As... with the Java IDE.
From now on, sketches are created in the temp folder,
and will be moved to the `directories.user` location
when the user performs a manual `Save`.

A new sketch can be created with the `CtrlCmd+N` binding.

Closes: arduino/arduino-pro-ide#260
Closes: arduino/arduino-pro-ide#261

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-15 16:26:42 +02:00
Akos Kitta
20bd7bcd64 Documented how to build from sources on ARM Linux.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-15 10:44:41 +02:00
Akos Kitta
3082b3d643 Merge pull request #111 from bcmi-labs/debugger_cli_update
[debugger] Added --interpreter mi2 flag
2020-07-15 10:24:13 +02:00
Akos Kitta
18ca84d682 Merge pull request #120 from bcmi-labs/grpc-js
Switched from `grpc` to `@grpc/grpc-js`.
2020-07-13 17:28:02 +02:00
Akos Kitta
16cb2cf88b ATL-240: Fixed the VS Code extensions in the app.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-13 15:06:43 +02:00
Miro Spönemann
e7a134a181 [debugger] Added --interpreter mi2 flag 2020-07-13 14:47:26 +02:00
Akos Kitta
0942ef6450 Switched from grpc to @grpc/grpc-js.
This change is required to be able to support ARM arch
in the future.

 - Fixed the download links for armv7l Linux.
 - Checked in the generated code. [grpc/grpc-node#1497]
 - Made the code generation a manual step.
 - Made the `grpc-tools` dependency optional.
 - From now on, the serial port regex is case-insensitive.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-13 13:30:06 +02:00
Akos Kitta
68f95ae5b4 Merge pull request #123 from bcmi-labs/arch-doc
Documented basic architecture overview.
2020-07-09 20:21:43 +02:00
Akos Kitta
976f858c7c Documented basic architecture overview.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-09 16:10:31 +02:00
Akos Kitta
ee196bfc3a Merge pull request #121 from bcmi-labs/fix-build-badge
Fixed the build-badge in the README.
2020-07-09 12:37:41 +02:00
Akos Kitta
8e8a8ac945 Fixed the expected tag prefix.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-09 10:23:02 +02:00
Akos Kitta
2f93af4faa Fixed the build-badge in the README.
- Added the missing link to GH Actions.
 - Fixed  a typo.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-09 09:17:15 +02:00
Akos Kitta
66d29d6155 Merge pull request #119 from bcmi-labs/doc-ci-cd
Updated the documentation.
2020-07-08 14:47:37 +02:00
Akos Kitta
45f06718b4 Updated the documentation.
- [macOS] Removed `zip` target. We need it later for the auto-update.
 - [CI]: From now on, the release tag must not start with `v`.
 - [yarn]: Added steps on how to rebuild the natives from the source.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-08 14:21:06 +02:00
Akos Kitta
08e3731493 Merge pull request #118 from bcmi-labs/release-workflow-fixes
Fixed the version part in the artifact name.
2020-07-07 17:21:59 +02:00
Akos Kitta
bf1351ffdc Fixed the version part in the artifact name.
Removed unused `require`s.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-07 17:02:05 +02:00
Akos Kitta
8da8f2a50e Merge pull request #117 from bcmi-labs/gh_actions_needs
Made the upload and release depend on the build job.
2020-07-07 15:37:27 +02:00
Akos Kitta
5a353ffaa5 Made the upload and release depend on the build job.
- Split up the pipeline to build, publish, and release.
 - Set a 30 minutes build timeout, to avoid macOS signing issues.
 - Removed global envs. `env` cannot be accessed for `if` in jobs.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-07 15:17:01 +02:00
Akos Kitta
951884045c Merge pull request #114 from bcmi-labs/gh-actions
Gh actions
2020-07-03 15:01:49 +02:00
Akos Kitta
6bb852c613 Build on GH Actions. Set up nightly.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-07-03 14:26:17 +02:00
Akos Kitta
d9a866579c Include the VS Code C++ extension in the app.
Closes arduino/arduino-pro-ide#257

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-06-29 13:58:58 +02:00
Akos Kitta
ecce237c6c Updated to Theia 1.4.0-next.a62011a5.
- Aligned the daemon test to latest `js-yaml`.
 - Aligned the TS version with Theia.
 - Resolved a dependency-cycle with `next` Theia.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-06-29 13:58:32 +02:00
Akos Kitta
ae6aec27db Updated the CLI to 0.11.0.
- Adjusted to gRPC API change, and
 - Log the CLI commit only once when generating from protoc.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-06-29 13:19:43 +02:00
Akos Kitta
f6f6cb20de Merge pull request #113 from bcmi-labs/0.0.7
Updated to `0.0.7` after the release.
2020-05-07 09:53:01 +02:00
Akos Kitta
02d1f349ad Updated to 0.0.7 after the release.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-05-07 09:20:34 +02:00
Akos Kitta
f71a266fe3 Merge pull request #112 from bcmi-labs/GH-240
GH-240: Warn if not connected to the Internet
2020-04-27 15:38:06 +02:00
Akos Kitta
d8a742e440 GH-240: Warn if not connected to the Internet.
Make sure the gRPC client initialization is rejected.

Closes #240.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-04-27 14:41:57 +02:00
Akos Kitta
f1fca4d5b3 Updated to 1.1.0-next.bda9ff9d Theia.
Also bumped up the `lerna` dependency as it mysteriously made the
`nsfw` module re-build incorrectly for electron and caused a runtime
error due to missing `lodash.isnumber` dependency.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-04-27 14:37:36 +02:00
Akos Kitta
4732a1d68b Merge pull request #110 from bcmi-labs/ci
0.0.6-alpha RC
2020-04-27 10:43:28 +02:00
Akos Kitta
6ce4143d49 [ci]: Made various changes for the electron app:
- Support for multiple electron targe per platform.
 - Removed packager CLI. Changed the logic we calculate the app name.
 - Fixed various OS-specific tests: stubbed `os`.
 - Restructured the final ZIP formats for Windows and Linux.
 - Added packager tests.
 - Switched from `@grpc/grpc-js` to native `grpc`.
 - Updated the version from 0.0.5 to 0.0.6.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-04-09 08:55:43 +02:00
Akos Kitta
d54a69935e [experimental]: Introduced the Boards Control.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-04-09 08:55:43 +02:00
Akos Kitta
12f2aa35ff Added support for 3rd party core settings.
Closes arduino/arduino-pro-ide#10.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-04-09 08:55:43 +02:00
Akos Kitta
5c16f8d6c9 From now on, monitor widget does not expect EOL.
Otherwise, if client code does not contain `Serial.write('\n')`,
the widget does not show any output.

Closes arduino/arduino-pro-ide#201

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-04-09 08:55:43 +02:00
Akos Kitta
807b2ad424 Support of the CLI config.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-04-09 08:55:38 +02:00
Akos Kitta
c7bf98dfa3 Merge pull request #106 from bcmi-labs/issue192
Fixed Open... dialog
2020-03-27 11:18:07 +01:00
Miro Spönemann
b2d53b1a35 #192: Fixed Open... dialog 2020-03-26 09:39:18 +01:00
Akos Kitta
a9bbf47a59 Merge pull request #107 from bcmi-labs/arduino/arduino-pro-ide#212
Wait when opening all files from a sketch folder.
2020-03-17 16:33:12 +01:00
Akos Kitta
3974f2d8a1 Merge pull request #105 from sbhklr/new-icons
Add new app icons
2020-03-12 21:03:06 +01:00
Akos Kitta
2a2238bb82 Wait when opening all files from a sketch folder.
This commit is a temporary workaround for eclipse-theia/theia#6298.

Closes arduino/arduino-pro-ide#212.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-03-12 14:57:38 +01:00
Sebastian Hunkeler
44504ab916 Add new app icons 2020-03-05 00:33:08 +01:00
Miro Spönemann
8cf019bc07 Updated CLI to v0.9.0 2020-02-26 18:17:37 +01:00
Miro Spönemann
ad4928957e Increased version number to 0.0.5 2020-02-26 17:32:30 +01:00
Roberto Sora
6f6f620ec9 Merge pull request #100 from bcmi-labs/debugger-cli
Debugger implementation based on arduino-cli debug command
2020-02-26 16:46:38 +01:00
Miro Spönemann
b055bd9e41 Workaround for Windows: We cannot use SIGINT to interrupt gdb, so kill the process on disconnect 2020-02-26 16:12:02 +01:00
Miro Spönemann
a6cef7c605 Detect even more error cases 2020-02-26 13:55:12 +01:00
Miro Spönemann
d56962251e Fixed: Commands that are registered to toolbar did not show up in Electron menu 2020-02-26 10:55:03 +01:00
Miro Spönemann
69c7383da8 Update Electron main menu when a toggle button is switched 2020-02-26 09:43:32 +01:00
Miro Spönemann
f6a8dceabc Improved error detection to catch more cases 2020-02-25 15:43:21 +01:00
Miro Spönemann
3ed72de810 Detect errors in spawned process 2020-02-25 14:08:08 +01:00
Miro Spönemann
2d9fa5615b Removed some unused stuff 2020-02-24 15:50:46 +01:00
Miro Spönemann
24bd23b669 arduino/arduino-pro-ide#188: Open Boards and Library manager on first start 2020-02-24 15:27:20 +01:00
Miro Spönemann
1bc996d8d8 Updated to CLI version 0.9.0-rc2 2020-02-24 15:26:35 +01:00
Miro Spönemann
beb529cf15 Removed unused CMSIS code 2020-02-24 15:05:09 +01:00
Miro Spönemann
a72533b208 Added basic support for global and static variables 2020-02-24 14:33:51 +01:00
Miro Spönemann
acf7b6a8da Removed workaround 2020-02-24 10:37:17 +01:00
Miro Spönemann
0445700088 Added 'optimize for debug' option 2020-02-24 10:35:36 +01:00
Miro Spönemann
486f110c80 Added initial commands 2020-02-20 16:53:50 +01:00
Miro Spönemann
a427cf94f1 Created new debug adapter that uses the arduino-cli debug command 2020-02-20 11:39:59 +01:00
Miro Spönemann
bd6a6382f6 Removed C/C++ config with hard-coded paths 2020-02-13 10:19:33 +01:00
Miro Spönemann
887682b9c3 Updated yarn.lock 2020-02-13 10:19:33 +01:00
jbicker
4c63af572e Added debug button to toolbar.
Signed-off-by: jbicker <jan.bicker@typefox.io>
2020-02-13 10:15:12 +01:00
jbicker
40ddd3714b Added signal handlers to kill gdb server.
Signed-off-by: jbicker <jan.bicker@typefox.io>
2020-02-13 10:15:12 +01:00
Miro Spönemann
2855026cec [debugger] Don't allow running more than one debug session 2020-02-13 10:15:12 +01:00
Miro Spönemann
879d5c7cc9 Fixed compile error 2020-02-13 10:15:12 +01:00
Miro Spönemann
8c3fab824f [debugger] Resolve URIs through FileSystem 2020-02-13 10:15:12 +01:00
Miro Spönemann
0f35821d14 Reuse spawnCommand util for more robust command execution 2020-02-13 10:15:12 +01:00
Miro Spönemann
fb50244a29 [debugger] Kill the gdb server on debug adapter process exit 2020-02-13 10:15:12 +01:00
Miro Spönemann
8a78e09c6d Improved error message when spawning commands fails with stderr output 2020-02-13 10:15:12 +01:00
Miro Spönemann
fe3cc1904c Don't use EventEmitter method 'off' introduced in NodeJS 10 (arduino/arduino-pro-ide#182) 2020-02-13 10:15:12 +01:00
Miro Spönemann
828379cdc9 Don't send 'terminated' on 'disconnect' (arduino/arduino-pro-ide#183) 2020-02-13 10:15:12 +01:00
jbicker
576f96a502 Validate workspace/current editor and open file on debug start
Tests whether the current workspace is a sketchfolder and
opens the respective ino file
or whether  the current editor is a ino file.

Signed-off-by: jbicker <jan.bicker@typefox.io>
2020-02-13 10:15:12 +01:00
Miro Spönemann
2ba95947de [debug] Shut down previous session properly before starting a new one 2020-02-13 10:15:12 +01:00
Miro Spönemann
68db44fa49 [debugger] Convert URIs to paths 2020-02-13 10:15:12 +01:00
Miro Spönemann
36ac97d95d Improved creation of default debug configurations 2020-02-13 10:15:12 +01:00
Miro Spönemann
a886a106f5 Improved variable resolution and error handling 2020-02-13 10:15:12 +01:00
Miro Spönemann
1441b685ee Improved error reporting on launch 2020-02-13 10:15:12 +01:00
Miro Spönemann
38ab95973e Updated code to current version 2020-02-13 10:15:12 +01:00
Miro Spönemann
2ffca88c02 Updated versions and yarn.lock 2020-02-13 10:15:12 +01:00
Akos Kitta
2b7bceada0 Updated the packager, included the debug extension
Note, I did not check in `/electron/packager/yarn.lock`.
It should be checked in, see the `master`.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-02-13 10:15:12 +01:00
Christian Weichel
5baf43bf25 Integrate with classic mode and start debugging immediately 2020-02-13 10:15:12 +01:00
Christian Weichel
68ff6acb6a [electron] Added debugger to Electron build 2020-02-13 10:15:12 +01:00
Christian Weichel
76f126b913 Make openocd stop properly 2020-02-13 10:15:12 +01:00
Christian Weichel
ec18cf0dc1 Cleanup 2020-02-13 10:15:12 +01:00
Christian Weichel
8aa356bd6e Automated debug config setup 2020-02-13 10:15:12 +01:00
Christian Weichel
ea5f528ef0 Actual debugging works 2020-02-13 10:15:12 +01:00
Christian Weichel
3d6d2ce814 Ran first debugging session 2020-02-13 10:15:12 +01:00
Christian Weichel
e189a8c33e Add theia/debug to build 2020-02-13 10:15:12 +01:00
Miro Spönemann
2f9ef76cd2 Updated yarn.lock 2020-02-13 07:56:25 +00:00
Akos Kitta
ef74b04b0b Merge pull request #98 from bcmi-labs/theme-update-vol2
Theme update vol2
2020-01-30 14:24:41 +01:00
Akos Kitta
4b859c2db9 Added a workaround for a memory leak.
eclipse-theia/theia#7008

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-01-30 11:31:38 +01:00
Akos Kitta
d53d474243 Disabled the window reload in the bundled app.
This change is a NOOP for the electron application started in dev mode.

Closes arduino/arduino-pro-ide#187

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-01-30 11:31:38 +01:00
Akos Kitta
403fdbfdc0 Removed a few custom colors and derived them from existing ones.
Fixed the color for the:
 - selected items in the Explorer,
 - warning `input`s,
 - set custom dialog background for the Arduino theme,
 - the query term matches in the command palette, and
 - react-select.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2020-01-30 11:31:32 +01:00
Jan Bicker
cbe603a99f Updated Arduino App to new theming system
Signed-off-by: Jan Bicker <jan.bicker@typefox.io>
2020-01-29 11:08:53 +01:00
Miro Spönemann
1d98e79d7b [build] Updated to macOS 10.14 2020-01-27 08:50:14 +01:00
Luca Cipriani
41bf1ce6dc Merge pull request #97 from bcmi-labs/robust_workspace_init
More robust workspace initialization
2020-01-23 11:08:28 +00:00
Miro Spönemann
1aa944b25e More robust workspace initialization: guard against errors creating sketch dir 2020-01-20 16:48:24 +01:00
Miro Spönemann
b220ce4c5f Removed fs-extra dependency again, updated electron build resolution 2020-01-16 16:06:01 +01:00
Miro Spönemann
15c66442cc Use direct dependency instead of dep resolution for fs-extra 2020-01-16 15:31:30 +01:00
pirropirro
3a56c16ab2 Merge pull request #95 from bcmi-labs/pro-ide-142
Align language server spawning with arduino-cli
2020-01-16 11:36:28 +01:00
Miro Spönemann
cea62e315a Added unit test for getExecPath 2020-01-16 11:10:13 +01:00
Miro Spönemann
6618816330 Align language server spawning with arduino-cli 2020-01-16 09:39:43 +01:00
Miro Spönemann
2577451c15 Use latest version of fs-extra due to stack overflow bugs in earlier versions 2020-01-15 17:10:59 +01:00
pirropirro
a1ab42d282 Merge pull request #96 from bcmi-labs/pro-ide-21
Fallback rendering for Boards Manager
2020-01-14 16:27:03 +01:00
Miro Spönemann
8dbcb8bbb6 Fallback rendering in case a BoardPackage with no name or author is found (arduino/arduino-pro-ide#21) 2020-01-14 15:35:44 +01:00
pirropirro
1be76aa264 Merge pull request #93 from bcmi-labs/clangd_linux
Include clangd for Linux
2020-01-14 10:56:32 +01:00
Miro Spönemann
21cd580e41 Use zip target for Linux (see electron-userland/electron-builder#2868) 2020-01-13 09:44:06 +01:00
Miro Spönemann
8839e318f4 Merge pull request #92 from bcmi-labs/arduino-pro-ide_17
Updated keybindings
2020-01-13 09:14:24 +01:00
Miro Spönemann
bef9185c6c arduino/arduino-pro-ide#31: Include clangd for linux with 'bin' and 'lib' folders 2020-01-10 11:02:23 +01:00
Miro Spönemann
b8bd444def Updated keybindings (arduino/arduino-pro-ide#17), restore Output view on Verify / Upload 2020-01-09 16:22:03 +01:00
Miro Spönemann
b8fdb03433 Added script to configure node_gyp (nodejs/node-gyp#1933) 2020-01-08 13:09:22 +01:00
pirropirro
4290497edc Merge pull request #91 from bcmi-labs/fixed_cli_version
Use fixed version 0.7.1 of the cli to avoid future breakage
2020-01-07 11:02:05 +01:00
Miro Spönemann
7a89a8048f Use fixed version 0.7.1 of the cli to avoid future breakage 2020-01-07 10:49:36 +01:00
pirropirro
84be804df0 Update CLI config parsing (v0.7.0) 2020-01-07 10:44:54 +01:00
Miro Spönemann
f07441a7fc Updated clangd to version 9.0.0 2020-01-06 16:25:00 +01:00
Miro Spönemann
08f127711f bcmi-labs/arduino-language-server#17 (workaround for eclipse-theia/theia#6308) 2019-12-17 11:40:33 +01:00
Akos Kitta
d1ae15a838 Updated to the latest CLI config format.
See: arduino/arduino-cli@f2df284
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-12-12 15:11:02 +01:00
Akos Kitta
7ca8830a02 Bumped up from 0.0.3 to 0.0.4.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-12-11 16:23:33 +01:00
Akos Kitta
13b7a7e1d8 Ignore LS logs.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-12-11 16:23:06 +01:00
Akos Kitta
c5c9b8674b Merge pull request #85 from bcmi-labs/arduino/arduino-pro-ide#112
Various serial-monitor fixes for 0.0.4: arduino/arduino-pro-ide#112
2019-12-11 16:18:46 +01:00
Akos Kitta
6447191bf5 [win] Implemented naive reconnecting.
For some reason, port is reported to be busy on Windows.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-12-11 09:40:41 +01:00
Akos Kitta
e78ed85761 [win]: Launch config fixes for Windows.
It is a workaround for eclipse-theia/theia#3590

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-12-10 14:37:10 +01:00
Akos Kitta
9bc520ccf9 Removed unused chance.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-12-10 12:54:01 +01:00
Akos Kitta
cfdb00529c Fixed focus.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-12-10 12:06:16 +01:00
Akos Kitta
8ccea24452 Let the serial monitor connect to unknown boards.
Fixes arduino/arduino-pro-ide#127

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-12-10 12:06:16 +01:00
Akos Kitta
ad563d26ba Re-enabled the build on this branch.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-12-10 12:06:15 +01:00
Akos Kitta
f0a628534e Updated to 0.14.0-next.0159cd5b Theia.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-12-10 12:05:55 +01:00
Akos Kitta
1b95242ad1 forward messages only when connected.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-12-10 12:02:30 +01:00
Akos Kitta
729588770e fixed broken promise when reconnecting on baudRate changes.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-12-10 12:02:30 +01:00
Akos Kitta
6b2046e090 Do not disconnect from the widget, it is done automatically.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-12-10 12:02:30 +01:00
Akos Kitta
80673ad18f Styled the input.
Do not render the widget after a close request.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-12-10 12:02:30 +01:00
Akos Kitta
2f33038695 No disconnect/reconnect when DNDing the widget.
- Updated to next Theia,
 - Added elecron launch config,
 - Yet another syling for the input + selects,
 - Close monitor connection on widget close not detach.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-12-10 12:02:28 +01:00
Akos Kitta
6154d1e8d5 aligned input to the selects.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-12-10 12:02:16 +01:00
Akos Kitta
557ec2ae42 Wait until the boards config has been reset
from the local storage, then start the monitor connection.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-12-10 12:02:16 +01:00
Akos Kitta
8c49c04359 🤞 finalized the monitor UI
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-12-10 12:02:16 +01:00
Akos Kitta
29ebf055e6 Do not re-render the entire widget.
Otherwise the selects do not work.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-12-10 12:02:16 +01:00
Akos Kitta
71842abfa3 Got rid of the send button, use keybinding instead
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-12-10 12:02:16 +01:00
Akos Kitta
ed660ccd64 fixed the input focus when the view is activated
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-12-10 12:02:16 +01:00
Akos Kitta
6af22ec9b8 aligned select height with Theia styles
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-12-10 12:02:16 +01:00
Akos Kitta
79f588d067 Finalized the styling for react-select
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-12-10 12:02:16 +01:00
Akos Kitta
e3e4a96db3 do not show border on focus.
when the list is opened, we have the accent color anyway.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-12-10 12:02:16 +01:00
Akos Kitta
4129544738 generalized the react-select component
so tha we can reuse it all over the application.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-12-10 12:02:16 +01:00
Akos Kitta
a866bde4d1 fixed background style when holding down select
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-12-10 12:02:16 +01:00
Akos Kitta
92b6208a76 aligned core/lib input style with react-select
made the UI slicker by removing any non- :hover, :select borders.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-12-10 12:02:16 +01:00
Akos Kitta
12deceef19 got rid of the border when not focused/selected
it does not remove the border but uses the background of the container.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-12-10 12:02:16 +01:00
Akos Kitta
f635751a8c fix the react-select styling
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-12-10 12:02:16 +01:00
Akos Kitta
85bf50213d Removed more logic from the widget.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-12-10 12:02:16 +01:00
Akos Kitta
5aeb2d388e Flip the auto install buttons.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-12-10 12:02:16 +01:00
Akos Kitta
b6b4c75718 CI skip.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-12-10 12:02:16 +01:00
Akos Kitta
c4a8062df4 Updated to next Theia.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-12-10 12:02:14 +01:00
Akos Kitta
6e89e89738 Fixed layout initialization.
Fixes for eclipse-theia/theia#6688

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-12-10 12:01:54 +01:00
Akos Kitta
c7242ca34f slightly better reconnecting experience.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-12-10 12:01:54 +01:00
Akos Kitta
a4e5e65286 simplified monitor connection API.
we have one connenction per editor anyways.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-12-10 12:01:54 +01:00
Akos Kitta
80549db289 a few bugfixes. updated grpc dependencies.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-12-10 12:01:54 +01:00
Akos Kitta
eb7b3ad683 Reconnect on interrupted system call.
However, we have to figure out why does it happen at all.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-12-10 12:01:53 +01:00
Akos Kitta
9efcbcf2ae [rewrite-me]: initial serial monitor changes
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-12-10 12:01:53 +01:00
Akos Kitta
d22c0b9e55 Merge pull request #90 from bcmi-labs/jx/update-theia
Update Theia and adjust Electron package name
2019-12-10 11:59:45 +01:00
Jan Keromnes
5d2f09354d Adjust Electron package 'name' and 'appId'. 2019-12-10 11:03:01 +01:00
Jan Keromnes
fcd6c792e3 Updated to next (0.14.0-next.0159cd5b) Theia.
Co-authored-by: Jan Keromnes <jan.keromnes@typefox.io>
Co-authored-by: Akos Kitta <kittaakos@typefox.io>

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-12-10 11:02:49 +01:00
Akos Kitta
94233a1a19 Merge pull request #80 from bcmi-labs/0.3.0-rc
All in on PR for 0.0.3
2019-12-09 09:58:59 +01:00
Jan Keromnes
7fb32766ca [doc] Fix a few typos 2019-12-07 09:59:45 +01:00
Akos Kitta
85cf8757c4 Merge pull request #89 from bcmi-labs/jx/document-boards-service
[doc] Document Arduino Pro IDE extension and a few services
2019-12-07 09:50:19 +01:00
Jan Keromnes
41c56c1126 [doc] Document Arduino Pro IDE extension and a few services 2019-12-06 16:03:58 +00:00
Jan Keromnes
4c503c0c5e Merge pull request #86 from bcmi-labs/jx/support-electron-dev
Support running the Electron app in Gitpod for faster code reviews
2019-12-06 11:10:03 +01:00
Jan Keromnes
3f180b6059 [minor] Make the README.md GIFs a bit smaller 2019-12-06 11:07:03 +01:00
Jan Keromnes
6a8a76f720 [minor] Fix project name in README.md 2019-12-06 11:04:01 +01:00
Jan Keromnes
9a27252d91 Support running the Electron app in Gitpod for faster code reviews 2019-12-05 10:26:53 +00:00
Akos Kitta
4e683b237d Made the editors closeable in pro mode.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-11-26 10:33:59 +01:00
Akos Kitta
a2a9cbb02e Fixed a styling issue in the boards select dialog.
Closes: arduino/arduino-pro-ide#137
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-11-26 09:18:46 +01:00
Akos Kitta
dd10436051 Fixed the Platform ordering.
We have to pick the installed version first.
Otherwise we lose the FQBN of the boards.
FBQN is used to check if a board has the corresponding core installed.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-11-26 09:10:01 +01:00
Akos Kitta
e79d42d6bd Updated to next (0.13.0-next.145f9137) Theia.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-11-25 09:16:22 +01:00
Akos Kitta
a9c9dcde7b Fixed a selection bug after installing a core/lib
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-11-22 17:09:45 +01:00
Akos Kitta
62b18ccbed Fixed lib uninstall. Do not log it more than once.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-11-22 17:09:45 +01:00
Akos Kitta
0a8b6bc41e Restart the LS on core install/remove.
Fixes bcmi-labs/arduino-language-server#9

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-11-22 17:09:45 +01:00
Akos Kitta
b1388be5f9 Implemented uninstall.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-11-22 17:09:45 +01:00
Akos Kitta
b4848f62fa Corrected the docs.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-11-22 17:09:45 +01:00
Akos Kitta
f359843635 Fixed the version ordering for libs.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-11-22 17:09:45 +01:00
Akos Kitta
6448b447b3 Resolved a React warning.
Removed the widget update due to an incorrect manual merge.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-11-22 17:09:45 +01:00
Akos Kitta
c7bb3abf19 Updated doc, code style changes.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-11-22 17:09:45 +01:00
Akos Kitta
c3e2aa4feb Generalized the list item renderers.
To support update/downgrade.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-11-22 17:09:45 +01:00
Akos Kitta
63cd2701b4 Simplified code when deceding which CLI to use.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-11-22 17:09:45 +01:00
Akos Kitta
35ac73181b Enabled New Folder in classic mode.
-  Made sure the `Explorer` is visible before raising the input dialog.
 - Removed unused module.

Fixes arduino/arduino-pro-ide#84

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-11-22 17:09:45 +01:00
Akos Kitta
840cde872c Made the editor mode dynamic.Signed-off-by: Akos Kitta <kittaakos@typefox.io> 2019-11-22 17:09:45 +01:00
Akos Kitta
c2008460b0 Fixed storeLayout when toggling the editor mode.
Workaround for eclipse-theia/theia#6579.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-11-22 17:09:45 +01:00
Akos Kitta
435fdcdf7f Adjusted the version numbers.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-11-22 17:09:45 +01:00
Akos Kitta
7e6343e60e Update the ListWidget on list container render.
To recalculate the desired size of the scroll-bar thumb.

arduino/arduino-pro-ide#101

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-11-22 17:09:45 +01:00
Akos Kitta
fdda4a72d0 Initial support for updating/downgrading cores.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-11-22 17:09:45 +01:00
Akos Kitta
7077303a36 Hid the Explorer. Disabled new folder in workspace
when not in `pro-mode`.

Closes arduino/arduino-pro-ide#84.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-11-22 17:09:45 +01:00
Akos Kitta
acd9bf1354 Fixed the editor restoration when toggling mode.
- Do not reset the layout. It messes up the editor's restoration.
 - Close all pro-mode only views when leaving pro-mode.
 - Initialize all views `onStart`. It is a NOOP in normal mode.

Closes arduino/arduino-pro-ide#101

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-11-22 17:09:45 +01:00
Akos Kitta
d92fc25769 Fixed endless loop in the sketch service.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-11-22 17:09:45 +01:00
Akos Kitta
f9a98d708e Removed an unused field.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-11-22 17:09:45 +01:00
Akos Kitta
df33c5689f Gracefully handle disconnected frontends.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-11-22 17:09:45 +01:00
Akos Kitta
2dc73eb3b5 Updated to next (0.13.0-next.83c59134) Theia.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-11-22 17:09:45 +01:00
Akos Kitta
f6444b2570 Update the ListWidget on list container render.
To recalculate the desired size of the scroll-bar thumb.

arduino/arduino-pro-ide#101

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-11-22 17:09:45 +01:00
Akos Kitta
186180800f Increased the z-index of the scroll-bar thumb
to make it visible even with the customized list item `background-color`

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-11-22 17:09:45 +01:00
Jan Keromnes
20bc3c6f13 Merge pull request #81 from bcmi-labs/choose-cli
Only pick `arduino-cli` from the PATH if it's more recent
2019-11-21 14:53:23 +01:00
Jan Keromnes
125ee70fa3 Sort package.json dependencies alphabetically 2019-11-21 10:37:14 +00:00
Jan Keromnes
3cfb1450c0 Only pick arduino-cli from the PATH if it's more recent 2019-11-21 10:37:14 +00:00
Akos Kitta
9643dd397f [doc]: Updated the CI section.
Documented when do we build the electron-based applications.
2019-11-21 11:16:52 +01:00
Akos Kitta
7c1ebf273c Merge pull request #75 from bcmi-labs/25-10-release
Various bug fixes, plus one or two enhancements.
2019-10-28 12:41:29 -04:00
Akos Kitta
05850b5f27 Ensure default data and sketch dir existence.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-10-25 15:13:53 +02:00
Akos Kitta
21dedd4b09 DROPME: disabled the uglification in the bundle.js
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-10-25 14:10:06 +02:00
Akos Kitta
90d7d88162 Updated the application name, version to 0.0.2.
Increased the heap size for the packager.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-10-25 11:48:33 +02:00
Akos Kitta
3efb5a4e08 Switched from execFile to spawn.
So that we can add guards against whitespaces in the path.
Also cleaned up the code a bit.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-10-25 11:48:33 +02:00
Akos Kitta
4353bfb5b9 Updated port discovery to support unknown boards
From now on, we do not retrieve the ports from the attached boards.
A board can be unknown but the port is still relevant.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-10-25 11:48:33 +02:00
Akos Kitta
8971dc4c5f Implemented naive reconnecting.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-10-25 11:48:33 +02:00
Akos Kitta
2be54944bf Fixed the checkmark position in the dropdown.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-10-25 11:48:33 +02:00
Akos Kitta
2f84b5c6b7 Show the CLI version from the about dialog.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-10-25 11:48:33 +02:00
Akos Kitta
cebe15ef69 Removed duplicate log level from the log.
Print CLI version at start-up.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-10-25 11:48:33 +02:00
Akos Kitta
1dda5dd95b Exposed version from the CLI.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-10-25 11:48:33 +02:00
Akos Kitta
de1caf1451 PROEDITOR-46: Added a core auto-installer.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-10-25 11:48:33 +02:00
Akos Kitta
fb6785c5d3 PROEDITOR-53: Changed the way we set the workspace
Got rid of the `sketch` search parameter from the URL.

Rules:
 - Get the desired workspace location from the
  - `Path` defined as the `window.location.hash` of the URL,
  - most recent workspaces,
  - most recent sketches from the default sketch folder.
 - Validate the location.
 - If no valid location was found, create a new sketch in the default sketch folder.

Note: when validating the location of the workspace root, the root must always exist. However, when in pro-mode, the desired workspace root must
not be a sketch directory with the `.ino` file, but can be any existing location.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-10-25 11:48:24 +02:00
Akos Kitta
de1f341d19 Merge pull request #74 from bcmi-labs/remove-tab-context-menu-no-pro-mode
Removed the tab context menu when not in pro-mode.
2019-10-23 10:30:30 +02:00
Akos Kitta
817a28291b Removed the tab context menu when not in pro-mode.
When we are not in `pro-mode`, it does not make much sense to show the
context menu. It does not work anyways.

See: https://arduino.slack.com/archives/CJJHJCJSJ/p1569502896082800?thread_ts=1569489282.073200&cid=CJJHJCJSJ

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-10-23 09:57:56 +02:00
Akos Kitta
06ef598806 Merge pull request #72 from bcmi-labs/azure-service-connection-update
Switched to `typefox-service-account1`.
2019-10-17 10:00:27 +02:00
Akos Kitta
cc6a0ae212 Fixed various electron packager issues
- We have to reuse the `yarn.lock` file for the final app, not just
for the extensions.
 - Simplified the clean-up phase.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-10-17 08:45:26 +02:00
Akos Kitta
65a58ce2be Switched to typefox-service-account1.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-10-16 13:56:40 +02:00
Akos Kitta
6331b7ddfd Merge pull request #65 from bcmi-labs/increase_maxBuffer
Increase maxBuffer for spawned daemon
2019-10-07 16:57:25 +02:00
Miro Spönemann
f3667f0270 Merge pull request #67 from bcmi-labs/restartLSOnBoardChange
Restart the language server when the board is changed
2019-10-04 11:54:13 +02:00
Miro Spönemann
aa4f216544 Restart the language server when the board is changed 2019-10-02 13:16:10 +02:00
Akos Kitta
065f9f042b Merge pull request #66 from bcmi-labs/various-bug-fixes
Various bug fixes
2019-09-26 11:59:23 +02:00
Akos Kitta
765fcdfba7 Fixed the styles for the boards list dropdown.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-09-26 10:15:57 +02:00
Akos Kitta
476e658fea Cleaned up the menu contributions.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-09-26 10:15:30 +02:00
Akos Kitta
a96ed31a45 Fixed the daemon log.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-09-25 16:34:42 +02:00
Miro Spönemann
ed4f23a32a Merge pull request #64 from bcmi-labs/msp_sendBoardConfig
Added JSON-RPC message to send the board configuration to the language server
2019-09-25 09:12:59 +02:00
Akos Kitta
4949df7395 Fixed missing New Sketch menu in electron.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-09-24 16:01:19 +02:00
Akos Kitta
55923be7fd PROEDITOR-48: Open last sketch at start-up
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-09-24 14:23:16 +02:00
Martino Facchin
2ef0d1d0db Increase maxBuffer for spawned daemon
When installed cores are A LOT, core listing needs a lot of space :)
2019-09-23 17:06:10 +02:00
Akos Kitta
7244694bd3 PROEDITOR-47: FIxed the visibility of close button
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-09-20 16:09:58 +02:00
Akos Kitta
d9e71c7e0d PROEDITOR-51: Fixed the styling for toggeled icons
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-09-20 15:39:15 +02:00
Akos Kitta
daedae1ba7 PROEDITOR-50: Customized the editor for built-ins
- From now on, sources from the `dataDir` opened in a read-only editor.
 - Disabled the tab-bar decoration for built-ins.
 - No problem markers for the built-ins.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-09-20 15:10:38 +02:00
Akos Kitta
ac4e877a10 Open More info in the default browser.
Instead of the Electron application.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-09-18 15:37:58 +02:00
Miro Spönemann
09243ff74d Added JSON-RPC message to send the board configuration to the language server 2019-09-18 09:46:07 +02:00
Miro Spönemann
5496edbb42 Merge pull request #62 from bcmi-labs/setup_cpp
Configure cpp extension to use embedded clangd
2019-09-16 13:09:23 +02:00
Miro Spönemann
62eff29172 Configure cpp extension to use embedded clangd 2019-09-16 08:42:30 +02:00
jbicker
2220e66f4b Adapted Dark, Light and Arduino themes
Signed-off-by: jbicker <jan.bicker@typefox.io>
2019-09-11 11:55:29 +02:00
jbicker
c98ec29810 Merge branch 'add-cpp-extension' 2019-09-09 17:33:46 +02:00
jbicker
768958dfd5 Updated Yarn.lock
Signed-off-by: jbicker <jan.bicker@typefox.io>
2019-09-09 17:25:07 +02:00
Jan Bicker
8e747e19a6 CPP extension added. Theia updated.
Signed-off-by: Jan Bicker <jan.bicker@typefox.io>
2019-09-09 17:10:18 +02:00
Miro Spönemann
b1c69aef9f Merge pull request #59 from bcmi-labs/ino-language
Added language support for ino files
2019-09-09 10:28:40 +02:00
Miro Spönemann
ec6b5ed3f3 Added command line argument for specifying cli path 2019-09-06 14:15:59 +02:00
Miro Spönemann
60bf58ac0f Added download script for arduino-language-server 2019-09-06 14:15:59 +02:00
Miro Spönemann
c2675efea4 Fixed z-index of main toolbar 2019-09-06 14:15:59 +02:00
Miro Spönemann
7d04c7efb8 Added language contribution for ino files 2019-09-06 14:14:35 +02:00
Jan Bicker
fb542e2e40 Merge pull request #56 from bcmi-labs/advanced-mode-in-top-panel
Advanced mode in top panel
2019-09-06 13:08:18 +02:00
Jan Bicker
3e0842e93a Merge pull request #54 from bcmi-labs/monitor
Serial Monitor
2019-09-06 13:06:56 +02:00
Jan Bicker
90add23dae Merge pull request #61 from bcmi-labs/file-menu-fix
Fixed file menu
2019-09-06 13:05:18 +02:00
jbicker
6ff5405337 show advanced mode button in top panel
Signed-off-by: jbicker <jan.bicker@typefox.io>
2019-09-04 09:07:57 +02:00
jbicker
c564572718 Fixed file menu, New Sketch and New File items were not shown in main menu
Signed-off-by: jbicker <jan.bicker@typefox.io>
2019-09-03 16:44:50 +02:00
jbicker
79731304c1 Reestablish monitor connection after reloading the window, reconnect after selecting another board
Signed-off-by: jbicker <jan.bicker@typefox.io>
2019-09-03 16:42:00 +02:00
jbicker
2046c0bdee Continue monitoring with last connection if respective board is reconnected
Signed-off-by: jbicker <jan.bicker@typefox.io>
2019-09-03 16:42:00 +02:00
jbicker
3eebd580d8 Fixed wrong toppanel layout in electron
Signed-off-by: jbicker <jan.bicker@typefox.io>
2019-09-03 16:42:00 +02:00
jbicker
d8454456a9 Set focus on send field initially
Signed-off-by: jbicker <jan.bicker@typefox.io>
2019-09-03 16:42:00 +02:00
jbicker
dac9c6437e Preserve baud rate and line ending; Use google protobuf Struct type now for setting configs
Signed-off-by: jbicker <jan.bicker@typefox.io>
2019-09-03 16:42:00 +02:00
jbicker
7f33b62e0b Preserve Autoscroll and Timestamp states
Signed-off-by: jbicker <jan.bicker@typefox.io>
2019-09-03 16:42:00 +02:00
jbicker
459e55a69a Improved serial monitor dropdowns
Signed-off-by: jbicker <jan.bicker@typefox.io>
2019-09-03 16:42:00 +02:00
jbicker
f76f4543e9 Minor code improvements
Signed-off-by: jbicker <jan.bicker@typefox.io>
2019-09-03 16:42:00 +02:00
jbicker
9b255ac072 Timestamp formatted
Signed-off-by: jbicker <jan.bicker@typefox.io>
2019-09-03 16:42:00 +02:00
jbicker
592086466c Clear send field after sending the value
Signed-off-by: jbicker <jan.bicker@typefox.io>
2019-09-03 16:42:00 +02:00
jbicker
c81ee1ede2 Arduino Toolbar Tooltips don't get clipped anymore.
Signed-off-by: jbicker <jan.bicker@typefox.io>
2019-09-03 16:42:00 +02:00
jbicker
6d2816a7f3 Added icon, changed appearance of active toolbar item
Signed-off-by: jbicker <jan.bicker@typefox.io>
2019-09-03 16:42:00 +02:00
jbicker
dd69092afd Added additional toolbar to the right of the toppanel.
Added Toolbar button for toggling serial monitor and tooltips for serial monitor toolbar items.

Signed-off-by: jbicker <jan.bicker@typefox.io>
2019-09-03 16:42:00 +02:00
jbicker
76d0f5a464 Implemented the Widget
Re-introduced bottom panel tabs

Signed-off-by: jbicker <jan.bicker@typefox.io>
2019-09-03 16:40:19 +02:00
Jan Bicker
206b65f138 Merge pull request #58 from bcmi-labs/use-sketch-as-ws
Use sketch folder as workspace
2019-09-03 16:32:08 +02:00
Akos Kitta
6d590cd111 Fixed the packager for the new folder structure.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-09-02 14:57:28 +02:00
Akos Kitta
e8e3c3dc4c Use the latest CLI, as stated in the doc.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-09-02 13:45:36 +02:00
Akos Kitta
e6e042c856 Moved System declaration before its use-site.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-08-30 10:41:05 +02:00
Akos Kitta
9298a8cc55 Log clean-up.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-08-30 10:26:13 +02:00
Akos Kitta
98764b56aa Switched to the JSON log format for the daemon.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-08-30 10:11:43 +02:00
Akos Kitta
9f7aec4091 Adapted to latest CLI.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-08-29 09:52:56 +02:00
Akos Kitta
e636e06a7e Download today's CLI.
The issues was an interim CI problem.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-08-29 09:21:51 +02:00
Akos Kitta
c6311ecb1d Adapted the CLI download script.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-08-29 09:17:44 +02:00
Akos Kitta
cd94608aee Renamed the applications.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-08-29 08:05:47 +02:00
Jan Bicker
b82d5e4f0b Use sketch directory as url param when a new created sketch gets opened
Signed-off-by: Jan Bicker <jan.bicker@typefox.io>
2019-08-28 08:13:11 +00:00
Akos Kitta
9ae721292d Fixed the FS path issue on Windows.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-08-27 18:27:12 +02:00
jbicker
41c603937c Setting download dir to {dataDir}/staging; Create data and sketch folders if they don't exist.
Signed-off-by: jbicker <jan.bicker@typefox.io>
2019-08-26 16:53:59 +02:00
jbicker
d5589c435f Get the default sketchbook path from backend
Signed-off-by: jbicker <jan.bicker@typefox.io>
2019-08-26 15:59:18 +02:00
jbicker
d809daa20a Use sketch folder as workspace
Signed-off-by: jbicker <jan.bicker@typefox.io>
2019-08-26 13:20:01 +02:00
Akos Kitta
f9641a3d76 Initial support of the default paths from the CLI.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-08-26 12:42:27 +02:00
Sven Efftinge
59553bf81f Merge pull request #55 from bcmi-labs/se/better-output
Better output format
2019-08-16 14:00:44 +02:00
Sven Efftinge
037efbaba2 Better output format 2019-08-15 11:50:50 +00:00
Luca Cipriani
a936e4c505 Merge pull request #49 from bcmi-labs/boards-manager
generalized the boards and the libraries views.
2019-08-14 17:34:55 +02:00
Akos Kitta
7c2a295631 Fixed bug when checking if a core is installed
`startsWith` was incorrect: `arduino:samd` Vs. `arduino:samd_beta`

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-08-12 11:40:39 +02:00
Akos Kitta
c5796677f8 Ignore whitespaces when searhing for libs, cores.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-08-12 11:39:02 +02:00
Akos Kitta
b6306c330f Update/download the library_index.json at start
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-08-05 19:42:24 +02:00
Akos Kitta
692c3f6e3f Implemented serial-monitoring for the backend.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-08-05 19:42:24 +02:00
Akos Kitta
8d79bb3ffb restored the the search limit for the lib manager.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-08-05 19:40:25 +02:00
Akos Kitta
ec50ea673c do not await for attached boards.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-08-05 19:40:25 +02:00
Akos Kitta
502e9042ad fine tuned selectedPort update
based on the detached boards.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-08-05 19:40:25 +02:00
Akos Kitta
66f429c478 workaround for non-unique names.
Fine tuned the port unnselection when attached boards change.

This should make sure we do not have to `await` for the attached boards
from the backend.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-08-05 19:40:25 +02:00
Akos Kitta
0dc45daf01 aligned list view styles.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-08-05 19:40:25 +02:00
Akos Kitta
3fcf5a6ac9 generalized the boards and the libraries views.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-08-05 19:40:25 +02:00
Akos Kitta
b24d440e22 Merge pull request #53 from bcmi-labs/PROEDITOR-27
PROEDITOR-27: Try to preserve the window.
2019-08-05 13:47:53 +02:00
Akos Kitta
af9b9fbeab Yet another attempt to fix timeout issues on Azure.
```
info There appears to be trouble with your network connection. Retrying...
error An unexpected error occurred: "https://registry.yarnpkg.com/rxjs/-/rxjs-6.5.2.tgz: ESOCKETTIMEDOUT".
info If you think this is a bug, please open a bug report with the information provided in "D:\\a\\1\\s\\yarn-error.log".
```

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-08-05 13:17:59 +02:00
Stefania
37db6c4b43 Merge pull request #51 from bcmi-labs/search-in-workspace-and-git
Added "Search In Workspace" and "SCM/Git" Extensions.
2019-08-05 11:12:46 +02:00
Jan Bicker
9d5ad9b003 Added "Search In Workspace" and "SCM/Git" Extensions.
Signed-off-by: Jan Bicker <jan.bicker@typefox.io>
2019-08-05 09:58:52 +02:00
Akos Kitta
ded838b4e8 Fixed the preloadTemplate for electron.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-08-05 09:57:07 +02:00
Akos Kitta
82df8a6add PROEDITOR-27: Try to preserve the window.
When opening sketches. Rules:
 - If `sketch` is missing from the URL, we reuse the same window.
 - NOOP, if we try to open the currently opened sketch.
 - Otherwise, use the existing logic: open sketch in a new window.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-08-05 09:57:05 +02:00
Luca Cipriani
2914379586 Merge pull request #46 from bcmi-labs/poll-boards
Implemented the board discovery with polling.
2019-08-02 17:08:08 +02:00
Akos Kitta
6b25659fa6 Merge pull request #48 from bcmi-labs/monitoring-api
Updated the TS/JS API with the monitoring.
2019-07-30 13:04:46 +02:00
Akos Kitta
27dc6f9816 Updated the TS/JS API with the monitoring.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-07-30 10:57:23 +02:00
Akos Kitta
b78ddbeb64 Implemented the board discovery with polling.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-07-30 10:32:10 +02:00
jbicker
db78c8ac2d Minor css adjustments
Signed-off-by: jbicker <jan.bicker@typefox.io>
2019-07-26 12:00:26 +02:00
Luca Cipriani
95c5536060 Merge pull request #45 from bcmi-labs/new-file-menu-item
Added 'New File' Item in file menu
2019-07-26 11:37:48 +02:00
Akos Kitta
0aa34b1169 Added the Prerequisites section to the README.
Closes #44.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-07-26 11:25:40 +02:00
jbicker
b7d951b809 Added 'New File' Item in file menu
Signed-off-by: jbicker <jan.bicker@typefox.io>
2019-07-26 11:00:18 +02:00
Luca Cipriani
e11d9e0c78 Merge pull request #43 from bcmi-labs/toggle-pro-mode
One can toggle between pro and simple mode
2019-07-25 18:29:17 +02:00
jbicker
436e660d47 Avoid duplicate react keys in board select dialog
Signed-off-by: jbicker <jan.bicker@typefox.io>
2019-07-25 18:04:59 +02:00
jbicker
23a967bd4c One can toggle between pro and simple mode
Signed-off-by: jbicker <jan.bicker@typefox.io>
2019-07-25 17:38:16 +02:00
Jan Bicker
17fab651e5 Merge pull request #41 from bcmi-labs/made-board-selector-async
Made boards selector async
2019-07-25 08:04:02 -07:00
Luca Cipriani
df7225c32b Merge pull request #29 from bcmi-labs/PROEDITOR-20
PROEDITOR-20: Restored the dirt flag in editor tab
2019-07-25 16:52:50 +02:00
Akos Kitta
69f63668b2 Merge pull request #42 from bcmi-labs/terminate-daemon
Fixed the daemon process termination.
2019-07-25 16:44:04 +02:00
Akos Kitta
d29ed24e49 Fixed the daemon process termination.
From now on, we spawn a detached process that
will periodically check whether the parent Theia
the process is alive, if no, terminates the daemon.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-07-25 16:11:40 +02:00
jbicker
a5294417c3 Made boards selector async
Signed-off-by: jbicker <jan.bicker@typefox.io>
2019-07-25 11:20:56 +02:00
Akos Kitta
d6637c44e5 PROEDITOR-20: Restored the dirt flag in editor tab
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2019-07-22 14:19:49 +02:00
307 changed files with 43638 additions and 12451 deletions

32
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View File

@@ -0,0 +1,32 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: bug
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Desktop (please complete the following information):**
- OS: [e.g. Windows]
- Version: [e.g. 2.0.0]
**Additional context**
Add any other context about the problem here.

View File

@@ -0,0 +1,20 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: enhancement
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.

176
.github/workflows/build.yml vendored Normal file
View File

@@ -0,0 +1,176 @@
name: Arduino IDE
on:
push:
branches:
- main
tags:
- '[0-9]+.[0-9]+.[0-9]+*'
workflow_dispatch:
pull_request:
branches:
- main
schedule:
- cron: '0 3 * * *' # run every day at 3AM (https://docs.github.com/en/actions/reference/events-that-trigger-workflows#scheduled-events-schedule)
jobs:
build:
strategy:
matrix:
config:
- os: windows-latest
- os: ubuntu-latest
- os: macos-latest
runs-on: ${{ matrix.config.os }}
timeout-minutes: 90
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Install Node.js 12.x
uses: actions/setup-node@v1
with:
node-version: '12.14.1'
registry-url: 'https://registry.npmjs.org'
- name: Install Python 2.7
uses: actions/setup-python@v2
with:
python-version: '2.7'
- name: Package
shell: bash
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
AC_USERNAME: ${{ secrets.AC_USERNAME }}
AC_PASSWORD: ${{ secrets.AC_PASSWORD }}
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
IS_NIGHTLY: ${{ github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main') }}
IS_RELEASE: ${{ startsWith(github.ref, 'refs/tags/') }}
run: |
# See: https://www.electron.build/code-signing
if [ "${{ runner.OS }}" = "macOS" ]; then
export CSC_LINK="${{ runner.temp }}/signing_certificate.p12"
# APPLE_SIGNING_CERTIFICATE_P12 secret was produced by following the procedure from:
# https://www.kencochrane.com/2020/08/01/build-and-sign-golang-binaries-for-macos-with-github-actions/#exporting-the-developer-certificate
echo "${{ secrets.APPLE_SIGNING_CERTIFICATE_P12 }}" | base64 --decode > "$CSC_LINK"
export CSC_KEY_PASSWORD="${{ secrets.KEYCHAIN_PASSWORD }}"
elif [ "${{ runner.OS }}" = "Windows" ]; then
export CSC_LINK="${{ runner.temp }}/signing_certificate.pfx"
echo "${{ secrets.WINDOWS_SIGNING_CERTIFICATE_PFX }}" | base64 --decode > "$CSC_LINK"
export CSC_KEY_PASSWORD="${{ secrets.WINDOWS_SIGNING_CERTIFICATE_PASSWORD }}"
fi
yarn --cwd ./electron/packager/
yarn --cwd ./electron/packager/ package
- name: Upload [GitHub Actions]
uses: actions/upload-artifact@v2
with:
name: build-artifacts
path: electron/build/dist/build-artifacts/
changelog:
needs: build
runs-on: ubuntu-latest
outputs:
BODY: ${{ steps.changelog.outputs.BODY }}
steps:
- name: Checkout
uses: actions/checkout@v2
with:
fetch-depth: 0 # To fetch all history for all branches and tags.
- name: Generate Changelog
id: changelog
env:
IS_RELEASE: ${{ startsWith(github.ref, 'refs/tags/') }}
run: |
export LATEST_TAG=$(git describe --abbrev=0)
export GIT_LOG=$(git log --pretty=" - %s [%h]" $LATEST_TAG..HEAD | sed 's/ *$//g')
if [ "$IS_RELEASE" = true ]; then
export BODY=$(echo -e "$GIT_LOG")
else
export LATEST_TAG_WITH_LINK=$(echo "[$LATEST_TAG](https://github.com/arduino/arduino-ide/releases/tag/$LATEST_TAG)")
if [ -z "$GIT_LOG" ]; then
export BODY="There were no changes since version $LATEST_TAG_WITH_LINK."
else
export BODY=$(echo -e "Changes since version $LATEST_TAG_WITH_LINK:\n$GIT_LOG")
fi
fi
echo -e "$BODY"
OUTPUT_SAFE_BODY="${BODY//'%'/'%25'}"
OUTPUT_SAFE_BODY="${OUTPUT_SAFE_BODY//$'\n'/'%0A'}"
OUTPUT_SAFE_BODY="${OUTPUT_SAFE_BODY//$'\r'/'%0D'}"
echo "::set-output name=BODY::$OUTPUT_SAFE_BODY"
echo "$BODY" > CHANGELOG.txt
- name: Upload Changelog [GitHub Actions]
if: github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main')
uses: actions/upload-artifact@v2
with:
name: build-artifacts
path: CHANGELOG.txt
publish:
needs: changelog
if: github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main')
runs-on: ubuntu-latest
steps:
- name: Download [GitHub Actions]
uses: actions/download-artifact@v2
with:
name: build-artifacts
path: build-artifacts
- name: Publish Nightly [S3]
uses: docker://plugins/s3
env:
PLUGIN_SOURCE: "build-artifacts/*"
PLUGIN_STRIP_PREFIX: "build-artifacts/"
PLUGIN_TARGET: "/arduino-ide/nightly"
PLUGIN_BUCKET: ${{ secrets.DOWNLOADS_BUCKET }}
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
release:
needs: changelog
if: startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
steps:
- name: Download [GitHub Actions]
uses: actions/download-artifact@v2
with:
name: build-artifacts
path: build-artifacts
- name: Get Tag
id: tag_name
run: |
echo ::set-output name=TAG_NAME::${GITHUB_REF#refs/tags/}
- name: Publish Release [GitHub]
uses: svenstaro/upload-release-action@2.2.0
with:
repo_token: ${{ secrets.GITHUB_TOKEN }}
release_name: ${{ steps.tag_name.outputs.TAG_NAME }}
file: build-artifacts/*
tag: ${{ github.ref }}
file_glob: true
body: ${{ needs.changelog.outputs.BODY }}
- name: Publish Release [S3]
uses: docker://plugins/s3
env:
PLUGIN_SOURCE: "build-artifacts/*"
PLUGIN_STRIP_PREFIX: "build-artifacts/"
PLUGIN_TARGET: "/arduino-ide"
PLUGIN_BUCKET: ${{ secrets.DOWNLOADS_BUCKET }}
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}

122
.github/workflows/check-certificates.yml vendored Normal file
View File

@@ -0,0 +1,122 @@
name: Check for issues with signing certificates
on:
schedule:
# run every 10 hours
- cron: "0 */10 * * *"
# workflow_dispatch event allows the workflow to be triggered manually.
# This could be used to run an immediate check after updating certificate secrets.
# See: https://docs.github.com/en/actions/reference/events-that-trigger-workflows#workflow_dispatch
workflow_dispatch:
env:
# Begin notifications when there are less than this many days remaining before expiration
EXPIRATION_WARNING_PERIOD: 30
jobs:
check-certificates:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
certificate:
- identifier: macOS signing certificate # Text used to identify the certificate in notifications
certificate-secret: APPLE_SIGNING_CERTIFICATE_P12 # The name of the secret that contains the certificate
password-secret: KEYCHAIN_PASSWORD # The name of the secret that contains the certificate password
- identifier: Windows signing certificate
certificate-secret: WINDOWS_SIGNING_CERTIFICATE_PFX
password-secret: WINDOWS_SIGNING_CERTIFICATE_PASSWORD
steps:
- name: Set certificate path environment variable
run: |
# See: https://docs.github.com/en/free-pro-team@latest/actions/reference/workflow-commands-for-github-actions#setting-an-environment-variable
echo "CERTIFICATE_PATH=${{ runner.temp }}/certificate.p12" >> "$GITHUB_ENV"
- name: Decode certificate
env:
CERTIFICATE: ${{ secrets[matrix.certificate.certificate-secret] }}
run: |
echo "${{ env.CERTIFICATE }}" | base64 --decode > "${{ env.CERTIFICATE_PATH }}"
- name: Verify certificate
env:
CERTIFICATE_PASSWORD: ${{ secrets[matrix.certificate.password-secret] }}
run: |
(
openssl pkcs12 \
-in "${{ env.CERTIFICATE_PATH }}" \
-noout -passin env:CERTIFICATE_PASSWORD
) || (
echo "::error::Verification of ${{ matrix.certificate.identifier }} failed!!!"
exit 1
)
# See: https://github.com/rtCamp/action-slack-notify
- name: Slack notification of certificate verification failure
if: failure()
uses: rtCamp/action-slack-notify@v2.1.0
env:
SLACK_WEBHOOK: ${{ secrets.TEAM_TOOLING_CHANNEL_SLACK_WEBHOOK }}
SLACK_MESSAGE: |
:warning::warning::warning::warning:
WARNING: ${{ github.repository }} ${{ matrix.certificate.identifier }} verification failed!!!
:warning::warning::warning::warning:
SLACK_COLOR: danger
MSG_MINIMAL: true
- name: Get days remaining before certificate expiration date
env:
CERTIFICATE_PASSWORD: ${{ secrets[matrix.certificate.password-secret] }}
id: get-days-before-expiration
run: |
EXPIRATION_DATE="$(
(
openssl pkcs12 \
-in "${{ env.CERTIFICATE_PATH }}" \
-clcerts \
-nodes \
-passin env:CERTIFICATE_PASSWORD
) | (
openssl x509 \
-noout \
-enddate
) | (
grep \
--max-count=1 \
--only-matching \
--perl-regexp \
'notAfter=(\K.*)'
)
)"
DAYS_BEFORE_EXPIRATION="$((($(date --utc --date="$EXPIRATION_DATE" +%s) - $(date --utc +%s)) / 60 / 60 / 24))"
# Display the expiration information in the log
echo "Certificate expiration date: $EXPIRATION_DATE"
echo "Days remaining before expiration: $DAYS_BEFORE_EXPIRATION"
echo "::set-output name=days::$DAYS_BEFORE_EXPIRATION"
- name: Check if expiration notification period has been reached
id: check-expiration
run: |
if [[ ${{ steps.get-days-before-expiration.outputs.days }} -lt ${{ env.EXPIRATION_WARNING_PERIOD }} ]]; then
echo "::error::${{ matrix.certificate.identifier }} will expire in ${{ steps.get-days-before-expiration.outputs.days }} days!!!"
exit 1
fi
- name: Slack notification of pending certificate expiration
# Don't send spurious expiration notification if verification fails
if: failure() && steps.check-expiration.outcome == 'failure'
uses: rtCamp/action-slack-notify@v2.1.0
env:
SLACK_WEBHOOK: ${{ secrets.TEAM_TOOLING_CHANNEL_SLACK_WEBHOOK }}
SLACK_MESSAGE: |
:warning::warning::warning::warning:
WARNING: ${{ github.repository }} ${{ matrix.certificate.identifier }} will expire in ${{ steps.get-days-before-expiration.outputs.days }} days!!!
:warning::warning::warning::warning:
SLACK_COLOR: danger
MSG_MINIMAL: true

11
.gitignore vendored
View File

@@ -2,12 +2,17 @@ node_modules/
# .node_modules is a hack for the electron builder.
.node_modules/
lib/
build/
downloads/
build/
Examples/
!electron/build/
src-gen/
arduino-ide-*/webpack.config.js
*webpack.config.js
.DS_Store
/workspace/static
# switching from `electron` to `browser` in dev mode.
.browser_modules
yarn*.log
# For the VS Code extensions used by Theia.
plugins
# the config files for the CLI
arduino-ide-extension/data/cli/config

View File

@@ -1,20 +0,0 @@
image:
file: Dockerfile
ports:
- port: 3000
onOpen: open-browser
tasks:
- init: >
yarn &&
yarn --cwd ./arduino-ide-browser start
github:
prebuilds:
master: true
branches: true
pullRequests: true
pullRequestsFromForks: true
addComment: false
addBadge: false

143
.vscode/launch.json vendored
View File

@@ -1,38 +1,109 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Node.js Program",
"program": "${file}"
},
{
"type": "node",
"request": "launch",
"name": "Launch Backend",
"program": "${workspaceRoot}/arduino-ide-browser/src-gen/backend/main.js",
"args": [
"--hostname=0.0.0.0",
"--port=3000",
"--no-cluster",
"--no-app-auto-install"
],
"env": {
"NODE_ENV": "development"
},
"sourceMaps": true,
"outFiles": [
"${workspaceRoot}/arduino-ide-browser/src-gen/backend/*.js",
"${workspaceRoot}/arduino-ide-browser/lib/**/*.js",
"${workspaceRoot}/arduino-ide-extension/*/lib/**/*.js"
],
"smartStep": true,
"internalConsoleOptions": "openOnSessionStart",
"outputCapture": "std"
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "attach",
"name": "Attach by Process ID",
"processId": "${command:PickProcess}"
},
{
"type": "node",
"request": "launch",
"name": "Electron Packager",
"program": "${workspaceRoot}/electron/packager/index.js",
"cwd": "${workspaceFolder}/electron/packager"
},
{
"type": "node",
"request": "launch",
"name": "App (Electron)",
"runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron",
"windows": {
"runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron.cmd",
"env": {
"NODE_ENV": "development",
"NODE_PRESERVE_SYMLINKS": "1"
}
]
}
},
"program": "${workspaceRoot}/electron-app/src-gen/frontend/electron-main.js",
"protocol": "inspector",
"args": [
"--log-level=debug",
"--hostname=localhost",
"--no-cluster",
"--remote-debugging-port=9222",
"--no-app-auto-install",
"--plugins=local-dir:plugins"
],
"env": {
"NODE_ENV": "development"
},
"sourceMaps": true,
"outFiles": [
"${workspaceRoot}/electron-app/src-gen/backend/*.js",
"${workspaceRoot}/electron-app/src-gen/frontend/*.js",
"${workspaceRoot}/electron-app/lib/**/*.js",
"${workspaceRoot}/arduino-ide-extension/lib/**/*.js"
],
"smartStep": true,
"internalConsoleOptions": "openOnSessionStart",
"outputCapture": "std"
},
{
"type": "node",
"request": "launch",
"name": "App (Browser)",
"program": "${workspaceRoot}/browser-app/src-gen/backend/main.js",
"args": [
"--hostname=0.0.0.0",
"--port=3000",
"--no-cluster",
"--no-app-auto-install",
"--plugins=local-dir:plugins"
],
"windows": {
"env": {
"NODE_ENV": "development",
"NODE_PRESERVE_SYMLINKS": "1"
}
},
"env": {
"NODE_ENV": "development"
},
"sourceMaps": true,
"outFiles": [
"${workspaceRoot}/browser-app/src-gen/backend/*.js",
"${workspaceRoot}/browser-app/lib/**/*.js",
"${workspaceRoot}/arduino-ide-extension/lib/**/*.js"
],
"smartStep": true,
"internalConsoleOptions": "openOnSessionStart",
"outputCapture": "std"
},
{
"type": "node",
"request": "launch",
"protocol": "inspector",
"name": "Run Test [current]",
"program": "${workspaceRoot}/node_modules/mocha/bin/_mocha",
"args": [
"--require",
"reflect-metadata/Reflect",
"--no-timeouts",
"--colors",
"**/${fileBasenameNoExtension}.js"
],
"env": {
"TS_NODE_PROJECT": "${workspaceRoot}/tsconfig.json"
},
"sourceMaps": true,
"smartStep": true,
"internalConsoleOptions": "openOnSessionStart",
"outputCapture": "std"
}
]
}

21
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,21 @@
{
"tslint.enable": true,
"tslint.configFile": "./tslint.json",
"editor.formatOnSave": true,
"files.exclude": {
"**/lib": false
},
"editor.insertSpaces": true,
"editor.detectIndentation": false,
"[typescript]": {
"editor.tabSize": 4
},
"[json]": {
"editor.tabSize": 2
},
"[jsonc]": {
"editor.tabSize": 2
},
"files.insertFinalNewline": true,
"typescript.tsdk": "node_modules/typescript/lib"
}

124
.vscode/tasks.json vendored
View File

@@ -1,48 +1,78 @@
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "Arduino-PoC - Start Browser Example",
"type": "shell",
"command": "yarn --cwd ./arduino-ide-browser start",
"group": "build",
"presentation": {
"reveal": "always",
"panel": "new",
"clear": true
}
},
{
"label": "Arduino-PoC - Watch Theia Extension",
"type": "shell",
"command": "yarn --cwd ./arduino-ide-extension watch",
"group": "build",
"presentation": {
"reveal": "always",
"panel": "new",
"clear": false
}
},
{
"label": "Arduino-PoC - Watch Browser Example",
"type": "shell",
"command": "yarn --cwd ./arduino-ide-browser watch",
"group": "build",
"presentation": {
"reveal": "always",
"panel": "new",
"clear": false
}
},
{
"label": "Arduino-PoC - Watch All",
"type": "shell",
"dependsOn": [
"Arduino-PoC - Watch Theia Extension",
"Arduino-PoC - Watch Browser Example"
]
}
]
}
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "Arduino IDE - Rebuild Electron App",
"type": "shell",
"command": "yarn rebuild:browser && yarn rebuild:electron",
"group": "build",
"presentation": {
"reveal": "always",
"panel": "new",
"clear": false
}
},
{
"label": "Arduino IDE - Start Browser App",
"type": "shell",
"command": "yarn --cwd ./browser-app start",
"group": "build",
"presentation": {
"reveal": "always",
"panel": "new",
"clear": true
}
},
{
"label": "Arduino IDE - Watch IDE Extension",
"type": "shell",
"command": "yarn --cwd ./arduino-ide-extension watch",
"group": "build",
"presentation": {
"reveal": "always",
"panel": "new",
"clear": false
}
}
{
"label": "Arduino IDE - Watch Browser App",
"type": "shell",
"command": "yarn --cwd ./browser-app watch",
"group": "build",
"presentation": {
"reveal": "always",
"panel": "new",
"clear": false
}
},
{
"label": "Arduino IDE - Watch Electron App",
"type": "shell",
"command": "yarn --cwd ./electron-app watch",
"group": "build",
"presentation": {
"reveal": "always",
"panel": "new",
"clear": false
}
},
{
"label": "Arduino IDE - Watch All [Browser]",
"type": "shell",
"dependsOn": [
"Arduino IDE - Watch IDE Extension",
"Arduino IDE - Watch Browser App"
]
},
{
"label": "Arduino IDE - Watch All [Electron]",
"type": "shell",
"dependsOn": [
"Arduino IDE - Watch IDE Extension",
"Arduino IDE - Watch Electron App"
]
}
]
}

View File

@@ -1,4 +1,4 @@
FROM gitpod/workspace-full
FROM gitpod/workspace-full-vnc
USER root
RUN apt-get update -q --fix-missing && \
@@ -7,7 +7,8 @@ RUN apt-get update -q --fix-missing && \
build-essential \
libssl-dev \
golang-go \
libxkbfile-dev
libxkbfile-dev \
libnss3-dev
RUN set -ex && \
tmpdir=$(mktemp -d) && \

181
README.md
View File

@@ -1,44 +1,165 @@
# Arduino IDE PoC
# Arduino IDE
[![Build Status](https://dev.azure.com/typefox/Arduino/_apis/build/status/bcmi-labs.arduino-editor?branchName=master)](https://dev.azure.com/typefox/Arduino/_build/latest?definitionId=4&branchName=master)
[![Arduino IDE](https://github.com/arduino/arduino-ide/workflows/Arduino%20IDE/badge.svg)](https://github.com/arduino/arduino-ide/actions?query=workflow%3A%22Arduino+IDE%22)
> **Beware:** This is very much work-in-progress. Things can and probably will be broken, even on master.
### Download
This repo contains a proof-of-concept for an Arduino IDE based on Theia.
It's built on top of a [fork of the arduino-cli](https://github.com/typefox/arduino-cli/tree/daemon) that sports a gRPC interface.
You can download the latest version of the Arduino IDE application for the supported platforms from the [GitHub release page](https://github.com/arduino/arduino-ide/releases) or following the links in the following table.
## How to try (offline)
#### Latest version
```
git clone https://github.com/bcmi-labs/arduino-editor
cd arduino-editor
Platform | 32 bit | 64 bit |
--------- | ------------------------ | ------------------------------------------------------------------------------ |
Linux | | [Linux 64 bit] |
Linux ARM | [🚧 Work in progress...] | [🚧 Work in progress...] |
Windows | | [Windows 64 bit installer]<br />[Windows 64 bit MSI]<br />[Windows 64 bit ZIP] |
macOS | | [macOS 64 bit] |
[🚧 Work in progress...]: https://github.com/arduino/arduino-ide/issues/287
[Linux 64 bit]: https://downloads.arduino.cc/arduino-ide/arduino-ide_latest_Linux_64bit.zip
[Windows 64 bit installer]: https://downloads.arduino.cc/arduino-ide/arduino-ide_latest_Windows_64bit.exe
[Windows 64 bit MSI]: https://downloads.arduino.cc/arduino-ide/arduino-ide_latest_Windows_64bit.msi
[Windows 64 bit ZIP]: https://downloads.arduino.cc/arduino-ide/arduino-ide_latest_Windows_64bit.zip
[macOS 64 bit]: https://downloads.arduino.cc/arduino-ide/arduino-ide_latest_macOS_64bit.dmg
#### Previous versions
These are available from the [GitHub releases page](https://github.com/arduino/arduino-ide/releases).
#### Nightly builds
These builds are generated every day at 03:00 GMT from the `main` branch and
should be considered unstable. In order to get the latest nightly build
available for the supported platform, use the following links:
Platform | 32 bit | 64 bit |
--------- | ------------------------ | ------------------------------------------------------------------------------------------------------ |
Linux | | [Nightly Linux 64 bit] |
Linux ARM | [🚧 Work in progress...] | [🚧 Work in progress...] |
Windows | | [Nightly Windows 64 bit installer]<br />[Nightly Windows 64 bit MSI]<br />[Nightly Windows 64 bit ZIP] |
macOS | | [Nightly macOS 64 bit] |
[🚧 Work in progress...]: https://github.com/arduino/arduino-ide/issues/287
[Nightly Linux 64 bit]: https://downloads.arduino.cc/arduino-ide/nightly/arduino-ide_nightly-latest_Linux_64bit.zip
[Nightly Windows 64 bit installer]: https://downloads.arduino.cc/arduino-ide/nightly/arduino-ide_nightly-latest_Windows_64bit.exe
[Nightly Windows 64 bit MSI]: https://downloads.arduino.cc/arduino-ide/nightly/arduino-ide_nightly-latest_Windows_64bit.msi
[Nightly Windows 64 bit ZIP]: https://downloads.arduino.cc/arduino-ide/nightly/arduino-ide_nightly-latest_Windows_64bit.zip
[Nightly macOS 64 bit]: https://downloads.arduino.cc/arduino-ide/nightly/arduino-ide_nightly-latest_macOS_64bit.dmg
> These links return an HTTP `302: Found` response, redirecting to latest
generated builds by replacing `latest` with the latest available build
date, using the format YYYYMMDD (i.e for 2019/Aug/06 `latest` is
replaced with `20190806` )
### Build from source
If youre familiar with TypeScript, the [Theia IDE](https://theia-ide.org/), and if you want to contribute to the
project, you should be able to build the Arduino IDE locally. Please refer to the [Theia IDE prerequisites](https://github.com/theia-ide/theia/blob/master/doc/) documentation for the setup instructions.
### Build
```sh
yarn
```
### Rebuild the native dependencies
```sh
yarn rebuild:electron
yarn --cwd arduino-ide-electron start
```
If you want to switch back to the browser-based example, execute the following in the repository root
```
yarn rebuild:browser
```
Then you can start the browser example again:
```
yarn --cwd arduino-ide-browser start
### Start
```sh
yarn start
```
## Arduino-PoC Electron Application
The project is built on [Azure DevOps](https://dev.azure.com/typefox/Arduino).
### CI
Currently, we provide the Arduino-PoC for the following platforms:
- Windows,
- macOS, and
- Linux.
You can download the latest release applications fom [here](https://github.com/bcmi-labs/arduino-editor/releases/latest).
If you want to get a nightly build, go to the [Azure DevOps page](https://dev.azure.com/typefox/Arduino/_build?definitionId=4),
and follow the steps from below.
This project is built on [GitHub Actions](https://github.com/bcmi-labs/arduino-editor/actions?query=workflow%3A%22Arduino+Pro+IDE%22).
![](static/download_01.gif)
![](static/download_02.gif)
- _Snapshot_ builds run when changes are pushed to the `main` branch, or when a PR is created against the `main` branch. For the sake of the review and verification process, the build artifacts can be downloaded from the GitHub Actions page. Note: [due to a limitation](https://github.com/actions/upload-artifact/issues/80#issuecomment-630030144) with the GH Actions UI, you cannot download a particular build, but you have to get all together inside the `build-artifacts.zip`.
- _Nightly_ builds run every day at 03:00 GMT from the `main` branch.
- _Release_ builds run when a new tag is pushed to the remote. The tag must follow the [semver](https://semver.org/). For instance, `1.2.3` is a correct tag, but `v2.3.4` won't work. Steps to trigger a new release build:
- Create a local tag:
```sh
git tag -a 1.2.3 -m "Creating a new tag for the `1.2.3` release."
```
- Push it to the remote:
```sh
git push origin 1.2.3
```
Click [here](./electron/README.md) for more details on the CI/CD, the GitHub release, and the build process in general.
### Creating a GH release
This section guides you through how to create a new release. Let's assume the current version is `0.1.3` and you want to release `0.2.0`.
- Make sure the `main` state represents what you want to release and you're on `main`.
- Prepare a release-candidate build on a branch:
```bash
git branch 0.2.0-rc \
&& git checkout 0.2.0-rc
```
- Bump up the version number. It must be a valid [semver](https://semver.org/) and must be greater than the current one:
```bash
yarn update:version 0.2.0
```
- This should generate multiple outgoing changes with the version update.
- Commit your changes and push to the remote:
```bash
git add . \
&& git commit -s -m "Updated versions to 0.2.0" \
&& git push
```
- Create the GH PR the workflow starts automatically.
- Once you're happy with the RC, merge the changes to the `main`.
- Create a tag and push it:
```bash
git tag -a 0.2.0 -m "0.2.0" \
&& git push origin 0.2.0
```
- The release build starts automatically and uploads the artifacts with the changelog to the Pro IDE [release page](https://github.com/arduino/arduino-ide/releases).
- If you do not want to release the `EXE` and `MSI` installers, wipe them manually.
- If you do not like the generated changelog, modify it and update the GH release.
### FAQ
- Q: Can I manually change the version of the [`arduino-cli`](https://github.com/arduino/arduino-cli/) used by the IDE?
- A: Yes. It is possible but not recommended. The CLI exposes a set of functionality via [gRPC](https://github.com/arduino/arduino-cli/tree/master/rpc) and the IDE uses this API to communicate with the CLI. Before we build a new version of IDE, we pin a specific version of CLI and use the corresponding `proto` files to generate TypeScript modules for gRPC. This means, a particular version of IDE is compliant only with the pinned version of CLI. Mismatching IDE and CLI versions might not be able to communicate with each other. This could cause unpredictable IDE behavior.
- Q: I have understood that not all versions of the CLI is compatible with my version of IDE but how can I manually update the `arduino-cli` inside the IDE?
- A: [Get](https://arduino.github.io/arduino-cli/installation) the desired version of `arduino-cli` for your platform and manually replace the one inside the IDE. The CLI can be found inside the IDE at:
- Windows: `C:\path\to\Arduino IDE\resources\app\node_modules\arduino-ide-extension\build\arduino-cli.exe`,
- macOS: `/path/to/Arduino IDE.app/Contents/Resources/app/node_modules/arduino-ide-extension/build/arduino-cli`, and
- Linux: `/path/to/Arduino IDE/resources/app/node_modules/arduino-ide-extension/build/arduino-cli`.
### Architecture overview
The Pro IDE consists of three major parts:
- the _Electron main_ process,
- the _backend_, and
- the _frontend_.
The _Electron main_ process is responsible for:
- creating the application,
- managing the application lifecycle via listeners, and
- creating and managing the web pages for the app.
In Electron, the process that runs the main entry JavaScript file is called the main process. The _Electron main_ process can display a GUI by creating web pages. An Electron app always has exactly on main process.
By default, whenever the _Electron main_ process creates a web page, it will instantiate a new `BrowserWindow` instance. Since Electron uses Chromium for displaying web pages, Chromium's multi-process architecture is also used. Each web page in Electron runs in its own process, which is called the renderer process. Each `BrowserWindow` instance runs the web page in its own renderer process. When a `BrowserWindow` instance is destroyed, the corresponding renderer process is also terminated. The main process manages all web pages and their corresponding renderer processes. Each renderer process is isolated and only cares about the web page running in it.<sup>[[1]]</sup>
In normal browsers, web pages usually run in a sandboxed environment, and accessing native resources are disallowed. However, Electron has the power to use Node.js APIs in the web pages allowing lower-level OS interactions. Due to security reasons, accessing native resources is an undesired behavior in the Pro IDE. So by convention, we do not use Node.js APIs. (Note: the Node.js integration is [not yet disabled](https://github.com/eclipse-theia/theia/issues/2018) although it is not used). In the Pro IDE, only the _backend_ allows OS interaction.
The _backend_ process is responsible for:
- providing access to the filesystem,
- communicating with the Arduino CLI via gRPC,
- running your terminal,
- exposing additional RESTful APIs,
- performing the Git commands in the local repositories,
- hosting and running any VS Code extensions, or
- executing VS Code tasks<sup>[[2]]</sup>.
The _Electron main_ process spawns the _backend_ process. There is always exactly one _backend_ process. However, due to performance considerations, the _backend_ spawns several sub-processes for the filesystem watching, Git repository discovery, etc. The communication between the _backend_ process and its sub-processes is established via IPC. Besides spawning sub-processes, the _backend_ will start an HTTP server on a random available port, and serves the web application as static content. When the sub-processes are up and running, and the HTTP server is also listening, the _backend_ process sends the HTTP server port to the _Electron main_ process via IPC. The _Electron main_ process will load the _backend_'s endpoint in the `BrowserWindow`.
The _frontend_ is running as an Electron renderer process and can invoke services implemented on the _backend_. The communication between the _backend_ and the _frontend_ is done via JSON-RPC over a websocket connection. This means, the services running in the _frontend_ are all proxies, and will ask the corresponding service implementation on the _backend_.
[1]: https://www.electronjs.org/docs/tutorial/application-architecture#differences-between-main-process-and-renderer-process
[2]: https://code.visualstudio.com/Docs/editor/tasks

View File

@@ -1,49 +0,0 @@
{
"private": true,
"name": "arduino-ide-electron",
"version": "0.0.1",
"license": "MIT",
"dependencies": {
"@theia/core": "next",
"@theia/editor": "next",
"@theia/electron": "next",
"@theia/file-search": "next",
"@theia/filesystem": "next",
"@theia/languages": "next",
"@theia/messages": "next",
"@theia/monaco": "next",
"@theia/navigator": "next",
"@theia/preferences": "next",
"@theia/process": "next",
"@theia/terminal": "next",
"@theia/workspace": "next",
"@theia/textmate-grammars": "next",
"arduino-ide-extension": "0.0.1"
},
"devDependencies": {
"@theia/cli": "next",
"electron": "^4.2.0"
},
"scripts": {
"prepare": "theia build --mode development",
"start": "theia start --root-dir=../workspace",
"watch": "theia build --watch --mode development"
},
"theia": {
"target": "electron",
"frontend": {
"config": {
"applicationName": "Arduino-PoC",
"defaultTheme": "arduino-theme",
"preferences": {
"editor.autoSave": "on"
}
}
}
},
"generator": {
"config": {
"preloadTemplate": "<div class='theia-preload' style='background-color: rgb(237, 241, 242);'></div>"
}
}
}

View File

@@ -0,0 +1,56 @@
## Arduino IDE Extension
Arduino IDE is based on Theia, and most of its IDE features, UIs and customizations are implemented in this Theia extension.
### IDE Services
IDE services typically have a backend part in [src/node/](./src/node/) and a front-end part in [src/browser/](./src/browser/).
#### Boards Service
The Boards Service continuously checks the computer's ports, in order to detect when you connect or disconnect an Arduino board.
The Boards Manager lists all the known board types, and allows downloading new cores to get additional board types.
- [src/common/protocol/boards-service.ts](./src/common/protocol/boards-service.ts) implements the common classes and interfaces
- [src/node/boards-service-impl.ts](./src/node/boards-service-impl.ts) implements the service backend:
- discovering ports & boards
- searching for compatible board types
- installing new board types
- [src/browser/boards/boards-list-widget.ts](./src/browser/boards/boards-service-client-impl.ts) implements the Boards Manager front-end:
- browsing/searching available board types
- installing new board types
#### Core Service
The Core Service is responsible for building your sketches and uploading them to a board.
- [src/common/protocol/core-service.ts](./src/common/protocol/core-service.ts) implements the common classes and interfaces
- [src/node/core-service-impl.ts](./src/node/core-service-impl.ts) implements the service backend:
- compiling a sketch for a selected board type
- uploading a sketch to a connected board
#### Monitor Service
The Monitor Service allows getting information back from sketches running on your Arduino boards.
- [src/common/protocol/monitor-service.ts](./src/common/protocol/monitor-service.ts) implements the common classes and interfaces
- [src/node/monitor-service-impl.ts](./src/node/monitor-service-impl.ts) implements the service backend:
- connecting to / disconnecting from a board
- receiving and sending data
- [src/browser/monitor/monitor-widget.tsx](./src/browser/monitor/monitor-widget.tsx) implements the serial monitor front-end:
- viewing the output from a connected board
- entering data to send to the board
#### Config Service
The Config Service knows about your system, like for example the default sketch locations.
- [src/common/protocol/config-service.ts](./src/common/protocol/config-service.ts) implements the common classes and interfaces
- [src/node/config-service-impl.ts](./src/node/config-service-impl.ts) implements the service backend:
- getting the `arduino-cli` version and configuration
- checking whether a file is in a data or sketch directory
### `"arduino"` configuration in the `package.json`:
- `"cli"`:
- `"version"` type `string` | `{ owner: string, repo: string, commitish?: string }`: if the type is a `string` and is a valid semver, it will get the corresponding [released](https://github.com/arduino/arduino-cli/releases) CLI. If the type is `string` and is a [date in `YYYYMMDD`](https://arduino.github.io/arduino-cli/latest/installation/#nightly-builds) format, it will get a nightly CLI. If the type is an object, a CLI, build from the sources in the `owner/repo` will be used. If `commitish` is not defined, the HEAD of the default branch will be used. In any other cases an error is thrown.

File diff suppressed because it is too large Load Diff

View File

@@ -1,66 +1,129 @@
{
"name": "arduino-ide-extension",
"version": "0.0.1",
"version": "2.0.0-beta.2",
"description": "An extension for Theia building the Arduino IDE",
"license": "MIT",
"engines": {
"node": ">=10.10.0"
},
"dependencies": {
"@grpc/grpc-js": "^0.4.0",
"@theia/core": "next",
"@theia/editor": "next",
"@theia/filesystem": "next",
"@theia/languages": "next",
"@theia/markers": "next",
"@theia/monaco": "next",
"@theia/outline-view": "next",
"@theia/workspace": "next",
"@theia/navigator": "next",
"@theia/terminal": "next",
"@types/which": "^1.3.1",
"css-element-queries": "^1.2.0",
"p-queue": "^5.0.0",
"which": "^1.3.1"
},
"scripts": {
"prepare": "yarn download-cli && yarn run clean && yarn run build",
"prepare": "yarn download-cli && yarn download-ls && yarn clean && yarn download-examples && yarn build",
"clean": "rimraf lib",
"download-cli": "node ./scripts/download-cli.js",
"download-ls": "node ./scripts/download-ls.js",
"download-examples": "node ./scripts/download-examples.js",
"generate-protocol": "node ./scripts/generate-protocol.js",
"lint": "tslint -c ./tslint.json --project ./tsconfig.json",
"build": "tsc && ncp ./src/node/cli-protocol/ ./lib/node/cli-protocol/ && yarn lint",
"watch": "tsc -w"
"watch": "tsc -w",
"test": "mocha \"./lib/test/**/*.test.js\"",
"test:watch": "mocha --watch --watch-files lib \"./lib/test/**/*.test.js\""
},
"dependencies": {
"@grpc/grpc-js": "^1.1.1",
"@theia/application-package": "next",
"@theia/core": "next",
"@theia/editor": "next",
"@theia/filesystem": "next",
"@theia/git": "next",
"@theia/markers": "next",
"@theia/monaco": "next",
"@theia/navigator": "next",
"@theia/outline-view": "next",
"@theia/preferences": "next",
"@theia/output": "next",
"@theia/search-in-workspace": "next",
"@theia/terminal": "next",
"@theia/workspace": "next",
"@types/dateformat": "^3.0.1",
"@types/deepmerge": "^2.2.0",
"@types/glob": "^5.0.35",
"@types/google-protobuf": "^3.7.2",
"@types/js-yaml": "^3.12.2",
"@types/lodash.debounce": "^4.0.6",
"@types/ncp": "^2.0.4",
"@types/ps-tree": "^1.1.0",
"@types/react-select": "^3.0.0",
"@types/react-tabs": "^2.3.2",
"@types/sinon": "^7.5.2",
"@types/temp": "^0.8.34",
"@types/which": "^1.3.1",
"ajv": "^6.5.3",
"css-element-queries": "^1.2.0",
"dateformat": "^3.0.3",
"deepmerge": "^4.2.2",
"fuzzy": "^0.1.3",
"glob": "^7.1.6",
"google-protobuf": "^3.11.4",
"lodash.debounce": "^4.0.8",
"js-yaml": "^3.13.1",
"ncp": "^2.0.0",
"p-queue": "^5.0.0",
"ps-tree": "^1.2.0",
"react-disable": "^0.1.0",
"react-select": "^3.0.4",
"react-tabs": "^3.1.2",
"semver": "^7.3.2",
"string-natural-compare": "^2.0.3",
"temp": "^0.9.1",
"tree-kill": "^1.2.1",
"upath": "^1.1.2",
"which": "^1.3.1"
},
"devDependencies": {
"@types/chai": "^4.2.7",
"@types/chai-string": "^1.4.2",
"@types/mocha": "^5.2.7",
"chai": "^4.2.0",
"chai-string": "^1.5.0",
"decompress": "^4.2.0",
"decompress-tarbz2": "^4.1.1",
"decompress-targz": "^4.1.1",
"decompress-unzip": "^4.0.1",
"download": "^7.1.0",
"grpc-tools": "^1.7.3",
"grpc_tools_node_protoc_ts": "^2.5.0",
"ncp": "^2.0.0",
"rimraf": "^2.6.1",
"grpc_tools_node_protoc_ts": "^4.1.0",
"mocha": "^7.0.0",
"moment": "^2.24.0",
"protoc": "^1.0.4",
"shelljs": "^0.8.3",
"tslint": "^5.5.0",
"typescript": "2.9.1",
"sinon": "^9.0.1",
"uuid": "^3.2.1",
"yargs": "^11.1.0"
},
"optionalDependencies": {
"grpc-tools": "^1.9.0"
},
"mocha": {
"require": [
"reflect-metadata/Reflect"
],
"reporter": "spec",
"colors": true,
"watch-extensions": "js",
"timeout": 10000
},
"files": [
"lib",
"src",
"build",
"data"
"data",
"examples"
],
"theiaExtensions": [
{
"backend": "lib/node/arduino-backend-module",
"frontend": "lib/browser/arduino-frontend-module"
"backend": "lib/node/arduino-ide-backend-module",
"frontend": "lib/browser/arduino-ide-frontend-module"
},
{
"frontend": "lib/browser/menu/browser-arduino-menu-module",
"frontendElectron": "lib/electron-browser/electron-arduino-menu-module"
"frontend": "lib/browser/theia/core/browser-menu-module",
"frontendElectron": "lib/electron-browser/theia/core/electron-menu-module"
},
{
"frontend": "lib/browser/boards/quick-open/boards-quick-open-module"
},
{
"electronMain": "lib/electron-main/arduino-electron-main-module"
}
]
}
],
"arduino": {
"cli": {
"version": "0.16.0"
}
}
}

View File

@@ -1,117 +1,141 @@
// @ts-check
// The links to the downloads as of today (11.08.) are the followings:
// - https://downloads.arduino.cc/arduino-cli/nightly/arduino-cli-nightly-latest-${FILE_NAME}
// - https://downloads.arduino.cc/arduino-cli/arduino-cli-latest-${FILE_NAME}
(async () => {
const DEFAULT_VERSION = 'nightly';
const os = require('os');
const fs = require('fs');
const path = require('path');
const temp = require('temp');
const shell = require('shelljs');
const download = require('download');
const decompress = require('decompress');
const unzip = require('decompress-unzip');
const untarbz = require('decompress-tarbz2');
const semver = require('semver');
const moment = require('moment');
const downloader = require('./downloader');
process.on('unhandledRejection', (reason, _) => {
shell.echo(String(reason));
const version = (() => {
const pkg = require(path.join(__dirname, '..', 'package.json'));
if (!pkg) {
return undefined;
}
const { arduino } = pkg;
if (!arduino) {
return undefined;
}
const { cli } = arduino;
if (!cli) {
return undefined;
}
const { version } = cli;
return version;
})();
if (!version) {
shell.echo(`Could not retrieve CLI version info from the 'package.json'.`);
shell.exit(1);
throw reason;
});
process.on('uncaughtException', error => {
shell.echo(String(error));
shell.exit(1);
throw error;
});
const yargs = require('yargs')
.option('cli-version', {
alias: 'cv',
default: DEFAULT_VERSION,
choices: [
// 'latest', // TODO: How do we get the source for `latest`. Currently, `latest` is the `0.3.7-alpha.preview`.
'nightly'
],
describe: `The version of the 'arduino-cli' to download. Defaults to ${DEFAULT_VERSION}.`
})
.option('force-download', {
alias: 'fd',
default: false,
describe: `If set, this script force downloads the 'arduino-cli' even if it already exists on the file system.`
})
.version(false).parse();
const version = yargs['cli-version'];
const force = yargs['force-download'];
const { platform, arch } = process;
const build = path.join(__dirname, '..', 'build');
const downloads = path.join(__dirname, '..', 'downloads');
const cli = path.join(build, `arduino-cli${os.platform() === 'win32' ? '.exe' : ''}`);
if (fs.existsSync(cli) && !force) {
shell.echo(`The 'arduino-cli' already exists at ${cli}. Skipping download.`);
shell.exit(0);
}
if (!fs.existsSync(build)) {
if (shell.mkdir('-p', build).code !== 0) {
shell.echo('Could not create new directory.');
const { platform, arch } = process;
const buildFolder = path.join(__dirname, '..', 'build');
const cliName = `arduino-cli${platform === 'win32' ? '.exe' : ''}`;
const destinationPath = path.join(buildFolder, cliName);
if (typeof version === 'string') {
const suffix = (() => {
switch (platform) {
case 'darwin': return 'macOS_64bit.tar.gz';
case 'win32': return 'Windows_64bit.zip';
case 'linux': {
switch (arch) {
case 'arm': return 'Linux_ARMv7.tar.gz';
case 'arm64': return 'Linux_ARM64.tar.gz';
case 'x64': return 'Linux_64bit.tar.gz';
default: return undefined;
}
}
default: return undefined;
}
})();
if (!suffix) {
shell.echo(`The CLI is not available for ${platform} ${arch}.`);
shell.exit(1);
}
}
if (shell.rm('-rf', cli, downloads).code !== 0) {
shell.exit(1);
}
const suffix = (() => {
switch (platform) {
case 'darwin': return 'macosx.zip';
case 'win32': return 'windows.zip';
case 'linux': {
switch (arch) {
case 'arm64': return 'linuxarm.tar.bz2';
case 'x32': return 'linux32.tar.bz2';
case 'x64': return 'linux64.tar.bz2';
default: return undefined;
}
}
default: return undefined;
if (semver.valid(version)) {
const url = `https://downloads.arduino.cc/arduino-cli/arduino-cli_${version}_${suffix}`;
shell.echo(`📦 Identified released version of the CLI. Downloading version ${version} from '${url}'`);
await downloader.downloadUnzipFile(url, destinationPath, 'arduino-cli');
} else if (moment(version, 'YYYYMMDD', true).isValid()) {
const url = `https://downloads.arduino.cc/arduino-cli/nightly/arduino-cli_nightly-${version}_${suffix}`;
shell.echo(`🌙 Identified nightly version of the CLI. Downloading version ${version} from '${url}'`);
await downloader.downloadUnzipFile(url, destinationPath, 'arduino-cli');
} else {
shell.echo(`🔥 Could not interpret 'version': ${version}`);
shell.exit(1);
}
})();
if (!suffix) {
shell.echo(`The CLI is not available for ${platform} ${arch}.`);
shell.exit(1);
}
const url = `https://downloads.arduino.cc/arduino-cli/${version === 'nightly' ? 'nightly/' : ''}arduino-cli-${version}-latest-${suffix}`;
shell.echo(`>>> Downloading 'arduino-cli' from '${url}'...`);
const data = await download(url);
shell.echo(`<<< Download succeeded.`);
shell.echo('>>> Decompressing CLI...');
const files = await decompress(data, downloads, {
plugins: [
unzip(),
untarbz()
]
});
shell.echo('<<< Decompressing succeeded.');
if (files.length !== 1) {
shell.echo('Error ocurred when decompressing the CLI.');
shell.exit(1);
}
if (shell.mv('-f', path.join(downloads, files[0].path), cli).code !== 0) {
shell.echo(`Could not move file to ${cli}.`);
shell.exit(1);
}
if (!fs.existsSync(cli)) {
shell.echo(`Could not find CLI at ${cli}.`);
shell.exit(1);
} else {
shell.echo('Done.');
// We assume an object with `owner`, `repo`, commitish?` properties.
const { owner, repo, commitish } = version;
if (!owner) {
shell.echo(`Could not retrieve 'owner' from ${JSON.stringify(version)}`);
shell.exit(1);
}
if (!repo) {
shell.echo(`Could not retrieve 'repo' from ${JSON.stringify(version)}`);
shell.exit(1);
}
const url = `https://github.com/${owner}/${repo}.git`;
shell.echo(`Building CLI from ${url}. Commitish: ${commitish ? commitish : 'HEAD'}`);
if (fs.existsSync(destinationPath)) {
shell.echo(`Skipping the CLI build because it already exists: ${destinationPath}`);
return;
}
if (shell.mkdir('-p', buildFolder).code !== 0) {
shell.echo('Could not create build folder.');
shell.exit(1);
}
const tempRepoPath = temp.mkdirSync();
shell.echo(`>>> Cloning CLI source to ${tempRepoPath}...`);
if (shell.exec(`git clone ${url} ${tempRepoPath}`).code !== 0) {
shell.exit(1);
}
shell.echo('<<< Cloned CLI repo.')
if (commitish) {
shell.echo(`>>> Checking out ${commitish}...`);
if (shell.exec(`git -C ${tempRepoPath} checkout ${commitish}`).code !== 0) {
shell.exit(1);
}
shell.echo(`<<< Checked out ${commitish}.`);
}
shell.echo(`>>> Building the CLI...`);
if (shell.exec('go build', { cwd: tempRepoPath }).code !== 0) {
shell.exit(1);
}
shell.echo('<<< CLI build done.')
if (!fs.existsSync(path.join(tempRepoPath, cliName))) {
shell.echo(`Could not find the CLI at ${path.join(tempRepoPath, cliName)}.`);
shell.exit(1);
}
const builtCliPath = path.join(tempRepoPath, cliName);
shell.echo(`>>> Copying CLI from ${builtCliPath} to ${destinationPath}...`);
if (shell.cp(builtCliPath, destinationPath).code !== 0) {
shell.exit(1);
}
shell.echo(`<<< Copied the CLI.`);
shell.echo('<<< Verifying CLI...');
if (!fs.existsSync(destinationPath)) {
shell.exit(1);
}
shell.echo('>>> Verified CLI.');
}
})();
})();

View File

@@ -0,0 +1,33 @@
// @ts-check
// The version to use.
const version = '1.9.0';
(async () => {
const os = require('os');
const path = require('path');
const shell = require('shelljs');
const { v4 } = require('uuid');
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-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, 'examples', '*'), destination);
})();

View File

@@ -0,0 +1,72 @@
// @ts-check
// The links to the downloads as of today (28.08.2019) are the following:
// - https://downloads.arduino.cc/arduino-language-server/nightly/arduino-language-server_${SUFFIX}
// - https://downloads.arduino.cc/arduino-language-server/clangd/clangd_${VERSION}_${SUFFIX}
(() => {
const DEFAULT_ALS_VERSION = 'nightly';
const DEFAULT_CLANGD_VERSION = 'snapshot_20210124';
const path = require('path');
const shell = require('shelljs');
const downloader = require('./downloader');
const yargs = require('yargs')
.option('ls-version', {
alias: 'lv',
default: DEFAULT_ALS_VERSION,
choices: ['nightly'],
describe: `The version of the 'arduino-language-server' to download. Defaults to ${DEFAULT_ALS_VERSION}.`
})
.option('clangd-version', {
alias: 'cv',
default: DEFAULT_CLANGD_VERSION,
choices: ['snapshot_20210124'],
describe: `The version of 'clangd' to download. Defaults to ${DEFAULT_CLANGD_VERSION}.`
})
.option('force-download', {
alias: 'fd',
default: false,
describe: `If set, this script force downloads the 'arduino-language-server' even if it already exists on the file system.`
})
.version(false).parse();
const alsVersion = yargs['ls-version'];
const clangdVersion = yargs['clangd-version']
const force = yargs['force-download'];
const { platform, arch } = process;
const build = path.join(__dirname, '..', 'build');
const lsExecutablePath = path.join(build, `arduino-language-server${platform === 'win32' ? '.exe' : ''}`);
let clangdExecutablePath, lsSuffix, clangdPrefix;
switch (platform) {
case 'darwin':
clangdExecutablePath = path.join(build, 'bin', 'clangd')
lsSuffix = 'macOS_amd64.zip';
clangdPrefix = 'mac';
break;
case 'linux':
clangdExecutablePath = path.join(build, 'bin', 'clangd')
lsSuffix = 'Linux_amd64.zip';
clangdPrefix = 'linux'
break;
case 'win32':
clangdExecutablePath = path.join(build, 'bin', 'clangd.exe')
lsSuffix = 'Windows_amd64.zip';
clangdPrefix = 'windows';
break;
}
if (!lsSuffix) {
shell.echo(`The arduino-language-server is not available for ${platform} ${arch}.`);
shell.exit(1);
}
const alsUrl = `https://downloads.arduino.cc/arduino-language-server/${alsVersion === 'nightly' ? 'nightly/arduino-language-server' : 'arduino-language-server_' + alsVersion}_${lsSuffix}`;
downloader.downloadUnzipAll(alsUrl, build, lsExecutablePath, force);
const clangdUrl = `https://downloads.arduino.cc/arduino-language-server/clangd/clangd-${clangdPrefix}-${clangdVersion}.zip`;
downloader.downloadUnzipAll(clangdUrl, build, clangdExecutablePath, force, { strip: 1 }); // `strip`: the new clangd (12.x) is zipped into a folder, so we have to strip the outmost folder.
})();

View File

@@ -0,0 +1,120 @@
const fs = require('fs');
const path = require('path');
const shell = require('shelljs');
const download = require('download');
const decompress = require('decompress');
const unzip = require('decompress-unzip');
const untargz = require('decompress-targz');
process.on('unhandledRejection', (reason, _) => {
shell.echo(String(reason));
shell.exit(1);
throw reason;
});
process.on('uncaughtException', error => {
shell.echo(String(error));
shell.exit(1);
throw error;
});
/**
* @param url {string} Download URL
* @param targetFile {string} Path to the file to copy from the decompressed archive
* @param filePrefix {string} Prefix of the file name found in the archive
* @param force {boolean} Whether to download even if the target file exists. `false` by default.
*/
exports.downloadUnzipFile = async (url, targetFile, filePrefix, force = false) => {
if (fs.existsSync(targetFile) && !force) {
shell.echo(`Skipping download because file already exists: ${targetFile}`);
return;
}
if (!fs.existsSync(path.dirname(targetFile))) {
if (shell.mkdir('-p', path.dirname(targetFile)).code !== 0) {
shell.echo('Could not create new directory.');
shell.exit(1);
}
}
const downloads = path.join(__dirname, '..', 'downloads');
if (shell.rm('-rf', targetFile, downloads).code !== 0) {
shell.exit(1);
}
shell.echo(`>>> Downloading from '${url}'...`);
const data = await download(url);
shell.echo(`<<< Download succeeded.`);
shell.echo('>>> Decompressing...');
const files = await decompress(data, downloads, {
plugins: [
unzip(),
untargz()
]
});
if (files.length === 0) {
shell.echo('Error ocurred while decompressing the archive.');
shell.exit(1);
}
const fileIndex = files.findIndex(f => f.path.startsWith(filePrefix));
if (fileIndex === -1) {
shell.echo(`The downloaded artifact does not contain any file with prefix ${filePrefix}.`);
shell.exit(1);
}
shell.echo('<<< Decompressing succeeded.');
if (shell.mv('-f', path.join(downloads, files[fileIndex].path), targetFile).code !== 0) {
shell.echo(`Could not move file to target path: ${targetFile}`);
shell.exit(1);
}
if (!fs.existsSync(targetFile)) {
shell.echo(`Could not find file: ${targetFile}`);
shell.exit(1);
}
shell.echo(`Done: ${targetFile}`);
}
/**
* @param url {string} Download URL
* @param targetDir {string} Directory into which to decompress the archive
* @param targetFile {string} Path to the main file expected after decompressing
* @param force {boolean} Whether to download even if the target file exists
*/
exports.downloadUnzipAll = async (url, targetDir, targetFile, force, decompressOptions = undefined) => {
if (fs.existsSync(targetFile) && !force) {
shell.echo(`Skipping download because file already exists: ${targetFile}`);
return;
}
if (!fs.existsSync(targetDir)) {
if (shell.mkdir('-p', targetDir).code !== 0) {
shell.echo('Could not create new directory.');
shell.exit(1);
}
}
shell.echo(`>>> Downloading from '${url}'...`);
const data = await download(url);
shell.echo(`<<< Download succeeded.`);
shell.echo('>>> Decompressing...');
let options = {
plugins: [
unzip(),
untargz()
]
};
if (decompressOptions) {
options = Object.assign(options, decompressOptions)
}
const files = await decompress(data, targetDir, options);
if (files.length === 0) {
shell.echo('Error ocurred while decompressing the archive.');
shell.exit(1);
}
shell.echo('<<< Decompressing succeeded.');
if (!fs.existsSync(targetFile)) {
shell.echo(`Could not find file: ${targetFile}`);
shell.exit(1);
}
shell.echo(`Done: ${targetFile}`);
}

View File

@@ -2,80 +2,155 @@
(async () => {
const DEFAULT_VERSION = 'nightly'; // '0.3.7-alpha.preview';
const os = require('os');
const path = require('path');
const glob = require('glob');
const { v4 } = require('uuid');
const shell = require('shelljs');
const protoc = path.dirname(require('protoc/protoc'));
shell.env.PATH = `${shell.env.PATH}${path.delimiter}${protoc}`;
shell.env.PATH = `${shell.env.PATH}${path.delimiter}${path.join(__dirname, '..', 'node_modules', '.bin')}`;
const yargs = require('yargs')
.option('cli-version', {
alias: 'cv',
default: DEFAULT_VERSION,
choices: [
// 'latest', // TODO: How do we get the source for `latest`. Currently, `latest` is the `0.3.7-alpha.preview`.
'nightly'
],
describe: `The version of the 'arduino-cli' to download. Specify either an existing version or use 'nightly'. Defaults to ${DEFAULT_VERSION}.`
})
.version(false).parse();
const version = yargs['cli-version'];
if (version !== 'nightly') {
shell.echo(`Only 'nightly' version is supported.`);
shell.exit(1);
}
const repository = path.join(os.tmpdir(), `${v4()}-arduino-cli`);
if (shell.mkdir('-p', repository).code !== 0) {
shell.exit(1);
}
if (shell.exec(`git clone https://github.com/arduino/arduino-cli.git ${repository}`).code !== 0) {
const { owner, repo, commitish } = (() => {
const pkg = require(path.join(__dirname, '..', 'package.json'));
if (!pkg) {
shell.echo(`Could not parse the 'package.json'.`);
shell.exit(1);
}
const { arduino } = pkg;
if (!arduino) {
return { owner: 'arduino', repo: 'arduino-cli' };
}
const { cli } = arduino;
if (!cli) {
return { owner: 'arduino', repo: 'arduino-cli' };
}
const { version } = cli;
if (!version) {
return { owner: 'arduino', repo: 'arduino-cli' };
}
if (typeof version === 'string') {
return { owner: 'arduino', repo: 'arduino-cli' };
}
// We assume an object with `owner`, `repo`, commitish?` properties.
const { owner, repo, commitish } = version;
if (!owner) {
shell.echo(`Could not retrieve 'owner' from ${JSON.stringify(version)}`);
shell.exit(1);
}
if (!repo) {
shell.echo(`Could not retrieve 'repo' from ${JSON.stringify(version)}`);
shell.exit(1);
}
return { owner, repo, commitish };
})();
const url = `https://github.com/${owner}/${repo}.git`;
shell.echo(`>>> Cloning repository from '${url}'...`);
if (shell.exec(`git clone ${url} ${repository}`).code !== 0) {
shell.exit(1);
}
if (version !== 'nightly') {
shell.echo(`<<< Repository cloned.`);
const { platform } = process;
const build = path.join(__dirname, '..', 'build');
const cli = path.join(build, `arduino-cli${platform === 'win32' ? '.exe' : ''}`);
const versionJson = shell.exec(`${cli} version --format json`).trim();
if (!versionJson) {
shell.echo(`Could not retrieve the CLI version from ${cli}.`);
shell.exit(1);
}
// As of today (28.01.2021), the `VersionString` can be one of the followings:
// - `nightly-YYYYMMDD` stands for the nightly build, we use the , the `commitish` from the `package.json` to check out the code.
// - `0.0.0-git` for local builds, we use the `commitish` from the `package.json` to check out the code and generate the APIs.
// - `git-snapshot` for local build executed via `task build`. We do not do this.
// - rest, we assume it is a valid semver and has the corresponding tagged code, we use the tag to generate the APIs from the `proto` files.
/*
{
"Application": "arduino-cli",
"VersionString": "nightly-20210126",
"Commit": "079bb6c6",
"Status": "alpha",
"Date": "2021-01-26T01:46:31Z"
}
*/
const versionObject = JSON.parse(versionJson);
const version = versionObject.VersionString;
if (version && !version.startsWith('nightly-') && version !== '0.0.0-git' && version !== 'git-snapshot') {
shell.echo(`>>> Checking out tagged version: '${version}'...`);
shell.exec(`git -C ${repository} fetch --all --tags`);
if (shell.exec(`git -C ${repository} checkout tags/${version} -b ${version}`).code !== 0) {
shell.exit(1);
}
shell.echo(`<<< Checked out tagged version: '${commitish}'.`);
} else if (commitish) {
shell.echo(`>>> Checking out commitish from 'package.json': '${commitish}'...`);
if (shell.exec(`git -C ${repository} checkout ${commitish}`).code !== 0) {
shell.exit(1);
}
shell.echo(`<<< Checked out commitish from 'package.json': '${commitish}'.`);
} else if (versionObject.Commit) {
shell.echo(`>>> Checking out commitish from the CLI: '${versionObject.Commit}'...`);
if (shell.exec(`git -C ${repository} checkout ${versionObject.Commit}`).code !== 0) {
shell.exit(1);
}
shell.echo(`<<< Checked out commitish from the CLI: '${versionObject.Commit}'.`);
} else {
shell.echo(`WARN: no 'git checkout'. Generating from the HEAD revision.`);
}
shell.echo('Generating TS/JS API from:');
shell.echo('>>> Generating TS/JS API from:');
if (shell.exec(`git -C ${repository} rev-parse --abbrev-ref HEAD`).code !== 0) {
shell.exit(1);
}
if (shell.exec(`git -C ${repository} rev-parse --short HEAD`).code !== 0) {
shell.exit(1);
}
const pluginExec = shell.which('grpc_tools_node_protoc_plugin');
if (!pluginExec || pluginExec.code !== 0) {
shell.exit(1);
}
const plugin = pluginExec.stdout.trim();
const rpc = path.join(repository, 'rpc');
const out = path.join(__dirname, '..', 'src', 'node', 'cli-protocol');
shell.mkdir('-p', out);
const protos = await new Promise(resolve =>
glob('**/*.proto', { cwd: rpc }, (error, matches) => {
if (error) {
shell.echo(error.stack);
resolve([]);
return;
}
resolve(matches.map(filename => path.join(rpc, filename)));
}));
if (!protos || protos.length === 0) {
shell.echo(`Could not find any .proto files under ${rpc}.`);
shell.exit(1);
}
// Generate JS code from the `.proto` files.
if (shell.exec(`grpc_tools_node_protoc \
--js_out=import_style=commonjs,binary:${out} \
--grpc_out=${out} \
--plugin=protoc-gen-grpc=${plugin} \
--grpc_out=generate_package_definition:${out} \
-I ${rpc} \
${path.join(rpc, '/**/*.proto')}`).code !== 0) {
${protos.join(' ')}`).code !== 0) {
shell.exit(1);
}
// Generate the `.d.ts` files for JS.
if (shell.exec(`protoc \
--plugin=protoc-gen-ts=${path.resolve(__dirname, '..', 'node_modules', '.bin', 'protoc-gen-ts')} \
--ts_out=${out} \
--plugin=protoc-gen-ts=${path.resolve(__dirname, '..', 'node_modules', '.bin', `protoc-gen-ts${platform === 'win32' ? '.cmd' : ''}`)} \
--ts_out=generate_package_definition:${out} \
-I ${rpc} \
${path.join(rpc, '/**/*.proto')}`).code !== 0) {
${protos.join(' ')}`).code !== 0) {
shell.exit(1);
}
const { patch } = require('./patch-grpc-js');
patch([out])
shell.echo('Done.');
shell.echo('<<< Generation was successful.');
})();
})();

View File

@@ -1,38 +0,0 @@
// Use `@grpc/grpc-js` instead of `grpc` at runtime.
// https://github.com/grpc/grpc-node/issues/624
// https://github.com/grpc/grpc-node/issues/931
const fs = require('fs');
const path = require('path');
module.exports.patch = function (roots = [path.join(__dirname, '..', 'src', 'node')]) {
console.info('🔧 <<< Patching code...');
patch(roots);
console.info('👌 <<< Done. The code has been patched.');
};
function patch(paths) {
for (const p of paths) {
const exist = fs.existsSync(p);
if (exist) {
const stat = fs.statSync(p);
if (stat.isDirectory()) {
console.info(`🔧 >>> Scanning code in ${p}...`);
patch(fs.readdirSync(p).map(name => path.join(p, name)));
} else {
let content = fs.readFileSync(p, { encoding: 'utf8' });
if (content.indexOf("require('grpc')") !== -1) {
console.info(`Updated require('grpc') to require('@grpc/grpc-js') in ${p}.`);
fs.writeFileSync(p, content.replace("require('grpc')", "require('@grpc/grpc-js')"));
}
content = fs.readFileSync(p, { encoding: 'utf8' });
if (content.indexOf('import * as grpc from "grpc"') !== -1) {
console.info(`Updated import * as grpc from "grpc" to import * as grpc from "@grpc/grpc-js" in ${p}.`);
fs.writeFileSync(p, content.replace('import * as grpc from "grpc"', 'import * as grpc from "@grpc/grpc-js"'));
}
}
} else {
console.warn(`${p} does not exist. Skipping.`);
}
}
}

View File

@@ -1,51 +1,23 @@
import { Command } from '@theia/core/lib/common/command';
/**
* @deprecated all these commands should go under contributions and have their command, menu, keybinding, and toolbar contributions.
*/
export namespace ArduinoCommands {
export const VERIFY: Command = {
id: 'arduino-verify',
label: 'Verify Sketch'
}
export const TOGGLE_COMPILE_FOR_DEBUG: Command = {
id: 'arduino-toggle-compile-for-debug'
};
export const UPLOAD: Command = {
id: 'arduino-upload',
label: 'Upload Sketch'
}
export const SHOW_OPEN_CONTEXT_MENU: Command = {
id: 'arduino-show-open-context-menu',
label: 'Open Sketch'
}
export const OPEN_FILE_NAVIGATOR: Command = {
id: 'arduino-open-file-navigator'
}
export const OPEN_SKETCH: Command = {
id: 'arduino-open-file'
}
export const SAVE_SKETCH: Command = {
id: 'arduino-save-file'
}
export const NEW_SKETCH: Command = {
id: "arduino-new-sketch",
label: 'New Sketch',
category: 'File'
}
export const REFRESH_BOARDS: Command = {
id: "arduino-refresh-attached-boards",
label: "Refresh attached boards"
}
export const SELECT_BOARD: Command = {
id: "arduino-select-board"
}
/**
* Unlike `OPEN_SKETCH`, it opens all files from a sketch folder. (ino, cpp, etc...)
*/
export const OPEN_SKETCH_FILES: Command = {
id: 'arduino-open-sketch-files'
};
export const OPEN_BOARDS_DIALOG: Command = {
id: "arduino-open-boards-dialog"
}
id: 'arduino-open-boards-dialog'
};
}

View File

@@ -1,25 +0,0 @@
import { injectable, inject } from "inversify";
import { MenuContribution, MenuModelRegistry, MenuPath } from "@theia/core";
import { CommonMenus } from "@theia/core/lib/browser";
import { ArduinoCommands } from "./arduino-commands";
export namespace ArduinoToolbarContextMenu {
export const OPEN_SKETCH_PATH: MenuPath = ['arduino-open-sketch-context-menu'];
export const OPEN_GROUP: MenuPath = [...OPEN_SKETCH_PATH, '1_open'];
export const WS_SKETCHES_GROUP: MenuPath = [...OPEN_SKETCH_PATH, '2_sketches'];
export const EXAMPLE_SKETCHES_GROUP: MenuPath = [...OPEN_SKETCH_PATH, '3_examples'];
}
@injectable()
export class ArduinoToolbarMenuContribution implements MenuContribution {
constructor(
@inject(MenuModelRegistry) protected readonly menuRegistry: MenuModelRegistry) {
}
registerMenus(registry: MenuModelRegistry) {
registry.registerMenuAction([...CommonMenus.FILE, '0_new_sletch'], {
commandId: ArduinoCommands.NEW_SKETCH.id
})
}
}

View File

@@ -1,78 +1,76 @@
import * as React from 'react';
import { injectable, inject, postConstruct } from 'inversify';
import URI from '@theia/core/lib/common/uri';
import { EditorWidget } from '@theia/editor/lib/browser/editor-widget';
import { MessageService } from '@theia/core/lib/common/message-service';
import { CommandContribution, CommandRegistry, Command } from '@theia/core/lib/common/command';
const debounce = require('lodash.debounce');
import { MAIN_MENU_BAR, MenuContribution, MenuModelRegistry, SelectionService, ILogger } from '@theia/core';
import {
ContextMenuRenderer,
FrontendApplication, FrontendApplicationContribution,
OpenerService, StatusBar, StatusBarAlignment
} from '@theia/core/lib/browser';
import { ColorContribution } from '@theia/core/lib/browser/color-application-contribution';
import { ColorRegistry } from '@theia/core/lib/browser/color-registry';
import { CommonMenus } from '@theia/core/lib/browser/common-frontend-contribution';
import { TabBarToolbarContribution, TabBarToolbarRegistry } from '@theia/core/lib/browser/shell/tab-bar-toolbar';
import { BoardsService, Board } from '../common/protocol/boards-service';
import { ArduinoCommands } from './arduino-commands';
import { ConnectedBoards } from './components/connected-boards';
import { CoreService } from '../common/protocol/core-service';
import { WorkspaceServiceExt } from './workspace-service-ext';
import { ToolOutputServiceClient } from '../common/protocol/tool-output-service';
import { QuickPickService } from '@theia/core/lib/common/quick-pick-service';
import { BoardsListWidgetFrontendContribution } from './boards/boards-widget-frontend-contribution';
import { BoardsNotificationService } from './boards-notification-service';
import { WorkspaceRootUriAwareCommandHandler, WorkspaceCommands } from '@theia/workspace/lib/browser/workspace-commands';
import { SelectionService, MenuContribution, MenuModelRegistry, MAIN_MENU_BAR } from '@theia/core';
import { WorkspaceService } from '@theia/workspace/lib/browser/workspace-service';
import { SketchFactory } from './sketch-factory';
import { ArduinoToolbar } from './toolbar/arduino-toolbar';
import { EditorManager, EditorMainMenu } from '@theia/editor/lib/browser';
import { ContextMenuRenderer, OpenerService, Widget, StatusBar } from '@theia/core/lib/browser';
import { OpenFileDialogProps, FileDialogService } from '@theia/filesystem/lib/browser/file-dialog';
import { FileSystem, FileStat } from '@theia/filesystem/lib/common';
import { ArduinoToolbarContextMenu } from './arduino-file-menu';
import { Sketch, SketchesService } from '../common/protocol/sketches-service';
import { WindowService } from '@theia/core/lib/browser/window/window-service';
import { CommonCommands, CommonMenus } from '@theia/core/lib/browser/common-frontend-contribution';
import { FileSystemCommands } from '@theia/filesystem/lib/browser/filesystem-frontend-contribution';
import { FileDownloadCommands } from '@theia/filesystem/lib/browser/download/file-download-command-contribution';
import { CommandContribution, CommandRegistry } from '@theia/core/lib/common/command';
import { MessageService } from '@theia/core/lib/common/message-service';
import URI from '@theia/core/lib/common/uri';
import { EditorMainMenu, EditorManager } from '@theia/editor/lib/browser';
import { FileDialogService } from '@theia/filesystem/lib/browser/file-dialog';
import { ProblemContribution } from '@theia/markers/lib/browser/problem/problem-contribution';
import { MonacoMenus } from '@theia/monaco/lib/browser/monaco-menu';
import { FileNavigatorContribution } from '@theia/navigator/lib/browser/navigator-contribution';
import { OutlineViewContribution } from '@theia/outline-view/lib/browser/outline-view-contribution';
import { OutputContribution } from '@theia/output/lib/browser/output-contribution';
import { ScmContribution } from '@theia/scm/lib/browser/scm-contribution';
import { SearchInWorkspaceFrontendContribution } from '@theia/search-in-workspace/lib/browser/search-in-workspace-frontend-contribution';
import { TerminalMenus } from '@theia/terminal/lib/browser/terminal-frontend-contribution';
import { MaybePromise } from '@theia/core/lib/common/types';
import { SelectBoardDialog } from './boards/select-board-dialog';
import { inject, injectable, postConstruct } from 'inversify';
import * as React from 'react';
import { remote } from 'electron';
import { MainMenuManager } from '../common/main-menu-manager';
import { BoardsService, CoreService, Port, SketchesService, ExecutableService } from '../common/protocol';
import { ArduinoDaemon } from '../common/protocol/arduino-daemon';
import { ConfigService } from '../common/protocol/config-service';
import { FileSystemExt } from '../common/protocol/filesystem-ext';
import { ArduinoCommands } from './arduino-commands';
import { BoardsConfig } from './boards/boards-config';
import { BoardsConfigDialog } from './boards/boards-config-dialog';
import { BoardsDataStore } from './boards/boards-data-store';
import { BoardsServiceProvider } from './boards/boards-service-provider';
import { BoardsToolBarItem } from './boards/boards-toolbar-item';
export namespace ArduinoMenus {
export const SKETCH = [...MAIN_MENU_BAR, '3_sketch'];
export const TOOLS = [...MAIN_MENU_BAR, '4_tools'];
}
import { EditorMode } from './editor-mode';
import { ArduinoMenus } from './menu/arduino-menus';
import { MonitorConnection } from './monitor/monitor-connection';
import { MonitorViewContribution } from './monitor/monitor-view-contribution';
import { WorkspaceService } from './theia/workspace/workspace-service';
import { ArduinoToolbar } from './toolbar/arduino-toolbar';
import { HostedPluginSupport } from '@theia/plugin-ext/lib/hosted/browser/hosted-plugin';
import { FileService } from '@theia/filesystem/lib/browser/file-service';
import { OutputService } from '../common/protocol/output-service';
import { ArduinoPreferences } from './arduino-preferences';
import { SketchesServiceClientImpl } from '../common/protocol/sketches-service-client-impl';
import { SaveAsSketch } from './contributions/save-as-sketch';
@injectable()
export class ArduinoFrontendContribution implements TabBarToolbarContribution, CommandContribution, MenuContribution {
export class ArduinoFrontendContribution implements FrontendApplicationContribution,
TabBarToolbarContribution, CommandContribution, MenuContribution, ColorContribution {
@inject(ILogger)
protected logger: ILogger;
@inject(MessageService)
protected readonly messageService: MessageService;
@inject(BoardsService)
protected readonly boardService: BoardsService;
protected readonly boardsService: BoardsService;
@inject(CoreService)
protected readonly coreService: CoreService;
@inject(WorkspaceServiceExt)
protected readonly workspaceServiceExt: WorkspaceServiceExt;
@inject(ToolOutputServiceClient)
protected readonly toolOutputServiceClient: ToolOutputServiceClient;
@inject(QuickPickService)
protected readonly quickPickService: QuickPickService;
@inject(BoardsListWidgetFrontendContribution)
protected readonly boardsListWidgetFrontendContribution: BoardsListWidgetFrontendContribution;
@inject(BoardsNotificationService)
protected readonly boardsNotificationService: BoardsNotificationService;
@inject(BoardsServiceProvider)
protected readonly boardsServiceClientImpl: BoardsServiceProvider;
@inject(SelectionService)
protected readonly selectionService: SelectionService;
@inject(SketchFactory)
protected readonly sketchFactory: SketchFactory;
@inject(EditorManager)
protected readonly editorManager: EditorManager;
@@ -82,384 +80,331 @@ export class ArduinoFrontendContribution implements TabBarToolbarContribution, C
@inject(FileDialogService)
protected readonly fileDialogService: FileDialogService;
@inject(FileSystem)
protected readonly fileSystem: FileSystem;
@inject(OpenerService)
protected readonly openerService: OpenerService;
@inject(WindowService)
protected readonly windowService: WindowService;
@inject(FileService)
protected readonly fileSystem: FileService;
@inject(SketchesService)
protected readonly sketches: SketchesService;
protected readonly sketchService: SketchesService;
@inject(SelectBoardDialog)
protected readonly selectBoardsDialog: SelectBoardDialog;
@inject(BoardsConfigDialog)
protected readonly boardsConfigDialog: BoardsConfigDialog;
@inject(MenuModelRegistry)
protected readonly menuRegistry: MenuModelRegistry;
@inject(CommandRegistry)
protected readonly commands: CommandRegistry;
protected readonly commandRegistry: CommandRegistry;
@inject(StatusBar)
protected readonly statusBar: StatusBar;
protected boardsToolbarItem: BoardsToolBarItem | null;
protected wsSketchCount: number = 0;
@inject(WorkspaceService)
protected readonly workspaceService: WorkspaceService;
constructor(@inject(WorkspaceService) protected readonly workspaceService: WorkspaceService) {
this.workspaceService.onWorkspaceChanged(() => {
if (this.workspaceService.workspace) {
this.registerSketchesInMenu(this.menuRegistry);
}
})
}
@inject(MonitorConnection)
protected readonly monitorConnection: MonitorConnection;
@inject(FileNavigatorContribution)
protected readonly fileNavigatorContributions: FileNavigatorContribution;
@inject(OutputContribution)
protected readonly outputContribution: OutputContribution;
@inject(OutlineViewContribution)
protected readonly outlineContribution: OutlineViewContribution;
@inject(ProblemContribution)
protected readonly problemContribution: ProblemContribution;
@inject(ScmContribution)
protected readonly scmContribution: ScmContribution;
@inject(SearchInWorkspaceFrontendContribution)
protected readonly siwContribution: SearchInWorkspaceFrontendContribution;
@inject(EditorMode)
protected readonly editorMode: EditorMode;
@inject(ArduinoDaemon)
protected readonly daemon: ArduinoDaemon;
@inject(OpenerService)
protected readonly openerService: OpenerService;
@inject(ConfigService)
protected readonly configService: ConfigService;
@inject(BoardsDataStore)
protected readonly boardsDataStore: BoardsDataStore;
@inject(MainMenuManager)
protected readonly mainMenuManager: MainMenuManager;
@inject(FileSystemExt)
protected readonly fileSystemExt: FileSystemExt;
@inject(HostedPluginSupport)
protected hostedPluginSupport: HostedPluginSupport;
@inject(ExecutableService)
protected executableService: ExecutableService;
@inject(OutputService)
protected readonly outputService: OutputService;
@inject(ArduinoPreferences)
protected readonly arduinoPreferences: ArduinoPreferences;
@inject(SketchesServiceClientImpl)
protected readonly sketchServiceClient: SketchesServiceClientImpl;
protected invalidConfigPopup: Promise<void | 'No' | 'Yes' | undefined> | undefined;
@postConstruct()
protected async init(): Promise<void> {
// This is a hack. Otherwise, the backend services won't bind.
await this.workspaceServiceExt.roots();
if (!window.navigator.onLine) {
// tslint:disable-next-line:max-line-length
this.messageService.warn('You appear to be offline. Without an Internet connection, the Arduino CLI might not be able to download the required resources and could cause malfunction. Please connect to the Internet and restart the application.');
}
const updateStatusBar = ({ selectedBoard, selectedPort }: BoardsConfig.Config) => {
this.statusBar.setElement('arduino-selected-board', {
alignment: StatusBarAlignment.RIGHT,
text: selectedBoard ? `$(microchip) ${selectedBoard.name}` : '$(close) no board selected',
className: 'arduino-selected-board'
});
if (selectedBoard) {
this.statusBar.setElement('arduino-selected-port', {
alignment: StatusBarAlignment.RIGHT,
text: selectedPort ? `on ${Port.toString(selectedPort)}` : '[not connected]',
className: 'arduino-selected-port'
});
}
}
this.boardsServiceClientImpl.onBoardsConfigChanged(updateStatusBar);
updateStatusBar(this.boardsServiceClientImpl.boardsConfig);
}
onStart(app: FrontendApplication): void {
// Initialize all `pro-mode` widgets. This is a NOOP if in normal mode.
for (const viewContribution of [
this.fileNavigatorContributions,
this.outputContribution,
this.outlineContribution,
this.problemContribution,
this.scmContribution,
this.siwContribution] as Array<FrontendApplicationContribution>) {
if (viewContribution.initializeLayout) {
viewContribution.initializeLayout(app);
}
}
const start = async ({ selectedBoard }: BoardsConfig.Config) => {
if (selectedBoard) {
const { name, fqbn } = selectedBoard;
if (fqbn) {
await this.hostedPluginSupport.didStart;
this.startLanguageServer(fqbn, name);
}
}
};
this.boardsServiceClientImpl.onBoardsConfigChanged(start);
this.arduinoPreferences.onPreferenceChanged(event => {
if (event.preferenceName === 'arduino.language.log' && event.newValue !== event.oldValue) {
start(this.boardsServiceClientImpl.boardsConfig);
}
});
this.arduinoPreferences.ready.then(() => {
const webContents = remote.getCurrentWebContents();
const zoomLevel = this.arduinoPreferences.get('arduino.window.zoomLevel');
webContents.setZoomLevel(zoomLevel);
});
this.arduinoPreferences.onPreferenceChanged(event => {
if (event.preferenceName === 'arduino.window.zoomLevel' && typeof event.newValue === 'number' && event.newValue !== event.oldValue) {
const webContents = remote.getCurrentWebContents();
webContents.setZoomLevel(event.newValue || 0);
}
});
}
protected startLanguageServer = debounce((fqbn: string, name: string | undefined) => this.doStartLanguageServer(fqbn, name));
protected async doStartLanguageServer(fqbn: string, name: string | undefined): Promise<void> {
this.logger.info(`Starting language server: ${fqbn}`);
const log = this.arduinoPreferences.get('arduino.language.log');
let currentSketchPath: string | undefined = undefined;
if (log) {
const currentSketch = await this.sketchServiceClient.currentSketch();
if (currentSketch) {
currentSketchPath = await this.fileSystem.fsPath(new URI(currentSketch.uri));
}
}
const { clangdUri, cliUri, lsUri } = await this.executableService.list();
const [clangdPath, cliPath, lsPath] = await Promise.all([
this.fileSystem.fsPath(new URI(clangdUri)),
this.fileSystem.fsPath(new URI(cliUri)),
this.fileSystem.fsPath(new URI(lsUri)),
]);
this.commandRegistry.executeCommand('arduino.languageserver.start', {
lsPath,
cliPath,
clangdPath,
log: currentSketchPath ? currentSketchPath : log,
board: {
fqbn,
name: name ? `"${name}"` : undefined
}
});
}
registerToolbarItems(registry: TabBarToolbarRegistry): void {
registry.registerItem({
id: ArduinoCommands.VERIFY.id,
command: ArduinoCommands.VERIFY.id,
tooltip: 'Verify',
text: '$(check)'
});
registry.registerItem({
id: ArduinoCommands.UPLOAD.id,
command: ArduinoCommands.UPLOAD.id,
tooltip: 'Upload',
text: '$(arrow-right)'
});
registry.registerItem({
id: ArduinoCommands.SHOW_OPEN_CONTEXT_MENU.id,
command: ArduinoCommands.SHOW_OPEN_CONTEXT_MENU.id,
tooltip: 'Open',
text: '$(arrow-up)'
});
registry.registerItem({
id: ArduinoCommands.SAVE_SKETCH.id,
command: ArduinoCommands.SAVE_SKETCH.id,
tooltip: 'Save',
text: '$(arrow-down)'
});
registry.registerItem({
id: ConnectedBoards.TOOLBAR_ID,
id: BoardsToolBarItem.TOOLBAR_ID,
render: () => <BoardsToolBarItem
key='boardsToolbarItem'
ref={ref => this.boardsToolbarItem = ref}
commands={this.commands}
statusBar={this.statusBar}
contextMenuRenderer={this.contextMenuRenderer}
boardsNotificationService={this.boardsNotificationService}
boardService={this.boardService} />,
isVisible: widget => this.isArduinoToolbar(widget)
})
commands={this.commandRegistry}
boardsServiceClient={this.boardsServiceClientImpl} />,
isVisible: widget => ArduinoToolbar.is(widget) && widget.side === 'left',
priority: 7
});
registry.registerItem({
id: 'toggle-serial-monitor',
command: MonitorViewContribution.TOGGLE_SERIAL_MONITOR_TOOLBAR,
tooltip: 'Serial Monitor'
});
}
registerCommands(registry: CommandRegistry): void {
registry.registerCommand(ArduinoCommands.VERIFY, {
isVisible: widget => this.isArduinoToolbar(widget),
isEnabled: widget => true,
execute: async () => {
const widget = this.getCurrentWidget();
if (widget instanceof EditorWidget) {
await widget.saveable.save();
}
const uri = this.toUri(widget);
if (!uri) {
return;
}
try {
await this.coreService.compile({ uri: uri.toString() });
} catch (e) {
await this.messageService.error(e.toString());
}
registry.registerCommand(ArduinoCommands.TOGGLE_COMPILE_FOR_DEBUG, {
execute: () => this.editorMode.toggleCompileForDebug(),
isToggled: () => this.editorMode.compileForDebug
});
registry.registerCommand(ArduinoCommands.OPEN_SKETCH_FILES, {
execute: async (uri: URI) => {
this.openSketchFiles(uri);
}
});
registry.registerCommand(ArduinoCommands.UPLOAD, {
isVisible: widget => this.isArduinoToolbar(widget),
isEnabled: widget => true,
execute: async () => {
const widget = this.getCurrentWidget();
if (widget instanceof EditorWidget) {
await widget.saveable.save();
}
const uri = this.toUri(widget);
if (!uri) {
return;
}
try {
await this.coreService.upload({ uri: uri.toString() });
} catch (e) {
await this.messageService.error(e.toString());
}
}
});
registry.registerCommand(ArduinoCommands.SHOW_OPEN_CONTEXT_MENU, {
isVisible: widget => this.isArduinoToolbar(widget),
isEnabled: widget => this.isArduinoToolbar(widget),
execute: async (widget: Widget, target: EventTarget) => {
if (this.wsSketchCount) {
const el = (target as HTMLElement).parentElement;
if (el) {
this.contextMenuRenderer.render(ArduinoToolbarContextMenu.OPEN_SKETCH_PATH, {
x: el.getBoundingClientRect().left,
y: el.getBoundingClientRect().top + el.offsetHeight
});
}
} else {
this.commands.executeCommand(ArduinoCommands.OPEN_FILE_NAVIGATOR.id);
}
}
});
registry.registerCommand(ArduinoCommands.OPEN_FILE_NAVIGATOR, {
isEnabled: () => true,
execute: () => this.doOpenFile()
})
registry.registerCommand(ArduinoCommands.OPEN_SKETCH, {
isEnabled: () => true,
execute: async (sketch: Sketch) => {
this.openSketchFilesInNewWindow(sketch.uri);
}
})
registry.registerCommand(ArduinoCommands.SAVE_SKETCH, {
isEnabled: widget => this.isArduinoToolbar(widget),
isVisible: widget => this.isArduinoToolbar(widget),
execute: async (sketch: Sketch) => {
registry.executeCommand(CommonCommands.SAVE_ALL.id);
}
})
registry.registerCommand(ArduinoCommands.NEW_SKETCH, new WorkspaceRootUriAwareCommandHandler(this.workspaceService, this.selectionService, {
execute: async uri => {
try {
// hack: sometimes we don't get the workspace root, but the currently active file: correct for that
if (uri.path.ext !== "") {
uri = uri.withPath(uri.path.dir.dir);
}
await this.sketchFactory.createNewSketch(uri);
} catch (e) {
await this.messageService.error(e.toString());
}
}
}));
registry.registerCommand(ArduinoCommands.REFRESH_BOARDS, {
isEnabled: () => true,
execute: () => this.boardsNotificationService.notifyBoardsInstalled()
});
registry.registerCommand(ArduinoCommands.SELECT_BOARD, {
isEnabled: () => true,
execute: async (board: Board) => {
this.selectBoard(board);
}
})
registry.registerCommand(ArduinoCommands.OPEN_BOARDS_DIALOG, {
isEnabled: () => true,
execute: async () => {
const boardAndPort = await this.selectBoardsDialog.open();
if (boardAndPort && boardAndPort.board) {
this.selectBoard(boardAndPort.board);
execute: async (query?: string | undefined) => {
const boardsConfig = await this.boardsConfigDialog.open(query);
if (boardsConfig) {
this.boardsServiceClientImpl.boardsConfig = boardsConfig;
}
}
})
});
}
protected async selectBoard(board: Board) {
await this.boardService.selectBoard(board);
if (this.boardsToolbarItem) {
this.boardsToolbarItem.setSelectedBoard(board);
}
}
registerMenus(registry: MenuModelRegistry) {
registry.unregisterMenuAction(FileSystemCommands.UPLOAD);
registry.unregisterMenuAction(FileDownloadCommands.DOWNLOAD);
registry.unregisterMenuAction(WorkspaceCommands.NEW_FILE);
registry.unregisterMenuAction(WorkspaceCommands.NEW_FOLDER);
registry.unregisterMenuAction(WorkspaceCommands.OPEN_FOLDER);
registry.unregisterMenuAction(WorkspaceCommands.OPEN_WORKSPACE);
registry.unregisterMenuAction(WorkspaceCommands.OPEN_RECENT_WORKSPACE);
registry.unregisterMenuAction(WorkspaceCommands.SAVE_WORKSPACE_AS);
registry.unregisterMenuAction(WorkspaceCommands.CLOSE);
registry.getMenu(MAIN_MENU_BAR).removeNode(this.getMenuId(MonacoMenus.SELECTION));
registry.getMenu(MAIN_MENU_BAR).removeNode(this.getMenuId(EditorMainMenu.GO));
registry.getMenu(MAIN_MENU_BAR).removeNode(this.getMenuId(TerminalMenus.TERMINAL));
registry.getMenu(MAIN_MENU_BAR).removeNode(this.getMenuId(CommonMenus.VIEW));
registry.getMenu(MAIN_MENU_BAR).removeNode(this.getMenuId(CommonMenus.HELP));
const menuId = (menuPath: string[]): string => {
const index = menuPath.length - 1;
const menuId = menuPath[index];
return menuId;
}
registry.getMenu(MAIN_MENU_BAR).removeNode(menuId(MonacoMenus.SELECTION));
registry.getMenu(MAIN_MENU_BAR).removeNode(menuId(EditorMainMenu.GO));
registry.getMenu(MAIN_MENU_BAR).removeNode(menuId(TerminalMenus.TERMINAL));
registry.getMenu(MAIN_MENU_BAR).removeNode(menuId(CommonMenus.VIEW));
registry.registerSubmenu(ArduinoMenus.SKETCH, 'Sketch');
registry.registerMenuAction(ArduinoMenus.SKETCH, {
commandId: ArduinoCommands.VERIFY.id,
label: 'Verify/Compile',
order: '1'
});
registry.registerMenuAction(ArduinoMenus.SKETCH, {
commandId: ArduinoCommands.UPLOAD.id,
label: 'Upload',
order: '2'
});
registry.registerMenuAction(ArduinoToolbarContextMenu.OPEN_GROUP, {
commandId: ArduinoCommands.OPEN_FILE_NAVIGATOR.id,
label: 'Open...'
});
registry.registerSubmenu(ArduinoMenus.TOOLS, 'Tools');
registry.registerMenuAction(ArduinoMenus.SKETCH__MAIN_GROUP, {
commandId: ArduinoCommands.TOGGLE_COMPILE_FOR_DEBUG.id,
label: 'Optimize for Debugging',
order: '4'
});
}
protected getMenuId(menuPath: string[]): string {
const index = menuPath.length - 1;
const menuId = menuPath[index];
return menuId;
}
protected registerSketchesInMenu(registry: MenuModelRegistry) {
this.getWorkspaceSketches().then(sketches => {
this.wsSketchCount = sketches.length;
sketches.forEach(sketch => {
const command: Command = {
id: 'openSketch' + sketch.name
}
this.commands.registerCommand(command, {
execute: () => this.commands.executeCommand(ArduinoCommands.OPEN_SKETCH.id, sketch)
protected async openSketchFiles(uri: URI): Promise<void> {
try {
const sketch = await this.sketchService.loadSketch(uri.toString());
const { mainFileUri, rootFolderFileUris } = sketch;
for (const uri of [mainFileUri, ...rootFolderFileUris]) {
await this.ensureOpened(uri);
}
await this.ensureOpened(mainFileUri, true);
if (mainFileUri.endsWith('.pde')) {
const message = `The '${sketch.name}' still uses the old \`.pde\` format. Do you want to switch to the new \`.ino\` extension?`;
this.messageService.info(message, 'Later', 'Yes').then(async answer => {
if (answer === 'Yes') {
this.commandRegistry.executeCommand(SaveAsSketch.Commands.SAVE_AS_SKETCH.id, { execOnlyIfTemp: false, openAfterMove: true, wipeOriginal: false });
}
});
registry.registerMenuAction(ArduinoToolbarContextMenu.WS_SKETCHES_GROUP, {
commandId: command.id,
label: sketch.name
});
})
})
}
protected async getWorkspaceSketches(): Promise<Sketch[]> {
const sketches = this.sketches.getSketches(this.workspaceService.workspace);
return sketches;
}
protected async openSketchFilesInNewWindow(uri: string) {
const location = new URL(window.location.href);
location.searchParams.set('sketch', uri);
this.windowService.openNewWindow(location.toString());
}
async openSketchFiles(uri: string) {
const fileStat = await this.fileSystem.getFileStat(uri);
if (fileStat) {
const uris = await this.sketches.getSketchFiles(fileStat);
for (const uri of uris) {
this.editorManager.open(new URI(uri));
}
} catch (e) {
console.error(e);
const message = e instanceof Error ? e.message : JSON.stringify(e);
this.messageService.error(message);
}
}
/**
* Opens a file after prompting the `Open File` dialog. Resolves to `undefined`, if
* - the workspace root is not set,
* - the file to open does not exist, or
* - it was not a file, but a directory.
*
* Otherwise, resolves to the URI of the file.
*/
protected async doOpenFile(): Promise<URI | undefined> {
const props: OpenFileDialogProps = {
title: WorkspaceCommands.OPEN_FILE.dialogLabel,
canSelectFolders: false,
canSelectFiles: true
};
const [rootStat] = await this.workspaceService.roots;
const destinationFileUri = await this.fileDialogService.showOpenDialog(props, rootStat);
if (destinationFileUri) {
const destinationFile = await this.fileSystem.getFileStat(destinationFileUri.toString());
if (destinationFile && !destinationFile.isDirectory) {
const message = await this.validate(destinationFile);
if (!message) {
await this.openSketchFilesInNewWindow(destinationFileUri.toString());
return destinationFileUri;
} else {
this.messageService.warn(message);
}
protected async ensureOpened(uri: string, forceOpen: boolean = false): Promise<any> {
const widget = this.editorManager.all.find(widget => widget.editor.uri.toString() === uri);
if (!widget || forceOpen) {
return this.editorManager.open(new URI(uri));
}
}
registerColors(colors: ColorRegistry): void {
colors.register(
{
id: 'arduino.branding.primary',
defaults: {
dark: 'statusBar.background',
light: 'statusBar.background'
},
description: 'The primary branding color, such as dialog titles, library, and board manager list labels.'
},
{
id: 'arduino.branding.secondary',
defaults: {
dark: 'statusBar.background',
light: 'statusBar.background'
},
description: 'Secondary branding color for list selections, dropdowns, and widget borders.'
},
{
id: 'arduino.foreground',
defaults: {
dark: 'editorWidget.background',
light: 'editorWidget.background',
hc: 'editorWidget.background'
},
description: 'Color of the Arduino IDE foreground which is used for dialogs, such as the Select Board dialog.'
},
{
id: 'arduino.toolbar.background',
defaults: {
dark: 'button.background',
light: 'button.background',
hc: 'activityBar.inactiveForeground'
},
description: 'Background color of the toolbar items. Such as Upload, Verify, etc.'
},
{
id: 'arduino.toolbar.hoverBackground',
defaults: {
dark: 'button.hoverBackground',
light: 'button.hoverBackground',
hc: 'activityBar.inactiveForeground'
},
description: 'Background color of the toolbar items when hovering over them. Such as Upload, Verify, etc.'
},
{
id: 'arduino.output.foreground',
defaults: {
dark: 'editor.foreground',
light: 'editor.foreground',
hc: 'editor.foreground'
},
description: 'Color of the text in the Output view.'
},
{
id: 'arduino.output.background',
defaults: {
dark: 'editor.background',
light: 'editor.background',
hc: 'editor.background'
},
description: 'Background color of the Output view.'
}
}
return undefined;
}
protected getCurrentWidget(): EditorWidget | undefined {
let widget = this.editorManager.currentEditor;
if (!widget) {
const visibleWidgets = this.editorManager.all.filter(w => w.isVisible);
if (visibleWidgets.length > 0) {
widget = visibleWidgets[0];
}
}
return widget;
}
/**
* Returns `undefined` if the `file` is valid. Otherwise, returns with the validation error message.
*/
protected validate(file: FileStat): MaybePromise<string | undefined> {
const uri = new URI(file.uri);
const path = uri.path;
const { name, ext, dir } = path;
if (ext !== '.ino') {
return "Only sketches with '.ino' extension can be opened.";
}
if (name !== dir.name) {
return `The file "${name}${ext}" needs to be inside a sketch folder named "${name}".`;
}
return undefined;
}
// private async onNoBoardsInstalled() {
// const action = await this.messageService.info("You have no boards installed. Use the boards manager to install one.", "Open Boards Manager");
// if (!action) {
// return;
// }
// this.boardsListWidgetFrontendContribution.openView({ reveal: true });
// }
// private async onUnknownBoard() {
// const action = await this.messageService.warn("There's a board connected for which you need to install software." +
// " If this were not a PoC we would offer you the right package now.", "Open Boards Manager");
// if (!action) {
// return;
// }
// this.boardsListWidgetFrontendContribution.openView({ reveal: true });
// }
private isArduinoToolbar(maybeToolbarWidget: any): boolean {
if (maybeToolbarWidget instanceof ArduinoToolbar) {
return true;
}
return false;
}
private toUri(arg: any): URI | undefined {
if (arg instanceof URI) {
return arg;
}
if (typeof arg === 'string') {
return new URI(arg);
}
if (arg instanceof EditorWidget) {
return arg.editor.uri;
}
return undefined;
);
}
}

View File

@@ -1,161 +0,0 @@
import '../../src/browser/style/index.css';
import { ContainerModule, interfaces } from 'inversify';
import { WidgetFactory } from '@theia/core/lib/browser/widget-manager';
import { CommandContribution } from '@theia/core/lib/common/command';
import { bindViewContribution } from '@theia/core/lib/browser/shell/view-contribution';
import { TabBarToolbarContribution } from '@theia/core/lib/browser/shell/tab-bar-toolbar';
import { WebSocketConnectionProvider } from '@theia/core/lib/browser/messaging/ws-connection-provider';
import { FrontendApplicationContribution, FrontendApplication } from '@theia/core/lib/browser/frontend-application'
import { LanguageGrammarDefinitionContribution } from '@theia/monaco/lib/browser/textmate';
import { LibraryListWidget } from './library/library-list-widget';
import { ArduinoFrontendContribution } from './arduino-frontend-contribution';
import { ArduinoLanguageGrammarContribution } from './language/arduino-language-grammar-contribution';
import { LibraryService, LibraryServicePath } from '../common/protocol/library-service';
import { BoardsService, BoardsServicePath } from '../common/protocol/boards-service';
import { SketchesService, SketchesServicePath } from '../common/protocol/sketches-service';
import { LibraryListWidgetFrontendContribution } from './library/list-widget-frontend-contribution';
import { CoreService, CoreServicePath } from '../common/protocol/core-service';
import { BoardsListWidget } from './boards/boards-list-widget';
import { BoardsListWidgetFrontendContribution } from './boards/boards-widget-frontend-contribution';
import { WorkspaceServiceExt, WorkspaceServiceExtPath } from './workspace-service-ext';
import { WorkspaceServiceExtImpl } from './workspace-service-ext-impl';
import { ToolOutputServiceClient } from '../common/protocol/tool-output-service';
import { ToolOutputService } from '../common/protocol/tool-output-service';
import { ToolOutputServiceClientImpl } from './tool-output/client-service-impl';
import { BoardsNotificationService } from './boards-notification-service';
import { WorkspaceService } from '@theia/workspace/lib/browser/workspace-service';
import { AWorkspaceService } from './arduino-workspace-service';
import { ThemeService } from '@theia/core/lib/browser/theming';
import { ArduinoTheme } from './arduino-theme';
import { ArduinoToolbarMenuContribution } from './arduino-file-menu';
import { MenuContribution } from '@theia/core';
import { SketchFactory } from './sketch-factory';
import { OutlineViewContribution } from '@theia/outline-view/lib/browser/outline-view-contribution';
import { SilentOutlineViewContribution } from './customization/silent-outline-contribution';
import { ProblemContribution } from '@theia/markers/lib/browser/problem/problem-contribution';
import { SilentProblemContribution } from './customization/silent-problem-contribution';
import { SilentNavigatorContribution } from './customization/silent-navigator-contribution';
import { FileNavigatorContribution } from '@theia/navigator/lib/browser/navigator-contribution';
import { ArduinoToolbarContribution } from './toolbar/arduino-toolbar-contribution';
import { OutputToolbarContribution } from '@theia/output/lib/browser/output-toolbar-contribution';
import { ArduinoOutputToolContribution } from './customization/silent-output-tool-contribution';
import { EditorContribution } from '@theia/editor/lib/browser/editor-contribution';
import { CustomEditorContribution } from './customization/custom-editor-contribution';
import { MonacoStatusBarContribution } from '@theia/monaco/lib/browser/monaco-status-bar-contribution';
import { SilentMonacoStatusBarContribution } from './customization/silent-monaco-status-bar-contribution';
import { ApplicationShell } from '@theia/core/lib/browser';
import { CustomApplicationShell } from './customization/custom-application-shell';
import { CustomFrontendApplication } from './customization/custom-frontend-application';
import { EditorWidgetFactory } from '@theia/editor/lib/browser/editor-widget-factory';
import { CustomEditorWidgetFactory } from './customization/custom-editor-widget-factory';
import { SelectBoardDialog, SelectBoardDialogProps } from './boards/select-board-dialog';
import { SelectBoardDialogWidget } from './boards/select-board-dialog-widget';
const ElementQueries = require('css-element-queries/src/ElementQueries');
export default new ContainerModule((bind: interfaces.Bind, unbind: interfaces.Unbind, isBound: interfaces.IsBound, rebind: interfaces.Rebind) => {
ElementQueries.listen();
ElementQueries.init();
// Commands and toolbar items
bind(ArduinoFrontendContribution).toSelf().inSingletonScope();
bind(CommandContribution).toService(ArduinoFrontendContribution);
bind(MenuContribution).toService(ArduinoFrontendContribution);
bind(TabBarToolbarContribution).toService(ArduinoFrontendContribution);
bind(FrontendApplicationContribution).toService(ArduinoFrontendContribution);
bind(MenuContribution).to(ArduinoToolbarMenuContribution).inSingletonScope();
bind(ArduinoToolbarContribution).toSelf().inSingletonScope();
bind(FrontendApplicationContribution).toService(ArduinoToolbarContribution);
// `ino` TextMate grammar
bind(LanguageGrammarDefinitionContribution).to(ArduinoLanguageGrammarContribution).inSingletonScope();
// Library service
bind(LibraryService).toDynamicValue(context => WebSocketConnectionProvider.createProxy(context.container, LibraryServicePath)).inSingletonScope();
// Library list widget
bind(LibraryListWidget).toSelf();
bindViewContribution(bind, LibraryListWidgetFrontendContribution);
bind(WidgetFactory).toDynamicValue(context => ({
id: LibraryListWidget.WIDGET_ID,
createWidget: () => context.container.get(LibraryListWidget)
}));
bind(FrontendApplicationContribution).toService(LibraryListWidgetFrontendContribution);
// Sketch list service
bind(SketchesService).toDynamicValue(context => WebSocketConnectionProvider.createProxy(context.container, SketchesServicePath)).inSingletonScope();
// Boards Notification service for updating boards list
// TODO (post-PoC): move this to boards service/backend
bind(BoardsNotificationService).toSelf().inSingletonScope();
// Boards service
bind(BoardsService).toDynamicValue(context => WebSocketConnectionProvider.createProxy(context.container, BoardsServicePath)).inSingletonScope();
// Boards list widget
bind(BoardsListWidget).toSelf();
bindViewContribution(bind, BoardsListWidgetFrontendContribution);
bind(WidgetFactory).toDynamicValue(context => ({
id: BoardsListWidget.WIDGET_ID,
createWidget: () => context.container.get(BoardsListWidget)
}));
bind(FrontendApplicationContribution).toService(BoardsListWidgetFrontendContribution);
// Board select dialog
bind(SelectBoardDialogWidget).toSelf().inSingletonScope();
bind(SelectBoardDialog).toSelf().inSingletonScope();
bind(SelectBoardDialogProps).toConstantValue({
title: 'Select Board'
})
// Core service
bind(CoreService)
.toDynamicValue(context => WebSocketConnectionProvider.createProxy(context.container, CoreServicePath))
.inSingletonScope();
// Tool output service client
bind(ToolOutputServiceClientImpl).toSelf().inSingletonScope();
bind(ToolOutputServiceClient).toDynamicValue(context => {
const client = context.container.get(ToolOutputServiceClientImpl);
WebSocketConnectionProvider.createProxy(context.container, ToolOutputService.SERVICE_PATH, client);
return client;
}).inSingletonScope();
// The workspace service extension
bind(WorkspaceServiceExt).to(WorkspaceServiceExtImpl).inSingletonScope().onActivation(({ container }, workspaceServiceExt) => {
WebSocketConnectionProvider.createProxy(container, WorkspaceServiceExtPath, workspaceServiceExt);
// Eagerly active the core, library, and boards services.
container.get(CoreService);
container.get(LibraryService);
container.get(BoardsService);
container.get(SketchesService);
return workspaceServiceExt;
});
bind(AWorkspaceService).toSelf().inSingletonScope();
rebind(WorkspaceService).to(AWorkspaceService).inSingletonScope();
bind(SketchFactory).toSelf().inSingletonScope();
const themeService = ThemeService.get();
themeService.register(...ArduinoTheme.themes);
// customizing default theia
unbind(OutlineViewContribution);
bind(OutlineViewContribution).to(SilentOutlineViewContribution).inSingletonScope();
unbind(ProblemContribution);
bind(ProblemContribution).to(SilentProblemContribution).inSingletonScope();
unbind(FileNavigatorContribution);
bind(FileNavigatorContribution).to(SilentNavigatorContribution).inSingletonScope();
unbind(OutputToolbarContribution);
bind(OutputToolbarContribution).to(ArduinoOutputToolContribution).inSingletonScope();
unbind(EditorContribution);
bind(EditorContribution).to(CustomEditorContribution).inSingletonScope();
unbind(MonacoStatusBarContribution);
bind(MonacoStatusBarContribution).to(SilentMonacoStatusBarContribution).inSingletonScope();
unbind(ApplicationShell);
bind(ApplicationShell).to(CustomApplicationShell).inSingletonScope();
unbind(FrontendApplication);
bind(FrontendApplication).to(CustomFrontendApplication).inSingletonScope();
unbind(EditorWidgetFactory);
bind(EditorWidgetFactory).to(CustomEditorWidgetFactory).inSingletonScope();
});

View File

@@ -0,0 +1,403 @@
import '../../src/browser/style/index.css';
import { ContainerModule } from 'inversify';
import { WidgetFactory } from '@theia/core/lib/browser/widget-manager';
import { CommandContribution } from '@theia/core/lib/common/command';
import { bindViewContribution } from '@theia/core/lib/browser/shell/view-contribution';
import { TabBarToolbarContribution, TabBarToolbarFactory } from '@theia/core/lib/browser/shell/tab-bar-toolbar';
import { WebSocketConnectionProvider } from '@theia/core/lib/browser/messaging/ws-connection-provider';
import { FrontendApplicationContribution, FrontendApplication as TheiaFrontendApplication } from '@theia/core/lib/browser/frontend-application'
import { LibraryListWidget } from './library/library-list-widget';
import { ArduinoFrontendContribution } from './arduino-frontend-contribution';
import { LibraryService, LibraryServicePath } from '../common/protocol/library-service';
import { BoardsService, BoardsServicePath } from '../common/protocol/boards-service';
import { SketchesService, SketchesServicePath } from '../common/protocol/sketches-service';
import { SketchesServiceClientImpl } from '../common/protocol/sketches-service-client-impl';
import { CoreService, CoreServicePath } from '../common/protocol/core-service';
import { BoardsListWidget } from './boards/boards-list-widget';
import { BoardsListWidgetFrontendContribution } from './boards/boards-widget-frontend-contribution';
import { BoardsServiceProvider } from './boards/boards-service-provider';
import { WorkspaceService as TheiaWorkspaceService } from '@theia/workspace/lib/browser/workspace-service';
import { WorkspaceService } from './theia/workspace/workspace-service';
import { OutlineViewContribution as TheiaOutlineViewContribution } from '@theia/outline-view/lib/browser/outline-view-contribution';
import { OutlineViewContribution } from './theia/outline/outline-contribution';
import { ProblemContribution as TheiaProblemContribution } from '@theia/markers/lib/browser/problem/problem-contribution';
import { ProblemContribution } from './theia/markers/problem-contribution';
import { FileNavigatorContribution } from './theia/navigator/navigator-contribution';
import { FileNavigatorContribution as TheiaFileNavigatorContribution } from '@theia/navigator/lib/browser/navigator-contribution';
import { ArduinoToolbarContribution } from './toolbar/arduino-toolbar-contribution';
import { EditorContribution as TheiaEditorContribution } from '@theia/editor/lib/browser/editor-contribution';
import { EditorContribution } from './theia/editor/editor-contribution';
import { MonacoStatusBarContribution as TheiaMonacoStatusBarContribution } from '@theia/monaco/lib/browser/monaco-status-bar-contribution';
import { MonacoStatusBarContribution } from './theia/monaco/monaco-status-bar-contribution';
import {
ApplicationShell as TheiaApplicationShell,
ShellLayoutRestorer as TheiaShellLayoutRestorer,
CommonFrontendContribution as TheiaCommonFrontendContribution,
KeybindingRegistry as TheiaKeybindingRegistry,
TabBarRendererFactory,
ContextMenuRenderer
} from '@theia/core/lib/browser';
import { MenuContribution } from '@theia/core/lib/common/menu';
import { ApplicationShell } from './theia/core/application-shell';
import { FrontendApplication } from './theia/core/frontend-application';
import { BoardsConfigDialog, BoardsConfigDialogProps } from './boards/boards-config-dialog';
import { BoardsConfigDialogWidget } from './boards/boards-config-dialog-widget';
import { ScmContribution as TheiaScmContribution } from '@theia/scm/lib/browser/scm-contribution';
import { ScmContribution } from './theia/scm/scm-contribution';
import { SearchInWorkspaceFrontendContribution as TheiaSearchInWorkspaceFrontendContribution } from '@theia/search-in-workspace/lib/browser/search-in-workspace-frontend-contribution';
import { SearchInWorkspaceFrontendContribution } from './theia/search-in-workspace/search-in-workspace-frontend-contribution';
import { LibraryListWidgetFrontendContribution } from './library/library-widget-frontend-contribution';
import { MonitorServiceClientImpl } from './monitor/monitor-service-client-impl';
import { MonitorServicePath, MonitorService, MonitorServiceClient } from '../common/protocol/monitor-service';
import { ConfigService, ConfigServicePath } from '../common/protocol/config-service';
import { MonitorWidget } from './monitor/monitor-widget';
import { MonitorViewContribution } from './monitor/monitor-view-contribution';
import { MonitorConnection } from './monitor/monitor-connection';
import { MonitorModel } from './monitor/monitor-model';
import { TabBarDecoratorService as TheiaTabBarDecoratorService } from '@theia/core/lib/browser/shell/tab-bar-decorator';
import { TabBarDecoratorService } from './theia/core/tab-bar-decorator';
import { ProblemManager as TheiaProblemManager } from '@theia/markers/lib/browser';
import { ProblemManager } from './theia/markers/problem-manager';
import { BoardsAutoInstaller } from './boards/boards-auto-installer';
import { ShellLayoutRestorer } from './theia/core/shell-layout-restorer';
import { EditorMode } from './editor-mode';
import { ListItemRenderer } from './widgets/component-list/list-item-renderer';
import { ColorContribution } from '@theia/core/lib/browser/color-application-contribution';
import { MonacoThemingService } from '@theia/monaco/lib/browser/monaco-theming-service';
import { ArduinoDaemonPath, ArduinoDaemon } from '../common/protocol/arduino-daemon';
import { EditorManager as TheiaEditorManager, EditorCommandContribution as TheiaEditorCommandContribution } from '@theia/editor/lib/browser';
import { EditorManager } from './theia/editor/editor-manager';
import { FrontendConnectionStatusService, ApplicationConnectionStatusContribution } from './theia/core/connection-status-service';
import {
FrontendConnectionStatusService as TheiaFrontendConnectionStatusService,
ApplicationConnectionStatusContribution as TheiaApplicationConnectionStatusContribution
} from '@theia/core/lib/browser/connection-status-service';
import { BoardsDataMenuUpdater } from './boards/boards-data-menu-updater';
import { BoardsDataStore } from './boards/boards-data-store';
import { ILogger } from '@theia/core';
import { FileSystemExt, FileSystemExtPath } from '../common/protocol/filesystem-ext';
import {
WorkspaceFrontendContribution as TheiaWorkspaceFrontendContribution,
FileMenuContribution as TheiaFileMenuContribution,
WorkspaceCommandContribution as TheiaWorkspaceCommandContribution
} from '@theia/workspace/lib/browser';
import { WorkspaceFrontendContribution, ArduinoFileMenuContribution } from './theia/workspace/workspace-frontend-contribution';
import { Contribution } from './contributions/contribution';
import { NewSketch } from './contributions/new-sketch';
import { OpenSketch } from './contributions/open-sketch';
import { Close } from './contributions/close';
import { SaveAsSketch } from './contributions/save-as-sketch';
import { SaveSketch } from './contributions/save-sketch';
import { VerifySketch } from './contributions/verify-sketch';
import { UploadSketch } from './contributions/upload-sketch';
import { CommonFrontendContribution } from './theia/core/common-frontend-contribution';
import { EditContributions } from './contributions/edit-contributions';
import { OpenSketchExternal } from './contributions/open-sketch-external';
import { PreferencesContribution as TheiaPreferencesContribution } from '@theia/preferences/lib/browser/preferences-contribution';
import { PreferencesContribution } from './theia/preferences/preferences-contribution';
import { QuitApp } from './contributions/quit-app';
import { SketchControl } from './contributions/sketch-control';
import { Settings } from './contributions/settings';
import { KeybindingRegistry } from './theia/core/keybindings';
import { WorkspaceCommandContribution } from './theia/workspace/workspace-commands';
import { WorkspaceDeleteHandler as TheiaWorkspaceDeleteHandler } from '@theia/workspace/lib/browser/workspace-delete-handler';
import { WorkspaceDeleteHandler } from './theia/workspace/workspace-delete-handler';
import { TabBarToolbar } from './theia/core/tab-bar-toolbar';
import { EditorWidgetFactory as TheiaEditorWidgetFactory } from '@theia/editor/lib/browser/editor-widget-factory';
import { EditorWidgetFactory } from './theia/editor/editor-widget-factory';
import { OutputWidget as TheiaOutputWidget } from '@theia/output/lib/browser/output-widget';
import { OutputWidget } from './theia/output/output-widget';
import { BurnBootloader } from './contributions/burn-bootloader';
import { ExamplesServicePath, ExamplesService } from '../common/protocol/examples-service';
import { BuiltInExamples, LibraryExamples } from './contributions/examples';
import { IncludeLibrary } from './contributions/include-library';
import { OutputChannelManager as TheiaOutputChannelManager } from '@theia/output/lib/common/output-channel';
import { OutputChannelManager } from './theia/output/output-channel';
import { OutputChannelRegistryMainImpl as TheiaOutputChannelRegistryMainImpl, OutputChannelRegistryMainImpl } from './theia/plugin-ext/output-channel-registry-main';
import { ExecutableService, ExecutableServicePath } from '../common/protocol';
import { MonacoTextModelService as TheiaMonacoTextModelService } from '@theia/monaco/lib/browser/monaco-text-model-service';
import { MonacoTextModelService } from './theia/monaco/monaco-text-model-service';
import { OutputServiceImpl } from './output-service-impl';
import { OutputServicePath, OutputService } from '../common/protocol/output-service';
import { NotificationCenter } from './notification-center';
import { NotificationServicePath, NotificationServiceServer } from '../common/protocol';
import { About } from './contributions/about';
import { IconThemeService } from '@theia/core/lib/browser/icon-theme-service';
import { TabBarRenderer } from './theia/core/tab-bars';
import { EditorCommandContribution } from './theia/editor/editor-command';
import { NavigatorTabBarDecorator as TheiaNavigatorTabBarDecorator } from '@theia/navigator/lib/browser/navigator-tab-bar-decorator';
import { NavigatorTabBarDecorator } from './theia/navigator/navigator-tab-bar-decorator';
import { Debug } from './contributions/debug';
import { DebugSessionManager } from './theia/debug/debug-session-manager';
import { DebugSessionManager as TheiaDebugSessionManager } from '@theia/debug/lib/browser/debug-session-manager';
import { Sketchbook } from './contributions/sketchbook';
import { DebugFrontendApplicationContribution } from './theia/debug/debug-frontend-application-contribution';
import { DebugFrontendApplicationContribution as TheiaDebugFrontendApplicationContribution } from '@theia/debug/lib/browser/debug-frontend-application-contribution';
import { BoardSelection } from './contributions/board-selection';
import { OpenRecentSketch } from './contributions/open-recent-sketch';
import { Help } from './contributions/help';
import { bindArduinoPreferences } from './arduino-preferences'
import { SettingsService, SettingsDialog, SettingsWidget, SettingsDialogProps } from './settings';
import { AddFile } from './contributions/add-file';
import { ArchiveSketch } from './contributions/archive-sketch';
import { OutputToolbarContribution as TheiaOutputToolbarContribution } from '@theia/output/lib/browser/output-toolbar-contribution';
import { OutputToolbarContribution } from './theia/output/output-toolbar-contribution';
const ElementQueries = require('css-element-queries/src/ElementQueries');
MonacoThemingService.register({
id: 'arduino-theme',
label: 'Light (Arduino)',
uiTheme: 'vs',
json: require('../../src/browser/data/arduino.color-theme.json')
});
export default new ContainerModule((bind, unbind, isBound, rebind) => {
ElementQueries.listen();
ElementQueries.init();
// Commands and toolbar items
bind(ArduinoFrontendContribution).toSelf().inSingletonScope();
bind(CommandContribution).toService(ArduinoFrontendContribution);
bind(MenuContribution).toService(ArduinoFrontendContribution);
bind(TabBarToolbarContribution).toService(ArduinoFrontendContribution);
bind(FrontendApplicationContribution).toService(ArduinoFrontendContribution);
bind(ColorContribution).toService(ArduinoFrontendContribution);
bind(ArduinoToolbarContribution).toSelf().inSingletonScope();
bind(FrontendApplicationContribution).toService(ArduinoToolbarContribution);
// Renderer for both the library and the core widgets.
bind(ListItemRenderer).toSelf().inSingletonScope();
// Library service
bind(LibraryService).toDynamicValue(context => WebSocketConnectionProvider.createProxy(context.container, LibraryServicePath)).inSingletonScope();
// Library list widget
bind(LibraryListWidget).toSelf();
bindViewContribution(bind, LibraryListWidgetFrontendContribution);
bind(WidgetFactory).toDynamicValue(context => ({
id: LibraryListWidget.WIDGET_ID,
createWidget: () => context.container.get(LibraryListWidget)
}));
bind(FrontendApplicationContribution).toService(LibraryListWidgetFrontendContribution);
// Sketch list service
bind(SketchesService).toDynamicValue(context => WebSocketConnectionProvider.createProxy(context.container, SketchesServicePath)).inSingletonScope();
bind(SketchesServiceClientImpl).toSelf().inSingletonScope();
bind(FrontendApplicationContribution).toService(SketchesServiceClientImpl);
// Config service
bind(ConfigService).toDynamicValue(context => WebSocketConnectionProvider.createProxy(context.container, ConfigServicePath)).inSingletonScope();
// Boards service
bind(BoardsService).toDynamicValue(context => WebSocketConnectionProvider.createProxy(context.container, BoardsServicePath)).inSingletonScope();
// Boards service client to receive and delegate notifications from the backend.
bind(BoardsServiceProvider).toSelf().inSingletonScope();
bind(FrontendApplicationContribution).toService(BoardsServiceProvider);
// To be able to track, and update the menu based on the core settings (aka. board details) of the currently selected board.
bind(FrontendApplicationContribution).to(BoardsDataMenuUpdater).inSingletonScope();
bind(BoardsDataStore).toSelf().inSingletonScope();
bind(FrontendApplicationContribution).toService(BoardsDataStore);
// Logger for the Arduino daemon
bind(ILogger).toDynamicValue(ctx => {
const parentLogger = ctx.container.get<ILogger>(ILogger);
return parentLogger.child('store');
}).inSingletonScope().whenTargetNamed('store');
// Boards auto-installer
bind(BoardsAutoInstaller).toSelf().inSingletonScope();
bind(FrontendApplicationContribution).toService(BoardsAutoInstaller);
// Boards list widget
bind(BoardsListWidget).toSelf();
bindViewContribution(bind, BoardsListWidgetFrontendContribution);
bind(WidgetFactory).toDynamicValue(context => ({
id: BoardsListWidget.WIDGET_ID,
createWidget: () => context.container.get(BoardsListWidget)
}));
bind(FrontendApplicationContribution).toService(BoardsListWidgetFrontendContribution);
// Board select dialog
bind(BoardsConfigDialogWidget).toSelf().inSingletonScope();
bind(BoardsConfigDialog).toSelf().inSingletonScope();
bind(BoardsConfigDialogProps).toConstantValue({
title: 'Select Board'
})
// Core service
bind(CoreService).toDynamicValue(context => WebSocketConnectionProvider.createProxy(context.container, CoreServicePath)).inSingletonScope();
// Serial monitor
bind(MonitorModel).toSelf().inSingletonScope();
bind(FrontendApplicationContribution).toService(MonitorModel);
bind(MonitorWidget).toSelf();
bindViewContribution(bind, MonitorViewContribution);
bind(TabBarToolbarContribution).toService(MonitorViewContribution);
bind(WidgetFactory).toDynamicValue(context => ({
id: MonitorWidget.ID,
createWidget: () => context.container.get(MonitorWidget)
}));
// Frontend binding for the serial monitor service
bind(MonitorService).toDynamicValue(context => {
const connection = context.container.get(WebSocketConnectionProvider);
const client = context.container.get(MonitorServiceClientImpl);
return connection.createProxy(MonitorServicePath, client);
}).inSingletonScope();
bind(MonitorConnection).toSelf().inSingletonScope();
// Serial monitor service client to receive and delegate notifications from the backend.
bind(MonitorServiceClientImpl).toSelf().inSingletonScope();
bind(MonitorServiceClient).toDynamicValue(context => {
const client = context.container.get(MonitorServiceClientImpl);
WebSocketConnectionProvider.createProxy(context.container, MonitorServicePath, client);
return client;
}).inSingletonScope();
bind(WorkspaceService).toSelf().inSingletonScope();
rebind(TheiaWorkspaceService).toService(WorkspaceService);
// Customizing default Theia layout based on the editor mode: `pro-mode` or `classic`.
bind(EditorMode).toSelf().inSingletonScope();
bind(FrontendApplicationContribution).toService(EditorMode);
// Layout and shell customizations.
rebind(TheiaOutlineViewContribution).to(OutlineViewContribution).inSingletonScope();
rebind(TheiaProblemContribution).to(ProblemContribution).inSingletonScope();
rebind(TheiaFileNavigatorContribution).to(FileNavigatorContribution).inSingletonScope();
rebind(TheiaEditorContribution).to(EditorContribution).inSingletonScope();
rebind(TheiaMonacoStatusBarContribution).to(MonacoStatusBarContribution).inSingletonScope();
rebind(TheiaApplicationShell).to(ApplicationShell).inSingletonScope();
rebind(TheiaScmContribution).to(ScmContribution).inSingletonScope();
rebind(TheiaSearchInWorkspaceFrontendContribution).to(SearchInWorkspaceFrontendContribution).inSingletonScope();
rebind(TheiaFrontendApplication).to(FrontendApplication).inSingletonScope();
rebind(TheiaWorkspaceFrontendContribution).to(WorkspaceFrontendContribution).inSingletonScope();
rebind(TheiaFileMenuContribution).to(ArduinoFileMenuContribution).inSingletonScope();
rebind(TheiaCommonFrontendContribution).to(CommonFrontendContribution).inSingletonScope();
rebind(TheiaPreferencesContribution).to(PreferencesContribution).inSingletonScope();
rebind(TheiaKeybindingRegistry).to(KeybindingRegistry).inSingletonScope();
rebind(TheiaWorkspaceCommandContribution).to(WorkspaceCommandContribution).inSingletonScope();
rebind(TheiaWorkspaceDeleteHandler).to(WorkspaceDeleteHandler).inSingletonScope();
rebind(TheiaEditorWidgetFactory).to(EditorWidgetFactory).inSingletonScope();
rebind(TabBarToolbarFactory).toFactory(({ container: parentContainer }) => () => {
const container = parentContainer.createChild();
container.bind(TabBarToolbar).toSelf().inSingletonScope();
return container.get(TabBarToolbar);
});
bind(OutputWidget).toSelf().inSingletonScope();
rebind(TheiaOutputWidget).toService(OutputWidget);
bind(OutputChannelManager).toSelf().inSingletonScope();
rebind(TheiaOutputChannelManager).toService(OutputChannelManager);
bind(OutputChannelRegistryMainImpl).toSelf().inTransientScope();
rebind(TheiaOutputChannelRegistryMainImpl).toService(OutputChannelRegistryMainImpl);
bind(MonacoTextModelService).toSelf().inSingletonScope();
rebind(TheiaMonacoTextModelService).toService(MonacoTextModelService);
// Show a disconnected status bar, when the daemon is not available
bind(ApplicationConnectionStatusContribution).toSelf().inSingletonScope();
rebind(TheiaApplicationConnectionStatusContribution).toService(ApplicationConnectionStatusContribution);
bind(FrontendConnectionStatusService).toSelf().inSingletonScope();
rebind(TheiaFrontendConnectionStatusService).toService(FrontendConnectionStatusService);
// Editor customizations. Sets the editor to `readOnly` if under the data dir.
bind(EditorManager).toSelf().inSingletonScope();
rebind(TheiaEditorManager).toService(EditorManager);
// Decorator customizations
bind(TabBarDecoratorService).toSelf().inSingletonScope();
rebind(TheiaTabBarDecoratorService).toService(TabBarDecoratorService);
// Problem markers
bind(ProblemManager).toSelf().inSingletonScope();
rebind(TheiaProblemManager).toService(ProblemManager);
// Customized layout restorer that can restore the state in async way: https://github.com/eclipse-theia/theia/issues/6579
bind(ShellLayoutRestorer).toSelf().inSingletonScope();
rebind(TheiaShellLayoutRestorer).toService(ShellLayoutRestorer);
// No dropdown for the _Output_ view.
bind(OutputToolbarContribution).toSelf().inSingletonScope();
rebind(TheiaOutputToolbarContribution).toService(OutputToolbarContribution);
bind(ArduinoDaemon).toDynamicValue(context => WebSocketConnectionProvider.createProxy(context.container, ArduinoDaemonPath)).inSingletonScope();
// File-system extension
bind(FileSystemExt).toDynamicValue(context => WebSocketConnectionProvider.createProxy(context.container, FileSystemExtPath)).inSingletonScope();
// Examples service@
bind(ExamplesService).toDynamicValue(context => WebSocketConnectionProvider.createProxy(context.container, ExamplesServicePath)).inSingletonScope();
// Executable URIs known by the backend
bind(ExecutableService).toDynamicValue(context => WebSocketConnectionProvider.createProxy(context.container, ExecutableServicePath)).inSingletonScope();
Contribution.configure(bind, NewSketch);
Contribution.configure(bind, OpenSketch);
Contribution.configure(bind, Close);
Contribution.configure(bind, SaveSketch);
Contribution.configure(bind, SaveAsSketch);
Contribution.configure(bind, VerifySketch);
Contribution.configure(bind, UploadSketch);
Contribution.configure(bind, OpenSketchExternal);
Contribution.configure(bind, EditContributions);
Contribution.configure(bind, QuitApp);
Contribution.configure(bind, SketchControl);
Contribution.configure(bind, Settings);
Contribution.configure(bind, BurnBootloader);
Contribution.configure(bind, BuiltInExamples);
Contribution.configure(bind, LibraryExamples);
Contribution.configure(bind, IncludeLibrary);
Contribution.configure(bind, About);
Contribution.configure(bind, Debug);
Contribution.configure(bind, Sketchbook);
Contribution.configure(bind, BoardSelection);
Contribution.configure(bind, OpenRecentSketch);
Contribution.configure(bind, Help);
Contribution.configure(bind, AddFile);
Contribution.configure(bind, ArchiveSketch);
bind(OutputServiceImpl).toSelf().inSingletonScope().onActivation(({ container }, outputService) => {
WebSocketConnectionProvider.createProxy(container, OutputServicePath, outputService);
return outputService;
});
bind(OutputService).toService(OutputServiceImpl);
bind(NotificationCenter).toSelf().inSingletonScope();
bind(FrontendApplicationContribution).toService(NotificationCenter);
bind(NotificationServiceServer).toDynamicValue(context => WebSocketConnectionProvider.createProxy(context.container, NotificationServicePath)).inSingletonScope();
// Enable the dirty indicator on uncloseable widgets.
rebind(TabBarRendererFactory).toFactory(context => () => {
const contextMenuRenderer = context.container.get<ContextMenuRenderer>(ContextMenuRenderer);
const decoratorService = context.container.get<TabBarDecoratorService>(TabBarDecoratorService);
const iconThemeService = context.container.get<IconThemeService>(IconThemeService);
return new TabBarRenderer(contextMenuRenderer, decoratorService, iconThemeService);
});
// Workaround for https://github.com/eclipse-theia/theia/issues/8722
// Do not trigger a save on IDE startup if `"editor.autoSave": "on"` was set as a preference.
bind(EditorCommandContribution).toSelf().inSingletonScope();
rebind(TheiaEditorCommandContribution).toService(EditorCommandContribution);
// Silent the badge decoration in the Explorer view.
bind(NavigatorTabBarDecorator).toSelf().inSingletonScope();
rebind(TheiaNavigatorTabBarDecorator).toService(NavigatorTabBarDecorator);
// To avoid running `Save All` when there are no dirty editors before starting the debug session.
bind(DebugSessionManager).toSelf().inSingletonScope();
rebind(TheiaDebugSessionManager).toService(DebugSessionManager);
// To remove the `Run` menu item from the application menu.
bind(DebugFrontendApplicationContribution).toSelf().inSingletonScope();
rebind(TheiaDebugFrontendApplicationContribution).toService(DebugFrontendApplicationContribution);
// Preferences
bindArduinoPreferences(bind);
// Settings wrapper for the preferences and the CLI config.
bind(SettingsService).toSelf().inSingletonScope();
// Settings dialog and widget
bind(SettingsWidget).toSelf().inSingletonScope();
bind(SettingsDialog).toSelf().inSingletonScope();
bind(SettingsDialogProps).toConstantValue({
title: 'Preferences'
});
});

View File

@@ -0,0 +1,73 @@
import { interfaces } from 'inversify';
import {
createPreferenceProxy,
PreferenceProxy,
PreferenceService,
PreferenceContribution,
PreferenceSchema
} from '@theia/core/lib/browser/preferences';
export const ArduinoConfigSchema: PreferenceSchema = {
'type': 'object',
'properties': {
'arduino.language.log': {
'type': 'boolean',
'description': "True if the Arduino Language Server should generate log files into the sketch folder. Otherwise, false. It's false by default.",
'default': false
},
'arduino.compile.verbose': {
'type': 'boolean',
'description': 'True for verbose compile output. False by default',
'default': false
},
'arduino.upload.verbose': {
'type': 'boolean',
'description': 'True for verbose upload output. False by default.',
'default': false
},
'arduino.upload.verify': {
'type': 'boolean',
'default': false
},
'arduino.window.autoScale': {
'type': 'boolean',
'description': 'True if the user interface automatically scales with the font size.',
'default': true
},
'arduino.window.zoomLevel': {
'type': 'number',
'description': 'Adjust the zoom level of the window. The original size is 0 and each increment above (e.g. 1) or below (e.g. -1) represents zooming 20% larger or smaller. You can also enter decimals to adjust the zoom level with a finer granularity.',
'default': 0
},
'arduino.ide.autoUpdate': {
'type': 'boolean',
'description': 'True to enable automatic update checks. The IDE will check for updates automatically and periodically.',
'default': true
}
}
};
export interface ArduinoConfiguration {
'arduino.language.log': boolean;
'arduino.compile.verbose': boolean;
'arduino.upload.verbose': boolean;
'arduino.upload.verify': boolean;
'arduino.window.autoScale': boolean;
'arduino.window.zoomLevel': number;
'arduino.ide.autoUpdate': boolean;
}
export const ArduinoPreferences = Symbol('ArduinoPreferences');
export type ArduinoPreferences = PreferenceProxy<ArduinoConfiguration>;
export function createArduinoPreferences(preferences: PreferenceService): ArduinoPreferences {
return createPreferenceProxy(preferences, ArduinoConfigSchema);
}
export function bindArduinoPreferences(bind: interfaces.Bind): void {
bind(ArduinoPreferences).toDynamicValue(ctx => {
const preferences = ctx.container.get<PreferenceService>(PreferenceService);
return createArduinoPreferences(preferences);
});
bind(PreferenceContribution).toConstantValue({ schema: ArduinoConfigSchema });
}

View File

@@ -1,27 +0,0 @@
import { Theme } from '@theia/core/lib/browser/theming';
import { MonacoThemeRegistry } from '@theia/monaco/lib/browser/textmate/monaco-theme-registry';
const ARDUINO_CSS = require('../../src/browser/style/arduino.useable.css');
const ARDUINO_JSON = MonacoThemeRegistry.SINGLETON.register(
require('../../src/browser/data/arduino.color-theme.json'), {}, 'arduino', 'vs').name!;
export class ArduinoTheme {
static readonly arduino: Theme = {
id: 'arduino-theme',
label: 'Arduino Light Theme',
description: 'Arduino Light Theme',
editorTheme: ARDUINO_JSON,
activate() {
ARDUINO_CSS.use();
},
deactivate() {
ARDUINO_CSS.unuse();
}
}
static readonly themes: Theme[] = [
ArduinoTheme.arduino
]
}

View File

@@ -0,0 +1,68 @@
import { toUnix } from 'upath';
import URI from '@theia/core/lib/common/uri';
import { isWindows } from '@theia/core/lib/common/os';
import { notEmpty } from '@theia/core/lib/common/objects';
import { MaybePromise } from '@theia/core/lib/common/types';
/**
* Class for determining the default workspace location from the
* `location.hash`, the historical workspace locations, and recent sketch files.
*
* The following logic is used for determining the default workspace location:
* - `hash` points to an existing location?
* - Yes
* - `validate location`. Is valid sketch location?
* - Yes
* - Done.
* - No
* - `try open recent workspace roots`, then `try open last modified sketches`, finally `create new sketch`.
* - No
* - `try open recent workspace roots`, then `try open last modified sketches`, finally `create new sketch`.
*/
namespace ArduinoWorkspaceRootResolver {
export interface InitOptions {
readonly isValid: (uri: string) => MaybePromise<boolean>;
}
export interface ResolveOptions {
readonly hash?: string
readonly recentWorkspaces: string[];
// Gathered from the default sketch folder. The default sketch folder is defined by the CLI.
readonly recentSketches: string[];
}
}
export class ArduinoWorkspaceRootResolver {
constructor(protected options: ArduinoWorkspaceRootResolver.InitOptions) {
}
async resolve(options: ArduinoWorkspaceRootResolver.ResolveOptions): Promise<{ uri: string } | undefined> {
const { hash, recentWorkspaces, recentSketches } = options;
for (const uri of [this.hashToUri(hash), ...recentWorkspaces, ...recentSketches].filter(notEmpty)) {
const valid = await this.isValid(uri);
if (valid) {
return { uri };
}
}
return undefined;
}
protected isValid(uri: string): MaybePromise<boolean> {
return this.options.isValid(uri);
}
// Note: here, the `hash` was defined as new `URI(yourValidFsPath).path` so we have to map it to a valid FS path first.
// This is important for Windows only and a NOOP on POSIX.
// Note: we set the `new URI(myValidUri).path.toString()` as the `hash`. See:
// - https://github.com/eclipse-theia/theia/blob/8196e9dcf9c8de8ea0910efeb5334a974f426966/packages/workspace/src/browser/workspace-service.ts#L143 and
// - https://github.com/eclipse-theia/theia/blob/8196e9dcf9c8de8ea0910efeb5334a974f426966/packages/workspace/src/browser/workspace-service.ts#L423
protected hashToUri(hash: string | undefined): string | undefined {
if (hash
&& hash.length > 1
&& hash.startsWith('#')) {
const path = hash.slice(1); // Trim the leading `#`.
return new URI(toUnix(path.slice(isWindows && hash.startsWith('/') ? 1 : 0))).withScheme('file').toString();
}
return undefined;
}
}

View File

@@ -1,50 +0,0 @@
import { WorkspaceService } from "@theia/workspace/lib/browser/workspace-service";
import { injectable, inject } from "inversify";
import { WorkspaceServer } from "@theia/workspace/lib/common";
import { FileSystem, FileStat } from "@theia/filesystem/lib/common";
import URI from "@theia/core/lib/common/uri";
import { SketchFactory } from "./sketch-factory";
/**
* This is workaround to have custom frontend binding for the default workspace, although we
* already have a custom binding for the backend.
*/
@injectable()
export class AWorkspaceService extends WorkspaceService {
@inject(WorkspaceServer)
protected readonly workspaceServer: WorkspaceServer;
@inject(FileSystem)
protected readonly fileSystem: FileSystem;
@inject(SketchFactory)
protected readonly sketchFactory: SketchFactory;
protected async getDefaultWorkspacePath(): Promise<string | undefined> {
let result = await super.getDefaultWorkspacePath();
if (!result) {
const userHome = await this.fileSystem.getCurrentUserHome();
if (!userHome) {
return;
}
// The backend has created this location if it was missing.
result = new URI(userHome.uri).resolve('Arduino-PoC').resolve('Sketches').toString();
}
const stat = await this.fileSystem.getFileStat(result);
if (!stat) {
// workspace does not exist yet, create it
await this.fileSystem.createFolder(result);
await this.sketchFactory.createNewSketch(new URI(result));
}
return result;
}
protected async setWorkspace(workspaceStat: FileStat | undefined): Promise<void> {
await super.setWorkspace(workspaceStat);
}
}

View File

@@ -1,19 +0,0 @@
import { EventEmitter } from "events";
import { injectable } from "inversify";
// TODO (post-PoC): move this to the backend / BoardsService
@injectable()
export class BoardsNotificationService {
protected readonly emitter = new EventEmitter();
public on(event: 'boards-installed', listener: (...args: any[]) => void): this {
this.emitter.on(event, listener);
return this;
}
public notifyBoardsInstalled() {
this.emitter.emit('boards-installed');
}
}

View File

@@ -0,0 +1,62 @@
import { injectable, inject } from 'inversify';
import { MessageService } from '@theia/core/lib/common/message-service';
import { FrontendApplicationContribution } from '@theia/core/lib/browser/frontend-application';
import { BoardsService, BoardsPackage } from '../../common/protocol/boards-service';
import { BoardsServiceProvider } from './boards-service-provider';
import { BoardsListWidgetFrontendContribution } from './boards-widget-frontend-contribution';
import { InstallationProgressDialog } from '../widgets/progress-dialog';
import { BoardsConfig } from './boards-config';
/**
* Listens on `BoardsConfig.Config` changes, if a board is selected which does not
* have the corresponding core installed, it proposes the user to install the core.
*/
@injectable()
export class BoardsAutoInstaller implements FrontendApplicationContribution {
@inject(MessageService)
protected readonly messageService: MessageService;
@inject(BoardsService)
protected readonly boardsService: BoardsService;
@inject(BoardsServiceProvider)
protected readonly boardsServiceClient: BoardsServiceProvider;
@inject(BoardsListWidgetFrontendContribution)
protected readonly boardsManagerFrontendContribution: BoardsListWidgetFrontendContribution;
onStart(): void {
this.boardsServiceClient.onBoardsConfigChanged(this.ensureCoreExists.bind(this));
this.ensureCoreExists(this.boardsServiceClient.boardsConfig);
}
protected ensureCoreExists(config: BoardsConfig.Config): void {
const { selectedBoard } = config;
if (selectedBoard) {
this.boardsService.search({}).then(packages => {
const candidates = packages
.filter(pkg => BoardsPackage.contains(selectedBoard, pkg))
.filter(({ installable, installedVersion }) => installable && !installedVersion);
for (const candidate of candidates) {
// tslint:disable-next-line:max-line-length
this.messageService.info(`The \`"${candidate.name}"\` core has to be installed for the currently selected \`"${selectedBoard.name}"\` board. Do you want to install it now?`, 'Install Manually', 'Yes').then(async answer => {
if (answer === 'Yes') {
const dialog = new InstallationProgressDialog(candidate.name, candidate.availableVersions[0]);
dialog.open();
try {
await this.boardsService.install({ item: candidate });
} finally {
dialog.close();
}
}
if (answer) {
this.boardsManagerFrontendContribution.openView({ reveal: true }).then(widget => widget.refresh(candidate.name.toLocaleLowerCase()));
}
});
}
})
}
}
}

View File

@@ -0,0 +1,68 @@
import * as React from 'react';
import { injectable, inject } from 'inversify';
import { Emitter } from '@theia/core/lib/common/event';
import { ReactWidget, Message } from '@theia/core/lib/browser';
import { BoardsService } from '../../common/protocol/boards-service';
import { BoardsConfig } from './boards-config';
import { BoardsServiceProvider } from './boards-service-provider';
import { NotificationCenter } from '../notification-center';
@injectable()
export class BoardsConfigDialogWidget extends ReactWidget {
@inject(BoardsService)
protected readonly boardsService: BoardsService;
@inject(BoardsServiceProvider)
protected readonly boardsServiceClient: BoardsServiceProvider;
@inject(NotificationCenter)
protected readonly notificationCenter: NotificationCenter;
protected readonly onFilterTextDidChangeEmitter = new Emitter<string>();
protected readonly onBoardConfigChangedEmitter = new Emitter<BoardsConfig.Config>();
readonly onBoardConfigChanged = this.onBoardConfigChangedEmitter.event;
protected focusNode: HTMLElement | undefined;
constructor() {
super();
this.id = 'select-board-dialog';
this.toDispose.pushAll([
this.onBoardConfigChangedEmitter,
this.onFilterTextDidChangeEmitter
]);
}
search(query: string): void {
this.onFilterTextDidChangeEmitter.fire(query);
}
protected fireConfigChanged = (config: BoardsConfig.Config) => {
this.onBoardConfigChangedEmitter.fire(config);
}
protected setFocusNode = (element: HTMLElement | undefined) => {
this.focusNode = element;
}
protected render(): React.ReactNode {
return <div className='selectBoardContainer'>
<BoardsConfig
boardsServiceProvider={this.boardsServiceClient}
notificationCenter={this.notificationCenter}
onConfigChange={this.fireConfigChanged}
onFocusNodeSet={this.setFocusNode}
onFilteredTextDidChangeEvent={this.onFilterTextDidChangeEmitter.event} />
</div>;
}
protected onActivateRequest(msg: Message): void {
super.onActivateRequest(msg);
if (this.focusNode instanceof HTMLInputElement) {
this.focusNode.select();
}
(this.focusNode || this.node).focus();
}
}

View File

@@ -0,0 +1,123 @@
import { injectable, inject, postConstruct } from 'inversify';
import { Message } from '@phosphor/messaging';
import { AbstractDialog, DialogProps, Widget, DialogError } from '@theia/core/lib/browser';
import { BoardsConfig } from './boards-config';
import { BoardsService } from '../../common/protocol/boards-service';
import { BoardsServiceProvider } from './boards-service-provider';
import { BoardsConfigDialogWidget } from './boards-config-dialog-widget';
@injectable()
export class BoardsConfigDialogProps extends DialogProps {
}
@injectable()
export class BoardsConfigDialog extends AbstractDialog<BoardsConfig.Config> {
@inject(BoardsConfigDialogWidget)
protected readonly widget: BoardsConfigDialogWidget;
@inject(BoardsService)
protected readonly boardService: BoardsService;
@inject(BoardsServiceProvider)
protected readonly boardsServiceClient: BoardsServiceProvider;
protected config: BoardsConfig.Config = {};
constructor(@inject(BoardsConfigDialogProps) protected readonly props: BoardsConfigDialogProps) {
super(props);
this.contentNode.classList.add('select-board-dialog');
this.contentNode.appendChild(this.createDescription());
this.appendCloseButton('CANCEL');
this.appendAcceptButton('OK');
}
@postConstruct()
protected init(): void {
this.toDispose.push(this.boardsServiceClient.onBoardsConfigChanged(config => {
this.config = config;
this.update();
}));
}
/**
* Pass in an empty string if you want to reset the search term. Using `undefined` has no effect.
*/
async open(query: string | undefined = undefined): Promise<BoardsConfig.Config | undefined> {
if (typeof query === 'string') {
this.widget.search(query);
}
return super.open();
}
protected createDescription(): HTMLElement {
const head = document.createElement('div');
head.classList.add('head');
const title = document.createElement('div');
title.textContent = 'Select Other Board & Port';
title.classList.add('title');
head.appendChild(title);
const text = document.createElement('div');
text.classList.add('text');
head.appendChild(text);
for (const paragraph of [
'Select both a Board and a Port if you want to upload a sketch.',
'If you only select a Board you will be able just to compile, but not to upload your sketch.'
]) {
const p = document.createElement('p');
p.textContent = paragraph;
text.appendChild(p);
}
return head;
}
protected onAfterAttach(msg: Message): void {
if (this.widget.isAttached) {
Widget.detach(this.widget);
}
Widget.attach(this.widget, this.contentNode);
this.toDisposeOnDetach.push(this.widget.onBoardConfigChanged(config => {
this.config = config;
this.update();
}));
super.onAfterAttach(msg);
this.update();
}
protected onUpdateRequest(msg: Message) {
super.onUpdateRequest(msg);
this.widget.update();
}
protected onActivateRequest(msg: Message): void {
super.onActivateRequest(msg);
this.widget.activate();
}
protected handleEnter(event: KeyboardEvent): boolean | void {
if (event.target instanceof HTMLTextAreaElement) {
return false;
}
}
protected isValid(value: BoardsConfig.Config): DialogError {
if (!value.selectedBoard) {
if (value.selectedPort) {
return 'Please pick a board connected to the port you have selected.';
}
return false;
}
return '';
}
get value(): BoardsConfig.Config {
return this.config;
}
}

View File

@@ -0,0 +1,286 @@
import * as React from 'react';
import { Event } from '@theia/core/lib/common/event';
import { notEmpty } from '@theia/core/lib/common/objects';
import { MaybePromise } from '@theia/core/lib/common/types';
import { DisposableCollection } from '@theia/core/lib/common/disposable';
import { Board, Port, AttachedBoardsChangeEvent, BoardWithPackage } from '../../common/protocol/boards-service';
import { NotificationCenter } from '../notification-center';
import { BoardsServiceProvider } from './boards-service-provider';
export namespace BoardsConfig {
export interface Config {
selectedBoard?: Board;
selectedPort?: Port;
}
export interface Props {
readonly boardsServiceProvider: BoardsServiceProvider;
readonly notificationCenter: NotificationCenter;
readonly onConfigChange: (config: Config) => void;
readonly onFocusNodeSet: (element: HTMLElement | undefined) => void;
readonly onFilteredTextDidChangeEvent: Event<string>;
}
export interface State extends Config {
searchResults: Array<BoardWithPackage>;
knownPorts: Port[];
showAllPorts: boolean;
query: string;
}
}
export abstract class Item<T> extends React.Component<{
item: T,
label: string,
selected: boolean,
onClick: (item: T) => void,
missing?: boolean,
details?: string
}> {
render(): React.ReactNode {
const { selected, label, missing, details } = this.props;
const classNames = ['item'];
if (selected) {
classNames.push('selected');
}
if (missing === true) {
classNames.push('missing')
}
return <div onClick={this.onClick} className={classNames.join(' ')} title={`${label}${!details ? '' : details}`}>
<div className='label'>
{label}
</div>
{!details ? '' : <div className='details'>{details}</div>}
{!selected ? '' : <div className='selected-icon'><i className='fa fa-check' /></div>}
</div>;
}
protected onClick = () => {
this.props.onClick(this.props.item);
}
}
export class BoardsConfig extends React.Component<BoardsConfig.Props, BoardsConfig.State> {
protected toDispose = new DisposableCollection();
constructor(props: BoardsConfig.Props) {
super(props);
const { boardsConfig } = props.boardsServiceProvider;
this.state = {
searchResults: [],
knownPorts: [],
showAllPorts: false,
query: '',
...boardsConfig
}
}
componentDidMount() {
this.updateBoards();
this.updatePorts(this.props.boardsServiceProvider.availableBoards.map(({ port }) => port).filter(notEmpty));
this.toDispose.pushAll([
this.props.notificationCenter.onAttachedBoardsChanged(event => this.updatePorts(event.newState.ports, AttachedBoardsChangeEvent.diff(event).detached.ports)),
this.props.boardsServiceProvider.onBoardsConfigChanged(({ selectedBoard, selectedPort }) => {
this.setState({ selectedBoard, selectedPort }, () => this.fireConfigChanged());
}),
this.props.notificationCenter.onPlatformInstalled(() => this.updateBoards(this.state.query)),
this.props.notificationCenter.onPlatformUninstalled(() => this.updateBoards(this.state.query)),
this.props.notificationCenter.onIndexUpdated(() => this.updateBoards(this.state.query)),
this.props.notificationCenter.onDaemonStarted(() => this.updateBoards(this.state.query)),
this.props.notificationCenter.onDaemonStopped(() => this.setState({ searchResults: [] })),
this.props.onFilteredTextDidChangeEvent(query => this.setState({ query }, () => this.updateBoards(this.state.query)))
]);
}
componentWillUnmount(): void {
this.toDispose.dispose();
}
protected fireConfigChanged() {
const { selectedBoard, selectedPort } = this.state;
this.props.onConfigChange({ selectedBoard, selectedPort });
}
protected updateBoards = (eventOrQuery: React.ChangeEvent<HTMLInputElement> | string = '') => {
const query = typeof eventOrQuery === 'string'
? eventOrQuery
: eventOrQuery.target.value.toLowerCase();
this.setState({ query });
this.queryBoards({ query }).then(searchResults => this.setState({ searchResults }));
}
protected updatePorts = (ports: Port[] = [], removedPorts: Port[] = []) => {
this.queryPorts(Promise.resolve(ports)).then(({ knownPorts }) => {
let { selectedPort } = this.state;
// If the currently selected port is not available anymore, unset the selected port.
if (removedPorts.some(port => Port.equals(port, selectedPort))) {
selectedPort = undefined;
}
this.setState({ knownPorts, selectedPort }, () => this.fireConfigChanged());
});
}
protected queryBoards = (options: { query?: string } = {}): Promise<Array<BoardWithPackage>> => {
return this.props.boardsServiceProvider.searchBoards(options);
}
protected get availablePorts(): MaybePromise<Port[]> {
return this.props.boardsServiceProvider.availableBoards.map(({ port }) => port).filter(notEmpty);
}
protected queryPorts = async (availablePorts: MaybePromise<Port[]> = this.availablePorts) => {
const ports = await availablePorts;
return { knownPorts: ports.sort(Port.compare) };
}
protected toggleFilterPorts = () => {
this.setState({ showAllPorts: !this.state.showAllPorts });
}
protected selectPort = (selectedPort: Port | undefined) => {
this.setState({ selectedPort }, () => this.fireConfigChanged());
}
protected selectBoard = (selectedBoard: BoardWithPackage | undefined) => {
this.setState({ selectedBoard }, () => this.fireConfigChanged());
}
protected focusNodeSet = (element: HTMLElement | null) => {
this.props.onFocusNodeSet(element || undefined);
}
render(): React.ReactNode {
return <div className='body'>
{this.renderContainer('boards', this.renderBoards.bind(this))}
{this.renderContainer('ports', this.renderPorts.bind(this), this.renderPortsFooter.bind(this))}
</div>;
}
protected renderContainer(title: string, contentRenderer: () => React.ReactNode, footerRenderer?: () => React.ReactNode): React.ReactNode {
return <div className='container'>
<div className='content'>
<div className='title'>
{title}
</div>
{contentRenderer()}
<div className='footer'>
{(footerRenderer ? footerRenderer() : '')}
</div>
</div>
</div>;
}
protected renderBoards(): React.ReactNode {
const { selectedBoard, searchResults, query } = this.state;
// Board names are not unique per core https://github.com/arduino/arduino-pro-ide/issues/262#issuecomment-661019560
// It is tricky when the core is not yet installed, no FQBNs are available.
const distinctBoards = new Map<string, Board.Detailed>();
const toKey = ({ name, packageName, fqbn }: Board.Detailed) => !!fqbn ? `${name}-${packageName}-${fqbn}` : `${name}-${packageName}`;
for (const board of Board.decorateBoards(selectedBoard, searchResults)) {
const key = toKey(board);
if (!distinctBoards.has(key)) {
distinctBoards.set(key, board);
}
}
return <React.Fragment>
<div className='search'>
<input
type='search'
value={query}
className='theia-input'
placeholder='SEARCH BOARD'
onChange={this.updateBoards}
ref={this.focusNodeSet}
/>
<i className='fa fa-search'></i>
</div>
<div className='boards list'>
{Array.from(distinctBoards.values()).map(board => <Item<BoardWithPackage>
key={`${board.name}-${board.packageName}`}
item={board}
label={board.name}
details={board.details}
selected={board.selected}
onClick={this.selectBoard}
missing={board.missing}
/>)}
</div>
</React.Fragment>;
}
protected renderPorts(): React.ReactNode {
const filter = this.state.showAllPorts ? () => true : Port.isBoardPort;
const ports = this.state.knownPorts.filter(filter);
return !ports.length ?
(
<div className='loading noselect'>
No ports discovered
</div>
) :
(
<div className='ports list'>
{ports.map(port => <Item<Port>
key={Port.toString(port)}
item={port}
label={Port.toString(port)}
selected={Port.equals(this.state.selectedPort, port)}
onClick={this.selectPort}
/>)}
</div>
);
}
protected renderPortsFooter(): React.ReactNode {
return <div className='noselect'>
<label
title='Shows all available ports when enabled'>
<input
type='checkbox'
defaultChecked={this.state.showAllPorts}
onChange={this.toggleFilterPorts}
/>
<span>Show all ports</span>
</label>
</div>;
}
}
export namespace BoardsConfig {
export namespace Config {
export function sameAs(config: Config, other: Config | Board): boolean {
const { selectedBoard, selectedPort } = config;
if (Board.is(other)) {
return !!selectedBoard
&& Board.equals(other, selectedBoard)
&& Port.sameAs(selectedPort, other.port);
}
return sameAs(config, other);
}
export function equals(left: Config, right: Config): boolean {
return left.selectedBoard === right.selectedBoard
&& left.selectedPort === right.selectedPort;
}
export function toString(config: Config, options: { default: string } = { default: '' }): string {
const { selectedBoard, selectedPort: port } = config;
if (!selectedBoard) {
return options.default;
}
const { name } = selectedBoard;
return `${name}${port ? ' at ' + Port.toString(port) : ''}`;
}
}
}

View File

@@ -0,0 +1,101 @@
import * as PQueue from 'p-queue';
import { inject, injectable } from 'inversify';
import { CommandRegistry } from '@theia/core/lib/common/command';
import { MenuModelRegistry } from '@theia/core/lib/common/menu';
import { Disposable, DisposableCollection } from '@theia/core/lib/common/disposable';
import { BoardsServiceProvider } from './boards-service-provider';
import { Board, ConfigOption, Programmer } from '../../common/protocol';
import { FrontendApplicationContribution } from '@theia/core/lib/browser';
import { BoardsDataStore } from './boards-data-store';
import { MainMenuManager } from '../../common/main-menu-manager';
import { ArduinoMenus, unregisterSubmenu } from '../menu/arduino-menus';
@injectable()
export class BoardsDataMenuUpdater implements FrontendApplicationContribution {
@inject(CommandRegistry)
protected readonly commandRegistry: CommandRegistry;
@inject(MenuModelRegistry)
protected readonly menuRegistry: MenuModelRegistry;
@inject(MainMenuManager)
protected readonly mainMenuManager: MainMenuManager;
@inject(BoardsDataStore)
protected readonly boardsDataStore: BoardsDataStore;
@inject(BoardsServiceProvider)
protected readonly boardsServiceClient: BoardsServiceProvider;
protected readonly queue = new PQueue({ autoStart: true, concurrency: 1 });
protected readonly toDisposeOnBoardChange = new DisposableCollection();
async onStart(): Promise<void> {
this.updateMenuActions(this.boardsServiceClient.boardsConfig.selectedBoard);
this.boardsDataStore.onChanged(() => this.updateMenuActions(this.boardsServiceClient.boardsConfig.selectedBoard));
this.boardsServiceClient.onBoardsConfigChanged(({ selectedBoard }) => this.updateMenuActions(selectedBoard));
}
protected async updateMenuActions(selectedBoard: Board | undefined): Promise<void> {
return this.queue.add(async () => {
this.toDisposeOnBoardChange.dispose();
this.mainMenuManager.update();
if (selectedBoard) {
const { fqbn } = selectedBoard;
if (fqbn) {
const { configOptions, programmers, selectedProgrammer } = await this.boardsDataStore.getData(fqbn);
if (configOptions.length) {
const boardsConfigMenuPath = [...ArduinoMenus.TOOLS__BOARD_SETTINGS_GROUP, 'z01_boardsConfig']; // `z_` is for ordering.
for (const { label, option, values } of configOptions.sort(ConfigOption.LABEL_COMPARATOR)) {
const menuPath = [...boardsConfigMenuPath, `${option}`];
const commands = new Map<string, Disposable & { label: string }>()
for (const value of values) {
const id = `${fqbn}-${option}--${value.value}`;
const command = { id };
const selectedValue = value.value;
const handler = {
execute: () => this.boardsDataStore.selectConfigOption({ fqbn, option, selectedValue }),
isToggled: () => value.selected
};
commands.set(id, Object.assign(this.commandRegistry.registerCommand(command, handler), { label: value.label }));
}
this.menuRegistry.registerSubmenu(menuPath, label);
this.toDisposeOnBoardChange.pushAll([
...commands.values(),
Disposable.create(() => unregisterSubmenu(menuPath, this.menuRegistry)),
...Array.from(commands.keys()).map((commandId, i) => {
const { label } = commands.get(commandId)!;
this.menuRegistry.registerMenuAction(menuPath, { commandId, order: `${i}`, label });
return Disposable.create(() => this.menuRegistry.unregisterMenuAction(commandId));
})
]);
}
}
if (programmers.length) {
const programmersMenuPath = [...ArduinoMenus.TOOLS__BOARD_SETTINGS_GROUP, 'z02_programmers'];
const label = selectedProgrammer ? `Programmer: "${selectedProgrammer.name}"` : 'Programmer'
this.menuRegistry.registerSubmenu(programmersMenuPath, label);
this.toDisposeOnBoardChange.push(Disposable.create(() => unregisterSubmenu(programmersMenuPath, this.menuRegistry)));
for (const programmer of programmers) {
const { id, name } = programmer;
const command = { id: `${fqbn}-programmer--${id}` };
const handler = {
execute: () => this.boardsDataStore.selectProgrammer({ fqbn, selectedProgrammer: programmer }),
isToggled: () => Programmer.equals(programmer, selectedProgrammer)
};
this.menuRegistry.registerMenuAction(programmersMenuPath, { commandId: command.id, label: name });
this.commandRegistry.registerCommand(command, handler);
this.toDisposeOnBoardChange.pushAll([
Disposable.create(() => this.commandRegistry.unregisterCommand(command)),
Disposable.create(() => this.menuRegistry.unregisterMenuAction(command.id))
]);
}
}
this.mainMenuManager.update();
}
}
});
}
}

View File

@@ -0,0 +1,211 @@
import { injectable, inject, named } from 'inversify';
import { ILogger } from '@theia/core/lib/common/logger';
import { deepClone } from '@theia/core/lib/common/objects';
import { MaybePromise } from '@theia/core/lib/common/types';
import { Event, Emitter } from '@theia/core/lib/common/event';
import { FrontendApplicationContribution, LocalStorageService } from '@theia/core/lib/browser';
import { notEmpty } from '../../common/utils';
import { BoardsService, ConfigOption, Installable, BoardDetails, Programmer } from '../../common/protocol';
import { NotificationCenter } from '../notification-center';
@injectable()
export class BoardsDataStore implements FrontendApplicationContribution {
@inject(ILogger)
@named('store')
protected readonly logger: ILogger;
@inject(BoardsService)
protected readonly boardsService: BoardsService;
@inject(NotificationCenter)
protected readonly notificationCenter: NotificationCenter;
@inject(LocalStorageService)
protected readonly storageService: LocalStorageService;
protected readonly onChangedEmitter = new Emitter<void>();
onStart(): void {
this.notificationCenter.onPlatformInstalled(async ({ item }) => {
const { installedVersion: version } = item;
if (!version) {
return;
}
let shouldFireChanged = false;
for (const fqbn of item.boards.map(({ fqbn }) => fqbn).filter(notEmpty).filter(fqbn => !!fqbn)) {
const key = this.getStorageKey(fqbn, version);
let data = await this.storageService.getData<ConfigOption[] | undefined>(key);
if (!data || !data.length) {
const details = await this.getBoardDetailsSafe(fqbn);
if (details) {
data = details.configOptions;
if (data.length) {
await this.storageService.setData(key, data);
shouldFireChanged = true;
}
}
}
}
if (shouldFireChanged) {
this.fireChanged();
}
});
}
get onChanged(): Event<void> {
return this.onChangedEmitter.event;
}
async appendConfigToFqbn(
fqbn: string | undefined,
boardsPackageVersion: MaybePromise<Installable.Version | undefined> = this.getBoardsPackageVersion(fqbn)): Promise<string | undefined> {
if (!fqbn) {
return undefined;
}
const { configOptions } = await this.getData(fqbn, boardsPackageVersion);
return ConfigOption.decorate(fqbn, configOptions);
}
async getData(
fqbn: string | undefined,
boardsPackageVersion: MaybePromise<Installable.Version | undefined> = this.getBoardsPackageVersion(fqbn)): Promise<BoardsDataStore.Data> {
if (!fqbn) {
return BoardsDataStore.Data.EMPTY;
}
const version = await boardsPackageVersion;
if (!version) {
return BoardsDataStore.Data.EMPTY;
}
const key = this.getStorageKey(fqbn, version);
let data = await this.storageService.getData<BoardsDataStore.Data | undefined>(key, undefined);
if (BoardsDataStore.Data.is(data)) {
return data;
}
const boardDetails = await this.getBoardDetailsSafe(fqbn);
if (!boardDetails) {
return BoardsDataStore.Data.EMPTY;
}
data = { configOptions: boardDetails.configOptions, programmers: boardDetails.programmers };
await this.storageService.setData(key, data);
return data;
}
async selectProgrammer(
{ fqbn, selectedProgrammer }: { fqbn: string, selectedProgrammer: Programmer },
boardsPackageVersion: MaybePromise<Installable.Version | undefined> = this.getBoardsPackageVersion(fqbn)): Promise<boolean> {
const data = deepClone(await this.getData(fqbn, boardsPackageVersion));
const { programmers } = data;
if (!programmers.find(p => Programmer.equals(selectedProgrammer, p))) {
return false;
}
const version = await boardsPackageVersion;
if (!version) {
return false;
}
await this.setData({ fqbn, data: { ...data, selectedProgrammer }, version });
this.fireChanged();
return true;
}
async selectConfigOption(
{ fqbn, option, selectedValue }: { fqbn: string, option: string, selectedValue: string },
boardsPackageVersion: MaybePromise<Installable.Version | undefined> = this.getBoardsPackageVersion(fqbn)): Promise<boolean> {
const data = deepClone(await this.getData(fqbn, boardsPackageVersion));
const { configOptions } = data;
const configOption = configOptions.find(c => c.option === option);
if (!configOption) {
return false;
}
let updated = false;
for (const value of configOption.values) {
if (value.value === selectedValue) {
(value as any).selected = true;
updated = true;
} else {
(value as any).selected = false;
}
}
if (!updated) {
return false;
}
const version = await boardsPackageVersion;
if (!version) {
return false;
}
await this.setData({ fqbn, data, version });
this.fireChanged();
return true;
}
protected async setData(
{ fqbn, data, version }: { fqbn: string, data: BoardsDataStore.Data, version: Installable.Version }): Promise<void> {
const key = this.getStorageKey(fqbn, version);
return this.storageService.setData(key, data);
}
protected getStorageKey(fqbn: string, version: Installable.Version): string {
return `.arduinoIDE-configOptions-${version}-${fqbn}`;
}
protected async getBoardDetailsSafe(fqbn: string): Promise<BoardDetails | undefined> {
try {
const details = this.boardsService.getBoardDetails({ fqbn });
return details;
} catch (err) {
if (err instanceof Error && err.message.includes('loading board data') && err.message.includes('is not installed')) {
this.logger.warn(`The boards package is not installed for board with FQBN: ${fqbn}`);
} else {
this.logger.error(`An unexpected error occurred while retrieving the board details for ${fqbn}.`, err);
}
return undefined;
}
}
protected fireChanged(): void {
this.onChangedEmitter.fire();
}
protected async getBoardsPackageVersion(fqbn: string | undefined): Promise<Installable.Version | undefined> {
if (!fqbn) {
return undefined;
}
const boardsPackage = await this.boardsService.getContainerBoardPackage({ fqbn });
if (!boardsPackage) {
return undefined;
}
return boardsPackage.installedVersion;
}
}
export namespace BoardsDataStore {
export interface Data {
readonly configOptions: ConfigOption[];
readonly programmers: Programmer[];
readonly selectedProgrammer?: Programmer;
}
export namespace Data {
export const EMPTY: Data = {
configOptions: [],
programmers: []
};
export function is(arg: any): arg is Data {
return !!arg
&& 'configOptions' in arg && Array.isArray(arg['configOptions'])
&& 'programmers' in arg && Array.isArray(arg['programmers'])
}
}
}

View File

@@ -0,0 +1,36 @@
import { inject, injectable, postConstruct } from 'inversify';
import { BoardsPackage, BoardsService } from '../../common/protocol/boards-service';
import { ListWidget } from '../widgets/component-list/list-widget';
import { ListItemRenderer } from '../widgets/component-list/list-item-renderer';
@injectable()
export class BoardsListWidget extends ListWidget<BoardsPackage> {
static WIDGET_ID = 'boards-list-widget';
static WIDGET_LABEL = 'Boards Manager';
constructor(
@inject(BoardsService) protected service: BoardsService,
@inject(ListItemRenderer) protected itemRenderer: ListItemRenderer<BoardsPackage>) {
super({
id: BoardsListWidget.WIDGET_ID,
label: BoardsListWidget.WIDGET_LABEL,
iconClass: 'fa fa-microchip',
searchable: service,
installable: service,
itemLabel: (item: BoardsPackage) => item.name,
itemRenderer
});
}
@postConstruct()
protected init(): void {
super.init();
this.toDispose.pushAll([
this.notificationCenter.onPlatformInstalled(() => this.refresh(undefined)),
this.notificationCenter.onPlatformUninstalled(() => this.refresh(undefined)),
]);
}
}

View File

@@ -1,16 +0,0 @@
import { ListWidget } from './list-widget';
export class BoardsListWidget extends ListWidget {
static WIDGET_ID = 'boards-list-widget';
static WIDGET_LABEL = 'Boards Manager';
protected widgetProps(): ListWidget.Props {
return {
id: BoardsListWidget.WIDGET_ID,
title: BoardsListWidget.WIDGET_LABEL,
iconClass: 'fa fa-microchip'
}
}
}

View File

@@ -0,0 +1,487 @@
import { injectable, inject } from 'inversify';
import { Emitter } from '@theia/core/lib/common/event';
import { ILogger } from '@theia/core/lib/common/logger';
import { MessageService } from '@theia/core/lib/common/message-service';
import { StorageService } from '@theia/core/lib/browser/storage-service';
import { FrontendApplicationContribution } from '@theia/core/lib/browser/frontend-application';
import { RecursiveRequired } from '../../common/types';
import {
Port,
Board,
BoardsService,
BoardsPackage,
AttachedBoardsChangeEvent,
BoardWithPackage
} from '../../common/protocol';
import { BoardsConfig } from './boards-config';
import { naturalCompare } from '../../common/utils';
import { compareAnything } from '../theia/monaco/comparers';
import { NotificationCenter } from '../notification-center';
import { CommandService } from '@theia/core';
import { ArduinoCommands } from '../arduino-commands';
interface BoardMatch {
readonly board: BoardWithPackage;
readonly matches: monaco.filters.IMatch[] | undefined;
}
@injectable()
export class BoardsServiceProvider implements FrontendApplicationContribution {
@inject(ILogger)
protected logger: ILogger;
@inject(MessageService)
protected messageService: MessageService;
@inject(StorageService)
protected storageService: StorageService;
@inject(BoardsService)
protected boardsService: BoardsService;
@inject(CommandService)
protected commandService: CommandService;
@inject(NotificationCenter)
protected notificationCenter: NotificationCenter;
protected readonly onBoardsConfigChangedEmitter = new Emitter<BoardsConfig.Config>();
protected readonly onAvailableBoardsChangedEmitter = new Emitter<AvailableBoard[]>();
/**
* Used for the auto-reconnecting. Sometimes, the attached board gets disconnected after uploading something to it.
* It happens with certain boards on Windows. For example, the `MKR1000` boards is selected on post `COM5` on Windows,
* perform an upload, the board automatically disconnects and reconnects, but on another port, `COM10`.
* We have to listen on such changes and auto-reconnect the same board on another port.
* See: https://arduino.slack.com/archives/CJJHJCJSJ/p1568645417013000?thread_ts=1568640504.009400&cid=CJJHJCJSJ
*/
protected latestValidBoardsConfig: RecursiveRequired<BoardsConfig.Config> | undefined = undefined;
protected latestBoardsConfig: BoardsConfig.Config | undefined = undefined;
protected _boardsConfig: BoardsConfig.Config = {};
protected _attachedBoards: Board[] = []; // This does not contain the `Unknown` boards. They're visible from the available ports only.
protected _availablePorts: Port[] = [];
protected _availableBoards: AvailableBoard[] = [];
/**
* Unlike `onAttachedBoardsChanged` this even fires when the user modifies the selected board in the IDE.\
* This even also fires, when the boards package was not available for the currently selected board,
* and the user installs the board package. Note: installing a board package will set the `fqbn` of the
* currently selected board.\
* This even also emitted when the board package for the currently selected board was uninstalled.
*/
readonly onBoardsConfigChanged = this.onBoardsConfigChangedEmitter.event;
readonly onAvailableBoardsChanged = this.onAvailableBoardsChangedEmitter.event;
onStart(): void {
this.notificationCenter.onAttachedBoardsChanged(this.notifyAttachedBoardsChanged.bind(this));
this.notificationCenter.onPlatformInstalled(this.notifyPlatformInstalled.bind(this));
this.notificationCenter.onPlatformUninstalled(this.notifyPlatformUninstalled.bind(this));
Promise.all([
this.boardsService.getAttachedBoards(),
this.boardsService.getAvailablePorts(),
this.loadState()
]).then(([attachedBoards, availablePorts]) => {
this._attachedBoards = attachedBoards;
this._availablePorts = availablePorts;
this.reconcileAvailableBoards().then(() => this.tryReconnect());
});
}
protected notifyAttachedBoardsChanged(event: AttachedBoardsChangeEvent): void {
if (!AttachedBoardsChangeEvent.isEmpty(event)) {
this.logger.info('Attached boards and available ports changed:');
this.logger.info(AttachedBoardsChangeEvent.toString(event));
this.logger.info(`------------------------------------------`);
}
this._attachedBoards = event.newState.boards;
this._availablePorts = event.newState.ports;
this.reconcileAvailableBoards().then(() => this.tryReconnect());
}
protected notifyPlatformInstalled(event: { item: BoardsPackage }): void {
this.logger.info('Boards package installed: ', JSON.stringify(event));
const { selectedBoard } = this.boardsConfig;
const { installedVersion, id } = event.item;
if (selectedBoard) {
const installedBoard = event.item.boards.find(({ name }) => name === selectedBoard.name);
if (installedBoard && (!selectedBoard.fqbn || selectedBoard.fqbn === installedBoard.fqbn)) {
this.logger.info(`Board package ${id}[${installedVersion}] was installed. Updating the FQBN of the currently selected ${selectedBoard.name} board. [FQBN: ${installedBoard.fqbn}]`);
this.boardsConfig = {
...this.boardsConfig,
selectedBoard: installedBoard
};
return;
}
// The board name can change after install.
// This logic handles it "gracefully" by unselecting the board, so that we can avoid no FQBN is set error.
// https://github.com/arduino/arduino-cli/issues/620
// https://github.com/arduino/arduino-pro-ide/issues/374
if (BoardWithPackage.is(selectedBoard) && selectedBoard.packageId === event.item.id && !installedBoard) {
this.messageService.warn(`Could not find previously selected board '${selectedBoard.name}' in installed platform '${event.item.name}'. Please manually reselect the board you want to use. Do you want to reselect it now?`, 'Reselect later', 'Yes').then(async answer => {
if (answer === 'Yes') {
this.commandService.executeCommand(ArduinoCommands.OPEN_BOARDS_DIALOG.id, selectedBoard.name);
}
});
this.boardsConfig = {}
return;
}
// Trigger a board re-set. See: https://github.com/arduino/arduino-cli/issues/954
// E.g: install `adafruit:avr`, then select `adafruit:avr:adafruit32u4` board, and finally install the required `arduino:avr`
this.boardsConfig = this.boardsConfig;
}
}
protected notifyPlatformUninstalled(event: { item: BoardsPackage }): void {
this.logger.info('Boards package uninstalled: ', JSON.stringify(event));
const { selectedBoard } = this.boardsConfig;
if (selectedBoard && selectedBoard.fqbn) {
const uninstalledBoard = event.item.boards.find(({ name }) => name === selectedBoard.name);
if (uninstalledBoard && uninstalledBoard.fqbn === selectedBoard.fqbn) {
this.logger.info(`Board package ${event.item.id} was uninstalled. Discarding the FQBN of the currently selected ${selectedBoard.name} board.`);
const selectedBoardWithoutFqbn = {
name: selectedBoard.name
// No FQBN
};
this.boardsConfig = {
...this.boardsConfig,
selectedBoard: selectedBoardWithoutFqbn
};
}
}
}
protected async tryReconnect(): Promise<boolean> {
if (this.latestValidBoardsConfig && !this.canUploadTo(this.boardsConfig)) {
for (const board of this.availableBoards.filter(({ state }) => state !== AvailableBoard.State.incomplete)) {
if (this.latestValidBoardsConfig.selectedBoard.fqbn === board.fqbn
&& this.latestValidBoardsConfig.selectedBoard.name === board.name
&& Port.sameAs(this.latestValidBoardsConfig.selectedPort, board.port)) {
this.boardsConfig = this.latestValidBoardsConfig;
return true;
}
}
// If we could not find an exact match, we compare the board FQBN-name pairs and ignore the port, as it might have changed.
// See documentation on `latestValidBoardsConfig`.
for (const board of this.availableBoards.filter(({ state }) => state !== AvailableBoard.State.incomplete)) {
if (this.latestValidBoardsConfig.selectedBoard.fqbn === board.fqbn
&& this.latestValidBoardsConfig.selectedBoard.name === board.name) {
this.boardsConfig = {
...this.latestValidBoardsConfig,
selectedPort: board.port
};
return true;
}
}
}
return false;
}
set boardsConfig(config: BoardsConfig.Config) {
this.doSetBoardsConfig(config);
this.saveState().finally(() => this.reconcileAvailableBoards().finally(() => this.onBoardsConfigChangedEmitter.fire(this._boardsConfig)));
}
protected doSetBoardsConfig(config: BoardsConfig.Config): void {
this.logger.info('Board config changed: ', JSON.stringify(config));
this._boardsConfig = config;
this.latestBoardsConfig = this._boardsConfig;
if (this.canUploadTo(this._boardsConfig)) {
this.latestValidBoardsConfig = this._boardsConfig;
}
}
async searchBoards({ query, cores }: { query?: string, cores?: string[] }): Promise<Array<BoardWithPackage>> {
const boards = await this.boardsService.allBoards({});
const coresFilter = !!cores && cores.length
? ((toFilter: BoardWithPackage) => cores.some(core => core === toFilter.packageName || core === toFilter.packageId))
: () => true;
if (!query) {
return boards.filter(coresFilter).sort(Board.compare);
}
const toMatch = ((toFilter: BoardWithPackage) => (({ board: toFilter, matches: monaco.filters.matchesFuzzy(query, toFilter.name, true) })));
const compareEntries = (left: BoardMatch, right: BoardMatch, lookFor: string) => {
const leftMatches = left.matches || [];
const rightMatches = right.matches || [];
if (leftMatches.length && !rightMatches.length) {
return -1;
}
if (!leftMatches.length && rightMatches.length) {
return 1;
}
if (leftMatches.length === 0 && rightMatches.length === 0) {
return 0;
}
const leftLabel = left.board.name.replace(/\r?\n/g, ' ');
const rightLabel = right.board.name.replace(/\r?\n/g, ' ');
return compareAnything(leftLabel, rightLabel, lookFor);
}
const normalizedQuery = query.toLowerCase();
return boards
.filter(coresFilter)
.map(toMatch)
.filter(({ matches }) => !!matches)
.sort((left, right) => compareEntries(left, right, normalizedQuery))
.map(({ board }) => board);
}
get boardsConfig(): BoardsConfig.Config {
return this._boardsConfig;
}
/**
* `true` if the `config.selectedBoard` is defined; hence can compile against the board. Otherwise, `false`.
*/
canVerify(
config: BoardsConfig.Config | undefined = this.boardsConfig,
options: { silent: boolean } = { silent: true }): config is BoardsConfig.Config & { selectedBoard: Board } {
if (!config) {
return false;
}
if (!config.selectedBoard) {
if (!options.silent) {
this.messageService.warn('No boards selected.', { timeout: 3000 });
}
return false;
}
return true;
}
/**
* `true` if `canVerify`, the board has an FQBN and the `config.selectedPort` is also set, hence can upload to board. Otherwise, `false`.
*/
canUploadTo(
config: BoardsConfig.Config | undefined = this.boardsConfig,
options: { silent: boolean } = { silent: true }): config is RecursiveRequired<BoardsConfig.Config> {
if (!this.canVerify(config, options)) {
return false;
}
const { name } = config.selectedBoard;
if (!config.selectedPort) {
if (!options.silent) {
this.messageService.warn(`No ports selected for board: '${name}'.`, { timeout: 3000 });
}
return false;
}
if (!config.selectedBoard.fqbn) {
if (!options.silent) {
this.messageService.warn(`The FQBN is not available for the selected board ${name}. Do you have the corresponding core installed?`, { timeout: 3000 });
}
return false;
}
return true;
}
get availableBoards(): AvailableBoard[] {
return this._availableBoards;
}
async waitUntilAvailable(what: Board & { port: Port }, timeout?: number): Promise<void> {
const find = (needle: Board & { port: Port }, haystack: AvailableBoard[]) =>
haystack.find(board => Board.equals(needle, board) && Port.equals(needle.port, board.port));
const timeoutTask = !!timeout && timeout > 0
? new Promise<void>((_, reject) => setTimeout(() => reject(new Error(`Timeout after ${timeout} ms.`)), timeout))
: new Promise<void>(() => { /* never */ });
const waitUntilTask = new Promise<void>(resolve => {
let candidate = find(what, this.availableBoards);
if (candidate) {
resolve();
return;
}
const disposable = this.onAvailableBoardsChanged(availableBoards => {
candidate = find(what, availableBoards);
if (candidate) {
disposable.dispose();
resolve();
}
});
});
return await Promise.race([waitUntilTask, timeoutTask]);
}
protected async reconcileAvailableBoards(): Promise<void> {
const attachedBoards = this._attachedBoards;
const availablePorts = this._availablePorts;
// Unset the port on the user's config, if it is not available anymore.
if (this.boardsConfig.selectedPort && !availablePorts.some(port => Port.sameAs(port, this.boardsConfig.selectedPort))) {
this.doSetBoardsConfig({ selectedBoard: this.boardsConfig.selectedBoard, selectedPort: undefined });
this.onBoardsConfigChangedEmitter.fire(this._boardsConfig);
}
const boardsConfig = this.boardsConfig;
const currentAvailableBoards = this._availableBoards;
const availableBoards: AvailableBoard[] = [];
const availableBoardPorts = availablePorts.filter(Port.isBoardPort);
const attachedSerialBoards = attachedBoards.filter(({ port }) => !!port);
for (const boardPort of availableBoardPorts) {
let state = AvailableBoard.State.incomplete; // Initial pessimism.
let board = attachedSerialBoards.find(({ port }) => Port.sameAs(boardPort, port));
if (board) {
state = AvailableBoard.State.recognized;
} else {
// If the selected board is not recognized because it is a 3rd party board: https://github.com/arduino/arduino-cli/issues/623
// We still want to show it without the red X in the boards toolbar: https://github.com/arduino/arduino-pro-ide/issues/198#issuecomment-599355836
const lastSelectedBoard = await this.getLastSelectedBoardOnPort(boardPort);
if (lastSelectedBoard) {
board = {
...lastSelectedBoard,
port: boardPort
};
state = AvailableBoard.State.guessed;
}
}
if (!board) {
availableBoards.push({ name: 'Unknown', port: boardPort, state });
} else {
const selected = BoardsConfig.Config.sameAs(boardsConfig, board);
availableBoards.push({ ...board, state, selected, port: boardPort });
}
}
if (boardsConfig.selectedBoard && !availableBoards.some(({ selected }) => selected)) {
availableBoards.push({
...boardsConfig.selectedBoard,
port: boardsConfig.selectedPort,
selected: true,
state: AvailableBoard.State.incomplete
});
}
const sortedAvailableBoards = availableBoards.sort(AvailableBoard.compare);
let hasChanged = sortedAvailableBoards.length !== currentAvailableBoards.length;
for (let i = 0; !hasChanged && i < sortedAvailableBoards.length; i++) {
hasChanged = AvailableBoard.compare(sortedAvailableBoards[i], currentAvailableBoards[i]) !== 0;
}
if (hasChanged) {
this._availableBoards = sortedAvailableBoards;
this.onAvailableBoardsChangedEmitter.fire(this._availableBoards);
}
}
protected async getLastSelectedBoardOnPort(port: Port | string | undefined): Promise<Board | undefined> {
if (!port) {
return undefined;
}
const key = this.getLastSelectedBoardOnPortKey(port);
return this.storageService.getData<Board>(key);
}
protected async saveState(): Promise<void> {
// We save the port with the selected board name/FQBN, to be able to guess a better board name.
// Required when the attached board belongs to a 3rd party boards package, and neither the name, nor
// the FQBN can be retrieved with a `board list` command.
// https://github.com/arduino/arduino-cli/issues/623
const { selectedBoard, selectedPort } = this.boardsConfig;
if (selectedBoard && selectedPort) {
const key = this.getLastSelectedBoardOnPortKey(selectedPort);
await this.storageService.setData(key, selectedBoard);
}
await Promise.all([
this.storageService.setData('latest-valid-boards-config', this.latestValidBoardsConfig),
this.storageService.setData('latest-boards-config', this.latestBoardsConfig)
]);
}
protected getLastSelectedBoardOnPortKey(port: Port | string): string {
// TODO: we lose the port's `protocol` info (`serial`, `network`, etc.) here if the `port` is a `string`.
return `last-selected-board-on-port:${typeof port === 'string' ? port : Port.toString(port)}`;
}
protected async loadState(): Promise<void> {
const storedLatestValidBoardsConfig = await this.storageService.getData<RecursiveRequired<BoardsConfig.Config>>('latest-valid-boards-config');
if (storedLatestValidBoardsConfig) {
this.latestValidBoardsConfig = storedLatestValidBoardsConfig;
if (this.canUploadTo(this.latestValidBoardsConfig)) {
this.boardsConfig = this.latestValidBoardsConfig;
}
} else {
// If we could not restore the latest valid config, try to restore something, the board at least.
const storedLatestBoardsConfig = await this.storageService.getData<BoardsConfig.Config | undefined>('latest-boards-config');
if (storedLatestBoardsConfig) {
this.latestBoardsConfig = storedLatestBoardsConfig;
this.boardsConfig = this.latestBoardsConfig;
}
}
}
}
/**
* Representation of a ready-to-use board, either the user has configured it or was automatically recognized by the CLI.
* An available board was not necessarily recognized by the CLI (e.g.: it is a 3rd party board) or correctly configured but ready for `verify`.
* If it has the selected board and a associated port, it can be used for `upload`. We render an available board for the user
* when it has the `port` set.
*/
export interface AvailableBoard extends Board {
readonly state: AvailableBoard.State;
readonly selected?: boolean;
readonly port?: Port;
}
export namespace AvailableBoard {
export enum State {
/**
* Retrieved from the CLI via the `board list` command.
*/
'recognized',
/**
* Guessed the name/FQBN of the board from the available board ports (3rd party).
*/
'guessed',
/**
* We do not know anything about this board, probably a 3rd party. The user has not selected a board for this port yet.
*/
'incomplete'
}
export function is(board: any): board is AvailableBoard {
return Board.is(board) && 'state' in board;
}
export function hasPort(board: AvailableBoard): board is AvailableBoard & { port: Port } {
return !!board.port;
}
export const compare = (left: AvailableBoard, right: AvailableBoard) => {
if (left.selected && !right.selected) {
return -1;
}
if (right.selected && !left.selected) {
return 1;
}
let result = naturalCompare(left.name, right.name);
if (result !== 0) {
return result;
}
if (left.fqbn && right.fqbn) {
result = naturalCompare(left.fqbn, right.fqbn);
if (result !== 0) {
return result;
}
}
if (left.port && right.port) {
result = Port.compare(left.port, right.port);
if (result !== 0) {
return result;
}
}
if (!!left.selected && !right.selected) {
return -1;
}
if (!!right.selected && !left.selected) {
return 1;
}
return left.state - right.state;
}
}

View File

@@ -1,61 +1,38 @@
import * as React from 'react';
import { BoardsService, Board, AttachedSerialBoard } from '../../common/protocol/boards-service';
import { ContextMenuRenderer, StatusBar, StatusBarAlignment } from '@theia/core/lib/browser';
import { BoardsNotificationService } from '../boards-notification-service';
import { Command, CommandRegistry } from '@theia/core';
import * as ReactDOM from 'react-dom';
import { CommandRegistry } from '@theia/core/lib/common/command';
import { DisposableCollection } from '@theia/core/lib/common/disposable';
import { Port } from '../../common/protocol';
import { BoardsConfig } from './boards-config';
import { ArduinoCommands } from '../arduino-commands';
import ReactDOM = require('react-dom');
import { BoardsServiceProvider, AvailableBoard } from './boards-service-provider';
export interface BoardsDropdownItem {
label: string;
commandExecutor: () => void;
isSelected: () => boolean;
}
export interface BoardsDropDownListCoord {
top: number;
left: number;
width: number;
paddingTop: number;
}
export namespace BoardsDropdownItemComponent {
export interface Props {
label: string;
onClick: () => void;
isSelected: boolean;
}
}
export class BoardsDropdownItemComponent extends React.Component<BoardsDropdownItemComponent.Props> {
render() {
return <div className={`arduino-boards-dropdown-item ${this.props.isSelected ? 'selected' : ''}`} onClick={this.props.onClick}>
<div>{this.props.label}</div>
{this.props.isSelected ? <span className='fa fa-check'></span> : ''}
</div>;
}
export interface BoardsDropDownListCoords {
readonly top: number;
readonly left: number;
readonly width: number;
readonly paddingTop: number;
}
export namespace BoardsDropDown {
export interface Props {
readonly coords: BoardsDropDownListCoord;
readonly isOpen: boolean;
readonly dropDownItems: BoardsDropdownItem[];
readonly openDialog: () => void;
readonly coords: BoardsDropDownListCoords | 'hidden';
readonly items: Array<AvailableBoard & { onClick: () => void, port: Port }>;
readonly openBoardsConfig: () => void;
}
}
export class BoardsDropDown extends React.Component<BoardsDropDown.Props> {
protected dropdownId: string = 'boards-dropdown-container';
protected dropdownElement: HTMLElement;
constructor(props: BoardsDropDown.Props) {
super(props);
let list = document.getElementById(this.dropdownId);
let list = document.getElementById('boards-dropdown-container');
if (!list) {
list = document.createElement('div');
list.id = this.dropdownId;
list.id = 'boards-dropdown-container';
document.body.appendChild(list);
this.dropdownElement = list;
}
@@ -65,179 +42,152 @@ export class BoardsDropDown extends React.Component<BoardsDropDown.Props> {
return ReactDOM.createPortal(this.renderNode(), this.dropdownElement);
}
renderNode(): React.ReactNode {
if (this.props.isOpen) {
return <div className='arduino-boards-dropdown-list'
style={{
position: 'absolute',
top: this.props.coords.top,
left: this.props.coords.left,
width: this.props.coords.width,
paddingTop: this.props.coords.paddingTop
}}>
{
this.props.dropDownItems.map(item => {
return <React.Fragment key={item.label}>
<BoardsDropdownItemComponent isSelected={item.isSelected()} label={item.label} onClick={item.commandExecutor}></BoardsDropdownItemComponent>
</React.Fragment>;
})
}
<BoardsDropdownItemComponent isSelected={false} label={'Select Other Board & Port'} onClick={this.props.openDialog}></BoardsDropdownItemComponent>
</div>
} else {
protected renderNode(): React.ReactNode {
const { coords, items } = this.props;
if (coords === 'hidden') {
return '';
}
}
}
export namespace BoardsToolBarItem {
export interface Props {
readonly contextMenuRenderer: ContextMenuRenderer;
readonly boardsNotificationService: BoardsNotificationService;
readonly boardService: BoardsService;
readonly commands: CommandRegistry;
readonly statusBar: StatusBar;
return <div className='arduino-boards-dropdown-list'
style={{
position: 'absolute',
...coords
}}>
{this.renderItem({
label: 'Select Other Board & Port',
onClick: () => this.props.openBoardsConfig()
})}
{items.map(({ name, port, selected, onClick }) => ({ label: `${name} at ${Port.toString(port)}`, selected, onClick })).map(this.renderItem)}
</div>
}
export interface State {
selectedBoard?: Board;
selectedIsAttached: boolean;
boardItems: BoardsDropdownItem[];
isOpen: boolean;
protected renderItem({ label, selected, onClick }: { label: string, selected?: boolean, onClick: () => void }): React.ReactNode {
return <div key={label} className={`arduino-boards-dropdown-item ${selected ? 'selected' : ''}`} onClick={onClick}>
<div>
{label}
</div>
{selected ? <span className='fa fa-check' /> : ''}
</div>
}
}
export class BoardsToolBarItem extends React.Component<BoardsToolBarItem.Props, BoardsToolBarItem.State> {
protected attachedBoards: Board[];
protected dropDownListCoord: BoardsDropDownListCoord;
static TOOLBAR_ID: 'boards-toolbar';
protected readonly toDispose: DisposableCollection = new DisposableCollection();
constructor(props: BoardsToolBarItem.Props) {
super(props);
const { availableBoards } = props.boardsServiceClient;
this.state = {
selectedBoard: undefined,
selectedIsAttached: true,
boardItems: [],
isOpen: false
availableBoards,
coords: 'hidden'
};
document.addEventListener('click', () => {
this.setState({ isOpen: false });
this.setState({ coords: 'hidden' });
});
}
componentDidMount() {
this.setAttachedBoards();
this.props.boardsServiceClient.onAvailableBoardsChanged(availableBoards => this.setState({ availableBoards }));
}
setSelectedBoard(board: Board) {
if (this.attachedBoards && this.attachedBoards.length) {
this.setState({ selectedIsAttached: !!this.attachedBoards.find(attachedBoard => attachedBoard.name === board.name) });
}
this.setState({ selectedBoard: board });
componentWillUnmount(): void {
this.toDispose.dispose();
}
protected async setAttachedBoards() {
const { boards } = await this.props.boardService.getAttachedBoards();
this.attachedBoards = boards;
if (this.attachedBoards.length) {
await this.createBoardDropdownItems();
await this.props.boardService.selectBoard(this.attachedBoards[0]);
this.setSelectedBoard(this.attachedBoards[0]);
}
}
protected createBoardDropdownItems() {
const boardItems: BoardsDropdownItem[] = [];
this.attachedBoards.forEach(board => {
const { commands } = this.props;
const port = this.getPort(board);
const command: Command = {
id: 'selectBoard' + port
protected readonly show = (event: React.MouseEvent<HTMLElement>) => {
const { currentTarget: element } = event;
if (element instanceof HTMLElement) {
if (this.state.coords === 'hidden') {
const rect = element.getBoundingClientRect();
this.setState({
coords: {
top: rect.top,
left: rect.left,
width: rect.width,
paddingTop: rect.height
}
});
} else {
this.setState({ coords: 'hidden' });
}
commands.registerCommand(command, {
execute: () => {
commands.executeCommand(ArduinoCommands.SELECT_BOARD.id, board);
this.setState({ isOpen: false, selectedBoard: board });
}
});
boardItems.push({
commandExecutor: () => commands.executeCommand(command.id),
label: board.name + ' at ' + port,
isSelected: () => this.doIsSelectedBoard(board)
});
});
this.setState({ boardItems });
}
protected doIsSelectedBoard = (board: Board) => this.isSelectedBoard(board);
protected isSelectedBoard(board: Board): boolean {
return AttachedSerialBoard.is(board) &&
!!this.state.selectedBoard &&
AttachedSerialBoard.is(this.state.selectedBoard) &&
board.port === this.state.selectedBoard.port &&
board.fqbn === this.state.selectedBoard.fqbn;
}
protected getPort(board: Board): string {
if (AttachedSerialBoard.is(board)) {
return board.port;
}
return '';
}
protected readonly doShowSelectBoardsMenu = (event: React.MouseEvent<HTMLElement>) => {
this.showSelectBoardsMenu(event);
event.stopPropagation();
event.nativeEvent.stopImmediatePropagation();
};
protected showSelectBoardsMenu(event: React.MouseEvent<HTMLElement>) {
const el = (event.currentTarget as HTMLElement);
if (el) {
this.dropDownListCoord = {
top: el.getBoundingClientRect().top,
left: el.getBoundingClientRect().left,
paddingTop: el.getBoundingClientRect().height,
width: el.getBoundingClientRect().width
}
this.setState({ isOpen: !this.state.isOpen });
}
}
render(): React.ReactNode {
const selectedBoard = this.state.selectedBoard;
const port = selectedBoard ? this.getPort(selectedBoard) : undefined;
const boardTxt = selectedBoard && `${selectedBoard.name}${port ? ' at ' + port : ''}` || '';
this.props.statusBar.setElement('arduino-selected-board', {
alignment: StatusBarAlignment.RIGHT,
text: boardTxt
});
const { coords, availableBoards } = this.state;
const boardsConfig = this.props.boardsServiceClient.boardsConfig;
const title = BoardsConfig.Config.toString(boardsConfig, { default: 'no board selected' });
const decorator = (() => {
const selectedBoard = availableBoards.find(({ selected }) => selected);
if (!selectedBoard || !selectedBoard.port) {
return 'fa fa-times notAttached'
}
if (selectedBoard.state === AvailableBoard.State.guessed) {
return 'fa fa-exclamation-triangle guessed'
}
return ''
})();
return <React.Fragment>
<div className='arduino-boards-toolbar-item-container'>
<div className='arduino-boards-toolbar-item' title={boardTxt}>
<div className='inner-container' onClick={this.doShowSelectBoardsMenu}>
<span className={!selectedBoard || !this.state.selectedIsAttached ? 'fa fa-times notAttached' : ''}></span>
<div className='arduino-boards-toolbar-item' title={title}>
<div className='inner-container' onClick={this.show}>
<span className={decorator} />
<div className='label noWrapInfo'>
<div className='noWrapInfo noselect'>
{selectedBoard ? boardTxt : 'no board selected'}
{title}
</div>
</div>
<span className='fa fa-caret-down caret'></span>
<span className='fa fa-caret-down caret' />
</div>
</div>
</div>
<BoardsDropDown
isOpen={this.state.isOpen}
coords={this.dropDownListCoord}
dropDownItems={this.state.boardItems}
openDialog={this.openDialog}>
coords={coords}
items={availableBoards.filter(AvailableBoard.hasPort).map(board => ({
...board,
onClick: () => {
if (board.state === AvailableBoard.State.incomplete) {
this.props.boardsServiceClient.boardsConfig = {
selectedPort: board.port
};
this.openDialog();
} else {
this.props.boardsServiceClient.boardsConfig = {
selectedBoard: board,
selectedPort: board.port
}
}
}
}))}
openBoardsConfig={this.openDialog}>
</BoardsDropDown>
</React.Fragment>;
}
protected openDialog = () => {
this.props.commands.executeCommand(ArduinoCommands.OPEN_BOARDS_DIALOG.id);
this.setState({ isOpen: false });
this.setState({ coords: 'hidden' });
};
}
}
export namespace BoardsToolBarItem {
export interface Props {
readonly boardsServiceClient: BoardsServiceProvider;
readonly commands: CommandRegistry;
}
export interface State {
availableBoards: AvailableBoard[];
coords: BoardsDropDownListCoords | 'hidden';
}
}

View File

@@ -1,24 +1,10 @@
import { injectable } from 'inversify';
import { FrontendApplicationContribution } from '@theia/core/lib/browser/frontend-application';
import { AbstractViewContribution } from '@theia/core/lib/browser/shell/view-contribution';
import { ListWidget } from './list-widget';
import { BoardsListWidget } from './boards-list-widget';
import { MenuModelRegistry } from '@theia/core';
import { ArduinoMenus } from '../arduino-frontend-contribution';
import { BoardsPackage } from '../../common/protocol/boards-service';
import { ListWidgetFrontendContribution } from '../widgets/component-list/list-widget-frontend-contribution';
@injectable()
export abstract class ListWidgetFrontendContribution extends AbstractViewContribution<ListWidget> implements FrontendApplicationContribution {
async initializeLayout(): Promise<void> {
// await this.openView();
}
}
@injectable()
export class BoardsListWidgetFrontendContribution extends ListWidgetFrontendContribution {
static readonly OPEN_MANAGER = `${BoardsListWidget.WIDGET_ID}:toggle`;
export class BoardsListWidgetFrontendContribution extends ListWidgetFrontendContribution<BoardsPackage> {
constructor() {
super({
@@ -28,18 +14,13 @@ export class BoardsListWidgetFrontendContribution extends ListWidgetFrontendCont
area: 'left',
rank: 600
},
toggleCommandId: BoardsListWidgetFrontendContribution.OPEN_MANAGER,
toggleKeybinding: 'ctrlcmd+shift+b'
toggleCommandId: `${BoardsListWidget.WIDGET_ID}:toggle`,
toggleKeybinding: 'CtrlCmd+Shift+B'
});
}
registerMenus(menus: MenuModelRegistry): void {
if (this.toggleCommand) {
menus.registerMenuAction(ArduinoMenus.TOOLS, {
commandId: this.toggleCommand.id,
label: 'Boards Manager...'
});
}
async initializeLayout(): Promise<void> {
this.openView();
}
}

View File

@@ -1,88 +0,0 @@
import * as React from 'react';
import { inject, injectable, postConstruct } from 'inversify';
import { Message } from '@phosphor/messaging';
import { ReactWidget } from '@theia/core/lib/browser/widgets/react-widget';
import { WindowService } from '@theia/core/lib/browser/window/window-service';
import { FilterableListContainer } from '../components/component-list/filterable-list-container';
import { BoardsService, Board, BoardPackage } from '../../common/protocol/boards-service';
import { BoardsNotificationService } from '../boards-notification-service';
import { LibraryService } from '../../common/protocol/library-service';
@injectable()
export abstract class ListWidget extends ReactWidget {
@inject(BoardsService)
protected readonly boardsService: BoardsService;
@inject(WindowService)
protected readonly windowService: WindowService;
@inject(BoardsNotificationService)
protected readonly boardsNotificationService: BoardsNotificationService;
constructor() {
super();
const { id, title, iconClass } = this.widgetProps();
this.id = id;
this.title.label = title;
this.title.caption = title;
this.title.iconClass = iconClass;
this.title.closable = true;
this.addClass(ListWidget.Styles.LIST_WIDGET_CLASS);
this.node.tabIndex = 0; // To be able to set the focus on the widget.
}
protected abstract widgetProps(): ListWidget.Props;
@postConstruct()
protected init(): void {
this.update();
}
protected onActivateRequest(msg: Message): void {
super.onActivateRequest(msg);
this.node.focus();
this.render();
}
protected onUpdateRequest(msg: Message): void {
super.onUpdateRequest(msg);
this.render();
}
render(): React.ReactNode {
const boardsServiceDelegate = this.boardsService;
const boardsService: BoardsService = {
getAttachedBoards: () => boardsServiceDelegate.getAttachedBoards(),
selectBoard: (board: Board) => boardsServiceDelegate.selectBoard(board),
getSelectBoard: () => boardsServiceDelegate.getSelectBoard(),
search: (options: { query?: string, props?: LibraryService.Search.Props }) => boardsServiceDelegate.search(options),
install: async (item: BoardPackage) => {
await boardsServiceDelegate.install(item);
this.boardsNotificationService.notifyBoardsInstalled();
}
}
return <FilterableListContainer
service={boardsService}
windowService={this.windowService}
/>;
}
}
export namespace ListWidget {
/**
* Props for customizing the abstract list widget.
*/
export interface Props {
readonly id: string;
readonly title: string;
readonly iconClass: string;
}
export namespace Styles {
export const LIST_WIDGET_CLASS = 'arduino-list-widget'
}
}

View File

@@ -0,0 +1,16 @@
import { ContainerModule } from 'inversify';
import { ILogger } from '@theia/core/lib/common/logger';
import { CommandContribution } from '@theia/core/lib/common/command';
import { QuickOpenContribution } from '@theia/core/lib/browser/quick-open';
import { KeybindingContribution } from '@theia/core/lib/browser/keybinding';
import { BoardsQuickOpenService } from './boards-quick-open-service';
export default new ContainerModule(bind => {
bind(BoardsQuickOpenService).toSelf().inSingletonScope();
bind(CommandContribution).toService(BoardsQuickOpenService);
bind(KeybindingContribution).toService(BoardsQuickOpenService);
bind(QuickOpenContribution).toService(BoardsQuickOpenService);
bind(ILogger).toDynamicValue(({ container }) => container.get<ILogger>(ILogger).child('boards-quick-open'))
.inSingletonScope()
.whenTargetNamed('boards-quick-open');
});

View File

@@ -0,0 +1,309 @@
import * as fuzzy from 'fuzzy';
import { inject, injectable, postConstruct, named } from 'inversify';
import { ILogger } from '@theia/core/lib/common/logger';
import { CommandContribution, CommandRegistry, Command } from '@theia/core/lib/common/command';
import { KeybindingContribution, KeybindingRegistry } from '@theia/core/lib/browser/keybinding';
import { QuickOpenItem, QuickOpenModel, QuickOpenMode, QuickOpenGroupItem } from '@theia/core/lib/common/quick-open-model';
import {
QuickOpenService,
QuickOpenHandler,
QuickOpenOptions,
QuickOpenItemOptions,
QuickOpenContribution,
QuickOpenActionProvider,
QuickOpenHandlerRegistry,
QuickOpenGroupItemOptions
} from '@theia/core/lib/browser/quick-open';
import { naturalCompare } from '../../../common/utils';
import { BoardsService, Port, Board, ConfigOption, ConfigValue } from '../../../common/protocol';
import { BoardsDataStore } from '../boards-data-store';
import { BoardsServiceProvider, AvailableBoard } from '../boards-service-provider';
import { NotificationCenter } from '../../notification-center';
@injectable()
export class BoardsQuickOpenService implements QuickOpenContribution, QuickOpenModel, QuickOpenHandler, CommandContribution, KeybindingContribution, Command {
readonly id = 'arduino-boards-quick-open';
readonly prefix = '|';
readonly description = 'Configure Available Boards';
readonly label: 'Configure Available Boards';
@inject(ILogger)
@named('boards-quick-open')
protected readonly logger: ILogger;
@inject(QuickOpenService)
protected readonly quickOpenService: QuickOpenService;
@inject(BoardsService)
protected readonly boardsService: BoardsService;
@inject(BoardsServiceProvider)
protected readonly boardsServiceClient: BoardsServiceProvider;
@inject(BoardsDataStore)
protected readonly boardsDataStore: BoardsDataStore;
@inject(NotificationCenter)
protected notificationCenter: NotificationCenter;
protected isOpen: boolean = false;
protected currentQuery: string = '';
// Attached boards plus the user's config.
protected availableBoards: AvailableBoard[] = [];
// Only for the `selected` one from the `availableBoards`. Note: the `port` of the `selected` is optional.
protected data: BoardsDataStore.Data = BoardsDataStore.Data.EMPTY;
protected allBoards: Board.Detailed[] = []
protected selectedBoard?: (AvailableBoard & { port: Port });
// `init` name is used by the `QuickOpenHandler`.
@postConstruct()
protected postConstruct(): void {
this.notificationCenter.onIndexUpdated(() => this.update(this.availableBoards));
this.boardsServiceClient.onAvailableBoardsChanged(availableBoards => this.update(availableBoards));
this.update(this.boardsServiceClient.availableBoards);
}
registerCommands(registry: CommandRegistry): void {
registry.registerCommand(this, { execute: () => this.open() });
}
registerKeybindings(registry: KeybindingRegistry): void {
registry.registerKeybinding({ command: this.id, keybinding: 'ctrlCmd+k ctrlCmd+b' });
}
registerQuickOpenHandlers(registry: QuickOpenHandlerRegistry): void {
registry.registerHandler(this);
}
getModel(): QuickOpenModel {
return this;
}
getOptions(): QuickOpenOptions {
let placeholder = '';
if (!this.selectedBoard) {
placeholder += 'No board selected.';
}
placeholder += 'Type to filter boards';
if (this.data.configOptions.length) {
placeholder += ' or use the ↓↑ keys to adjust the board settings...';
} else {
placeholder += '...';
}
return {
placeholder,
fuzzyMatchLabel: true,
onClose: () => this.isOpen = false
};
}
open(): void {
this.isOpen = true;
this.quickOpenService.open(this, this.getOptions());
}
onType(
lookFor: string,
acceptor: (items: QuickOpenItem<QuickOpenItemOptions>[], actionProvider?: QuickOpenActionProvider) => void): void {
this.currentQuery = lookFor;
const fuzzyFilter = this.fuzzyFilter(lookFor);
const availableBoards = this.availableBoards.filter(AvailableBoard.hasPort).filter(({ name }) => fuzzyFilter(name));
const toAccept: QuickOpenItem<QuickOpenItemOptions>[] = [];
// Show the selected attached in a different group.
if (this.selectedBoard && fuzzyFilter(this.selectedBoard.name)) {
toAccept.push(this.toQuickItem(this.selectedBoard, { groupLabel: 'Selected Board' }));
}
// Filter the selected from the attached ones.
toAccept.push(...availableBoards.filter(board => board !== this.selectedBoard).map((board, i) => {
let group: QuickOpenGroupItemOptions | undefined = undefined;
if (i === 0) {
// If no `selectedBoard`, then this item is the top one, no borders required.
group = { groupLabel: 'Attached Boards', showBorder: !!this.selectedBoard };
}
return this.toQuickItem(board, group);
}));
// Show the config only if the `input` is empty.
if (!lookFor.trim().length) {
toAccept.push(...this.data.configOptions.map((config, i) => {
let group: QuickOpenGroupItemOptions | undefined = undefined;
if (i === 0) {
group = { groupLabel: 'Board Settings', showBorder: true };
}
return this.toQuickItem(config, group);
}));
} else {
toAccept.push(...this.allBoards.filter(({ name }) => fuzzyFilter(name)).map((board, i) => {
let group: QuickOpenGroupItemOptions | undefined = undefined;
if (i === 0) {
group = { groupLabel: 'Boards', showBorder: true };
}
return this.toQuickItem(board, group);
}));
}
acceptor(toAccept);
}
private fuzzyFilter(lookFor: string): (inputString: string) => boolean {
const shouldFilter = !!lookFor.trim().length;
return (inputString: string) => shouldFilter ? fuzzy.test(lookFor.toLocaleLowerCase(), inputString.toLocaleLowerCase()) : true;
}
protected async update(availableBoards: AvailableBoard[]): Promise<void> {
// `selectedBoard` is not an attached board, we need to show the board settings for it (TODO: clarify!)
const selectedBoard = availableBoards.filter(AvailableBoard.hasPort).find(({ selected }) => selected);
const [data, boards] = await Promise.all([
selectedBoard && selectedBoard.fqbn ? this.boardsDataStore.getData(selectedBoard.fqbn) : Promise.resolve(BoardsDataStore.Data.EMPTY),
this.boardsService.allBoards({})
]);
this.allBoards = Board.decorateBoards(selectedBoard, boards)
.filter(board => !availableBoards.some(availableBoard => Board.sameAs(availableBoard, board)));
this.availableBoards = availableBoards;
this.data = data;
this.selectedBoard = selectedBoard;
if (this.isOpen) {
// Hack, to update the state without closing and reopening the quick open widget.
(this.quickOpenService as any).onType(this.currentQuery);
}
}
protected toQuickItem(item: BoardsQuickOpenService.Item, group?: QuickOpenGroupItemOptions): QuickOpenItem<QuickOpenItemOptions> {
let options: QuickOpenItemOptions;
if (AvailableBoard.is(item)) {
const description = `on ${Port.toString(item.port)}`
options = {
label: `${item.name}`,
description,
descriptionHighlights: [
{
start: 0,
end: description.length
}
],
run: this.toRun(() => this.boardsServiceClient.boardsConfig = ({ selectedBoard: item, selectedPort: item.port }))
};
} else if (ConfigOption.is(item)) {
const selected = item.values.find(({ selected }) => selected);
const value = selected ? selected.label : 'Not set';
const label = `${item.label}: ${value}`;
options = {
label,
// Intended to match the value part of a board setting.
// NOTE: this does not work, as `fuzzyMatchLabel: true` is set. Manual highlighting is ignored, apparently.
labelHighlights: [
{
start: label.length - value.length,
end: label.length
}
],
run: (mode) => {
if (mode === QuickOpenMode.OPEN) {
this.setConfig(item);
return false;
}
return true;
}
};
if (!selected) {
options.description = 'Not set';
};
} else {
options = {
label: `${item.name}`,
description: `${item.missing ? '' : `[installed with '${item.packageName}']`}`,
run: (mode) => {
if (mode === QuickOpenMode.OPEN) {
this.selectBoard(item);
return false;
}
return true;
}
};
}
if (group) {
return new QuickOpenGroupItem<QuickOpenGroupItemOptions>({ ...options, ...group });
} else {
return new QuickOpenItem<QuickOpenItemOptions>(options);
}
}
protected toRun(run: (() => void)): ((mode: QuickOpenMode) => boolean) {
return (mode) => {
if (mode !== QuickOpenMode.OPEN) {
return false;
}
run();
return true;
};
}
protected async selectBoard(board: Board): Promise<void> {
const allPorts = this.availableBoards.filter(AvailableBoard.hasPort).map(({ port }) => port).sort(Port.compare);
const toItem = (port: Port) => new QuickOpenItem<QuickOpenItemOptions>({
label: Port.toString(port, { useLabel: true }),
run: this.toRun(() => {
this.boardsServiceClient.boardsConfig = {
selectedBoard: board,
selectedPort: port
};
})
});
const options = {
placeholder: `Select a port for '${board.name}'. Press 'Enter' to confirm or 'Escape' to cancel.`,
fuzzyMatchLabel: true
}
this.quickOpenService.open({
onType: (lookFor, acceptor) => {
const fuzzyFilter = this.fuzzyFilter(lookFor);
acceptor(allPorts.filter(({ address }) => fuzzyFilter(address)).map(toItem));
}
}, options);
}
protected async setConfig(config: ConfigOption): Promise<void> {
const toItem = (value: ConfigValue) => new QuickOpenItem<QuickOpenItemOptions>({
label: value.label,
iconClass: value.selected ? 'fa fa-check' : '',
run: this.toRun(() => {
if (!this.selectedBoard) {
this.logger.warn(`Could not alter the boards settings. No board selected. ${JSON.stringify(config)}`);
return;
}
if (!this.selectedBoard.fqbn) {
this.logger.warn(`Could not alter the boards settings. The selected board does not have a FQBN. ${JSON.stringify(this.selectedBoard)}`);
return;
}
const { fqbn } = this.selectedBoard;
this.boardsDataStore.selectConfigOption({
fqbn,
option: config.option,
selectedValue: value.value
});
})
});
const options = {
placeholder: `Configure '${config.label}'. Press 'Enter' to confirm or 'Escape' to cancel.`,
fuzzyMatchLabel: true
}
this.quickOpenService.open({
onType: (lookFor, acceptor) => {
const fuzzyFilter = this.fuzzyFilter(lookFor);
acceptor(config.values
.filter(({ label }) => fuzzyFilter(label))
.sort((left, right) => naturalCompare(left.label, right.label))
.map(toItem));
}
}, options);
}
}
export namespace BoardsQuickOpenService {
export type Item = AvailableBoard & { port: Port } | Board.Detailed | ConfigOption;
}

View File

@@ -1,305 +0,0 @@
import * as React from 'react';
import { ReactWidget } from '@theia/core/lib/browser';
import { injectable, inject } from 'inversify';
import { BoardsService, Board, BoardPackage, AttachedSerialBoard } from '../../common/protocol/boards-service';
import { BoardsNotificationService } from '../boards-notification-service';
import { Emitter, Event } from '@theia/core';
export interface BoardAndPortSelection {
board?: Board;
port?: string;
}
export namespace BoardAndPortSelectableItem {
export interface Props {
item: BoardAndPortSelection,
selected: boolean,
onSelect: (selection: BoardAndPortSelection) => void
}
}
export class BoardAndPortSelectableItem extends React.Component<BoardAndPortSelectableItem.Props> {
render(): React.ReactNode {
if (this.props.item.board || this.props.item.port) {
return <div onClick={this.select} className={`item ${this.props.selected ? 'selected' : ''}`}>
{this.props.item.board ? this.props.item.board.name : this.props.item.port}
{this.props.selected ? <i className='fa fa-check'></i> : ''}
</div>;
}
}
protected readonly select = (() => {
this.props.onSelect({ board: this.props.item.board, port: this.props.item.port })
}).bind(this);
}
export namespace BoardAndPortSelectionList {
export interface Props {
type: 'boards' | 'ports';
list: BoardAndPortSelection[];
onSelect: (selection: BoardAndPortSelection) => void;
}
export interface State {
selection: BoardAndPortSelection
}
}
export class BoardAndPortSelectionList extends React.Component<BoardAndPortSelectionList.Props, BoardAndPortSelectionList.State> {
constructor(props: BoardAndPortSelectionList.Props) {
super(props);
this.state = {
selection: {}
}
}
reset(): void {
this.setState({ selection: {} });
}
render(): React.ReactNode {
return <div className={`${this.props.type} list`}>
{this.props.list.map(item => <BoardAndPortSelectableItem
key={item.board ? item.board.name : item.port}
onSelect={this.doSelect}
item={item}
selected={this.isSelectedItem(item)}
/>)}
</div>
}
protected readonly doSelect = (boardAndPortSelection: BoardAndPortSelection) => {
this.setState({ selection: boardAndPortSelection });
this.props.onSelect(boardAndPortSelection);
}
protected readonly isSelectedItem = ((item: BoardAndPortSelection) => {
if (this.state.selection.board) {
return (this.state.selection.board === item.board);
} else if (this.state.selection.port) {
return (this.state.selection.port === item.port);
}
return false;
});
protected readonly isSelectedPort = ((port: string) => {
return (this.state.selection.port && this.state.selection.port === port) || false;
});
}
export namespace BoardAndPortSelectionComponent {
export interface Props {
boardsService: BoardsService;
onSelect: (selection: BoardAndPortSelection) => void;
}
export interface State {
boards: Board[];
ports: string[];
selection: BoardAndPortSelection;
}
}
export class BoardAndPortSelectionComponent extends React.Component<BoardAndPortSelectionComponent.Props, BoardAndPortSelectionComponent.State> {
protected allBoards: Board[] = [];
protected boardListComponent: BoardAndPortSelectionList | null;
protected portListComponent: BoardAndPortSelectionList | null;
constructor(props: BoardAndPortSelectionComponent.Props) {
super(props);
this.state = {
boards: [],
ports: [],
selection: {}
}
}
componentDidMount() {
this.searchAvailableBoards();
this.setPorts();
}
reset(): void {
if (this.boardListComponent) {
this.boardListComponent.reset();
}
if (this.portListComponent) {
this.portListComponent.reset();
}
this.setState({ selection: {} });
}
render(): React.ReactNode {
return <React.Fragment>
<div className='body'>
<div className='left container'>
<div className='content'>
<div className='title'>
BOARDS
</div>
<div className='search'>
<input type='search' placeholder='SEARCH BOARD' onChange={this.doFilter} />
<i className='fa fa-search'></i>
</div>
<BoardAndPortSelectionList
ref={ref => { this.boardListComponent = ref }}
type='boards'
onSelect={this.doSelect}
list={this.state.boards.map<BoardAndPortSelection>(board => ({ board }))} />
</div>
</div>
<div className='right container'>
<div className='content'>
<div className='title'>
PORTS
</div>
{
this.state.ports.length ?
<BoardAndPortSelectionList
ref={ref => { this.portListComponent = ref }}
type='ports'
onSelect={this.doSelect}
list={this.state.ports.map<BoardAndPortSelection>(port => ({ port }))} /> : 'loading ports...'
}
</div>
</div>
</div>
</React.Fragment>
}
protected sort(items: Board[]): Board[] {
return items.sort((a, b) => {
if (a.name < b.name) {
return -1;
} else if (a.name === b.name) {
return 0;
} else {
return 1;
}
});
}
protected readonly doSelect = (boardAndPortSelection: BoardAndPortSelection) => {
const selection = this.state.selection;
if (boardAndPortSelection.board) {
selection.board = boardAndPortSelection.board;
}
if (boardAndPortSelection.port) {
selection.port = boardAndPortSelection.port;
}
this.setState({ selection });
this.props.onSelect(this.state.selection);
}
protected readonly doFilter = (event: React.ChangeEvent<HTMLInputElement>) => {
const boards = this.allBoards.filter(board => board.name.toLowerCase().indexOf(event.target.value.toLowerCase()) >= 0);
this.setState({ boards })
}
protected async searchAvailableBoards() {
const boardPkg = await this.props.boardsService.search({});
const boards = [].concat.apply([], boardPkg.items.map<Board[]>(item => item.boards)) as Board[];
this.allBoards = this.sort(boards);
this.setState({ boards: this.allBoards });
}
protected async setPorts() {
const ports: string[] = [];
const { boards } = await this.props.boardsService.getAttachedBoards();
boards.forEach(board => {
if (AttachedSerialBoard.is(board)) {
ports.push(board.port);
}
});
this.setState({ ports });
}
}
@injectable()
export class SelectBoardDialogWidget extends ReactWidget {
@inject(BoardsService)
protected readonly boardsService: BoardsService;
@inject(BoardsNotificationService)
protected readonly boardsNotificationService: BoardsNotificationService;
protected readonly onChangedEmitter = new Emitter<BoardAndPortSelection>();
protected boardAndPortSelectionComponent: BoardAndPortSelectionComponent | null;
protected attachedBoards: Promise<{ boards: Board[] }>;
boardAndPort: BoardAndPortSelection = {};
constructor() {
super();
this.id = 'select-board-dialog';
this.toDispose.push(this.onChangedEmitter);
}
get onChanged(): Event<BoardAndPortSelection> {
return this.onChangedEmitter.event;
}
reset(): void {
if (this.boardAndPortSelectionComponent) {
this.boardAndPortSelectionComponent.reset();
}
this.boardAndPort = {};
}
setAttachedBoards(attachedBoards: Promise<{ boards: Board[] }>): void {
this.attachedBoards = attachedBoards;
}
protected fireChanged(boardAndPort: BoardAndPortSelection): void {
this.onChangedEmitter.fire(boardAndPort);
}
protected render(): React.ReactNode {
let content: React.ReactNode;
const boardsServiceDelegate = this.boardsService;
const attachedBoards = this.attachedBoards;
const boardsService: BoardsService = {
getAttachedBoards: () => attachedBoards,
selectBoard: (board: Board) => boardsServiceDelegate.selectBoard(board),
getSelectBoard: () => boardsServiceDelegate.getSelectBoard(),
search: (options: { query?: string }) => boardsServiceDelegate.search(options),
install: async (item: BoardPackage) => {
await boardsServiceDelegate.install(item);
this.boardsNotificationService.notifyBoardsInstalled();
}
}
content = <React.Fragment>
<div className='selectBoardContainer'>
<div className='head'>
<div className='title'>
Select Other Board &amp; Port
</div>
<div className='text'>
<p>Select both a BOARD and a PORT if you want to upload a sketch.</p>
<p>If you only select a BOARD you will be able just to compile,</p>
<p>but not to upload your sketch.</p>
</div>
</div>
<BoardAndPortSelectionComponent
ref={ref => this.boardAndPortSelectionComponent = ref}
boardsService={boardsService}
onSelect={this.onSelect} />
</div>
</React.Fragment>
return content;
}
protected readonly onSelect = (selection: BoardAndPortSelection) => { this.doOnSelect(selection) };
protected doOnSelect(selection: BoardAndPortSelection) {
this.boardAndPort = selection;
this.fireChanged(this.boardAndPort);
}
}

View File

@@ -1,113 +0,0 @@
import { AbstractDialog, DialogProps, Widget, Panel, DialogError } from '@theia/core/lib/browser';
import { injectable, inject } from 'inversify';
import { SelectBoardDialogWidget, BoardAndPortSelection } from './select-board-dialog-widget';
import { Message } from '@phosphor/messaging';
import { Disposable } from '@theia/core';
import { Board, BoardsService, AttachedSerialBoard } from '../../common/protocol/boards-service';
@injectable()
export class SelectBoardDialogProps extends DialogProps {
}
@injectable()
export class SelectBoardDialog extends AbstractDialog<BoardAndPortSelection> {
protected readonly dialogPanel: Panel;
protected attachedBoards: Board[];
constructor(
@inject(SelectBoardDialogProps) protected readonly props: SelectBoardDialogProps,
@inject(SelectBoardDialogWidget) protected readonly widget: SelectBoardDialogWidget,
@inject(BoardsService) protected readonly boardService: BoardsService
) {
super({ title: props.title });
this.dialogPanel = new Panel();
this.dialogPanel.addWidget(this.widget);
this.contentNode.classList.add('select-board-dialog');
this.toDispose.push(this.widget.onChanged(() => this.update()));
this.toDispose.push(this.dialogPanel);
this.attachedBoards = [];
this.init();
this.appendCloseButton('CANCEL');
this.appendAcceptButton('OK');
}
protected init() {
const boards = this.boardService.getAttachedBoards();
boards.then(b => this.attachedBoards = b.boards);
this.widget.setAttachedBoards(boards);
}
protected onAfterAttach(msg: Message): void {
Widget.attach(this.dialogPanel, this.contentNode);
this.toDisposeOnDetach.push(Disposable.create(() => {
Widget.detach(this.dialogPanel);
}))
super.onAfterAttach(msg);
this.update();
}
protected onUpdateRequest(msg: Message) {
super.onUpdateRequest(msg);
this.widget.update();
}
protected onActivateRequest(msg: Message): void {
this.widget.activate();
}
protected handleEnter(event: KeyboardEvent): boolean | void {
if (event.target instanceof HTMLTextAreaElement) {
return false;
}
}
protected isValid(value: BoardAndPortSelection): DialogError {
if (!value.board) {
if (value.port) {
return 'Please pick the Board connected to the Port you have selected';
}
return false;
}
return '';
}
get value(): BoardAndPortSelection {
const boardAndPortSelection = this.widget.boardAndPort;
if (this.attachedBoards.length) {
boardAndPortSelection.board = this.attachedBoards.find(b => {
const isAttachedBoard = !!boardAndPortSelection.board &&
b.name === boardAndPortSelection.board.name &&
b.fqbn === boardAndPortSelection.board.fqbn;
if (boardAndPortSelection.port) {
return isAttachedBoard &&
AttachedSerialBoard.is(b) &&
b.port === boardAndPortSelection.port;
} else {
return isAttachedBoard;
}
})
|| boardAndPortSelection.board;
}
return boardAndPortSelection;
}
close(): void {
this.widget.reset();
super.close();
}
onAfterDetach(msg: Message) {
this.widget.reset();
super.onAfterDetach(msg);
}
}

View File

@@ -1,78 +0,0 @@
import * as React from 'react';
import { WindowService } from '@theia/core/lib/browser/window/window-service';
import { ArduinoComponent } from '../../../common/protocol/arduino-component';
export class ComponentListItem extends React.Component<ComponentListItem.Props> {
protected onClick = (event: React.SyntheticEvent<HTMLAnchorElement, Event>) => {
const { target } = event.nativeEvent;
if (target instanceof HTMLAnchorElement) {
this.props.windowService.openNewWindow(target.href);
event.nativeEvent.preventDefault();
}
}
protected async install(item: ArduinoComponent): Promise<void> {
await this.props.install(item);
}
render(): React.ReactNode {
const { item } = this.props;
const style = ComponentListItem.Styles;
const name = <span className={style.NAME_CLASS}>{item.name}</span>;
const author = <span className={style.AUTHOR_CLASS}>{item.author}</span>;
const installedVersion = !!item.installedVersion && <div className={style.VERSION_INFO_CLASS}>
<span className={style.VERSION_CLASS}>Version {item.installedVersion}</span>
<span className={style.INSTALLED_CLASS}>INSTALLED</span>
</div>;
const summary = <div className={style.SUMMARY_CLASS}>{item.summary}</div>;
const moreInfo = !!item.moreInfoLink && <a href={item.moreInfoLink} onClick={this.onClick}>More info</a>;
const install = this.props.install && item.installable && !item.installedVersion &&
<button className={style.INSTALL_BTN_CLASS} onClick={this.install.bind(this, item)}>INSTALL</button>;
return <div className={[style.LIST_ITEM_CLASS, style.NO_SELECT_CLASS].join(' ')}>
<div className={style.HEADER_CLASS}>
<span>{name} by {author}</span>
{installedVersion}
</div>
<div className={style.CONTENT_CLASS}>
{summary}
</div>
<div className={style.FOOTER_CLASS}>
{moreInfo}
{install}
</div>
</div>;
}
}
export namespace ComponentListItem {
export interface Props {
readonly item: ArduinoComponent;
readonly windowService: WindowService;
readonly install: (comp: ArduinoComponent) => Promise<void>;
}
export namespace Styles {
export const LIST_ITEM_CLASS = 'component-list-item';
export const HEADER_CLASS = 'header';
export const VERSION_INFO_CLASS = 'version-info';
export const CONTENT_CLASS = 'content';
export const FOOTER_CLASS = 'footer';
export const INSTALLED_CLASS = 'installed';
export const NO_SELECT_CLASS = 'noselect';
export const NAME_CLASS = 'name';
export const AUTHOR_CLASS = 'author';
export const VERSION_CLASS = 'version';
export const SUMMARY_CLASS = 'summary';
export const DESCRIPTION_CLASS = 'description';
export const INSTALL_BTN_CLASS = 'install';
}
}

View File

@@ -1,39 +0,0 @@
import * as React from 'react';
import { WindowService } from '@theia/core/lib/browser/window/window-service';
import { ComponentListItem } from './component-list-item';
import { ArduinoComponent } from '../../../common/protocol/arduino-component';
export class ComponentList extends React.Component<ComponentList.Props> {
protected container?: HTMLElement;
render(): React.ReactNode {
return <div
className={'items-container'}
ref={element => this.container = element || undefined}>
{this.props.items.map(item => this.createItem(item))}
</div>;
}
componentDidMount(): void {
if (this.container && this.props.resolveContainer) {
this.props.resolveContainer(this.container);
}
}
protected createItem(item: ArduinoComponent): React.ReactNode {
return <ComponentListItem key={item.name} item={item} windowService={this.props.windowService} install={this.props.install} />
}
}
export namespace ComponentList {
export interface Props {
readonly items: ArduinoComponent[];
readonly windowService: WindowService;
readonly install: (comp: ArduinoComponent) => Promise<void>;
readonly resolveContainer?: (element: HTMLElement) => void;
}
}

View File

@@ -1,104 +0,0 @@
import * as React from 'react';
import { WindowService } from '@theia/core/lib/browser/window/window-service';
import { SearchBar } from './search-bar';
import { ComponentList } from './component-list';
import { LibraryService } from '../../../common/protocol/library-service';
import { ArduinoComponent } from '../../../common/protocol/arduino-component';
import { InstallationProgressDialog } from '../installation-progress-dialog';
export class FilterableListContainer extends React.Component<FilterableListContainer.Props, FilterableListContainer.State> {
constructor(props: Readonly<FilterableListContainer.Props>) {
super(props);
this.state = {
filterText: '',
items: []
};
this.handleFilterTextChange = this.handleFilterTextChange.bind(this);
}
componentWillMount(): void {
this.handleFilterTextChange('');
}
render(): React.ReactNode {
return <div className={'filterable-list-container'}>
{this.renderSearchFilter()}
{this.renderSearchBar()}
{this.renderComponentList()}
</div>
}
protected renderSearchFilter(): React.ReactNode {
return undefined;
}
protected renderSearchBar(): React.ReactNode {
return <SearchBar
resolveFocus={this.props.resolveFocus}
filterText={this.state.filterText}
onFilterTextChanged={this.handleFilterTextChange}
/>
}
protected renderComponentList(): React.ReactNode {
return <ComponentList
items={this.state.items}
install={this.install.bind(this)}
windowService={this.props.windowService}
resolveContainer={this.props.resolveContainer}
/>
}
private handleFilterTextChange(filterText: string): void {
const { props } = this.state;
this.props.service.search({ query: filterText, props }).then(result => {
const { items } = result;
this.setState({
filterText,
items: this.sort(items)
});
});
}
protected sort(items: ArduinoComponent[]): ArduinoComponent[] {
return items.sort((left, right) => left.name.localeCompare(right.name));
}
protected async install(comp: ArduinoComponent): Promise<void> {
const dialog = new InstallationProgressDialog(comp.name);
dialog.open();
try {
await this.props.service.install(comp);
const { props } = this.state;
const { items } = await this.props.service.search({ query: this.state.filterText, props });
this.setState({ items: this.sort(items) });
} finally {
dialog.close();
}
}
}
export namespace FilterableListContainer {
export interface Props {
readonly service: ComponentSource;
readonly windowService: WindowService;
readonly resolveContainer?: (element: HTMLElement) => void;
readonly resolveFocus?: (element: HTMLElement | undefined) => void;
}
export interface State {
filterText: string;
items: ArduinoComponent[];
props?: LibraryService.Search.Props;
}
export interface ComponentSource {
search(req: { query: string, props?: LibraryService.Search.Props }): Promise<{ items: ArduinoComponent[] }>
install(board: ArduinoComponent): Promise<void>;
}
}

View File

@@ -1,148 +0,0 @@
import * as React from 'react';
import { BoardsService, Board } from '../../common/protocol/boards-service';
// import { SelectBoardDialog } from './select-board-dialog';
import { QuickPickService } from '@theia/core/lib/common/quick-pick-service';
import { BoardsNotificationService } from '../boards-notification-service';
import { ARDUINO_TOOLBAR_ITEM_CLASS } from '../toolbar/arduino-toolbar';
export class ConnectedBoards extends React.Component<ConnectedBoards.Props, ConnectedBoards.State> {
static TOOLBAR_ID: 'connected-boards-toolbar';
constructor(props: ConnectedBoards.Props) {
super(props);
this.state = { boardsLoading: false };
props.boardsNotificationService.on('boards-installed', () => this.onBoardsInstalled());
}
render(): React.ReactNode {
let content = [];
if (!!this.state.boards && this.state.boards.length > 0) {
content = this.state.boards.map((b, i) => <option value={i} key={i}>{b.name}</option>);
} else {
let label;
if (this.state.boardsLoading) {
label = "Loading ...";
} else {
label = "No board attached";
}
content = [ <option key="loading" value="0">{label}</option> ];
}
return <div key='arduino-connected-boards' className={`${ARDUINO_TOOLBAR_ITEM_CLASS} item ${ConnectedBoards.Styles.CONNECTED_BOARDS_CLASS}`}>
<select key='arduino-connected-boards-select' disabled={!this.state.boards}
onChange={this.onBoardSelect.bind(this)}
value={this.state.selection}>
<optgroup key='arduino-connected-boards-select-opt-group' label="Attached boards">
{ content }
</optgroup>
<optgroup label="_________" key='arduino-connected-boards-select-opt-group2'>
{ !!this.state.otherBoard && <option value="selected-other" key="selected-other">{this.state.otherBoard.name} (not attached)</option> }
<option value="select-other" key="select-other">Select other Board</option>
</optgroup>
</select>
</div>;
}
componentDidMount(): void {
this.reloadBoards();
}
protected onBoardsInstalled() {
if (!!this.findUnknownBoards()) {
this.reloadBoards();
}
}
protected findUnknownBoards(): Board[] {
if (!this.state || !this.state.boards) {
return [];
}
return this.state.boards.filter(b => !b.fqbn || b.name === "unknown");
}
protected async reloadBoards() {
const prevSelection = this.state.selection;
this.setState({ boardsLoading: true, boards: undefined, selection: "loading" });
const { boards } = await this.props.boardsService.getAttachedBoards()
this.setState({ boards, boardsLoading: false, selection: prevSelection });
if (boards) {
this.setState({ selection: "0" });
await this.props.boardsService.selectBoard(boards[0]);
const unknownBoards = this.findUnknownBoards();
if (unknownBoards && unknownBoards.length > 0) {
this.props.onUnknownBoard(unknownBoards[0]);
}
}
}
protected async onBoardSelect(evt: React.ChangeEvent<HTMLSelectElement>) {
const selection = evt.target.value;
if (selection === "select-other" || selection === "selected-other") {
let selectedBoard = this.state.otherBoard;
if (selection === "select-other" || !selectedBoard) {
selectedBoard = await this.selectedInstalledBoard();
}
if (!selectedBoard) {
return;
}
await this.props.boardsService.selectBoard(selectedBoard);
this.setState({otherBoard: selectedBoard, selection: "selected-other"});
return;
}
const selectedBoard = (this.state.boards || [])[parseInt(selection, 10)];
if (!selectedBoard) {
return;
}
await this.props.boardsService.selectBoard(selectedBoard);
this.setState({selection});
}
protected async selectedInstalledBoard(): Promise<Board | undefined> {
const {items} = await this.props.boardsService.search({});
const idx = new Map<string, Board>();
items.filter(pkg => !!pkg.installedVersion).forEach(pkg => pkg.boards.forEach(brd => idx.set(`${brd.name}`, brd) ));
if (idx.size === 0) {
this.props.onNoBoardsInstalled();
return;
}
const selection = await this.props.quickPickService.show(Array.from(idx.keys()));
if (!selection) {
return;
}
return idx.get(selection);
}
}
export namespace ConnectedBoards {
export interface Props {
readonly boardsService: BoardsService;
readonly boardsNotificationService: BoardsNotificationService;
readonly quickPickService: QuickPickService;
readonly onNoBoardsInstalled: () => void;
readonly onUnknownBoard: (board: Board) => void;
}
export interface State {
boardsLoading: boolean;
boards?: Board[];
otherBoard?: Board;
selection?: string;
}
export namespace Styles {
export const CONNECTED_BOARDS_CLASS = 'connected-boards';
}
}

View File

@@ -1,12 +0,0 @@
import { AbstractDialog } from "@theia/core/lib/browser";
export class InstallationProgressDialog extends AbstractDialog<string> {
readonly value: "does-not-matter";
constructor(componentName: string) {
super({ title: 'Installation in progress' });
this.contentNode.textContent = `Installing ${componentName}. Please wait.`;
}
}

View File

@@ -0,0 +1,105 @@
import { inject, injectable } from 'inversify';
import * as moment from 'moment';
import { remote } from 'electron';
import { isOSX, isWindows } from '@theia/core/lib/common/os';
import { ClipboardService } from '@theia/core/lib/browser/clipboard-service';
import { FrontendApplicationConfigProvider } from '@theia/core/lib/browser/frontend-application-config-provider';
import { Contribution, Command, MenuModelRegistry, CommandRegistry } from './contribution';
import { ArduinoMenus } from '../menu/arduino-menus';
import { ConfigService } from '../../common/protocol';
@injectable()
export class About extends Contribution {
@inject(ClipboardService)
protected readonly clipboardService: ClipboardService;
@inject(ConfigService)
protected readonly configService: ConfigService;
registerCommands(registry: CommandRegistry): void {
registry.registerCommand(About.Commands.ABOUT_APP, {
execute: () => this.showAbout()
});
}
registerMenus(registry: MenuModelRegistry): void {
registry.registerMenuAction(ArduinoMenus.HELP__ABOUT_GROUP, {
commandId: About.Commands.ABOUT_APP.id,
label: `About ${this.applicationName}`,
order: '0'
});
}
async showAbout(): Promise<void> {
const { version, commit, status: cliStatus } = await this.configService.getVersion();
const buildDate = this.buildDate;
const detail = (showAll: boolean) => `Version: ${remote.app.getVersion()}
Date: ${buildDate ? buildDate : 'dev build'}${buildDate && showAll ? ` (${this.ago(buildDate)})` : ''}
CLI Version: ${version}${cliStatus ? ` ${cliStatus}` : ''} [${commit}]
${showAll ? `Copyright © ${new Date().getFullYear()} Arduino SA` : ''}
`;
const ok = 'OK';
const copy = 'Copy';
const buttons = !isWindows && !isOSX ? [copy, ok] : [ok, copy];
const { response } = await remote.dialog.showMessageBox(remote.getCurrentWindow(), {
message: `${this.applicationName}`,
title: `${this.applicationName}`,
type: 'info',
detail: detail(true),
buttons,
noLink: true,
defaultId: buttons.indexOf(ok),
cancelId: buttons.indexOf(ok)
});
if (buttons[response] === copy) {
await this.clipboardService.writeText(detail(false).trim());
}
}
protected get applicationName(): string {
return FrontendApplicationConfigProvider.get().applicationName;
}
protected get buildDate(): string | undefined {
return FrontendApplicationConfigProvider.get().buildDate;
}
protected ago(isoTime: string): string {
const now = moment(Date.now());
const other = moment(isoTime);
let result = now.diff(other, 'minute');
if (result < 60) {
return result === 1 ? `${result} minute ago` : `${result} minute ago`;
}
result = now.diff(other, 'hour');
if (result < 25) {
return result === 1 ? `${result} hour ago` : `${result} hours ago`;
}
result = now.diff(other, 'day');
if (result < 8) {
return result === 1 ? `${result} day ago` : `${result} days ago`;
}
result = now.diff(other, 'week');
if (result < 5) {
return result === 1 ? `${result} week ago` : `${result} weeks ago`;
}
result = now.diff(other, 'month');
if (result < 13) {
return result === 1 ? `${result} month ago` : `${result} months ago`;
}
result = now.diff(other, 'year');
return result === 1 ? `${result} year ago` : `${result} years ago`;
}
}
export namespace About {
export namespace Commands {
export const ABOUT_APP: Command = {
id: 'arduino-about'
};
}
}

View File

@@ -0,0 +1,68 @@
import { inject, injectable } from 'inversify';
import { remote } from 'electron';
import { ArduinoMenus } from '../menu/arduino-menus';
import { SketchContribution, Command, CommandRegistry, MenuModelRegistry, URI } from './contribution';
import { FileDialogService } from '@theia/filesystem/lib/browser';
@injectable()
export class AddFile extends SketchContribution {
@inject(FileDialogService)
protected readonly fileDialogService: FileDialogService;
registerCommands(registry: CommandRegistry): void {
registry.registerCommand(AddFile.Commands.ADD_FILE, {
execute: () => this.addFile()
});
}
registerMenus(registry: MenuModelRegistry): void {
registry.registerMenuAction(ArduinoMenus.SKETCH__UTILS_GROUP, {
commandId: AddFile.Commands.ADD_FILE.id,
label: 'Add File...',
order: '2'
});
}
protected async addFile(): Promise<void> {
const sketch = await this.sketchServiceClient.currentSketch();
if (!sketch) {
return;
}
const toAddUri = await this.fileDialogService.showOpenDialog({
title: 'Add File',
canSelectFiles: true,
canSelectFolders: false,
canSelectMany: false
});
if (!toAddUri) {
return;
}
const sketchUri = new URI(sketch.uri);
const filename = toAddUri.path.base;
const targetUri = sketchUri.resolve('data').resolve(filename);
const exists = await this.fileService.exists(targetUri);
if (exists) {
const { response } = await remote.dialog.showMessageBox({
type: 'question',
title: 'Replace',
buttons: ['Cancel', 'OK'],
message: `Replace the existing version of ${filename}?`
});
if (response === 0) { // Cancel
return;
}
}
await this.fileService.copy(toAddUri, targetUri, { overwrite: true });
this.messageService.info('One file added to the sketch.', { timeout: 2000 });
}
}
export namespace AddFile {
export namespace Commands {
export const ADD_FILE: Command = {
id: 'arduino-add-file'
};
}
}

View File

@@ -0,0 +1,55 @@
import { injectable } from 'inversify';
import { remote } from 'electron';
import * as dateFormat from 'dateformat';
import URI from '@theia/core/lib/common/uri';
import { ArduinoMenus } from '../menu/arduino-menus';
import { SketchContribution, Command, CommandRegistry, MenuModelRegistry } from './contribution';
@injectable()
export class ArchiveSketch extends SketchContribution {
registerCommands(registry: CommandRegistry): void {
registry.registerCommand(ArchiveSketch.Commands.ARCHIVE_SKETCH, {
execute: () => this.archiveSketch()
});
}
registerMenus(registry: MenuModelRegistry): void {
registry.registerMenuAction(ArduinoMenus.TOOLS__MAIN_GROUP, {
commandId: ArchiveSketch.Commands.ARCHIVE_SKETCH.id,
label: 'Archive Sketch',
order: '1'
});
}
protected async archiveSketch(): Promise<void> {
const [sketch, config] = await Promise.all([
this.sketchServiceClient.currentSketch(),
this.configService.getConfiguration()
]);
if (!sketch) {
return;
}
const archiveBasename = `${sketch.name}-${dateFormat(new Date(), 'yymmdd')}a.zip`;
const defaultPath = await this.fileService.fsPath(new URI(config.sketchDirUri).resolve(archiveBasename));
const { filePath, canceled } = await remote.dialog.showSaveDialog({ title: 'Save sketch folder as...', defaultPath });
if (!filePath || canceled) {
return;
}
const destinationUri = await this.fileSystemExt.getUri(filePath);
if (!destinationUri) {
return;
}
await this.sketchService.archive(sketch, destinationUri.toString());
this.messageService.info(`Created archive '${archiveBasename}'.`, { timeout: 2000 });
}
}
export namespace ArchiveSketch {
export namespace Commands {
export const ARCHIVE_SKETCH: Command = {
id: 'arduino-archive-sketch'
};
}
}

View File

@@ -0,0 +1,222 @@
import { inject, injectable } from 'inversify';
import { remote } from 'electron';
import { MenuModelRegistry } from '@theia/core/lib/common/menu';
import { DisposableCollection, Disposable } from '@theia/core/lib/common/disposable';
import { firstToUpperCase } from '../../common/utils';
import { BoardsConfig } from '../boards/boards-config';
import { MainMenuManager } from '../../common/main-menu-manager';
import { BoardsListWidget } from '../boards/boards-list-widget';
import { NotificationCenter } from '../notification-center';
import { BoardsServiceProvider } from '../boards/boards-service-provider';
import { ArduinoMenus, PlaceholderMenuNode, unregisterSubmenu } from '../menu/arduino-menus';
import { BoardsService, InstalledBoardWithPackage, AvailablePorts, Port } from '../../common/protocol';
import { SketchContribution, Command, CommandRegistry } from './contribution';
@injectable()
export class BoardSelection extends SketchContribution {
@inject(CommandRegistry)
protected readonly commandRegistry: CommandRegistry;
@inject(MainMenuManager)
protected readonly mainMenuManager: MainMenuManager;
@inject(MenuModelRegistry)
protected readonly menuModelRegistry: MenuModelRegistry;
@inject(NotificationCenter)
protected readonly notificationCenter: NotificationCenter;
@inject(BoardsService)
protected readonly boardsService: BoardsService;
@inject(BoardsServiceProvider)
protected readonly boardsServiceProvider: BoardsServiceProvider;
protected readonly toDisposeBeforeMenuRebuild = new DisposableCollection();
registerCommands(registry: CommandRegistry): void {
registry.registerCommand(BoardSelection.Commands.GET_BOARD_INFO, {
execute: async () => {
const { selectedBoard, selectedPort } = this.boardsServiceProvider.boardsConfig;
if (!selectedBoard) {
this.messageService.info('Please select a board to obtain board info.');
return;
}
if (!selectedBoard.fqbn) {
this.messageService.info(`The platform for the selected '${selectedBoard.name}' board is not installed.`);
return;
}
if (!selectedPort) {
this.messageService.info('Please select a port to obtain board info.');
return;
}
const boardDetails = await this.boardsService.getBoardDetails({ fqbn: selectedBoard.fqbn });
if (boardDetails) {
const { VID, PID } = boardDetails;
const detail = `BN: ${selectedBoard.name}
VID: ${VID}
PID: ${PID}`;
await remote.dialog.showMessageBox(remote.getCurrentWindow(), {
message: 'Board Info',
title: 'Board Info',
type: 'info',
detail,
buttons: ['OK']
});
}
}
});
}
onStart(): void {
this.updateMenus();
this.notificationCenter.onPlatformInstalled(this.updateMenus.bind(this));
this.notificationCenter.onPlatformUninstalled(this.updateMenus.bind(this));
this.boardsServiceProvider.onBoardsConfigChanged(this.updateMenus.bind(this));
this.boardsServiceProvider.onAvailableBoardsChanged(this.updateMenus.bind(this));
}
protected async updateMenus(): Promise<void> {
const [installedBoards, availablePorts, config] = await Promise.all([
this.installedBoards(),
this.boardsService.getState(),
this.boardsServiceProvider.boardsConfig
]);
this.rebuildMenus(installedBoards, availablePorts, config);
}
protected rebuildMenus(installedBoards: InstalledBoardWithPackage[], availablePorts: AvailablePorts, config: BoardsConfig.Config): void {
this.toDisposeBeforeMenuRebuild.dispose();
// Boards submenu
const boardsSubmenuPath = [...ArduinoMenus.TOOLS__BOARD_SELECTION_GROUP, '1_boards'];
const boardsSubmenuLabel = config.selectedBoard?.name;
// Note: The submenu order starts from `100` because `Auto Format`, `Serial Monitor`, etc starts from `0` index.
// The board specific items, and the rest, have order with `z`. We needed something between `0` and `z` with natural-order.
this.menuModelRegistry.registerSubmenu(boardsSubmenuPath, `Board${!!boardsSubmenuLabel ? `: "${boardsSubmenuLabel}"` : ''}`, { order: '100' });
this.toDisposeBeforeMenuRebuild.push(Disposable.create(() => unregisterSubmenu(boardsSubmenuPath, this.menuModelRegistry)));
// Ports submenu
const portsSubmenuPath = [...ArduinoMenus.TOOLS__BOARD_SELECTION_GROUP, '2_ports'];
const portsSubmenuLabel = config.selectedPort?.address;
this.menuModelRegistry.registerSubmenu(portsSubmenuPath, `Port${!!portsSubmenuLabel ? `: "${portsSubmenuLabel}"` : ''}`, { order: '101' });
this.toDisposeBeforeMenuRebuild.push(Disposable.create(() => unregisterSubmenu(portsSubmenuPath, this.menuModelRegistry)));
const getBoardInfo = { commandId: BoardSelection.Commands.GET_BOARD_INFO.id, label: 'Get Board Info', order: '103' };
this.menuModelRegistry.registerMenuAction(ArduinoMenus.TOOLS__BOARD_SELECTION_GROUP, getBoardInfo);
this.toDisposeBeforeMenuRebuild.push(Disposable.create(() => this.menuModelRegistry.unregisterMenuAction(getBoardInfo)));
const boardsManagerGroup = [...boardsSubmenuPath, '0_manager'];
const boardsPackagesGroup = [...boardsSubmenuPath, '1_packages'];
this.menuModelRegistry.registerMenuAction(boardsManagerGroup, {
commandId: `${BoardsListWidget.WIDGET_ID}:toggle`,
label: 'Boards Manager...'
});
// Installed boards
for (const board of installedBoards) {
const { packageId, packageName, fqbn, name } = board;
// Platform submenu
const platformMenuPath = [...boardsPackagesGroup, packageId];
// Note: Registering the same submenu twice is a noop. No need to group the boards per platform.
this.menuModelRegistry.registerSubmenu(platformMenuPath, packageName);
const id = `arduino-select-board--${fqbn}`;
const command = { id };
const handler = {
execute: () => {
if (fqbn !== this.boardsServiceProvider.boardsConfig.selectedBoard?.fqbn) {
this.boardsServiceProvider.boardsConfig = {
selectedBoard: {
name,
fqbn,
port: this.boardsServiceProvider.boardsConfig.selectedBoard?.port // TODO: verify!
},
selectedPort: this.boardsServiceProvider.boardsConfig.selectedPort
}
}
},
isToggled: () => fqbn === this.boardsServiceProvider.boardsConfig.selectedBoard?.fqbn
};
// Board menu
const menuAction = { commandId: id, label: name };
this.commandRegistry.registerCommand(command, handler);
this.toDisposeBeforeMenuRebuild.push(Disposable.create(() => this.commandRegistry.unregisterCommand(command)));
this.menuModelRegistry.registerMenuAction(platformMenuPath, menuAction);
// Note: we do not dispose the menu actions individually. Calling `unregisterSubmenu` on the parent will wipe the children menu nodes recursively.
}
// Installed ports
const registerPorts = (ports: AvailablePorts) => {
const addresses = Object.keys(ports);
if (!addresses.length) {
return;
}
// Register placeholder for protocol
const [port] = ports[addresses[0]];
const protocol = port.protocol;
const menuPath = [...portsSubmenuPath, protocol];
const placeholder = new PlaceholderMenuNode(menuPath, `${firstToUpperCase(port.protocol)} ports`);
this.menuModelRegistry.registerMenuNode(menuPath, placeholder);
this.toDisposeBeforeMenuRebuild.push(Disposable.create(() => this.menuModelRegistry.unregisterMenuNode(placeholder.id)));
for (const address of addresses) {
if (!!ports[address]) {
const [port, boards] = ports[address];
if (!boards.length) {
boards.push({
name: ''
});
}
for (const { name, fqbn } of boards) {
const id = `arduino-select-port--${address}${fqbn ? `--${fqbn}` : ''}`;
const command = { id };
const handler = {
execute: () => {
if (!Port.equals(port, this.boardsServiceProvider.boardsConfig.selectedPort)) {
this.boardsServiceProvider.boardsConfig = {
selectedBoard: this.boardsServiceProvider.boardsConfig.selectedBoard,
selectedPort: port
}
}
},
isToggled: () => Port.equals(port, this.boardsServiceProvider.boardsConfig.selectedPort)
};
const label = `${address}${name ? ` (${name})` : ''}`;
const menuAction = {
commandId: id,
label,
order: `1${label}` // `1` comes after the placeholder which has order `0`
};
this.commandRegistry.registerCommand(command, handler);
this.toDisposeBeforeMenuRebuild.push(Disposable.create(() => this.commandRegistry.unregisterCommand(command)));
this.menuModelRegistry.registerMenuAction(menuPath, menuAction);
}
}
}
}
const { serial, network, unknown } = AvailablePorts.groupByProtocol(availablePorts);
registerPorts(serial);
registerPorts(network);
registerPorts(unknown);
this.mainMenuManager.update();
}
protected async installedBoards(): Promise<InstalledBoardWithPackage[]> {
const allBoards = await this.boardsService.allBoards({});
return allBoards.filter(InstalledBoardWithPackage.is);
}
}
export namespace BoardSelection {
export namespace Commands {
export const GET_BOARD_INFO: Command = { id: 'arduino-get-board-info' };
}
}

View File

@@ -0,0 +1,82 @@
import { inject, injectable } from 'inversify';
import { OutputChannelManager } from '@theia/output/lib/common/output-channel';
import { CoreService } from '../../common/protocol';
import { ArduinoMenus } from '../menu/arduino-menus';
import { BoardsDataStore } from '../boards/boards-data-store';
import { MonitorConnection } from '../monitor/monitor-connection';
import { BoardsServiceProvider } from '../boards/boards-service-provider';
import { SketchContribution, Command, CommandRegistry, MenuModelRegistry } from './contribution';
@injectable()
export class BurnBootloader extends SketchContribution {
@inject(CoreService)
protected readonly coreService: CoreService;
@inject(MonitorConnection)
protected readonly monitorConnection: MonitorConnection;
@inject(BoardsDataStore)
protected readonly boardsDataStore: BoardsDataStore;
@inject(BoardsServiceProvider)
protected readonly boardsServiceClientImpl: BoardsServiceProvider;
@inject(OutputChannelManager)
protected readonly outputChannelManager: OutputChannelManager;
registerCommands(registry: CommandRegistry): void {
registry.registerCommand(BurnBootloader.Commands.BURN_BOOTLOADER, {
execute: () => this.burnBootloader()
});
}
registerMenus(registry: MenuModelRegistry): void {
registry.registerMenuAction(ArduinoMenus.TOOLS__BOARD_SETTINGS_GROUP, {
commandId: BurnBootloader.Commands.BURN_BOOTLOADER.id,
label: 'Burn Bootloader',
order: 'z99'
});
}
async burnBootloader(): Promise<void> {
const monitorConfig = this.monitorConnection.monitorConfig;
if (monitorConfig) {
await this.monitorConnection.disconnect();
}
try {
const { boardsConfig } = this.boardsServiceClientImpl;
const port = boardsConfig.selectedPort?.address;
const [fqbn, { selectedProgrammer: programmer }, verify, verbose] = await Promise.all([
this.boardsDataStore.appendConfigToFqbn(boardsConfig.selectedBoard?.fqbn),
this.boardsDataStore.getData(boardsConfig.selectedBoard?.fqbn),
this.preferences.get('arduino.upload.verify'),
this.preferences.get('arduino.upload.verbose')
]);
this.outputChannelManager.getChannel('Arduino').clear();
await this.coreService.burnBootloader({
fqbn,
programmer,
port,
verify,
verbose
});
this.messageService.info('Done burning bootloader.', { timeout: 1000 });
} catch (e) {
this.messageService.error(e.toString());
} finally {
if (monitorConfig) {
await this.monitorConnection.connect(monitorConfig);
}
}
}
}
export namespace BurnBootloader {
export namespace Commands {
export const BURN_BOOTLOADER: Command = {
id: 'arduino-burn-bootloader'
};
}
}

View File

@@ -0,0 +1,119 @@
import { inject, injectable } from 'inversify';
import { toArray } from '@phosphor/algorithm';
import { remote } from 'electron';
import { MonacoEditor } from '@theia/monaco/lib/browser/monaco-editor';
import { EditorManager } from '@theia/editor/lib/browser/editor-manager';
import { ApplicationShell } from '@theia/core/lib/browser/shell/application-shell';
import { FrontendApplication } from '@theia/core/lib/browser/frontend-application';
import { ArduinoMenus } from '../menu/arduino-menus';
import { SaveAsSketch } from './save-as-sketch';
import { SketchContribution, Command, CommandRegistry, MenuModelRegistry, KeybindingRegistry, URI } from './contribution';
/**
* Closes the `current` closeable editor, or any closeable current widget from the main area, or the current sketch window.
*/
@injectable()
export class Close extends SketchContribution {
@inject(EditorManager)
protected readonly editorManager: EditorManager;
protected shell: ApplicationShell;
onStart(app: FrontendApplication): void {
this.shell = app.shell;
}
registerCommands(registry: CommandRegistry): void {
registry.registerCommand(Close.Commands.CLOSE, {
execute: async () => {
// Close current editor if closeable.
const { currentEditor } = this.editorManager;
if (currentEditor && currentEditor.title.closable) {
currentEditor.close();
return;
}
// Close current widget from the main area if possible.
const { currentWidget } = this.shell;
if (currentWidget) {
const currentWidgetInMain = toArray(this.shell.mainPanel.widgets()).find(widget => widget === currentWidget);
if (currentWidgetInMain && currentWidgetInMain.title.closable) {
return currentWidgetInMain.close();
}
}
// Close the sketch (window).
const sketch = await this.sketchServiceClient.currentSketch();
if (!sketch) {
return;
}
const isTemp = await this.sketchService.isTemp(sketch);
const uri = await this.sketchServiceClient.currentSketchFile();
if (!uri) {
return;
}
if (isTemp && await this.wasTouched(uri)) {
const { response } = await remote.dialog.showMessageBox({
type: 'question',
buttons: ["Don't Save", 'Cancel', 'Save'],
message: 'Do you want to save changes to this sketch before closing?',
detail: "If you don't save, your changes will be lost."
});
if (response === 1) { // Cancel
return;
}
if (response === 2) { // Save
const saved = await this.commandService.executeCommand(SaveAsSketch.Commands.SAVE_AS_SKETCH.id, { openAfterMove: false, execOnlyIfTemp: true });
if (!saved) { // If it was not saved, do bail the close.
return;
}
}
}
window.close();
}
});
}
registerMenus(registry: MenuModelRegistry): void {
registry.registerMenuAction(ArduinoMenus.FILE__SKETCH_GROUP, {
commandId: Close.Commands.CLOSE.id,
label: 'Close',
order: '5'
});
}
registerKeybindings(registry: KeybindingRegistry): void {
registry.registerKeybinding({
command: Close.Commands.CLOSE.id,
keybinding: 'CtrlCmd+W'
});
}
/**
* If the file was ever touched/modified. We get this based on the `version` of the monaco model.
*/
protected async wasTouched(uri: string): Promise<boolean> {
const editorWidget = await this.editorManager.getByUri(new URI(uri));
if (editorWidget) {
const { editor } = editorWidget;
if (editor instanceof MonacoEditor) {
const versionId = editor.getControl().getModel()?.getVersionId();
if (Number.isInteger(versionId) && versionId! > 1) {
return true;
}
}
}
return false;
}
}
export namespace Close {
export namespace Commands {
export const CLOSE: Command = {
id: 'arduino-close'
};
}
}

View File

@@ -0,0 +1,118 @@
import { inject, injectable, interfaces } from 'inversify';
import URI from '@theia/core/lib/common/uri';
import { ILogger } from '@theia/core/lib/common/logger';
import { Saveable } from '@theia/core/lib/browser/saveable';
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 { EditorManager } from '@theia/editor/lib/browser/editor-manager';
import { MessageService } from '@theia/core/lib/common/message-service';
import { WorkspaceService } from '@theia/workspace/lib/browser/workspace-service';
import { open, OpenerService } from '@theia/core/lib/browser/opener-service';
import { MenuModelRegistry, MenuContribution } from '@theia/core/lib/common/menu';
import { KeybindingRegistry, KeybindingContribution } from '@theia/core/lib/browser/keybinding';
import { TabBarToolbarContribution, TabBarToolbarRegistry } from '@theia/core/lib/browser/shell/tab-bar-toolbar';
import { FrontendApplicationContribution, FrontendApplication } from '@theia/core/lib/browser/frontend-application';
import { Command, CommandRegistry, CommandContribution, CommandService } from '@theia/core/lib/common/command';
import { EditorMode } from '../editor-mode';
import { SettingsService } from '../settings';
import { SketchesServiceClientImpl } from '../../common/protocol/sketches-service-client-impl';
import { SketchesService, ConfigService, FileSystemExt, Sketch } from '../../common/protocol';
import { ArduinoPreferences } from '../arduino-preferences';
export { Command, CommandRegistry, MenuModelRegistry, KeybindingRegistry, TabBarToolbarRegistry, URI, Sketch, open };
@injectable()
export abstract class Contribution implements CommandContribution, MenuContribution, KeybindingContribution, TabBarToolbarContribution, FrontendApplicationContribution {
@inject(ILogger)
protected readonly logger: ILogger;
@inject(MessageService)
protected readonly messageService: MessageService;
@inject(CommandService)
protected readonly commandService: CommandService;
@inject(WorkspaceService)
protected readonly workspaceService: WorkspaceService;
@inject(EditorMode)
protected readonly editorMode: EditorMode;
@inject(LabelProvider)
protected readonly labelProvider: LabelProvider;
@inject(SettingsService)
protected readonly settingsService: SettingsService;
onStart(app: FrontendApplication): MaybePromise<void> {
}
registerCommands(registry: CommandRegistry): void {
}
registerMenus(registry: MenuModelRegistry): void {
}
registerKeybindings(registry: KeybindingRegistry): void {
}
registerToolbarItems(registry: TabBarToolbarRegistry): void {
}
}
@injectable()
export abstract class SketchContribution extends Contribution {
@inject(FileService)
protected readonly fileService: FileService;
@inject(FileSystemExt)
protected readonly fileSystemExt: FileSystemExt;
@inject(ConfigService)
protected readonly configService: ConfigService;
@inject(SketchesService)
protected readonly sketchService: SketchesService;
@inject(OpenerService)
protected readonly openerService: OpenerService;
@inject(SketchesServiceClientImpl)
protected readonly sketchServiceClient: SketchesServiceClientImpl;
@inject(ArduinoPreferences)
protected readonly preferences: ArduinoPreferences;
@inject(EditorManager)
protected readonly editorManager: EditorManager;
protected async sourceOverride(): Promise<Record<string, string>> {
const override: Record<string, string> = {};
const sketch = await this.sketchServiceClient.currentSketch();
if (sketch) {
for (const editor of this.editorManager.all) {
const uri = editor.editor.uri;
if (Saveable.isDirty(editor) && Sketch.isInSketch(uri, sketch)) {
override[uri.toString()] = editor.editor.document.getText();
}
}
}
return override;
}
}
export namespace Contribution {
export function configure<T>(bind: interfaces.Bind, serviceIdentifier: typeof Contribution): void {
bind(serviceIdentifier).toSelf().inSingletonScope();
bind(CommandContribution).toService(serviceIdentifier);
bind(MenuContribution).toService(serviceIdentifier);
bind(KeybindingContribution).toService(serviceIdentifier);
bind(TabBarToolbarContribution).toService(serviceIdentifier);
bind(FrontendApplicationContribution).toService(serviceIdentifier);
}
}

View File

@@ -0,0 +1,134 @@
import { inject, injectable } from 'inversify';
import { Event, Emitter } from '@theia/core/lib/common/event';
import { HostedPluginSupport } from '@theia/plugin-ext/lib/hosted/browser/hosted-plugin';
import { ArduinoToolbar } from '../toolbar/arduino-toolbar';
import { NotificationCenter } from '../notification-center';
import { Board, BoardsService, ExecutableService } from '../../common/protocol';
import { BoardsServiceProvider } from '../boards/boards-service-provider';
import { URI, Command, CommandRegistry, SketchContribution, TabBarToolbarRegistry } from './contribution';
@injectable()
export class Debug extends SketchContribution {
@inject(HostedPluginSupport)
protected hostedPluginSupport: HostedPluginSupport;
@inject(NotificationCenter)
protected readonly notificationCenter: NotificationCenter;
@inject(ExecutableService)
protected readonly executableService: ExecutableService;
@inject(BoardsService)
protected readonly boardService: BoardsService;
@inject(BoardsServiceProvider)
protected readonly boardsServiceProvider: BoardsServiceProvider;
/**
* If `undefined`, debugging is enabled. Otherwise, the reason why it's disabled.
*/
protected _disabledMessages?: string = 'No board selected'; // Initial pessimism.
protected disabledMessageDidChangeEmitter = new Emitter<string | undefined>();
protected onDisabledMessageDidChange = this.disabledMessageDidChangeEmitter.event;
protected get disabledMessage(): string | undefined {
return this._disabledMessages;
}
protected set disabledMessage(message: string | undefined) {
this._disabledMessages = message;
this.disabledMessageDidChangeEmitter.fire(this._disabledMessages);
}
protected readonly debugToolbarItem = {
id: Debug.Commands.START_DEBUGGING.id,
command: Debug.Commands.START_DEBUGGING.id,
tooltip: `${this.disabledMessage ? `Debug - ${this.disabledMessage}` : 'Start Debugging'}`,
priority: 3,
onDidChange: this.onDisabledMessageDidChange as Event<void>
};
onStart(): void {
this.onDisabledMessageDidChange(() => this.debugToolbarItem.tooltip = `${this.disabledMessage ? `Debug - ${this.disabledMessage}` : 'Start Debugging'}`);
const refreshState = async (board: Board | undefined = this.boardsServiceProvider.boardsConfig.selectedBoard) => {
if (!board) {
this.disabledMessage = 'No board selected';
return;
}
const fqbn = board.fqbn;
if (!fqbn) {
this.disabledMessage = `Platform is not installed for '${board.name}'`;
return;
}
const details = await this.boardService.getBoardDetails({ fqbn });
if (!details) {
this.disabledMessage = `Platform is not installed for '${board.name}'`;
return;
}
const { debuggingSupported } = details;
if (!debuggingSupported) {
this.disabledMessage = `Debugging is not supported by '${board.name}'`;
} else {
this.disabledMessage = undefined;
}
}
this.boardsServiceProvider.onBoardsConfigChanged(({ selectedBoard }) => refreshState(selectedBoard));
this.notificationCenter.onPlatformInstalled(() => refreshState());
this.notificationCenter.onPlatformUninstalled(() => refreshState());
refreshState();
}
registerCommands(registry: CommandRegistry): void {
registry.registerCommand(Debug.Commands.START_DEBUGGING, {
execute: () => this.startDebug(),
isVisible: widget => ArduinoToolbar.is(widget) && widget.side === 'left',
isEnabled: () => !this.disabledMessage
});
}
registerToolbarItems(registry: TabBarToolbarRegistry): void {
registry.registerItem(this.debugToolbarItem);
}
protected async startDebug(board: Board | undefined = this.boardsServiceProvider.boardsConfig.selectedBoard): Promise<void> {
if (!board) {
return;
}
const { name, fqbn } = board;
if (!fqbn) {
return;
}
await this.hostedPluginSupport.didStart;
const [sketch, executables] = await Promise.all([
this.sketchServiceClient.currentSketch(),
this.executableService.list()
]);
if (!sketch) {
return;
}
const [cliPath, sketchPath] = await Promise.all([
this.fileService.fsPath(new URI(executables.cliUri)),
this.fileService.fsPath(new URI(sketch.uri))
])
const config = {
cliPath,
board: {
fqbn,
name
},
sketchPath
};
return this.commandService.executeCommand('arduino.debug.start', config);
}
}
export namespace Debug {
export namespace Commands {
export const START_DEBUGGING: Command = {
id: 'arduino-start-debug',
label: 'Start Debugging',
category: 'Arduino'
}
}
}

View File

@@ -0,0 +1,294 @@
import { inject, injectable } from 'inversify';
import { CommonCommands } from '@theia/core/lib/browser/common-frontend-contribution';
import { ClipboardService } from '@theia/core/lib/browser/clipboard-service';
import { PreferenceService } from '@theia/core/lib/browser/preferences/preference-service';
import { MonacoEditorService } from '@theia/monaco/lib/browser/monaco-editor-service';
import { Contribution, Command, MenuModelRegistry, KeybindingRegistry, CommandRegistry } from './contribution';
import { ArduinoMenus } from '../menu/arduino-menus';
// TODO: [macOS]: to remove `Start Dictation...` and `Emoji & Symbol` see this thread: https://github.com/electron/electron/issues/8283#issuecomment-269522072
// Depends on https://github.com/eclipse-theia/theia/pull/7964
@injectable()
export class EditContributions extends Contribution {
@inject(MonacoEditorService)
protected readonly codeEditorService: MonacoEditorService;
@inject(ClipboardService)
protected readonly clipboardService: ClipboardService;
@inject(PreferenceService)
protected readonly preferences: PreferenceService;
registerCommands(registry: CommandRegistry): void {
registry.registerCommand(EditContributions.Commands.GO_TO_LINE, { execute: () => this.run('editor.action.gotoLine') });
registry.registerCommand(EditContributions.Commands.TOGGLE_COMMENT, { execute: () => this.run('editor.action.commentLine') });
registry.registerCommand(EditContributions.Commands.INDENT_LINES, { execute: () => this.run('editor.action.indentLines') });
registry.registerCommand(EditContributions.Commands.OUTDENT_LINES, { execute: () => this.run('editor.action.outdentLines') });
registry.registerCommand(EditContributions.Commands.FIND, { execute: () => this.run('actions.find') });
registry.registerCommand(EditContributions.Commands.FIND_NEXT, { execute: () => this.run('actions.findWithSelection') });
registry.registerCommand(EditContributions.Commands.FIND_PREVIOUS, { execute: () => this.run('editor.action.nextMatchFindAction') });
registry.registerCommand(EditContributions.Commands.USE_FOR_FIND, { execute: () => this.run('editor.action.previousSelectionMatchFindAction') });
registry.registerCommand(EditContributions.Commands.INCREASE_FONT_SIZE, {
execute: async () => {
const settings = await this.settingsService.settings();
if (settings.autoScaleInterface) {
settings.interfaceScale = settings.interfaceScale + 1;
} else {
settings.editorFontSize = settings.editorFontSize + 1;
}
await this.settingsService.update(settings);
await this.settingsService.save();
}
});
registry.registerCommand(EditContributions.Commands.DECREASE_FONT_SIZE, {
execute: async () => {
const settings = await this.settingsService.settings();
if (settings.autoScaleInterface) {
settings.interfaceScale = settings.interfaceScale - 1;
} else {
settings.editorFontSize = settings.editorFontSize - 1;
}
await this.settingsService.update(settings);
await this.settingsService.save();
}
});
/* Tools */registry.registerCommand(EditContributions.Commands.AUTO_FORMAT, { execute: () => this.run('editor.action.formatDocument') });
registry.registerCommand(EditContributions.Commands.COPY_FOR_FORUM, {
execute: async () => {
const value = await this.currentValue();
if (value !== undefined) {
this.clipboardService.writeText(`[code]
${value}
[/code]`)
}
}
});
registry.registerCommand(EditContributions.Commands.COPY_FOR_GITHUB, {
execute: async () => {
const value = await this.currentValue();
if (value !== undefined) {
this.clipboardService.writeText(`\`\`\`cpp
${value}
\`\`\``)
}
}
});
}
registerMenus(registry: MenuModelRegistry): void {
registry.registerMenuAction(ArduinoMenus.EDIT__TEXT_CONTROL_GROUP, {
commandId: CommonCommands.CUT.id,
order: '0'
});
registry.registerMenuAction(ArduinoMenus.EDIT__TEXT_CONTROL_GROUP, {
commandId: CommonCommands.COPY.id,
order: '1'
});
registry.registerMenuAction(ArduinoMenus.EDIT__TEXT_CONTROL_GROUP, {
commandId: EditContributions.Commands.COPY_FOR_FORUM.id,
label: 'Copy for Forum',
order: '2'
});
registry.registerMenuAction(ArduinoMenus.EDIT__TEXT_CONTROL_GROUP, {
commandId: EditContributions.Commands.COPY_FOR_GITHUB.id,
label: 'Copy for GitHub',
order: '3'
});
registry.registerMenuAction(ArduinoMenus.EDIT__TEXT_CONTROL_GROUP, {
commandId: CommonCommands.PASTE.id,
order: '4'
});
registry.registerMenuAction(ArduinoMenus.EDIT__TEXT_CONTROL_GROUP, {
commandId: CommonCommands.SELECT_ALL.id,
order: '5'
});
registry.registerMenuAction(ArduinoMenus.EDIT__TEXT_CONTROL_GROUP, {
commandId: EditContributions.Commands.GO_TO_LINE.id,
label: 'Go to Line...',
order: '6'
});
registry.registerMenuAction(ArduinoMenus.EDIT__CODE_CONTROL_GROUP, {
commandId: EditContributions.Commands.TOGGLE_COMMENT.id,
label: 'Comment/Uncomment',
order: '0'
});
registry.registerMenuAction(ArduinoMenus.EDIT__CODE_CONTROL_GROUP, {
commandId: EditContributions.Commands.INDENT_LINES.id,
label: 'Increase Indent',
order: '1'
});
registry.registerMenuAction(ArduinoMenus.EDIT__CODE_CONTROL_GROUP, {
commandId: EditContributions.Commands.OUTDENT_LINES.id,
label: 'Decrease Indent',
order: '2'
});
registry.registerMenuAction(ArduinoMenus.EDIT__FONT_CONTROL_GROUP, {
commandId: EditContributions.Commands.INCREASE_FONT_SIZE.id,
label: 'Increase Font Size',
order: '0'
});
registry.registerMenuAction(ArduinoMenus.EDIT__FONT_CONTROL_GROUP, {
commandId: EditContributions.Commands.DECREASE_FONT_SIZE.id,
label: 'Decrease Font Size',
order: '1'
});
registry.registerMenuAction(ArduinoMenus.EDIT__FIND_GROUP, {
commandId: EditContributions.Commands.FIND.id,
label: 'Find',
order: '0'
});
registry.registerMenuAction(ArduinoMenus.EDIT__FIND_GROUP, {
commandId: EditContributions.Commands.FIND_NEXT.id,
label: 'Find Next',
order: '1'
});
registry.registerMenuAction(ArduinoMenus.EDIT__FIND_GROUP, {
commandId: EditContributions.Commands.FIND_PREVIOUS.id,
label: 'Find Previous',
order: '2'
});
registry.registerMenuAction(ArduinoMenus.EDIT__FIND_GROUP, {
commandId: EditContributions.Commands.USE_FOR_FIND.id,
label: 'Use Selection for Find', // XXX: The Java IDE uses `Use Selection For Find`.
order: '3'
});
// `Tools`
registry.registerMenuAction(ArduinoMenus.TOOLS__MAIN_GROUP, {
commandId: EditContributions.Commands.AUTO_FORMAT.id,
label: 'Auto Format', // XXX: The Java IDE uses `Use Selection For Find`.
order: '0'
});
}
registerKeybindings(registry: KeybindingRegistry): void {
registry.registerKeybinding({
command: EditContributions.Commands.COPY_FOR_FORUM.id,
keybinding: 'CtrlCmd+Shift+C',
when: 'editorFocus'
});
registry.registerKeybinding({
command: EditContributions.Commands.COPY_FOR_GITHUB.id,
keybinding: 'CtrlCmd+Alt+C',
when: 'editorFocus'
});
registry.registerKeybinding({
command: EditContributions.Commands.GO_TO_LINE.id,
keybinding: 'CtrlCmd+L',
when: 'editorFocus'
});
registry.registerKeybinding({
command: EditContributions.Commands.TOGGLE_COMMENT.id,
keybinding: 'CtrlCmd+/',
when: 'editorFocus'
});
registry.registerKeybinding({
command: EditContributions.Commands.INCREASE_FONT_SIZE.id,
keybinding: 'CtrlCmd+='
});
registry.registerKeybinding({
command: EditContributions.Commands.DECREASE_FONT_SIZE.id,
keybinding: 'CtrlCmd+-'
});
registry.registerKeybinding({
command: EditContributions.Commands.FIND.id,
keybinding: 'CtrlCmd+F'
});
registry.registerKeybinding({
command: EditContributions.Commands.FIND_NEXT.id,
keybinding: 'CtrlCmd+G'
});
registry.registerKeybinding({
command: EditContributions.Commands.FIND_PREVIOUS.id,
keybinding: 'CtrlCmd+Shift+G'
});
registry.registerKeybinding({
command: EditContributions.Commands.USE_FOR_FIND.id,
keybinding: 'CtrlCmd+E'
});
// `Tools`
registry.registerKeybinding({
command: EditContributions.Commands.AUTO_FORMAT.id,
keybinding: 'CtrlCmd+T'
});
}
protected async current(): Promise<monaco.editor.ICodeEditor | undefined> {
return this.codeEditorService.getFocusedCodeEditor() || this.codeEditorService.getActiveCodeEditor();
}
protected async currentValue(): Promise<string | undefined> {
const currentEditor = await this.current();
if (currentEditor) {
const selection = currentEditor.getSelection();
if (!selection || selection.isEmpty()) {
return currentEditor.getValue();
}
return currentEditor.getModel()?.getValueInRange(selection);
}
return undefined;
}
protected async run(commandId: string): Promise<any> {
const editor = await this.current();
if (editor) {
const action = editor.getAction(commandId);
if (action) {
return action.run();
}
}
}
}
export namespace EditContributions {
export namespace Commands {
export const COPY_FOR_FORUM: Command = {
id: 'arduino-copy-for-forum'
};
export const COPY_FOR_GITHUB: Command = {
id: 'arduino-copy-for-github'
};
export const GO_TO_LINE: Command = {
id: 'arduino-go-to-line'
};
export const TOGGLE_COMMENT: Command = {
id: 'arduino-toggle-comment'
};
export const INDENT_LINES: Command = {
id: 'arduino-indent-lines'
};
export const OUTDENT_LINES: Command = {
id: 'arduino-outdent-lines'
};
export const FIND: Command = {
id: 'arduino-find'
};
export const FIND_NEXT: Command = {
id: 'arduino-find-next'
};
export const FIND_PREVIOUS: Command = {
id: 'arduino-find-previous'
};
export const USE_FOR_FIND: Command = {
id: 'arduino-for-find'
};
export const INCREASE_FONT_SIZE: Command = {
id: 'arduino-increase-font-size'
};
export const DECREASE_FONT_SIZE: Command = {
id: 'arduino-decrease-font-size'
};
export const AUTO_FORMAT: Command = {
id: 'arduino-auto-format' // `Auto Format` should belong to `Tool`.
};
}
}

View File

@@ -0,0 +1,169 @@
import * as PQueue from 'p-queue';
import { inject, injectable, postConstruct } from 'inversify';
import { MenuPath, CompositeMenuNode } from '@theia/core/lib/common/menu';
import { Disposable, DisposableCollection } from '@theia/core/lib/common/disposable';
import { OpenSketch } from './open-sketch';
import { ArduinoMenus, PlaceholderMenuNode } from '../menu/arduino-menus';
import { MainMenuManager } from '../../common/main-menu-manager';
import { BoardsServiceProvider } from '../boards/boards-service-provider';
import { ExamplesService, ExampleContainer } from '../../common/protocol/examples-service';
import { SketchContribution, CommandRegistry, MenuModelRegistry } from './contribution';
import { NotificationCenter } from '../notification-center';
import { Board } from '../../common/protocol';
@injectable()
export abstract class Examples extends SketchContribution {
@inject(CommandRegistry)
protected readonly commandRegistry: CommandRegistry;
@inject(MenuModelRegistry)
protected readonly menuRegistry: MenuModelRegistry;
@inject(MainMenuManager)
protected readonly menuManager: MainMenuManager;
@inject(ExamplesService)
protected readonly examplesService: ExamplesService;
@inject(BoardsServiceProvider)
protected readonly boardsServiceClient: BoardsServiceProvider;
protected readonly toDispose = new DisposableCollection();
@postConstruct()
init(): void {
this.boardsServiceClient.onBoardsConfigChanged(({ selectedBoard }) => this.handleBoardChanged(selectedBoard));
}
protected handleBoardChanged(board: Board | undefined): void {
// NOOP
}
registerMenus(registry: MenuModelRegistry): void {
try {
// This is a hack the ensures the desired menu ordering! We cannot use https://github.com/eclipse-theia/theia/pull/8377 due to ATL-222.
const index = ArduinoMenus.FILE__EXAMPLES_SUBMENU.length - 1;
const menuId = ArduinoMenus.FILE__EXAMPLES_SUBMENU[index];
const groupPath = index === 0 ? [] : ArduinoMenus.FILE__EXAMPLES_SUBMENU.slice(0, index);
const parent: CompositeMenuNode = (registry as any).findGroup(groupPath);
const examples = new CompositeMenuNode(menuId, '', { order: '4' });
parent.addNode(examples);
} catch (e) {
console.error(e);
console.warn('Could not patch menu ordering.');
}
// Registering the same submenu multiple times has no side-effect.
// TODO: unregister submenu? https://github.com/eclipse-theia/theia/issues/7300
registry.registerSubmenu(ArduinoMenus.FILE__EXAMPLES_SUBMENU, 'Examples', { order: '4' });
}
registerRecursively(
exampleContainerOrPlaceholder: ExampleContainer | string,
menuPath: MenuPath,
pushToDispose: DisposableCollection = new DisposableCollection()): void {
if (typeof exampleContainerOrPlaceholder === 'string') {
const placeholder = new PlaceholderMenuNode(menuPath, exampleContainerOrPlaceholder);
this.menuRegistry.registerMenuNode(menuPath, placeholder);
pushToDispose.push(Disposable.create(() => this.menuRegistry.unregisterMenuNode(placeholder.id)));
} else {
const { label, sketches, children } = exampleContainerOrPlaceholder;
const submenuPath = [...menuPath, label];
this.menuRegistry.registerSubmenu(submenuPath, label);
children.forEach(child => this.registerRecursively(child, submenuPath, pushToDispose));
for (const sketch of sketches) {
const { uri } = sketch;
const commandId = `arduino-open-example-${submenuPath.join(':')}--${uri}`;
const command = { id: commandId };
const handler = {
execute: async () => {
const sketch = await this.sketchService.cloneExample(uri);
this.commandService.executeCommand(OpenSketch.Commands.OPEN_SKETCH.id, sketch);
}
};
pushToDispose.push(this.commandRegistry.registerCommand(command, handler));
this.menuRegistry.registerMenuAction(submenuPath, { commandId, label: sketch.name });
pushToDispose.push(Disposable.create(() => this.menuRegistry.unregisterMenuAction(command)));
}
}
}
}
@injectable()
export class BuiltInExamples extends Examples {
onStart(): void {
this.register(); // no `await`
}
protected async register() {
let exampleContainers: ExampleContainer[] | undefined;
try {
exampleContainers = await this.examplesService.builtIns();
} catch (e) {
console.error('Could not initialize built-in examples.', e);
this.messageService.error('Could not initialize built-in examples.');
return;
}
this.toDispose.dispose();
for (const container of ['Built-in examples', ...exampleContainers]) {
this.registerRecursively(container, ArduinoMenus.EXAMPLES__BUILT_IN_GROUP, this.toDispose);
}
this.menuManager.update();
// TODO: remove
console.log(typeof this.menuRegistry);
}
}
@injectable()
export class LibraryExamples extends Examples {
@inject(NotificationCenter)
protected readonly notificationCenter: NotificationCenter;
protected readonly queue = new PQueue({ autoStart: true, concurrency: 1 });
onStart(): void {
this.register(); // no `await`
this.notificationCenter.onLibraryInstalled(() => this.register());
this.notificationCenter.onLibraryUninstalled(() => this.register());
}
protected handleBoardChanged(board: Board | undefined): void {
this.register(board);
}
protected async register(board: Board | undefined = this.boardsServiceClient.boardsConfig.selectedBoard) {
return this.queue.add(async () => {
this.toDispose.dispose();
if (!board || !board.fqbn) {
return;
}
const { fqbn, name } = board;
const { user, current, any } = await this.examplesService.installed({ fqbn });
if (user.length) {
(user as any).unshift('Examples from Custom Libraries');
}
if (current.length) {
(current as any).unshift(`Examples for ${name}`);
}
if (any.length) {
(any as any).unshift('Examples for any board');
}
for (const container of user) {
this.registerRecursively(container, ArduinoMenus.EXAMPLES__USER_LIBS_GROUP, this.toDispose);
}
for (const container of current) {
this.registerRecursively(container, ArduinoMenus.EXAMPLES__CURRENT_BOARD_GROUP, this.toDispose);
}
for (const container of any) {
this.registerRecursively(container, ArduinoMenus.EXAMPLES__ANY_BOARD_GROUP, this.toDispose);
}
this.menuManager.update();
});
}
}

View File

@@ -0,0 +1,137 @@
import { inject, injectable } from 'inversify';
import { MonacoEditor } from '@theia/monaco/lib/browser/monaco-editor';
import { EditorManager } from '@theia/editor/lib/browser/editor-manager';
import { WindowService } from '@theia/core/lib/browser/window/window-service';
import { CommandHandler } from '@theia/core/lib/common/command';
import { QuickInputService } from '@theia/core/lib/browser/quick-open/quick-input-service';
import { ArduinoMenus } from '../menu/arduino-menus';
import { Contribution, Command, MenuModelRegistry, CommandRegistry, KeybindingRegistry } from './contribution';
@injectable()
export class Help extends Contribution {
@inject(EditorManager)
protected readonly editorManager: EditorManager;
@inject(WindowService)
protected readonly windowService: WindowService;
@inject(QuickInputService)
protected readonly quickInputService: QuickInputService;
registerCommands(registry: CommandRegistry): void {
const open = (url: string) => this.windowService.openNewWindow(url, { external: true });
const createOpenHandler = (url: string) => <CommandHandler>{
execute: () => open(url)
};
registry.registerCommand(Help.Commands.GETTING_STARTED, createOpenHandler('https://www.arduino.cc/en/Guide'));
registry.registerCommand(Help.Commands.ENVIRONMENT, createOpenHandler('https://www.arduino.cc/en/Guide/Environment'));
registry.registerCommand(Help.Commands.TROUBLESHOOTING, createOpenHandler('https://support.arduino.cc/hc/en-us'));
registry.registerCommand(Help.Commands.REFERENCE, createOpenHandler('https://www.arduino.cc/reference/en/'));
registry.registerCommand(Help.Commands.FIND_IN_REFERENCE, {
execute: async () => {
let searchFor: string | undefined = undefined;
const { currentEditor } = this.editorManager;
if (currentEditor && currentEditor.editor instanceof MonacoEditor) {
const codeEditor = currentEditor.editor.getControl();
const selection = codeEditor.getSelection();
const model = codeEditor.getModel();
if (model && selection && !monaco.Range.isEmpty(selection)) {
searchFor = model.getValueInRange(selection);
}
}
if (!searchFor) {
searchFor = await this.quickInputService.open({
prompt: 'Search on Arduino.cc',
placeHolder: 'Type a keyword'
});
}
if (searchFor) {
return open(`https://www.arduino.cc/search?q=${encodeURIComponent(searchFor)}&tab=reference`);
}
}
});
registry.registerCommand(Help.Commands.FAQ, createOpenHandler('https://support.arduino.cc/hc/en-us'));
registry.registerCommand(Help.Commands.VISIT_ARDUINO, createOpenHandler('https://www.arduino.cc/'));
}
registerMenus(registry: MenuModelRegistry): void {
registry.registerMenuAction(ArduinoMenus.HELP__MAIN_GROUP, {
commandId: Help.Commands.GETTING_STARTED.id,
order: '0'
});
registry.registerMenuAction(ArduinoMenus.HELP__MAIN_GROUP, {
commandId: Help.Commands.ENVIRONMENT.id,
order: '1'
});
registry.registerMenuAction(ArduinoMenus.HELP__MAIN_GROUP, {
commandId: Help.Commands.TROUBLESHOOTING.id,
order: '2'
});
registry.registerMenuAction(ArduinoMenus.HELP__MAIN_GROUP, {
commandId: Help.Commands.REFERENCE.id,
order: '3'
});
registry.registerMenuAction(ArduinoMenus.HELP__FIND_GROUP, {
commandId: Help.Commands.FIND_IN_REFERENCE.id,
order: '4'
});
registry.registerMenuAction(ArduinoMenus.HELP__FIND_GROUP, {
commandId: Help.Commands.FAQ.id,
order: '5'
});
registry.registerMenuAction(ArduinoMenus.HELP__FIND_GROUP, {
commandId: Help.Commands.VISIT_ARDUINO.id,
order: '6'
});
}
registerKeybindings(registry: KeybindingRegistry): void {
registry.registerKeybinding({
command: Help.Commands.FIND_IN_REFERENCE.id,
keybinding: 'CtrlCmd+Shift+F'
});
}
}
export namespace Help {
export namespace Commands {
export const GETTING_STARTED: Command = {
id: 'arduino-getting-started',
label: 'Getting Started',
category: 'Arduino'
};
export const ENVIRONMENT: Command = {
id: 'arduino-environment',
label: 'Environment',
category: 'Arduino'
};
export const TROUBLESHOOTING: Command = {
id: 'arduino-troubleshooting',
label: 'Troubleshooting',
category: 'Arduino'
};
export const REFERENCE: Command = {
id: 'arduino-reference',
label: 'Reference',
category: 'Arduino'
};
export const FIND_IN_REFERENCE: Command = {
id: 'arduino-find-in-reference',
label: 'Find in Reference',
category: 'Arduino'
};
export const FAQ: Command = {
id: 'arduino-faq',
label: 'Frequently Asked Questions',
category: 'Arduino'
};
export const VISIT_ARDUINO: Command = {
id: 'arduino-visit-arduino',
label: 'Visit Arduino.cc',
category: 'Arduino'
};
}
}

View File

@@ -0,0 +1,175 @@
import * as PQueue from 'p-queue';
import { inject, injectable } from 'inversify';
import URI from '@theia/core/lib/common/uri';
import { MonacoEditor } from '@theia/monaco/lib/browser/monaco-editor';
import { EditorManager } from '@theia/editor/lib/browser';
import { MenuModelRegistry, MenuPath } from '@theia/core/lib/common/menu';
import { Disposable, DisposableCollection } from '@theia/core/lib/common/disposable';
import { ArduinoMenus, PlaceholderMenuNode } from '../menu/arduino-menus';
import { LibraryPackage, LibraryService } from '../../common/protocol';
import { MainMenuManager } from '../../common/main-menu-manager';
import { LibraryListWidget } from '../library/library-list-widget';
import { BoardsServiceProvider } from '../boards/boards-service-provider';
import { SketchContribution, Command, CommandRegistry } from './contribution';
import { NotificationCenter } from '../notification-center';
@injectable()
export class IncludeLibrary extends SketchContribution {
@inject(CommandRegistry)
protected readonly commandRegistry: CommandRegistry;
@inject(MenuModelRegistry)
protected readonly menuRegistry: MenuModelRegistry;
@inject(MainMenuManager)
protected readonly mainMenuManager: MainMenuManager;
@inject(EditorManager)
protected readonly editorManager: EditorManager;
@inject(NotificationCenter)
protected readonly notificationCenter: NotificationCenter;
@inject(BoardsServiceProvider)
protected readonly boardsServiceClient: BoardsServiceProvider;
@inject(LibraryService)
protected readonly libraryService: LibraryService;
protected readonly queue = new PQueue({ autoStart: true, concurrency: 1 });
protected readonly toDispose = new DisposableCollection();
onStart(): void {
this.updateMenuActions();
this.boardsServiceClient.onBoardsConfigChanged(() => this.updateMenuActions())
this.notificationCenter.onLibraryInstalled(() => this.updateMenuActions());
this.notificationCenter.onLibraryUninstalled(() => this.updateMenuActions());
}
registerCommands(registry: CommandRegistry): void {
registry.registerCommand(IncludeLibrary.Commands.INCLUDE_LIBRARY, {
execute: async arg => {
if (LibraryPackage.is(arg)) {
this.includeLibrary(arg);
}
}
});
}
protected async updateMenuActions(): Promise<void> {
return this.queue.add(async () => {
this.toDispose.dispose();
this.mainMenuManager.update();
const libraries: LibraryPackage[] = []
const fqbn = this.boardsServiceClient.boardsConfig.selectedBoard?.fqbn;
// Do not show board specific examples, when no board is selected.
if (fqbn) {
libraries.push(...await this.libraryService.list({ fqbn }));
}
// `Include Library` submenu
const includeLibMenuPath = [...ArduinoMenus.SKETCH__UTILS_GROUP, '0_include'];
this.menuRegistry.registerSubmenu(includeLibMenuPath, 'Include Library', { order: '1' });
// `Manage Libraries...` group.
this.menuRegistry.registerMenuAction([...includeLibMenuPath, '0_manage'], {
commandId: `${LibraryListWidget.WIDGET_ID}:toggle`,
label: 'Manage Libraries...'
});
this.toDispose.push(Disposable.create(() => this.menuRegistry.unregisterMenuAction({ commandId: `${LibraryListWidget.WIDGET_ID}:toggle` })));
// `Add .ZIP Library...`
// TODO: implement it
// `Arduino libraries`
const packageMenuPath = [...includeLibMenuPath, '2_arduino'];
const userMenuPath = [...includeLibMenuPath, '3_contributed'];
const { user, rest } = LibraryPackage.groupByLocation(libraries);
if (rest.length) {
(rest as any).unshift('Arduino libraries');
}
if (user.length) {
(user as any).unshift('Contributed libraries');
}
for (const library of user) {
this.toDispose.push(this.registerLibrary(library, userMenuPath));
}
for (const library of rest) {
this.toDispose.push(this.registerLibrary(library, packageMenuPath));
}
this.mainMenuManager.update();
});
}
protected registerLibrary(libraryOrPlaceholder: LibraryPackage | string, menuPath: MenuPath): Disposable {
if (typeof libraryOrPlaceholder === 'string') {
const placeholder = new PlaceholderMenuNode(menuPath, libraryOrPlaceholder);
this.menuRegistry.registerMenuNode(menuPath, placeholder);
return Disposable.create(() => this.menuRegistry.unregisterMenuNode(placeholder.id));
}
const commandId = `arduino-include-library--${libraryOrPlaceholder.name}:${libraryOrPlaceholder.author}`;
const command = { id: commandId };
const handler = { execute: () => this.commandRegistry.executeCommand(IncludeLibrary.Commands.INCLUDE_LIBRARY.id, libraryOrPlaceholder) };
const menuAction = { commandId, label: libraryOrPlaceholder.name };
this.menuRegistry.registerMenuAction(menuPath, menuAction);
return new DisposableCollection(
this.commandRegistry.registerCommand(command, handler),
Disposable.create(() => this.menuRegistry.unregisterMenuAction(menuAction)),
);
}
protected async includeLibrary(library: LibraryPackage): Promise<void> {
const sketch = await this.sketchServiceClient.currentSketch();
if (!sketch) {
return;
}
// If the current editor is one of the additional files from the sketch, we use that.
// Otherwise, we pick the editor of the main sketch file.
let codeEditor: monaco.editor.IStandaloneCodeEditor | undefined;
const editor = this.editorManager.currentEditor?.editor;
if (editor instanceof MonacoEditor) {
if (sketch.additionalFileUris.some(uri => uri === editor.uri.toString())) {
codeEditor = editor.getControl();
}
}
if (!codeEditor) {
const widget = await this.editorManager.open(new URI(sketch.mainFileUri));
if (widget.editor instanceof MonacoEditor) {
codeEditor = widget.editor.getControl();
}
}
if (!codeEditor) {
return;
}
const textModel = codeEditor.getModel();
if (!textModel) {
return;
}
const cursorState = codeEditor.getSelections() || [];
const eol = textModel.getEOL();
const includes = library.includes.slice();
includes.push(''); // For the trailing new line.
const text = includes.map(include => include ? `#include <${include}>` : eol).join(eol);
textModel.pushStackElement(); // Start a fresh operation.
textModel.pushEditOperations(cursorState, [{
range: new monaco.Range(1, 1, 1, 1),
text,
forceMoveMarkers: true
}], () => cursorState);
textModel.pushStackElement(); // Make it undoable.
}
}
export namespace IncludeLibrary {
export namespace Commands {
export const INCLUDE_LIBRARY: Command = {
id: 'arduino-include-library'
};
}
}

View File

@@ -0,0 +1,63 @@
import { injectable } from 'inversify';
import { ArduinoMenus } from '../menu/arduino-menus';
import { ArduinoToolbar } from '../toolbar/arduino-toolbar';
import { SketchContribution, URI, Command, CommandRegistry, MenuModelRegistry, KeybindingRegistry, TabBarToolbarRegistry } from './contribution';
@injectable()
export class NewSketch extends SketchContribution {
registerCommands(registry: CommandRegistry): void {
registry.registerCommand(NewSketch.Commands.NEW_SKETCH, {
execute: () => this.newSketch()
});
registry.registerCommand(NewSketch.Commands.NEW_SKETCH__TOOLBAR, {
isVisible: widget => ArduinoToolbar.is(widget) && widget.side === 'left',
execute: () => registry.executeCommand(NewSketch.Commands.NEW_SKETCH.id)
});
}
registerMenus(registry: MenuModelRegistry): void {
registry.registerMenuAction(ArduinoMenus.FILE__SKETCH_GROUP, {
commandId: NewSketch.Commands.NEW_SKETCH.id,
label: 'New',
order: '0'
});
}
registerKeybindings(registry: KeybindingRegistry): void {
registry.registerKeybinding({
command: NewSketch.Commands.NEW_SKETCH.id,
keybinding: 'CtrlCmd+N'
});
}
registerToolbarItems(registry: TabBarToolbarRegistry): void {
registry.registerItem({
id: NewSketch.Commands.NEW_SKETCH__TOOLBAR.id,
command: NewSketch.Commands.NEW_SKETCH__TOOLBAR.id,
tooltip: 'New',
priority: 3
});
}
async newSketch(): Promise<void> {
try {
const sketch = await this.sketchService.createNewSketch();
this.workspaceService.open(new URI(sketch.uri));
} catch (e) {
await this.messageService.error(e.toString());
}
}
}
export namespace NewSketch {
export namespace Commands {
export const NEW_SKETCH: Command = {
id: 'arduino-new-sketch'
};
export const NEW_SKETCH__TOOLBAR: Command = {
id: 'arduino-new-sketch--toolbar'
};
}
}

View File

@@ -0,0 +1,62 @@
import { inject, injectable } from 'inversify';
import { WorkspaceServer } from '@theia/workspace/lib/common/workspace-protocol';
import { Disposable, DisposableCollection } from '@theia/core/lib/common/disposable';
import { SketchContribution, CommandRegistry, MenuModelRegistry, Sketch } from './contribution';
import { ArduinoMenus } from '../menu/arduino-menus';
import { MainMenuManager } from '../../common/main-menu-manager';
import { OpenSketch } from './open-sketch';
import { NotificationCenter } from '../notification-center';
@injectable()
export class OpenRecentSketch extends SketchContribution {
@inject(CommandRegistry)
protected readonly commandRegistry: CommandRegistry;
@inject(MenuModelRegistry)
protected readonly menuRegistry: MenuModelRegistry;
@inject(MainMenuManager)
protected readonly mainMenuManager: MainMenuManager;
@inject(WorkspaceServer)
protected readonly workspaceServer: WorkspaceServer;
@inject(NotificationCenter)
protected readonly notificationCenter: NotificationCenter;
protected toDisposeBeforeRegister = new Map<string, DisposableCollection>();
onStart(): void {
const refreshMenu = (sketches: Sketch[]) => {
this.register(sketches);
this.mainMenuManager.update();
};
this.notificationCenter.onRecentSketchesChanged(({ sketches }) => refreshMenu(sketches));
this.sketchService.recentlyOpenedSketches().then(refreshMenu);
}
registerMenus(registry: MenuModelRegistry): void {
registry.registerSubmenu(ArduinoMenus.FILE__OPEN_RECENT_SUBMENU, 'Open Recent', { order: '2' });
}
protected register(sketches: Sketch[]): void {
let order = 0;
for (const sketch of sketches) {
const { uri } = sketch;
const toDispose = this.toDisposeBeforeRegister.get(uri);
if (toDispose) {
toDispose.dispose();
}
const command = { id: `arduino-open-recent--${uri}` };
const handler = { execute: () => this.commandRegistry.executeCommand(OpenSketch.Commands.OPEN_SKETCH.id, sketch) };
this.commandRegistry.registerCommand(command, handler);
this.menuRegistry.registerMenuAction(ArduinoMenus.FILE__OPEN_RECENT_SUBMENU, { commandId: command.id, label: sketch.name, order: String(order) });
this.toDisposeBeforeRegister.set(sketch.uri, new DisposableCollection(
Disposable.create(() => this.commandRegistry.unregisterCommand(command)),
Disposable.create(() => this.menuRegistry.unregisterMenuAction(command))
));
}
}
}

View File

@@ -0,0 +1,52 @@
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';
@injectable()
export class OpenSketchExternal extends SketchContribution {
registerCommands(registry: CommandRegistry): void {
registry.registerCommand(OpenSketchExternal.Commands.OPEN_EXTERNAL, {
execute: () => this.openExternal()
});
}
registerMenus(registry: MenuModelRegistry): void {
registry.registerMenuAction(ArduinoMenus.SKETCH__UTILS_GROUP, {
commandId: OpenSketchExternal.Commands.OPEN_EXTERNAL.id,
label: 'Show Sketch Folder',
order: '0'
});
}
registerKeybindings(registry: KeybindingRegistry): void {
registry.registerKeybinding({
command: OpenSketchExternal.Commands.OPEN_EXTERNAL.id,
keybinding: 'CtrlCmd+Alt+K'
});
}
protected async openExternal(): Promise<void> {
const uri = await this.sketchServiceClient.currentSketchFile();
if (uri) {
const exists = this.fileService.exists(new URI(uri));
if (exists) {
const fsPath = await this.fileService.fsPath(new URI(uri));
if (fsPath) {
remote.shell.showItemInFolder(fsPath);
}
}
}
}
}
export namespace OpenSketchExternal {
export namespace Commands {
export const OPEN_EXTERNAL: Command = {
id: 'arduino-open-sketch-external'
};
}
}

View File

@@ -0,0 +1,179 @@
import { inject, injectable } from 'inversify';
import { remote } from 'electron';
import { MaybePromise } from '@theia/core/lib/common/types';
import { Widget, ContextMenuRenderer } from '@theia/core/lib/browser';
import { Disposable, DisposableCollection } from '@theia/core/lib/common/disposable';
import { ArduinoMenus } from '../menu/arduino-menus';
import { ArduinoToolbar } from '../toolbar/arduino-toolbar';
import { SketchContribution, Sketch, URI, Command, CommandRegistry, MenuModelRegistry, KeybindingRegistry, TabBarToolbarRegistry } from './contribution';
import { ExamplesService } from '../../common/protocol/examples-service';
import { BuiltInExamples } from './examples';
@injectable()
export class OpenSketch extends SketchContribution {
@inject(MenuModelRegistry)
protected readonly menuRegistry: MenuModelRegistry;
@inject(ContextMenuRenderer)
protected readonly contextMenuRenderer: ContextMenuRenderer;
@inject(BuiltInExamples)
protected readonly builtInExamples: BuiltInExamples;
@inject(ExamplesService)
protected readonly examplesService: ExamplesService;
protected readonly toDisposeBeforeCreateNewContextMenu = new DisposableCollection();
registerCommands(registry: CommandRegistry): void {
registry.registerCommand(OpenSketch.Commands.OPEN_SKETCH, {
execute: arg => Sketch.is(arg) ? this.openSketch(arg) : this.openSketch()
});
registry.registerCommand(OpenSketch.Commands.OPEN_SKETCH__TOOLBAR, {
isVisible: widget => ArduinoToolbar.is(widget) && widget.side === 'left',
execute: async (_: Widget, target: EventTarget) => {
const sketches = await this.sketchService.getSketches();
if (!sketches.length) {
this.openSketch();
} else {
this.toDisposeBeforeCreateNewContextMenu.dispose();
if (!(target instanceof HTMLElement)) {
return;
}
const { parentElement } = target;
if (!parentElement) {
return;
}
this.menuRegistry.registerMenuAction(ArduinoMenus.OPEN_SKETCH__CONTEXT__OPEN_GROUP, {
commandId: OpenSketch.Commands.OPEN_SKETCH.id,
label: 'Open...'
});
this.toDisposeBeforeCreateNewContextMenu.push(Disposable.create(() => this.menuRegistry.unregisterMenuAction(OpenSketch.Commands.OPEN_SKETCH)));
for (const sketch of sketches) {
const command = { id: `arduino-open-sketch--${sketch.uri}` };
const handler = { execute: () => this.openSketch(sketch) };
this.toDisposeBeforeCreateNewContextMenu.push(registry.registerCommand(command, handler));
this.menuRegistry.registerMenuAction(ArduinoMenus.OPEN_SKETCH__CONTEXT__RECENT_GROUP, {
commandId: command.id,
label: sketch.name
});
this.toDisposeBeforeCreateNewContextMenu.push(Disposable.create(() => this.menuRegistry.unregisterMenuAction(command)));
}
try {
const containers = await this.examplesService.builtIns();
for (const container of containers) {
this.builtInExamples.registerRecursively(container, ArduinoMenus.OPEN_SKETCH__CONTEXT__EXAMPLES_GROUP, this.toDisposeBeforeCreateNewContextMenu);
}
} catch (e) {
console.error('Error when collecting built-in examples.', e);
}
const options = {
menuPath: ArduinoMenus.OPEN_SKETCH__CONTEXT,
anchor: {
x: parentElement.getBoundingClientRect().left,
y: parentElement.getBoundingClientRect().top + parentElement.offsetHeight
}
}
this.contextMenuRenderer.render(options);
}
}
});
}
registerMenus(registry: MenuModelRegistry): void {
registry.registerMenuAction(ArduinoMenus.FILE__SKETCH_GROUP, {
commandId: OpenSketch.Commands.OPEN_SKETCH.id,
label: 'Open...',
order: '1'
});
}
registerKeybindings(registry: KeybindingRegistry): void {
registry.registerKeybinding({
command: OpenSketch.Commands.OPEN_SKETCH.id,
keybinding: 'CtrlCmd+O'
});
}
registerToolbarItems(registry: TabBarToolbarRegistry): void {
registry.registerItem({
id: OpenSketch.Commands.OPEN_SKETCH__TOOLBAR.id,
command: OpenSketch.Commands.OPEN_SKETCH__TOOLBAR.id,
tooltip: 'Open',
priority: 4
});
}
async openSketch(toOpen: MaybePromise<Sketch | undefined> = this.selectSketch()): Promise<void> {
const sketch = await toOpen;
if (sketch) {
this.workspaceService.open(new URI(sketch.uri));
}
}
protected async selectSketch(): Promise<Sketch | undefined> {
const config = await this.configService.getConfiguration();
const defaultPath = await this.fileService.fsPath(new URI(config.sketchDirUri));
const { filePaths } = await remote.dialog.showOpenDialog({
defaultPath,
properties: ['createDirectory', 'openFile'],
filters: [
{
name: 'Sketch',
extensions: ['ino', 'pde']
}
]
});
if (!filePaths.length) {
return undefined;
}
if (filePaths.length > 1) {
this.logger.warn(`Multiple sketches were selected: ${filePaths}. Using the first one.`);
}
const sketchFilePath = filePaths[0];
const sketchFileUri = await this.fileSystemExt.getUri(sketchFilePath);
const sketch = await this.sketchService.getSketchFolder(sketchFileUri);
if (sketch) {
return sketch;
}
if (Sketch.isSketchFile(sketchFileUri)) {
const name = new URI(sketchFileUri).path.name;
const nameWithExt = this.labelProvider.getName(new URI(sketchFileUri));
const { response } = await remote.dialog.showMessageBox({
title: 'Moving',
type: 'question',
buttons: ['Cancel', 'OK'],
message: `The file "${nameWithExt}" needs to be inside a sketch folder named as "${name}".\nCreate this folder, move the file, and continue?`
});
if (response === 1) { // OK
const newSketchUri = new URI(sketchFileUri).parent.resolve(name);
const exists = await this.fileService.exists(newSketchUri);
if (exists) {
await remote.dialog.showMessageBox({
type: 'error',
title: 'Error',
message: `A folder named "${name}" already exists. Can't open sketch.`
});
return undefined;
}
await this.fileService.createFolder(newSketchUri);
await this.fileService.move(new URI(sketchFileUri), new URI(newSketchUri.resolve(nameWithExt).toString()));
return this.sketchService.getSketchFolder(newSketchUri.toString());
}
}
}
}
export namespace OpenSketch {
export namespace Commands {
export const OPEN_SKETCH: Command = {
id: 'arduino-open-sketch'
};
export const OPEN_SKETCH__TOOLBAR: Command = {
id: 'arduino-open-sketch--toolbar'
};
}
}

View File

@@ -0,0 +1,46 @@
import { injectable } from 'inversify';
import { remote } from 'electron';
import { isOSX } from '@theia/core/lib/common/os';
import { Contribution, Command, MenuModelRegistry, KeybindingRegistry, CommandRegistry } from './contribution';
import { ArduinoMenus } from '../menu/arduino-menus';
@injectable()
export class QuitApp extends Contribution {
registerCommands(registry: CommandRegistry): void {
if (!isOSX) {
registry.registerCommand(QuitApp.Commands.QUIT_APP, {
execute: () => remote.app.quit()
});
}
}
registerMenus(registry: MenuModelRegistry): void {
// On macOS we will get the `Quit ${YOUR_APP_NAME}` menu item natively, no need to duplicate it.
if (!isOSX) {
registry.registerMenuAction(ArduinoMenus.FILE__QUIT_GROUP, {
commandId: QuitApp.Commands.QUIT_APP.id,
label: 'Quit',
order: '0'
});
}
}
registerKeybindings(registry: KeybindingRegistry): void {
if (!isOSX) {
registry.registerKeybinding({
command: QuitApp.Commands.QUIT_APP.id,
keybinding: 'CtrlCmd+Q'
});
}
}
}
export namespace QuitApp {
export namespace Commands {
export const QUIT_APP: Command = {
id: 'arduino-quit-app'
};
}
}

View File

@@ -0,0 +1,96 @@
import { injectable } from 'inversify';
import { remote } from 'electron';
import * as dateFormat from 'dateformat';
import { ArduinoMenus } from '../menu/arduino-menus';
import { SketchContribution, URI, Command, CommandRegistry, MenuModelRegistry, KeybindingRegistry } from './contribution';
@injectable()
export class SaveAsSketch extends SketchContribution {
registerCommands(registry: CommandRegistry): void {
registry.registerCommand(SaveAsSketch.Commands.SAVE_AS_SKETCH, {
execute: args => this.saveAs(args)
});
}
registerMenus(registry: MenuModelRegistry): void {
registry.registerMenuAction(ArduinoMenus.FILE__SKETCH_GROUP, {
commandId: SaveAsSketch.Commands.SAVE_AS_SKETCH.id,
label: 'Save As...',
order: '7'
});
}
registerKeybindings(registry: KeybindingRegistry): void {
registry.registerKeybinding({
command: SaveAsSketch.Commands.SAVE_AS_SKETCH.id,
keybinding: 'CtrlCmd+Shift+S'
});
}
/**
* Resolves `true` if the sketch was successfully saved as something.
*/
async saveAs({ execOnlyIfTemp, openAfterMove, wipeOriginal }: SaveAsSketch.Options = SaveAsSketch.Options.DEFAULT): Promise<boolean> {
const sketch = await this.sketchServiceClient.currentSketch();
if (!sketch) {
return false;
}
const isTemp = await this.sketchService.isTemp(sketch);
if (!isTemp && !!execOnlyIfTemp) {
return false;
}
// 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.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.fileService.fsPath(defaultUri);
const { filePath, canceled } = await remote.dialog.showSaveDialog({ title: 'Save sketch folder as...', defaultPath });
if (!filePath || canceled) {
return false;
}
const destinationUri = await this.fileSystemExt.getUri(filePath);
if (!destinationUri) {
return false;
}
const workspaceUri = await this.sketchService.copy(sketch, { destinationUri });
if (workspaceUri && openAfterMove) {
if (wipeOriginal || (openAfterMove && execOnlyIfTemp)) {
try {
await this.fileService.delete(new URI(sketch.uri), { recursive: true });
} catch { /* NOOP: from time to time, it's not possible to wipe the old resource from the temp dir on Windows */ }
}
this.workspaceService.open(new URI(workspaceUri), { preserveWindow: true });
}
return !!workspaceUri;
}
}
export namespace SaveAsSketch {
export namespace Commands {
export const SAVE_AS_SKETCH: Command = {
id: 'arduino-save-as-sketch'
};
}
export interface Options {
readonly execOnlyIfTemp?: boolean;
readonly openAfterMove?: boolean;
/**
* Ignored if `openAfterMove` is `false`.
*/
readonly wipeOriginal?: boolean;
}
export namespace Options {
export const DEFAULT: Options = {
execOnlyIfTemp: false,
openAfterMove: true,
wipeOriginal: false
};
}
}

View File

@@ -0,0 +1,59 @@
import { injectable } from 'inversify';
import { CommonCommands } from '@theia/core/lib/browser/common-frontend-contribution';
import { ArduinoMenus } from '../menu/arduino-menus';
import { ArduinoToolbar } from '../toolbar/arduino-toolbar';
import { SketchContribution, Command, CommandRegistry, MenuModelRegistry, KeybindingRegistry, TabBarToolbarRegistry } from './contribution';
@injectable()
export class SaveSketch extends SketchContribution {
registerCommands(registry: CommandRegistry): void {
registry.registerCommand(SaveSketch.Commands.SAVE_SKETCH, {
execute: () => this.saveSketch()
});
registry.registerCommand(SaveSketch.Commands.SAVE_SKETCH__TOOLBAR, {
isVisible: widget => ArduinoToolbar.is(widget) && widget.side === 'left',
execute: () => registry.executeCommand(SaveSketch.Commands.SAVE_SKETCH.id)
});
}
registerMenus(registry: MenuModelRegistry): void {
registry.registerMenuAction(ArduinoMenus.FILE__SKETCH_GROUP, {
commandId: SaveSketch.Commands.SAVE_SKETCH.id,
label: 'Save',
order: '6'
});
}
registerKeybindings(registry: KeybindingRegistry): void {
registry.registerKeybinding({
command: SaveSketch.Commands.SAVE_SKETCH.id,
keybinding: 'CtrlCmd+S'
});
}
registerToolbarItems(registry: TabBarToolbarRegistry): void {
registry.registerItem({
id: SaveSketch.Commands.SAVE_SKETCH__TOOLBAR.id,
command: SaveSketch.Commands.SAVE_SKETCH__TOOLBAR.id,
tooltip: 'Save',
priority: 5
});
}
async saveSketch(): Promise<void> {
return this.commandService.executeCommand(CommonCommands.SAVE_ALL.id);
}
}
export namespace SaveSketch {
export namespace Commands {
export const SAVE_SKETCH: Command = {
id: 'arduino-save-sketch'
};
export const SAVE_SKETCH__TOOLBAR: Command = {
id: 'arduino-save-sketch--toolbar'
};
}
}

View File

@@ -0,0 +1,60 @@
import { inject, injectable } from 'inversify';
import { Command, MenuModelRegistry, CommandRegistry, SketchContribution, KeybindingRegistry } from './contribution';
import { ArduinoMenus } from '../menu/arduino-menus';
import { Settings as Preferences, SettingsDialog } from '../settings';
@injectable()
export class Settings extends SketchContribution {
@inject(SettingsDialog)
protected readonly settingsDialog: SettingsDialog;
protected settingsOpened = false;
registerCommands(registry: CommandRegistry): void {
registry.registerCommand(Settings.Commands.OPEN, {
execute: async () => {
let settings: Preferences | undefined = undefined;
try {
this.settingsOpened = true;
settings = await this.settingsDialog.open();
} finally {
this.settingsOpened = false;
}
if (settings) {
await this.settingsService.update(settings);
await this.settingsService.save();
} else {
await this.settingsService.reset();
}
},
isEnabled: () => !this.settingsOpened
});
}
registerMenus(registry: MenuModelRegistry): void {
registry.registerMenuAction(ArduinoMenus.FILE__SETTINGS_GROUP, {
commandId: Settings.Commands.OPEN.id,
label: 'Preferences...',
order: '0'
});
}
registerKeybindings(registry: KeybindingRegistry): void {
registry.registerKeybinding({
command: Settings.Commands.OPEN.id,
keybinding: 'CtrlCmd+,',
});
}
}
export namespace Settings {
export namespace Commands {
export const OPEN: Command = {
id: 'arduino-settings-open',
label: 'Open Preferences...',
category: 'Arduino'
}
}
}

View File

@@ -0,0 +1,129 @@
import { inject, injectable } from 'inversify';
import { CommonCommands } from '@theia/core/lib/browser/common-frontend-contribution';
import { ApplicationShell } from '@theia/core/lib/browser/shell/application-shell';
import { WorkspaceCommands } from '@theia/workspace/lib/browser';
import { ContextMenuRenderer } from '@theia/core/lib/browser/context-menu-renderer';
import { Disposable, DisposableCollection } from '@theia/core/lib/common/disposable';
import { URI, SketchContribution, Command, CommandRegistry, MenuModelRegistry, KeybindingRegistry, TabBarToolbarRegistry, open } from './contribution';
import { ArduinoMenus } from '../menu/arduino-menus';
@injectable()
export class SketchControl extends SketchContribution {
@inject(ApplicationShell)
protected readonly shell: ApplicationShell;
@inject(MenuModelRegistry)
protected readonly menuRegistry: MenuModelRegistry;
@inject(ContextMenuRenderer)
protected readonly contextMenuRenderer: ContextMenuRenderer;
protected readonly toDisposeBeforeCreateNewContextMenu = new DisposableCollection();
registerCommands(registry: CommandRegistry): void {
registry.registerCommand(SketchControl.Commands.OPEN_SKETCH_CONTROL__TOOLBAR, {
isVisible: widget => this.shell.getWidgets('main').indexOf(widget) !== -1,
execute: async () => {
this.toDisposeBeforeCreateNewContextMenu.dispose();
const sketch = await this.sketchServiceClient.currentSketch();
if (!sketch) {
return;
}
const target = document.getElementById(SketchControl.Commands.OPEN_SKETCH_CONTROL__TOOLBAR.id);
if (!(target instanceof HTMLElement)) {
return;
}
const { parentElement } = target;
if (!parentElement) {
return;
}
const { mainFileUri, rootFolderFileUris } = await this.sketchService.loadSketch(sketch.uri);
const uris = [mainFileUri, ...rootFolderFileUris];
for (let i = 0; i < uris.length; i++) {
const uri = new URI(uris[i]);
const command = { id: `arduino-focus-file--${uri.toString()}` };
const handler = { execute: () => open(this.openerService, uri) };
this.toDisposeBeforeCreateNewContextMenu.push(registry.registerCommand(command, handler));
this.menuRegistry.registerMenuAction(ArduinoMenus.SKETCH_CONTROL__CONTEXT__RESOURCES_GROUP, {
commandId: command.id,
label: this.labelProvider.getName(uri),
order: `${i}`
});
this.toDisposeBeforeCreateNewContextMenu.push(Disposable.create(() => this.menuRegistry.unregisterMenuAction(command)));
}
const options = {
menuPath: ArduinoMenus.SKETCH_CONTROL__CONTEXT,
anchor: {
x: parentElement.getBoundingClientRect().left,
y: parentElement.getBoundingClientRect().top + parentElement.offsetHeight
}
}
this.contextMenuRenderer.render(options);
}
});
}
registerMenus(registry: MenuModelRegistry): void {
registry.registerMenuAction(ArduinoMenus.SKETCH_CONTROL__CONTEXT__MAIN_GROUP, {
commandId: WorkspaceCommands.NEW_FILE.id,
label: 'New Tab',
order: '0'
});
registry.registerMenuAction(ArduinoMenus.SKETCH_CONTROL__CONTEXT__MAIN_GROUP, {
commandId: WorkspaceCommands.FILE_RENAME.id,
label: 'Rename',
order: '1'
});
registry.registerMenuAction(ArduinoMenus.SKETCH_CONTROL__CONTEXT__MAIN_GROUP, {
commandId: WorkspaceCommands.FILE_DELETE.id, // TODO: customize delete. Wipe sketch if deleting main file. Close window.
label: 'Delete',
order: '2'
});
registry.registerMenuAction(ArduinoMenus.SKETCH_CONTROL__CONTEXT__NAVIGATION_GROUP, {
commandId: CommonCommands.PREVIOUS_TAB.id,
label: 'Previous Tab',
order: '0'
});
registry.registerMenuAction(ArduinoMenus.SKETCH_CONTROL__CONTEXT__NAVIGATION_GROUP, {
commandId: CommonCommands.NEXT_TAB.id,
label: 'Next Tab',
order: '0'
});
}
registerKeybindings(registry: KeybindingRegistry): void {
registry.registerKeybinding({
command: WorkspaceCommands.NEW_FILE.id,
keybinding: 'CtrlCmd+Shift+N'
});
registry.registerKeybinding({
command: CommonCommands.PREVIOUS_TAB.id,
keybinding: 'CtrlCmd+Alt+Left' // TODO: check why electron does not show the keybindings in the UI.
});
registry.registerKeybinding({
command: CommonCommands.NEXT_TAB.id,
keybinding: 'CtrlCmd+Alt+Right'
});
}
registerToolbarItems(registry: TabBarToolbarRegistry): void {
registry.registerItem({
id: SketchControl.Commands.OPEN_SKETCH_CONTROL__TOOLBAR.id,
command: SketchControl.Commands.OPEN_SKETCH_CONTROL__TOOLBAR.id
});
}
}
export namespace SketchControl {
export namespace Commands {
export const OPEN_SKETCH_CONTROL__TOOLBAR: Command = {
id: 'arduino-open-sketch-control--toolbar',
iconClass: 'fa fa-caret-down'
};
}
}

View File

@@ -0,0 +1,69 @@
import { inject, injectable } from 'inversify';
import { Disposable, DisposableCollection } from '@theia/core/lib/common/disposable';
import { SketchContribution, CommandRegistry, MenuModelRegistry, Sketch } from './contribution';
import { ArduinoMenus } from '../menu/arduino-menus';
import { MainMenuManager } from '../../common/main-menu-manager';
import { NotificationCenter } from '../notification-center';
import { OpenSketch } from './open-sketch';
@injectable()
export class Sketchbook extends SketchContribution {
@inject(CommandRegistry)
protected readonly commandRegistry: CommandRegistry;
@inject(MenuModelRegistry)
protected readonly menuRegistry: MenuModelRegistry;
@inject(MainMenuManager)
protected readonly mainMenuManager: MainMenuManager;
@inject(NotificationCenter)
protected readonly notificationCenter: NotificationCenter;
protected toDisposePerSketch = new Map<string, DisposableCollection>();
onStart(): void {
this.sketchService.getSketches().then(sketches => {
this.register(sketches);
this.mainMenuManager.update();
});
this.sketchServiceClient.onSketchbookDidChange(({ created, removed }) => {
this.unregister(removed);
this.register(created);
this.mainMenuManager.update();
});
}
registerMenus(registry: MenuModelRegistry): void {
registry.registerSubmenu(ArduinoMenus.FILE__SKETCHBOOK_SUBMENU, 'Sketchbook', { order: '3' });
}
protected register(sketches: Sketch[]): void {
for (const sketch of sketches) {
const { uri } = sketch;
const toDispose = this.toDisposePerSketch.get(uri);
if (toDispose) {
toDispose.dispose();
}
const command = { id: `arduino-sketchbook-open--${uri}` };
const handler = { execute: () => this.commandRegistry.executeCommand(OpenSketch.Commands.OPEN_SKETCH.id, sketch) };
this.commandRegistry.registerCommand(command, handler);
this.menuRegistry.registerMenuAction(ArduinoMenus.FILE__SKETCHBOOK_SUBMENU, { commandId: command.id, label: sketch.name });
this.toDisposePerSketch.set(sketch.uri, new DisposableCollection(
Disposable.create(() => this.commandRegistry.unregisterCommand(command)),
Disposable.create(() => this.menuRegistry.unregisterMenuAction(command))
));
}
}
protected unregister(sketches: Sketch[]): void {
for (const { uri } of sketches) {
const toDispose = this.toDisposePerSketch.get(uri);
if (toDispose) {
toDispose.dispose();
}
}
}
}

View File

@@ -0,0 +1,169 @@
import { inject, injectable } from 'inversify';
import { OutputChannelManager } from '@theia/output/lib/common/output-channel';
import { CoreService } from '../../common/protocol';
import { ArduinoMenus } from '../menu/arduino-menus';
import { ArduinoToolbar } from '../toolbar/arduino-toolbar';
import { BoardsDataStore } from '../boards/boards-data-store';
import { MonitorConnection } from '../monitor/monitor-connection';
import { BoardsServiceProvider } from '../boards/boards-service-provider';
import { SketchContribution, Command, CommandRegistry, MenuModelRegistry, KeybindingRegistry, TabBarToolbarRegistry } from './contribution';
@injectable()
export class UploadSketch extends SketchContribution {
@inject(CoreService)
protected readonly coreService: CoreService;
@inject(MonitorConnection)
protected readonly monitorConnection: MonitorConnection;
@inject(BoardsDataStore)
protected readonly boardsDataStore: BoardsDataStore;
@inject(BoardsServiceProvider)
protected readonly boardsServiceClientImpl: BoardsServiceProvider;
@inject(OutputChannelManager)
protected readonly outputChannelManager: OutputChannelManager;
registerCommands(registry: CommandRegistry): void {
registry.registerCommand(UploadSketch.Commands.UPLOAD_SKETCH, {
execute: () => this.uploadSketch()
});
registry.registerCommand(UploadSketch.Commands.UPLOAD_SKETCH_USING_PROGRAMMER, {
execute: () => this.uploadSketch(true)
});
registry.registerCommand(UploadSketch.Commands.UPLOAD_SKETCH_TOOLBAR, {
isVisible: widget => ArduinoToolbar.is(widget) && widget.side === 'left',
execute: () => registry.executeCommand(UploadSketch.Commands.UPLOAD_SKETCH.id)
});
}
registerMenus(registry: MenuModelRegistry): void {
registry.registerMenuAction(ArduinoMenus.SKETCH__MAIN_GROUP, {
commandId: UploadSketch.Commands.UPLOAD_SKETCH.id,
label: 'Upload',
order: '1'
});
registry.registerMenuAction(ArduinoMenus.SKETCH__MAIN_GROUP, {
commandId: UploadSketch.Commands.UPLOAD_SKETCH_USING_PROGRAMMER.id,
label: 'Upload Using Programmer',
order: '2'
});
}
registerKeybindings(registry: KeybindingRegistry): void {
registry.registerKeybinding({
command: UploadSketch.Commands.UPLOAD_SKETCH.id,
keybinding: 'CtrlCmd+U'
});
registry.registerKeybinding({
command: UploadSketch.Commands.UPLOAD_SKETCH_USING_PROGRAMMER.id,
keybinding: 'CtrlCmd+Shift+U'
});
}
registerToolbarItems(registry: TabBarToolbarRegistry): void {
registry.registerItem({
id: UploadSketch.Commands.UPLOAD_SKETCH_TOOLBAR.id,
command: UploadSketch.Commands.UPLOAD_SKETCH_TOOLBAR.id,
tooltip: 'Upload',
priority: 1
});
}
async uploadSketch(usingProgrammer: boolean = false): Promise<void> {
const sketch = await this.sketchServiceClient.currentSketch();
if (!sketch) {
return;
}
let shouldAutoConnect = false;
const monitorConfig = this.monitorConnection.monitorConfig;
if (monitorConfig) {
await this.monitorConnection.disconnect();
if (this.monitorConnection.autoConnect) {
shouldAutoConnect = true;
}
this.monitorConnection.autoConnect = false;
}
try {
const { boardsConfig } = this.boardsServiceClientImpl;
const [fqbn, { selectedProgrammer }, verify, verbose, sourceOverride] = await Promise.all([
this.boardsDataStore.appendConfigToFqbn(boardsConfig.selectedBoard?.fqbn),
this.boardsDataStore.getData(boardsConfig.selectedBoard?.fqbn),
this.preferences.get('arduino.upload.verify'),
this.preferences.get('arduino.upload.verbose'),
this.sourceOverride()
]);
let options: CoreService.Upload.Options | undefined = undefined;
const sketchUri = sketch.uri;
const optimizeForDebug = this.editorMode.compileForDebug;
const { selectedPort } = boardsConfig;
const port = selectedPort?.address;
if (usingProgrammer) {
const programmer = selectedProgrammer;
options = {
sketchUri,
fqbn,
optimizeForDebug,
programmer,
port,
verbose,
verify,
sourceOverride
};
} else {
options = {
sketchUri,
fqbn,
optimizeForDebug,
port,
verbose,
verify,
sourceOverride
};
}
this.outputChannelManager.getChannel('Arduino').clear();
if (usingProgrammer) {
await this.coreService.uploadUsingProgrammer(options);
} else {
await this.coreService.upload(options);
}
this.messageService.info('Done uploading.', { timeout: 1000 });
} catch (e) {
this.messageService.error(e.toString());
} finally {
if (monitorConfig) {
const { board, port } = monitorConfig;
try {
await this.boardsServiceClientImpl.waitUntilAvailable(Object.assign(board, { port }), 10_000);
if (shouldAutoConnect) {
// Enabling auto-connect will trigger a connect.
this.monitorConnection.autoConnect = true;
} else {
await this.monitorConnection.connect(monitorConfig);
}
} catch (waitError) {
this.messageService.error(`Could not reconnect to serial monitor. ${waitError.toString()}`);
}
}
}
}
}
export namespace UploadSketch {
export namespace Commands {
export const UPLOAD_SKETCH: Command = {
id: 'arduino-upload-sketch'
};
export const UPLOAD_SKETCH_USING_PROGRAMMER: Command = {
id: 'arduino-upload-sketch-using-programmer'
};
export const UPLOAD_SKETCH_TOOLBAR: Command = {
id: 'arduino-upload-sketch--toolbar'
};
}
}

View File

@@ -0,0 +1,112 @@
import { inject, injectable } from 'inversify';
import { OutputChannelManager } from '@theia/output/lib/common/output-channel';
import { CoreService } from '../../common/protocol';
import { ArduinoMenus } from '../menu/arduino-menus';
import { ArduinoToolbar } from '../toolbar/arduino-toolbar';
import { BoardsDataStore } from '../boards/boards-data-store';
import { BoardsServiceProvider } from '../boards/boards-service-provider';
import { SketchContribution, Command, CommandRegistry, MenuModelRegistry, KeybindingRegistry, TabBarToolbarRegistry } from './contribution';
@injectable()
export class VerifySketch extends SketchContribution {
@inject(CoreService)
protected readonly coreService: CoreService;
@inject(BoardsDataStore)
protected readonly boardsDataStore: BoardsDataStore;
@inject(BoardsServiceProvider)
protected readonly boardsServiceClientImpl: BoardsServiceProvider;
@inject(OutputChannelManager)
protected readonly outputChannelManager: OutputChannelManager;
registerCommands(registry: CommandRegistry): void {
registry.registerCommand(VerifySketch.Commands.VERIFY_SKETCH, {
execute: () => this.verifySketch()
});
registry.registerCommand(VerifySketch.Commands.EXPORT_BINARIES, {
execute: () => this.verifySketch(true)
});
registry.registerCommand(VerifySketch.Commands.VERIFY_SKETCH_TOOLBAR, {
isVisible: widget => ArduinoToolbar.is(widget) && widget.side === 'left',
execute: () => registry.executeCommand(VerifySketch.Commands.VERIFY_SKETCH.id)
});
}
registerMenus(registry: MenuModelRegistry): void {
registry.registerMenuAction(ArduinoMenus.SKETCH__MAIN_GROUP, {
commandId: VerifySketch.Commands.VERIFY_SKETCH.id,
label: 'Verify/Compile',
order: '0'
});
registry.registerMenuAction(ArduinoMenus.SKETCH__MAIN_GROUP, {
commandId: VerifySketch.Commands.EXPORT_BINARIES.id,
label: 'Export compiled Binary',
order: '3'
});
}
registerKeybindings(registry: KeybindingRegistry): void {
registry.registerKeybinding({
command: VerifySketch.Commands.VERIFY_SKETCH.id,
keybinding: 'CtrlCmd+R'
});
registry.registerKeybinding({
command: VerifySketch.Commands.EXPORT_BINARIES.id,
keybinding: 'CtrlCmd+Alt+S'
});
}
registerToolbarItems(registry: TabBarToolbarRegistry): void {
registry.registerItem({
id: VerifySketch.Commands.VERIFY_SKETCH_TOOLBAR.id,
command: VerifySketch.Commands.VERIFY_SKETCH_TOOLBAR.id,
tooltip: 'Verify',
priority: 0
});
}
async verifySketch(exportBinaries?: boolean): Promise<void> {
const sketch = await this.sketchServiceClient.currentSketch();
if (!sketch) {
return;
}
try {
const { boardsConfig } = this.boardsServiceClientImpl;
const [fqbn, sourceOverride] = await Promise.all([
this.boardsDataStore.appendConfigToFqbn(boardsConfig.selectedBoard?.fqbn),
this.sourceOverride()
]);
const verbose = this.preferences.get('arduino.compile.verbose');
this.outputChannelManager.getChannel('Arduino').clear();
await this.coreService.compile({
sketchUri: sketch.uri,
fqbn,
optimizeForDebug: this.editorMode.compileForDebug,
verbose,
exportBinaries,
sourceOverride
});
this.messageService.info('Done compiling.', { timeout: 1000 });
} catch (e) {
this.messageService.error(e.toString());
}
}
}
export namespace VerifySketch {
export namespace Commands {
export const VERIFY_SKETCH: Command = {
id: 'arduino-verify-sketch'
};
export const EXPORT_BINARIES: Command = {
id: 'arduino-export-binaries'
};
export const VERIFY_SKETCH_TOOLBAR: Command = {
id: 'arduino-verify-sketch--toolbar'
};
}
}

View File

@@ -1,7 +0,0 @@
import { ApplicationShell } from "@theia/core/lib/browser";
export class CustomApplicationShell extends ApplicationShell {
protected refreshBottomPanelToggleButton() {
}
}

View File

@@ -1,44 +0,0 @@
import { injectable } from "inversify";
import { CommonFrontendContribution, CommonMenus, CommonCommands } from "@theia/core/lib/browser";
import { MenuModelRegistry } from "@theia/core";
@injectable()
export class CustomCommonFrontendContribution extends CommonFrontendContribution {
registerMenus(registry: MenuModelRegistry): void {
registry.registerSubmenu(CommonMenus.FILE, 'File');
registry.registerSubmenu(CommonMenus.EDIT, 'Edit');
registry.registerSubmenu(CommonMenus.FILE_SETTINGS_SUBMENU, 'Settings');
registry.registerMenuAction(CommonMenus.EDIT_UNDO, {
commandId: CommonCommands.UNDO.id,
order: '0'
});
registry.registerMenuAction(CommonMenus.EDIT_UNDO, {
commandId: CommonCommands.REDO.id,
order: '1'
});
registry.registerMenuAction(CommonMenus.EDIT_FIND, {
commandId: CommonCommands.FIND.id,
order: '0'
});
registry.registerMenuAction(CommonMenus.EDIT_FIND, {
commandId: CommonCommands.REPLACE.id,
order: '1'
});
registry.registerMenuAction(CommonMenus.EDIT_CLIPBOARD, {
commandId: CommonCommands.CUT.id,
order: '0'
});
registry.registerMenuAction(CommonMenus.EDIT_CLIPBOARD, {
commandId: CommonCommands.COPY.id,
order: '1'
});
registry.registerMenuAction(CommonMenus.EDIT_CLIPBOARD, {
commandId: CommonCommands.PASTE.id,
order: '2'
});
}
}

View File

@@ -1,22 +0,0 @@
import { injectable } from "inversify";
import { EditorWidgetFactory } from "@theia/editor/lib/browser/editor-widget-factory";
import URI from "@theia/core/lib/common/uri";
import { EditorWidget } from "@theia/editor/lib/browser";
@injectable()
export class CustomEditorWidgetFactory extends EditorWidgetFactory {
protected async createEditor(uri: URI): Promise<EditorWidget> {
const icon = await this.labelProvider.getIcon(uri);
return this.editorProvider(uri).then(textEditor => {
const newEditor = new EditorWidget(textEditor, this.selectionService);
newEditor.id = this.id + ':' + uri.toString();
newEditor.title.closable = false;
newEditor.title.label = this.labelProvider.getName(uri);
newEditor.title.iconClass = icon + ' file-icon';
newEditor.title.caption = this.labelProvider.getLongName(uri);
return newEditor;
});
}
}

View File

@@ -1,10 +0,0 @@
import { injectable } from "inversify";
import { FileMenuContribution } from "@theia/workspace/lib/browser";
import { MenuModelRegistry } from "@theia/core";
@injectable()
export class CustomFileMenuContribution extends FileMenuContribution {
registerMenus(registry: MenuModelRegistry) {
}
}

View File

@@ -1,18 +0,0 @@
import { injectable, inject } from "inversify";
import { FrontendApplication } from "@theia/core/lib/browser";
import { ArduinoFrontendContribution } from "../arduino-frontend-contribution";
@injectable()
export class CustomFrontendApplication extends FrontendApplication {
@inject(ArduinoFrontendContribution)
protected readonly frontendContribution: ArduinoFrontendContribution;
protected async initializeLayout(): Promise<void> {
const location = new URL(window.location.href);
const sketchPath = location.searchParams.get('sketch');
if (sketchPath) {
this.frontendContribution.openSketchFiles(decodeURIComponent(sketchPath));
}
}
}

View File

@@ -1,10 +0,0 @@
import { injectable } from "inversify";
import { MonacoEditorMenuContribution } from "@theia/monaco/lib/browser/monaco-menu";
import { MenuModelRegistry } from "@theia/core";
@injectable()
export class CustomMonacoEditorMenuContribution extends MonacoEditorMenuContribution {
registerMenus(registry: MenuModelRegistry) {
}
}

View File

@@ -1,11 +0,0 @@
import {MonacoStatusBarContribution} from '@theia/monaco/lib/browser/monaco-status-bar-contribution';
export class SilentMonacoStatusBarContribution extends MonacoStatusBarContribution {
protected setConfigTabSizeWidget() {
}
protected setLineEndingWidget() {
}
}

View File

@@ -1,10 +0,0 @@
import { injectable } from "inversify";
import { FileNavigatorContribution } from "@theia/navigator/lib/browser/navigator-contribution";
import { FrontendApplication } from "@theia/core/lib/browser";
@injectable()
export class SilentNavigatorContribution extends FileNavigatorContribution {
async initializeLayout(app: FrontendApplication): Promise<void> {
// await this.openView();
}
}

View File

@@ -1,26 +0,0 @@
/********************************************************************************
* Copyright (C) 2017 TypeFox and others.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the Eclipse
* Public License v. 2.0 are satisfied: GNU General Public License, version 2
* with the GNU Classpath Exception which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
********************************************************************************/
import { injectable } from 'inversify';
import { OutlineViewContribution } from '@theia/outline-view/lib/browser/outline-view-contribution';
@injectable()
export class SilentOutlineViewContribution extends OutlineViewContribution {
async initializeLayout(): Promise<void> {
// await this.openView();
}
}

View File

@@ -1,10 +0,0 @@
import { OutputToolbarContribution } from "@theia/output/lib/browser/output-toolbar-contribution";
import { TabBarToolbarRegistry } from "@theia/core/lib/browser/shell/tab-bar-toolbar";
import { injectable } from "inversify";
@injectable()
export class ArduinoOutputToolContribution extends OutputToolbarContribution {
async registerToolbarItems(toolbarRegistry: TabBarToolbarRegistry): Promise<void> {
// register nothing
}
}

View File

@@ -1,15 +0,0 @@
import { injectable } from 'inversify';
import { ProblemContribution } from '@theia/markers/lib/browser/problem/problem-contribution';
import { ProblemStat } from '@theia/markers/lib/browser/problem/problem-manager';
@injectable()
export class SilentProblemContribution extends ProblemContribution {
async initializeLayout(): Promise<void> {
// await this.openView();
}
protected setStatusBarElement(problemStat: ProblemStat) {
}
}

View File

@@ -1,91 +1,117 @@
{
"tokenColors": [
{
"settings": {
"foreground": "#434f54"
}
},
{
"name": "Comments",
"scope": "comment",
"settings": {
"foreground": "#95a5a6cc"
}
},
{
"name": "Keywords Attributes",
"scope": [
"storage",
"support",
"string.quoted.single.c"
],
"settings": {
"foreground": "#00979D"
}
},
{
"name": "literal",
"scope": [
"meta.function.c",
"entity.name.function",
"meta.function-call.c"
],
"settings": {
"foreground": "#D35400"
}
},
{
"name": "punctuation",
"scope": [
"punctuation.section",
"meta.function-call.c",
"meta.block.c",
"meta.function.c",
"entity.name.function.preprocessor.c",
"meta.preprocessor.macro.c"
],
"settings": {
"foreground": "#434f54"
}
},
{
"name": "strings",
"scope": [
"string.quoted.double"
],
"settings": {
"foreground": "#005C5F"
}
},
{
"name": "meta keywords",
"scope": [
"keyword.control",
"meta.preprocessor.c"
],
"settings": {
"foreground": "#728E00"
}
},
{
"name": "numeric preprocessor",
"scope": [
"meta.preprocessor.macro.c",
"constant.numeric.preprocessor.c",
"meta.preprocessor.c"
],
"settings": {
"foreground": "#434f54"
}
}
],
"colors": {
"editor.background": "#FFFFFF",
"editorCursor.foreground": "#434f54",
"editor.foreground": "#434f54",
"editorWhitespace.foreground": "#BFBFBF",
"editor.lineHighlightBackground": "#434f5410",
"editor.selectionBackground": "#ffcb00"
},
"name": "Arduino"
}
"tokenColors": [
{
"settings": {
"foreground": "#434f54"
}
},
{
"name": "Comments",
"scope": "comment",
"settings": {
"foreground": "#95a5a6cc"
}
},
{
"name": "Keywords Attributes",
"scope": [
"storage",
"support",
"string.quoted.single.c"
],
"settings": {
"foreground": "#00979D"
}
},
{
"name": "literal",
"scope": [
"meta.function.c",
"entity.name.function",
"meta.function-call.c"
],
"settings": {
"foreground": "#D35400"
}
},
{
"name": "punctuation",
"scope": [
"punctuation.section",
"meta.function-call.c",
"meta.block.c",
"meta.function.c",
"entity.name.function.preprocessor.c",
"meta.preprocessor.macro.c"
],
"settings": {
"foreground": "#434f54"
}
},
{
"name": "strings",
"scope": [
"string.quoted.double"
],
"settings": {
"foreground": "#005C5F"
}
},
{
"name": "meta keywords",
"scope": [
"keyword.control",
"meta.preprocessor.c"
],
"settings": {
"foreground": "#728E00"
}
},
{
"name": "numeric preprocessor",
"scope": [
"meta.preprocessor.macro.c",
"constant.numeric.preprocessor.c",
"meta.preprocessor.c"
],
"settings": {
"foreground": "#434f54"
}
}
],
"colors": {
"list.highlightForeground": "#006468",
"list.activeSelectionBackground": "#006468",
"editor.background": "#ffffff",
"editorCursor.foreground": "#434f54",
"editor.foreground": "#434f54",
"editorWhitespace.foreground": "#bfbfbf",
"editor.lineHighlightBackground": "#434f5410",
"editor.selectionBackground": "#ffcb00",
"focusBorder": "#4db7bb99",
"menubar.selectionBackground": "#ffffff",
"menubar.selectionForeground": "#212121",
"menu.selectionBackground": "#dae3e3",
"menu.selectionForeground": "#212121",
"editorGroupHeader.tabsBackground": "#f7f9f9",
"button.background": "#4db7bb",
"titleBar.activeBackground": "#006468",
"titleBar.activeForeground": "#ffffff",
"terminal.background": "#000000",
"terminal.foreground": "#e0e0e0",
"dropdown.border": "#ececec",
"dropdown.background": "#ececec",
"activityBar.background": "#ececec",
"activityBar.foreground": "#616161",
"statusBar.background": "#006468",
"secondaryButton.background": "#b5c8c9",
"secondaryButton.hoverBackground": "#dae3e3",
"arduino.branding.primary": "#00979d",
"arduino.branding.secondary": "#b5c8c9",
"arduino.foreground": "#edf1f1",
"arduino.output.foreground": "#FFFFFF",
"arduino.output.background": "#000000"
},
"type": "light",
"name": "Arduino"
}

View File

@@ -0,0 +1,33 @@
import { injectable, inject } from 'inversify';
import { FrontendApplicationContribution, FrontendApplication } from '@theia/core/lib/browser';
import { MainMenuManager } from '../common/main-menu-manager';
@injectable()
export class EditorMode implements FrontendApplicationContribution {
@inject(MainMenuManager)
protected readonly mainMenuManager: MainMenuManager;
protected app: FrontendApplication;
onStart(app: FrontendApplication): void {
this.app = app;
}
get compileForDebug(): boolean {
const value = window.localStorage.getItem(EditorMode.COMPILE_FOR_DEBUG_KEY);
return value === 'true';
}
async toggleCompileForDebug(): Promise<void> {
const oldState = this.compileForDebug;
const newState = !oldState;
window.localStorage.setItem(EditorMode.COMPILE_FOR_DEBUG_KEY, String(newState));
this.mainMenuManager.update();
}
}
export namespace EditorMode {
export const COMPILE_FOR_DEBUG_KEY = 'arduino-compile-for-debug';
}

View File

@@ -0,0 +1,4 @@
<!--Copyright (c) Microsoft Corporation. All rights reserved.-->
<!--Copyright (C) 2019 TypeFox and others.-->
<!--Licensed under the MIT License. See License.txt in the project root for license information.-->
<svg width="28" height="28" viewBox="0 0 28 28" fill="#F6F6F6" xmlns="http://www.w3.org/2000/svg"><g clip-path="url(#clip0)"><path d="M15.1673 18.0687V23.0247C15.1673 23.5637 15.2723 24.5 14.7315 24.5H12.8328V23.3327H14V19.6122L13.7988 19.4022C13.0604 20.0803 12.1008 20.4669 11.0986 20.49C10.0964 20.5132 9.11994 20.1714 8.351 19.5282C7 18.1737 7.13826 16.3327 8.60475 14H4.66726V15.1672H3.50001V13.2685C3.50001 12.7277 4.43626 12.8327 4.97526 12.8327H9.76326L15.1673 18.0687ZM11.6673 5.83275H10.5V4.66725H12.775C13.3123 4.66725 14 4.9245 14 5.4635V9.366L14.8593 10.3862C14.927 9.83979 15.1906 9.33644 15.6013 8.96958C16.0119 8.60271 16.5416 8.39723 17.0923 8.39125C17.2298 8.37945 17.3684 8.39492 17.5 8.43675V5.83275H18.6673V8.88825C18.703 8.99154 18.7618 9.08536 18.8391 9.16265C18.9164 9.23995 19.0102 9.29871 19.1135 9.3345H22.1673V10.5H19.5615C19.593 10.5 19.6105 10.675 19.6105 10.85C19.6058 11.4034 19.4011 11.9365 19.0341 12.3508C18.6671 12.7651 18.1626 13.0326 17.6138 13.104L18.634 14H22.5383C23.0773 14 23.3345 14.6807 23.3345 15.225V17.5H22.1673V16.3327H19.2273L11.6673 8.98275V5.83275ZM14 0C11.2311 0 8.52431 0.821086 6.22202 2.35943C3.91973 3.89776 2.12532 6.08426 1.06569 8.64243C0.00606593 11.2006 -0.271181 14.0155 0.269012 16.7313C0.809205 19.447 2.14258 21.9416 4.10051 23.8995C6.05845 25.8574 8.55301 27.1908 11.2687 27.731C13.9845 28.2712 16.7994 27.9939 19.3576 26.9343C21.9157 25.8747 24.1022 24.0803 25.6406 21.778C27.1789 19.4757 28 16.7689 28 14C28 10.287 26.525 6.72601 23.8995 4.1005C21.274 1.475 17.713 0 14 0V0ZM25.6673 14C25.6692 16.6908 24.7364 19.2988 23.0283 21.378L6.622 4.97175C8.33036 3.57269 10.4009 2.68755 12.5927 2.41935C14.7845 2.15115 17.0074 2.51091 19.0027 3.45676C20.998 4.40262 22.6836 5.89567 23.8635 7.76217C25.0433 9.62867 25.6689 11.7919 25.6673 14ZM2.33276 14C2.33066 11.3091 3.26351 8.70111 4.97176 6.622L21.378 23.03C19.6693 24.4284 17.5987 25.313 15.407 25.5807C13.2153 25.8485 10.9926 25.4884 8.99754 24.5425C7.00244 23.5965 5.31693 22.1036 4.13708 20.2373C2.95722 18.3709 2.33152 16.208 2.33276 14Z" fill="white"/></g><defs><clipPath id="clip0"><rect width="28" height="28" fill="#F6F6F6"/></clipPath></defs></svg>

After

Width:  |  Height:  |  Size: 2.3 KiB

View File

Before

Width:  |  Height:  |  Size: 962 B

After

Width:  |  Height:  |  Size: 962 B

View File

@@ -0,0 +1,70 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!--Generator: Adobe Illustrator 18.1.1, SVG Export Plug-In . SVG Version: 6.00 Build 0)-->
<svg xmlns="http://www.w3.org/2000/svg" xmlns:cc="http://creativecommons.org/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:svg="http://www.w3.org/2000/svg" id="Layer_1" width="198px" height="99px" x="0px" y="0px" enable-background="new 0 0 198 99" version="1.1" viewBox="0 0 198 99" inkscape:version="0.91 r13725" sodipodi:docname="buttons.svg" xml:space="preserve">
<metadata id="metadata327">
<rdf:RDF>
<cc:Work rdf:about="">
<dc:format>
image/svg+xml
</dc:format>
<dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage"/>
<dc:title/>
</cc:Work>
</rdf:RDF>
</metadata>
<defs id="defs325"/>
<sodipodi:namedview id="namedview323" bordercolor="#666666" borderopacity="1" gridtolerance="10" guidetolerance="10" objecttolerance="10" pagecolor="#ffffff" showgrid="false" showguides="true" inkscape:current-layer="Layer_1" inkscape:cx="45.252385" inkscape:cy="36.224987" inkscape:guide-bbox="true" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-height="1000" inkscape:window-maximized="1" inkscape:window-width="1215" inkscape:window-x="65" inkscape:window-y="24" inkscape:zoom="4"/>
<g id="g5" transform="translate(-0.12000084,0)">
<polyline id="polyline9" stroke-miterlimit="10" points="21.453,12.745 15.788,20.571 11.775,16.658 " style="fill:none;stroke:#000000;stroke-width:2.30489993;stroke-miterlimit:10"/>
</g>
<g id="g23" transform="translate(-0.26100159,0)">
<polygon id="polygon27" points="45.412,15.313 49.307,15.313 49.307,11.53 54.701,16.875 49.331,22.245 49.331,18.563 45.412,18.539 " style="fill:#000000"/>
</g>
<g id="g41" transform="translate(-0.54399872,0)">
<polygon id="polygon45" points="114.44,19.083 114.44,15.116 110.586,15.116 116.032,9.621 121.502,15.091 117.751,15.091 117.726,19.083 " style="fill:#000000"/>
<rect id="rect47" width="1" height="1" x="110.511" y="22.193001" style="fill:#000000"/>
<rect id="rect49" width="1" height="1" x="112.518" y="22.193001" style="fill:#000000"/>
<rect id="rect51" width="1" height="1" x="114.517" y="22.193001" style="fill:#000000"/>
<rect id="rect53" width="1" height="1" x="116.525" y="22.193001" style="fill:#000000"/>
<rect id="rect55" width="1" height="1" x="118.524" y="22.193001" style="fill:#000000"/>
<rect id="rect57" width="1" height="1" x="120.531" y="22.193001" style="fill:#000000"/>
</g>
<g id="g59" transform="translate(-0.68600464,0)">
<polygon id="polygon63" points="150.79,9.621 150.79,13.588 154.644,13.588 149.198,19.083 143.728,13.612 147.479,13.613 147.504,9.621 " style="fill:#000000"/>
<rect id="rect65" width="1" height="1" x="143.65199" y="22.193001" style="fill:#000000"/>
<rect id="rect67" width="1" height="1" x="145.66" y="22.193001" style="fill:#000000"/>
<rect id="rect69" width="1" height="1" x="147.659" y="22.193001" style="fill:#000000"/>
<rect id="rect71" width="1" height="1" x="149.666" y="22.193001" style="fill:#000000"/>
<rect id="rect73" width="1" height="1" x="151.666" y="22.193001" style="fill:#000000"/>
<rect id="rect75" width="1" height="1" x="153.673" y="22.193001" style="fill:#000000"/>
</g>
<g id="g149" transform="translate(-0.40299988,0)">
<path id="path151" d="M 87.445,22.097" style="fill:#000000" inkscape:connector-curvature="0"/>
<polygon id="polygon155" points="83.44,10.094 84.441,10.094 88.421,14.079 88.421,15.057 87.445,15.057 83.44,15.057 " style="fill:#000000"/>
<polygon id="polygon157" points="78.404,11.093 78.404,22.097 87.445,22.097 87.445,14.87 88.421,14.87 88.421,23.134 77.399,23.134 77.399,10.094 83.562,10.094 83.568,11.093 " style="fill:#000000"/>
<rect id="rect159" width="0.995" height="0.99599999" x="79.399002" y="12.111" style="fill:#000000"/>
<rect id="rect161" width="0.995" height="0.99599999" x="81.394997" y="12.111" style="fill:#000000"/>
<rect id="rect163" width="0.995" height="0.99599999" x="79.399002" y="14.103" style="fill:#000000"/>
<rect id="rect165" width="0.995" height="0.99599999" x="81.394997" y="14.103" style="fill:#000000"/>
<rect id="rect167" width="0.995" height="0.99599999" x="79.399002" y="16.115999" style="fill:#000000"/>
<rect id="rect169" width="0.995" height="0.99599999" x="81.394997" y="16.115999" style="fill:#000000"/>
<rect id="rect171" width="0.995" height="0.99599999" x="83.403" y="16.115999" style="fill:#000000"/>
<rect id="rect173" width="0.995" height="0.99599999" x="85.400002" y="16.115999" style="fill:#000000"/>
<rect id="rect175" width="0.995" height="0.99599999" x="79.399002" y="18.118" style="fill:#000000"/>
<rect id="rect177" width="0.995" height="0.99599999" x="81.394997" y="18.118" style="fill:#000000"/>
<rect id="rect179" width="0.995" height="0.99599999" x="79.399002" y="20.132" style="fill:#000000"/>
<rect id="rect181" width="0.995" height="0.99599999" x="81.394997" y="20.132" style="fill:#000000"/>
<rect id="rect183" width="0.995" height="0.99599999" x="83.403" y="18.118" style="fill:#000000"/>
<rect id="rect185" width="0.995" height="0.99599999" x="85.400002" y="18.118" style="fill:#000000"/>
<rect id="rect187" width="0.995" height="0.99599999" x="83.403" y="20.132" style="fill:#000000"/>
<rect id="rect189" width="0.995" height="0.99599999" x="85.400002" y="20.132" style="fill:#000000"/>
</g>
<g id="g275" transform="translate(-0.82800293,0)">
<rect id="rect279" width="0.99900001" height="0.99800003" x="187.819" y="16.101" style="fill:#000000"/>
<rect id="rect281" width="0.99900001" height="0.99800003" x="189.825" y="16.101" style="fill:#000000"/>
<rect id="rect283" width="0.99900001" height="0.99800003" x="174.83299" y="16.101" style="fill:#000000"/>
<circle id="circle285" cx="181.80299" cy="16.101" r="4.0900002" stroke-miterlimit="10" style="fill:none;stroke:#000000;stroke-width:1.95439994;stroke-miterlimit:10"/>
<rect id="rect287" width="2.6800001" height="4.4229999" x="175.895" y="18.427999" style="fill:#000000" transform="matrix(0.6915,0.7224,-0.7224,0.6915,69.5827,-121.6599)"/>
<rect id="rect289" width="2.0280001" height="1.9960001" x="180.789" y="15.103" style="fill:#000000"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 6.4 KiB

View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0" y="0" width="24" height="24" viewBox="0, 0, 24, 24">
<g>
<path d="M16.2 8.1c0-4.5-3.6-8.1-8.1-8.1S0 3.6 0 8.1s3.6 8.1 8.1 8.1c1.9 0 3.7-.7 5.1-1.8l5.6 5.6 1.4-1.4-5.7-5.6c1.1-1.4 1.7-3.1 1.7-4.9zm-14.4 0c0-3.5 2.8-6.3 6.3-6.3s6.3 2.8 6.3 6.3-2.8 6.3-6.3 6.3c-3.5.1-6.3-2.8-6.3-6.3z" />
<rect x="7.1" y="7.1" width="2" height="2" />
<rect x="17.2" y="7.1" width="2" height="2" />
<rect x="20.3" y="7.1" width="2" height="2" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 711 B

View File

@@ -1,63 +0,0 @@
import { injectable } from 'inversify';
import { LanguageGrammarDefinitionContribution, TextmateRegistry } from '@theia/monaco/lib/browser/textmate';
@injectable()
export class ArduinoLanguageGrammarContribution implements LanguageGrammarDefinitionContribution {
static INO_LANGUAGE_ID = 'ino';
registerTextmateLanguage(registry: TextmateRegistry) {
monaco.languages.register({
id: ArduinoLanguageGrammarContribution.INO_LANGUAGE_ID,
extensions: ['.ino'],
aliases: ['INO', 'Ino', 'ino'],
});
monaco.languages.setLanguageConfiguration(ArduinoLanguageGrammarContribution.INO_LANGUAGE_ID, this.configuration);
const inoGrammar = require('../../../data/ino.tmLanguage.json');
registry.registerTextmateGrammarScope('source.ino', {
async getGrammarDefinition() {
return {
format: 'json',
content: inoGrammar
};
}
});
registry.mapLanguageIdToTextmateGrammar(ArduinoLanguageGrammarContribution.INO_LANGUAGE_ID, 'source.ino');
}
private readonly configuration: monaco.languages.LanguageConfiguration = {
comments: {
lineComment: '//',
blockComment: ['/*', '*/'],
},
brackets: [
['{', '}'],
['[', ']'],
['(', ')']
],
autoClosingPairs: [
{ open: '[', close: ']' },
{ open: '{', close: '}' },
{ open: '(', close: ')' },
{ open: '\'', close: '\'', notIn: ['string', 'comment'] },
{ open: '"', close: '"', notIn: ['string'] },
{ open: '/*', close: ' */', notIn: ['string'] }
],
surroundingPairs: [
{ open: '{', close: '}' },
{ open: '[', close: ']' },
{ open: '(', close: ')' },
{ open: '"', close: '"' },
{ open: '\'', close: '\'' },
],
folding: {
markers: {
start: new RegExp('^\\s*#pragma\\s+region\\b'),
end: new RegExp('^\\s*#pragma\\s+endregion\\b')
}
}
};
}

View File

@@ -1,50 +0,0 @@
import * as React from 'react';
import { ComponentListItem } from '../components/component-list/component-list-item';
export class LibraryComponentListItem extends ComponentListItem {
render(): React.ReactNode {
const { item } = this.props;
const name = <span className={'name'}>{item.name}</span>;
const author = <span className={'author'}>by {item.author}</span>;
const installedVersion = !!item.installedVersion && <div className={'version-info'}>
<span className={'version'}>Version {item.installedVersion}</span>
<span className={'installed'}>INSTALLED</span>
</div>;
const summary = <div className={'summary'}>{item.summary}</div>;
const moreInfo = !!item.moreInfoLink && <a href={item.moreInfoLink} onClick={this.onClick}>More info</a>;
const install = this.props.install && item.installable && !item.installedVersion &&
<button className={'install'} onClick={this.install.bind(this, item)}>INSTALL</button>;
const versions = (() => {
const { availableVersions } = item;
if (availableVersions.length === 0) {
return undefined;
} else if (availableVersions.length === 1) {
return <label>{availableVersions[0]}</label>
} else {
return <select>{item.availableVersions.map(version => <option value={version} key={version}>{version}</option>)}</select>;
}
})();
return <div className={'component-list-item noselect'}>
<div className={'header'}>
<span>{name} {author}</span>
{installedVersion}
</div>
<div className={'content'}>
{summary}
</div>
<div className={'info'}>
{moreInfo}
</div>
<div className={'footer'}>
{install}
{versions}
</div>
</div>;
}
}

View File

@@ -1,17 +0,0 @@
import * as React from 'react';
import { ArduinoComponent } from '../../common/protocol/arduino-component';
import { ComponentList } from '../components/component-list/component-list';
import { LibraryComponentListItem } from './library-component-list-item';
export class LibraryComponentList extends ComponentList {
createItem(item: ArduinoComponent): React.ReactNode {
return <LibraryComponentListItem
key={item.name}
item={item}
windowService={this.props.windowService}
install={this.props.install}
/>
}
}

View File

@@ -1,110 +0,0 @@
import * as React from 'react';
import { FilterableListContainer } from '../components/component-list/filterable-list-container';
import { LibraryComponentList } from './library-component-list';
export class LibraryFilterableListContainer extends FilterableListContainer {
constructor(props: Readonly<FilterableListContainer.Props>) {
super(props);
this.state = {
filterText: '',
items: [],
props: {
topic: this.topics[0],
type: this.types[0]
}
};
}
protected renderSearchFilter(): React.ReactNode {
const types = this.types.map(type => <option value={type} key={type}>{type}</option>);
let type = this.types[0];
if (this.state.props) {
const currentType = this.types.find(t => t === this.state.props!.type) || this.types[0];
if (currentType) {
type = currentType;
}
}
const topics = this.topics.map(topic => <option value={topic} key={topic}>{topic}</option>);
let topic = this.topics[0];
if (this.state.props) {
const currentTopic = this.topics.find(t => t === this.state.props!.topic) || this.topics[0];
if (currentTopic) {
topic = currentTopic;
}
}
return <div className={'search-filters'}>
<div className={'filter'}>
<div className={'title'} style={{ minWidth: '32.088px' }}>Type</div> {/** TODO: do `minWidth` better! */}
<select
value={type}
onChange={this.onTypeChange}>
{types}
</select>
</div>
<div className={'filter'}>
<div className={'title'}>Topic</div>
<select
value={topic}
onChange={this.onTopicChange}>
{topics}
</select>
</div>
</div>
}
protected onTypeChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
const type = event.target.value;
const props = { ...(this.state.props || {}), ...{ type } };
this.setState({
props
});
}
protected onTopicChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
const topic = event.target.value;
const props = { ...(this.state.props || {}), ...{ topic } };
this.setState({
props
});
}
protected renderComponentList(): React.ReactNode {
return <LibraryComponentList
items={this.state.items}
install={this.install.bind(this)}
windowService={this.props.windowService}
resolveContainer={this.props.resolveContainer}
/>
}
private get topics(): string[] {
return [
'All',
'Communication',
'Data Processing',
'Data Storage',
'Device Control',
'Display',
'Other',
'Sensor',
'Signal Input/Output',
'Timing',
'Uncategorized'
];
}
private get types(): string[] {
return [
'All',
'Updatable',
'Installed',
'Arduino',
'Partner',
'Recommended',
'Contributed',
'Retired'
];
}
}

View File

@@ -0,0 +1,36 @@
import { injectable, postConstruct, inject } from 'inversify';
import { LibraryPackage, LibraryService } from '../../common/protocol/library-service';
import { ListWidget } from '../widgets/component-list/list-widget';
import { ListItemRenderer } from '../widgets/component-list/list-item-renderer';
@injectable()
export class LibraryListWidget extends ListWidget<LibraryPackage> {
static WIDGET_ID = 'library-list-widget';
static WIDGET_LABEL = 'Library Manager';
constructor(
@inject(LibraryService) protected service: LibraryService,
@inject(ListItemRenderer) protected itemRenderer: ListItemRenderer<LibraryPackage>) {
super({
id: LibraryListWidget.WIDGET_ID,
label: LibraryListWidget.WIDGET_LABEL,
iconClass: 'library-tab-icon',
searchable: service,
installable: service,
itemLabel: (item: LibraryPackage) => item.name,
itemRenderer
});
}
@postConstruct()
protected init(): void {
super.init();
this.toDispose.pushAll([
this.notificationCenter.onLibraryInstalled(() => this.refresh(undefined)),
this.notificationCenter.onLibraryUninstalled(() => this.refresh(undefined)),
]);
}
}

View File

@@ -1,88 +0,0 @@
import * as React from 'react';
import { inject, injectable, postConstruct } from 'inversify';
import { Message } from '@phosphor/messaging';
import { Deferred } from '@theia/core/lib/common/promise-util';
import { MaybePromise } from '@theia/core/lib/common/types';
import { ReactWidget } from '@theia/core/lib/browser/widgets/react-widget';
import { WindowService } from '@theia/core/lib/browser/window/window-service';
import { LibraryFilterableListContainer } from './library-filterable-list-container';
import { LibraryService } from '../../common/protocol/library-service';
@injectable()
export class LibraryListWidget extends ReactWidget {
static WIDGET_ID = 'library-list-widget';
static WIDGET_LABEL = 'Library Manager';
@inject(LibraryService)
protected readonly libraryService: LibraryService;
@inject(WindowService)
protected readonly windowService: WindowService;
/**
* Do not touch or use it. It is for setting the focus on the `input` after the widget activation.
*/
protected focusNode: HTMLElement | undefined;
protected readonly deferredContainer = new Deferred<HTMLElement>();
constructor() {
super();
this.id = LibraryListWidget.WIDGET_ID
this.title.label = LibraryListWidget.WIDGET_LABEL;
this.title.caption = LibraryListWidget.WIDGET_LABEL
this.title.iconClass = 'library-tab-icon';
this.title.closable = true;
this.addClass('arduino-list-widget');
this.node.tabIndex = 0; // To be able to set the focus on the widget.
this.scrollOptions = {
suppressScrollX: true
}
}
@postConstruct()
protected init(): void {
this.update();
}
protected getScrollContainer(): MaybePromise<HTMLElement> {
return this.deferredContainer.promise;
}
protected onActivateRequest(msg: Message): void {
super.onActivateRequest(msg);
(this.focusNode || this.node).focus();
}
protected onUpdateRequest(msg: Message): void {
super.onUpdateRequest(msg);
this.render();
}
protected onFocusResolved = (element: HTMLElement | undefined) => {
this.focusNode = element;
}
render(): React.ReactNode {
return <LibraryFilterableListContainer
resolveContainer={this.deferredContainer.resolve}
resolveFocus={this.onFocusResolved}
service={this.libraryService}
windowService={this.windowService}
/>;
}
}
export namespace ListWidget {
/**
* Props for customizing the abstract list widget.
*/
export interface Props {
readonly id: string;
readonly title: string;
readonly iconClass: string;
}
}

View File

@@ -3,7 +3,7 @@ import { FrontendApplicationContribution } from '@theia/core/lib/browser/fronten
import { AbstractViewContribution } from '@theia/core/lib/browser/shell/view-contribution';
import { MenuModelRegistry } from '@theia/core';
import { LibraryListWidget } from './library-list-widget';
import { ArduinoMenus } from '../arduino-frontend-contribution';
import { ArduinoMenus } from '../menu/arduino-menus';
@injectable()
export class LibraryListWidgetFrontendContribution extends AbstractViewContribution<LibraryListWidget> implements FrontendApplicationContribution {
@@ -14,22 +14,23 @@ export class LibraryListWidgetFrontendContribution extends AbstractViewContribut
widgetName: LibraryListWidget.WIDGET_LABEL,
defaultWidgetOptions: {
area: 'left',
rank: 600
rank: 700
},
toggleCommandId: `${LibraryListWidget.WIDGET_ID}:toggle`,
toggleKeybinding: 'ctrlcmd+shift+l'
toggleKeybinding: 'CtrlCmd+Shift+I'
});
}
initializeLayout(): void {
// NOOP
async initializeLayout(): Promise<void> {
this.openView();
}
registerMenus(menus: MenuModelRegistry): void {
if (this.toggleCommand) {
menus.registerMenuAction(ArduinoMenus.SKETCH, {
menus.registerMenuAction(ArduinoMenus.TOOLS__MAIN_GROUP, {
commandId: this.toggleCommand.id,
label: 'Manage Libraries...'
label: 'Manage Libraries...',
order: '3'
});
}
}

Some files were not shown because too many files have changed in this diff Show More