Compare commits

..

309 Commits

Author SHA1 Message Date
Akos Kitta
06ad7d143c fix: name of translation (UA) module
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-08-29 08:22:39 +02:00
github-actions[bot]
b78c4621fc Updated translation files 2023-08-28 11:24:10 +02:00
Akos Kitta
e08439b6a4 fix: missing app icon for AppImage on Linux (#2190)
Closes #131

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-08-24 17:04:58 +02:00
Akos Kitta
e03e5eb603 chore: bump the version to 2.2.0
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-08-24 17:01:15 +02:00
Akos Kitta
b723951d78 chore(deps): Use arduino-cli@0.34.0
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-08-24 10:18:47 +02:00
Akos Kitta
ea2c54bff0 chore(deps): Use arduino-fwuploader@2.4.0
Ref: arduino/arduino-fwuploader#211
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-08-24 10:18:47 +02:00
Akos Kitta
5fd02b9fd7 fix: falsy context menu handlerId
The very first context menu item with ID `0` has not had a click handler

Ref: eclipse-theia/theia#12500
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-08-22 08:51:00 +02:00
per1234
10b38820bc Generalize name of "Firmware Updater"
Some Arduino boards have a supplemental hardware module that provides functionality separate from the primary
microcontroller the sketch program runs on.

Enhancements or fixes to the firmware that runs on these supplemental modules may be made over time so it is important
for the users of these boards to have an easy way to update the firmware. Arduino IDE provides a tool for doing this.

At the time the tool was created, the poor choice was made to include the names of the specific modules it supported at
the time in the tool's name. As was inevitable, that list has changed, rendering the tool name no longer accurate.

The immediate problem is that support has been added for updating the "bridge" and radio module on the UNO R4 WiFi. That
module is neither a "WiFi101" nor a "NINA", so the tool name does not reflect the support for the UNO R4 WiFi.

More significant changes in the supported modules are under way and will be introduced in the next release:

- Dropping support for the "WiFi101" module
- Adding support for the module on the Portenta C33 board

Rather than attempting to maintain a regularly changing and overly verbose name that includes the list of every
supported module, it is better to use a name for the tool that only describes its general purpose, leaving the task of
describing the specific supported modules to the documentation.
2023-08-21 08:44:10 -07:00
per1234
ea91904f00 Do full run of "Arduino IDE" workflow on tag push
The project was recently switched to using a "trunk-based" development strategy. This necessitated some adjustments to
the configuration of the GitHub Actions workflows in order to ensure the CI system could be used to effectively validate
the project at the state staged for release in the release branch.

A `run-determination` job was added to the workflow. This job determines whether the conditions under which the workflow
was triggered indicate that the rest of the jobs in the workflow should be run.

A validation workflow should run fully under any of the following conditions:

- The trigger event was something other than a branch creation
- The trigger event was a release branch creation

Since the project is fully validated prior to a release, running the workflow when triggered by a release tag is
pointless (and even harmful in some specific standardized workflows not currently used in this repository), so (even if
for no other reason than efficiency) verification workflows are configured to not run under these conditions.

The standardized Arduino tooling workflows follow a modular design where each workflow has a narrow scope of purpose.
That path was not taken by those who set up the infrastructure for this repository. They instead created a single
massive monolithic "Arduino IDE" workflow that performs many unrelated operations under various conditions. This workflow generates
releases in addition to doing validation. Even though it is pointless to run the workflow's validation operations when
the workflow is triggered by a release tag, it is essential to run it for the release generation.

Previously, the code used in the "Arduino IDE" workflow's `run-determination` job was configured as appropriate for a
verification workflow. This meant that a release would not be generated on push of a release tag as intended. The bug is
fixed by adjusting the code to do a full run of the workflow when triggered by a release tag.
2023-08-20 14:39:44 -07:00
Akos Kitta
57fa18b940 fix: do not start obsolete daemon watcher process
Before arduino/arduino-cli#488, IDE2 required a way to stop the daemon
process if the parent (backend) process crashed. However, this mechanism
is no longer necessary as the CLI daemon process is not actually a true
daemon process.

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-08-20 21:54:13 +02:00
Akos Kitta
2aae9e0a07 fix: execute the Arduino CLI without a shell
Closes arduino/arduino-ide#2112
Ref: arduino/arduino-ide#2067

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-08-20 21:54:13 +02:00
Akos Kitta
9a99957e73 fix: incorrect certificate flashing command string (#2181)
Use a `string` array of command flags instead of the concatenated final
`string` command.

Ref: arduino/arduino-ide#2067
Closes arduino/arduino-ide#2179

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-08-20 21:53:43 +02:00
Akos Kitta
b25665561e fix: handle UNKNOWN code on syscall: 'stat'
Closes #2166

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-08-20 17:15:00 +02:00
Akos Kitta
420d31ff4b chore(cli): pin version to 0.34.0-rc.1
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-08-20 17:14:29 +02:00
Akos Kitta
db01efead3 fix: expand boards if available on detected port
moved the board inference logic from UI to  model

Closes #2175

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-08-20 17:14:29 +02:00
dependabot[bot]
5a76be306a build(deps): Bump svenstaro/upload-release-action from 2.6.1 to 2.7.0
Bumps [svenstaro/upload-release-action](https://github.com/svenstaro/upload-release-action) from 2.6.1 to 2.7.0.
- [Release notes](https://github.com/svenstaro/upload-release-action/releases)
- [Changelog](https://github.com/svenstaro/upload-release-action/blob/master/CHANGELOG.md)
- [Commits](https://github.com/svenstaro/upload-release-action/compare/2.6.1...2.7.0)

---
updated-dependencies:
- dependency-name: svenstaro/upload-release-action
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-18 20:53:13 -07:00
Akos Kitta
69ae38effa feat: simplify board and port handling (#2165)
Use Arduino CLI revision `38479dc`

Closes #43
Closes #82
Closes #1319
Closes #1366
Closes #2143
Closes #2158

Ref: 38479dc706

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-08-18 14:42:50 +02:00
Akos Kitta
9a6a457bc4 chore(deps): Updated to Theia 1.39.0 (#2144)
- update Theia to `1.39.0`,
 - remove the application packager and fix the security vulnerabilities,
 - bundle the backed application with `webpack`, and
 - enhance the developer docs.

Co-authored-by: Akos Kitta <a.kitta@arduino.cc>
Co-authored-by: per1234 <accounts@perglass.com>

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-08-14 12:12:05 +02:00
per1234
144df893d0 Clean localization data files before pulling from Transifex
The localization of the UI strings specific to the Arduino IDE application is done via the Transifex localization
platform. A scheduled workflow pulls the data from Transifex weekly and submits a pull request for the updates.

Previously, the script used to pull the data did not clean the data files before pulling. This meant that a vestigial
file would accumulate in the repository whenever a language was removed from the Transifex project.

The accumulation is avoided by deleting the data files for the locales managed on Transifex (all locales other than the
source English locale) before downloading the data from Transifex.
2023-07-26 01:10:25 -07:00
coby2023t
e17472ef07 Add 中文(繁體) ("Chinese (Traditional)") localization (#2151)
This will add a "中文(繁體)" option to the "Language" menu in the Arduino IDE preferences, which will cause the strings
in the IDE UI to be localized for "Chinese (Traditional)".

In addition to the translations for the strings that originate from the Eclipse Theia IDE framework provided by the
"Chinese (Traditional) Language Pack for Visual Studio Code" language pack, this will also utilize the translations of
the Arduino IDE-specific strings contributed by the community.
2023-07-25 23:52:04 -07:00
dankeboy36
f6a43254f5 feat: can dock the monitor widget to the "right"
Added a new preference (`arduino.monitor.dockPanel`) to specify the
location of the application shell where the _Serial Monitor_ widget
resides. The possible values are `"bottom"` and `"right"`. The default\
value is the `"bottom"`.

The dock panel is per application and not per workspace or window.
However, advanced users can create the `./.vscode/settings.json` and
configure per sketch preference.

Signed-off-by: dankeboy36 <dankeboy36@gmail.com>
2023-07-13 09:42:47 +02:00
Akos Kitta
94d2962985 fix: include all log args in the log message
- In the bundled application, the customized logger that writes the log
files bogusly includes only the first message fragment in the log
message. This PR ensures all message fragments are included in the final
message before it is printed to the console/terminal and persisted to
the rotating log files.
 - Includes messages with `debug` severity in the log.
 - Disables the ANSI coloring in the CLI daemon log by adding the
`NO_COLOR=true` environment variable to the spawned CLI daemon process.
 - Trims trailing line ending of the daemon log.

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-07-07 17:28:16 +02:00
Akos Kitta
95fdc593ed chore(version): updated the version to 2.1.2
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-07-05 20:00:34 +02:00
dankeboy36
954fee41a0 fix(terminal): split-terminal visibility
Removed the toolbar contribution from the UI.

Ref: eclipse-theia/theia#12626/
Signed-off-by: dankeboy36 <dankeboy36@gmail.com>
2023-07-05 16:58:44 +02:00
dankeboy36
0bcb182ec0 fix(terminal): widget flickering on resize
Ref: eclipse-theia/theia#12587
Signed-off-by: dankeboy36 <dankeboy36@gmail.com>
2023-07-05 16:58:44 +02:00
dankeboy36
42d017e876 feat: expose Arduino state to VS Code extensions
- Update a shared state on fqbn, port, sketch path, and etc. changes.
VS Code extensions can access it and listen on changes.
 - Force VISX activation order: API VSIX starts first.

Signed-off-by: dankeboy36 <dankeboy36@gmail.com>
2023-07-05 16:58:44 +02:00
Akos Kitta
c66b720509 chore(cli): Bumped the CLI version to 0.33.1
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-07-05 09:31:23 +02:00
Akos Kitta
a5c9735619 Revert "Revert "chore(cli): Bumped the CLI version to 0.33.0""
This reverts commit d0bce15f8b.

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-07-05 09:31:23 +02:00
per1234
6e18dca644 Adjust release procedure and CI system for "trunk-based" development strategy
Previously, releases were always made from a point in the revision history of the `main` branch (typically the tip of
the branch at the time of the release). Although the simplicity of this approach is nice, it can be limiting in some
cases. For this reason, the project is switching to using a "trunk-based" development strategy, as described here:

https://trunkbaseddevelopment.com/

This approach allows making releases at any time that consist of the arbitrary subset of revisions suitable for shipping
to the users at that time. The commits that should be included in the release are cherry-picked to a release branch and
the tag created on that branch.

This means that:

- PRs can be merged to the `main` branch as soon as they have passed review rather than having to postpone the merge of
  changes that are not ready to be included in the next release.
- Releases don't need to be postponed if the prior revision history on the `main` branch contains changes that are not
  ready to be included in the release.

The documented release procedure must be adjusted to reflect the new development strategy.

CI System Adjustments
---------------------

The status of the GitHub Actions workflows should be evaluated before making a release. However, this is not so simple as
checking the status of the commit at the tip of the release branch. The reason is that, for the sake of efficiency, the
workflows are configured to run only when the processes are relevant to the trigger event (e.g., no need to run unit
tests for a change to the readme).

In the case of the default branch, you can simply set the workflow runs filter to that branch and then check the result
of the latest run of each workflow of interest. However, that was not possible to do with the release branch since it
might be that the workflow was never run in that branch. The status of the latest run of the workflow in the default
branch might not match the status for the release branch if the release branch does not contain the full history.

For this reason, it will be helpful to trigger all relevant workflows on the creation of a release branch. This will
ensure that each of those workflows will always have at least one run in the release branch. Subsequent commits pushed to
the branch can run based on their usual trigger filters and the status of the latest run of each workflow in the branch
will provide an accurate indication of the state of that branch.

Branches are created for purposes other than releases, most notably feature branches to stage work for a pull request.
Due to the comprehensive nature of this project's CI system, it would not be convenient or efficient to fully run all CI
workflows on the creation of every feature branch.

Unfortunately, GitHub Actions does not support filters on the `create` event of branch creation like it does for the
`push` and `pull_request` events. There is support for a `branches` filter of the `push` event, but that filter is an
"AND" to the `paths` filter while this application requires an "OR". For this reason, the workflows must be triggered by
the creation of any branch. The unwanted job runs are prevented by adding a `run-determination` job with the branch
filter handled by Bash commands. The other jobs of the workflow use this `run-determination` job as a dependency, only
running when it indicates they should via a job output. Because this minimal `run-determination` job runs very quickly,
it is roughly equivalent to the workflow having been skipped entirely for non-release branch creations.
2023-06-30 11:31:47 -07:00
Akos Kitta
f3b99b08da chore(cli): Bumped the CLI version to 0.32.3
Ref: arduino/arduino-cli#2234
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-06-30 16:38:48 +02:00
Akos Kitta
d0bce15f8b Revert "chore(cli): Bumped the CLI version to 0.33.0"
This reverts commit 0fbd1fbe85.
2023-06-30 14:02:08 +02:00
Andrew Sepulveda
d79bc0d083 add linux-arm64 to download-ls (#2078) 2023-06-12 13:45:58 +02:00
Akos Kitta
8f8b46fa6f fix: warn user when IDE cannot save the sketch
Happens when the IDE2 backend process crashes, and the communication
drops between the client and the server.

Closes #2081

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-06-09 12:11:31 +02:00
dependabot[bot]
d1fa6d4f3b build(deps): Bump svenstaro/upload-release-action from 2.5.0 to 2.6.1
Bumps [svenstaro/upload-release-action](https://github.com/svenstaro/upload-release-action) from 2.5.0 to 2.6.1.
- [Release notes](https://github.com/svenstaro/upload-release-action/releases)
- [Changelog](https://github.com/svenstaro/upload-release-action/blob/master/CHANGELOG.md)
- [Commits](https://github.com/svenstaro/upload-release-action/compare/2.5.0...2.6.1)

---
updated-dependencies:
- dependency-name: svenstaro/upload-release-action
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-06-09 00:02:33 -07:00
Akos Kitta
4af488b05e fix: relaxed saveAll if no Internet connection
The previous logic has incorrectly bailed the save when there is no
Internet connection. The corrected logic disallows saving files if there
is no connection between the frontend and the backend.

Ref: cff2c95684
Closes #2079

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-06-08 08:53:47 +02:00
Akos Kitta
db0049d635 fix: omit port from upload request when not set
Previously, if the `port` was not set in IDE2, the compile request
object has been created with an empty port object (`{}`). From now on,
if the port is not specified, IDE2 will create a compile request with
the default `null` `port` value.

Closes #2089

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-06-06 19:40:03 +02:00
Akos Kitta
0fbd1fbe85 chore(cli): Bumped the CLI version to 0.33.0
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-06-06 13:03:46 +02:00
Akos Kitta
9d2297c684 fix: removed unsafe shell when executing process
Ref: PNX-3671

Co-authored-by: per1234 <accounts@perglass.com>
Co-authored-by: Akos Kitta <a.kitta@arduino.cc>

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-06-06 11:39:37 +02:00
Akos Kitta
e47fb2e651 fix: remove setting unsafe innerHTML
As it is vulnerable to stored Cross-Site Scripting.

Ref: PNX-3669
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-05-16 10:57:17 +02:00
Akos Kitta
ee43a12eb7 fix: show no errors if users cancel lib install
Throwing and catching a `UserAbortError` is part of the natural flow.

Closes #2063

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-05-16 10:56:39 +02:00
Akos Kitta
31deeebb49 test: use raw core index-update for the tests
It should make integration tests more resilient on the Windows CI.

From now on, tests are not starting a daemon to initialize the
`directories.data` folder for the test suites but rely on the raw
command. It is required to avoid spawning the discovery processes, which
cannot be terminated on Windows while the daemon is up and running.

Closes #2059

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-05-12 09:40:42 +02:00
Akos Kitta
117b2a4fc7 fix: do not enqueue write operations on conflict
Closes #2051

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-05-11 11:16:49 +02:00
Akos Kitta
278dd4ba87 fix: show notification if lib/core install failed
Closes #621

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-05-11 10:03:56 +02:00
Akos Kitta
36e2092398 build: use execa for the packager
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-05-09 17:37:24 +02:00
Akos Kitta
33ab2a6955 build: use execFileSync for npm scripts
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-05-09 17:37:24 +02:00
Akos Kitta
192aac5a81 chore: updated to Theia 1.37.0
- Updated `@theia/*` to `1.37.0`.
 - Fixed all `yarn audit` security vulnerabilities.
 - Updated to `electron@23.2.4`:
   - `contextIsolation` is `true`,
   - `nodeIntegration` is `false`, and the
   - `webpack` target is moved from `electron-renderer` to `web`.
 - Updated to `typescript@4.9.3`.
 - Updated the `eslint` plugins.
 - Added the new `Light High Contrast` theme to the IDE2.
 - High contrast themes use Theia APIs for style adjustments.
 - Support for ESM modules: `"moduleResolution": "node16"`.
 - Node.js >= 16.14 is required.
 - VISX langage packs were bumped to `1.70.0`.
 - Removed undesired editor context menu items. (Closes #1394)

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-05-09 17:37:24 +02:00
Akos Kitta
964ea3bc0c fix: copy when punctuation marks in sketch path
Changed the `source` and `cwd` args to avoid accidentally creating an
invalid `glob` patterns when doing the brace expansion by `cpy`.

Closes #2043

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-05-06 14:32:13 +02:00
Akos Kitta
e6828f86d7 fix: do not exclude cloud sketch diagnostics
PROEDITOR-50: error markers have been disabled for built-ins (daedae1).
Relaxed the error marker filtering for cloud sketches.

Closes #669

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-05-05 14:15:42 +02:00
Akos Kitta
51f69f6a59 test: gRPC core client init integration test
- Copied the env-variable server from Theia and made it possible to
customize it for the tests. Each test has its own `data` folder.
 - Relaxed the primary package and library index error detection.
This should make the init error detection locale independent.
 - Kill the daemon process subtree when stopping the daemon.

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-05-03 15:38:17 +02:00
Akos Kitta
097c92d904 fix: reduced unnecessary GET /sketches request
Ref: #1849

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-04-24 09:47:13 +02:00
Muhammad Zaheer
b451e2db8c Corrected library.properties assignment w.r.t description and summary
Ref: arduino/arduino-ide#1611
2023-04-21 14:43:14 +02:00
per1234
b3b94948a3 Document 3rd party theme installation in "Advanced Usage"
Arduino IDE comes with a selection of officially maintained and supported built-in themes:

- Light
- Dark
- High Contrast

Although these three should be sufficient for most users, some users may have other requirements or preferences for the
Arduino IDE UI theming. Fortunately, because it is built on the Eclipse Theia IDE framework, Arduino IDE supports VS
Code theme extensions. This makes a large variety of 3rd party themes available to the user, and even the ability to
create custom themes.

Instructions for installing VS Code theme extensions are here added to the "Advanced Usage" document hosted in the
repository.
2023-04-20 11:11:24 -07:00
Akos Kitta
80afd382ad chore: Updated to the next version after release.
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-04-20 17:15:55 +02:00
per1234
2c74ad6437 Don't upload "channel update info files" related to manual builds to S3 on release
Arduino IDE offers an update to the user when a newer version is available. The availability of an update is determined
by comparing the user's IDE version against data file ("channel update info file") stored on Arduino's download server.

These "channel update info files" are automatically generated by the build workflow.

Previously the release process was fully automated, including the upload of the "channel update info files" to the
server.

As a temporary workaround for limitations of the GitHub Actions runner machines used to produce the automated builds,
some release builds are now produced manually:

- Linux build (because the Ubuntu 18.04 runner was shut down and newer runner versions produce builds incompatible with
  older Linux versions)
- macOS Apple Silicon build (because GitHub hosted Apple Silicon runners are not available)

The automatic upload of the "channel update info files" produced by the build workflow is problematic because if users
receive update offers before the "channel update info files" are updated for the manually produced builds, they can
receive an update to a different build than intended:

- Users of older Linux versions would update to a build that won't start on their machine
- macOS Apple Silicon users would update to macOS x86 build that is less performant on their machine

For this reason, the build workflow is adjusted to no longer upload the Linux and macOS "channel update info files" to
the download server on release. These files will now be manually uploaded after they have been updated to provide the
manually produced builds.

This workaround will be reverted once a fully automated release system is regained.
2023-04-18 23:50:14 -07:00
Akos Kitta
9fff553f1a chore: Prepared for the 2.1.0 release
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-04-17 09:30:59 +02:00
github-actions[bot]
4c2f0fb841 Updated translation files 2023-04-17 08:31:30 +02:00
Akos Kitta
54f210d4de fix: try fetch the sketch by path if not in the cache
The sketch cache might be empty, when trying to generate
the secrets include in the main sketch file from the
`secrets` property.

Closes #1999

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-04-17 08:23:30 +02:00
Akos Kitta
5540170341 feat: removed the non official themes from the UI
Closes #1283
Ref eclipse-theia/theia#11151

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-04-14 13:42:40 +02:00
Akos Kitta
7cc252fc36 fix: location of possible drop-in folder for VSIX
Closes #1851

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-04-14 13:42:40 +02:00
Akos Kitta
cb2a371263 fix: update themeId settings after theme change
In Theia, the theme ID is not always in sync with the persisted
`workbench.colorTheme` preference value. For example, one can preview a
theme with the `CtrlCmd+K` + `CtrlCmd+T` key chords. On quick pick
selection change events, the theme changes, but the change is persisted
only on accept (user presses `Enter`).

IDE2 has its own way of showing and managing different settings in the
UI. When the theme is changed from outside of the IDE2's UI, the model
could get out of sync. This PR ensures that on `workbench.colorTheme`
preference change, IDE2's settings model is synchronized with persisted
Theia preferences.

Closes #1987

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-04-14 08:56:29 +02:00
Akos Kitta
96da5bb5ea fix: updated to electron-builder@23.6.0 (#1986)
- updated to `electron-builder@23.6.0`
 - set `CSC_FOR_PULL_REQUEST` env to run notarization for a PR build.

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-04-13 17:53:43 +02:00
dependabot[bot]
ef5762599a build(deps): Bump peter-evans/create-pull-request from 4 to 5
Bumps [peter-evans/create-pull-request](https://github.com/peter-evans/create-pull-request) from 4 to 5.
- [Release notes](https://github.com/peter-evans/create-pull-request/releases)
- [Commits](https://github.com/peter-evans/create-pull-request/compare/v4...v5)

---
updated-dependencies:
- dependency-name: peter-evans/create-pull-request
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-04-13 08:52:14 -07:00
Akos Kitta
3aee575a35 chore(cli): Updated to 0.32.2 CLI
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>

Co-authored-by: per1234 <accounts@perglass.com>
Co-authored-by: Akos Kitta <a.kitta@arduino.cc>
2023-04-13 16:27:47 +02:00
Akos Kitta
80d5b5afa7 fix: propagate monitor errors to the frontend
- Handle when the board's platform is not installed (Closes #1974)
 - UX: Smoother monitor widget reset (Closes #1985)
 - Fixed monitor <input> readOnly state (Closes #1984)
 - Set monitor widget header color (Ref #682)

Closes #1508

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-04-13 11:58:49 +02:00
Akos Kitta
ab5c63c4b7 Update .github/workflows/build.yml
Co-authored-by: per1234 <accounts@perglass.com>
2023-04-13 11:12:55 +02:00
Akos Kitta
0a53550b0b ci: use ubuntu-latest for the Linux build
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-04-13 11:12:55 +02:00
Akos Kitta
f5c98c8400 feat(infra): support for topic: cloud label
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-04-12 19:18:39 +02:00
Akos Kitta
eb1f247296 fix: the focus in the sketchbook widget
Ref: arduino/arduino-ide#1720

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-03-31 17:12:12 +02:00
Akos Kitta
6e72be1b4c feat: re-focus monitor widget after verify/upload
supported when the monitor widget was the current in the bottom panel,
and the core command (upload/verify/etc./) was successful

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-03-29 10:02:34 +02:00
Akos Kitta
e4beb03a40 fix: incorrect editor widget key calculation
to avoid duplicate editor tabs when opening a sketch with no previously
saved workbench layout

Closes #1791

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-03-28 18:56:10 +02:00
Akos Kitta
39ab836880 fix: let the resource finish all write operation
before checking if it's in sync or not.

Closes #437

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-03-28 18:55:31 +02:00
Akos Kitta
dafb2454fd chore: latest VSIX handles custom directories.data
so when starting the debugger the CLI config path is used by the CLI for
the `daemon -I` command.

Closes #1911

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-03-28 08:20:11 +02:00
Akos Kitta
9b49712669 feat: omit release details to speed up lib search
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-03-16 10:01:15 +01:00
Akos Kitta
0ab28266df feat: introduced cloud state in sketchbook view
Closes #1879
Closes #1876
Closes #1899
Closes #1878

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-03-16 10:00:17 +01:00
dependabot[bot]
b09ae48536 build(deps): Bump actions/setup-go from 3 to 4
Bumps [actions/setup-go](https://github.com/actions/setup-go) from 3 to 4.
- [Release notes](https://github.com/actions/setup-go/releases)
- [Commits](https://github.com/actions/setup-go/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/setup-go
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-03-15 16:43:30 -07:00
Akos Kitta
2aad0e3b16 feat: new UX for the boards/library manager widgets
Closes #19
Closes #781
Closes #1591
Closes #1607
Closes #1697
Closes #1707
Closes #1924
Closes #1941

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-03-15 16:17:05 +01:00
per1234
58aac236bf Allow leading underscore in sketch filenames
The Arduino Sketch Specification defines the allowed format of sketch folder names and sketch code filenames. Arduino
IDE enforces compliance with the specification in order to ensure sketches created with Arduino IDE can be used with any
other Arduino development tool.

The Arduino Sketch Specification has been changed to allow a leading underscore in sketch folder names and sketch code
filenames so IDE's sketch name validation must be updated accordingly.
2023-03-13 10:11:47 -07:00
Akos Kitta
ec24b6813d fix: use text --format for the CLI
`Can't write debug log: available only in text format` error is thrown
by the CLI if the `--debug` flag is present.

Ref: arduino/arduino-cli#2003
Closes #1942

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-03-13 10:29:17 +01:00
per1234
d398ed1345 Add bundled tools version check step to release procedure
The Arduino IDE release includes several tool dependencies. Unstable versions of these tools may be pinned provisionally
for use with the development version of Arduino IDE, but production releases of Arduino IDE must use production releases
of the tool dependencies.

The release manager should check the tool versions before making a release, but previously this step was not mentioned
in the release procedure documentation.
2023-03-13 00:59:13 -07:00
Akos Kitta
fb10de1446 fix: jsonc parsing in the IDE2 backend
Occurred when `settings.json` contained comments or a trailing comma.

Closes #1945

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-03-13 08:34:39 +01:00
Akos Kitta
24dc0bbc88 fix: update monitor output after widget show
Closes #1724

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-03-07 16:11:35 +01:00
Akos Kitta
fa9777e529 fix: scroll to the bottom after the state update
Closes #1736

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-03-07 16:11:35 +01:00
Akos Kitta
77213507fb fix: encoding when reading a cloud sketch
Closes #449
Closes #634

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-03-02 09:48:09 +01:00
Akos Kitta
bfec85c352 fix: no unnecessary tree update on mouse over/out
Closes #1766

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-03-02 09:47:48 +01:00
per1234
f3d3d40c75 Bump version metadata post release
On every startup, Arduino IDE checks for new versions of the IDE. If a newer version is available, a notification/dialog
is shown offering an update.

"Newer" is determined by comparing the version of the user's IDE to the latest available version on the update channel.
This comparison is done according to the Semantic Versioning Specification ("SemVer").

In order to facilitate beta testing, builds are generated of the Arduino IDE at the current stage in development. These
builds are given an identifying version of the following form:

- <version>-snapshot-<short hash> - builds generated for every push and pull request that modifies relevant files
- <version>-nightly-<YYYYMMDD> - daily builds of the tip of the default branch

In order to cause these builds to be correctly considered "newer" than the release version, the version metadata must be
bumped immediately following each release.

This will also serve as the metadata bump for the next release in the event that release is a minor release. In case it
is instead a minor or major release, the version metadata will need to be updated once more before the release tag is
created.
2023-02-27 09:08:39 -08:00
github-actions[bot]
5bf38d804e Updated translation files (#1763)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-02-27 15:09:52 +01:00
Dave Simpson
9dec9c5a18 Bump CLI to 0.31.0 (#1921) 2023-02-27 12:34:31 +01:00
Dave Simpson
43b5d4e22f Enhance board config auto-selection with hardwareId (#1913) 2023-02-27 10:35:51 +01:00
per1234
fe19e0ef26 Use Apple Silicon build artifact name required by electron-updater
The Arduino IDE update check uses a "channel update info file" on Arduino's download server. This file specifies the
latest version of Arduino IDE available from the Arduino download server as well as the download URLs for the release
archives.

There is a separate channel file for each host operating system:

- Windows
- Linux
- macOS

Two macOS host architectures are now supported:

- x86 (AKA "Intel")
- ARM64 (AKA "Apple Silicon")

These each have their own release archive files. The macOS channel file contains data on both. So the updater must be
able to identify the appropriate archive to use for the update based on the host architecture. This is based on the
archive filename.

Arduino IDE's auto-update feature is built on the electron-updater package. The release archive selection is handled by
the electron-updater codebase and the filename pattern is hardcoded there. It selects the archive file that contains
`arm64` in its name (case sensitive), if present, to use for updates on macOS hosts with ARM64 architecture.

Previously, the build system produced archive files with the name format arduino-ide_<version>_macOS_ARM64.zip,
consistent with the established naming in other Arduino tooling projects. Unfortunately this naming would cause either
(depending on the order of the entries in the channel file) the x86 build to be used to update ARM64 macOS hosts
(resulting in lesser performance due to Rosetta 2 overhead) or the ARM64 build to be used to update x86 hosts (resulting
in the IDE failing to start).

So it is necessary to change the build artifact name to follow the format dictated by the electron-updater package.
Although it is not required (because electron-updater uses separate channel files for the x86 and ARM hosts), the Linux
archive filename format was also changed for the sake of consistency.
2023-02-27 01:05:36 -08:00
Akos Kitta
c0af297f48 build: force notarization on macOS if not on a CI
IDE2 needs a way to manually sign the application on M1.
The 'MACOS_FORCE_NOTARIZE' env variable forces the
notarization to proceed if not on a CI.

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-02-27 09:52:34 +01:00
dependabot[bot]
c97e34aa04 build(deps): Bump svenstaro/upload-release-action from 2.4.1 to 2.5.0
Bumps [svenstaro/upload-release-action](https://github.com/svenstaro/upload-release-action) from 2.4.1 to 2.5.0.
- [Release notes](https://github.com/svenstaro/upload-release-action/releases)
- [Changelog](https://github.com/svenstaro/upload-release-action/blob/master/CHANGELOG.md)
- [Commits](https://github.com/svenstaro/upload-release-action/compare/2.4.1...2.5.0)

---
updated-dependencies:
- dependency-name: svenstaro/upload-release-action
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-02-26 23:13:02 -08:00
Akos Kitta
01ee045beb chore: Updated to 0.31.0-rc.1 CLI
Aligned CLI build path calculation (arduino/arduino-cli#2031)

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-02-22 15:14:08 +01:00
Dave Simpson
cf6f83c8a2 bump go version in workflow .yml files 2023-02-22 11:37:29 +01:00
Akos Kitta
4deaf4fb76 feat: moved login entry point to the side-bar
Closes #1877

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-02-20 17:30:47 +01:00
Akos Kitta
d68bc4abdb feat: rename, deletion, and validation support
Closes #1599
Closes #1825
Closes #649
Closes #1847
Closes #1882

Co-authored-by: Akos Kitta <a.kitta@arduino.cc>
Co-authored-by: per1234 <accounts@perglass.com>

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-02-15 14:09:36 +01:00
github-actions[bot]
4f07515ee8 Updated themes (#1836)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-02-15 09:27:23 +01:00
Akos Kitta
25b545d4c4 fix: added GH token for vscode-ripgrep download
Otherwise, yarn install hits an HTTP 403 due to the rate-limiter.

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-02-13 15:28:39 +01:00
Akos Kitta
79b6b7ecc0 fix: library search boosting
Closes #1106

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-02-10 14:29:26 +01:00
Akos Kitta
5d264ef5b6 fix: show board info based on the selected port
include serial number of board if available

Closes #1489
Closes #1435

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-02-06 09:20:44 +01:00
dependabot[bot]
f63ee85fa3 build(deps): Bump svenstaro/upload-release-action from 2.4.0 to 2.4.1
Bumps [svenstaro/upload-release-action](https://github.com/svenstaro/upload-release-action) from 2.4.0 to 2.4.1.
- [Release notes](https://github.com/svenstaro/upload-release-action/releases)
- [Changelog](https://github.com/svenstaro/upload-release-action/blob/master/CHANGELOG.md)
- [Commits](https://github.com/svenstaro/upload-release-action/compare/2.4.0...2.4.1)

---
updated-dependencies:
- dependency-name: svenstaro/upload-release-action
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-02-05 07:55:22 -08:00
per1234
083a7069f0 Add leading+trailing line break to "Copy for Forum" content
Arduino IDE's "Edit > Copy for Forum (Markdown)" feature copies the contents of the currently selected editor tab to the
clipboard, with "fenced code block" markup added to provide correct formatting when the content is posted to a platform
supporting Markdown language such as Arduino Forum, GitHub, Stack Exchange, etc.

One of the most common points of friction between the volunteer helpers on the forum and the newcomers requesting
assistance is the failure to use the correct markup when posting code. In the best case scenario the code and thread is
made less readable and less convenient to copy to the IDE for further investigation. Components of the code often
resemble markup, which causes it to be corrupted by the forum's renderer.

Even in cases where the user was conscientious enough to attempt to add the right markup, which is facilitated by tools
such as "Copy for Forum (Markdown)", they often still don't get it quite right. So it is worthwhile to make efforts to
make it less likely for the markup to be inadvertently invalidated.

"Fenced code block" markup must be on its own lines before and after the code content. Someone not familiar with
Markdown won't know this fact and may simply paste the content copied via "Copy for Forum (Markdown)" without manually
adding a newline before and after. Since the code content is preceded and succeeded by a newline, they will not have any
visual indication of a problem.

Adding a newline before and after the content will ensure the markup is valid regardless of the context it is pasted
into. In cases where the user did add a newline and this introduces a redundant line break in the forum post, it will
not have any effect on the rendered content because the additional newlines are ignored by the renderer.
2023-02-03 04:58:15 -08:00
Akos Kitta
f5621db85d fix: flaky compiler test
- The gRPC core client provider requires an initialized config service when processing the error message received during the `InitRequest`
 - Additional logging in the config service.
 - The tests log into the console.

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-01-27 10:23:51 +01:00
Akos Kitta
658f117e93 test: added compiler + build output path test
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-01-24 09:06:07 +01:00
Akos Kitta
6140ae525c feat: handle when starting debug session failed (#1809)
If the sketch has not been verified, IDE2 offers the user a verify action.

Closes #808

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-01-23 09:03:49 +01:00
dependabot[bot]
afb02da806 build(deps): Bump svenstaro/upload-release-action from 2.3.0 to 2.4.0
Bumps [svenstaro/upload-release-action](https://github.com/svenstaro/upload-release-action) from 2.3.0 to 2.4.0.
- [Release notes](https://github.com/svenstaro/upload-release-action/releases)
- [Changelog](https://github.com/svenstaro/upload-release-action/blob/master/CHANGELOG.md)
- [Commits](https://github.com/svenstaro/upload-release-action/compare/2.3.0...2.4.0)

---
updated-dependencies:
- dependency-name: svenstaro/upload-release-action
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-01-18 22:08:34 -08:00
Akos Kitta
692f29fe1a fix: sketchbook container building
Closes #1185

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-01-17 13:54:26 +01:00
Akos Kitta
40e797966f fix: start the LS with the board specific settings
restart the LS when board settings of the running LS has changed

Closes #1029

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-01-16 11:39:22 +01:00
Akos Kitta
a15a94a339 fix: workaround for # in the app path
Closes #1815
Ref eclipse-theia/theia#12064

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-01-16 09:43:20 +01:00
Akos Kitta
ca687cfe40 fix: remove unused module
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-01-16 09:43:20 +01:00
Akos Kitta
32e17745f1 chore: Use 0.7.4 LS with the URL encoding fixes
Closes #1124

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-01-16 09:43:20 +01:00
Akos Kitta
432f3654df fix: restart LS on lib/core change, client re-init
Closes #670

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-01-16 09:38:27 +01:00
Akos Kitta
197cea2a60 fix: aligned Add File... behavior with IDE 1.x
- code files will be copied to sketch folder root
 - other files go under the `data` folder in the sketch folder root

Closes #284

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-01-11 09:23:50 +01:00
Akos Kitta
b2bf368db9 fix: update Examples and Include Library menu after ZIP install
Closes #659

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-01-11 09:23:23 +01:00
Akos Kitta
287b2e3f41 feat: removed encoding from the status bar
Closes #1393

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-01-11 09:22:53 +01:00
Akos Kitta
da0fecfd0f feat: no remote fetch when IDE gets CLI version
the CLI version is retrieved from the `package.json` of the extension:
`arduino.cli.version`

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2023-01-11 09:22:29 +01:00
Akos Kitta
76f9f635d8 feat: configure sketchbook location without restart
Closes #1764
Closes #796
Closes #569
Closes #655

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-12-21 15:44:10 +01:00
Self Not Found
3f05396222 Replace socks with socks5 in proxy protocol (#1776)
The net/http package in arduino-cli supports socks5 as scheme rather than socks.

Co-authored-by: per1234 <accounts@perglass.com>
2022-12-21 14:34:09 +01:00
Self Not Found
644e6079b3 Remove trailing colon when parsing the protocol from URL (#1778)
* Remove trailing colon when parsing the protocol from URL
* Fix bug
2022-12-21 14:32:46 +01:00
Akos Kitta
1d342cdbd0 build: use a local npm registry for app packaging
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-12-15 12:29:26 +01:00
Akos Kitta
908ec4c544 fix: menu item enablement issues
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-12-15 09:21:45 +01:00
Frank Palazzolo
7c86f1f9d3 Fix corruption of incoming UTF-8-encoded serial data (#1758)
* Fix corruption of incoming UTF-8-encoded serial data
* Make TextDecoder() readonly because it can be

Co-authored-by: z3bra <111462146+z3bra5hax@users.noreply.github.com>
2022-12-13 09:01:51 +01:00
Akos Kitta
f8c01e379c fix: list view filtering when opening the view
When the widget is opened the first time with any search options,
the widget might miss the refresh event as it does not happen at
instantiation time. This PR ensures that all list widget refresh
events wait until the React component is rendered and is visible
in the UI.

This change also ensures that the debounced search will run with
the most recent search options by setting the `trailing` property
of the debounced function to `true`.

Closes #1740

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-12-08 08:17:23 +01:00
Akos Kitta
af468a73bc feat: show the selected board config value on menu
closes #343

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-12-08 08:16:02 +01:00
per1234
d3a863911c Restore certificate check compatibility w/ RC2-40-CBC encrypted PKS#12
The "Check Certificates" GitHub Actions workflow uses OpenSSL to check for problems with the project's signing
certificates.

Certificates exported to PKS#12 archive files using older tools may have been encrypted using the "RC2-40-CBC"
algorithm.

Due to the availability of more secure modern alternatives, default support for RC2-40-CBC encryption was dropped in
OpenSSL 3.x.

The macOS signing certificate uses this RC2-40-CBC encryption.

The "Check Certificates" GitHub Actions workflow runs on the `ubuntu-latest` runner. Previously, this runner used Ubuntu
20.04. This has now changed to Ubuntu 22.04. With the operating system update came an OpenSSL update from 1.1.1f to
3.0.2. This caused the workflow runs to fail on the macOS certificate job:

Error outputting keys and certificates
80FBB0C5087F0000:error:0308010C:digital envelope routines:inner_evp_generic_fetch:unsupported:../crypto/evp/evp_fetch.c:349:Global default library context, Algorithm (RC2-40-CBC : 0), Properties ()

Even though no longer done by default, OpenSSL still supports RC2-40-CBC encryption via its "legacy" provider. So
compatibility with the certificate is restored by adding the `-legacy` flag to the `openssl pkcs12` commands.
2022-12-07 03:09:40 -08:00
Akos Kitta
c4172ee8e1 fix: theme service binding
cleaned up unused symbol

closes #1742

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-12-07 09:52:12 +01:00
Akos Kitta
ed8ed15168 fix: Preferences menu enablement defect
Manually update the menus when executing the command.

Also disabled the menu when the settings dialog is opened.

closes #1735

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-12-07 09:51:55 +01:00
per1234
32f0426f01 Fix formatting of generated release notes
The "Arduino IDE" GitHub Actions workflow generates a changelog from the commits since the last tag.

This changelog is published in multiple ways:

- Printed to workflow run logs
- Uploaded to Arduino's download server (mostly useful for the nightly builds)
- Initial version of release notes

For the last, the changelog text must be passed from the dedicated changelog generation workflow step to the release
step. This is done via workflow job output.

At the time the system was set up, outputs for workflow `run` steps were set using the `set-output` workflow command.
That "workflow command" system was later determined by GitHub to have potential security vulnerabilities, so it was
replaced with a `GITHUB_OUTPUT` environment file.

The "Arduino IDE" workflow was migrated to the new "environment file" approach. It was later discovered that there was
an undocumented breaking change in the method for handling multi-line strings in workflow step outputs between the old
"workflow command" system and the new "environment file". This resulted in the initial release notes having an incorrect
format. For example, what would previously have been formatted like this:

- Updated translation files (#1606) [23c7f5f]
- Use 0.29.0 CLI in IDE2 (#1683) [f1144ef]

Was now formatted like this:

- Updated translation files (#1606) [23c7f5f]%0A - Use 0.29.0 CLI in IDE2 (#1683) [f1144ef]%0A

The solution is to remove the commands that did the escaping of the changelog text in a manner that is no longer
supported and replace them with a "here document"-style format.

A random number is used as the "delimiter" (limit string) per the security recommendations in the official GitHub
documentation. Note that even though the multiline strings handling documentation was placed under the environment
variable section, it also applies to setting outputs.
2022-12-07 00:44:21 -08:00
Alberto Iannaccone
200c00244b 2.0.4 2022-12-06 04:13:54 -08:00
github-actions[bot]
1104467329 Updated translation files (#1701)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2022-12-05 10:24:38 +01:00
Akos Kitta
5695fd8afb fix: filtered undesired contributions: RTOS view
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-12-01 11:43:25 +01:00
Akos Kitta
d0e383853f feat: patched the Theia debug functionality
Patch for:
 - eclipse-theia/theia#11871
 - eclipse-theia/theia#11879
 - eclipse-theia/theia#11880
 - eclipse-theia/theia#11885
 - eclipse-theia/theia#11886
 - eclipse-theia/theia#11916

Closes #1582

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-12-01 11:43:25 +01:00
Akos Kitta
3bc412b42f feat: Updated to cortex-debug@1.5.1
Closes #246

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-12-01 11:43:25 +01:00
Akos Kitta
f553d6919d feat: no ping timeout in dev mode
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-12-01 11:43:25 +01:00
Akos Kitta
d6a4b0f910 fix: update monitor settings only if it's changed
Closes #375

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-11-29 14:07:58 +01:00
Akos Kitta
c0488d1f64 fix: remote sketch creation if tree is not active
Closes #1715

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-11-29 11:19:13 +01:00
Akos Kitta
81195431b0 fix: double update of the zoom level on save
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-11-29 10:58:23 +01:00
Akos Kitta
87109e6559 chore: Switched to window.zoomLevel preference
Deprecated `arduino.window.zoomLevel`.

Closes #1657

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-11-29 10:58:23 +01:00
Akos Kitta
c0af1e62e8 fix: main sketch file editor focus on layout reset
Closes #643

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-11-29 10:51:19 +01:00
Akos Kitta
ac9cce16f7 chore: Updated to Theia 1.31.1 (#1662)
Closes #1655
Closes #1656

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-11-29 09:39:54 +01:00
Alberto Iannaccone
3ad660927f Fix keybindings to switch between tabs on MacOs (#1686) 2022-11-29 09:22:14 +01:00
Akos Kitta
8778d70ad7 fix: editor widget resolving when creating new tab
An already opened editor widget can resolve without waiting.

Closes #1718

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-11-29 09:20:16 +01:00
Alberto Iannaccone
fe3fbb189c 2.0.3 (#1687) 2022-11-17 15:03:22 +01:00
github-actions[bot]
23c7f5f848 Updated translation files (#1606)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2022-11-17 12:47:21 +01:00
Alberto Iannaccone
f1144efb93 Use 0.29.0 CLI in IDE2 (#1683) 2022-11-17 12:43:28 +01:00
per1234
9cec643cab Fix nightly build links in issue forms
The issue forms are configured to request the contributor to test using the nightly build of Arduino IDE before
submitting an issue in order to make sure the bug or feature request has not already been resolved.

Some time ago, the repository's readme contained a table of download links. The links in the issue forms pointed there.
That table was replaced with a link to the official "Software" page in order to reduce unnecessary verbosity and
maintenance burden of the project's documentation content.

The issue form links were not updated at that time. The resulting additional link in the chain made obtaining the
nightly build less convenient for the contributor to obtain.

The links are hereby updated to point directly to the list of nightly build download links on the arduino.cc "Software"
page.
2022-11-17 03:25:26 -08:00
Akos Kitta
1a7784a540 feat: progress for the remote sketch creation
Closes #1668

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-11-17 11:05:34 +01:00
Akos Kitta
d24a3911f8 fix: workaround for arduino/arduino-cli#1968
Do not try to parse the original `NotFound` error message, but look for
a sketch somewhere in the requested path.

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-11-11 13:19:08 +01:00
Akos Kitta
3735553003 fix: flawed timing issue when opening editors
From now on, the editor widget open promise resolution does not rely on
internal Theia events but solely on @phosphor's `isAttached`/`isVisible`
properties.
The editor widget promise resolves with the next task after a navigation
frame so the browser can render the widget.

Closes #1612

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-11-11 13:19:08 +01:00
Akos Kitta
f6d112e1f6 fix: escaped regex chars in pattern
Closes #1600

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-11-10 16:33:42 +01:00
Akos Kitta
cc2d557706 fix: relaxed condition to check if resource exists
The original (`fs-extra`-based) implementation did not check if the
file is writable either.

Resources are not writable in mounted AppImages.

Closes #1586

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-11-10 11:27:44 +01:00
Akos Kitta
103acc4b7e fix: allow second instance on macOS
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-11-10 11:27:17 +01:00
Akos Kitta
c3dc7c6307 fix: avoid ENOTDIR when opening second instance.
If the resource is a file, do not try to `readdir`, but return undefined

Closes #1590

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-11-10 11:27:17 +01:00
Akos Kitta
7d6a2d5e33 feat: Create remote sketch
Closes #1580

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-11-10 11:12:20 +01:00
Akos Kitta
6984c52b92 fix: Handle gracefully when trying to detect invalid sketch name error and folder is missing on filesystem (#1616)
- feat: generalized Node.js error handling
    - Gracefully handle when the sketch folder has been deleted
 - feat: spare detecting invalid sketch name error
    - The invalid sketch name detection requires at least one extra FS access.
       Do not try to detect the invalid sketch name error, but use the original
       `NotFound` from the CLI.
 - fix: typo

Closes #1596

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-11-10 11:11:35 +01:00
Akos Kitta
3a70547770 fix: do not trim stdout of clang-format process
Otherwise, it always causes a _no newline at the end of file_ problem.

Closes #1487

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-11-08 09:39:41 +01:00
per1234
8a85b5c3d8 Migrate workflows from deprecated set-output commands
GitHub Actions provides the capability for workflow authors to use the capabilities of the GitHub Actions ToolKit
package directly in the `run` keys of workflows via "workflow commands". One such command is `set-output`, which allows
data to be passed out of a workflow step as an output.

It has been determined that this command has potential to be a security risk in some applications. For this reason,
GitHub has deprecated the command and a warning of this is shown in the workflow run summary page of any workflow using
it:

The `set-output` command is deprecated and will be disabled soon. Please upgrade to using Environment Files. For more
information see: https://github.blog/changelog/2022-10-11-github-actions-deprecating-save-state-and-set-output-commands/

The identical capability is now provided in a safer form via the GitHub Actions "environment files" system. Migrating
the use of the deprecated workflow commands to use the `GITHUB_OUTPUT` environment file instead fixes any potential
vulnerabilities in the workflows, resolves the warnings, and avoids the eventual complete breakage of the workflows that
would result from GitHub's planned removal of the `set-output` workflow command 2023-05-31.
2022-11-04 00:45:14 -07:00
dependabot[bot]
b998d35524 Bump actions/checkout from 2 to 3
Bumps [actions/checkout](https://github.com/actions/checkout) from 2 to 3.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v2...v3)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-11-03 16:39:12 -07:00
dependabot[bot]
ddec64c4a5 Bump svenstaro/upload-release-action from 2.2.0 to 2.3.0
Bumps [svenstaro/upload-release-action](https://github.com/svenstaro/upload-release-action) from 2.2.0 to 2.3.0.
- [Release notes](https://github.com/svenstaro/upload-release-action/releases)
- [Changelog](https://github.com/svenstaro/upload-release-action/blob/master/CHANGELOG.md)
- [Commits](https://github.com/svenstaro/upload-release-action/compare/2.2.0...2.3.0)

---
updated-dependencies:
- dependency-name: svenstaro/upload-release-action
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-11-03 16:09:57 -07:00
dependabot[bot]
8fed08003e Bump actions/upload-artifact from 2 to 3
Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 2 to 3.
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](https://github.com/actions/upload-artifact/compare/v2...v3)

---
updated-dependencies:
- dependency-name: actions/upload-artifact
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-11-03 16:09:37 -07:00
dependabot[bot]
8454c625f7 Bump geekyeggo/delete-artifact from 1 to 2
Bumps [geekyeggo/delete-artifact](https://github.com/geekyeggo/delete-artifact) from 1 to 2.
- [Release notes](https://github.com/geekyeggo/delete-artifact/releases)
- [Commits](https://github.com/geekyeggo/delete-artifact/compare/v1...v2)

---
updated-dependencies:
- dependency-name: geekyeggo/delete-artifact
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-11-03 16:04:18 -07:00
dependabot[bot]
60df322f09 Bump actions/setup-node from 1 to 3
Bumps [actions/setup-node](https://github.com/actions/setup-node) from 1 to 3.
- [Release notes](https://github.com/actions/setup-node/releases)
- [Commits](https://github.com/actions/setup-node/compare/v1...v3)

---
updated-dependencies:
- dependency-name: actions/setup-node
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-11-03 16:03:47 -07:00
dependabot[bot]
8bfb140e7c Bump actions/setup-python from 2 to 4
Bumps [actions/setup-python](https://github.com/actions/setup-python) from 2 to 4.
- [Release notes](https://github.com/actions/setup-python/releases)
- [Commits](https://github.com/actions/setup-python/compare/v2...v4)

---
updated-dependencies:
- dependency-name: actions/setup-python
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-11-03 14:51:19 -07:00
dependabot[bot]
260227e79a Bump peter-evans/create-pull-request from 3 to 4
Bumps [peter-evans/create-pull-request](https://github.com/peter-evans/create-pull-request) from 3 to 4.
- [Release notes](https://github.com/peter-evans/create-pull-request/releases)
- [Commits](https://github.com/peter-evans/create-pull-request/compare/v3...v4)

---
updated-dependencies:
- dependency-name: peter-evans/create-pull-request
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-11-03 14:30:50 -07:00
dependabot[bot]
cc310bf1a5 Bump actions/download-artifact from 2 to 3
Bumps [actions/download-artifact](https://github.com/actions/download-artifact) from 2 to 3.
- [Release notes](https://github.com/actions/download-artifact/releases)
- [Commits](https://github.com/actions/download-artifact/compare/v2...v3)

---
updated-dependencies:
- dependency-name: actions/download-artifact
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-11-03 14:25:30 -07:00
per1234
dbd52e2f34 Remove unused GitHub release download stats workflow
The "github-stats" GitHub Actions workflow periodically gathers GitHub release asset download statistics for Arduino CLI
and pushes the results to Datadog.

There are no known problems with this workflow. However, the companion "arduino-stats" workflow that did the same for
the downloads of Arduino IDE from downloads.arduino.cc was broken and thus removed from the repository.

The GitHub stats are not very valuable on their own as they only provide an unknown fraction of the total downloads of
Arduino IDE. They have also not ended up being used.

The workflow also uses deprecated Node.js 12 runtime, which currently results in warnings printed to the workflow run
summary page, but will eventually cause the complete breakage of the workflow.

Since it doesn't provide any value and represents a maintenance burden, the workflow is hereby removed from the
repository.
2022-11-03 14:13:40 -07:00
per1234
9cd03bec46 Remove broken download stats workflow
The "arduino-stats" GitHub Actions workflow was designed to periodically gather download statistics from Arduino CDN and
push results to Datadog.

The recorded stats from the identical system in the Arduino CLI repository showed a periodic decrease in total download
count. Since this is patently impossible, it is clear that something is wrong with the system and that the recorded data
is not trustworthy. An investigation into the problem
was never done.

On 2022-03-14, the runs of the "arduino-stats" GitHub Actions workflow began to fail. Because there had not been any
relevant change in the repository between the last successful run and the first failing run, it seems that some external
change caused the breakage.

The workflow also uses deprecated Node.js 12 runtime-based actions and set-output workflow command, which currently
results in warnings printed to the workflow run summary page, but will eventually cause the complete breakage of the
workflow.

Since the workflow was not ever working successfully and the lack of an investigation about that indicates that the
stats are not of immediate importance, the best course of action is to simply remove the broken infrastructure from the
repository rather than investing time into fixing something that isn't being used anyway.
2022-11-03 14:13:40 -07:00
dependabot[bot]
c29452a858 Bump carlosperate/download-file-action from 1 to 2
Bumps [carlosperate/download-file-action](https://github.com/carlosperate/download-file-action) from 1 to 2.
- [Release notes](https://github.com/carlosperate/download-file-action/releases)
- [Commits](https://github.com/carlosperate/download-file-action/compare/v1...v2)

---
updated-dependencies:
- dependency-name: carlosperate/download-file-action
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-11-03 14:05:51 -07:00
per1234
7d91f2d8cb Configure Dependabot to check for outdated actions used in workflows
Dependabot will periodically check the versions of all actions used in the repository's workflows. If any are found to
be outdated, it will submit a pull request to update them.

NOTE: Dependabot's PRs will occasionally propose to pin to the patch version of the action (e.g., updating
`uses: foo/bar@v1` to `uses: foo/bar@v2.3.4`). When the action author has provided a major version ref, use that instead
(e.g., `uses: foo/bar@v2`). Dependabot will automatically close its PR once the workflow has been updated.

More information:
https://docs.github.com/code-security/dependabot/working-with-dependabot/keeping-your-actions-up-to-date-with-dependabot
2022-11-03 13:56:30 -07:00
Akos Kitta
f6275f9f62 feat: build IDE2 on darwin arm64
- Use Node.js 16+,
 - All workflow files use `.yml` instead of `.yaml`,
 - Use Arduino LS `0.7.2`,
 - Updated `electron-builder` to `23.3.3`,
 - Removed unused `conf-node-gyp.sh`,
 - Removed unused `THEIA_ELECTRON_SKIP_REPLACE_FFMPEG`, and
 - Aligned `node-gyp@9.3.0`, `electron-rebuild@3.2.9` to Theia.

Co-authored-by: per1234 <accounts@perglass.com>
Co-authored-by: Akos Kitta <a.kitta@arduino.cc>

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-11-02 15:48:04 +01:00
per1234
0d0550974a Bump version metadata post release
On every startup, the Arduino IDE checks for new versions of the IDE. If a newer version is available, a
notification/dialog is shown offering an update.

"Newer" is determined by comparing the version of the user's IDE to the latest available version on the update channel.
This comparison is done according to the Semantic Versioning Specification ("SemVer").

In order to facilitate beta testing, builds are generated of the Arduino IDE at the current stage in development. These
builds are given an identifying version of the following form:

- <version>-snapshot-<short hash> - builds generated for every push and pull request that modifies relevant files
- <version>-nightly-<YYYYMMDD> - daily builds of the tip of the default branch

In order to cause these builds to be correctly considered "newer" than the release version, the version metadata must be
bumped immediately following each release.

This will also serve as the metadata bump for the next release in the event that release is a minor release. In case it
is instead a minor or major release, the version metadata will need to be updated once more before the release tag is
created.
2022-10-28 06:42:46 -07:00
Alberto Iannaccone
4e882d25d9 bump arduino-fwuploader to 2.2.2 (#1584) 2022-10-27 14:53:36 +02:00
github-actions[bot]
f93f78039b Updated translation files (#1496)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2022-10-27 12:40:56 +02:00
Akos Kitta
2b2463b834 fix: Prompt sketch move when opening an invalid outside from IDE2
Log IDE2 version on start.

Closes #964
Closes #1484

Co-authored-by: Alberto Iannaccone <a.iannaccone@arduino.cc>
Co-authored-by: Akos Kitta <a.kitta@arduino.cc>

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-10-26 18:53:00 +02:00
Nick B
0773c3915c Added an optional user modifiable default sketch file when creating a new project. (#1559)
* Added a modifiable default sketch for new project

* Removed unused file

* WiP : Now nothing's working... :(

* yarn i18n:generate for the settings

* Updated the desription for markdown description.

* Lintered the code

* Remove undesirable whitespaces

* Applied kittaakos suggestions

* Removed extra whitespaces

* Fixed default `.ino` for the missings empty lines.
2022-10-26 14:08:22 +02:00
Francesco Spissu
2f5afe0d9c Prevent layout shift on hover in libs/board manager (#1568) 2022-10-25 08:58:37 +02:00
Muhammad Zaheer
b8370686ec Coding style fix - newline added 2022-10-25 08:51:21 +02:00
Muhammad Zaheer
3b2d12eff9 Cleaner implementation of HistoryList
- The implementation has been taken from @kittaakos repo
d10de01736/arduino-ide-extension/src/browser/serial/monitor/serial-monitor-send-input.tsx
- The previous method has been modified to ensure the first element instead of an empty string is returned if the index is at the beginning of the list.
- The push method has been modified to check if the current command is same as the last command. If same then, it is not added to the list else it is added.
2022-10-25 08:51:21 +02:00
Muhammad Zaheer
cdaaa5584d Changed logic to avoid end value being shown twice 2022-10-25 08:51:21 +02:00
Muhammad Zaheer
3476de27f7 Added Message History to Serial Monitor 2022-10-25 08:51:21 +02:00
Akos Kitta
b55cfc2052 chore: Use 0.28.0 CLI in IDE2.
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-10-24 16:08:57 +02:00
Akos Kitta
44751c370b Changed the daemon output from json to text
Closes #1544

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-10-24 14:14:33 +02:00
Alberto Iannaccone
32d904ca36 Let the user edit the font size settings with the keyboard (#1547)
* let the user edit the stepper input with keyboard

* consider exceptions and fix styling

* fix onBlur with empty strings

* always set the internal state value

* misc fixes

Co-authored-by: David Simpson <45690499+davegarthsimpson@users.noreply.github.com>
2022-10-21 17:36:19 +02:00
Muhammad Zaheer
5424dfcf70 Fix #1566 : Port submenu section heading show at top 2022-10-21 09:04:07 +02:00
per1234
b8bf1eefa2 Allow uploads without port selection
It is common for a "port" to be used in some way during the process of uploading to a board. However, the array of
Arduino boards is very diverse. Some of these do not produce a port and their upload method has no need for one.

For this reason, the IDE must allow the upload process to be initiated regardless of whether a port happens to be
selected. During the addition of support for user provided fields, an unwarranted assumption was made that all boards
require a port selection for upload and this resulted in a regression that broke uploading for these boards. This
regression was especially user unfriendly in that there was no response whatsoever from the IDE when the user attempted
to initiate an upload under these conditions.

The bug is hereby fixed. The upload process will always be initiated by the IDE regardless of whether a port is
selected. In cases where a port is required, the resulting error message returned by Arduino CLI or the upload tool will
communicate the problem to the user.
2022-10-20 08:31:52 -07:00
Francesco Spissu
93291b6811 Adjust library installation dialog buttons style (#1401)
Closes #1314.
2022-10-20 12:40:40 +02:00
Akos Kitta
87ebcbe77e Let CSS do the uppercase transformation.
Expose no implementation details to translation files.

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-10-19 10:49:02 +02:00
Akos Kitta
99b10942bb Listen on the client's port change event
If the board select dialog is listening on the backend's event,
the frontend might miss the event when it comes up, although boards
are connected and ports are discovered.

Closes #573

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-10-17 10:31:19 +02:00
Alberto Iannaccone
960a2d0634 Fix boards listing (#1520)
* Fix boards listing

* use arduio-cli sorting fix

* re-use code to handle board list response

* change `handleListBoards` visibility to `private`

* pad menu items order with leading zeros to fix alphanumeric order
2022-10-17 10:03:41 +02:00
Francesco Spissu
e577de4e8e Put Arduino libs and platforms on top of the Library/Boards Manager (#1541) 2022-10-14 09:07:54 +02:00
Francesco Spissu
f3ef95cfe2 Retain installation interface using version menu (#1471) 2022-10-13 12:05:29 +02:00
dankeboy36
bc264d1adf Apply margin adjustments to the first hover row
Signed-off-by: dankeboy36 <dankeboy36@gmail.com>
2022-10-07 04:16:26 -07:00
dankeboy36
5444395f34 Better tooltips.
fixes #1503

Signed-off-by: dankeboy36 <dankeboy36@gmail.com>
2022-10-07 04:16:26 -07:00
Akos Kitta
2d2be1f6d0 Ensure exact match when installing Arduino_BuiltIn
on the first IDE2 startup.

Closes #1526

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-10-07 11:55:53 +02:00
r3inbowari
1e269ac83d Fix status bar clipped in minimal state (#1517) 2022-10-07 10:43:45 +02:00
Akos Kitta
0c49709f26 Link resolved for lib/boards manager.
Closes #1442

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-10-07 10:00:36 +02:00
Akos Kitta
019b2d5588 Avoid using reportResult if installing lib/core
Closes #1529

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-10-07 09:01:25 +02:00
Alberto Iannaccone
aa0807ca3f Limit interface scale (#1502)
* limit interface scale

* debounce interface scale updates

* limit font-size + refactor

* remove excessive settings duplicate

* remove useless async

* fix interface scale step

* change mainMenuManager visibility to private

* fix menu registration

* update menu actions when autoScaleInterface changes
2022-10-06 17:37:26 +02:00
Akos Kitta
61a11a0857 Removed real_name of the libraries.
It has been removed from the gRPC API: arduino/arduino-cli#1890

This PR switches from `real_name` to `name` in the UI, as the `name` is
the canonical form provided by the CLI.

Closes #1525

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-10-05 13:47:38 +02:00
Akos Kitta
0c20ae0e28 Various library/platform index update fixes
- IDE2 can start if the package index download fails. Closes #1084
 - Split the lib and platform index update. Closes #1156

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-10-05 09:17:37 +02:00
per1234
945a8f4841 Bump built-in example sketches version to 1.10.0
The Arduino IDE installation includes a collection of example sketches demonstrating fundamental concepts.

These examples are hosted in a dedicated repository, which is a dependency of this project. A new release has been made
in that `arduino/arduino-examples` repository.

This release updates the formatting of the examples to be compliant with the code style of the Arduino IDE 2.x
"Auto Format" feature.
2022-10-04 01:59:50 -07:00
per1234
ae76432944 Update library dependency installation dialog response indexes
Arduino libraries may specify dependencies on other libraries in their metadata. The installation of these dependencies
is offered by the Arduino IDE when the user installs the dependent library using the Library Manager widget.

The order of the buttons in the dialog that offers the dependencies installation was recently rearranged. The dialog
response interpretation code was not updated to reflect the changes to the button indexes at that time. This caused the
"CANCEL" button to trigger the behavior expected from the "INSTALL ALL" button, and vice versa.

The library dependencies installation dialog response interpretation code is hereby updated to use the new button
indexes.
2022-10-03 23:56:22 -07:00
per1234
40807db65e Bump arduino-serial-plotter-webapp dependency to 0.2.0 2022-10-03 23:33:17 -07:00
Akos Kitta
da22f1ed11 Refresh menus when opening example/recent fails.
Closes #53

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-10-04 08:10:27 +02:00
per1234
32b70efd5c Correct text of "INSTALLED" label in Library/Boards Manager
An "INSTALLED" label is shown on the items in the Library Manager and Boards Manager views that are currently installed
on the user's system.

During some work to add missing internationalization to the UI strings, this text was changed to "INSTALL". That text is
not appropriate for what this label is intended to communicate.

The regression is hereby corrected, while retaining the internationalization of the string.
2022-10-03 00:53:40 -07:00
Alberto Iannaccone
6f07717369 Dialog focus (#1472)
* focus on dialog controls when is open

* fix "Configure and Upload" label

* fix focus on user fields
2022-09-29 15:16:28 +02:00
r3inbowari
d6cb23f782 fix splitHandle above widget 2022-09-27 06:19:55 -07:00
r3inbowari
9ac2638335 Avoid intellisense widgets being covered by the bottom panel 2022-09-27 06:19:55 -07:00
Alberto Iannaccone
96cf09d594 Initialise the IDE updater even when 'checkForUpdates' preference is false (#1490) 2022-09-26 17:39:19 +02:00
per1234
8380c82028 Add readme for localization data
Arduino IDE has been translated to several languages.

The localization process follows the following steps:

1. An English language source string is defined in the Arduino IDE codebase
2. The source string is pushed to Transifex
3. Community translators localize the string
4. The localization data is pulled into the Arduino IDE repository
5. The localization data is incorporated into the Arduino IDE distribution

Experience with maintenance of Arduino's localized projects indicates that the data files generated at step (4) can
appear to be the appropriate place to make edits for casual contributors not familiar with the project's sophisticated
internationalization infrastructure.

Since those files are generated by automated systems, any edits made there would only be overwritten, so it is important
to clearly communicate the correct way to make enhancements or corrections to these strings. This is accomplished by a
local readme file most likely to be seen by those working in the folder containing these files, which supplements the
existing information about translation in the project's translation guide.
2022-09-26 05:07:34 -07:00
per1234
5eb2926407 Add a dedicated translator guide document
Translation of the strings of the Arduino IDE UI is a valuable contribution which helps to make Arduino accessible to
everyone around the world.

Localization of the Arduino-specific strings of the IDE is done in the "Arduino IDE 2.0" project on Transifex.
Previously, the "Translation" row in the contribution methods summary table in the contributor guide entry page simply
linked to that project.

Arduino IDE also uses localized strings from several other sources:

- VS Code language packs
- Arduino CLI

Users may notice unlocalized strings or errors or areas for improvement in the existing translations and wish to
contribute translations. For this reason, it is important to also provide instructions for contributing to those other
localization data sources. The contribution methods summary table can not effectively accommodate that additional
content so a dedicated document is added for the purpose. This will also allow linking directly to that document from
related documentation or conversations.
2022-09-26 05:07:34 -07:00
per1234
a4ab204400 Correct issue report guide link in issue template chooser
Contributor are presented with an issue template chooser page at the start of the issue creation process.

In addition to the issue report templates, some "contact links" provide information and links to other communication
channels. In order to encourage high quality issues, a link to the "issue report guide" is included on this page.

Previously that link pointed to an incorrect URL, resulting in a 404 error for those who visited it. The URL is hereby
corrected.
2022-09-26 05:04:43 -07:00
per1234
6416c431c6 Bump version metadata to produce correct tester and nightly build precedence
On every startup, the Arduino IDE checks for new versions of the IDE. If a newer version is available, a
notification/dialog is shown offering an update.

"Newer" is determined by comparing the version of the user's IDE to the latest available version on the update channel.
This comparison is done according to the Semantic Versioning Specification ("SemVer").

In order to facilitate beta testing, builds are generated of the Arduino IDE at the current stage in development. These
builds are given an identifying version of the following form:

- <version>-snapshot-<short hash> - builds generated for every push and pull request that modifies relevant files
- <version>-nightly-<YYYYMMDD> - daily builds of the tip of the default branch

The previous release procedure caused the <version> component of these to be the version of the most recent release.

During the pre-release phase of the project development, all releases had a pre-release suffix (e.g., 2.0.0-rc9.4).
Appending the "snapshot" or "nightly" suffix to that pre-release version caused these builds to have the correct
precedence (e.g., 2.0.0-rc9.2.snapshot-20cc34c > 2.0.0-rc9.2). This situation has changed now that the project is using
production release versions (e.g., 2.0.0-nightly-20220915 < 2.0.0). This caused users of "snapshot" or "nightly" builds
to be presented with a spurious update notification on startup.

The solution is to do a minor bump of the version metadata after creating the release tag. That was not done immediately
following the 2.0.0 release. The omission is hereby corrected.

This will provide the metadata bump traditionally done before the creation of the release tag in the event the version
number of the next release is 2.0.1. In case it is instead a minor or major release, the version metadata will need to
be updated once more before the release tag is created.
2022-09-26 05:04:43 -07:00
per1234
8f88aa69bf Adjust release procedure to produce correct tester and nightly build version precedence
On every startup, the Arduino IDE checks for new versions of the IDE. If a newer version is available, a
notification/dialog is shown offering an update.

"Newer" is determined by comparing the version of the user's IDE to the latest available version on the update channel.
This comparison is done according to the Semantic Versioning Specification ("SemVer").

In order to facilitate beta testing, builds are generated of the Arduino IDE at the current stage in development. These
builds are given an identifying version of the following form:

- <version>-snapshot-<short hash> - builds generated for every push and pull request that modifies relevant files
- <version>-nightly-<YYYYMMDD> - daily builds of the tip of the default branch

The previous release procedure caused the <version> component of these to be the version of the most recent release.

During the pre-release phase of the project development, all releases had a pre-release suffix (e.g., 2.0.0-rc9.4).
Appending the "snapshot" or "nightly" suffix to that pre-release version caused these builds to have the correct
precedence (e.g., 2.0.0-rc9.2.snapshot-20cc34c > 2.0.0-rc9.2). This situation has changed now that the project is using
production release versions (e.g., 2.0.0-nightly-20220915 < 2.0.0). This caused users of "snapshot" or "nightly" builds
to be presented with a spurious update notification on startup.

The solution is to add a step to the end of the release procedure to do a minor bump of the version metadata after
creating the release tag.

This means that the metadata bump traditionally done before the creation of the release tag will already have been done
in advance for patch releases. However, it will still need to be done for minor or major releases.

The release procedure documentation is hereby updated to produce correct tester and nightly build version precedence.

The metadata bump step is moved from before to after the tag creation step, replaced by a new step to verify the version
before the tag creation, updating it in the event it is not a patch release. Both those steps may require updating the
metadata. As an alternative to maintaining duplicate copies, each step links to a single copy of the fairly complex
instructions for doing so. The structure of the document is adjusted to accomodate this, by placing the steps of the
procedure under a "Steps" section and creating a new "Operations" section to contain any such shared content.
2022-09-26 05:04:43 -07:00
per1234
3c2b2a0734 Format release procedure document as ordered list
The release procedure is a set of steps which must be performed in a specific sequence. This fact is more effectively
communicated by formatting it as an ordered list.
2022-09-26 05:04:43 -07:00
per1234
39538f163f Move package metadata update step to dedicated section of release docs
Previously the instructions for updating the npm package metadata, submitting a PR for that, and merging the PR was in
the same section as the tag push instructions in the release procedure documentation.

These two operations are distinct from each other. Mashing them into a single step makes the release procedure document
difficult to read and the process more prone to error.

For this reason, a dedicated step is used for each of the two things.
2022-09-26 05:04:43 -07:00
Akos Kitta
9ef04bb8d6 Fixed missing translations
Aligned the languge pack versions.

Closes #1431

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-09-26 10:49:31 +02:00
Akos Kitta
707f3bef61 Listen on keyboard layout changes from the OS.
Closes #989

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-09-26 10:49:03 +02:00
Akos Kitta
878395221a Use the parent of the existing sketch if not temp.
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-09-22 10:08:38 +02:00
Akos Kitta
6a35bbfa7e Made the file dialogs modal.
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-09-22 10:08:38 +02:00
Francesco Spissu
42f6f43870 Avoid new line if 3rd party URLs text is too long (#1474)
Closes #1470.
2022-09-21 11:51:38 +02:00
Akos Kitta
6983c5bf7f Ensure directories.user exists.
Closes #1445

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-09-21 09:10:26 +02:00
Francesco Spissu
b3ab5cbd2a Fix input background in Firmware Updater dialog (#1465)
Closes #1441.
2022-09-20 14:47:30 +02:00
Alberto Iannaccone
8a5995920a fix board selection and workspace input dialogs width and height (#1406)
* fix board selection and workspace input dialogs width and height

* use same dialog for new file and rename

* fix board list getting small when filtering

* board select dialog: show variant text when no board is found

* fix addition boards url outline
2022-09-20 14:36:02 +02:00
github-actions[bot]
8de6cf84d9 Updated translation files (#1462)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2022-09-20 12:57:27 +02:00
Dwight
f5c36bb691 Serial Monitor autoscroll only makes bottom line partially visible #972 (#1446) 2022-09-20 12:26:57 +02:00
Francesco Spissu
364f8b8e51 Move primary buttons on the right of the dialogs (#1382)
Closes #1368.
2022-09-20 11:48:19 +02:00
Alberto Iannaccone
671d2eabd4 Show user fields dialog again if upload fails (#1415)
* Show user fields dialog again if upload fails

* move user fields logic into own contribution

* apply suggestions
2022-09-20 09:27:09 +02:00
Akos Kitta
9a65ef6ea8 Disabled the tokenizer after 500 chars.
Closes #1343.

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-09-19 12:17:13 +02:00
Alberto Iannaccone
4e590ab618 use ipc message to focus on serial plotter window (#1410) 2022-09-15 16:07:13 +02:00
Dave Simpson
026e80e7fc fix #1383: missing port labels (#1412)
* fallback to port.address if addressLabel is false

* addressLabel if possible, reconcileAvailableBoards

* remove fallback
2022-09-15 15:29:28 +02:00
Akos Kitta
fdf6f0f9c8 Avoid deleting the workspace when it's still in use.
- From now on, NSFW service disposes after last reference
is removed. No more 10sec delay.
 - Moved the temp workspace deletion to a startup task.
 - Can set initial task for the window from electron-main.
 - Removed the `browser-app`.

Closes #39

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-09-15 15:24:25 +02:00
per1234
0151e4c224 Make instructions re: non-notarized PR tester build more user friendly
For security reasons, the macOS tester builds generated for PRs from forks are not notarized. Instructions are provided for
beta testing under these conditions.

Previously, the instructions for bypassing the macOS notarization requirement involved disabling macOS Gatekeeper
entirely using the spctl command. These instructions are hereby replaced by an alternative approach, where the
restriction is bypassed for the Arduino IDE application alone, via the macOS GUI.

The new approach is superior for the following reasons:

- More secure due to having limited scope
- More accessible due to the use of the macOS GUI
2022-09-15 05:53:09 -07:00
per1234
e8b0ea4f2d Reduce overlap between readme and development+contributor guides
The readme should provide a concise overview of the essential information about the project. Additional details are
provided in dedicated documents, so the readme only needs to provide links to that information.
2022-09-15 05:53:09 -07:00
per1234
7c1ca04c75 Add a project contributor guide
Documentation of how to contribute to the project gives everyone the opportunity to participate, while also reducing the
maintenance effort and increasing the quality of contributions.

This guide documents the various ways of contributing to the project.
2022-09-15 05:53:09 -07:00
per1234
0ba88d5ab6 Move beta testing information to a dedicated documentation file
Previously, the information about tester builds was mixed in with the documentation about building the project from
source.

The two subjects are of relevance to two distinct contribution options. Building from source will primarily be done by
developers working on the project code base. Tester builds will be used by beta testers and reviewers.

For this reason, it doesn't make sense to require beta testers to wade through a lot of development documentation not
directly related to their work in order to find the instructions for obtaining tester builds. Likewise, it doesn't make
sense to clutter up the development documentation with such information.

Moving the information about tester builds to a dedicated file makes it easier for the interested parties to find, and
also allows the creation of a comprehensive guide for beta testers without making a negative impact on the development
documentation content.
2022-09-15 05:53:09 -07:00
per1234
96e229d803 Move documentation assets to standard location 2022-09-15 05:53:09 -07:00
per1234
d07d83fdfe Move development documentation to a more suitable location
Previously, information about project development was stored in a file named BUILDING.md in the root of the repository.

That content is hereby moved to the file docs/development.md. This will provide the following benefits:

- Broaden the scope of the file to all information related to development rather than building only
- Store all documentation content under a single folder instead of randomly putting some in the root and others under
  docs
2022-09-15 05:53:09 -07:00
Akos Kitta
5f82577bc1 Can send message to the monitor with Enter.
Removed the required `Ctrl/Cmd` modifier.

Closes #572

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-09-14 17:18:31 +02:00
per1234
35fcfb89c1 Remove obsolete fragment identifier from IDE manual download link
The Arduino IDE has an auto update capability. A new version is checked for on every startup, and if available the user
is offered an update.

Although this update can usually be done automatically by the IDE, under some conditions this is not possible. For
example:

- The IDE package in use does not support auto update (i.e., Linux ZIP package)
- The file could not be downloaded due to a transient network service outage

In this case, the user is presented with a friendly dialog that explains the situation and links to the "Software" page
on arduino.cc, where the user can manually download and install the new version.

During the pre-release development phase of the project, the download links for Arduino IDE 2.x were on a sub-section of
the "Software" page. For this reason, the linked URL included the fragment identifier `#experimental-software` so that
the page would load scrolled down to the anchor at that section of the page.

With the 2.0.0 release, the Arduino IDE 2.x project has graduated to a production development phase. For this reason,
the download links have been moved to the top of the "Software" page and the now inaccurate `experimental-software`
anchor removed from the page.

The previous link with that fragment is still perfectly functional, but the fragment to a non-existent anchor serves no
purpose and also miscommunicates the project status to users who notice the URL that was loaded. For this reason, it is
hereby removed from the link.
2022-09-14 05:14:58 -07:00
Alberto Iannaccone
6e3fe08c4c update README.md 2022-09-13 23:58:23 -07:00
Alberto Iannaccone
7f06b148f4 Revert "change naming of nightly and snapshot builds (#1326)"
This reverts commit 5be1f9d7fe.
2022-09-13 23:58:23 -07:00
Alberto Iannaccone
bf303d1b2f 2.0.0 2022-09-13 23:58:23 -07:00
per1234
59ca91d805 Remove table of nightly build links from readme
During the early phase of development, the download links for the nightly build were only available from the table in the project readme.

Since that time, download links were also added to the "Software" page on arduino.cc, which is already linked to from
the readme. This means the nightly build link table is superfluous and only harms the readability of the readme.

The superfluous table is hereby removed from the readme.
2022-09-12 06:04:36 -07:00
github-actions[bot]
69bb0aa385 Updated translation files (#1421)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2022-09-12 09:53:06 +02:00
per1234
565970e779 Update release procedure documentation
An internal release procedure document was created separately from the documentation hosted in this repository. That
internal document became significantly more comprehensive and up to date than the unmaintained documentation in this
repository.

In order to avoid either the burden of maintaining two copies of the same information, or more likely the out of sync
state between the information in the two resulting from lack of such maintenance, a single document will be maintained
here in this repository.

The superior version of the information from the internal document is hereby migrated to the repository where it will be
maintained from here on.
2022-09-08 13:30:36 -07:00
per1234
fec3b1138b Move release procedure documentation to more appropriate location
Previously, the procedure for creating a new release of the project was included in the development documentation.

This information is distinct from the rest of the contents of that file in that it is not of any value or interest to
most contributors from the community since only project maintainers will ever create a release. This meant that it make
the document less readable and approachable without adding significant value in return.

The information is still essential to the project maintainers, so it must not be removed, but it can be moved to a
dedicated file under the existing `docs/internal/` folder that is specifically intended for storing such information.
2022-09-08 13:30:36 -07:00
Alberto Iannaccone
dcc0c0aa5d Prepare 2.0.0-rc9.4 (#1411) 2022-09-08 10:00:42 +02:00
Muhammad Zaheer
76673cb553 Time format in SerialMonitor changed.Fixes #580 2022-09-08 00:15:26 -07:00
per1234
8f95fd6ca6 Add instructions for accessing IDE's advanced settings
Although the Arduino IDE's primary preferences interface provides all required configuration capabilities, advanced
users may wish to fine tune the behavior of the application or temporarily enable additional log output to use for
troubleshooting problems with the IDE.

The IDE provides such settings in a separate interface.

Previously, the existence and access procedure for these settings was undocumented.

Since this is an advanced capability, the documentation is not appropriate for inclusion with the standard user
documentation on arduino.cc. A file here in the Arduino IDE is used instead. This file will serve as a container for all
such user-targeted documentation.
2022-09-07 00:16:14 -07:00
Akos Kitta
4907ef2a47 Prepared 2.0.0-rc9.3.
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-09-05 11:17:38 +02:00
github-actions[bot]
9ae3402631 Updated translation files 2022-09-05 10:22:13 +02:00
Akos Kitta
d0dfc656e6 Improved the scrolling UX in list widgets
- Fixed scrollbar does not reach end of list widget.
 - Estimated row heights to provide better scroll UX.
 - Last item's `<select>` must be visible.

Closes #1380
Closes #1381
Closes #1387

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-09-05 10:20:05 +02:00
Akos Kitta
df3a34eec6 Coerce a semver when calculating updatables.
Closes #1390

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-09-05 10:00:29 +02:00
Akos Kitta
20cc34ca9d Use CLI 0.27.0-rc.1.
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-09-02 16:24:48 +02:00
Akos Kitta
1b7f86b231 Install the Arduino_BuiltIn to built-in location
Closes #1055.

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-09-02 16:24:48 +02:00
Akos Kitta
0d545bea0e Show ports if has recognized board attached to it.
Closes #1365

 - Ref: 79ea0fa9a6
 - Ref: 74bfdc4c56

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-09-01 09:08:20 +02:00
Akos Kitta
204d71b2dd Fixed highlighting of non-unicode chars in Output
Closes #1210

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-08-31 21:16:07 +02:00
Akos Kitta
5cb9166c83 Implemented filter and update all for libs/boards.
Closes #177
Closes #1188

Co-authored-by: Francesco Spissu <f.spissu@arduino.cc>
Co-authored-by: Per Tillisch <p.tillisch@arduino.cc>
Co-authored-by: Akos Kitta <a.kitta@arduino.cc>

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-08-31 10:07:27 +02:00
github-actions[bot]
7828cc11ac Updated translation files (#1305)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2022-08-31 09:50:01 +02:00
Akos Kitta
34a7fdb733 Pinned 63f1e18 CLI.
Ref: 63f1e1855a
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-08-26 18:35:11 +02:00
Akos Kitta
7c361cf2d1 Can close non-root sketch file editors.
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-08-26 14:18:39 +02:00
Akos Kitta
8beade0867 Fixed sketch content changes when renaming a file.
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-08-26 14:18:39 +02:00
Akos Kitta
3afc2d7e4b Fixed dirty indicator of uncloseable widgets.
Closes #1034.

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-08-26 14:18:39 +02:00
Akos Kitta
d40401437a removed space from discovery json log.
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-08-26 14:18:39 +02:00
Akos Kitta
10ac7fd50a Removed File > Close Editor.
Closes arduino/arduino-ide#660

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-08-26 14:18:39 +02:00
Akos Kitta
07962e81d4 Moved uncloseable widget tracking to manager.
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-08-26 14:18:39 +02:00
Akos Kitta
785775327b Updated translations.
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-08-26 14:18:39 +02:00
Akos Kitta
80dfa5b7dd Restored logic to close current closable widget
and then the window.

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-08-26 14:18:39 +02:00
Akos Kitta
40425d49e0 Unified the sketch close and the app quit logic.
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-08-26 14:18:39 +02:00
Akos Kitta
0c87fa9877 Update currentSketch when files change.
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-08-26 14:18:39 +02:00
Akos Kitta
5b79320302 do not try to restore temp sketches.
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-08-26 14:18:39 +02:00
Akos Kitta
1da2dfc349 No save dialog prompt if closing untouched sketch.
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-08-26 14:18:39 +02:00
Akos Kitta
d7bbfc515d init
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-08-26 14:18:39 +02:00
Francesco Spissu
0c22884729 Error message if upload is not possible (#1353) 2022-08-26 11:24:03 +02:00
Akos Kitta
fc9107c084 Use addressLabel in the UI.
- for the boards dropdown, and
 - for the `Tools` > `Port` menu.

Closes #1331

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-08-25 11:49:50 +02:00
Akos Kitta
474d5e5975 Added a workaround for missing port#properties.
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-08-25 11:49:50 +02:00
Akos Kitta
f7f644cf36 Use port properties from the discovery.
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>

Closes #740
2022-08-25 11:49:50 +02:00
Dave Simpson
b5f9aa0f15 change hard coded max and min (#1345) 2022-08-24 12:32:42 +02:00
Dave Simpson
cc5cf3b165 fix 180: prevent erroneous "auto-reconnect"(s) in board selector (#1328)
* ensure auto-select doesn't select wrong port

prevent auto-select of unattached boards Co-authored-by: Francesco Spissu <francescospissu@users.noreply.github.com>

* clean up

* add "uploadInProgress" prop to boards change event

* remove unused methods and deps

* [WIP]: leverage upload event to derived new port

* remove timeout

* refine port selection logic

* clean up naming

* refine port selection logic & add delayed clean up

* renaming & refactoring

* method syntax & remove unnecessary methods
2022-08-24 12:31:51 +02:00
per1234
125bd64c91 Install Arduino CLI build dependencies in all dependent workflows
Arduino CLI is a tool dependency of Arduino IDE. For this reason, the necessary Arduino CLI build is acquired whenever
running the `yarn` command in the repository.

The way the Arduino CLI build is acquired depends on the type of version specified as dependency in the
`arduino.cli.version` field of the arduino-ide-extension package metadata:

- Release/nightly: download pre-built standard distribution
- Git ref: build from source

This means that, in the latter case, all build dependencies of Arduino CLI must be present. While the Go module
dependencies are automatically installed during the build, the build tool dependencies must be installed in advance:

- Go programming language
- Task task runner

Arduino IDE's infrastructure was recently changed to use the Task tool to build Arduino CLI in the supported manner. A
step to install Task was not added to some of the workflows that run `yarn`, which caused them to fail when a
non-release version of Arduino CLI was used as a dependency:

arduino-ide-extension: >>> Building the CLI...
arduino-ide-extension: /bin/sh: 1: task: not found
arduino-ide-extension: error Command failed with exit code 1.

A step for the missing tool dependency is hereby added to those workflows.

The lack of an explicit installation of the other dependency, Go did not result in an error because Go is pre-installed
on the GitHub Actions runner. However, the installed version may not match the version Arduino CLI is intended to be
built with and validated for, and the version provided by the runner may change at any time. For this reason, it will be
safest to explicitly set up the appropriate version of Go in the workflows.
2022-08-24 01:11:21 -07:00
per1234
ca47e8a09a Fix inconsistency of input field placeholder text capitalization
The board search input field of the "Select Other Board and Port" dialog uses placeholder text to explain the usage of
the field to the user.

All other placeholder text in the IDE's UI uses sentence case. This specific placeholder was the exception, using
unpleasant caps lock instead.

The inconsistency is resolved by changing the placeholder text to the standard sentence case.
2022-08-22 01:06:18 -07:00
per1234
52804a5b52 Add missing i18n for UI strings
The text of the Arduino IDE user interface has been localized to 12 languages.

Before localization can be accomplished, internationalization must be done in the application's code base:

- Set up infrastructure to export localization data
- Pass all target strings to that infrastructure

While the first of these tasks is completed, the second was not completed for several strings which are part of the user
interface.

Those outstanding strings are hereby internationalized and will be made available for localization.
2022-08-22 01:06:18 -07:00
per1234
3ec62642dd Fix typos in log messages
Several of the log messages contained minor typos.
2022-08-21 05:45:49 -07:00
per1234
1281ad1932 Use more relevant page for "Help > Environment" menu item target
Selecting "Help > Environment" from the Arduino IDE menus opens a page containing usage information for the Arduino IDE
application in the browser.

Previously, the URL used was the same as that of in Arduino IDE 1.x:

https://www.arduino.cc/en/Guide/Environment

The documentation from that page was written for Arduino IDE 1.x. Even though the UI of the two versions is aligned for
the most part, some advancements made for the 2.x major version series resulted in some differences. This means that
documentation targeted at Arduino IDE 1.x is not always applicable to Arduino IDE 2.x.

Fortunately, documentation is now available for each major version series of the IDE. So resolution is only a matter of
pointing the menu item at the correct URL.
2022-08-21 05:45:17 -07:00
Alberto Iannaccone
de32bddc20 Fix dialogs UI scalability (#1311)
* make dialogs scroll when scaling up the UI

* add unit of measure to settings step input

* wrap settings dialog items when scaling up the UI

* fix dialogs width when scaling up the UI

* rework board config UI to make it scale up better

* refactor ide updater dialog: move buttons outside the dialog content

* refactor ide updater dialog: clean-up code and rename events

* fix board config dialog title case and and remove double ellipsis
2022-08-18 16:42:16 +02:00
Akos Kitta
79ea0fa9a6 Show all network and serial ports.
Otherwise, unrecognized network boards are ignored
by IDE2.

Closes #1327

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-08-18 11:03:27 +02:00
Akos Kitta
683219dc1c Fixed typos.
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-08-18 11:03:27 +02:00
Akos Kitta
d674ab9b73 Handle missing core when getting board user fields
Closes #1142

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-08-18 10:56:03 +02:00
Alberto Iannaccone
5be1f9d7fe change naming of nightly and snapshot builds (#1326)
replace `-` with `.` to make auto-update work correctly
2022-08-17 17:13:25 +02:00
per1234
9e2b73a045 Use unmodified official ClangFormat configuration as base formatter configuration (#1324)
The Arduino IDE's "Auto Format" feature is configured to produce the standard Arduino sketch formatting style by
default.

The Arduino IDE editor's default settings are compliant with that style. However, the user may adjust the editor
settings. In this case, the Arduino IDE automatically adjusts the Auto Format configuration to align with the user's
preferences.

The formatter configuration is consumed by several other projects in addition to the Arduino IDE. For this reason, the
configuration is hosted and maintained in a centralized location, from which it is pulled by all projects that use it.

Previously, the adjustment of the Arduino IDE formatter configuration according to the editor settings was integrated
into the configuration object itself. This meant that the standardized configuration had to be modified each time it was
pulled in to sync from the upstream source.

Moving the base formatter configuration object to a dedicated file, separated from the handling and adjustment code
allows syncs to be done by simply replacing the existing configuration file with the one automatically generated by the
CI system of the repository where the source configuration is hosted.
2022-08-16 08:09:39 -07:00
per1234
75e00c2bae Document clangd update procedure
Arduino IDE has dependencies on the clangd C++ language server and ClangFormat code formatter tools. These are updated
periodically to benefit from the ongoing development on those projects.

The update procedure requires operations in three different repositories:

- Generate builds in arduino/clang-static-binaries
- Validate and update formatter configuration in arduino/tooling-project-assets
- Update metadata in arduino/arduino-ide

Previously, this was undocumented and the procedure existed only in the form of "institutional memory".

The procedure is now fully documented in the readme of arduino-ide-extension.
2022-08-15 08:42:31 -07:00
Akos Kitta
989300f25d Close core error notification on subsequent action
Closes #1154

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-08-15 16:55:17 +02:00
Akos Kitta
5226636fed Link compiler errors to editor.
Closes #118

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-08-15 16:55:17 +02:00
Akos Kitta
8b3f3c69fc Use the refactored CLI in IDE2.
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-08-15 09:19:57 +02:00
Akos Kitta
a39ab47e70 Use Task to build pinned CLI for IDE2.
Closes #1313

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-08-11 09:28:50 +02:00
Alberto Iannaccone
9cabd40429 2.0.0-rc9.2 (#1312)
* 2.0.0-rc9.2

* use arduino-cli version 0.26.0-rc1
2022-08-10 13:04:02 +02:00
Francesco Spissu
6e3681896c Add Auto Format item under the Edit menu (#1230) 2022-08-10 11:36:53 +02:00
Akos Kitta
8a1cabd2bc Defer notification area rendering until app ready.
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-08-09 17:23:10 +02:00
Akos Kitta
7a3e6789d1 Defer settings/certificates load until app ready.
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-08-09 17:23:10 +02:00
Akos Kitta
92bc5ecf7b Replaced the splash screen with a preload.
Added a bare minimum example.

Closes #193
Closes #324
Closes #327
Closes #717
Closes #851

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-08-09 17:23:10 +02:00
Francesco Spissu
aebec0f942 Live change of theme from Preferences dropdown (#1296) 2022-08-09 14:40:56 +02:00
per1234
54db9bbce8 Sync sketch formatter configuration from source
The Arduino IDE's "Auto Format" feature is configured to produce the standard Arduino sketch formatting style, as
established by the Arduino IDE 1.x formatter.

The configuration is consumed by several other projects which require the configuration in a YAML file. In order to
provide all the consumers with a single canonical source and to locate the infrastructure and activity related to the
maintenance of the file in a more appropriate repository, it is now hosted in a permanent location in the
`arduino/tooling-project-assets` repository.

The following changes have been made to the source configuration:

- Move documentation comments to a dedicated file in the upstream repository
- Make additional non-functional changes to the configuration format to facilitate maintenance
- Update to use the configuration API of ClangFormat 14.0.0

This last item did result in some functional changes to the configuration which will result in minor differences in the
formatter output.

These are actually reversions of unwanted differences from the Arduino IDE 1.x formatter output, which were unavoidable
when using the 11.0.1 version of ClangFormat in use at the time of the configuration's creation. These changes will
provide greater consistency during the migration from Arduino IDE 1.x to 2.x. The default output of the Arduino IDE
1.x formatter will continue to be considered the "gold standard" until Arduino IDE 2.x graduates from "pre-release"
status.

The Arduino IDE 2.x formatter configuration is fully customizable according to the preferences of each user. Those
already using custom configurations will not be affected in any way (though they are encouraged to sync their
configuration files from the source to bring them into compliance with the configuration API of the ClangFormat version
currently in use by Arduino IDE 2.x).

See the documentation and commit history for the source file for details on the configuration changes:

https://github.com/arduino/tooling-project-assets/tree/main/other/clang-format-configuration
2022-08-08 12:48:41 -07:00
per1234
676eb2f588 Escape special characters in formatter configuration for Windows
The sketch code formatter configuration is passed to the ClangFormat tool as a string representing a JSON object via a
command line argument.

Previously, the contents of this string were not given any special treatment to ensure compatibility with the command
interpreter used on Windows machines. That did not result in problems only because the configuration didn't contain
problematic combinations of characters. This good fortune will not persist through updates to the configuration, so the
command must be properly processed.

The Windows command interpreter does not use the POSIX style backslash escaping. For this reason, escaped quotes in the
argument are recognized as normal quotes, meaning that the string alternates between quoted and unquoted states at
random. When a character with special significance to the Windows command interpreter happens to occur outside a quoted
section, an error results.

The solution is to use the Windows command interpreter's caret escaping on these characters. Since such an escaping
system is not recognized by POSIX shells, this is only done when the application is running on a Windows machine.

References:

- https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/echo#remarks
- https://en.wikipedia.org/wiki/Escape_character#Windows_Command_Prompt
2022-08-08 12:48:41 -07:00
per1234
ce273adf77 Correctly escape escaped content in formatter configuration
The sketch code formatter configuration is passed to the ClangFormat tool as a string representing a JSON object via a
command line argument.

The quotes in the JSON syntax are escaped in order to make them compatible with this usage. Previously, consideration
was not given to escaping of the content. For example, with the previous escaping code, this content: `\"` would be
converted to `\\"`, whereas the correct escaping would look like `\\\"`.

That did not result in problems only because the configuration didn't contain escaped content. This good fortune will
not persist through updates to the configuration so the command must be properly processed.

The content of the configuration will now be escaped in addition to the quotes of the JSON data format.
2022-08-08 12:48:41 -07:00
Akos Kitta
0b33b51700 Set XDG_CONFIG_HOME env on Linux when not set.
Otherwise, `node-log-rotate` creates a folder with `undefined` name.

Closes #394.

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-08-04 16:29:27 +02:00
Akos Kitta
36ac47b975 Can check if the current window is the first one.
Closes #1070

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-08-04 11:11:46 +02:00
Akos Kitta
bf193b1cac Pinned 2dd8976 CLI in the IDE2. (#1280)
Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-08-04 09:28:28 +02:00
InstantMuffin
879aedeaa3 Update BUILDING.md (#1281)
* Update BUILDING.md

Added "Notes for Linux contributors" based on my own building experience

* Update BUILDING.md

Removing the linux specific section and instead updating the Theia IDE prerequisites link to point to the mentioned file directly.
2022-08-03 16:43:01 +02:00
Akos Kitta
d556ee95c0 Use FQBN instead of Board for the monitor ID.
Closes #1278

Signed-off-by: Akos Kitta <a.kitta@arduino.cc>
2022-08-03 15:16:39 +02:00
543 changed files with 49453 additions and 30335 deletions

View File

@@ -15,9 +15,10 @@ module.exports = {
'.browser_modules/*',
'docs/*',
'scripts/*',
'electron/*',
'electron-app/*',
'browser-app/*',
'electron-app/lib/*',
'electron-app/src-gen/*',
'electron-app/gen-webpack*.js',
'!electron-app/webpack.config.js',
'plugins/*',
'arduino-ide-extension/src/node/cli-protocol',
],

View File

@@ -30,7 +30,7 @@ body:
description: |
Which version of the Arduino IDE are you using?
See **Help > About Arduino IDE** in the Arduino IDE menus (**Arduino IDE > About Arduino IDE** on macOS).
This should be the latest [nightly build](https://github.com/arduino/arduino-ide#nightly-builds).
This should be the latest [nightly build](https://www.arduino.cc/en/software#nightly-builds).
validations:
required: true
- type: dropdown
@@ -68,7 +68,7 @@ body:
options:
- label: I searched for previous reports in [the issue tracker](https://github.com/arduino/arduino-ide/issues?q=)
required: true
- label: I verified the problem still occurs when using the latest [nightly build](https://github.com/arduino/arduino-ide#nightly-builds)
- label: I verified the problem still occurs when using the latest [nightly build](https://www.arduino.cc/en/software#nightly-builds)
required: true
- label: My report contains all necessary details
required: true

View File

@@ -8,6 +8,12 @@ contact_links:
- name: Support request
url: https://forum.arduino.cc/
about: We can help you out on the Arduino Forum!
- name: Issue report guide
url: https://github.com/arduino/arduino-ide/blob/main/docs/contributor-guide/issues.md#issue-report-guide
about: Learn about submitting issue reports to this repository.
- name: Contributor guide
url: https://github.com/arduino/arduino-ide/blob/main/docs/CONTRIBUTING.md#contributor-guide
about: Learn about contributing to this project.
- name: Discuss development work on the project
url: https://groups.google.com/a/arduino.cc/g/developers
about: Arduino Developers Mailing List

View File

@@ -25,7 +25,7 @@ body:
description: |
Which version of the Arduino IDE are you using?
See **Help > About Arduino IDE** in the Arduino IDE menus (**Arduino IDE > About Arduino IDE** on macOS).
This should be the latest [nightly build](https://github.com/arduino/arduino-ide#nightly-builds).
This should be the latest [nightly build](https://www.arduino.cc/en/software#nightly-builds).
validations:
required: true
- type: dropdown
@@ -63,7 +63,7 @@ body:
options:
- label: I searched for previous requests in [the issue tracker](https://github.com/arduino/arduino-ide/issues?q=)
required: true
- label: I verified the feature was still missing when using the latest [nightly build](https://github.com/arduino/arduino-ide#nightly-builds)
- label: I verified the feature was still missing when using the latest [nightly build](https://www.arduino.cc/en/software#nightly-builds)
required: true
- label: My request contains all necessary details
required: true

15
.github/dependabot.yml vendored Normal file
View File

@@ -0,0 +1,15 @@
# See: https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file#about-the-dependabotyml-file
version: 2
updates:
# Configure check for outdated GitHub Actions actions in workflows.
# Source: https://github.com/arduino/tooling-project-assets/blob/main/workflow-templates/assets/dependabot/README.md
# See: https://docs.github.com/code-security/dependabot/working-with-dependabot/keeping-your-actions-up-to-date-with-dependabot
- package-ecosystem: github-actions
directory: / # Check the repository's workflows under /.github/workflows/
assignees:
- per1234
schedule:
interval: daily
labels:
- "topic: infrastructure"

View File

@@ -7,6 +7,9 @@
- name: "topic: CLI"
color: "00ffff"
description: Related to Arduino CLI
- name: "topic: cloud"
color: "00ffff"
description: Related to Arduino Cloud and cloud sketches
- name: "topic: debugger"
color: "00ffff"
description: Related to the integrated debugger

View File

@@ -1,131 +0,0 @@
import boto3
import semver
import os
import logging
import uuid
import time
# logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
log = logging.getLogger()
logging.getLogger("boto3").setLevel(logging.CRITICAL)
logging.getLogger("botocore").setLevel(logging.CRITICAL)
logging.getLogger("urllib3").setLevel(logging.CRITICAL)
def execute(client, statement, dest_s3_output_location):
log.info("execute query: {} dumping in {}".format(statement, dest_s3_output_location))
result = client.start_query_execution(
QueryString=statement,
ClientRequestToken=str(uuid.uuid4()),
ResultConfiguration={
"OutputLocation": dest_s3_output_location,
},
)
execution_id = result["QueryExecutionId"]
log.info("wait for query {} completion".format(execution_id))
wait_for_query_execution_completion(client, execution_id)
log.info("operation successful")
return execution_id
def wait_for_query_execution_completion(client, query_execution_id):
query_ended = False
while not query_ended:
query_execution = client.get_query_execution(QueryExecutionId=query_execution_id)
state = query_execution["QueryExecution"]["Status"]["State"]
if state == "SUCCEEDED":
query_ended = True
elif state in ["FAILED", "CANCELLED"]:
raise BaseException(
"query failed or canceled: {}".format(query_execution["QueryExecution"]["Status"]["StateChangeReason"])
)
else:
time.sleep(1)
def valid(key):
split = key.split("_")
if len(split) < 1:
return False
try:
semver.parse(split[0])
except ValueError:
return False
return True
def get_results(client, execution_id):
results_paginator = client.get_paginator("get_query_results")
results_iter = results_paginator.paginate(QueryExecutionId=execution_id, PaginationConfig={"PageSize": 1000})
res = {}
for results_page in results_iter:
for row in results_page["ResultSet"]["Rows"][1:]:
# Loop through the JSON objects
key = row["Data"][0]["VarCharValue"]
if valid(key):
res[key] = row["Data"][1]["VarCharValue"]
return res
def convert_data(data):
result = []
for key, value in data.items():
# 0.18.0_macOS_64bit.tar.gz
split_key = key.split("_")
if len(split_key) != 3:
continue
(version, os_version, arch) = split_key
arch_split = arch.split(".")
if len(arch_split) < 1:
continue
arch = arch_split[0]
if len(arch) > 10:
# This can't be an architecture really.
# It's an ugly solution but works for now so deal with it.
continue
repo = os.environ["GITHUB_REPOSITORY"].split("/")[1]
result.append(
{
"type": "gauge",
"name": "arduino.downloads.total",
"value": value,
"host": os.environ["GITHUB_REPOSITORY"],
"tags": [
f"version:{version}",
f"os:{os_version}",
f"arch:{arch}",
"cdn:downloads.arduino.cc",
f"project:{repo}",
],
}
)
return result
if __name__ == "__main__":
DEST_S3_OUTPUT = os.environ["AWS_ATHENA_OUTPUT_LOCATION"]
AWS_ATHENA_SOURCE_TABLE = os.environ["AWS_ATHENA_SOURCE_TABLE"]
session = boto3.session.Session(region_name="us-east-1")
athena_client = session.client("athena")
# Load all partitions before querying downloads
execute(athena_client, f"MSCK REPAIR TABLE {AWS_ATHENA_SOURCE_TABLE};", DEST_S3_OUTPUT)
query = f"""SELECT replace(json_extract_scalar(url_decode(url_decode(querystring)),
'$.data.url'), 'https://downloads.arduino.cc/arduino-ide/arduino-ide_', '')
AS flavor, count(json_extract(url_decode(url_decode(querystring)),'$')) AS gauge
FROM {AWS_ATHENA_SOURCE_TABLE}
WHERE json_extract_scalar(url_decode(url_decode(querystring)),'$.data.url')
LIKE 'https://downloads.arduino.cc/arduino-ide/arduino-ide_%'
AND json_extract_scalar(url_decode(url_decode(querystring)),'$.data.url')
NOT LIKE '%latest%' -- exclude latest redirect
group by 1 ;"""
exec_id = execute(athena_client, query, DEST_S3_OUTPUT)
results = get_results(athena_client, exec_id)
result_json = convert_data(results)
print(f"::set-output name=result::{result_json}")

View File

@@ -1,57 +0,0 @@
name: arduino-stats
on:
schedule:
# run every day at 07:00 AM, 03:00 PM and 11:00 PM
- cron: "0 7,15,23 * * *"
workflow_dispatch:
repository_dispatch:
jobs:
push-stats:
# This workflow is only of value to the arduino/arduino-ide repository and
# would always fail in forks
if: github.repository == 'arduino/arduino-ide'
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
- uses: actions/setup-python@v2
with:
python-version: '3.x'
- name: Fetch downloads count form Arduino CDN using AWS Athena
id: fetch
env:
AWS_ACCESS_KEY_ID: ${{ secrets.STATS_AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.STATS_AWS_SECRET_ACCESS_KEY }}
AWS_ATHENA_SOURCE_TABLE: ${{ secrets.STATS_AWS_ATHENA_SOURCE_TABLE }}
AWS_ATHENA_OUTPUT_LOCATION: ${{ secrets.STATS_AWS_ATHENA_OUTPUT_LOCATION }}
GITHUB_REPOSITORY: ${{ github.repository }}
run: |
pip install boto3 semver
python .github/tools/fetch_athena_stats.py
- name: Send metrics
uses: masci/datadog@v1
with:
api-key: ${{ secrets.DD_API_KEY }}
# Metrics input expects YAML but JSON will work just right.
metrics: ${{steps.fetch.outputs.result}}
- name: Report failure
if: failure()
uses: masci/datadog@v1
with:
api-key: ${{ secrets.DD_API_KEY }}
events: |
- title: "Arduino IDE stats failing"
text: "Stats collection failed"
alert_type: "error"
host: ${{ github.repository }}
tags:
- "project:arduino-ide"
- "cdn:downloads.arduino.cc"
- "workflow:${{ github.workflow }}"

View File

@@ -1,9 +1,11 @@
name: Arduino IDE
on:
create:
push:
branches:
- main
- '[0-9]+.[0-9]+.x'
paths-ignore:
- '.github/**'
- '!.github/workflows/build.yml'
@@ -28,20 +30,48 @@ on:
- cron: '0 3 * * *' # run every day at 3AM (https://docs.github.com/en/actions/reference/events-that-trigger-workflows#scheduled-events-schedule)
env:
# See vars.GO_VERSION field of https://github.com/arduino/arduino-cli/blob/master/DistTasks.yml
GO_VERSION: "1.19"
JOB_TRANSFER_ARTIFACT: build-artifacts
CHANGELOG_ARTIFACTS: changelog
jobs:
run-determination:
runs-on: ubuntu-latest
outputs:
result: ${{ steps.determination.outputs.result }}
permissions: {}
steps:
- name: Determine if the rest of the workflow should run
id: determination
run: |
RELEASE_BRANCH_REGEX="refs/heads/[0-9]+.[0-9]+.x"
# The `create` event trigger doesn't support `branches` filters, so it's necessary to use Bash instead.
if [[
"${{ github.event_name }}" != "create" ||
"${{ github.ref }}" =~ $RELEASE_BRANCH_REGEX
]]; then
# Run the other jobs.
RESULT="true"
else
# There is no need to run the other jobs.
RESULT="false"
fi
echo "result=$RESULT" >> $GITHUB_OUTPUT
build:
name: build (${{ matrix.config.os }})
needs: run-determination
if: needs.run-determination.outputs.result == 'true'
strategy:
matrix:
config:
- os: windows-2019
certificate-secret: WINDOWS_SIGNING_CERTIFICATE_PFX # Name of the secret that contains the certificate.
certificate-password-secret: WINDOWS_SIGNING_CERTIFICATE_PASSWORD # Name of the secret that contains the certificate password.
certificate-extension: pfx # File extension for the certificate.
- os: ubuntu-18.04 # https://github.com/arduino/arduino-ide/issues/259
certificate-extension: pfx # File extension for the certificate.
- os: ubuntu-20.04
- os: macos-latest
# 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
@@ -53,19 +83,31 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v2
uses: actions/checkout@v3
- name: Install Node.js 14.x
uses: actions/setup-node@v1
- name: Install Node.js 16.14
uses: actions/setup-node@v3
with:
node-version: '14.x'
node-version: '16.14'
registry-url: 'https://registry.npmjs.org'
cache: 'yarn'
- name: Install Python 3.x
uses: actions/setup-python@v2
uses: actions/setup-python@v4
with:
python-version: '3.x'
- name: Install Go
uses: actions/setup-go@v4
with:
go-version: ${{ env.GO_VERSION }}
- name: Install Taskfile
uses: arduino/setup-task@v1
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
version: 3.x
- name: Package
shell: bash
env:
@@ -86,20 +128,30 @@ jobs:
export CSC_LINK="${{ runner.temp }}/signing_certificate.${{ matrix.config.certificate-extension }}"
echo "${{ secrets[matrix.config.certificate-secret] }}" | base64 --decode > "$CSC_LINK"
export CSC_KEY_PASSWORD="${{ secrets[matrix.config.certificate-password-secret] }}"
export CSC_FOR_PULL_REQUEST=true
fi
if [ "${{ runner.OS }}" = "Windows" ]; then
npm config set msvs_version 2017 --global
fi
npx node-gyp install
yarn --cwd ./electron/packager/
yarn --cwd ./electron/packager/ package
yarn install --immutable
yarn --cwd arduino-ide-extension build
yarn test
yarn --cwd arduino-ide-extension test:slow
yarn --cwd arduino-ide-extension lint
yarn --cwd electron-app rebuild
yarn --cwd electron-app build
yarn --cwd electron-app package
- name: Upload [GitHub Actions]
uses: actions/upload-artifact@v2
uses: actions/upload-artifact@v3
with:
name: ${{ env.JOB_TRANSFER_ARTIFACT }}
path: electron/build/dist/build-artifacts/
path: electron-app/dist/build-artifacts
artifacts:
name: ${{ matrix.artifact.name }} artifact
@@ -127,13 +179,13 @@ jobs:
steps:
- name: Download job transfer artifact
uses: actions/download-artifact@v2
uses: actions/download-artifact@v3
with:
name: ${{ env.JOB_TRANSFER_ARTIFACT }}
path: ${{ env.JOB_TRANSFER_ARTIFACT }}
- name: Upload tester build artifact
uses: actions/upload-artifact@v2
uses: actions/upload-artifact@v3
with:
name: ${{ matrix.artifact.name }}
path: ${{ env.JOB_TRANSFER_ARTIFACT }}/${{ matrix.artifact.path }}
@@ -145,7 +197,7 @@ jobs:
BODY: ${{ steps.changelog.outputs.BODY }}
steps:
- name: Checkout
uses: actions/checkout@v2
uses: actions/checkout@v3
with:
fetch-depth: 0 # To fetch all history for all branches and tags.
@@ -167,15 +219,19 @@ jobs:
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"
# Set workflow step output
# See: https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#multiline-strings
DELIMITER="$RANDOM"
echo "BODY<<$DELIMITER" >> $GITHUB_OUTPUT
echo "$BODY" >> $GITHUB_OUTPUT
echo "$DELIMITER" >> $GITHUB_OUTPUT
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
uses: actions/upload-artifact@v3
with:
name: ${{ env.JOB_TRANSFER_ARTIFACT }}
path: CHANGELOG.txt
@@ -186,7 +242,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Download [GitHub Actions]
uses: actions/download-artifact@v2
uses: actions/download-artifact@v3
with:
name: ${{ env.JOB_TRANSFER_ARTIFACT }}
path: ${{ env.JOB_TRANSFER_ARTIFACT }}
@@ -207,7 +263,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Download [GitHub Actions]
uses: actions/download-artifact@v2
uses: actions/download-artifact@v3
with:
name: ${{ env.JOB_TRANSFER_ARTIFACT }}
path: ${{ env.JOB_TRANSFER_ARTIFACT }}
@@ -215,10 +271,10 @@ jobs:
- name: Get Tag
id: tag_name
run: |
echo ::set-output name=TAG_NAME::${GITHUB_REF#refs/tags/}
echo "TAG_NAME=${GITHUB_REF#refs/tags/}" >> $GITHUB_OUTPUT
- name: Publish Release [GitHub]
uses: svenstaro/upload-release-action@2.2.0
uses: svenstaro/upload-release-action@2.7.0
with:
repo_token: ${{ secrets.GITHUB_TOKEN }}
release_name: ${{ steps.tag_name.outputs.TAG_NAME }}
@@ -227,6 +283,15 @@ jobs:
file_glob: true
body: ${{ needs.changelog.outputs.BODY }}
# Temporary measure to prevent release update offers before the manually produced builds are uploaded.
# The step must be removed once fully automated builds are regained.
- name: Remove "channel update info files" related to manual builds
run: |
# See: https://github.com/arduino/arduino-ide/issues/2018
rm "${{ env.JOB_TRANSFER_ARTIFACT }}/stable-linux.yml"
# See: https://github.com/arduino/arduino-ide/issues/408
rm "${{ env.JOB_TRANSFER_ARTIFACT }}/stable-mac.yml"
- name: Publish Release [S3]
if: github.repository == 'arduino/arduino-ide'
uses: docker://plugins/s3
@@ -250,6 +315,6 @@ jobs:
steps:
- name: Remove unneeded job transfer artifact
uses: geekyeggo/delete-artifact@v1
uses: geekyeggo/delete-artifact@v2
with:
name: ${{ env.JOB_TRANSFER_ARTIFACT }}

View File

@@ -3,6 +3,7 @@ name: Check Certificates
# See: https://docs.github.com/en/actions/reference/events-that-trigger-workflows
on:
create:
push:
paths:
- '.github/workflows/check-certificates.ya?ml'
@@ -20,12 +21,49 @@ env:
EXPIRATION_WARNING_PERIOD: 30
jobs:
run-determination:
runs-on: ubuntu-latest
outputs:
result: ${{ steps.determination.outputs.result }}
steps:
- name: Determine if the rest of the workflow should run
id: determination
run: |
RELEASE_BRANCH_REGEX="refs/heads/[0-9]+.[0-9]+.x"
REPO_SLUG="arduino/arduino-ide"
if [[
(
# Only run on branch creation when it is a release branch.
# The `create` event trigger doesn't support `branches` filters, so it's necessary to use Bash instead.
"${{ github.event_name }}" != "create" ||
"${{ github.ref }}" =~ $RELEASE_BRANCH_REGEX
) &&
(
# Only run when the workflow will have access to the certificate secrets.
# This could be done via a GitHub Actions workflow conditional, but makes more sense to do it here as well.
(
"${{ github.event_name }}" != "pull_request" &&
"${{ github.repository }}" == "$REPO_SLUG"
) ||
(
"${{ github.event_name }}" == "pull_request" &&
"${{ github.event.pull_request.head.repo.full_name }}" == "$REPO_SLUG"
)
)
]]; then
# Run the other jobs.
RESULT="true"
else
# There is no need to run the other jobs.
RESULT="false"
fi
echo "result=$RESULT" >> $GITHUB_OUTPUT
check-certificates:
name: ${{ matrix.certificate.identifier }}
# Only run when the workflow will have access to the certificate secrets.
if: >
(github.event_name != 'pull_request' && github.repository == 'arduino/arduino-ide') ||
(github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == 'arduino/arduino-ide')
needs: run-determination
if: needs.run-determination.outputs.result == 'true'
runs-on: ubuntu-latest
strategy:
fail-fast: false
@@ -59,7 +97,9 @@ jobs:
(
openssl pkcs12 \
-in "${{ env.CERTIFICATE_PATH }}" \
-noout -passin env:CERTIFICATE_PASSWORD
-legacy \
-noout \
-passin env:CERTIFICATE_PASSWORD
) || (
echo "::error::Verification of ${{ matrix.certificate.identifier }} failed!!!"
exit 1
@@ -87,6 +127,7 @@ jobs:
openssl pkcs12 \
-in "${{ env.CERTIFICATE_PATH }}" \
-clcerts \
-legacy \
-nodes \
-passin env:CERTIFICATE_PASSWORD
) | (
@@ -108,7 +149,7 @@ jobs:
echo "Certificate expiration date: $EXPIRATION_DATE"
echo "Days remaining before expiration: $DAYS_BEFORE_EXPIRATION"
echo "::set-output name=days::$DAYS_BEFORE_EXPIRATION"
echo "days=$DAYS_BEFORE_EXPIRATION" >> $GITHUB_OUTPUT
- name: Check if expiration notification period has been reached
id: check-expiration

View File

@@ -1,7 +1,12 @@
name: Check Internationalization
env:
# See vars.GO_VERSION field of https://github.com/arduino/arduino-cli/blob/master/DistTasks.yml
GO_VERSION: "1.19"
# See: https://docs.github.com/en/actions/reference/events-that-trigger-workflows
on:
create:
push:
paths:
- '.github/workflows/check-i18n-task.ya?ml'
@@ -18,21 +23,63 @@ on:
repository_dispatch:
jobs:
run-determination:
runs-on: ubuntu-latest
outputs:
result: ${{ steps.determination.outputs.result }}
permissions: {}
steps:
- name: Determine if the rest of the workflow should run
id: determination
run: |
RELEASE_BRANCH_REGEX="refs/heads/[0-9]+.[0-9]+.x"
TAG_REGEX="refs/tags/.*"
# The `create` event trigger doesn't support `branches` filters, so it's necessary to use Bash instead.
if [[
("${{ github.event_name }}" != "create" ||
"${{ github.ref }}" =~ $RELEASE_BRANCH_REGEX) &&
! "${{ github.ref }}" =~ $TAG_REGEX
]]; then
# Run the other jobs.
RESULT="true"
else
# There is no need to run the other jobs.
RESULT="false"
fi
echo "result=$RESULT" >> $GITHUB_OUTPUT
check:
needs: run-determination
if: needs.run-determination.outputs.result == 'true'
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v2
uses: actions/checkout@v3
- name: Install Node.js 14.x
uses: actions/setup-node@v2
- name: Install Node.js 16.14
uses: actions/setup-node@v3
with:
node-version: '14.x'
node-version: '16.14'
registry-url: 'https://registry.npmjs.org'
cache: 'yarn'
- name: Install Go
uses: actions/setup-go@v4
with:
go-version: ${{ env.GO_VERSION }}
- name: Install Taskfile
uses: arduino/setup-task@v1
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
version: 3.x
- name: Install dependencies
run: yarn
run: yarn install --immutable
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Check for errors
run: yarn i18n:check

View File

@@ -8,7 +8,7 @@ on:
env:
CHANGELOG_ARTIFACTS: changelog
# See: https://github.com/actions/setup-node/#readme
NODE_VERSION: 14.x
NODE_VERSION: 16.x
jobs:
create-changelog:
@@ -16,7 +16,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
uses: actions/checkout@v3
- name: Install Node.js
uses: actions/setup-node@v3
@@ -27,7 +27,7 @@ jobs:
- name: Get Tag
id: tag_name
run: |
echo ::set-output name=TAG_NAME::${GITHUB_REF#refs/tags/}
echo "TAG_NAME=${GITHUB_REF#refs/tags/}" >> $GITHUB_OUTPUT
- name: Create full changelog
id: full-changelog

View File

@@ -1,96 +0,0 @@
name: github-stats
on:
schedule:
# run every 30 minutes
- cron: "*/30 * * * *"
workflow_dispatch:
repository_dispatch:
jobs:
push-stats:
# This workflow is only of value to the arduino/arduino-ide repository and
# would always fail in forks
if: github.repository == 'arduino/arduino-ide'
runs-on: ubuntu-latest
steps:
- name: Fetch downloads count
id: fetch
uses: actions/github-script@v4
with:
github-token: ${{github.token}}
script: |
let metrics = []
// Get a list of releases
const opts = github.repos.listReleases.endpoint.merge({
...context.repo
})
const releases = await github.paginate(opts)
// Get download stats for every release
for (const rel of releases) {
// Names for assets are like `arduino-ide_2.0.0-beta.12_Linux_64bit.zip`,
// we'll use this later to split the asset file name more easily
const baseName = `arduino-ide_${rel.name}_`
// Get a list of assets for this release
const opts = github.repos.listReleaseAssets.endpoint.merge({
...context.repo,
release_id: rel.id
})
const assets = await github.paginate(opts)
for (const asset of assets) {
// Ignore files that are not arduino-ide packages
if (!asset.name.startsWith(baseName)) {
continue
}
// Strip the base and remove file extension to get `Linux_32bit`
systemArch = asset.name.replace(baseName, "").split(".")[0].split("_")
// Add a metric object to the list of gathered metrics
metrics.push({
"type": "gauge",
"name": "arduino.downloads.total",
"value": asset.download_count,
"host": "${{ github.repository }}",
"tags": [
`version:${rel.name}`,
`os:${systemArch[0]}`,
`arch:${systemArch[1]}`,
"cdn:github.com",
"project:arduino-ide"
]
})
}
}
// The action will put whatever we return from this function in
// `outputs.result`, JSON encoded. So we just return the array
// of objects and GitHub will do the rest.
return metrics
- name: Send metrics
uses: masci/datadog@v1
with:
api-key: ${{ secrets.DD_API_KEY }}
# Metrics input expects YAML but JSON will work just right.
metrics: ${{steps.fetch.outputs.result}}
- name: Report failure
if: failure()
uses: masci/datadog@v1
with:
api-key: ${{ secrets.DD_API_KEY }}
events: |
- title: "Arduino IDE stats failing"
text: "Stats collection failed"
alert_type: "error"
host: ${{ github.repository }}
tags:
- "project:arduino-ide"
- "cdn:github.com"
- "workflow:${{ github.workflow }}"

View File

@@ -1,5 +1,9 @@
name: i18n-nightly-push
env:
# See vars.GO_VERSION field of https://github.com/arduino/arduino-cli/blob/master/DistTasks.yml
GO_VERSION: "1.19"
on:
schedule:
# run every day at 1AM
@@ -10,16 +14,28 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
uses: actions/checkout@v3
- name: Install Node.js 14.x
uses: actions/setup-node@v2
- name: Install Node.js 16.14
uses: actions/setup-node@v3
with:
node-version: '14.x'
node-version: '16.14'
registry-url: 'https://registry.npmjs.org'
cache: 'yarn'
- name: Install Go
uses: actions/setup-go@v4
with:
go-version: ${{ env.GO_VERSION }}
- name: Install Task
uses: arduino/setup-task@v1
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
version: 3.x
- name: Install dependencies
run: yarn
run: yarn install --immutable
- name: Run i18n:push script
run: yarn run i18n:push

View File

@@ -1,5 +1,9 @@
name: i18n-weekly-pull
env:
# See vars.GO_VERSION field of https://github.com/arduino/arduino-cli/blob/master/DistTasks.yml
GO_VERSION: "1.19"
on:
schedule:
# run every monday at 2AM
@@ -10,16 +14,28 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
uses: actions/checkout@v3
- name: Install Node.js 14.x
uses: actions/setup-node@v2
- name: Install Node.js 16.14
uses: actions/setup-node@v3
with:
node-version: '14.x'
node-version: '16.14'
registry-url: 'https://registry.npmjs.org'
cache: 'yarn'
- name: Install Go
uses: actions/setup-go@v4
with:
go-version: ${{ env.GO_VERSION }}
- name: Install Task
uses: arduino/setup-task@v1
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
version: 3.x
- name: Install dependencies
run: yarn
run: yarn install --immutable
- name: Run i18n:pull script
run: yarn run i18n:pull
@@ -30,7 +46,7 @@ jobs:
TRANSIFEX_API_KEY: ${{ secrets.TRANSIFEX_API_KEY }}
- name: Create Pull Request
uses: peter-evans/create-pull-request@v3
uses: peter-evans/create-pull-request@v5
with:
commit-message: Updated translation files
title: Update translation files

View File

@@ -27,11 +27,11 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v2
uses: actions/checkout@v3
- name: Download JSON schema for labels configuration file
id: download-schema
uses: carlosperate/download-file-action@v1
uses: carlosperate/download-file-action@v2
with:
file-url: https://raw.githubusercontent.com/arduino/tooling-project-assets/main/workflow-templates/assets/sync-labels/arduino-tooling-gh-label-configuration-schema.json
location: ${{ runner.temp }}/label-configuration-schema
@@ -66,12 +66,12 @@ jobs:
steps:
- name: Download
uses: carlosperate/download-file-action@v1
uses: carlosperate/download-file-action@v2
with:
file-url: https://raw.githubusercontent.com/arduino/tooling-project-assets/main/workflow-templates/assets/sync-labels/${{ matrix.filename }}
- name: Pass configuration files to next job via workflow artifact
uses: actions/upload-artifact@v2
uses: actions/upload-artifact@v3
with:
path: |
*.yaml
@@ -103,19 +103,19 @@ jobs:
run: |
# Use of this flag in the github-label-sync command will cause it to only check the validity of the
# configuration.
echo "::set-output name=flag::--dry-run"
echo "flag=--dry-run" >> $GITHUB_OUTPUT
- name: Checkout repository
uses: actions/checkout@v2
uses: actions/checkout@v3
- name: Download configuration files artifact
uses: actions/download-artifact@v2
uses: actions/download-artifact@v3
with:
name: ${{ env.CONFIGURATIONS_ARTIFACT }}
path: ${{ env.CONFIGURATIONS_FOLDER }}
- name: Remove unneeded artifact
uses: geekyeggo/delete-artifact@v1
uses: geekyeggo/delete-artifact@v2
with:
name: ${{ env.CONFIGURATIONS_ARTIFACT }}

View File

@@ -7,7 +7,9 @@ on:
workflow_dispatch:
env:
NODE_VERSION: 14.x
# See vars.GO_VERSION field of https://github.com/arduino/arduino-cli/blob/master/DistTasks.yml
GO_VERSION: "1.19"
NODE_VERSION: 16.x
jobs:
pull-from-jsonbin:
@@ -21,9 +23,21 @@ jobs:
with:
node-version: ${{ env.NODE_VERSION }}
registry-url: 'https://registry.npmjs.org'
cache: 'yarn'
- name: Install Go
uses: actions/setup-go@v4
with:
go-version: ${{ env.GO_VERSION }}
- name: Install Task
uses: arduino/setup-task@v1
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
version: 3.x
- name: Install dependencies
run: yarn
run: yarn install --immutable
- name: Run themes:pull script
run: yarn run themes:pull
@@ -41,7 +55,7 @@ jobs:
run: yarn run themes:generate
- name: Create Pull Request
uses: peter-evans/create-pull-request@v4
uses: peter-evans/create-pull-request@v5
with:
commit-message: Updated themes
title: Update themes

19
.gitignore vendored
View File

@@ -1,25 +1,22 @@
node_modules/
# .node_modules is a hack for the electron builder.
.node_modules/
lib/
downloads/
build/
Examples/
!electron/build/
resources/
arduino-ide-extension/Examples/
src-gen/
!webpack.config.js
gen-webpack.config.js
gen-webpack.node.config.js
.DS_Store
# 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
electron-app/plugins
# the tokens folder for the themes
scripts/themes/tokens
# environment variables
.env
# content trace files for electron
electron-app/traces
# any Arduino LS generated log files
inols*.log
# The electron-builder output.
electron-app/dist

103
.vscode/launch.json vendored
View File

@@ -4,36 +4,33 @@
{
"type": "node",
"request": "launch",
"name": "App (Electron) [Dev]",
"runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron",
"name": "App",
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron",
"windows": {
"runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron.cmd",
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron.cmd",
},
"cwd": "${workspaceFolder}/electron-app",
"args": [
".",
"--log-level=debug",
"--hostname=localhost",
"--no-cluster",
"--app-project-path=${workspaceRoot}/electron-app",
"--app-project-path=${workspaceFolder}/electron-app",
"--remote-debugging-port=9222",
"--no-app-auto-install",
"--plugins=local-dir:../plugins",
"--plugins=local-dir:./plugins",
"--hosted-plugin-inspect=9339",
"--nosplash",
"--content-trace",
"--open-devtools"
"--no-ping-timeout",
],
"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",
"${workspaceRoot}/node_modules/@theia/**/*.js"
"${workspaceFolder}/electron-app/lib/backend/electron-main.js",
"${workspaceFolder}/electron-app/lib/backend/main.js",
"${workspaceFolder}/electron-app/lib/**/*.js",
"${workspaceFolder}/arduino-ide-extension/lib/**/*.js",
"${workspaceFolder}/node_modules/@theia/**/*.js"
],
"smartStep": true,
"internalConsoleOptions": "openOnSessionStart",
@@ -42,33 +39,35 @@
{
"type": "node",
"request": "launch",
"name": "App (Electron)",
"runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron",
"name": "App [Dev]",
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron",
"windows": {
"runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron.cmd",
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron.cmd",
},
"cwd": "${workspaceFolder}/electron-app",
"args": [
".",
"--log-level=debug",
"--hostname=localhost",
"--no-cluster",
"--app-project-path=${workspaceRoot}/electron-app",
"--app-project-path=${workspaceFolder}/electron-app",
"--remote-debugging-port=9222",
"--no-app-auto-install",
"--plugins=local-dir:../plugins",
"--hosted-plugin-inspect=9339"
"--plugins=local-dir:./plugins",
"--hosted-plugin-inspect=9339",
"--content-trace",
"--open-devtools",
"--no-ping-timeout",
],
"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",
"${workspaceRoot}/node_modules/@theia/**/*.js"
"${workspaceFolder}/electron-app/lib/backend/electron-main.js",
"${workspaceFolder}/electron-app/lib/backend/main.js",
"${workspaceFolder}/electron-app/lib/**/*.js",
"${workspaceFolder}/arduino-ide-extension/lib/**/*.js",
"${workspaceFolder}/node_modules/@theia/**/*.js"
],
"smartStep": true,
"internalConsoleOptions": "openOnSessionStart",
@@ -81,42 +80,11 @@
"port": 9222,
"webRoot": "${workspaceFolder}/electron-app"
},
{
"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",
"name": "Run Test [current]",
"program": "${workspaceRoot}/node_modules/mocha/bin/_mocha",
"program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
"args": [
"--require",
"reflect-metadata/Reflect",
@@ -126,8 +94,16 @@
"--colors",
"**/${fileBasenameNoExtension}.js"
],
"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",
"${workspaceRoot}/node_modules/@theia/**/*.js"
],
"env": {
"TS_NODE_PROJECT": "${workspaceRoot}/tsconfig.json"
"TS_NODE_PROJECT": "${workspaceFolder}/tsconfig.json",
"IDE2_TEST": "true"
},
"sourceMaps": true,
"smartStep": true,
@@ -140,19 +116,12 @@
"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"
}
],
"compounds": [
{
"name": "Launch Electron Backend & Frontend",
"configurations": [
"App (Electron)",
"App",
"Attach to Electron Frontend"
]
}

View File

@@ -2,6 +2,9 @@
"files.exclude": {
"**/lib": false
},
"search.exclude": {
"arduino-ide-extension/src/test/node/__test_sketchbook__": true
},
"typescript.tsdk": "node_modules/typescript/lib",
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true

42
.vscode/tasks.json vendored
View File

@@ -2,7 +2,7 @@
"version": "2.0.0",
"tasks": [
{
"label": "Arduino IDE - Rebuild Electron App",
"label": "Rebuild App",
"type": "shell",
"command": "yarn rebuild:browser && yarn rebuild:electron",
"group": "build",
@@ -13,18 +13,7 @@
}
},
{
"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",
"label": "Watch Extension",
"type": "shell",
"command": "yarn --cwd ./arduino-ide-extension watch",
"group": "build",
@@ -35,18 +24,7 @@
}
},
{
"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",
"label": "Watch App",
"type": "shell",
"command": "yarn --cwd ./electron-app watch",
"group": "build",
@@ -57,19 +35,11 @@
}
},
{
"label": "Arduino IDE - Watch All [Browser]",
"label": "Watch All",
"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"
"Watch Extension",
"Watch App"
]
}
]

View File

@@ -1,153 +1,3 @@
# Development
This page includes technical documentation for developers who want to build the IDE locally and contribute to the project.
## Architecture overview
The 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 one 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 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 IDE, only the _backend_ allows OS interaction.
The _backend_ process is responsible for:
- providing access to the filesystem,
- communicating with the [Arduino CLI](https://github.com/arduino/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
## 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.
> **Note**: Node.js 14 must be used instead of the version 12 recommended at the link above.
Once you have all the tools installed, you can build the editor following these steps
1. Install the dependencies and build
```sh
yarn
```
2. Rebuild the dependencies
```sh
yarn rebuild:browser
```
3. Rebuild the electron dependencies
```sh
yarn rebuild:electron
```
4. Start the application
```sh
yarn start
```
### Notes for Windows contributors
Windows requires the Microsoft Visual C++ (MSVC) compiler toolset to be installed on your development machine.
In case it's not already present, it can be downloaded from the "**Tools for Visual Studio 20XX**" section of the Visual Studio [downloads page](https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2022) via the "**Build Tools for Visual Studio 20XX**" (e.g., "**Build Tools for Visual Studio 2022**") download link.
Select "**Desktop development with C++**" from the "**Workloads**" tab during the installation procedure.
### CI
This project is built on [GitHub Actions](https://github.com/arduino/arduino-ide/actions).
- _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 for each operating system can be downloaded from the GitHub Actions page.
- _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
```
## Notes for macOS contributors
Beginning in macOS 10.14.5, the software [must be notarized to run](https://developer.apple.com/documentation/xcode/notarizing_macos_software_before_distribution). The signing and notarization processes for the Arduino IDE are managed by our Continuous Integration (CI) workflows, implemented with GitHub Actions. On every push and pull request, the Arduino IDE is built and saved to a workflow artifact. These artifacts can be used by contributors and beta testers who don't want to set up a build system locally.
For security reasons, signing and notarization are disabled for workflow runs for pull requests from forks of this repository. This means that macOS will block you from running those artifacts.
Due to this limitation, Mac users have two options for testing contributions from forks:
### The Safe approach (recommended)
Follow [the instructions above](#build-from-source) to create the build environment locally, then build the code you want to test.
### The Risky approach
*Please note that this approach is risky as you are lowering the security on your system, therefore we strongly discourage you from following it.*
1. Use [this guide](https://help.apple.com/xcode/mac/10.2/index.html?localePath=en.lproj#/dev9b7736b0e), in order to disable Gatekeeper (at your own risk!).
1. Download the unsigned artifact provided by the CI workflow run related to the Pull Request at each push.
1. Re-enable Gatekeeper after tests are done, following the guide linked above.
### Creating a release
You will not need to create a new release yourself as the Arduino team takes care of this on a regular basis, but we are documenting the process here. 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 [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
* *Can I manually change the version of the [`arduino-cli`](https://github.com/arduino/arduino-cli/) used by the IDE?*
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.
* *I have understood that not all versions of the CLI are compatible with my version of IDE but how can I manually update the `arduino-cli` inside the IDE?*
[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`.
# Development Guide
This documentation has been moved [**here**](docs/development.md#development-guide).

View File

@@ -1,45 +1,18 @@
<img src="https://content.arduino.cc/website/Arduino_logo_teal.svg" height="100" align="right" />
# Arduino IDE 2.x (beta)
# Arduino IDE 2.x
[![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)
This repository contains the source code of the Arduino IDE 2.x, which is currently in beta stage. If you're looking for the stable IDE, go to the repository of the 1.x version at https://github.com/arduino/Arduino.
This repository contains the source code of the Arduino IDE 2.x. If you're looking for the old IDE, go to the repository of the 1.x version at https://github.com/arduino/Arduino.
The Arduino IDE 2.x is a major rewrite, sharing no code with the IDE 1.x. It is based on the [Theia IDE](https://theia-ide.org/) framework and built with [Electron](https://www.electronjs.org/). The backend operations such as compilation and uploading are offloaded to an [arduino-cli](https://github.com/arduino/arduino-cli) instance running in daemon mode. This new IDE was developed with the goal of preserving the same interface and user experience of the previous major version in order to provide a frictionless upgrade.
> ⚠️ This is **beta** software. Help us test it!
![](static/screenshot.png)
## Download
You can download the latest version from the [software download page on the Arduino website](https://www.arduino.cc/en/software#experimental-software).
### Nightly builds
These builds are generated every day at 03:00 GMT from the `main` branch and
should be considered unstable:
| Platform | 32 bit | 64 bit |
| --------- | ------------------------ | ------------------------------------------------------------------------------------------------------ |
| Linux | | [Nightly Linux AppImage 64 bit]<br />[Nightly Linux ZIP file 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/107
[nightly linux appimage 64 bit]: https://downloads.arduino.cc/arduino-ide/nightly/arduino-ide_nightly-latest_Linux_64bit.AppImage
[nightly linux zip file 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`)
You can download the latest release version and nightly builds from the [software download page on the Arduino website](https://www.arduino.cc/en/software).
## Support
@@ -47,10 +20,9 @@ If you need assistance, see the [Help Center](https://support.arduino.cc/hc/en-u
## Bugs & Issues
If you want to report an issue, you can submit it to the [issue tracker](https://github.com/arduino/arduino-ide/issues) of this repository. A few rules apply:
If you want to report an issue, you can submit it to the [issue tracker](https://github.com/arduino/arduino-ide/issues) of this repository.
- Before posting, please check if the same problem has been already reported by someone else to avoid duplicates.
- Remember to include as much detail as you can about your hardware set-up, code and steps for reproducing the issue. Make sure you're using an original Arduino board.
See [**the issue report guide**](docs/contributor-guide/issues.md#issue-report-guide) for instructions.
### Security
@@ -62,16 +34,15 @@ e-mail contact: security@arduino.cc
## Contributions and development
Contributions are very welcome! You can browse the list of open issues to see what's needed and then you can submit your code using a Pull Request. Please provide detailed descriptions. We also appreciate any help in testing issues and patches contributed by other users.
Contributions are very welcome! There are several ways to participate in this project, including:
This repository contains the main code, but two more repositories are included during the build process:
- Fixing bugs
- Beta testing
- Translation
- [vscode-arduino-tools](https://github.com/arduino/vscode-arduino-tools): provides support for the language server and the debugger
- [arduino-language-server](https://github.com/arduino/arduino-language-server): provides the language server that parses Arduino code
See [**the contributor guide**](docs/CONTRIBUTING.md#contributor-guide) for more information.
See the [BUILDING.md](BUILDING.md) for a technical overview of the application and instructions for building the code.
You can help with the translation of the Arduino IDE to your language here: [Arduino IDE on Transifex](https://www.transifex.com/arduino-1/ide2/dashboard/).
See the [**development guide**](docs/development.md) for a technical overview of the application and instructions for building the code.
## Donations

View File

@@ -62,6 +62,15 @@ The Config Service knows about your system, like for example the default sketch
- Some CLI updates can bring changes to the gRPC interfaces, as the API might change. gRPC interfaces can be updated running the command
`yarn --cwd arduino-ide-extension generate-protocol`
### Update **clangd** and **ClangFormat**
The [**clangd** C++ language server](https://clangd.llvm.org/) and the [**ClangFormat** code formatter](https://clang.llvm.org/docs/ClangFormat.html) tool dependencies are managed in parallel. Updating them to a different version is done by the following procedure:
1. If the target version is not already [available from the `arduino/clang-static-binaries` repository](https://github.com/arduino/clang-static-binaries/releases), submit [an issue there](https://github.com/arduino/clang-static-binaries/issues) requesting a build and wait for that to be completed.
1. Validate the **ClangFormat** configuration for the target version by following the instructions [**here**](https://github.com/arduino/tooling-project-assets/tree/main/other/clang-format-configuration#clangformat-version-updates)
1. Submit a pull request in the `arduino/arduino-ide` repository to update the version in the `arduino.clangd.version` key of [`package.json`](package.json).
1. Submit a pull request in [the `arduino/tooling-project-assets` repository](https://github.com/arduino/tooling-project-assets) to update the version in the `vars.DEFAULT_CLANG_FORMAT_VERSION` field of [`Taskfile.yml`](https://github.com/arduino/tooling-project-assets/blob/main/Taskfile.yml).
### Customize Icons
ArduinoIde uses a customized version of FontAwesome.
In order to update/replace icons follow the following steps:

File diff suppressed because one or more lines are too long

View File

@@ -1,89 +1,101 @@
{
"name": "arduino-ide-extension",
"version": "2.0.0-rc9.1",
"version": "2.2.0",
"description": "An extension for Theia building the Arduino IDE",
"license": "AGPL-3.0-or-later",
"scripts": {
"prepare": "yarn download-cli && yarn download-fwuploader && yarn download-ls && yarn copy-i18n && yarn clean && yarn download-examples && yarn build && yarn test",
"prepare": "yarn download-cli && yarn download-fwuploader && yarn download-ls && yarn copy-i18n && yarn download-examples",
"clean": "rimraf lib",
"compose-changelog": "node ./scripts/compose-changelog.js",
"download-cli": "node ./scripts/download-cli.js",
"download-fwuploader": "node ./scripts/download-fwuploader.js",
"copy-i18n": "npx ncp ../i18n ./build/i18n",
"copy-i18n": "ncp ../i18n ./src/node/resources/i18n",
"download-ls": "node ./scripts/download-ls.js",
"download-examples": "node ./scripts/download-examples.js",
"generate-protocol": "node ./scripts/generate-protocol.js",
"lint": "eslint",
"build": "tsc && ncp ./src/node/cli-protocol/ ./lib/node/cli-protocol/ && yarn lint",
"prebuild": "rimraf lib",
"build": "tsc",
"build:dev": "yarn build",
"postbuild": "ncp ./src/node/cli-protocol/ ./lib/node/cli-protocol/",
"watch": "tsc -w",
"test": "mocha \"./lib/test/**/*.test.js\"",
"test:watch": "mocha --watch --watch-files lib \"./lib/test/**/*.test.js\""
"test": "cross-env IDE2_TEST=true mocha \"./lib/test/**/*.test.js\"",
"test:slow": "cross-env IDE2_TEST=true mocha \"./lib/test/**/*.slow-test.js\" --slow 5000"
},
"dependencies": {
"@grpc/grpc-js": "^1.6.7",
"@theia/application-package": "1.25.0",
"@theia/core": "1.25.0",
"@theia/editor": "1.25.0",
"@theia/electron": "1.25.0",
"@theia/filesystem": "1.25.0",
"@theia/keymaps": "1.25.0",
"@theia/markers": "1.25.0",
"@theia/monaco": "1.25.0",
"@theia/navigator": "1.25.0",
"@theia/outline-view": "1.25.0",
"@theia/output": "1.25.0",
"@theia/preferences": "1.25.0",
"@theia/search-in-workspace": "1.25.0",
"@theia/terminal": "1.25.0",
"@theia/workspace": "1.25.0",
"@grpc/grpc-js": "^1.8.14",
"@theia/application-package": "1.39.0",
"@theia/core": "1.39.0",
"@theia/debug": "1.39.0",
"@theia/editor": "1.39.0",
"@theia/electron": "1.39.0",
"@theia/filesystem": "1.39.0",
"@theia/keymaps": "1.39.0",
"@theia/markers": "1.39.0",
"@theia/messages": "1.39.0",
"@theia/monaco": "1.39.0",
"@theia/monaco-editor-core": "1.72.3",
"@theia/navigator": "1.39.0",
"@theia/outline-view": "1.39.0",
"@theia/output": "1.39.0",
"@theia/plugin-ext": "1.39.0",
"@theia/preferences": "1.39.0",
"@theia/scm": "1.39.0",
"@theia/search-in-workspace": "1.39.0",
"@theia/terminal": "1.39.0",
"@theia/typehierarchy": "1.39.0",
"@theia/workspace": "1.39.0",
"@tippyjs/react": "^4.2.5",
"@types/atob": "^2.1.2",
"@types/auth0-js": "^9.14.0",
"@types/btoa": "^1.2.3",
"@types/dateformat": "^3.0.1",
"@types/deep-equal": "^1.0.1",
"@types/deepmerge": "^2.2.0",
"@types/glob": "^7.2.0",
"@types/google-protobuf": "^3.7.2",
"@types/js-yaml": "^3.12.2",
"@types/keytar": "^4.4.0",
"@types/jsdom": "^21.1.1",
"@types/lodash.debounce": "^4.0.6",
"@types/ncp": "^2.0.4",
"@types/node-fetch": "^2.5.7",
"@types/p-queue": "^2.3.1",
"@types/ps-tree": "^1.1.0",
"@types/react-select": "^3.0.0",
"@types/react-tabs": "^2.3.2",
"@types/temp": "^0.8.34",
"@types/which": "^1.3.1",
"ajv": "^6.5.3",
"arduino-serial-plotter-webapp": "0.1.0",
"arduino-serial-plotter-webapp": "0.2.0",
"async-mutex": "^0.3.0",
"atob": "^2.1.2",
"auth0-js": "^9.14.0",
"btoa": "^1.2.1",
"classnames": "^2.3.1",
"cpy": "^10.0.0",
"cross-fetch": "^3.1.5",
"dateformat": "^3.0.3",
"deep-equal": "^2.0.5",
"deepmerge": "2.0.1",
"deepmerge": "^4.2.2",
"drivelist": "^9.2.4",
"electron-updater": "^4.6.5",
"fast-json-stable-stringify": "^2.1.0",
"fast-safe-stringify": "^2.1.1",
"filename-reserved-regex": "^2.0.0",
"glob": "^7.1.6",
"google-protobuf": "^3.20.1",
"hash.js": "^1.1.7",
"is-valid-path": "^0.1.1",
"is-online": "^10.0.0",
"js-yaml": "^3.13.1",
"jsdom": "^21.1.1",
"jsonc-parser": "^2.2.0",
"just-diff": "^5.1.1",
"jwt-decode": "^3.1.2",
"keytar": "7.2.0",
"lodash.debounce": "^4.0.8",
"ncp": "^2.0.0",
"minimatch": "^3.1.2",
"node-fetch": "^2.6.1",
"node-log-rotate": "^0.1.5",
"open": "^8.0.6",
"p-queue": "^5.0.0",
"p-debounce": "^2.1.0",
"p-queue": "^2.4.2",
"process": "^0.11.10",
"ps-tree": "^1.2.0",
"query-string": "^7.0.1",
"react-disable": "^0.1.0",
"react-disable": "^0.1.1",
"react-markdown": "^8.0.0",
"react-select": "^3.0.4",
"react-perfect-scrollbar": "^1.5.8",
"react-select": "^5.6.0",
"react-tabs": "^3.1.2",
"react-window": "^1.8.6",
"semver": "^7.3.2",
@@ -91,38 +103,34 @@
"temp": "^0.9.1",
"temp-dir": "^2.0.0",
"tree-kill": "^1.2.1",
"upath": "^1.1.2",
"url": "^0.11.0",
"which": "^1.3.1"
"util": "^0.12.5",
"vscode-arduino-api": "^0.1.2"
},
"devDependencies": {
"@octokit/rest": "^18.12.0",
"@types/chai": "^4.2.7",
"@types/chai-string": "^1.4.2",
"@types/mocha": "^5.2.7",
"@types/react-window": "^1.8.5",
"@types/sinon": "^10.0.6",
"@types/sinon-chai": "^3.2.6",
"@xhmikosr/downloader": "^13.0.1",
"chai": "^4.2.0",
"chai-string": "^1.5.0",
"cross-env": "^7.0.3",
"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_node_protoc_ts": "^4.1.0",
"mocha": "^7.0.0",
"mockdate": "^3.0.5",
"moment": "^2.24.0",
"protoc": "^1.0.4",
"ncp": "^2.0.0",
"rimraf": "^2.6.1",
"shelljs": "^0.8.3",
"sinon": "^12.0.1",
"sinon-chai": "^3.7.0",
"typemoq": "^2.1.0",
"uuid": "^3.2.1",
"yargs": "^11.1.0"
},
"optionalDependencies": {
"grpc-tools": "^1.9.0"
"grpc-tools": "^1.9.0",
"protoc": "^1.0.4"
},
"mocha": {
"require": [
@@ -142,30 +150,38 @@
"examples"
],
"theiaExtensions": [
{
"preload": "lib/electron-browser/preload"
},
{
"backend": "lib/node/arduino-ide-backend-module",
"frontend": "lib/browser/arduino-ide-frontend-module"
},
{
"frontend": "lib/browser/theia/core/browser-menu-module",
"frontendElectron": "lib/electron-browser/theia/core/electron-menu-module"
},
{
"frontendElectron": "lib/electron-browser/theia/core/electron-window-module"
},
{
"frontendElectron": "lib/electron-browser/electron-arduino-module"
},
{
"electronMain": "lib/electron-main/arduino-electron-main-module"
}
],
"arduino": {
"cli": {
"version": "0.25.1"
"arduino-cli": {
"version": "0.34.0"
},
"fwuploader": {
"version": "2.2.0"
"arduino-fwuploader": {
"version": "2.4.0"
},
"arduino-language-server": {
"version": "0.7.4"
},
"clangd": {
"version": "14.0.0"
},
"languageServer": {
"version": "0.7.1"
}
}
}

View File

@@ -6,7 +6,7 @@
const semver = require('semver');
const moment = require('moment');
const downloader = require('./downloader');
const { goBuildFromGit } = require('./utils');
const { taskBuildFromGit } = require('./utils');
const version = (() => {
const pkg = require(path.join(__dirname, '..', 'package.json'));
@@ -19,7 +19,7 @@
return undefined;
}
const { cli } = arduino;
const cli = arduino['arduino-cli'];
if (!cli) {
return undefined;
}
@@ -34,14 +34,23 @@
}
const { platform, arch } = process;
const buildFolder = path.join(__dirname, '..', 'build');
const resourcesFolder = path.join(
__dirname,
'..',
'src',
'node',
'resources'
);
const cliName = `arduino-cli${platform === 'win32' ? '.exe' : ''}`;
const destinationPath = path.join(buildFolder, cliName);
const destinationPath = path.join(resourcesFolder, cliName);
if (typeof version === 'string') {
const suffix = (() => {
switch (platform) {
case 'darwin':
if (arch === 'arm64') {
return 'macOS_ARM64.tar.gz';
}
return 'macOS_64bit.tar.gz';
case 'win32':
return 'Windows_64bit.zip';
@@ -82,6 +91,6 @@
shell.exit(1);
}
} else {
goBuildFromGit(version, destinationPath, 'CLI');
taskBuildFromGit(version, destinationPath, 'CLI');
}
})();

View File

@@ -1,36 +1,48 @@
// @ts-check
// The version to use.
const version = '1.9.1';
const version = '1.10.0';
(async () => {
const os = require('os');
const { promises: fs } = require('fs');
const path = require('path');
const os = require('node:os');
const { existsSync, promises: fs } = require('node:fs');
const path = require('node:path');
const shell = require('shelljs');
const { v4 } = require('uuid');
const { exec } = require('./utils');
const destination = path.join(
__dirname,
'..',
'src',
'node',
'resources',
'Examples'
);
if (existsSync(destination)) {
shell.echo(
`Skipping Git checkout of the examples because the repository already exists: ${destination}`
);
return;
}
const repository = path.join(os.tmpdir(), `${v4()}-arduino-examples`);
if (shell.mkdir('-p', repository).code !== 0) {
shell.exit(1);
}
if (
shell.exec(
`git clone https://github.com/arduino/arduino-examples.git ${repository}`
).code !== 0
) {
shell.exit(1);
}
exec(
'git',
['clone', 'https://github.com/arduino/arduino-examples.git', repository],
shell
);
if (
shell.exec(`git -C ${repository} checkout tags/${version} -b ${version}`)
.code !== 0
) {
shell.exit(1);
}
exec(
'git',
['-C', repository, 'checkout', `tags/${version}`, '-b', version],
shell
);
const destination = path.join(__dirname, '..', 'Examples');
shell.mkdir('-p', destination);
shell.cp('-fR', path.join(repository, 'examples', '*'), destination);

View File

@@ -1,12 +1,11 @@
// @ts-check
(async () => {
const fs = require('fs');
const path = require('path');
const temp = require('temp');
const path = require('node:path');
const shell = require('shelljs');
const semver = require('semver');
const downloader = require('./downloader');
const { taskBuildFromGit } = require('./utils');
const version = (() => {
const pkg = require(path.join(__dirname, '..', 'package.json'));
@@ -19,7 +18,7 @@
return undefined;
}
const { fwuploader } = arduino;
const fwuploader = arduino['arduino-fwuploader'];
if (!fwuploader) {
return undefined;
}
@@ -36,11 +35,17 @@
}
const { platform, arch } = process;
const buildFolder = path.join(__dirname, '..', 'build');
const resourcesFolder = path.join(
__dirname,
'..',
'src',
'node',
'resources'
);
const fwuploderName = `arduino-fwuploader${
platform === 'win32' ? '.exe' : ''
}`;
const destinationPath = path.join(buildFolder, fwuploderName);
const destinationPath = path.join(resourcesFolder, fwuploderName);
if (typeof version === 'string') {
const suffix = (() => {
@@ -86,81 +91,6 @@
shell.exit(1);
}
} else {
// 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 Firmware Uploader from ${url}. Commitish: ${
commitish ? commitish : 'HEAD'
}`
);
if (fs.existsSync(destinationPath)) {
shell.echo(
`Skipping the Firmware Uploader 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 Firmware Uploader source to ${tempRepoPath}...`);
if (shell.exec(`git clone ${url} ${tempRepoPath}`).code !== 0) {
shell.exit(1);
}
shell.echo('<<< Cloned Firmware Uploader 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 Firmware Uploader...`);
if (shell.exec('go build', { cwd: tempRepoPath }).code !== 0) {
shell.exit(1);
}
shell.echo('<<< Firmware Uploader build done.');
if (!fs.existsSync(path.join(tempRepoPath, fwuploderName))) {
shell.echo(
`Could not find the Firmware Uploader at ${path.join(
tempRepoPath,
fwuploderName
)}.`
);
shell.exit(1);
}
const builtFwUploaderPath = path.join(tempRepoPath, fwuploderName);
shell.echo(
`>>> Copying Firmware Uploader from ${builtFwUploaderPath} to ${destinationPath}...`
);
if (shell.cp(builtFwUploaderPath, destinationPath).code !== 0) {
shell.exit(1);
}
shell.echo(`<<< Copied the Firmware Uploader.`);
shell.echo('<<< Verifying Firmware Uploader...');
if (!fs.existsSync(destinationPath)) {
shell.exit(1);
}
shell.echo('>>> Verified Firmware Uploader.');
taskBuildFromGit(version, destinationPath, 'Firmware Uploader');
}
})();

View File

@@ -16,7 +16,8 @@
const { arduino } = pkg;
if (!arduino) return [undefined, undefined];
const { languageServer, clangd } = arduino;
const { clangd } = arduino;
const languageServer = arduino['arduino-language-server'];
if (!languageServer) return [undefined, undefined];
if (!clangd) return [undefined, undefined];
@@ -62,29 +63,50 @@
const force = yargs['force-download'];
const { platform, arch } = process;
const platformArch = platform + '-' + arch;
const build = path.join(__dirname, '..', 'build');
const resourcesFolder = path.join(
__dirname,
'..',
'src',
'node',
'resources'
);
const lsExecutablePath = path.join(
build,
resourcesFolder,
`arduino-language-server${platform === 'win32' ? '.exe' : ''}`
);
let clangdExecutablePath, clangFormatExecutablePath, lsSuffix, clangdSuffix;
switch (platformArch) {
case 'darwin-x64':
clangdExecutablePath = path.join(build, 'clangd');
clangFormatExecutablePath = path.join(build, 'clang-format');
clangdExecutablePath = path.join(resourcesFolder, 'clangd');
clangFormatExecutablePath = path.join(resourcesFolder, 'clang-format');
lsSuffix = 'macOS_64bit.tar.gz';
clangdSuffix = 'macOS_64bit';
break;
case 'darwin-arm64':
clangdExecutablePath = path.join(resourcesFolder, 'clangd');
clangFormatExecutablePath = path.join(resourcesFolder, 'clang-format');
lsSuffix = 'macOS_ARM64.tar.gz';
clangdSuffix = 'macOS_ARM64';
break;
case 'linux-x64':
clangdExecutablePath = path.join(build, 'clangd');
clangFormatExecutablePath = path.join(build, 'clang-format');
clangdExecutablePath = path.join(resourcesFolder, 'clangd');
clangFormatExecutablePath = path.join(resourcesFolder, 'clang-format');
lsSuffix = 'Linux_64bit.tar.gz';
clangdSuffix = 'Linux_64bit';
break;
case 'linux-arm64':
clangdExecutablePath = path.join(resourcesFolder, 'clangd');
clangFormatExecutablePath = path.join(resourcesFolder, 'clang-format');
lsSuffix = 'Linux_ARM64.tar.gz';
clangdSuffix = 'Linux_ARM64';
break;
case 'win32-x64':
clangdExecutablePath = path.join(build, 'clangd.exe');
clangFormatExecutablePath = path.join(build, 'clang-format.exe');
clangdExecutablePath = path.join(resourcesFolder, 'clangd.exe');
clangFormatExecutablePath = path.join(
resourcesFolder,
'clang-format.exe'
);
lsSuffix = 'Windows_64bit.zip';
clangdSuffix = 'Windows_64bit';
break;
@@ -104,20 +126,31 @@
? 'nightly/arduino-language-server'
: 'arduino-language-server_' + lsVersion
}_${lsSuffix}`;
downloader.downloadUnzipAll(lsUrl, build, lsExecutablePath, force);
downloader.downloadUnzipAll(
lsUrl,
resourcesFolder,
lsExecutablePath,
force
);
} else {
goBuildFromGit(lsVersion, lsExecutablePath, 'language-server');
}
const clangdUrl = `https://downloads.arduino.cc/tools/clangd_${clangdVersion}_${clangdSuffix}.tar.bz2`;
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.
downloader.downloadUnzipAll(
clangdUrl,
resourcesFolder,
clangdExecutablePath,
force,
{
strip: 1,
}
); // `strip`: the new clangd (12.x) is zipped into a folder, so we have to strip the outmost folder.
const clangdFormatUrl = `https://downloads.arduino.cc/tools/clang-format_${clangdVersion}_${clangdSuffix}.tar.bz2`;
downloader.downloadUnzipAll(
clangdFormatUrl,
build,
resourcesFolder,
clangFormatExecutablePath,
force,
{

View File

@@ -1,7 +1,6 @@
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');
@@ -47,6 +46,7 @@ exports.downloadUnzipFile = async (
}
shell.echo(`>>> Downloading from '${url}'...`);
const { default: download } = await import('@xhmikosr/downloader');
const data = await download(url);
shell.echo(`<<< Download succeeded.`);
@@ -107,6 +107,7 @@ exports.downloadUnzipAll = async (
}
shell.echo(`>>> Downloading from '${url}'...`);
const { default: download } = await import('@xhmikosr/downloader');
const data = await download(url);
shell.echo(`<<< Download succeeded.`);

View File

@@ -1,156 +1,190 @@
// @ts-check
(async () => {
const os = require('node:os');
const path = require('node:path');
const { exec } = require('./utils');
const glob = require('glob');
const { v4 } = require('uuid');
const shell = require('shelljs');
const protoc = path.dirname(require('protoc/protoc'));
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 repository = path.join(os.tmpdir(), `${v4()}-arduino-cli`);
if (shell.mkdir('-p', repository).code !== 0) {
shell.exit(1);
}
const repository = path.join(os.tmpdir(), `${v4()}-arduino-cli`);
if (shell.mkdir('-p', repository).code !== 0) {
shell.exit(1);
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 { 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);
}
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.`);
const defaultVersion = {
owner: 'arduino',
repo: 'arduino-cli',
commitish: undefined,
};
const { arduino } = pkg;
if (!arduino) {
return defaultVersion;
}
shell.echo('>>> Generating TS/JS API from:');
if (shell.exec(`git -C ${repository} rev-parse --abbrev-ref HEAD`).code !== 0) {
shell.exit(1);
const cli = arduino['arduino-cli'];
if (!cli) {
return defaultVersion;
}
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);
const { version } = cli;
if (!version) {
return defaultVersion;
}
// Generate JS code from the `.proto` files.
if (shell.exec(`grpc_tools_node_protoc \
--js_out=import_style=commonjs,binary:${out} \
--grpc_out=generate_package_definition:${out} \
-I ${rpc} \
${protos.join(' ')}`).code !== 0) {
shell.exit(1);
if (typeof version === 'string') {
return defaultVersion;
}
// Generate the `.d.ts` files for JS.
if (shell.exec(`protoc \
--plugin=protoc-gen-ts=${path.resolve(__dirname, '..', 'node_modules', '.bin', `protoc-gen-ts${platform === 'win32' ? '.cmd' : ''}`)} \
--ts_out=generate_package_definition:${out} \
-I ${rpc} \
${protos.join(' ')}`).code !== 0) {
shell.exit(1);
// 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);
}
shell.echo('<<< Generation was successful.');
return { owner, repo, commitish };
})();
const url = `https://github.com/${owner}/${repo}.git`;
shell.echo(`>>> Cloning repository from '${url}'...`);
exec('git', ['clone', url, repository], shell);
shell.echo(`<<< Repository cloned.`);
const { platform } = process;
const resourcesFolder = path.join(
__dirname,
'..',
'src',
'node',
'resources'
);
const cli = path.join(
resourcesFolder,
`arduino-cli${platform === 'win32' ? '.exe' : ''}`
);
const versionJson = exec(cli, ['version', '--format', 'json'], shell).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}'...`);
exec('git', ['-C', repository, 'fetch', '--all', '--tags'], shell);
exec(
'git',
['-C', repository, 'checkout', `tags/${version}`, '-b', version],
shell
);
shell.echo(`<<< Checked out tagged version: '${version}'.`);
} else if (commitish) {
shell.echo(
`>>> Checking out commitish from 'package.json': '${commitish}'...`
);
exec('git', ['-C', repository, 'checkout', commitish], shell);
shell.echo(
`<<< Checked out commitish from 'package.json': '${commitish}'.`
);
} else if (versionObject.Commit) {
shell.echo(
`>>> Checking out commitish from the CLI: '${versionObject.Commit}'...`
);
exec('git', ['-C', repository, 'checkout', versionObject.Commit], shell);
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:');
exec('git', ['-C', repository, 'rev-parse', '--abbrev-ref', 'HEAD'], shell);
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 ?? error.message);
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.
exec(
'grpc_tools_node_protoc',
[
`--js_out=import_style=commonjs,binary:${out}`,
`--grpc_out=generate_package_definition:${out}`,
'-I',
rpc,
...protos,
],
shell
);
// Generate the `.d.ts` files for JS.
exec(
path.join(protoc, `protoc${platform === 'win32' ? '.exe' : ''}`),
[
`--plugin=protoc-gen-ts=${path.resolve(
__dirname,
'..',
'node_modules',
'.bin',
`protoc-gen-ts${platform === 'win32' ? '.cmd' : ''}`
)}`,
`--ts_out=generate_package_definition:${out}`,
'-I',
rpc,
...protos,
],
shell
);
shell.echo('<<< Generation was successful.');
})();

View File

@@ -1,3 +1,42 @@
// @ts-check
const exec = (
/** @type {string} */ command,
/** @type {readonly string[]} */ args,
/** @type {import('shelljs')|undefined}*/ shell = undefined,
/** @type {import('node:child_process').ExecFileSyncOptionsWithStringEncoding|undefined} */ options = undefined
) => {
try {
const stdout = require('node:child_process').execFileSync(
command,
args,
options ? options : { encoding: 'utf8' }
);
if (shell) {
shell.echo(stdout.trim());
}
return stdout;
} catch (err) {
if (shell) {
shell.echo(err instanceof Error ? err.message : String(err));
shell.exit(1);
}
throw err;
}
};
exports.exec = exec;
/**
* Clones something from GitHub and builds it with [`Task`](https://taskfile.dev/).
*
* @param version {object} the version object.
* @param destinationPath {string} the absolute path of the output binary. For example, `C:\\folder\\arduino-cli.exe` or `/path/to/arduino-language-server`
* @param taskName {string} for the CLI logging . Can be `'CLI'` or `'language-server'`, etc.
*/
exports.taskBuildFromGit = (version, destinationPath, taskName) => {
return buildFromGit('task', version, destinationPath, taskName);
};
/**
* Clones something from GitHub and builds it with `Golang`.
*
@@ -6,8 +45,19 @@
* @param taskName {string} for the CLI logging . Can be `'CLI'` or `'language-server'`, etc.
*/
exports.goBuildFromGit = (version, destinationPath, taskName) => {
const fs = require('fs');
const path = require('path');
return buildFromGit('go', version, destinationPath, taskName);
};
/**
* The `command` must be either `'go'` or `'task'`.
* @param {string} command
* @param {{ owner: any; repo: any; commitish: any; }} version
* @param {string} destinationPath
* @param {string} taskName
*/
function buildFromGit(command, version, destinationPath, taskName) {
const fs = require('node:fs');
const path = require('node:path');
const temp = require('temp');
const shell = require('shelljs');
@@ -40,31 +90,33 @@ exports.goBuildFromGit = (version, destinationPath, taskName) => {
return;
}
const buildFolder = path.join(__dirname, '..', 'build');
if (shell.mkdir('-p', buildFolder).code !== 0) {
shell.echo('Could not create build folder.');
const resourcesFolder = path.join(
__dirname,
'..',
'src',
'node',
'resources'
);
if (shell.mkdir('-p', resourcesFolder).code !== 0) {
shell.echo('Could not create resources folder.');
shell.exit(1);
}
const tempRepoPath = temp.mkdirSync();
shell.echo(`>>> Cloning ${taskName} source to ${tempRepoPath}...`);
if (shell.exec(`git clone ${url} ${tempRepoPath}`).code !== 0) {
shell.exit(1);
}
exec('git', ['clone', url, tempRepoPath], shell);
shell.echo(`<<< Cloned ${taskName} repo.`);
if (commitish) {
shell.echo(`>>> Checking out ${commitish}...`);
if (shell.exec(`git -C ${tempRepoPath} checkout ${commitish}`).code !== 0) {
shell.exit(1);
}
exec('git', ['-C', tempRepoPath, 'checkout', commitish], shell);
shell.echo(`<<< Checked out ${commitish}.`);
}
exec('git', ['-C', tempRepoPath, 'rev-parse', '--short', 'HEAD'], shell);
shell.echo(`>>> Building the ${taskName}...`);
if (shell.exec('go build', { cwd: tempRepoPath }).code !== 0) {
shell.exit(1);
}
exec(command, ['build'], shell, { cwd: tempRepoPath, encoding: 'utf8' });
shell.echo(`<<< Done ${taskName} build.`);
const binName = path.basename(destinationPath);
@@ -89,4 +141,4 @@ exports.goBuildFromGit = (version, destinationPath, taskName) => {
shell.exit(1);
}
shell.echo(`>>> Verified ${taskName}.`);
};
}

View File

@@ -0,0 +1,16 @@
import type { Disposable } from '@theia/core/lib/common/disposable';
import type { AppInfo } from '../electron-common/electron-arduino';
import type { StartupTasks } from '../electron-common/startup-task';
import type { Sketch } from './contributions/contribution';
export type { AppInfo };
export const AppService = Symbol('AppService');
export interface AppService {
quit(): void;
info(): Promise<AppInfo>;
registerStartupTasksHandler(
handler: (tasks: StartupTasks) => void
): Disposable;
scheduleDeletion(sketch: Sketch): void; // TODO: find a better place
}

View File

@@ -1,52 +1,47 @@
import * as remote from '@theia/core/electron-shared/@electron/remote';
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 { FrontendApplicationContribution } from '@theia/core/lib/browser/frontend-application';
import { FrontendApplicationStateService } from '@theia/core/lib/browser/frontend-application-state';
import {
TabBarToolbarContribution,
TabBarToolbarRegistry,
} from '@theia/core/lib/browser/shell/tab-bar-toolbar';
import {
ColorTheme,
CssStyleCollector,
StylingParticipant,
} from '@theia/core/lib/browser/styling-service';
import {
CommandContribution,
CommandRegistry,
} from '@theia/core/lib/common/command';
import {
MAIN_MENU_BAR,
MenuContribution,
MenuModelRegistry,
} from '@theia/core/lib/common/menu';
import { MessageService } from '@theia/core/lib/common/message-service';
import { nls } from '@theia/core/lib/common/nls';
import { isHighContrast } from '@theia/core/lib/common/theme';
import { ElectronWindowPreferences } from '@theia/core/lib/electron-browser/window/electron-window-preferences';
import {
inject,
injectable,
postConstruct,
} from '@theia/core/shared/inversify';
import * as React from '@theia/core/shared/react';
import { SketchesService } from '../common/protocol';
import {
MAIN_MENU_BAR,
MenuContribution,
MenuModelRegistry,
} from '@theia/core';
import {
Dialog,
FrontendApplication,
FrontendApplicationContribution,
OnWillStopAction,
} 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 { nls } from '@theia/core/lib/common';
import {
CommandContribution,
CommandRegistry,
} from '@theia/core/lib/common/command';
import { MessageService } from '@theia/core/lib/common/message-service';
import { EditorCommands, EditorMainMenu } from '@theia/editor/lib/browser';
import React from '@theia/core/shared/react';
import { EditorCommands } from '@theia/editor/lib/browser/editor-command';
import { EditorMainMenu } from '@theia/editor/lib/browser/editor-menu';
import { MonacoMenus } from '@theia/monaco/lib/browser/monaco-menu';
import { FileNavigatorCommands } from '@theia/navigator/lib/browser/navigator-contribution';
import { TerminalMenus } from '@theia/terminal/lib/browser/terminal-frontend-contribution';
import {
CurrentSketch,
SketchesServiceClientImpl,
} from '../common/protocol/sketches-service-client-impl';
import { ArduinoPreferences } from './arduino-preferences';
import { BoardsServiceProvider } from './boards/boards-service-provider';
import { BoardsToolBarItem } from './boards/boards-toolbar-item';
import { SaveAsSketch } from './contributions/save-as-sketch';
import { ArduinoMenus } from './menu/arduino-menus';
import { MonitorViewContribution } from './serial/monitor/monitor-view-contribution';
import { ArduinoToolbar } from './toolbar/arduino-toolbar';
import { FrontendApplicationStateService } from '@theia/core/lib/browser/frontend-application-state';
import { SerialPlotterContribution } from './serial/plotter/plotter-frontend-contribution';
import { ArduinoToolbar } from './toolbar/arduino-toolbar';
@injectable()
export class ArduinoFrontendContribution
@@ -55,7 +50,8 @@ export class ArduinoFrontendContribution
TabBarToolbarContribution,
CommandContribution,
MenuContribution,
ColorContribution
ColorContribution,
StylingParticipant
{
@inject(MessageService)
private readonly messageService: MessageService;
@@ -63,23 +59,17 @@ export class ArduinoFrontendContribution
@inject(BoardsServiceProvider)
private readonly boardsServiceProvider: BoardsServiceProvider;
@inject(SketchesService)
private readonly sketchService: SketchesService;
@inject(CommandRegistry)
private readonly commandRegistry: CommandRegistry;
@inject(ArduinoPreferences)
private readonly arduinoPreferences: ArduinoPreferences;
@inject(SketchesServiceClientImpl)
private readonly sketchServiceClient: SketchesServiceClientImpl;
@inject(ElectronWindowPreferences)
private readonly electronWindowPreferences: ElectronWindowPreferences;
@inject(FrontendApplicationStateService)
private readonly appStateService: FrontendApplicationStateService;
@postConstruct()
protected async init(): Promise<void> {
protected init(): void {
if (!window.navigator.onLine) {
// tslint:disable-next-line:max-line-length
this.messageService.warn(
@@ -91,30 +81,25 @@ export class ArduinoFrontendContribution
}
}
async onStart(app: FrontendApplication): Promise<void> {
this.arduinoPreferences.onPreferenceChanged((event) => {
onStart(): void {
this.electronWindowPreferences.onPreferenceChanged((event) => {
if (event.newValue !== event.oldValue) {
switch (event.preferenceName) {
case 'arduino.window.zoomLevel':
case 'window.zoomLevel':
if (typeof event.newValue === 'number') {
const webContents = remote.getCurrentWebContents();
webContents.setZoomLevel(event.newValue || 0);
window.electronTheiaCore.setZoomLevel(event.newValue || 0);
}
break;
}
}
});
this.appStateService.reachedState('ready').then(() =>
this.arduinoPreferences.ready.then(() => {
const webContents = remote.getCurrentWebContents();
const zoomLevel = this.arduinoPreferences.get(
'arduino.window.zoomLevel'
);
webContents.setZoomLevel(zoomLevel);
this.electronWindowPreferences.ready.then(() => {
const zoomLevel =
this.electronWindowPreferences.get('window.zoomLevel');
window.electronTheiaCore.setZoomLevel(zoomLevel);
})
);
// Removes the _Settings_ (cog) icon from the left sidebar
app.shell.leftPanelHandler.removeBottomMenu('settings-menu');
}
registerToolbarItems(registry: TabBarToolbarRegistry): void {
@@ -188,7 +173,8 @@ export class ArduinoFrontendContribution
defaults: {
dark: 'button.background',
light: 'button.background',
hc: 'activityBar.inactiveForeground',
hcDark: 'activityBar.inactiveForeground',
hcLight: 'activityBar.inactiveForeground',
},
description:
'Background color of the toolbar items. Such as Upload, Verify, etc.',
@@ -198,7 +184,8 @@ export class ArduinoFrontendContribution
defaults: {
dark: 'button.hoverBackground',
light: 'button.hoverBackground',
hc: 'button.background',
hcDark: 'button.background',
hcLight: 'button.background',
},
description:
'Background color of the toolbar items when hovering over them. Such as Upload, Verify, etc.',
@@ -208,7 +195,8 @@ export class ArduinoFrontendContribution
defaults: {
dark: 'secondaryButton.foreground',
light: 'button.foreground',
hc: 'activityBar.inactiveForeground',
hcDark: 'activityBar.inactiveForeground',
hcLight: 'activityBar.inactiveForeground',
},
description:
'Foreground color of the toolbar items. Such as Serial Monitor and Serial Plotter',
@@ -218,7 +206,8 @@ export class ArduinoFrontendContribution
defaults: {
dark: 'secondaryButton.hoverBackground',
light: 'button.hoverBackground',
hc: 'textLink.foreground',
hcDark: 'textLink.foreground',
hcLight: 'textLink.foreground',
},
description:
'Background color of the toolbar items when hovering over them, such as "Serial Monitor" and "Serial Plotter"',
@@ -228,7 +217,8 @@ export class ArduinoFrontendContribution
defaults: {
dark: 'editor.selectionBackground',
light: 'editor.selectionBackground',
hc: 'textPreformat.foreground',
hcDark: 'textPreformat.foreground',
hcLight: 'textPreformat.foreground',
},
description:
'Toggle color of the toolbar items when they are currently toggled (the command is in progress)',
@@ -238,37 +228,38 @@ export class ArduinoFrontendContribution
defaults: {
dark: 'dropdown.border',
light: 'dropdown.border',
hc: 'dropdown.border',
hcDark: 'dropdown.border',
hcLight: 'dropdown.border',
},
description: 'Border color of the Board Selector.',
},
{
id: 'arduino.toolbar.dropdown.borderActive',
defaults: {
dark: 'focusBorder',
light: 'focusBorder',
hc: 'focusBorder',
hcDark: 'focusBorder',
hcLight: 'focusBorder',
},
description: "Border color of the Board Selector when it's active",
},
{
id: 'arduino.toolbar.dropdown.background',
defaults: {
dark: 'tab.unfocusedActiveBackground',
light: 'dropdown.background',
hc: 'dropdown.background',
hcDark: 'dropdown.background',
hcLight: 'dropdown.background',
},
description: 'Background color of the Board Selector.',
},
{
id: 'arduino.toolbar.dropdown.label',
defaults: {
dark: 'dropdown.foreground',
light: 'dropdown.foreground',
hc: 'dropdown.foreground',
hcDark: 'dropdown.foreground',
hcLight: 'dropdown.foreground',
},
description: 'Font color of the Board Selector.',
},
@@ -277,7 +268,8 @@ export class ArduinoFrontendContribution
defaults: {
dark: 'list.activeSelectionIconForeground',
light: 'list.activeSelectionIconForeground',
hc: 'list.activeSelectionIconForeground',
hcDark: 'list.activeSelectionIconForeground',
hcLight: 'list.activeSelectionIconForeground',
},
description:
'Color of the selected protocol icon in the Board Selector.',
@@ -287,7 +279,8 @@ export class ArduinoFrontendContribution
defaults: {
dark: 'list.hoverBackground',
light: 'list.hoverBackground',
hc: 'list.hoverBackground',
hcDark: 'list.hoverBackground',
hcLight: 'list.hoverBackground',
},
description: 'Background color on hover of the Board Selector options.',
},
@@ -296,7 +289,8 @@ export class ArduinoFrontendContribution
defaults: {
dark: 'list.activeSelectionBackground',
light: 'list.activeSelectionBackground',
hc: 'list.activeSelectionBackground',
hcDark: 'list.activeSelectionBackground',
hcLight: 'list.activeSelectionBackground',
},
description:
'Background color of the selected board in the Board Selector.',
@@ -304,57 +298,182 @@ export class ArduinoFrontendContribution
);
}
// TODO: should be handled by `Close` contribution. https://github.com/arduino/arduino-ide/issues/1016
onWillStop(): OnWillStopAction {
return {
reason: 'temp-sketch',
action: () => {
return this.showTempSketchDialog();
},
};
}
private async showTempSketchDialog(): Promise<boolean> {
const sketch = await this.sketchServiceClient.currentSketch();
if (!CurrentSketch.isValid(sketch)) {
return true;
}
const isTemp = await this.sketchService.isTemp(sketch);
if (!isTemp) {
return true;
}
const messageBoxResult = await remote.dialog.showMessageBox(
remote.getCurrentWindow(),
{
message: nls.localize(
'arduino/sketch/saveTempSketch',
'Save your sketch to open it again later.'
),
title: nls.localize(
'theia/core/quitTitle',
'Are you sure you want to quit?'
),
type: 'question',
buttons: [
Dialog.CANCEL,
nls.localizeByDefault('Save As...'),
nls.localizeByDefault("Don't Save"),
],
}
registerThemeStyle(theme: ColorTheme, collector: CssStyleCollector): void {
const warningForeground = theme.getColor('warningForeground');
const warningBackground = theme.getColor('warningBackground');
const focusBorder = theme.getColor('focusBorder');
const contrastBorder = theme.getColor('contrastBorder');
const notificationsBackground = theme.getColor('notifications.background');
const buttonBorder = theme.getColor('button.border');
const buttonBackground = theme.getColor('button.background') || 'none';
const dropdownBackground = theme.getColor('dropdown.background');
const arduinoToolbarButtonBackground = theme.getColor(
'arduino.toolbar.button.background'
);
const result = messageBoxResult.response;
if (result === 2) {
return true;
} else if (result === 1) {
return !!(await this.commandRegistry.executeCommand(
SaveAsSketch.Commands.SAVE_AS_SKETCH.id,
{
execOnlyIfTemp: false,
openAfterMove: false,
wipeOriginal: true,
if (isHighContrast(theme.type)) {
// toolbar items
collector.addRule(`
.p-TabBar-toolbar .item.arduino-tool-item.enabled:hover > div.toggle-serial-monitor,
.p-TabBar-toolbar .item.arduino-tool-item.enabled:hover > div.toggle-serial-plotter {
background: transparent;
}
));
`);
if (contrastBorder) {
collector.addRule(`
.quick-input-widget {
outline: 1px solid ${contrastBorder};
outline-offset: -1px;
}
`);
}
if (focusBorder) {
// customized react-select widget
collector.addRule(`
.arduino-select__option--is-selected {
outline: 1px solid ${focusBorder};
}
`);
collector.addRule(`
.arduino-select__option--is-focused {
outline: 1px dashed ${focusBorder};
}
`);
// boards selector dropdown
collector.addRule(`
#select-board-dialog .selectBoardContainer .list .item:hover {
outline: 1px dashed ${focusBorder};
}
`);
// button hover
collector.addRule(`
.theia-button:hover,
button.theia-button:hover {
outline: 1px dashed ${focusBorder};
}
`);
collector.addRule(`
.theia-button {
border: 1px solid ${focusBorder};
}
`);
collector.addRule(`
.component-list-item .header .installed-version:hover:before {
background-color: transparent;
outline: 1px dashed ${focusBorder};
}
`);
// tree node
collector.addRule(`
.theia-TreeNode:hover {
outline: 1px dashed ${focusBorder};
}
`);
collector.addRule(`
.quick-input-list .monaco-list-row.focused,
.theia-Tree .theia-TreeNode.theia-mod-selected {
outline: 1px dotted ${focusBorder};
}
`);
collector.addRule(`
div#select-board-dialog .selectBoardContainer .list .item.selected,
.theia-Tree:focus .theia-TreeNode.theia-mod-selected,
.theia-Tree .ReactVirtualized__List:focus .theia-TreeNode.theia-mod-selected {
outline: 1px solid ${focusBorder};
}
`);
// quick input
collector.addRule(`
.quick-input-list .monaco-list-row:hover {
outline: 1px dashed ${focusBorder};
}
`);
// editor tab-bar
collector.addRule(`
.p-TabBar.theia-app-centers .p-TabBar-tab.p-mod-closable > .p-TabBar-tabCloseIcon:hover {
outline: 1px dashed ${focusBorder};
}
`);
collector.addRule(`
#theia-main-content-panel .p-TabBar .p-TabBar-tab:hover {
outline: 1px dashed ${focusBorder};
outline-offset: -4px;
}
`);
collector.addRule(`
#theia-main-content-panel .p-TabBar .p-TabBar-tab.p-mod-current {
outline: 1px solid ${focusBorder};
outline-offset: -4px;
}
`);
// boards selector dropdown
collector.addRule(`
.arduino-boards-dropdown-item:hover {
outline: 1px dashed ${focusBorder};
outline-offset: -2px;
}
`);
if (notificationsBackground) {
// notification
collector.addRule(`
.theia-notification-list-item:hover:not(:focus) {
background-color: ${notificationsBackground};
outline: 1px dashed ${focusBorder};
outline-offset: -2px;
}
`);
}
if (arduinoToolbarButtonBackground) {
// toolbar item
collector.addRule(`
.item.arduino-tool-item.toggled .arduino-upload-sketch--toolbar,
.item.arduino-tool-item.toggled .arduino-verify-sketch--toolbar {
background-color: ${arduinoToolbarButtonBackground} !important;
outline: 1px solid ${focusBorder};
}
`);
collector.addRule(`
.p-TabBar-toolbar .item.arduino-tool-item.enabled:hover > div {
background: ${arduinoToolbarButtonBackground};
outline: 1px dashed ${focusBorder};
}
`);
}
}
if (dropdownBackground) {
// boards selector dropdown
collector.addRule(`
.arduino-boards-dropdown-item:hover {
background: ${dropdownBackground};
}
`);
}
if (warningForeground && warningBackground) {
// <input> widget with inverted foreground and background colors
collector.addRule(`
.theia-input.warning:focus,
.theia-input.warning::placeholder,
.theia-input.warning {
color: ${warningBackground};
background-color: ${warningForeground};
}
`);
}
if (buttonBorder) {
collector.addRule(`
button.theia-button,
button.theia-button.secondary,
.component-list-item .theia-button.secondary.no-border,
.component-list-item .theia-button.secondary.no-border:hover {
border: 1px solid ${buttonBorder};
}
`);
collector.addRule(`
.component-list-item .header .installed-version:before {
color: ${buttonBackground};
border: 1px solid ${buttonBorder};
}
`);
}
}
return false;
}
}

View File

@@ -3,10 +3,7 @@ import { ContainerModule } from '@theia/core/shared/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 { TabBarToolbarContribution } from '@theia/core/lib/browser/shell/tab-bar-toolbar';
import { WebSocketConnectionProvider } from '@theia/core/lib/browser/messaging/ws-connection-provider';
import {
FrontendApplicationContribution,
@@ -26,11 +23,14 @@ import {
SketchesService,
SketchesServicePath,
} from '../common/protocol/sketches-service';
import { SketchesServiceClientImpl } from '../common/protocol/sketches-service-client-impl';
import { SketchesServiceClientImpl } from './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 {
BoardListDumper,
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';
@@ -53,8 +53,6 @@ import {
DockPanelRenderer as TheiaDockPanelRenderer,
TabBarRendererFactory,
ContextMenuRenderer,
createTreeContainer,
TreeWidget,
} from '@theia/core/lib/browser';
import { MenuContribution } from '@theia/core/lib/common/menu';
import {
@@ -66,7 +64,6 @@ 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';
@@ -84,12 +81,12 @@ import { ProblemManager as TheiaProblemManager } from '@theia/markers/lib/browse
import { ProblemManager } from './theia/markers/problem-manager';
import { BoardsAutoInstaller } from './boards/boards-auto-installer';
import { ShellLayoutRestorer } from './theia/core/shell-layout-restorer';
import { ListItemRenderer } from './widgets/component-list/list-item-renderer';
import { ColorContribution } from '@theia/core/lib/browser/color-application-contribution';
import {
MonacoThemeJson,
MonacoThemingService,
} from '@theia/monaco/lib/browser/monaco-theming-service';
ArduinoComponentContextMenuRenderer,
ListItemRenderer,
} from './widgets/component-list/list-item-renderer';
import { ColorContribution } from '@theia/core/lib/browser/color-application-contribution';
import {
ArduinoDaemonPath,
ArduinoDaemon,
@@ -98,14 +95,17 @@ import { EditorCommandContribution as TheiaEditorCommandContribution } from '@th
import {
FrontendConnectionStatusService,
ApplicationConnectionStatusContribution,
DaemonPort,
IsOnline,
} 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 { BoardsDataMenuUpdater } from './contributions/boards-data-menu-updater';
import { BoardsDataStore } from './boards/boards-data-store';
import { ILogger } from '@theia/core';
import { ILogger } from '@theia/core/lib/common/logger';
import { bindContributionProvider } from '@theia/core/lib/common/contribution-provider';
import {
FileSystemExt,
FileSystemExtPath,
@@ -134,15 +134,12 @@ import { PreferencesContribution as TheiaPreferencesContribution } from '@theia/
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 { OpenSettings } from './contributions/open-settings';
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,
@@ -184,8 +181,6 @@ 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';
@@ -208,15 +203,13 @@ import { WorkspaceVariableContribution as TheiaWorkspaceVariableContribution } f
import { WorkspaceVariableContribution } from './theia/workspace/workspace-variable-contribution';
import { DebugConfigurationManager } from './theia/debug/debug-configuration-manager';
import { DebugConfigurationManager as TheiaDebugConfigurationManager } from '@theia/debug/lib/browser/debug-configuration-manager';
import { SearchInWorkspaceWidget as TheiaSearchInWorkspaceWidget } from '@theia/search-in-workspace/lib/browser/search-in-workspace-widget';
import { SearchInWorkspaceWidget } from './theia/search-in-workspace/search-in-workspace-widget';
import { SearchInWorkspaceFactory as TheiaSearchInWorkspaceFactory } from '@theia/search-in-workspace/lib/browser/search-in-workspace-factory';
import { SearchInWorkspaceFactory } from './theia/search-in-workspace/search-in-workspace-factory';
import { SearchInWorkspaceResultTreeWidget as TheiaSearchInWorkspaceResultTreeWidget } from '@theia/search-in-workspace/lib/browser/search-in-workspace-result-tree-widget';
import { SearchInWorkspaceResultTreeWidget } from './theia/search-in-workspace/search-in-workspace-result-tree-widget';
import { MonacoEditorProvider } from './theia/monaco/monaco-editor-provider';
import { MonacoEditorProvider as TheiaMonacoEditorProvider } from '@theia/monaco/lib/browser/monaco-editor-provider';
import { StorageWrapper } from './storage-wrapper';
import {
MonacoEditorFactory,
MonacoEditorProvider as TheiaMonacoEditorProvider,
} from '@theia/monaco/lib/browser/monaco-editor-provider';
import { NotificationManager } from './theia/messages/notifications-manager';
import { NotificationManager as TheiaNotificationManager } from '@theia/messages/lib/browser/notifications-manager';
import { NotificationsRenderer as TheiaNotificationsRenderer } from '@theia/messages/lib/browser/notifications-renderer';
@@ -245,9 +238,7 @@ import { UploadFirmware } from './contributions/upload-firmware';
import {
UploadFirmwareDialog,
UploadFirmwareDialogProps,
UploadFirmwareDialogWidget,
} from './dialogs/firmware-uploader/firmware-uploader-dialog';
import { UploadCertificate } from './contributions/upload-certificate';
import {
ArduinoFirmwareUploader,
@@ -262,7 +253,6 @@ import { PlotterFrontendContribution } from './serial/plotter/plotter-frontend-c
import {
UserFieldsDialog,
UserFieldsDialogProps,
UserFieldsDialogWidget,
} from './dialogs/user-fields/user-fields-dialog';
import { nls } from '@theia/core/lib/common';
import { IDEUpdaterCommands } from './ide-updater/ide-updater-commands';
@@ -275,7 +265,6 @@ import { IDEUpdaterClientImpl } from './ide-updater/ide-updater-client-impl';
import {
IDEUpdaterDialog,
IDEUpdaterDialogProps,
IDEUpdaterDialogWidget,
} from './dialogs/ide-updater/ide-updater-dialog';
import { ElectronIpcConnectionProvider } from '@theia/core/lib/electron-browser/messaging/electron-ipc-connection-provider';
import { MonitorModel } from './monitor-model';
@@ -307,61 +296,96 @@ import { CoreErrorHandler } from './contributions/core-error-handler';
import { CompilerErrors } from './contributions/compiler-errors';
import { WidgetManager } from './theia/core/widget-manager';
import { WidgetManager as TheiaWidgetManager } from '@theia/core/lib/browser/widget-manager';
import { StartupTasks } from './widgets/sketchbook/startup-task';
import { StartupTasksExecutor } from './contributions/startup-tasks-executor';
import { IndexesUpdateProgress } from './contributions/indexes-update-progress';
import { Daemon } from './contributions/daemon';
import { FirstStartupInstaller } from './contributions/first-startup-installer';
import { OpenSketchFiles } from './contributions/open-sketch-files';
import { InoLanguage } from './contributions/ino-language';
import { SelectedBoard } from './contributions/selected-board';
import { CheckForUpdates } from './contributions/check-for-updates';
import { CheckForIDEUpdates } from './contributions/check-for-ide-updates';
import { OpenBoardsConfig } from './contributions/open-boards-config';
import { SketchFilesTracker } from './contributions/sketch-files-tracker';
import { MonacoThemeServiceIsReady } from './utils/window';
import { Deferred } from '@theia/core/lib/common/promise-util';
import { StatusBarImpl } from './theia/core/status-bar';
import { StatusBarImpl as TheiaStatusBarImpl } from '@theia/core/lib/browser';
import { EditorMenuContribution } from './theia/editor/editor-file';
import { EditorMenuContribution as TheiaEditorMenuContribution } from '@theia/editor/lib/browser/editor-menu';
import { PreferencesEditorWidget as TheiaPreferencesEditorWidget } from '@theia/preferences/lib/browser/views/preference-editor-widget';
import { PreferencesEditorWidget } from './theia/preferences/preference-editor-widget';
import { PreferencesWidget } from '@theia/preferences/lib/browser/views/preference-widget';
import { createPreferencesWidgetContainer } from '@theia/preferences/lib/browser/views/preference-widget-bindings';
import {
BoardsFilterRenderer,
LibraryFilterRenderer,
} from './widgets/component-list/filter-renderer';
import { CheckForUpdates } from './contributions/check-for-updates';
import { OutputEditorFactory } from './theia/output/output-editor-factory';
import { StartupTaskProvider } from '../electron-common/startup-task';
import { DeleteSketch } from './contributions/delete-sketch';
import { UserFields } from './contributions/user-fields';
import { UpdateIndexes } from './contributions/update-indexes';
import { InterfaceScale } from './contributions/interface-scale';
import { OpenHandler } from '@theia/core/lib/browser/opener-service';
import { NewCloudSketch } from './contributions/new-cloud-sketch';
import { SketchbookCompositeWidget } from './widgets/sketchbook/sketchbook-composite-widget';
import { WindowTitleUpdater } from './theia/core/window-title-updater';
import { WindowTitleUpdater as TheiaWindowTitleUpdater } from '@theia/core/lib/browser/window/window-title-updater';
import {
MonacoThemingService,
CleanupObsoleteThemes,
ThemesRegistrationSummary,
MonacoThemeRegistry,
} from './theia/monaco/monaco-theming-service';
import { MonacoThemeRegistry as TheiaMonacoThemeRegistry } from '@theia/monaco/lib/browser/textmate/monaco-theme-registry';
import { MonacoThemingService as TheiaMonacoThemingService } from '@theia/monaco/lib/browser/monaco-theming-service';
import { TypeHierarchyServiceProvider } from './theia/typehierarchy/type-hierarchy-service';
import { TypeHierarchyServiceProvider as TheiaTypeHierarchyServiceProvider } from '@theia/typehierarchy/lib/browser/typehierarchy-service';
import { TypeHierarchyContribution } from './theia/typehierarchy/type-hierarchy-contribution';
import { TypeHierarchyContribution as TheiaTypeHierarchyContribution } from '@theia/typehierarchy/lib/browser/typehierarchy-contribution';
import { DefaultDebugSessionFactory } from './theia/debug/debug-session-contribution';
import { DebugSessionFactory } from '@theia/debug/lib/browser/debug-session-contribution';
import { ConfigServiceClient } from './config/config-service-client';
import { ValidateSketch } from './contributions/validate-sketch';
import { RenameCloudSketch } from './contributions/rename-cloud-sketch';
import { CreateFeatures } from './create/create-features';
import { Account } from './contributions/account';
import { SidebarBottomMenuWidget } from './theia/core/sidebar-bottom-menu-widget';
import { SidebarBottomMenuWidget as TheiaSidebarBottomMenuWidget } from '@theia/core/lib/browser/shell/sidebar-bottom-menu-widget';
import { CreateCloudCopy } from './contributions/create-cloud-copy';
import { FileResourceResolver } from './theia/filesystem/file-resource';
import { FileResourceResolver as TheiaFileResourceResolver } from '@theia/filesystem/lib/browser/file-resource';
import { StylingParticipant } from '@theia/core/lib/browser/styling-service';
import { MonacoEditorMenuContribution } from './theia/monaco/monaco-menu';
import { MonacoEditorMenuContribution as TheiaMonacoEditorMenuContribution } from '@theia/monaco/lib/browser/monaco-menu';
import { UpdateArduinoState } from './contributions/update-arduino-state';
import { TerminalFrontendContribution } from './theia/terminal/terminal-frontend-contribution';
import { TerminalFrontendContribution as TheiaTerminalFrontendContribution } from '@theia/terminal/lib/browser/terminal-frontend-contribution';
const registerArduinoThemes = () => {
const themes: MonacoThemeJson[] = [
{
id: 'arduino-theme',
label: 'Light (Arduino)',
uiTheme: 'vs',
json: require('../../src/browser/data/default.color-theme.json'),
},
{
id: 'arduino-theme-dark',
label: 'Dark (Arduino)',
uiTheme: 'vs-dark',
json: require('../../src/browser/data/dark.color-theme.json'),
},
];
themes.forEach((theme) => MonacoThemingService.register(theme));
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const global = window as any;
const ready = global[MonacoThemeServiceIsReady] as Deferred;
if (ready) {
ready.promise.then(registerArduinoThemes);
} else {
registerArduinoThemes();
}
// Hack to fix copy/cut/paste issue after electron version update in Theia.
// https://github.com/eclipse-theia/theia/issues/12487
import('@theia/core/lib/browser/common-frontend-contribution.js').then(
(theiaCommonContribution) => {
theiaCommonContribution['supportCopy'] = true;
theiaCommonContribution['supportCut'] = true;
theiaCommonContribution['supportPaste'] = true;
}
);
export default new ContainerModule((bind, unbind, isBound, rebind) => {
// Commands and toolbar items
// Commands, colors, theme adjustments, 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(StylingParticipant).toService(ArduinoFrontendContribution);
bind(ArduinoToolbarContribution).toSelf().inSingletonScope();
bind(FrontendApplicationContribution).toService(ArduinoToolbarContribution);
// Renderer for both the library and the core widgets.
bind(ListItemRenderer).toSelf().inSingletonScope();
bind(LibraryFilterRenderer).toSelf().inSingletonScope();
bind(BoardsFilterRenderer).toSelf().inSingletonScope();
// Library service
bind(LibraryService)
@@ -383,6 +407,7 @@ export default new ContainerModule((bind, unbind, isBound, rebind) => {
bind(FrontendApplicationContribution).toService(
LibraryListWidgetFrontendContribution
);
bind(OpenHandler).toService(LibraryListWidgetFrontendContribution);
// Sketch list service
bind(SketchesService)
@@ -405,6 +430,8 @@ export default new ContainerModule((bind, unbind, isBound, rebind) => {
)
)
.inSingletonScope();
bind(ConfigServiceClient).toSelf().inSingletonScope();
bind(FrontendApplicationContribution).toService(ConfigServiceClient);
// Boards service
bind(BoardsService)
@@ -418,11 +445,10 @@ export default new ContainerModule((bind, unbind, isBound, rebind) => {
// Boards service client to receive and delegate notifications from the backend.
bind(BoardsServiceProvider).toSelf().inSingletonScope();
bind(FrontendApplicationContribution).toService(BoardsServiceProvider);
bind(CommandContribution).toService(BoardsServiceProvider);
bind(BoardListDumper).toSelf().inSingletonScope();
// 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
@@ -448,12 +474,15 @@ export default new ContainerModule((bind, unbind, isBound, rebind) => {
bind(FrontendApplicationContribution).toService(
BoardsListWidgetFrontendContribution
);
bind(OpenHandler).toService(BoardsListWidgetFrontendContribution);
// Board select dialog
bind(BoardsConfigDialogWidget).toSelf().inSingletonScope();
bind(BoardsConfigDialog).toSelf().inSingletonScope();
bind(BoardsConfigDialogProps).toConstantValue({
title: nls.localize('arduino/common/selectBoard', 'Select Board'),
title: nls.localize(
'arduino/board/boardConfigDialogTitle',
'Select Other Board and Port'
),
});
// Core service
@@ -475,15 +504,7 @@ export default new ContainerModule((bind, unbind, isBound, rebind) => {
bind(TabBarToolbarContribution).toService(MonitorViewContribution);
bind(WidgetFactory).toDynamicValue((context) => ({
id: MonitorWidget.ID,
createWidget: () => {
return new MonitorWidget(
context.container.get<MonitorModel>(MonitorModel),
context.container.get<MonitorManagerProxyClient>(
MonitorManagerProxyClient
),
context.container.get<BoardsServiceProvider>(BoardsServiceProvider)
);
},
createWidget: () => context.container.get(MonitorWidget),
}));
bind(MonitorManagerProxyFactory).toFactory(
@@ -563,16 +584,6 @@ export default new ContainerModule((bind, unbind, isBound, rebind) => {
.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();
@@ -584,9 +595,6 @@ export default new ContainerModule((bind, unbind, isBound, rebind) => {
bind(MonacoEditorProvider).toSelf().inSingletonScope();
rebind(TheiaMonacoEditorProvider).toService(MonacoEditorProvider);
bind(SearchInWorkspaceWidget).toSelf();
rebind(TheiaSearchInWorkspaceWidget).toService(SearchInWorkspaceWidget);
// Disabled reference counter in the editor manager to avoid opening the same editor (with different opener options) multiple times.
bind(EditorManager).toSelf().inSingletonScope();
rebind(TheiaEditorManager).toService(EditorManager);
@@ -596,17 +604,6 @@ export default new ContainerModule((bind, unbind, isBound, rebind) => {
.to(SearchInWorkspaceFactory)
.inSingletonScope();
rebind(TheiaSearchInWorkspaceResultTreeWidget).toDynamicValue(
({ container }) => {
const childContainer = createTreeContainer(container);
childContainer.bind(SearchInWorkspaceResultTreeWidget).toSelf();
childContainer
.rebind(TreeWidget)
.toService(SearchInWorkspaceResultTreeWidget);
return childContainer.get(SearchInWorkspaceResultTreeWidget);
}
);
// Show a disconnected status bar, when the daemon is not available
bind(ApplicationConnectionStatusContribution).toSelf().inSingletonScope();
rebind(TheiaApplicationConnectionStatusContribution).toService(
@@ -637,6 +634,15 @@ export default new ContainerModule((bind, unbind, isBound, rebind) => {
bind(WindowContribution).toSelf().inSingletonScope();
rebind(TheiaWindowContribution).toService(WindowContribution);
// To remove `File` > `Close Editor`.
bind(EditorMenuContribution).toSelf().inSingletonScope();
rebind(TheiaEditorMenuContribution).toService(EditorMenuContribution);
// To disable the highlighting of non-unicode characters in the _Output_ view
bind(OutputEditorFactory).toSelf().inSingletonScope();
// Rebind to `TheiaOutputEditorFactory` when https://github.com/eclipse-theia/theia/pull/11615 is available.
rebind(MonacoEditorFactory).toService(OutputEditorFactory);
bind(ArduinoDaemon)
.toDynamicValue((context) =>
WebSocketConnectionProvider.createProxy(
@@ -702,7 +708,7 @@ export default new ContainerModule((bind, unbind, isBound, rebind) => {
Contribution.configure(bind, EditContributions);
Contribution.configure(bind, QuitApp);
Contribution.configure(bind, SketchControl);
Contribution.configure(bind, Settings);
Contribution.configure(bind, OpenSettings);
Contribution.configure(bind, BurnBootloader);
Contribution.configure(bind, BuiltInExamples);
Contribution.configure(bind, LibraryExamples);
@@ -721,16 +727,32 @@ export default new ContainerModule((bind, unbind, isBound, rebind) => {
Contribution.configure(bind, PlotterFrontendContribution);
Contribution.configure(bind, Format);
Contribution.configure(bind, CompilerErrors);
Contribution.configure(bind, StartupTasks);
Contribution.configure(bind, StartupTasksExecutor);
Contribution.configure(bind, IndexesUpdateProgress);
Contribution.configure(bind, Daemon);
Contribution.configure(bind, FirstStartupInstaller);
Contribution.configure(bind, OpenSketchFiles);
Contribution.configure(bind, InoLanguage);
Contribution.configure(bind, SelectedBoard);
Contribution.configure(bind, CheckForUpdates);
Contribution.configure(bind, CheckForIDEUpdates);
Contribution.configure(bind, OpenBoardsConfig);
Contribution.configure(bind, SketchFilesTracker);
Contribution.configure(bind, CheckForUpdates);
Contribution.configure(bind, UserFields);
Contribution.configure(bind, DeleteSketch);
Contribution.configure(bind, UpdateIndexes);
Contribution.configure(bind, InterfaceScale);
Contribution.configure(bind, NewCloudSketch);
Contribution.configure(bind, ValidateSketch);
Contribution.configure(bind, RenameCloudSketch);
Contribution.configure(bind, Account);
Contribution.configure(bind, CloudSketchbookContribution);
Contribution.configure(bind, CreateCloudCopy);
Contribution.configure(bind, UpdateArduinoState);
Contribution.configure(bind, BoardsDataMenuUpdater);
bindContributionProvider(bind, StartupTaskProvider);
bind(StartupTaskProvider).toService(BoardsServiceProvider); // to reuse the boards config in another window
// Disabled the quick-pick customization from Theia when multiple formatters are available.
// Use the default VS Code behavior, and pick the first one. In the IDE2, clang-format has `exclusive` selectors.
@@ -812,9 +834,6 @@ export default new ContainerModule((bind, unbind, isBound, rebind) => {
bind(AboutDialog).toSelf().inSingletonScope();
rebind(TheiaAboutDialog).toService(AboutDialog);
// 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(
@@ -828,14 +847,22 @@ export default new ContainerModule((bind, unbind, isBound, rebind) => {
bind(WidgetManager).toSelf().inSingletonScope();
rebind(TheiaWidgetManager).toService(WidgetManager);
// To avoid running a status bar update on every single `keypress` event from the editor.
bind(StatusBarImpl).toSelf().inSingletonScope();
rebind(TheiaStatusBarImpl).toService(StatusBarImpl);
// Debounced update for the tab-bar toolbar when typing in the editor.
bind(DockPanelRenderer).toSelf();
rebind(TheiaDockPanelRenderer).toService(DockPanelRenderer);
// Avoid running the "reset scroll" interval tasks until the preference editor opens.
rebind(PreferencesWidget)
.toDynamicValue(({ container }) => {
const child = createPreferencesWidgetContainer(container);
child.bind(PreferencesEditorWidget).toSelf().inSingletonScope();
child
.rebind(TheiaPreferencesEditorWidget)
.toService(PreferencesEditorWidget);
return child.get(PreferencesWidget);
})
.inSingletonScope();
// Preferences
bindArduinoPreferences(bind);
@@ -851,9 +878,6 @@ export default new ContainerModule((bind, unbind, isBound, rebind) => {
),
});
bind(StorageWrapper).toSelf().inSingletonScope();
bind(CommandContribution).toService(StorageWrapper);
bind(NotificationManager).toSelf().inSingletonScope();
rebind(TheiaNotificationManager).toService(NotificationManager);
bind(NotificationsRenderer).toSelf().inSingletonScope();
@@ -870,6 +894,11 @@ export default new ContainerModule((bind, unbind, isBound, rebind) => {
id: 'arduino-sketchbook-widget',
createWidget: () => container.get(SketchbookWidget),
}));
bind(SketchbookCompositeWidget).toSelf();
bind<WidgetFactory>(WidgetFactory).toDynamicValue((ctx) => ({
id: 'sketchbook-composite-widget',
createWidget: () => ctx.container.get(SketchbookCompositeWidget),
}));
bind(CloudSketchbookWidget).toSelf();
rebind(SketchbookWidget).toService(CloudSketchbookWidget);
@@ -878,6 +907,8 @@ export default new ContainerModule((bind, unbind, isBound, rebind) => {
);
bind(CreateApi).toSelf().inSingletonScope();
bind(SketchCache).toSelf().inSingletonScope();
bind(CreateFeatures).toSelf().inSingletonScope();
bind(FrontendApplicationContribution).toService(CreateFeatures);
bind(ShareSketchDialog).toSelf().inSingletonScope();
bind(AuthenticationClientService).toSelf().inSingletonScope();
@@ -894,17 +925,14 @@ export default new ContainerModule((bind, unbind, isBound, rebind) => {
bind(CreateFsProvider).toSelf().inSingletonScope();
bind(FrontendApplicationContribution).toService(CreateFsProvider);
bind(FileServiceContribution).toService(CreateFsProvider);
bind(CloudSketchbookContribution).toSelf().inSingletonScope();
bind(CommandContribution).toService(CloudSketchbookContribution);
bind(LocalCacheFsProvider).toSelf().inSingletonScope();
bind(FileServiceContribution).toService(LocalCacheFsProvider);
bind(CloudSketchbookCompositeWidget).toSelf();
bind<WidgetFactory>(WidgetFactory).toDynamicValue((ctx) => ({
bind(WidgetFactory).toDynamicValue((ctx) => ({
id: 'cloud-sketchbook-composite-widget',
createWidget: () => ctx.container.get(CloudSketchbookCompositeWidget),
}));
bind(UploadFirmwareDialogWidget).toSelf().inSingletonScope();
bind(UploadFirmwareDialog).toSelf().inSingletonScope();
bind(UploadFirmwareDialogProps).toConstantValue({
title: 'UploadFirmware',
@@ -915,13 +943,11 @@ export default new ContainerModule((bind, unbind, isBound, rebind) => {
title: 'UploadCertificate',
});
bind(IDEUpdaterDialogWidget).toSelf().inSingletonScope();
bind(IDEUpdaterDialog).toSelf().inSingletonScope();
bind(IDEUpdaterDialogProps).toConstantValue({
title: 'IDEUpdater',
});
bind(UserFieldsDialogWidget).toSelf().inSingletonScope();
bind(UserFieldsDialog).toSelf().inSingletonScope();
bind(UserFieldsDialogProps).toConstantValue({
title: 'UserFields',
@@ -948,4 +974,60 @@ export default new ContainerModule((bind, unbind, isBound, rebind) => {
rebind(TheiaHostedPluginSupport).toService(HostedPluginSupport);
bind(HostedPluginEvents).toSelf().inSingletonScope();
bind(FrontendApplicationContribution).toService(HostedPluginEvents);
// custom window titles
bind(WindowTitleUpdater).toSelf().inSingletonScope();
rebind(TheiaWindowTitleUpdater).toService(WindowTitleUpdater);
// register Arduino themes
bind(MonacoThemingService).toSelf().inSingletonScope();
rebind(TheiaMonacoThemingService).toService(MonacoThemingService);
// workaround for themes cannot be removed after registration
// https://github.com/eclipse-theia/theia/issues/11151
bind(CleanupObsoleteThemes).toSelf().inSingletonScope();
bind(FrontendApplicationContribution).toService(CleanupObsoleteThemes);
bind(ThemesRegistrationSummary).toSelf().inSingletonScope();
bind(MonacoThemeRegistry).toSelf().inSingletonScope();
rebind(TheiaMonacoThemeRegistry).toService(MonacoThemeRegistry);
// disable type-hierarchy support
// https://github.com/eclipse-theia/theia/commit/16c88a584bac37f5cf3cc5eb92ffdaa541bda5be
bind(TypeHierarchyServiceProvider).toSelf().inSingletonScope();
rebind(TheiaTypeHierarchyServiceProvider).toService(
TypeHierarchyServiceProvider
);
bind(TypeHierarchyContribution).toSelf().inSingletonScope();
rebind(TheiaTypeHierarchyContribution).toService(TypeHierarchyContribution);
bind(DefaultDebugSessionFactory).toSelf().inSingletonScope();
rebind(DebugSessionFactory).toService(DefaultDebugSessionFactory);
bind(SidebarBottomMenuWidget).toSelf();
rebind(TheiaSidebarBottomMenuWidget).toService(SidebarBottomMenuWidget);
bind(ArduinoComponentContextMenuRenderer).toSelf().inSingletonScope();
bind(DaemonPort).toSelf().inSingletonScope();
bind(FrontendApplicationContribution).toService(DaemonPort);
bind(IsOnline).toSelf().inSingletonScope();
bind(FrontendApplicationContribution).toService(IsOnline);
// https://github.com/arduino/arduino-ide/issues/437
bind(FileResourceResolver).toSelf().inSingletonScope();
rebind(TheiaFileResourceResolver).toService(FileResourceResolver);
// Full control over the editor context menu to filter undesired menu items contributed by Theia.
// https://github.com/arduino/arduino-ide/issues/1394
// https://github.com/arduino/arduino-ide/pull/2027#pullrequestreview-1414246614
bind(MonacoEditorMenuContribution).toSelf().inSingletonScope();
rebind(TheiaMonacoEditorMenuContribution).toService(
MonacoEditorMenuContribution
);
// Patch terminal issues.
bind(TerminalFrontendContribution).toSelf().inSingletonScope();
rebind(TheiaTerminalFrontendContribution).toService(
TerminalFrontendContribution
);
});

View File

@@ -1,12 +1,15 @@
import { interfaces } from '@theia/core/shared/inversify';
import {
createPreferenceProxy,
PreferenceProxy,
PreferenceService,
PreferenceContribution,
PreferenceProxy,
PreferenceSchema,
PreferenceService,
createPreferenceProxy,
} from '@theia/core/lib/browser/preferences';
import { nls } from '@theia/core/lib/common';
import { ApplicationShell } from '@theia/core/lib/browser/shell/application-shell';
import { nls } from '@theia/core/lib/common/nls';
import { PreferenceSchemaProperty } from '@theia/core/lib/common/preferences/preference-schema';
import { interfaces } from '@theia/core/shared/inversify';
import { serialMonitorWidgetLabel } from '../common/nls';
import { CompilerWarningLiterals, CompilerWarnings } from '../common/protocol';
export enum UpdateChannel {
@@ -31,7 +34,7 @@ export const ErrorRevealStrategyLiterals = [
*/
'centerIfOutsideViewport',
] as const;
export type ErrorRevealStrategy = typeof ErrorRevealStrategyLiterals[number];
export type ErrorRevealStrategy = (typeof ErrorRevealStrategyLiterals)[number];
export namespace ErrorRevealStrategy {
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any
export function is(arg: any): arg is ErrorRevealStrategy {
@@ -40,208 +43,254 @@ export namespace ErrorRevealStrategy {
export const Default: ErrorRevealStrategy = 'centerIfOutsideViewport';
}
export type MonitorWidgetDockPanel = Extract<
ApplicationShell.Area,
'bottom' | 'right'
>;
export const defaultMonitorWidgetDockPanel: MonitorWidgetDockPanel = 'bottom';
export function isMonitorWidgetDockPanel(
arg: unknown
): arg is MonitorWidgetDockPanel {
return arg === 'bottom' || arg === 'right';
}
type StrictPreferenceSchemaProperties<T extends object> = {
[p in keyof T]: PreferenceSchemaProperty;
};
type ArduinoPreferenceSchemaProperties =
StrictPreferenceSchemaProperties<ArduinoConfiguration> & { 'arduino.window.zoomLevel': PreferenceSchemaProperty };
const properties: ArduinoPreferenceSchemaProperties = {
'arduino.language.log': {
type: 'boolean',
description: nls.localize(
'arduino/preferences/language.log',
"True if the Arduino Language Server should generate log files into the sketch folder. Otherwise, false. It's false by default."
),
default: false,
},
'arduino.language.realTimeDiagnostics': {
type: 'boolean',
description: nls.localize(
'arduino/preferences/language.realTimeDiagnostics',
"If true, the language server provides real-time diagnostics when typing in the editor. It's false by default."
),
default: false,
},
'arduino.compile.verbose': {
type: 'boolean',
description: nls.localize(
'arduino/preferences/compile.verbose',
'True for verbose compile output. False by default'
),
default: false,
},
'arduino.compile.experimental': {
type: 'boolean',
description: nls.localize(
'arduino/preferences/compile.experimental',
'True if the IDE should handle multiple compiler errors. False by default'
),
default: false,
},
'arduino.compile.revealRange': {
enum: [...ErrorRevealStrategyLiterals],
description: nls.localize(
'arduino/preferences/compile.revealRange',
"Adjusts how compiler errors are revealed in the editor after a failed verify/upload. Possible values: 'auto': Scroll vertically as necessary and reveal a line. 'center': Scroll vertically as necessary and reveal a line centered vertically. 'top': Scroll vertically as necessary and reveal a line close to the top of the viewport, optimized for viewing a code definition. 'centerIfOutsideViewport': Scroll vertically as necessary and reveal a line centered vertically only if it lies outside the viewport. The default value is '{0}'.",
ErrorRevealStrategy.Default
),
default: ErrorRevealStrategy.Default,
},
'arduino.compile.warnings': {
enum: [...CompilerWarningLiterals],
description: nls.localize(
'arduino/preferences/compile.warnings',
"Tells gcc which warning level to use. It's 'None' by default"
),
default: 'None',
},
'arduino.upload.verbose': {
type: 'boolean',
description: nls.localize(
'arduino/preferences/upload.verbose',
'True for verbose upload output. False by default.'
),
default: false,
},
'arduino.upload.verify': {
type: 'boolean',
default: false,
},
'arduino.window.autoScale': {
type: 'boolean',
description: nls.localize(
'arduino/preferences/window.autoScale',
'True if the user interface automatically scales with the font size.'
),
default: true,
},
'arduino.window.zoomLevel': {
type: 'number',
description: '',
default: 0,
deprecationMessage: nls.localize(
'arduino/preferences/window.zoomLevel/deprecationMessage',
"Deprecated. Use 'window.zoomLevel' instead."
),
},
'arduino.ide.updateChannel': {
type: 'string',
enum: Object.values(UpdateChannel) as UpdateChannel[],
default: UpdateChannel.Stable,
description: nls.localize(
'arduino/preferences/ide.updateChannel',
"Release channel to get updated from. 'stable' is the stable release, 'nightly' is the latest development build."
),
},
'arduino.ide.updateBaseUrl': {
type: 'string',
default: 'https://downloads.arduino.cc/arduino-ide',
description: nls.localize(
'arduino/preferences/ide.updateBaseUrl',
"The base URL where to download updates from. Defaults to 'https://downloads.arduino.cc/arduino-ide'"
),
},
'arduino.board.certificates': {
type: 'string',
description: nls.localize(
'arduino/preferences/board.certificates',
'List of certificates that can be uploaded to boards'
),
default: '',
},
'arduino.sketchbook.showAllFiles': {
type: 'boolean',
description: nls.localize(
'arduino/preferences/sketchbook.showAllFiles',
'True to show all sketch files inside the sketch. It is false by default.'
),
default: false,
},
'arduino.cloud.enabled': {
type: 'boolean',
description: nls.localize(
'arduino/preferences/cloud.enabled',
'True if the sketch sync functions are enabled. Defaults to true.'
),
default: true,
},
'arduino.cloud.pull.warn': {
type: 'boolean',
description: nls.localize(
'arduino/preferences/cloud.pull.warn',
'True if users should be warned before pulling a cloud sketch. Defaults to true.'
),
default: true,
},
'arduino.cloud.push.warn': {
type: 'boolean',
description: nls.localize(
'arduino/preferences/cloud.push.warn',
'True if users should be warned before pushing a cloud sketch. Defaults to true.'
),
default: true,
},
'arduino.cloud.pushpublic.warn': {
type: 'boolean',
description: nls.localize(
'arduino/preferences/cloud.pushpublic.warn',
'True if users should be warned before pushing a public sketch to the cloud. Defaults to true.'
),
default: true,
},
'arduino.cloud.sketchSyncEndpoint': {
type: 'string',
description: nls.localize(
'arduino/preferences/cloud.sketchSyncEndpoint',
'The endpoint used to push and pull sketches from a backend. By default it points to Arduino Cloud API.'
),
default: 'https://api2.arduino.cc/create',
},
'arduino.auth.clientID': {
type: 'string',
description: nls.localize(
'arduino/preferences/auth.clientID',
'The OAuth2 client ID.'
),
default: 'C34Ya6ex77jTNxyKWj01lCe1vAHIaPIo',
},
'arduino.auth.domain': {
type: 'string',
description: nls.localize(
'arduino/preferences/auth.domain',
'The OAuth2 domain.'
),
default: 'login.arduino.cc',
},
'arduino.auth.audience': {
type: 'string',
description: nls.localize(
'arduino/preferences/auth.audience',
'The OAuth2 audience.'
),
default: 'https://api.arduino.cc',
},
'arduino.auth.registerUri': {
type: 'string',
description: nls.localize(
'arduino/preferences/auth.registerUri',
'The URI used to register a new user.'
),
default: 'https://auth.arduino.cc/login#/register',
},
'arduino.survey.notification': {
type: 'boolean',
description: nls.localize(
'arduino/preferences/survey.notification',
'True if users should be notified if a survey is available. True by default.'
),
default: true,
},
'arduino.cli.daemon.debug': {
type: 'boolean',
description: nls.localize(
'arduino/preferences/cli.daemonDebug',
"Enable debug logging of the gRPC calls to the Arduino CLI. A restart of the IDE is needed for this setting to take effect. It's false by default."
),
default: false,
},
'arduino.checkForUpdates': {
type: 'boolean',
description: nls.localize(
'arduino/preferences/checkForUpdate',
"Receive notifications of available updates for the IDE, boards, and libraries. Requires an IDE restart after change. It's true by default."
),
default: true,
},
'arduino.sketch.inoBlueprint': {
type: 'string',
markdownDescription: nls.localize(
'arduino/preferences/sketch/inoBlueprint',
'Absolute filesystem path to the default `.ino` blueprint file. If specified, the content of the blueprint file will be used for every new sketch created by the IDE. The sketches will be generated with the default Arduino content if not specified. Unaccessible blueprint files are ignored. **A restart of the IDE is needed** for this setting to take effect.'
),
default: undefined,
},
'arduino.monitor.dockPanel': {
type: 'string',
enum: ['bottom', 'right'],
markdownDescription: nls.localize(
'arduino/preferences/monitor/dockPanel',
'The area of the application shell where the _{0}_ widget will reside. It is either "bottom" or "right". It defaults to "{1}".',
serialMonitorWidgetLabel,
defaultMonitorWidgetDockPanel
),
default: defaultMonitorWidgetDockPanel,
},
};
export const ArduinoConfigSchema: PreferenceSchema = {
type: 'object',
properties: {
'arduino.language.log': {
type: 'boolean',
description: nls.localize(
'arduino/preferences/language.log',
"True if the Arduino Language Server should generate log files into the sketch folder. Otherwise, false. It's false by default."
),
default: false,
},
'arduino.language.realTimeDiagnostics': {
type: 'boolean',
description: nls.localize(
'arduino/preferences/language.realTimeDiagnostics',
"If true, the language server provides real-time diagnostics when typing in the editor. It's false by default."
),
default: false,
},
'arduino.compile.verbose': {
type: 'boolean',
description: nls.localize(
'arduino/preferences/compile.verbose',
'True for verbose compile output. False by default'
),
default: false,
},
'arduino.compile.experimental': {
type: 'boolean',
description: nls.localize(
'arduino/preferences/compile.experimental',
'True if the IDE should handle multiple compiler errors. False by default'
),
default: false,
},
'arduino.compile.revealRange': {
enum: [...ErrorRevealStrategyLiterals],
description: nls.localize(
'arduino/preferences/compile.revealRange',
"Adjusts how compiler errors are revealed in the editor after a failed verify/upload. Possible values: 'auto': Scroll vertically as necessary and reveal a line. 'center': Scroll vertically as necessary and reveal a line centered vertically. 'top': Scroll vertically as necessary and reveal a line close to the top of the viewport, optimized for viewing a code definition. 'centerIfOutsideViewport': Scroll vertically as necessary and reveal a line centered vertically only if it lies outside the viewport. The default value is '{0}'.",
ErrorRevealStrategy.Default
),
default: ErrorRevealStrategy.Default,
},
'arduino.compile.warnings': {
enum: [...CompilerWarningLiterals],
description: nls.localize(
'arduino/preferences/compile.warnings',
"Tells gcc which warning level to use. It's 'None' by default"
),
default: 'None',
},
'arduino.upload.verbose': {
type: 'boolean',
description: nls.localize(
'arduino/preferences/upload.verbose',
'True for verbose upload output. False by default.'
),
default: false,
},
'arduino.upload.verify': {
type: 'boolean',
default: false,
},
'arduino.window.autoScale': {
type: 'boolean',
description: nls.localize(
'arduino/preferences/window.autoScale',
'True if the user interface automatically scales with the font size.'
),
default: true,
},
'arduino.window.zoomLevel': {
type: 'number',
description: nls.localize(
'arduino/preferences/window.zoomLevel',
'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.updateChannel': {
type: 'string',
enum: Object.values(UpdateChannel) as UpdateChannel[],
default: UpdateChannel.Stable,
description: nls.localize(
'arduino/preferences/ide.updateChannel',
"Release channel to get updated from. 'stable' is the stable release, 'nightly' is the latest development build."
),
},
'arduino.ide.updateBaseUrl': {
type: 'string',
default: 'https://downloads.arduino.cc/arduino-ide',
description: nls.localize(
'arduino/preferences/ide.updateBaseUrl',
"The base URL where to download updates from. Defaults to 'https://downloads.arduino.cc/arduino-ide'"
),
},
'arduino.board.certificates': {
type: 'string',
description: nls.localize(
'arduino/preferences/board.certificates',
'List of certificates that can be uploaded to boards'
),
default: '',
},
'arduino.sketchbook.showAllFiles': {
type: 'boolean',
description: nls.localize(
'arduino/preferences/sketchbook.showAllFiles',
'True to show all sketch files inside the sketch. It is false by default.'
),
default: false,
},
'arduino.cloud.enabled': {
type: 'boolean',
description: nls.localize(
'arduino/preferences/cloud.enabled',
'True if the sketch sync functions are enabled. Defaults to true.'
),
default: true,
},
'arduino.cloud.pull.warn': {
type: 'boolean',
description: nls.localize(
'arduino/preferences/cloud.pull.warn',
'True if users should be warned before pulling a cloud sketch. Defaults to true.'
),
default: true,
},
'arduino.cloud.push.warn': {
type: 'boolean',
description: nls.localize(
'arduino/preferences/cloud.push.warn',
'True if users should be warned before pushing a cloud sketch. Defaults to true.'
),
default: true,
},
'arduino.cloud.pushpublic.warn': {
type: 'boolean',
description: nls.localize(
'arduino/preferences/cloud.pushpublic.warn',
'True if users should be warned before pushing a public sketch to the cloud. Defaults to true.'
),
default: true,
},
'arduino.cloud.sketchSyncEndpoint': {
type: 'string',
description: nls.localize(
'arduino/preferences/cloud.sketchSyncEndpoint',
'The endpoint used to push and pull sketches from a backend. By default it points to Arduino Cloud API.'
),
default: 'https://api2.arduino.cc/create',
},
'arduino.auth.clientID': {
type: 'string',
description: nls.localize(
'arduino/preferences/auth.clientID',
'The OAuth2 client ID.'
),
default: 'C34Ya6ex77jTNxyKWj01lCe1vAHIaPIo',
},
'arduino.auth.domain': {
type: 'string',
description: nls.localize(
'arduino/preferences/auth.domain',
'The OAuth2 domain.'
),
default: 'login.arduino.cc',
},
'arduino.auth.audience': {
type: 'string',
description: nls.localize(
'arduino/preferences/auth.audience',
'The OAuth2 audience.'
),
default: 'https://api.arduino.cc',
},
'arduino.auth.registerUri': {
type: 'string',
description: nls.localize(
'arduino/preferences/auth.registerUri',
'The URI used to register a new user.'
),
default: 'https://auth.arduino.cc/login#/register',
},
'arduino.survey.notification': {
type: 'boolean',
description: nls.localize(
'arduino/preferences/survey.notification',
'True if users should be notified if a survey is available. True by default.'
),
default: true,
},
'arduino.cli.daemon.debug': {
type: 'boolean',
description: nls.localize(
'arduino/preferences/cli.daemonDebug',
"Enable debug logging of the gRPC calls to the Arduino CLI. A restart of the IDE is needed for this setting to take effect. It's false by default."
),
default: false,
},
},
properties,
};
export interface ArduinoConfiguration {
@@ -254,7 +303,6 @@ export interface ArduinoConfiguration {
'arduino.upload.verbose': boolean;
'arduino.upload.verify': boolean;
'arduino.window.autoScale': boolean;
'arduino.window.zoomLevel': number;
'arduino.ide.updateChannel': UpdateChannel;
'arduino.ide.updateBaseUrl': string;
'arduino.board.certificates': string;
@@ -270,6 +318,9 @@ export interface ArduinoConfiguration {
'arduino.auth.registerUri': string;
'arduino.survey.notification': boolean;
'arduino.cli.daemon.debug': boolean;
'arduino.sketch.inoBlueprint': string;
'arduino.checkForUpdates': boolean;
'arduino.monitor.dockPanel': MonitorWidgetDockPanel;
}
export const ArduinoPreferences = Symbol('ArduinoPreferences');

View File

@@ -1,68 +0,0 @@
import { URI } from '@theia/core/shared/vscode-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 = decodeURI(hash.slice(1)).replace(/\\/g, '/'); // Trim the leading `#`, decode the URI and replace Windows separators
return URI.file(path.slice(isWindows && hash.startsWith('/') ? 1 : 0)).toString();
}
return undefined;
}
}

View File

@@ -9,13 +9,13 @@ import {
CommandContribution,
} from '@theia/core/lib/common/command';
import {
AuthOptions,
AuthenticationService,
AuthenticationServiceClient,
AuthenticationSession,
authServerPort,
} from '../../common/protocol/authentication-service';
import { CloudUserCommands } from './cloud-user-commands';
import { serverPort } from '../../node/auth/authentication-server';
import { AuthOptions } from '../../node/auth/types';
import { ArduinoPreferences } from '../arduino-preferences';
@injectable()
@@ -61,7 +61,7 @@ export class AuthenticationClientService
setOptions(): Promise<void> {
return this.service.setOptions({
redirectUri: `http://localhost:${serverPort}/callback`,
redirectUri: `http://localhost:${authServerPort}/callback`,
responseType: 'code',
clientID: this.arduinoPreferences['arduino.auth.clientID'],
domain: this.arduinoPreferences['arduino.auth.domain'],
@@ -83,9 +83,13 @@ export class AuthenticationClientService
registerCommands(registry: CommandRegistry): void {
registry.registerCommand(CloudUserCommands.LOGIN, {
execute: () => this.service.login(),
isEnabled: () => !this._session,
isVisible: () => !this._session,
});
registry.registerCommand(CloudUserCommands.LOGOUT, {
execute: () => this.service.logout(),
isEnabled: () => !!this._session,
isVisible: () => !!this._session,
});
}

View File

@@ -1,5 +1,8 @@
import { Command } from '@theia/core/lib/common/command';
export const LEARN_MORE_URL =
'https://docs.arduino.cc/software/ide-v2/tutorials/ide-v2-cloud-sketch-sync';
export namespace CloudUserCommands {
export const LOGIN = Command.toLocalizedCommand(
{
@@ -16,9 +19,4 @@ export namespace CloudUserCommands {
},
'arduino/cloud/signOut'
);
export const OPEN_PROFILE_CONTEXT_MENU: Command = {
id: 'arduino-cloud-sketchbook--open-profile-menu',
label: 'Contextual menu',
};
}

View File

@@ -1,281 +1,229 @@
import { injectable, inject } from '@theia/core/shared/inversify';
import { MessageService } from '@theia/core/lib/common/message-service';
import { FrontendApplicationContribution } from '@theia/core/lib/browser/frontend-application';
import {
BoardsService,
BoardsPackage,
Board,
Port,
} from '../../common/protocol/boards-service';
import { BoardsServiceProvider } from './boards-service-provider';
import { DisposableCollection } from '@theia/core/lib/common/disposable';
import { MessageService } from '@theia/core/lib/common/message-service';
import { MessageType } from '@theia/core/lib/common/message-service-protocol';
import { nls } from '@theia/core/lib/common/nls';
import { notEmpty } from '@theia/core/lib/common/objects';
import { inject, injectable } from '@theia/core/shared/inversify';
import { NotificationManager } from '@theia/messages/lib/browser/notifications-manager';
import { InstallManually } from '../../common/nls';
import { Installable, ResponseServiceClient } from '../../common/protocol';
import { BoardsListWidgetFrontendContribution } from './boards-widget-frontend-contribution';
import { nls } from '@theia/core/lib/common';
import {
BoardIdentifier,
BoardsPackage,
BoardsService,
createPlatformIdentifier,
isBoardIdentifierChangeEvent,
PlatformIdentifier,
platformIdentifierEquals,
serializePlatformIdentifier,
} from '../../common/protocol/boards-service';
import { NotificationCenter } from '../notification-center';
interface AutoInstallPromptAction {
// isAcceptance, whether or not the action indicates acceptance of auto-install proposal
isAcceptance?: boolean;
key: string;
handler: (...args: unknown[]) => unknown;
}
type AutoInstallPromptActions = AutoInstallPromptAction[];
import { BoardsServiceProvider } from './boards-service-provider';
import { BoardsListWidgetFrontendContribution } from './boards-widget-frontend-contribution';
/**
* Listens on `BoardsConfig.Config` changes, if a board is selected which does not
* Listens on `BoardsConfigChangeEvent`s, if a board is selected which does not
* have the corresponding core installed, it proposes the user to install the core.
*/
// * Cases in which we do not show the auto-install prompt:
// 1. When a related platform is already installed
// 2. When a prompt is already showing in the UI
// 3. When a board is unplugged
@injectable()
export class BoardsAutoInstaller implements FrontendApplicationContribution {
@inject(NotificationCenter)
private readonly notificationCenter: NotificationCenter;
@inject(MessageService)
protected readonly messageService: MessageService;
private readonly messageService: MessageService;
@inject(NotificationManager)
private readonly notificationManager: NotificationManager;
@inject(BoardsService)
protected readonly boardsService: BoardsService;
private readonly boardsService: BoardsService;
@inject(BoardsServiceProvider)
protected readonly boardsServiceClient: BoardsServiceProvider;
private readonly boardsServiceProvider: BoardsServiceProvider;
@inject(ResponseServiceClient)
protected readonly responseService: ResponseServiceClient;
private readonly responseService: ResponseServiceClient;
@inject(BoardsListWidgetFrontendContribution)
protected readonly boardsManagerFrontendContribution: BoardsListWidgetFrontendContribution;
private readonly boardsManagerWidgetContribution: BoardsListWidgetFrontendContribution;
// Workaround for https://github.com/eclipse-theia/theia/issues/9349
protected notifications: Board[] = [];
// * "refusal" meaning a "prompt action" not accepting the auto-install offer ("X" or "install manually")
// we can use "portSelectedOnLastRefusal" to deduce when a board is unplugged after a user has "refused"
// an auto-install prompt. Important to know as we do not want "an unplug" to trigger a "refused" prompt
// showing again
private portSelectedOnLastRefusal: Port | undefined;
private lastRefusedPackageId: string | undefined;
private readonly installNotificationInfos: Readonly<{
boardName: string;
platformId: string;
notificationId: string;
}>[] = [];
private readonly toDispose = new DisposableCollection();
onStart(): void {
const setEventListeners = () => {
this.boardsServiceClient.onBoardsConfigChanged((config) => {
const { selectedBoard, selectedPort } = config;
const boardWasUnplugged =
!selectedPort && this.portSelectedOnLastRefusal;
this.clearLastRefusedPromptInfo();
if (
boardWasUnplugged ||
!selectedBoard ||
this.promptAlreadyShowingForBoard(selectedBoard)
) {
return;
this.toDispose.pushAll([
this.boardsServiceProvider.onBoardsConfigDidChange((event) => {
if (isBoardIdentifierChangeEvent(event)) {
this.ensureCoreExists(event.selectedBoard);
}
this.ensureCoreExists(selectedBoard, selectedPort);
});
// we "clearRefusedPackageInfo" if a "refused" package is eventually
// installed, though this is not strictly necessary. It's more of a
// cleanup, to ensure the related variables are representative of
// current state.
this.notificationCenter.onPlatformDidInstall((installed) => {
if (this.lastRefusedPackageId === installed.item.id) {
this.clearLastRefusedPromptInfo();
}
});
};
// we should invoke this.ensureCoreExists only once we're sure
// everything has been reconciled
this.boardsServiceClient.reconciled.then(() => {
const { selectedBoard, selectedPort } =
this.boardsServiceClient.boardsConfig;
if (selectedBoard) {
this.ensureCoreExists(selectedBoard, selectedPort);
}
setEventListeners();
}),
this.notificationCenter.onPlatformDidInstall((event) =>
this.clearAllNotificationForPlatform(event.item.id)
),
]);
this.boardsServiceProvider.ready.then(() => {
const { selectedBoard } = this.boardsServiceProvider.boardsConfig;
this.ensureCoreExists(selectedBoard);
});
}
private removeNotificationByBoard(selectedBoard: Board): void {
const index = this.notifications.findIndex((notification) =>
Board.sameAs(notification, selectedBoard)
);
if (index !== -1) {
this.notifications.splice(index, 1);
private async findPlatformToInstall(
selectedBoard: BoardIdentifier
): Promise<BoardsPackage | undefined> {
const platformId = await this.findPlatformIdToInstall(selectedBoard);
if (!platformId) {
return undefined;
}
const id = serializePlatformIdentifier(platformId);
const platform = await this.boardsService.getBoardPackage({ id });
if (!platform) {
console.warn(`Could not resolve platform for ID: ${id}`);
return undefined;
}
if (platform.installedVersion) {
return undefined;
}
return platform;
}
private clearLastRefusedPromptInfo(): void {
this.lastRefusedPackageId = undefined;
this.portSelectedOnLastRefusal = undefined;
}
private setLastRefusedPromptInfo(
packageId: string,
selectedPort?: Port
): void {
this.lastRefusedPackageId = packageId;
this.portSelectedOnLastRefusal = selectedPort;
}
private promptAlreadyShowingForBoard(board: Board): boolean {
return Boolean(
this.notifications.find((notification) =>
Board.sameAs(notification, board)
)
);
}
protected ensureCoreExists(selectedBoard: Board, selectedPort?: Port): void {
this.notifications.push(selectedBoard);
this.boardsService.search({}).then((packages) => {
const candidate = this.getInstallCandidate(packages, selectedBoard);
if (candidate) {
this.showAutoInstallPrompt(candidate, selectedBoard, selectedPort);
} else {
this.removeNotificationByBoard(selectedBoard);
private async findPlatformIdToInstall(
selectedBoard: BoardIdentifier
): Promise<PlatformIdentifier | undefined> {
const selectedBoardPlatformId = createPlatformIdentifier(selectedBoard);
// The board is installed or the FQBN is available from the `board list watch` for Arduino boards. The latter might change!
if (selectedBoardPlatformId) {
const installedPlatforms =
await this.boardsService.getInstalledPlatforms();
const installedPlatformIds = installedPlatforms
.map((platform) => createPlatformIdentifier(platform.id))
.filter(notEmpty);
if (
installedPlatformIds.every(
(installedPlatformId) =>
!platformIdentifierEquals(
installedPlatformId,
selectedBoardPlatformId
)
)
) {
return selectedBoardPlatformId;
}
});
} else {
// IDE2 knows that selected board is not installed. Look for board `name` match in not yet installed platforms.
// The order should be correct when there is a board name collision (e.g. Arduino Nano RP2040 from Arduino Mbed OS Nano Boards, [DEPRECATED] Arduino Mbed OS Nano Boards). The CLI boosts the platforms, so picking the first name match should be fine.
const platforms = await this.boardsService.search({});
for (const platform of platforms) {
// Ignore installed platforms
if (platform.installedVersion) {
continue;
}
if (
platform.boards.some((board) => board.name === selectedBoard.name)
) {
const platformId = createPlatformIdentifier(platform.id);
if (platformId) {
return platformId;
}
}
}
}
return undefined;
}
private getInstallCandidate(
packages: BoardsPackage[],
selectedBoard: Board
): BoardsPackage | undefined {
// filter packagesForBoard selecting matches from the cli (installed packages)
// and matches based on the board name
// NOTE: this ensures the Deprecated & new packages are all in the array
// so that we can check if any of the valid packages is already installed
const packagesForBoard = packages.filter(
(pkg) =>
BoardsPackage.contains(selectedBoard, pkg) ||
pkg.boards.some((board) => board.name === selectedBoard.name)
);
// check if one of the packages for the board is already installed. if so, no hint
if (packagesForBoard.some(({ installedVersion }) => !!installedVersion)) {
private async ensureCoreExists(
selectedBoard: BoardIdentifier | undefined
): Promise<void> {
if (!selectedBoard) {
return;
}
const candidate = await this.findPlatformToInstall(selectedBoard);
if (!candidate) {
return;
}
const platformIdToInstall = candidate.id;
const selectedBoardName = selectedBoard.name;
if (
this.installNotificationInfos.some(
({ boardName, platformId }) =>
platformIdToInstall === platformId && selectedBoardName === boardName
)
) {
// Already has a notification for the board with the same platform. Nothing to do.
return;
}
this.clearAllNotificationForPlatform(platformIdToInstall);
// filter the installable (not installed) packages,
// CLI returns the packages already sorted with the deprecated ones at the end of the list
// in order to ensure the new ones are preferred
const candidates = packagesForBoard.filter(
({ installable, installedVersion }) => installable && !installedVersion
);
return candidates[0];
}
private showAutoInstallPrompt(
candidate: BoardsPackage,
selectedBoard: Board,
selectedPort?: Port
): void {
const candidateName = candidate.name;
const version = candidate.availableVersions[0]
? `[v ${candidate.availableVersions[0]}]`
: '';
const info = this.generatePromptInfoText(
candidateName,
const yes = nls.localize('vscode/extensionsUtils/yes', 'Yes');
const message = nls.localize(
'arduino/board/installNow',
'The "{0} {1}" core has to be installed for the currently selected "{2}" board. Do you want to install it now?',
candidate.name,
version,
selectedBoard.name
);
const actions = this.createPromptActions(candidate);
const onRefuse = () => {
this.setLastRefusedPromptInfo(candidate.id, selectedPort);
};
const handleAction = this.createOnAnswerHandler(actions, onRefuse);
const onAnswer = (answer: string) => {
this.removeNotificationByBoard(selectedBoard);
handleAction(answer);
};
this.messageService
.info(info, ...actions.map((action) => action.key))
.then(onAnswer);
}
private generatePromptInfoText(
candidateName: string,
version: string,
boardName: string
): string {
return nls.localize(
'arduino/board/installNow',
'The "{0} {1}" core has to be installed for the currently selected "{2}" board. Do you want to install it now?',
candidateName,
version,
boardName
const notificationId = this.notificationId(message, InstallManually, yes);
this.installNotificationInfos.push({
boardName: selectedBoardName,
platformId: platformIdToInstall,
notificationId,
});
const answer = await this.messageService.info(
message,
InstallManually,
yes
);
}
private createPromptActions(
candidate: BoardsPackage
): AutoInstallPromptActions {
const yes = nls.localize('vscode/extensionsUtils/yes', 'Yes');
const manualInstall = nls.localize(
'arduino/board/installManually',
'Install Manually'
);
const actions: AutoInstallPromptActions = [
{
key: manualInstall,
handler: () => {
this.boardsManagerFrontendContribution
.openView({ reveal: true })
.then((widget) =>
widget.refresh(candidate.name.toLocaleLowerCase())
);
},
},
{
isAcceptance: true,
key: yes,
handler: () => {
return Installable.installWithProgress({
installable: this.boardsService,
item: candidate,
messageService: this.messageService,
responseService: this.responseService,
version: candidate.availableVersions[0],
});
},
},
];
return actions;
}
private createOnAnswerHandler(
actions: AutoInstallPromptActions,
onRefuse?: () => void
): (answer: string) => void {
return (answer) => {
const actionToHandle = actions.find((action) => action.key === answer);
actionToHandle?.handler();
if (!actionToHandle?.isAcceptance && onRefuse) {
onRefuse();
if (answer) {
const index = this.installNotificationInfos.findIndex(
({ boardName, platformId }) =>
platformIdToInstall === platformId && selectedBoardName === boardName
);
if (index !== -1) {
this.installNotificationInfos.splice(index, 1);
}
};
if (answer === yes) {
await Installable.installWithProgress({
installable: this.boardsService,
item: candidate,
messageService: this.messageService,
responseService: this.responseService,
version: candidate.availableVersions[0],
});
return;
}
if (answer === InstallManually) {
this.boardsManagerWidgetContribution
.openView({ reveal: true })
.then((widget) =>
widget.refresh({
query: candidate.name.toLocaleLowerCase(),
type: 'All',
})
);
}
}
}
private clearAllNotificationForPlatform(predicatePlatformId: string): void {
// Discard all install notifications for the same platform.
const notificationsLength = this.installNotificationInfos.length;
for (let i = notificationsLength - 1; i >= 0; i--) {
const { notificationId, platformId } = this.installNotificationInfos[i];
if (platformId === predicatePlatformId) {
this.installNotificationInfos.splice(i, 1);
this.notificationManager.clear(notificationId);
}
}
}
private notificationId(message: string, ...actions: string[]): string {
return this.notificationManager['getMessageId']({
text: message,
actions,
type: MessageType.Info,
});
}
}

View File

@@ -0,0 +1,328 @@
import { DisposableCollection } from '@theia/core/lib/common/disposable';
import { Event } from '@theia/core/lib/common/event';
import { FrontendApplicationState } from '@theia/core/lib/common/frontend-application-state';
import { nls } from '@theia/core/lib/common/nls';
import React from '@theia/core/shared/react';
import { EditBoardsConfigActionParams } from '../../common/protocol/board-list';
import {
Board,
BoardIdentifier,
BoardWithPackage,
DetectedPort,
findMatchingPortIndex,
Port,
PortIdentifier,
} from '../../common/protocol/boards-service';
import type { Defined } from '../../common/types';
import { NotificationCenter } from '../notification-center';
import { BoardsConfigDialogState } from './boards-config-dialog';
namespace BoardsConfigComponent {
export interface Props {
/**
* This is not the real config, it's only living in the dialog. Users can change it without update and can cancel any modifications.
*/
readonly boardsConfig: BoardsConfigDialogState;
readonly searchSet: BoardIdentifier[] | undefined;
readonly notificationCenter: NotificationCenter;
readonly appState: FrontendApplicationState;
readonly onFocusNodeSet: (element: HTMLElement | undefined) => void;
readonly onFilteredTextDidChangeEvent: Event<
Defined<EditBoardsConfigActionParams['query']>
>;
readonly onAppStateDidChange: Event<FrontendApplicationState>;
readonly onBoardSelected: (board: BoardIdentifier) => void;
readonly onPortSelected: (port: PortIdentifier) => void;
readonly searchBoards: (query?: {
query?: string;
}) => Promise<BoardWithPackage[]>;
readonly ports: (
predicate?: (port: DetectedPort) => boolean
) => readonly DetectedPort[];
}
export interface State {
searchResults: Array<BoardWithPackage>;
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;
}> {
override 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>
);
}
private readonly onClick = () => {
this.props.onClick(this.props.item);
};
}
export class BoardsConfigComponent extends React.Component<
BoardsConfigComponent.Props,
BoardsConfigComponent.State
> {
private readonly toDispose: DisposableCollection;
constructor(props: BoardsConfigComponent.Props) {
super(props);
this.state = {
searchResults: [],
showAllPorts: false,
query: '',
};
this.toDispose = new DisposableCollection();
}
override componentDidMount(): void {
this.toDispose.pushAll([
this.props.onAppStateDidChange(async (state) => {
if (state === 'ready') {
const searchResults = await this.queryBoards({});
this.setState({ searchResults });
}
}),
this.props.notificationCenter.onPlatformDidInstall(() =>
this.updateBoards(this.state.query)
),
this.props.notificationCenter.onPlatformDidUninstall(() =>
this.updateBoards(this.state.query)
),
this.props.notificationCenter.onIndexUpdateDidComplete(() =>
this.updateBoards(this.state.query)
),
this.props.notificationCenter.onDaemonDidStart(() =>
this.updateBoards(this.state.query)
),
this.props.notificationCenter.onDaemonDidStop(() =>
this.setState({ searchResults: [] })
),
this.props.onFilteredTextDidChangeEvent((query) => {
if (typeof query === 'string') {
this.setState({ query }, () => this.updateBoards(this.state.query));
}
}),
]);
}
override componentWillUnmount(): void {
this.toDispose.dispose();
}
private readonly 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 })
);
};
private readonly queryBoards = async (
options: { query?: string } = {}
): Promise<Array<BoardWithPackage>> => {
const result = await this.props.searchBoards(options);
const { searchSet } = this.props;
if (searchSet) {
return result.filter((board) =>
searchSet.some(
(restriction) =>
restriction.fqbn === board.fqbn || restriction.name === board.fqbn
)
);
}
return result;
};
private readonly toggleFilterPorts = () => {
this.setState({ showAllPorts: !this.state.showAllPorts });
};
private readonly selectPort = (selectedPort: PortIdentifier) => {
this.props.onPortSelected(selectedPort);
};
private readonly selectBoard = (selectedBoard: BoardWithPackage) => {
this.props.onBoardSelected(selectedBoard);
};
private readonly focusNodeSet = (element: HTMLElement | null) => {
this.props.onFocusNodeSet(element || undefined);
};
override render(): React.ReactNode {
return (
<>
{this.renderContainer(
nls.localize('arduino/board/boards', 'boards'),
this.renderBoards.bind(this)
)}
{this.renderContainer(
nls.localize('arduino/board/ports', 'ports'),
this.renderPorts.bind(this),
this.renderPortsFooter.bind(this)
)}
</>
);
}
private 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>
);
}
private renderBoards(): React.ReactNode {
const { boardsConfig } = this.props;
const { 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(
boardsConfig.selectedBoard,
searchResults
)) {
const key = toKey(board);
if (!distinctBoards.has(key)) {
distinctBoards.set(key, board);
}
}
const boardsList = Array.from(distinctBoards.values()).map((board) => (
<Item<BoardWithPackage>
key={toKey(board)}
item={board}
label={board.name}
details={board.details}
selected={board.selected}
onClick={this.selectBoard}
missing={board.missing}
/>
));
return (
<React.Fragment>
<div className="search">
<input
type="search"
value={query}
className="theia-input"
placeholder={nls.localize(
'arduino/board/searchBoard',
'Search board'
)}
onChange={this.updateBoards}
ref={this.focusNodeSet}
/>
<i className="fa fa-search"></i>
</div>
{boardsList.length > 0 ? (
<div className="boards list">{boardsList}</div>
) : (
<div className="no-result">
{nls.localize(
'arduino/board/noBoardsFound',
'No boards found for "{0}"',
query
)}
</div>
)}
</React.Fragment>
);
}
private renderPorts(): React.ReactNode {
const predicate = this.state.showAllPorts ? undefined : Port.isVisiblePort;
const detectedPorts = this.props.ports(predicate);
const matchingIndex = findMatchingPortIndex(
this.props.boardsConfig.selectedPort,
detectedPorts
);
return !detectedPorts.length ? (
<div className="no-result">
{nls.localize('arduino/board/noPortsDiscovered', 'No ports discovered')}
</div>
) : (
<div className="ports list">
{detectedPorts.map((detectedPort, index) => (
<Item<Port>
key={`${Port.keyOf(detectedPort.port)}`}
item={detectedPort.port}
label={Port.toString(detectedPort.port)}
selected={index === matchingIndex}
onClick={this.selectPort}
/>
))}
</div>
);
}
private renderPortsFooter(): React.ReactNode {
return (
<div className="noselect">
<label
title={nls.localize(
'arduino/board/showAllAvailablePorts',
'Shows all available ports when enabled'
)}
>
<input
type="checkbox"
defaultChecked={this.state.showAllPorts}
onChange={this.toggleFilterPorts}
/>
<span>
{nls.localize('arduino/board/showAllPorts', 'Show all ports')}
</span>
</label>
</div>
);
}
}

View File

@@ -1,71 +0,0 @@
import * as React from '@theia/core/shared/react';
import { injectable, inject } from '@theia/core/shared/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}
onAppStateDidChange={this.notificationCenter.onAppStateDidChange}
/>
</div>
);
}
protected override onActivateRequest(msg: Message): void {
super.onActivateRequest(msg);
if (this.focusNode instanceof HTMLInputElement) {
this.focusNode.select();
}
(this.focusNode || this.node).focus();
}
}

View File

@@ -1,145 +0,0 @@
import { injectable, inject, postConstruct } from '@theia/core/shared/inversify';
import { Message } from '@theia/core/shared/@phosphor/messaging';
import { DialogProps, Widget, DialogError } from '@theia/core/lib/browser';
import { AbstractDialog } from '../theia/dialogs/dialogs';
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';
import { nls } from '@theia/core/lib/common';
@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 override readonly props: BoardsConfigDialogProps
) {
super(props);
this.contentNode.classList.add('select-board-dialog');
this.contentNode.appendChild(this.createDescription());
this.appendCloseButton(
nls.localize('vscode/issueMainService/cancel', 'Cancel')
);
this.appendAcceptButton(nls.localize('vscode/issueMainService/ok', '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.
*/
override 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 = nls.localize(
'arduino/board/configDialogTitle',
'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 [
nls.localize(
'arduino/board/configDialog1',
'Select both a Board and a Port if you want to upload a sketch.'
),
nls.localize(
'arduino/board/configDialog2',
'If you only select a Board you will be able to compile, but not to upload your sketch.'
),
]) {
const p = document.createElement('div');
p.textContent = paragraph;
text.appendChild(p);
}
return head;
}
protected override 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 override onUpdateRequest(msg: Message): void {
super.onUpdateRequest(msg);
this.widget.update();
}
protected override onActivateRequest(msg: Message): void {
super.onActivateRequest(msg);
this.widget.activate();
}
protected override handleEnter(event: KeyboardEvent): boolean | void {
if (event.target instanceof HTMLTextAreaElement) {
return false;
}
}
protected override isValid(value: BoardsConfig.Config): DialogError {
if (!value.selectedBoard) {
if (value.selectedPort) {
return nls.localize(
'arduino/board/pleasePickBoard',
'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,202 @@
import { DialogError, DialogProps } from '@theia/core/lib/browser/dialogs';
import { FrontendApplicationStateService } from '@theia/core/lib/browser/frontend-application-state';
import { Emitter } from '@theia/core/lib/common/event';
import { nls } from '@theia/core/lib/common/nls';
import { deepClone } from '@theia/core/lib/common/objects';
import type { Message } from '@theia/core/shared/@phosphor/messaging';
import {
inject,
injectable,
postConstruct,
} from '@theia/core/shared/inversify';
import React from '@theia/core/shared/react';
import type { ReactNode } from '@theia/core/shared/react/index';
import { EditBoardsConfigActionParams } from '../../common/protocol/board-list';
import {
BoardIdentifier,
BoardsConfig,
BoardWithPackage,
DetectedPort,
emptyBoardsConfig,
PortIdentifier,
} from '../../common/protocol/boards-service';
import type { Defined } from '../../common/types';
import { NotificationCenter } from '../notification-center';
import { ReactDialog } from '../theia/dialogs/dialogs';
import { BoardsConfigComponent } from './boards-config-component';
import { BoardsServiceProvider } from './boards-service-provider';
@injectable()
export class BoardsConfigDialogProps extends DialogProps {}
export type BoardsConfigDialogState = Omit<BoardsConfig, 'selectedBoard'> & {
selectedBoard: BoardsConfig['selectedBoard'] | BoardWithPackage;
};
@injectable()
export class BoardsConfigDialog extends ReactDialog<BoardsConfigDialogState> {
@inject(BoardsServiceProvider)
private readonly boardsServiceProvider: BoardsServiceProvider;
@inject(NotificationCenter)
private readonly notificationCenter: NotificationCenter;
@inject(FrontendApplicationStateService)
private readonly appStateService: FrontendApplicationStateService;
private readonly onFilterTextDidChangeEmitter: Emitter<
Defined<EditBoardsConfigActionParams['query']>
>;
private readonly onBoardSelected = (board: BoardWithPackage): void => {
this._boardsConfig.selectedBoard = board;
this.update();
};
private readonly onPortSelected = (port: PortIdentifier): void => {
this._boardsConfig.selectedPort = port;
this.update();
};
private readonly setFocusNode = (element: HTMLElement | undefined): void => {
this.focusNode = element;
};
private readonly searchBoards = (options: {
query?: string;
}): Promise<BoardWithPackage[]> => {
return this.boardsServiceProvider.searchBoards(options);
};
private readonly ports = (
predicate?: (port: DetectedPort) => boolean
): readonly DetectedPort[] => {
return this.boardsServiceProvider.boardList.ports(predicate);
};
private _boardsConfig: BoardsConfigDialogState;
/**
* When the dialog's boards result set is limited to a subset of boards when searching, this field is set.
*/
private _searchSet: BoardIdentifier[] | undefined;
private focusNode: HTMLElement | undefined;
constructor(
@inject(BoardsConfigDialogProps)
protected override readonly props: BoardsConfigDialogProps
) {
super({ ...props, maxWidth: 500 });
this.node.id = 'select-board-dialog-container';
this.contentNode.classList.add('select-board-dialog');
this.appendCloseButton(
nls.localize('vscode/issueMainService/cancel', 'Cancel')
);
this.appendAcceptButton(nls.localize('vscode/issueMainService/ok', 'OK'));
this._boardsConfig = emptyBoardsConfig();
this.onFilterTextDidChangeEmitter = new Emitter();
}
@postConstruct()
protected init(): void {
this.boardsServiceProvider.onBoardListDidChange(() => {
this._boardsConfig = deepClone(this.boardsServiceProvider.boardsConfig);
this.update();
});
this._boardsConfig = deepClone(this.boardsServiceProvider.boardsConfig);
}
override async open(
params?: EditBoardsConfigActionParams
): Promise<BoardsConfig | undefined> {
this._searchSet = undefined;
this._boardsConfig.selectedBoard =
this.boardsServiceProvider.boardsConfig.selectedBoard;
this._boardsConfig.selectedPort =
this.boardsServiceProvider.boardsConfig.selectedPort;
if (params) {
if (typeof params.query === 'string') {
this.onFilterTextDidChangeEmitter.fire(params.query);
}
if (params.portToSelect) {
this._boardsConfig.selectedPort = params.portToSelect;
}
if (params.boardToSelect) {
this._boardsConfig.selectedBoard = params.boardToSelect;
}
if (params.searchSet) {
this._searchSet = params.searchSet.slice();
}
}
return super.open();
}
protected override onAfterAttach(msg: Message): void {
super.onAfterAttach(msg);
this.update();
}
protected override render(): ReactNode {
return (
<>
<div className="head">
<div className="text">
<div>
{nls.localize(
'arduino/board/configDialog1',
'Select both a Board and a Port if you want to upload a sketch.'
)}
</div>
<div>
{nls.localize(
'arduino/board/configDialog2',
'If you only select a Board you will be able to compile, but not to upload your sketch.'
)}
</div>
</div>
</div>
<div id="select-board-dialog" className="p-Widget ps">
<div className="selectBoardContainer">
<BoardsConfigComponent
boardsConfig={this._boardsConfig}
searchSet={this._searchSet}
onBoardSelected={this.onBoardSelected}
onPortSelected={this.onPortSelected}
notificationCenter={this.notificationCenter}
onFocusNodeSet={this.setFocusNode}
onFilteredTextDidChangeEvent={
this.onFilterTextDidChangeEmitter.event
}
appState={this.appStateService.state}
onAppStateDidChange={this.notificationCenter.onAppStateDidChange}
searchBoards={this.searchBoards}
ports={this.ports}
/>
</div>
</div>
</>
);
}
protected override onActivateRequest(msg: Message): void {
super.onActivateRequest(msg);
if (this.focusNode instanceof HTMLInputElement) {
this.focusNode.select();
}
(this.focusNode || this.node).focus();
}
protected override handleEnter(event: KeyboardEvent): boolean | void {
if (event.target instanceof HTMLTextAreaElement) {
return false;
}
}
protected override isValid(value: BoardsConfig): DialogError {
if (!value.selectedBoard) {
if (value.selectedPort) {
return nls.localize(
'arduino/board/pleasePickBoard',
'Please pick a board connected to the port you have selected.'
);
}
return false;
}
return '';
}
get value(): BoardsConfigDialogState {
return this._boardsConfig;
}
}

View File

@@ -1,470 +0,0 @@
import * as React from '@theia/core/shared/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 {
AvailableBoard,
BoardsServiceProvider,
} from './boards-service-provider';
import { naturalCompare } from '../../common/utils';
import { nls } from '@theia/core/lib/common';
import { FrontendApplicationState } from '@theia/core/lib/common/frontend-application-state';
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>;
readonly onAppStateDidChange: Event<FrontendApplicationState>;
}
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;
}> {
override 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,
};
}
override componentDidMount(): void {
this.toDispose.pushAll([
this.props.onAppStateDidChange((state) => {
if (state === 'ready') {
this.updateBoards();
this.updatePorts(
this.props.boardsServiceProvider.availableBoards
.map(({ port }) => port)
.filter(notEmpty)
);
}
}),
this.props.notificationCenter.onAttachedBoardsDidChange((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.onPlatformDidInstall(() =>
this.updateBoards(this.state.query)
),
this.props.notificationCenter.onPlatformDidUninstall(() =>
this.updateBoards(this.state.query)
),
this.props.notificationCenter.onIndexDidUpdate(() =>
this.updateBoards(this.state.query)
),
this.props.notificationCenter.onDaemonDidStart(() =>
this.updateBoards(this.state.query)
),
this.props.notificationCenter.onDaemonDidStop(() =>
this.setState({ searchResults: [] })
),
this.props.onFilteredTextDidChangeEvent((query) =>
this.setState({ query }, () => this.updateBoards(this.state.query))
),
]);
}
override componentWillUnmount(): void {
this.toDispose.dispose();
}
protected fireConfigChanged(): void {
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.sameAs(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 get availableBoards(): AvailableBoard[] {
return this.props.boardsServiceProvider.availableBoards;
}
protected queryPorts = async (
availablePorts: MaybePromise<Port[]> = this.availablePorts
) => {
// Available ports must be sorted in this order:
// 1. Serial with recognized boards
// 2. Serial with guessed boards
// 3. Serial with incomplete boards
// 4. Network with recognized boards
// 5. Other protocols with recognized boards
const ports = (await availablePorts).sort((left: Port, right: Port) => {
if (left.protocol === 'serial' && right.protocol !== 'serial') {
return -1;
} else if (left.protocol !== 'serial' && right.protocol === 'serial') {
return 1;
} else if (left.protocol === 'network' && right.protocol !== 'network') {
return -1;
} else if (left.protocol !== 'network' && right.protocol === 'network') {
return 1;
} else if (left.protocol === right.protocol) {
// We show ports, including those that have guessed
// or unrecognized boards, so we must sort those too.
const leftBoard = this.availableBoards.find(
(board) => board.port === left
);
const rightBoard = this.availableBoards.find(
(board) => board.port === right
);
if (leftBoard && !rightBoard) {
return -1;
} else if (!leftBoard && rightBoard) {
return 1;
} else if (leftBoard?.state! < rightBoard?.state!) {
return -1;
} else if (leftBoard?.state! > rightBoard?.state!) {
return 1;
}
}
return naturalCompare(left.address, right.address);
});
return { knownPorts: ports };
};
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);
};
override 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={toKey(board)}
item={board}
label={board.name}
details={board.details}
selected={board.selected}
onClick={this.selectBoard}
missing={board.missing}
/>
))}
</div>
</React.Fragment>
);
}
protected renderPorts(): React.ReactNode {
let ports = [] as Port[];
if (this.state.showAllPorts) {
ports = this.state.knownPorts;
} else {
ports = this.state.knownPorts.filter((port) => {
if (port.protocol === 'serial') {
return true;
}
// All other ports with different protocol are
// only shown if there is a recognized board
// connected
for (const board of this.availableBoards) {
if (board.port?.address === port.address) {
return true;
}
}
});
}
return !ports.length ? (
<div className="loading noselect">No ports discovered</div>
) : (
<div className="ports list">
{ports.map((port) => (
<Item<Port>
key={`${port.id}`}
item={port}
label={Port.toString(port)}
selected={Port.sameAs(this.state.selectedPort, port)}
onClick={this.selectPort}
/>
))}
</div>
);
}
protected renderPortsFooter(): React.ReactNode {
return (
<div className="noselect">
<label
title={nls.localize(
'arduino/board/showAllAvailablePorts',
'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.address}` : ''}`;
}
export function setConfig(
config: Config | undefined,
urlToAttachTo: URL
): URL {
const copy = new URL(urlToAttachTo.toString());
if (!config) {
copy.searchParams.delete('boards-config');
return copy;
}
const selectedBoard = config.selectedBoard
? {
name: config.selectedBoard.name,
fqbn: config.selectedBoard.fqbn,
}
: undefined;
const selectedPort = config.selectedPort
? {
protocol: config.selectedPort.protocol,
address: config.selectedPort.address,
}
: undefined;
const jsonConfig = JSON.stringify({ selectedBoard, selectedPort });
copy.searchParams.set('boards-config', encodeURIComponent(jsonConfig));
return copy;
}
export function getConfig(url: URL): Config | undefined {
const encoded = url.searchParams.get('boards-config');
if (!encoded) {
return undefined;
}
try {
const raw = decodeURIComponent(encoded);
const candidate = JSON.parse(raw);
if (typeof candidate === 'object') {
return candidate;
}
console.warn(
`Expected candidate to be an object. It was ${typeof candidate}. URL was: ${url}`
);
return undefined;
} catch (e) {
console.log(`Could not get board config from URL: ${url}.`, e);
return undefined;
}
}
}
}

View File

@@ -1,71 +1,72 @@
import { injectable, inject, named } from '@theia/core/shared/inversify';
import { FrontendApplicationContribution } from '@theia/core/lib/browser/frontend-application';
import { LocalStorageService } from '@theia/core/lib/browser/storage-service';
import { DisposableCollection } from '@theia/core/lib/common/disposable';
import { Emitter, Event } from '@theia/core/lib/common/event';
import { ILogger } from '@theia/core/lib/common/logger';
import { deepClone } from '@theia/core/lib/common/objects';
import { Event, Emitter } from '@theia/core/lib/common/event';
import {
FrontendApplicationContribution,
LocalStorageService,
} from '@theia/core/lib/browser';
import { notEmpty } from '../../common/utils';
import { inject, injectable, named } from '@theia/core/shared/inversify';
import {
BoardDetails,
BoardsService,
ConfigOption,
BoardDetails,
Programmer,
} from '../../common/protocol';
import { notEmpty } from '../../common/utils';
import { NotificationCenter } from '../notification-center';
@injectable()
export class BoardsDataStore implements FrontendApplicationContribution {
@inject(ILogger)
@named('store')
protected readonly logger: ILogger;
private readonly logger: ILogger;
@inject(BoardsService)
protected readonly boardsService: BoardsService;
private readonly boardsService: BoardsService;
@inject(NotificationCenter)
protected readonly notificationCenter: NotificationCenter;
private readonly notificationCenter: NotificationCenter;
@inject(LocalStorageService)
protected readonly storageService: LocalStorageService;
private readonly storageService: LocalStorageService;
protected readonly onChangedEmitter = new Emitter<void>();
private readonly onChangedEmitter = new Emitter<string[]>();
private readonly toDispose = new DisposableCollection(this.onChangedEmitter);
onStart(): void {
this.notificationCenter.onPlatformDidInstall(async ({ item }) => {
let shouldFireChanged = false;
for (const fqbn of item.boards
.map(({ fqbn }) => fqbn)
.filter(notEmpty)
.filter((fqbn) => !!fqbn)) {
const key = this.getStorageKey(fqbn);
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;
this.toDispose.push(
this.notificationCenter.onPlatformDidInstall(async ({ item }) => {
const dataDidChangePerFqbn: string[] = [];
for (const fqbn of item.boards
.map(({ fqbn }) => fqbn)
.filter(notEmpty)
.filter((fqbn) => !!fqbn)) {
const key = this.getStorageKey(fqbn);
let data = await this.storageService.getData<ConfigOption[]>(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);
dataDidChangePerFqbn.push(fqbn);
}
}
}
}
}
if (shouldFireChanged) {
this.fireChanged();
}
});
if (dataDidChangePerFqbn.length) {
this.fireChanged(...dataDidChangePerFqbn);
}
})
);
}
get onChanged(): Event<void> {
onStop(): void {
this.toDispose.dispose();
}
get onChanged(): Event<string[]> {
return this.onChangedEmitter.event;
}
async appendConfigToFqbn(
fqbn: string | undefined,
fqbn: string | undefined
): Promise<string | undefined> {
if (!fqbn) {
return undefined;
@@ -100,12 +101,13 @@ export class BoardsDataStore implements FrontendApplicationContribution {
return data;
}
async selectProgrammer(
{
fqbn,
selectedProgrammer,
}: { fqbn: string; selectedProgrammer: Programmer },
): Promise<boolean> {
async selectProgrammer({
fqbn,
selectedProgrammer,
}: {
fqbn: string;
selectedProgrammer: Programmer;
}): Promise<boolean> {
const data = deepClone(await this.getData(fqbn));
const { programmers } = data;
if (!programmers.find((p) => Programmer.equals(selectedProgrammer, p))) {
@@ -116,17 +118,19 @@ export class BoardsDataStore implements FrontendApplicationContribution {
fqbn,
data: { ...data, selectedProgrammer },
});
this.fireChanged();
this.fireChanged(fqbn);
return true;
}
async selectConfigOption(
{
fqbn,
option,
selectedValue,
}: { fqbn: string; option: string; selectedValue: string }
): Promise<boolean> {
async selectConfigOption({
fqbn,
option,
selectedValue,
}: {
fqbn: string;
option: string;
selectedValue: string;
}): Promise<boolean> {
const data = deepClone(await this.getData(fqbn));
const { configOptions } = data;
const configOption = configOptions.find((c) => c.option === option);
@@ -146,7 +150,7 @@ export class BoardsDataStore implements FrontendApplicationContribution {
return false;
}
await this.setData({ fqbn, data });
this.fireChanged();
this.fireChanged(fqbn);
return true;
}
@@ -190,8 +194,8 @@ export class BoardsDataStore implements FrontendApplicationContribution {
}
}
protected fireChanged(): void {
this.onChangedEmitter.fire();
protected fireChanged(...fqbn: string[]): void {
this.onChangedEmitter.fire(fqbn);
}
}

View File

@@ -4,22 +4,24 @@ import {
postConstruct,
} from '@theia/core/shared/inversify';
import {
BoardSearch,
BoardsPackage,
BoardsService,
} from '../../common/protocol/boards-service';
import { ListWidget } from '../widgets/component-list/list-widget';
import { ListItemRenderer } from '../widgets/component-list/list-item-renderer';
import { nls } from '@theia/core/lib/common';
import { BoardsFilterRenderer } from '../widgets/component-list/filter-renderer';
@injectable()
export class BoardsListWidget extends ListWidget<BoardsPackage> {
export class BoardsListWidget extends ListWidget<BoardsPackage, BoardSearch> {
static WIDGET_ID = 'boards-list-widget';
static WIDGET_LABEL = nls.localize('arduino/boardsManager', 'Boards Manager');
constructor(
@inject(BoardsService) protected service: BoardsService,
@inject(ListItemRenderer)
protected itemRenderer: ListItemRenderer<BoardsPackage>
@inject(BoardsService) service: BoardsService,
@inject(ListItemRenderer) itemRenderer: ListItemRenderer<BoardsPackage>,
@inject(BoardsFilterRenderer) filterRenderer: BoardsFilterRenderer
) {
super({
id: BoardsListWidget.WIDGET_ID,
@@ -28,8 +30,9 @@ export class BoardsListWidget extends ListWidget<BoardsPackage> {
searchable: service,
installable: service,
itemLabel: (item: BoardsPackage) => item.name,
itemDeprecated: (item: BoardsPackage) => item.deprecated,
itemRenderer,
filterRenderer,
defaultSearchOptions: { query: '', type: 'All' },
});
}

View File

@@ -1,16 +1,21 @@
import * as React from '@theia/core/shared/react';
import * as ReactDOM from '@theia/core/shared/react-dom';
import { TabBarToolbar } from '@theia/core/lib/browser/shell/tab-bar-toolbar/tab-bar-toolbar';
import { codicon } from '@theia/core/lib/browser/widgets/widget';
import { CommandRegistry } from '@theia/core/lib/common/command';
import { DisposableCollection } from '@theia/core/lib/common/disposable';
import { Port } from '../../common/protocol';
import { OpenBoardsConfig } from '../contributions/open-boards-config';
import {
BoardsServiceProvider,
AvailableBoard,
} from './boards-service-provider';
import { nls } from '@theia/core/lib/common';
Disposable,
DisposableCollection,
} from '@theia/core/lib/common/disposable';
import { nls } from '@theia/core/lib/common/nls';
import React from '@theia/core/shared/react';
import ReactDOM from '@theia/core/shared/react-dom';
import classNames from 'classnames';
import { BoardsConfig } from './boards-config';
import { boardIdentifierLabel, Port } from '../../common/protocol';
import { BoardListItemUI } from '../../common/protocol/board-list';
import { assertUnreachable } from '../../common/utils';
import type {
BoardListUI,
BoardsServiceProvider,
} from './boards-service-provider';
export interface BoardsDropDownListCoords {
readonly top: number;
@@ -22,18 +27,18 @@ export interface BoardsDropDownListCoords {
export namespace BoardsDropDown {
export interface Props {
readonly coords: BoardsDropDownListCoords | 'hidden';
readonly items: Array<AvailableBoard & { onClick: () => void; port: Port }>;
readonly boardList: BoardListUI;
readonly openBoardsConfig: () => void;
readonly hide: () => void;
}
}
export class BoardsDropDown extends React.Component<BoardsDropDown.Props> {
protected dropdownElement: HTMLElement;
export class BoardListDropDown extends React.Component<BoardsDropDown.Props> {
private dropdownElement: HTMLElement;
private listRef: React.RefObject<HTMLDivElement>;
constructor(props: BoardsDropDown.Props) {
super(props);
this.listRef = React.createRef();
let list = document.getElementById('boards-dropdown-container');
if (!list) {
@@ -51,11 +56,14 @@ export class BoardsDropDown extends React.Component<BoardsDropDown.Props> {
}
override render(): React.ReactNode {
return ReactDOM.createPortal(this.renderNode(), this.dropdownElement);
return ReactDOM.createPortal(
this.renderBoardListItems(),
this.dropdownElement
);
}
protected renderNode(): React.ReactNode {
const { coords, items } = this.props;
private renderBoardListItems(): React.ReactNode {
const { coords, boardList } = this.props;
if (coords === 'hidden') {
return '';
}
@@ -74,14 +82,12 @@ export class BoardsDropDown extends React.Component<BoardsDropDown.Props> {
tabIndex={0}
>
<div className="arduino-boards-dropdown-list--items-container">
{items
.map(({ name, port, selected, onClick }) => ({
boardLabel: name,
port,
selected,
onClick,
}))
.map(this.renderItem)}
{boardList.items.map((item, index) =>
this.renderBoardListItem({
item,
selected: index === boardList.selectedIndex,
})
)}
</div>
<div
key={footerLabel}
@@ -95,31 +101,43 @@ export class BoardsDropDown extends React.Component<BoardsDropDown.Props> {
);
}
protected renderItem({
boardLabel,
port,
private readonly onDefaultAction = (item: BoardListItemUI): unknown => {
const { boardList, hide } = this.props;
const { type, params } = item.defaultAction;
hide();
switch (type) {
case 'select-boards-config': {
return boardList.select(params);
}
case 'edit-boards-config': {
return boardList.edit(params);
}
default:
return assertUnreachable(type);
}
};
private renderBoardListItem({
item,
selected,
onClick,
}: {
boardLabel: string;
port: Port;
selected?: boolean;
onClick: () => void;
item: BoardListItemUI;
selected: boolean;
}): React.ReactNode {
const protocolIcon = iconNameFromProtocol(port.protocol);
const { boardLabel, portLabel, portProtocol, tooltip } = item.labels;
const port = item.port;
const onKeyUp = (e: React.KeyboardEvent) => {
if (e.key === 'Enter') {
onClick();
this.onDefaultAction(item);
}
};
return (
<div
key={`board-item--${boardLabel}-${port.address}`}
key={`board-item--${Port.keyOf(port)}`}
className={classNames('arduino-boards-dropdown-item', {
'arduino-boards-dropdown-item--selected': selected,
})}
onClick={onClick}
onClick={() => this.onDefaultAction(item)}
onKeyUp={onKeyUp}
tabIndex={0}
>
@@ -127,21 +145,81 @@ export class BoardsDropDown extends React.Component<BoardsDropDown.Props> {
className={classNames(
'arduino-boards-dropdown-item--protocol',
'fa',
protocolIcon
iconNameFromProtocol(portProtocol)
)}
/>
<div
className="arduino-boards-dropdown-item--label"
title={`${boardLabel}\n${port.address}`}
>
<div className="arduino-boards-dropdown-item--board-label noWrapInfo noselect">
{boardLabel}
<div className="arduino-boards-dropdown-item--label" title={tooltip}>
<div className="arduino-boards-dropdown-item--board-header">
<div className="arduino-boards-dropdown-item--board-label noWrapInfo noselect">
{boardLabel}
</div>
</div>
<div className="arduino-boards-dropdown-item--port-label noWrapInfo noselect">
{port.address}
{portLabel}
</div>
</div>
{selected ? <div className="fa fa-check" /> : ''}
{this.renderActions(item)}
</div>
);
}
private renderActions(item: BoardListItemUI): React.ReactNode {
const { boardList, hide } = this.props;
const { revert, edit } = item.otherActions;
if (!edit && !revert) {
return undefined;
}
const handleOnClick = (
event: React.MouseEvent<HTMLElement, MouseEvent>,
callback: () => void
) => {
event.preventDefault();
event.stopPropagation();
hide();
callback();
};
return (
<div className={TabBarToolbar.Styles.TAB_BAR_TOOLBAR}>
{edit && (
<div
className={`${TabBarToolbar.Styles.TAB_BAR_TOOLBAR_ITEM} enabled`}
>
{
<div
id="edit"
className={codicon('pencil', true)}
title={nls.localize(
'arduino/board/editBoardsConfig',
'Edit Board and Port...'
)}
onClick={(event) =>
handleOnClick(event, () => boardList.edit(edit.params))
}
/>
}
</div>
)}
{revert && (
<div
className={`${TabBarToolbar.Styles.TAB_BAR_TOOLBAR_ITEM} enabled`}
>
{
<div
id="revert"
className={codicon('discard', true)}
title={nls.localize(
'arduino/board/revertBoardsConfig',
"Use '{0}' discovered on '{1}'",
boardIdentifierLabel(revert.params.selectedBoard),
item.labels.portLabel
)}
onClick={(event) =>
handleOnClick(event, () => boardList.select(revert.params))
}
/>
}
</div>
)}
</div>
);
}
@@ -153,26 +231,27 @@ export class BoardsToolBarItem extends React.Component<
> {
static TOOLBAR_ID: 'boards-toolbar';
protected readonly toDispose: DisposableCollection =
new DisposableCollection();
private readonly toDispose: DisposableCollection;
constructor(props: BoardsToolBarItem.Props) {
super(props);
const { availableBoards } = props.boardsServiceProvider;
const { boardList } = props.boardsServiceProvider;
this.state = {
availableBoards,
boardList,
coords: 'hidden',
};
document.addEventListener('click', () => {
this.setState({ coords: 'hidden' });
});
const listener = () => this.setState({ coords: 'hidden' });
document.addEventListener('click', listener);
this.toDispose = new DisposableCollection(
Disposable.create(() => document.removeEventListener('click', listener))
);
}
override componentDidMount(): void {
this.props.boardsServiceProvider.onAvailableBoardsChanged(
(availableBoards) => this.setState({ availableBoards })
this.toDispose.push(
this.props.boardsServiceProvider.onBoardListDidChange((boardList) =>
this.setState({ boardList })
)
);
}
@@ -180,7 +259,7 @@ export class BoardsToolBarItem extends React.Component<
this.toDispose.dispose();
}
protected readonly show = (event: React.MouseEvent<HTMLElement>): void => {
private readonly show = (event: React.MouseEvent<HTMLElement>): void => {
const { currentTarget: element } = event;
if (element instanceof HTMLElement) {
if (this.state.coords === 'hidden') {
@@ -201,31 +280,26 @@ export class BoardsToolBarItem extends React.Component<
event.nativeEvent.stopImmediatePropagation();
};
private readonly hide = () => {
this.setState({ coords: 'hidden' });
};
override render(): React.ReactNode {
const { coords, availableBoards } = this.state;
const { selectedBoard, selectedPort } =
this.props.boardsServiceProvider.boardsConfig;
const boardLabel =
selectedBoard?.name ||
nls.localize('arduino/board/selectBoard', 'Select Board');
const selectedPortLabel = portLabel(selectedPort?.address);
const isConnected = Boolean(selectedBoard && selectedPort);
const protocolIcon = isConnected
? iconNameFromProtocol(selectedPort?.protocol || '')
const { coords, boardList } = this.state;
const { boardLabel, selected, portProtocol, tooltip } = boardList.labels;
const protocolIcon = portProtocol
? iconNameFromProtocol(portProtocol)
: null;
const protocolIconClassNames = classNames(
'arduino-boards-toolbar-item--protocol',
'fa',
protocolIcon
);
return (
<React.Fragment>
<div
className="arduino-boards-toolbar-item-container"
title={selectedPortLabel}
title={tooltip}
onClick={this.show}
>
{protocolIcon && <div className={protocolIconClassNames} />}
@@ -234,57 +308,22 @@ export class BoardsToolBarItem extends React.Component<
'arduino-boards-toolbar-item--label',
'noWrapInfo',
'noselect',
{ 'arduino-boards-toolbar-item--label-connected': isConnected }
{ 'arduino-boards-toolbar-item--label-connected': selected }
)}
>
{boardLabel}
</div>
<div className="fa fa-caret-down caret" />
</div>
<BoardsDropDown
<BoardListDropDown
coords={coords}
items={availableBoards
.filter(AvailableBoard.hasPort)
.map((board) => ({
...board,
onClick: () => {
if (!board.fqbn) {
const previousBoardConfig =
this.props.boardsServiceProvider.boardsConfig;
this.props.boardsServiceProvider.boardsConfig = {
selectedPort: board.port,
};
this.openDialog(previousBoardConfig);
} else {
this.props.boardsServiceProvider.boardsConfig = {
selectedBoard: board,
selectedPort: board.port,
};
}
this.setState({ coords: 'hidden' });
},
}))}
openBoardsConfig={this.openDialog}
></BoardsDropDown>
boardList={boardList}
openBoardsConfig={() => boardList.edit({ query: '' })}
hide={this.hide}
/>
</React.Fragment>
);
}
protected openDialog = async (
previousBoardConfig?: BoardsConfig.Config
): Promise<void> => {
const selectedBoardConfig =
await this.props.commands.executeCommand<BoardsConfig.Config>(
OpenBoardsConfig.Commands.OPEN_DIALOG.id
);
if (
previousBoardConfig &&
(!selectedBoardConfig?.selectedPort ||
!selectedBoardConfig?.selectedBoard)
) {
this.props.boardsServiceProvider.boardsConfig = previousBoardConfig;
}
};
}
export namespace BoardsToolBarItem {
export interface Props {
@@ -293,7 +332,7 @@ export namespace BoardsToolBarItem {
}
export interface State {
availableBoards: AvailableBoard[];
boardList: BoardListUI;
coords: BoardsDropDownListCoords | 'hidden';
}
}
@@ -304,19 +343,10 @@ function iconNameFromProtocol(protocol: string): string {
return 'fa-arduino-technology-usb';
case 'network':
return 'fa-arduino-technology-connection';
/*
Bluetooth ports are not listed yet from the CLI;
Not sure about the naming ('bluetooth'); make sure it's correct before uncommenting the following lines
*/
// case 'bluetooth':
// return 'fa-arduino-technology-bluetooth';
// it is fine to assign dedicated icons to the protocols used by the official boards,
// but other than that it is best to avoid implementing any special handling
// for specific protocols in the IDE codebase.
default:
return 'fa-arduino-technology-3dimensionscube';
}
}
function portLabel(portName?: string): string {
return portName
? nls.localize('arduino/board/portLabel', 'Port: {0}', portName)
: nls.localize('arduino/board/disconnected', 'Disconnected');
}

View File

@@ -1,10 +1,17 @@
import { injectable } from '@theia/core/shared/inversify';
import { BoardsListWidget } from './boards-list-widget';
import { BoardsPackage } from '../../common/protocol/boards-service';
import {
BoardSearch,
BoardsPackage,
} from '../../common/protocol/boards-service';
import { URI } from '../contributions/contribution';
import { ListWidgetFrontendContribution } from '../widgets/component-list/list-widget-frontend-contribution';
import { BoardsListWidget } from './boards-list-widget';
@injectable()
export class BoardsListWidgetFrontendContribution extends ListWidgetFrontendContribution<BoardsPackage> {
export class BoardsListWidgetFrontendContribution extends ListWidgetFrontendContribution<
BoardsPackage,
BoardSearch
> {
constructor() {
super({
widgetId: BoardsListWidget.WIDGET_ID,
@@ -18,7 +25,16 @@ export class BoardsListWidgetFrontendContribution extends ListWidgetFrontendCont
});
}
override async initializeLayout(): Promise<void> {
this.openView();
protected canParse(uri: URI): boolean {
try {
BoardSearch.UriParser.parse(uri);
return true;
} catch {
return false;
}
}
protected parse(uri: URI): BoardSearch | undefined {
return BoardSearch.UriParser.parse(uri);
}
}

View File

@@ -1,4 +1,4 @@
import * as React from '@theia/core/shared/react';
import React from '@theia/core/shared/react';
export type ProgressBarProps = {
percent?: number;

View File

@@ -0,0 +1,102 @@
import { FrontendApplicationContribution } from '@theia/core/lib/browser/frontend-application';
import { FrontendApplicationStateService } from '@theia/core/lib/browser/frontend-application-state';
import { DisposableCollection } from '@theia/core/lib/common/disposable';
import { Emitter, Event } from '@theia/core/lib/common/event';
import { MessageService } from '@theia/core/lib/common/message-service';
import { deepClone } from '@theia/core/lib/common/objects';
import URI from '@theia/core/lib/common/uri';
import {
inject,
injectable,
postConstruct,
} from '@theia/core/shared/inversify';
import { ConfigService, ConfigState } from '../../common/protocol';
import { NotificationCenter } from '../notification-center';
@injectable()
export class ConfigServiceClient implements FrontendApplicationContribution {
@inject(ConfigService)
private readonly delegate: ConfigService;
@inject(NotificationCenter)
private readonly notificationCenter: NotificationCenter;
@inject(FrontendApplicationStateService)
private readonly appStateService: FrontendApplicationStateService;
@inject(MessageService)
private readonly messageService: MessageService;
private readonly didChangeSketchDirUriEmitter = new Emitter<
URI | undefined
>();
private readonly didChangeDataDirUriEmitter = new Emitter<URI | undefined>();
private readonly toDispose = new DisposableCollection(
this.didChangeSketchDirUriEmitter,
this.didChangeDataDirUriEmitter
);
private config: ConfigState | undefined;
@postConstruct()
protected init(): void {
this.appStateService.reachedState('ready').then(async () => {
const config = await this.delegate.getConfiguration();
this.use(config);
});
}
onStart(): void {
this.notificationCenter.onConfigDidChange((config) => this.use(config));
}
onStop(): void {
this.toDispose.dispose();
}
get onDidChangeSketchDirUri(): Event<URI | undefined> {
return this.didChangeSketchDirUriEmitter.event;
}
get onDidChangeDataDirUri(): Event<URI | undefined> {
return this.didChangeDataDirUriEmitter.event;
}
/**
* CLI config related error messages if any.
*/
tryGetMessages(): string[] | undefined {
return this.config?.messages;
}
/**
* `directories.user`
*/
tryGetSketchDirUri(): URI | undefined {
return this.config?.config?.sketchDirUri
? new URI(this.config?.config?.sketchDirUri)
: undefined;
}
/**
* `directories.data`
*/
tryGetDataDirUri(): URI | undefined {
return this.config?.config?.dataDirUri
? new URI(this.config?.config?.dataDirUri)
: undefined;
}
private use(config: ConfigState): void {
const oldConfig = deepClone(this.config);
this.config = config;
if (oldConfig?.config?.sketchDirUri !== this.config?.config?.sketchDirUri) {
this.didChangeSketchDirUriEmitter.fire(this.tryGetSketchDirUri());
}
if (oldConfig?.config?.dataDirUri !== this.config?.config?.dataDirUri) {
this.didChangeDataDirUriEmitter.fire(this.tryGetDataDirUri());
}
if (this.config.messages?.length) {
const message = this.config.messages.join(' ');
// toast the error later otherwise it might not show up in IDE2
setTimeout(() => this.messageService.error(message), 1_000);
}
}
}

View File

@@ -1,26 +1,24 @@
import { inject, injectable } from '@theia/core/shared/inversify';
import * as moment from 'moment';
import * as remote from '@theia/core/electron-shared/@electron/remote';
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 { nls } from '@theia/core/lib/common/nls';
import { isOSX, isWindows } from '@theia/core/lib/common/os';
import { inject, injectable } from '@theia/core/shared/inversify';
import moment from 'moment';
import { AppService } from '../app-service';
import { ArduinoMenus } from '../menu/arduino-menus';
import { ConfigService } from '../../common/protocol';
import { nls } from '@theia/core/lib/common';
import {
Command,
CommandRegistry,
Contribution,
MenuModelRegistry,
} from './contribution';
@injectable()
export class About extends Contribution {
@inject(ClipboardService)
protected readonly clipboardService: ClipboardService;
@inject(ConfigService)
protected readonly configService: ConfigService;
private readonly clipboardService: ClipboardService;
@inject(AppService)
private readonly appService: AppService;
override registerCommands(registry: CommandRegistry): void {
registry.registerCommand(About.Commands.ABOUT_APP, {
@@ -40,23 +38,18 @@ export class About extends Contribution {
});
}
async showAbout(): Promise<void> {
const {
version,
commit,
status: cliStatus,
} = await this.configService.getVersion();
const buildDate = this.buildDate;
private async showAbout(): Promise<void> {
const appInfo = await this.appService.info();
const { appVersion, cliVersion, buildDate } = appInfo;
const detail = (showAll: boolean) =>
nls.localize(
'arduino/about/detail',
'Version: {0}\nDate: {1}{2}\nCLI Version: {3}{4} [{5}]\n\n{6}',
remote.app.getVersion(),
'Version: {0}\nDate: {1}{2}\nCLI Version: {3}\n\n{4}',
appVersion,
buildDate ? buildDate : nls.localize('', 'dev build'),
buildDate && showAll ? ` (${this.ago(buildDate)})` : '',
version,
cliStatus ? ` ${cliStatus}` : '',
commit,
cliVersion,
nls.localize(
'arduino/about/copyright',
'Copyright © {0} Arduino SA',
@@ -66,34 +59,27 @@ export class About extends Contribution {
const ok = nls.localize('vscode/issueMainService/ok', 'OK');
const copy = nls.localize('vscode/textInputActions/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),
}
);
const { response } = await this.dialogService.showMessageBox({
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 {
private get applicationName(): string {
return FrontendApplicationConfigProvider.get().applicationName;
}
protected get buildDate(): string | undefined {
return FrontendApplicationConfigProvider.get().buildDate;
}
protected ago(isoTime: string): string {
private ago(isoTime: string): string {
const now = moment(Date.now());
const other = moment(isoTime);
let result = now.diff(other, 'minute');

View File

@@ -0,0 +1,155 @@
import { FrontendApplication } from '@theia/core/lib/browser/frontend-application';
import { SidebarMenu } from '@theia/core/lib/browser/shell/sidebar-menu-widget';
import { WindowService } from '@theia/core/lib/browser/window/window-service';
import { DisposableCollection } from '@theia/core/lib/common/disposable';
import { MenuPath } from '@theia/core/lib/common/menu';
import { nls } from '@theia/core/lib/common/nls';
import { inject, injectable } from '@theia/core/shared/inversify';
import { CloudUserCommands, LEARN_MORE_URL } from '../auth/cloud-user-commands';
import { CreateFeatures } from '../create/create-features';
import { ArduinoMenus } from '../menu/arduino-menus';
import { ApplicationConnectionStatusContribution } from '../theia/core/connection-status-service';
import {
Command,
CommandRegistry,
Contribution,
MenuModelRegistry,
} from './contribution';
export const accountMenu: SidebarMenu = {
id: 'arduino-accounts-menu',
iconClass: 'codicon codicon-account',
title: nls.localize('arduino/account/menuTitle', 'Arduino Cloud'),
menuPath: ArduinoMenus.ARDUINO_ACCOUNT__CONTEXT,
order: 0,
};
@injectable()
export class Account extends Contribution {
@inject(WindowService)
private readonly windowService: WindowService;
@inject(CreateFeatures)
private readonly createFeatures: CreateFeatures;
@inject(ApplicationConnectionStatusContribution)
private readonly connectionStatus: ApplicationConnectionStatusContribution;
private readonly toDispose = new DisposableCollection();
private app: FrontendApplication;
override onStart(app: FrontendApplication): void {
this.app = app;
this.updateSidebarCommand();
this.toDispose.push(
this.createFeatures.onDidChangeEnabled((enabled) =>
this.updateSidebarCommand(enabled)
)
);
}
onStop(): void {
this.toDispose.dispose();
}
override registerCommands(registry: CommandRegistry): void {
const openExternal = (url: string) =>
this.windowService.openNewWindow(url, { external: true });
const loggedIn = () => Boolean(this.createFeatures.session);
const loggedInWithInternetConnection = () =>
loggedIn() && this.connectionStatus.offlineStatus !== 'internet';
registry.registerCommand(Account.Commands.LEARN_MORE, {
execute: () => openExternal(LEARN_MORE_URL),
isEnabled: () => !loggedIn(),
isVisible: () => !loggedIn(),
});
registry.registerCommand(Account.Commands.GO_TO_PROFILE, {
execute: () => openExternal('https://id.arduino.cc/'),
isEnabled: () => loggedInWithInternetConnection(),
isVisible: () => loggedIn(),
});
registry.registerCommand(Account.Commands.GO_TO_CLOUD_EDITOR, {
execute: () => openExternal('https://create.arduino.cc/editor'),
isEnabled: () => loggedInWithInternetConnection(),
isVisible: () => loggedIn(),
});
registry.registerCommand(Account.Commands.GO_TO_IOT_CLOUD, {
execute: () => openExternal('https://create.arduino.cc/iot/'),
isEnabled: () => loggedInWithInternetConnection(),
isVisible: () => loggedIn(),
});
}
override registerMenus(registry: MenuModelRegistry): void {
const register = (
menuPath: MenuPath,
...commands: (Command | [command: Command, menuLabel: string])[]
) =>
commands.forEach((command, index) => {
const commandId = Array.isArray(command) ? command[0].id : command.id;
const label = Array.isArray(command) ? command[1] : command.label;
registry.registerMenuAction(menuPath, {
label,
commandId,
order: String(index),
});
});
register(ArduinoMenus.ARDUINO_ACCOUNT__CONTEXT__SIGN_IN_GROUP, [
CloudUserCommands.LOGIN,
nls.localize('arduino/cloud/signInToCloud', 'Sign in to Arduino Cloud'),
]);
register(ArduinoMenus.ARDUINO_ACCOUNT__CONTEXT__LEARN_MORE_GROUP, [
Account.Commands.LEARN_MORE,
nls.localize('arduino/cloud/learnMore', 'Learn more'),
]);
register(
ArduinoMenus.ARDUINO_ACCOUNT__CONTEXT__GO_TO_GROUP,
[
Account.Commands.GO_TO_PROFILE,
nls.localize('arduino/account/goToProfile', 'Go to Profile'),
],
[
Account.Commands.GO_TO_CLOUD_EDITOR,
nls.localize('arduino/account/goToCloudEditor', 'Go to Cloud Editor'),
],
[
Account.Commands.GO_TO_IOT_CLOUD,
nls.localize('arduino/account/goToIoTCloud', 'Go to IoT Cloud'),
]
);
register(
ArduinoMenus.ARDUINO_ACCOUNT__CONTEXT__SIGN_OUT_GROUP,
CloudUserCommands.LOGOUT
);
}
private updateSidebarCommand(
visible: boolean = this.preferences['arduino.cloud.enabled']
): void {
if (!this.app) {
return;
}
const handler = this.app.shell.leftPanelHandler;
if (visible) {
handler.addBottomMenu(accountMenu);
} else {
handler.removeBottomMenu(accountMenu.id);
}
}
}
export namespace Account {
export namespace Commands {
export const GO_TO_PROFILE: Command = {
id: 'arduino-go-to-profile',
};
export const GO_TO_CLOUD_EDITOR: Command = {
id: 'arduino-go-to-cloud-editor',
};
export const GO_TO_IOT_CLOUD: Command = {
id: 'arduino-go-to-iot-cloud',
};
export const LEARN_MORE: Command = {
id: 'arduino-learn-more',
};
}
}

View File

@@ -1,21 +1,21 @@
import { nls } from '@theia/core/lib/common/nls';
import { inject, injectable } from '@theia/core/shared/inversify';
import * as remote from '@theia/core/electron-shared/@electron/remote';
import { FileDialogService } from '@theia/filesystem/lib/browser';
import { ArduinoMenus } from '../menu/arduino-menus';
import { CurrentSketch } from '../sketches-service-client-impl';
import {
SketchContribution,
Command,
CommandRegistry,
MenuModelRegistry,
Sketch,
SketchContribution,
URI,
} from './contribution';
import { FileDialogService } from '@theia/filesystem/lib/browser';
import { nls } from '@theia/core/lib/common';
import { CurrentSketch } from '../../common/protocol/sketches-service-client-impl';
@injectable()
export class AddFile extends SketchContribution {
@inject(FileDialogService)
protected readonly fileDialogService: FileDialogService;
private readonly fileDialogService: FileDialogService; // TODO: use dialogService
override registerCommands(registry: CommandRegistry): void {
registry.registerCommand(AddFile.Commands.ADD_FILE, {
@@ -31,7 +31,7 @@ export class AddFile extends SketchContribution {
});
}
protected async addFile(): Promise<void> {
private async addFile(): Promise<void> {
const sketch = await this.sketchServiceClient.currentSketch();
if (!CurrentSketch.isValid(sketch)) {
return;
@@ -41,16 +41,15 @@ export class AddFile extends SketchContribution {
canSelectFiles: true,
canSelectFolders: false,
canSelectMany: false,
modal: true,
});
if (!toAddUri) {
return;
}
const sketchUri = new URI(sketch.uri);
const filename = toAddUri.path.base;
const targetUri = sketchUri.resolve('data').resolve(filename);
const { uri: targetUri, filename } = this.resolveTarget(sketch, toAddUri);
const exists = await this.fileService.exists(targetUri);
if (exists) {
const { response } = await remote.dialog.showMessageBox({
const { response } = await this.dialogService.showMessageBox({
type: 'question',
title: nls.localize('arduino/contributions/replaceTitle', 'Replace'),
buttons: [
@@ -79,6 +78,22 @@ export class AddFile extends SketchContribution {
}
);
}
// https://github.com/arduino/arduino-ide/issues/284#issuecomment-1364533662
// File the file to add has one of the following extension, it goes to the sketch folder root: .ino, .h, .cpp, .c, .S
// Otherwise, the files goes to the `data` folder inside the sketch folder root.
private resolveTarget(
sketch: Sketch,
toAddUri: URI
): { uri: URI; filename: string } {
const path = toAddUri.path;
const filename = path.base;
let root = new URI(sketch.uri);
if (!Sketch.Extensions.CODE_FILES.includes(path.ext)) {
root = root.resolve('data');
}
return { uri: root.resolve(filename), filename: filename };
}
}
export namespace AddFile {

View File

@@ -1,8 +1,6 @@
import { inject, injectable } from '@theia/core/shared/inversify';
import * as remote from '@theia/core/electron-shared/@electron/remote';
import URI from '@theia/core/lib/common/uri';
import { ConfirmDialog } from '@theia/core/lib/browser/dialogs';
import { EnvVariablesServer } from '@theia/core/lib/common/env-variables';
import { ArduinoMenus } from '../menu/arduino-menus';
import { LibraryService, ResponseServiceClient } from '../../common/protocol';
import { ExecuteWithProgress } from '../../common/protocol/progressible';
@@ -16,14 +14,11 @@ import { nls } from '@theia/core/lib/common';
@injectable()
export class AddZipLibrary extends SketchContribution {
@inject(EnvVariablesServer)
protected readonly envVariableServer: EnvVariablesServer;
@inject(ResponseServiceClient)
protected readonly responseService: ResponseServiceClient;
private readonly responseService: ResponseServiceClient;
@inject(LibraryService)
protected readonly libraryService: LibraryService;
private readonly libraryService: LibraryService;
override registerCommands(registry: CommandRegistry): void {
registry.registerCommand(AddZipLibrary.Commands.ADD_ZIP_LIBRARY, {
@@ -43,10 +38,10 @@ export class AddZipLibrary extends SketchContribution {
});
}
async addZipLibrary(): Promise<void> {
private async addZipLibrary(): Promise<void> {
const homeUri = await this.envVariableServer.getHomeDirUri();
const defaultPath = await this.fileService.fsPath(new URI(homeUri));
const { canceled, filePaths } = await remote.dialog.showOpenDialog({
const { canceled, filePaths } = await this.dialogService.showOpenDialog({
title: nls.localize(
'arduino/selectZip',
"Select a zip file containing the library you'd like to add"

View File

@@ -1,7 +1,5 @@
import { injectable } from '@theia/core/shared/inversify';
import * as remote from '@theia/core/electron-shared/@electron/remote';
import * as dateFormat from 'dateformat';
import URI from '@theia/core/lib/common/uri';
import dateFormat from 'dateformat';
import { ArduinoMenus } from '../menu/arduino-menus';
import {
SketchContribution,
@@ -10,7 +8,7 @@ import {
MenuModelRegistry,
} from './contribution';
import { nls } from '@theia/core/lib/common';
import { CurrentSketch } from '../../common/protocol/sketches-service-client-impl';
import { CurrentSketch } from '../sketches-service-client-impl';
@injectable()
export class ArchiveSketch extends SketchContribution {
@@ -28,11 +26,8 @@ export class ArchiveSketch extends SketchContribution {
});
}
protected async archiveSketch(): Promise<void> {
const [sketch, config] = await Promise.all([
this.sketchServiceClient.currentSketch(),
this.configService.getConfiguration(),
]);
private async archiveSketch(): Promise<void> {
const sketch = await this.sketchServiceClient.currentSketch();
if (!CurrentSketch.isValid(sketch)) {
return;
}
@@ -40,10 +35,10 @@ export class ArchiveSketch extends SketchContribution {
new Date(),
'yymmdd'
)}a.zip`;
const defaultPath = await this.fileService.fsPath(
new URI(config.sketchDirUri).resolve(archiveBasename)
);
const { filePath, canceled } = await remote.dialog.showSaveDialog({
const defaultContainerUri = await this.defaultUri();
const defaultUri = defaultContainerUri.resolve(archiveBasename);
const defaultPath = await this.fileService.fsPath(defaultUri);
const { filePath, canceled } = await this.dialogService.showSaveDialog({
title: nls.localize(
'arduino/sketch/saveSketchAs',
'Save sketch folder as...'
@@ -57,7 +52,7 @@ export class ArchiveSketch extends SketchContribution {
if (!destinationUri) {
return;
}
await this.sketchService.archive(sketch, destinationUri.toString());
await this.sketchesService.archive(sketch, destinationUri.toString());
this.messageService.info(
nls.localize(
'arduino/sketch/createdArchive',

View File

@@ -1,134 +1,111 @@
import { inject, injectable } from '@theia/core/shared/inversify';
import * as remote from '@theia/core/electron-shared/@electron/remote';
import { MenuModelRegistry } from '@theia/core/lib/common/menu';
import {
DisposableCollection,
Disposable,
DisposableCollection,
} from '@theia/core/lib/common/disposable';
import { firstToUpperCase } from '../../common/utils';
import { BoardsConfig } from '../boards/boards-config';
import { MenuModelRegistry } from '@theia/core/lib/common/menu/menu-model-registry';
import type { MenuPath } from '@theia/core/lib/common/menu/menu-types';
import { nls } from '@theia/core/lib/common/nls';
import { Deferred } from '@theia/core/lib/common/promise-util';
import { inject, injectable } from '@theia/core/shared/inversify';
import { MainMenuManager } from '../../common/main-menu-manager';
import {
BoardsService,
BoardWithPackage,
createPlatformIdentifier,
getBoardInfo,
InstalledBoardWithPackage,
platformIdentifierEquals,
Port,
serializePlatformIdentifier,
} from '../../common/protocol';
import type { BoardList } from '../../common/protocol/board-list';
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';
import { nls } from '@theia/core/lib/common';
import { NotificationCenter } from '../notification-center';
import { Command, CommandRegistry, SketchContribution } from './contribution';
@injectable()
export class BoardSelection extends SketchContribution {
@inject(CommandRegistry)
protected readonly commandRegistry: CommandRegistry;
private readonly commandRegistry: CommandRegistry;
@inject(MainMenuManager)
protected readonly mainMenuManager: MainMenuManager;
private readonly mainMenuManager: MainMenuManager;
@inject(MenuModelRegistry)
protected readonly menuModelRegistry: MenuModelRegistry;
private readonly menuModelRegistry: MenuModelRegistry;
@inject(NotificationCenter)
protected readonly notificationCenter: NotificationCenter;
private readonly notificationCenter: NotificationCenter;
@inject(BoardsService)
protected readonly boardsService: BoardsService;
private readonly boardsService: BoardsService;
@inject(BoardsServiceProvider)
protected readonly boardsServiceProvider: BoardsServiceProvider;
private readonly boardsServiceProvider: BoardsServiceProvider;
protected readonly toDisposeBeforeMenuRebuild = new DisposableCollection();
private readonly toDisposeBeforeMenuRebuild = new DisposableCollection();
// do not query installed platforms on every change
private _installedBoards: Deferred<InstalledBoardWithPackage[]> | undefined;
override registerCommands(registry: CommandRegistry): void {
registry.registerCommand(BoardSelection.Commands.GET_BOARD_INFO, {
execute: async () => {
const { selectedBoard, selectedPort } =
this.boardsServiceProvider.boardsConfig;
if (!selectedBoard) {
this.messageService.info(
nls.localize(
'arduino/board/selectBoardForInfo',
'Please select a board to obtain board info.'
)
);
const boardInfo = await getBoardInfo(
this.boardsServiceProvider.boardList
);
if (typeof boardInfo === 'string') {
this.messageService.info(boardInfo);
return;
}
if (!selectedBoard.fqbn) {
this.messageService.info(
nls.localize(
'arduino/board/platformMissing',
"The platform for the selected '{0}' board is not installed.",
selectedBoard.name
)
);
return;
}
if (!selectedPort) {
this.messageService.info(
nls.localize(
'arduino/board/selectPortForInfo',
'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}
const { BN, VID, PID, SN } = boardInfo;
const detail = `
BN: ${BN}
VID: ${VID}
PID: ${PID}`;
await remote.dialog.showMessageBox(remote.getCurrentWindow(), {
message: nls.localize('arduino/board/boardInfo', 'Board Info'),
title: nls.localize('arduino/board/boardInfo', 'Board Info'),
type: 'info',
detail,
buttons: [nls.localize('vscode/issueMainService/ok', 'OK')],
});
}
PID: ${PID}
SN: ${SN}
`.trim();
await this.dialogService.showMessageBox({
message: nls.localize('arduino/board/boardInfo', 'Board Info'),
title: nls.localize('arduino/board/boardInfo', 'Board Info'),
type: 'info',
detail,
buttons: [nls.localize('vscode/issueMainService/ok', 'OK')],
});
},
});
}
override onStart(): void {
this.notificationCenter.onPlatformDidInstall(() => this.updateMenus());
this.notificationCenter.onPlatformDidUninstall(() => this.updateMenus());
this.boardsServiceProvider.onBoardsConfigChanged(() => this.updateMenus());
this.boardsServiceProvider.onAvailableBoardsChanged(() =>
this.updateMenus()
);
this.boardsServiceProvider.onAvailablePortsChanged(() =>
this.updateMenus()
this.notificationCenter.onPlatformDidInstall(() => this.updateMenus(true));
this.notificationCenter.onPlatformDidUninstall(() =>
this.updateMenus(true)
);
this.boardsServiceProvider.onBoardListDidChange(() => this.updateMenus());
}
override async onReady(): Promise<void> {
this.updateMenus();
}
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);
private async updateMenus(discardCache = false): Promise<void> {
if (discardCache) {
this._installedBoards?.reject();
this._installedBoards = undefined;
}
if (!this._installedBoards) {
this._installedBoards = new Deferred();
this.installedBoards().then((installedBoards) =>
this._installedBoards?.resolve(installedBoards)
);
}
const installedBoards = await this._installedBoards.promise;
this.rebuildMenus(installedBoards, this.boardsServiceProvider.boardList);
}
protected rebuildMenus(
private rebuildMenus(
installedBoards: InstalledBoardWithPackage[],
availablePorts: AvailablePorts,
config: BoardsConfig.Config
boardList: BoardList
): void {
this.toDisposeBeforeMenuRebuild.dispose();
@@ -137,7 +114,8 @@ PID: ${PID}`;
...ArduinoMenus.TOOLS__BOARD_SELECTION_GROUP,
'1_boards',
];
const boardsSubmenuLabel = config.selectedBoard?.name;
const { selectedBoard, selectedPort } = boardList.boardsConfig;
const boardsSubmenuLabel = 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(
@@ -156,11 +134,8 @@ PID: ${PID}`;
);
// Ports submenu
const portsSubmenuPath = [
...ArduinoMenus.TOOLS__BOARD_SELECTION_GROUP,
'2_ports',
];
const portsSubmenuLabel = config.selectedPort?.address;
const portsSubmenuPath = ArduinoMenus.TOOLS__PORTS_SUBMENU;
const portsSubmenuLabel = selectedPort?.address;
this.menuModelRegistry.registerSubmenu(
portsSubmenuPath,
nls.localize(
@@ -199,64 +174,116 @@ PID: ${PID}`;
label: `${BoardsListWidget.WIDGET_LABEL}...`,
});
// Installed boards
const selectedBoardPlatformId = selectedBoard
? createPlatformIdentifier(selectedBoard)
: undefined;
// Keys are the vendor IDs
type BoardsPerVendor = Record<string, BoardWithPackage[]>;
// Group boards by their platform names. The keys are the platform names as menu labels.
// If there is a platform name (menu label) collision, refine the menu label with the vendor ID.
const groupedBoards = new Map<string, BoardsPerVendor>();
for (const board of installedBoards) {
const { packageId, packageName, fqbn, name, manuallyInstalled } = board;
const packageLabel =
packageName +
`${manuallyInstalled
? nls.localize('arduino/board/inSketchbook', ' (in Sketchbook)')
: ''
}`;
// 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, packageLabel, {
order: packageName.toLowerCase(),
});
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.
const { packageId, packageName } = board;
const { vendorId } = packageId;
let boardsPerPackageName = groupedBoards.get(packageName);
if (!boardsPerPackageName) {
boardsPerPackageName = {} as BoardsPerVendor;
groupedBoards.set(packageName, boardsPerPackageName);
}
let boardPerVendor: BoardWithPackage[] | undefined =
boardsPerPackageName[vendorId];
if (!boardPerVendor) {
boardPerVendor = [];
boardsPerPackageName[vendorId] = boardPerVendor;
}
boardPerVendor.push(board);
}
// Installed ports
// Installed boards
Array.from(groupedBoards.entries()).forEach(
([packageName, boardsPerPackage]) => {
const useVendorSuffix = Object.keys(boardsPerPackage).length > 1;
Object.entries(boardsPerPackage).forEach(([vendorId, boards]) => {
let platformMenuPath: MenuPath | undefined = undefined;
boards.forEach((board, index) => {
const { packageId, fqbn, name, manuallyInstalled } = board;
// create the platform submenu once.
// creating and registering the same submenu twice in Theia is a noop, though.
if (!platformMenuPath) {
let packageLabel =
packageName +
`${
manuallyInstalled
? nls.localize(
'arduino/board/inSketchbook',
' (in Sketchbook)'
)
: ''
}`;
if (
selectedBoardPlatformId &&
platformIdentifierEquals(packageId, selectedBoardPlatformId)
) {
packageLabel = `${packageLabel}`;
}
if (useVendorSuffix) {
packageLabel += ` (${vendorId})`;
}
// Platform submenu
platformMenuPath = [
...boardsPackagesGroup,
serializePlatformIdentifier(packageId),
];
this.menuModelRegistry.registerSubmenu(
platformMenuPath,
packageLabel,
{
order: packageName.toLowerCase(),
}
);
}
const id = `arduino-select-board--${fqbn}`;
const command = { id };
const handler = {
execute: () =>
this.boardsServiceProvider.updateConfig({
name: name,
fqbn: fqbn,
}),
isToggled: () => fqbn === selectedBoard?.fqbn,
};
// Board menu
const menuAction = {
commandId: id,
label: name,
order: String(index).padStart(4), // pads with leading zeros for alphanumeric sort where order is 1, 2, 11, and NOT 1, 11, 2
};
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.
});
});
}
);
// Detected ports
const registerPorts = (
protocol: string,
protocolOrder: number,
ports: AvailablePorts
ports: ReturnType<BoardList['ports']>,
protocolOrder: number
) => {
const portIDs = Object.keys(ports);
if (!portIDs.length) {
if (!ports.length) {
return;
}
@@ -267,8 +294,12 @@ PID: ${PID}`;
];
const placeholder = new PlaceholderMenuNode(
menuPath,
`${firstToUpperCase(protocol)} ports`,
{ order: protocolOrder.toString() }
nls.localize(
'arduino/board/typeOfPorts',
'{0} ports',
Port.Protocols.protocolLabel(protocol)
),
{ order: protocolOrder.toString().padStart(4) }
);
this.menuModelRegistry.registerMenuNode(menuPath, placeholder);
this.toDisposeBeforeMenuRebuild.push(
@@ -277,49 +308,31 @@ PID: ${PID}`;
)
);
// First we show addresses with recognized boards connected,
// then all the rest.
const sortedIDs = Object.keys(ports).sort((left: string, right: string): number => {
const [, leftBoards] = ports[left];
const [, rightBoards] = ports[right];
return rightBoards.length - leftBoards.length;
});
for (let i = 0; i < sortedIDs.length; i++) {
const portID = sortedIDs[i];
const [port, boards] = ports[portID];
let label = `${port.address}`;
if (boards.length) {
for (let i = 0; i < ports.length; i++) {
const { port, boards } = ports[i];
const portKey = Port.keyOf(port);
let label = `${port.addressLabel}`;
if (boards?.length) {
const boardsList = boards.map((board) => board.name).join(', ');
label = `${label} (${boardsList})`;
}
const id = `arduino-select-port--${portID}`;
const id = `arduino-select-port--${portKey}`;
const command = { id };
const handler = {
execute: () => {
if (
!Port.sameAs(
port,
this.boardsServiceProvider.boardsConfig.selectedPort
)
) {
this.boardsServiceProvider.boardsConfig = {
selectedBoard:
this.boardsServiceProvider.boardsConfig.selectedBoard,
selectedPort: port,
};
}
this.boardsServiceProvider.updateConfig({
protocol: port.protocol,
address: port.address,
});
},
isToggled: () => {
return i === ports.matchingIndex;
},
isToggled: () =>
Port.sameAs(
port,
this.boardsServiceProvider.boardsConfig.selectedPort
),
};
const menuAction = {
commandId: id,
label,
order: `${protocolOrder + i + 1}`,
order: String(protocolOrder + i + 1).padStart(4),
};
this.commandRegistry.registerCommand(command, handler);
this.toDisposeBeforeMenuRebuild.push(
@@ -331,27 +344,17 @@ PID: ${PID}`;
}
};
const grouped = AvailablePorts.byProtocol(availablePorts);
const groupedPorts = boardList.portsGroupedByProtocol();
let protocolOrder = 100;
// We first show serial and network ports, then all the rest
['serial', 'network'].forEach((protocol) => {
const ports = grouped.get(protocol);
if (ports) {
registerPorts(protocol, protocolOrder, ports);
grouped.delete(protocol);
protocolOrder = protocolOrder + 100;
}
Object.entries(groupedPorts).forEach(([protocol, ports]) => {
registerPorts(protocol, ports, protocolOrder);
protocolOrder += 100;
});
grouped.forEach((ports, protocol) => {
registerPorts(protocol, protocolOrder, ports);
protocolOrder = protocolOrder + 100;
});
this.mainMenuManager.update();
}
protected async installedBoards(): Promise<InstalledBoardWithPackage[]> {
const allBoards = await this.boardsService.searchBoards({});
const allBoards = await this.boardsService.getInstalledBoards();
return allBoards.filter(InstalledBoardWithPackage.is);
}
}

View File

@@ -1,67 +1,66 @@
import * as PQueue from 'p-queue';
import { inject, injectable } from '@theia/core/shared/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 { nls } from '@theia/core/lib/common/nls';
import { inject, injectable } from '@theia/core/shared/inversify';
import PQueue from 'p-queue';
import {
BoardIdentifier,
ConfigOption,
isBoardIdentifierChangeEvent,
Programmer,
} from '../../common/protocol';
import { BoardsDataStore } from '../boards/boards-data-store';
import { BoardsServiceProvider } from '../boards/boards-service-provider';
import { ArduinoMenus, unregisterSubmenu } from '../menu/arduino-menus';
import { nls } from '@theia/core/lib/common';
import { FrontendApplicationStateService } from '@theia/core/lib/browser/frontend-application-state';
import {
CommandRegistry,
Contribution,
MenuModelRegistry,
} from './contribution';
@injectable()
export class BoardsDataMenuUpdater implements FrontendApplicationContribution {
export class BoardsDataMenuUpdater extends Contribution {
@inject(CommandRegistry)
protected readonly commandRegistry: CommandRegistry;
private readonly commandRegistry: CommandRegistry;
@inject(MenuModelRegistry)
protected readonly menuRegistry: MenuModelRegistry;
@inject(MainMenuManager)
protected readonly mainMenuManager: MainMenuManager;
private readonly menuRegistry: MenuModelRegistry;
@inject(BoardsDataStore)
protected readonly boardsDataStore: BoardsDataStore;
private readonly boardsDataStore: BoardsDataStore;
@inject(BoardsServiceProvider)
protected readonly boardsServiceClient: BoardsServiceProvider;
private readonly boardsServiceProvider: BoardsServiceProvider;
@inject(FrontendApplicationStateService)
private readonly appStateService: FrontendApplicationStateService;
private readonly queue = new PQueue({ autoStart: true, concurrency: 1 });
private readonly toDisposeOnBoardChange = new DisposableCollection();
protected readonly queue = new PQueue({ autoStart: true, concurrency: 1 });
protected readonly toDisposeOnBoardChange = new DisposableCollection();
async onStart(): Promise<void> {
this.appStateService
.reachedState('ready')
.then(() =>
this.updateMenuActions(
this.boardsServiceClient.boardsConfig.selectedBoard
)
);
override onStart(): void {
this.boardsDataStore.onChanged(() =>
this.updateMenuActions(
this.boardsServiceClient.boardsConfig.selectedBoard
this.boardsServiceProvider.boardsConfig.selectedBoard
)
);
this.boardsServiceClient.onBoardsConfigChanged(({ selectedBoard }) =>
this.updateMenuActions(selectedBoard)
this.boardsServiceProvider.onBoardsConfigDidChange((event) => {
if (isBoardIdentifierChangeEvent(event)) {
this.updateMenuActions(event.selectedBoard);
}
});
}
override onReady(): void {
this.boardsServiceProvider.ready.then(() =>
this.updateMenuActions(
this.boardsServiceProvider.boardsConfig.selectedBoard
)
);
}
protected async updateMenuActions(
selectedBoard: Board | undefined
private async updateMenuActions(
selectedBoard: BoardIdentifier | undefined
): Promise<void> {
return this.queue.add(async () => {
this.toDisposeOnBoardChange.dispose();
this.mainMenuManager.update();
this.menuManager.update();
if (selectedBoard) {
const { fqbn } = selectedBoard;
if (fqbn) {
@@ -80,16 +79,16 @@ export class BoardsDataMenuUpdater implements FrontendApplicationContribution {
string,
Disposable & { label: string }
>();
let selectedValue = '';
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,
selectedValue: value.value,
}),
isToggled: () => value.selected,
};
@@ -100,8 +99,14 @@ export class BoardsDataMenuUpdater implements FrontendApplicationContribution {
{ label: value.label }
)
);
if (value.selected) {
selectedValue = value.label;
}
}
this.menuRegistry.registerSubmenu(menuPath, label);
this.menuRegistry.registerSubmenu(
menuPath,
`${label}${selectedValue ? `: "${selectedValue}"` : ''}`
);
this.toDisposeOnBoardChange.pushAll([
...commands.values(),
Disposable.create(() =>
@@ -111,7 +116,7 @@ export class BoardsDataMenuUpdater implements FrontendApplicationContribution {
const { label } = commands.get(commandId)!;
this.menuRegistry.registerMenuAction(menuPath, {
commandId,
order: `${i}`,
order: String(i).padStart(4),
label,
});
return Disposable.create(() =>
@@ -166,7 +171,7 @@ export class BoardsDataMenuUpdater implements FrontendApplicationContribution {
]);
}
}
this.mainMenuManager.update();
this.menuManager.update();
}
}
});

View File

@@ -29,6 +29,7 @@ export class BurnBootloader extends CoreServiceContribution {
}
private async burnBootloader(): Promise<void> {
this.clearVisibleNotification();
const options = await this.options();
try {
await this.doWithProgress({

View File

@@ -0,0 +1,69 @@
import { nls } from '@theia/core/lib/common/nls';
import { LocalStorageService } from '@theia/core/lib/browser/storage-service';
import { inject, injectable } from '@theia/core/shared/inversify';
import {
IDEUpdater,
SKIP_IDE_VERSION,
} from '../../common/protocol/ide-updater';
import { IDEUpdaterDialog } from '../dialogs/ide-updater/ide-updater-dialog';
import { Contribution } from './contribution';
@injectable()
export class CheckForIDEUpdates extends Contribution {
@inject(IDEUpdater)
private readonly updater: IDEUpdater;
@inject(IDEUpdaterDialog)
private readonly updaterDialog: IDEUpdaterDialog;
@inject(LocalStorageService)
private readonly localStorage: LocalStorageService;
override onStart(): void {
this.preferences.onPreferenceChanged(
({ preferenceName, newValue, oldValue }) => {
if (newValue !== oldValue) {
switch (preferenceName) {
case 'arduino.ide.updateChannel':
case 'arduino.ide.updateBaseUrl':
this.updater.init(
this.preferences.get('arduino.ide.updateChannel'),
this.preferences.get('arduino.ide.updateBaseUrl')
);
}
}
}
);
}
override onReady(): void {
this.updater
.init(
this.preferences.get('arduino.ide.updateChannel'),
this.preferences.get('arduino.ide.updateBaseUrl')
)
.then(() => {
if (!this.preferences['arduino.checkForUpdates']) {
return;
}
return this.updater.checkForUpdates(true);
})
.then(async (updateInfo) => {
if (!updateInfo) return;
const versionToSkip = await this.localStorage.getData<string>(
SKIP_IDE_VERSION
);
if (versionToSkip === updateInfo.version) return;
this.updaterDialog.open(updateInfo);
})
.catch((e) => {
this.messageService.error(
nls.localize(
'arduino/ide-updater/errorCheckingForUpdates',
'Error while checking for Arduino IDE updates.\n{0}',
e.message
)
);
});
}
}

View File

@@ -1,64 +1,221 @@
import type { AbstractViewContribution } from '@theia/core/lib/browser/shell/view-contribution';
import { nls } from '@theia/core/lib/common/nls';
import { LocalStorageService } from '@theia/core/lib/browser/storage-service';
import { inject, injectable } from '@theia/core/shared/inversify';
import { InstallManually, Later } from '../../common/nls';
import {
IDEUpdater,
SKIP_IDE_VERSION,
} from '../../common/protocol/ide-updater';
import { IDEUpdaterDialog } from '../dialogs/ide-updater/ide-updater-dialog';
import { Contribution } from './contribution';
ArduinoComponent,
BoardsPackage,
BoardsService,
LibraryPackage,
LibraryService,
ResponseServiceClient,
Searchable,
} from '../../common/protocol';
import { Installable } from '../../common/protocol/installable';
import { ExecuteWithProgress } from '../../common/protocol/progressible';
import { BoardsListWidgetFrontendContribution } from '../boards/boards-widget-frontend-contribution';
import { LibraryListWidgetFrontendContribution } from '../library/library-widget-frontend-contribution';
import { WindowServiceExt } from '../theia/core/window-service-ext';
import type { ListWidget } from '../widgets/component-list/list-widget';
import { Command, CommandRegistry, Contribution } from './contribution';
const NoUpdates = nls.localize(
'arduino/checkForUpdates/noUpdates',
'There are no recent updates available.'
);
const PromptUpdateBoards = nls.localize(
'arduino/checkForUpdates/promptUpdateBoards',
'Updates are available for some of your boards.'
);
const PromptUpdateLibraries = nls.localize(
'arduino/checkForUpdates/promptUpdateLibraries',
'Updates are available for some of your libraries.'
);
const UpdatingBoards = nls.localize(
'arduino/checkForUpdates/updatingBoards',
'Updating boards...'
);
const UpdatingLibraries = nls.localize(
'arduino/checkForUpdates/updatingLibraries',
'Updating libraries...'
);
const InstallAll = nls.localize(
'arduino/checkForUpdates/installAll',
'Install All'
);
interface Task<T extends ArduinoComponent> {
readonly run: () => Promise<void>;
readonly item: T;
}
const Updatable = { type: 'Updatable' } as const;
@injectable()
export class CheckForUpdates extends Contribution {
@inject(IDEUpdater)
private readonly updater: IDEUpdater;
@inject(WindowServiceExt)
private readonly windowService: WindowServiceExt;
@inject(ResponseServiceClient)
private readonly responseService: ResponseServiceClient;
@inject(BoardsService)
private readonly boardsService: BoardsService;
@inject(LibraryService)
private readonly libraryService: LibraryService;
@inject(BoardsListWidgetFrontendContribution)
private readonly boardsContribution: BoardsListWidgetFrontendContribution;
@inject(LibraryListWidgetFrontendContribution)
private readonly librariesContribution: LibraryListWidgetFrontendContribution;
@inject(IDEUpdaterDialog)
private readonly updaterDialog: IDEUpdaterDialog;
@inject(LocalStorageService)
private readonly localStorage: LocalStorageService;
override onStart(): void {
this.preferences.onPreferenceChanged(
({ preferenceName, newValue, oldValue }) => {
if (newValue !== oldValue) {
switch (preferenceName) {
case 'arduino.ide.updateChannel':
case 'arduino.ide.updateBaseUrl':
this.updater.init(
this.preferences.get('arduino.ide.updateChannel'),
this.preferences.get('arduino.ide.updateBaseUrl')
);
}
}
}
);
override registerCommands(register: CommandRegistry): void {
register.registerCommand(CheckForUpdates.Commands.CHECK_FOR_UPDATES, {
execute: () => this.checkForUpdates(false),
});
}
override onReady(): void {
this.updater
.init(
this.preferences.get('arduino.ide.updateChannel'),
this.preferences.get('arduino.ide.updateBaseUrl')
)
.then(() => this.updater.checkForUpdates(true))
.then(async (updateInfo) => {
if (!updateInfo) return;
const versionToSkip = await this.localStorage.getData<string>(
SKIP_IDE_VERSION
);
if (versionToSkip === updateInfo.version) return;
this.updaterDialog.open(updateInfo);
})
.catch((e) => {
this.messageService.error(
nls.localize(
'arduino/ide-updater/errorCheckingForUpdates',
'Error while checking for Arduino IDE updates.\n{0}',
e.message
)
);
override async onReady(): Promise<void> {
const checkForUpdates = this.preferences['arduino.checkForUpdates'];
if (checkForUpdates) {
this.windowService.isFirstWindow().then((firstWindow) => {
if (firstWindow) {
this.checkForUpdates();
}
});
}
}
private async checkForUpdates(silent = true) {
const [boardsPackages, libraryPackages] = await Promise.all([
this.boardsService.search(Updatable),
this.libraryService.search(Updatable),
]);
this.promptUpdateBoards(boardsPackages);
this.promptUpdateLibraries(libraryPackages);
if (!libraryPackages.length && !boardsPackages.length && !silent) {
this.messageService.info(NoUpdates);
}
}
private promptUpdateBoards(items: BoardsPackage[]): void {
this.prompt({
items,
installable: this.boardsService,
viewContribution: this.boardsContribution,
viewSearchOptions: { query: '', ...Updatable },
promptMessage: PromptUpdateBoards,
updatingMessage: UpdatingBoards,
});
}
private promptUpdateLibraries(items: LibraryPackage[]): void {
this.prompt({
items,
installable: this.libraryService,
viewContribution: this.librariesContribution,
viewSearchOptions: { query: '', topic: 'All', ...Updatable },
promptMessage: PromptUpdateLibraries,
updatingMessage: UpdatingLibraries,
});
}
private prompt<
T extends ArduinoComponent,
S extends Searchable.Options
>(options: {
items: T[];
installable: Installable<T>;
viewContribution: AbstractViewContribution<ListWidget<T, S>>;
viewSearchOptions: S;
promptMessage: string;
updatingMessage: string;
}): void {
const {
items,
installable,
viewContribution,
promptMessage: message,
viewSearchOptions,
updatingMessage,
} = options;
if (!items.length) {
return;
}
this.messageService
.info(message, Later, InstallManually, InstallAll)
.then((answer) => {
if (answer === InstallAll) {
const tasks = items.map((item) =>
this.createInstallTask(item, installable)
);
this.executeTasks(updatingMessage, tasks);
} else if (answer === InstallManually) {
viewContribution
.openView({ reveal: true })
.then((widget) => widget.refresh(viewSearchOptions));
}
});
}
private async executeTasks(
message: string,
tasks: Task<ArduinoComponent>[]
): Promise<void> {
if (tasks.length) {
return ExecuteWithProgress.withProgress(
message,
this.messageService,
async (progress) => {
try {
const total = tasks.length;
let count = 0;
for (const { run, item } of tasks) {
try {
await run(); // runs update sequentially. // TODO: is parallel update desired?
} catch (err) {
console.error(err);
this.messageService.error(
`Failed to update ${item.name}. ${err}`
);
} finally {
progress.report({ work: { total, done: ++count } });
}
}
} finally {
progress.cancel();
}
}
);
}
}
private createInstallTask<T extends ArduinoComponent>(
item: T,
installable: Installable<T>
): Task<T> {
const latestVersion = item.availableVersions[0];
return {
item,
run: () =>
Installable.installWithProgress({
installable,
item,
version: latestVersion,
messageService: this.messageService,
responseService: this.responseService,
keepOutput: true,
}),
};
}
}
export namespace CheckForUpdates {
export namespace Commands {
export const CHECK_FOR_UPDATES: Command = Command.toLocalizedCommand(
{
id: 'arduino-check-for-updates',
label: 'Check for Arduino Updates',
category: 'Arduino',
},
'arduino/checkForUpdates/checkForUpdates'
);
}
}

View File

@@ -1,37 +1,66 @@
import { inject, injectable } from '@theia/core/shared/inversify';
import * as remote from '@theia/core/electron-shared/@electron/remote';
import { MonacoEditor } from '@theia/monaco/lib/browser/monaco-editor';
import { EditorManager } from '@theia/editor/lib/browser/editor-manager';
import { Dialog } from '@theia/core/lib/browser/dialogs';
import type {
FrontendApplication,
OnWillStopAction,
} from '@theia/core/lib/browser/frontend-application';
import { ApplicationShell } from '@theia/core/lib/browser/shell/application-shell';
import { FrontendApplication } from '@theia/core/lib/browser/frontend-application';
import { nls } from '@theia/core/lib/common/nls';
import type { MaybePromise } from '@theia/core/lib/common/types';
import { toArray } from '@theia/core/shared/@phosphor/algorithm';
import { inject, injectable } from '@theia/core/shared/inversify';
import { MonacoEditor } from '@theia/monaco/lib/browser/monaco-editor';
import { ArduinoMenus } from '../menu/arduino-menus';
import { CurrentSketch } from '../sketches-service-client-impl';
import { WindowServiceExt } from '../theia/core/window-service-ext';
import {
SketchContribution,
Command,
CommandRegistry,
MenuModelRegistry,
KeybindingRegistry,
MenuModelRegistry,
Sketch,
SketchContribution,
URI,
} from './contribution';
import { nls } from '@theia/core/lib/common';
import { SaveAsSketch } from './save-as-sketch';
/**
* 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 override readonly editorManager: EditorManager;
@inject(WindowServiceExt)
private readonly windowServiceExt: WindowServiceExt;
protected shell: ApplicationShell;
private shell: ApplicationShell | undefined;
override onStart(app: FrontendApplication): void {
override onStart(app: FrontendApplication): MaybePromise<void> {
this.shell = app.shell;
}
override registerCommands(registry: CommandRegistry): void {
registry.registerCommand(Close.Commands.CLOSE, {
execute: () => remote.getCurrentWindow().close()
execute: () => {
// Close current editor if closeable.
const { currentEditor } = this.editorManager;
if (currentEditor && currentEditor.title.closable) {
currentEditor.close();
return;
}
if (this.shell) {
// 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();
}
}
}
return this.windowServiceExt.close();
},
});
}
@@ -39,7 +68,7 @@ export class Close extends SketchContribution {
registry.registerMenuAction(ArduinoMenus.FILE__SKETCH_GROUP, {
commandId: Close.Commands.CLOSE.id,
label: nls.localize('vscode/editor.contribution/close', 'Close'),
order: '5',
order: '6',
});
}
@@ -50,6 +79,120 @@ export class Close extends SketchContribution {
});
}
// `FrontendApplicationContribution#onWillStop`
onWillStop(): OnWillStopAction {
return {
reason: 'save-sketch',
action: () => {
return this.showSaveSketchDialog();
},
};
}
/**
* If returns with `true`, IDE2 will close. Otherwise, it won't.
*/
private async showSaveSketchDialog(): Promise<boolean> {
const sketch = await this.isCurrentSketchTemp();
if (!sketch) {
// Normal close workflow: if there are dirty editors prompt the user.
if (!this.shell) {
console.error(
`Could not get the application shell. Something went wrong.`
);
return true;
}
if (this.shell.canSaveAll()) {
const prompt = await this.prompt(false);
switch (prompt) {
case Prompt.DoNotSave:
return true;
case Prompt.Cancel:
return false;
case Prompt.Save: {
await this.shell.saveAll();
return true;
}
default:
throw new Error(`Unexpected prompt: ${prompt}`);
}
}
return true;
}
// If non of the sketch files were ever touched, do not prompt the save dialog. (#1274)
const wereTouched = await Promise.all(
Sketch.uris(sketch).map((uri) => this.wasTouched(uri))
);
if (wereTouched.every((wasTouched) => !Boolean(wasTouched))) {
return true;
}
const prompt = await this.prompt(true);
switch (prompt) {
case Prompt.DoNotSave:
return true;
case Prompt.Cancel:
return false;
case Prompt.Save: {
// If `save as` was canceled by user, the result will be `undefined`, otherwise the new URI.
const result = await this.commandService.executeCommand(
SaveAsSketch.Commands.SAVE_AS_SKETCH.id,
{
execOnlyIfTemp: false,
openAfterMove: false,
wipeOriginal: true,
markAsRecentlyOpened: true,
}
);
return !!result;
}
default:
throw new Error(`Unexpected prompt: ${prompt}`);
}
}
private async prompt(isTemp: boolean): Promise<Prompt> {
const { response } = await this.dialogService.showMessageBox({
message: nls.localize(
'arduino/sketch/saveSketch',
'Save your sketch to open it again later.'
),
title: nls.localize(
'theia/core/quitTitle',
'Are you sure you want to quit?'
),
type: 'question',
buttons: [
nls.localizeByDefault("Don't Save"),
Dialog.CANCEL,
nls.localizeByDefault(isTemp ? 'Save As...' : 'Save'),
],
defaultId: 2, // `Save`/`Save As...` button index is the default.
});
switch (response) {
case 0:
return Prompt.DoNotSave;
case 1:
return Prompt.Cancel;
case 2:
return Prompt.Save;
default:
throw new Error(`Unexpected response: ${response}`);
}
}
private async isCurrentSketchTemp(): Promise<false | Sketch> {
const currentSketch = await this.sketchServiceClient.currentSketch();
if (CurrentSketch.isValid(currentSketch)) {
const isTemp = await this.sketchesService.isTemp(currentSketch);
if (isTemp) {
return currentSketch;
}
}
return false;
}
/**
* If the file was ever touched/modified. We get this based on the `version` of the monaco model.
*/
@@ -59,13 +202,23 @@ export class Close extends SketchContribution {
const { editor } = editorWidget;
if (editor instanceof MonacoEditor) {
const versionId = editor.getControl().getModel()?.getVersionId();
if (Number.isInteger(versionId) && versionId! > 1) {
if (this.isInteger(versionId) && versionId > 1) {
return true;
}
}
}
return false;
}
private isInteger(arg: unknown): arg is number {
return Number.isInteger(arg);
}
}
enum Prompt {
Save,
DoNotSave,
Cancel,
}
export namespace Close {

View File

@@ -0,0 +1,121 @@
import { CompositeTreeNode } from '@theia/core/lib/browser/tree';
import { nls } from '@theia/core/lib/common/nls';
import { inject, injectable } from '@theia/core/shared/inversify';
import { CreateApi } from '../create/create-api';
import { CreateFeatures } from '../create/create-features';
import { CreateUri } from '../create/create-uri';
import { Create, isNotFound } from '../create/typings';
import { CloudSketchbookTree } from '../widgets/cloud-sketchbook/cloud-sketchbook-tree';
import { CloudSketchbookTreeModel } from '../widgets/cloud-sketchbook/cloud-sketchbook-tree-model';
import { CloudSketchbookTreeWidget } from '../widgets/cloud-sketchbook/cloud-sketchbook-tree-widget';
import { SketchbookWidget } from '../widgets/sketchbook/sketchbook-widget';
import { SketchbookWidgetContribution } from '../widgets/sketchbook/sketchbook-widget-contribution';
import { SketchContribution } from './contribution';
export function sketchAlreadyExists(input: string): string {
return nls.localize(
'arduino/cloudSketch/alreadyExists',
"Cloud sketch '{0}' already exists.",
input
);
}
export function sketchNotFound(input: string): string {
return nls.localize(
'arduino/cloudSketch/notFound',
"Could not pull the cloud sketch '{0}'. It does not exist.",
input
);
}
export const synchronizingSketchbook = nls.localize(
'arduino/cloudSketch/synchronizingSketchbook',
'Synchronizing sketchbook...'
);
export function pullingSketch(input: string): string {
return nls.localize(
'arduino/cloudSketch/pulling',
"Synchronizing sketchbook, pulling '{0}'...",
input
);
}
export function pushingSketch(input: string): string {
return nls.localize(
'arduino/cloudSketch/pushing',
"Synchronizing sketchbook, pushing '{0}'...",
input
);
}
@injectable()
export abstract class CloudSketchContribution extends SketchContribution {
@inject(SketchbookWidgetContribution)
private readonly widgetContribution: SketchbookWidgetContribution;
@inject(CreateApi)
protected readonly createApi: CreateApi;
@inject(CreateFeatures)
protected readonly createFeatures: CreateFeatures;
protected async treeModel(): Promise<
(CloudSketchbookTreeModel & { root: CompositeTreeNode }) | undefined
> {
const { enabled, session } = this.createFeatures;
if (enabled && session) {
const widget = await this.widgetContribution.widget;
const treeModel = this.treeModelFrom(widget);
if (treeModel) {
const root = treeModel.root;
if (CompositeTreeNode.is(root)) {
return treeModel as CloudSketchbookTreeModel & {
root: CompositeTreeNode;
};
}
}
}
return undefined;
}
protected async pull(
sketch: Create.Sketch
): Promise<CloudSketchbookTree.CloudSketchDirNode | undefined> {
const treeModel = await this.treeModel();
if (!treeModel) {
return undefined;
}
const id = CreateUri.toUri(sketch).path.toString();
const node = treeModel.getNode(id);
if (!node) {
throw new Error(
`Could not find cloud sketchbook tree node with ID: ${id}.`
);
}
if (!CloudSketchbookTree.CloudSketchDirNode.is(node)) {
throw new Error(
`Cloud sketchbook tree node expected to represent a directory but it did not. Tree node ID: ${id}.`
);
}
try {
await treeModel.sketchbookTree().pull({ node }, true);
return node;
} catch (err) {
if (isNotFound(err)) {
await treeModel.refresh();
this.messageService.error(sketchNotFound(sketch.name));
return undefined;
}
throw err;
}
}
private treeModelFrom(
widget: SketchbookWidget
): CloudSketchbookTreeModel | undefined {
for (const treeWidget of widget.getTreeWidgets()) {
if (treeWidget instanceof CloudSketchbookTreeWidget) {
const model = treeWidget.model;
if (model instanceof CloudSketchbookTreeModel) {
return model;
}
}
}
return undefined;
}
}

View File

@@ -4,11 +4,13 @@ import {
Disposable,
DisposableCollection,
Emitter,
MaybeArray,
MaybePromise,
nls,
notEmpty,
} from '@theia/core';
import { ApplicationShell, FrontendApplication } from '@theia/core/lib/browser';
import { ITextModel } from '@theia/monaco-editor-core/esm/vs/editor/common/model';
import URI from '@theia/core/lib/common/uri';
import { inject, injectable } from '@theia/core/shared/inversify';
import {
@@ -28,14 +30,15 @@ import * as monaco from '@theia/monaco-editor-core';
import { MonacoEditor } from '@theia/monaco/lib/browser/monaco-editor';
import { MonacoToProtocolConverter } from '@theia/monaco/lib/browser/monaco-to-protocol-converter';
import { ProtocolToMonacoConverter } from '@theia/monaco/lib/browser/protocol-to-monaco-converter';
import { OutputUri } from '@theia/output/lib/common/output-uri';
import { CoreError } from '../../common/protocol/core-service';
import { ErrorRevealStrategy } from '../arduino-preferences';
import { InoSelector } from '../ino-selectors';
import { fullRange } from '../utils/monaco';
import { ArduinoOutputSelector, InoSelector } from '../selectors';
import { Contribution } from './contribution';
import { CoreErrorHandler } from './core-error-handler';
import { MonacoEditorModel } from '@theia/monaco/lib/browser/monaco-editor-model';
interface ErrorDecoration {
interface ErrorDecorationRef {
/**
* This is the unique ID of the decoration given by `monaco`.
*/
@@ -45,72 +48,89 @@ interface ErrorDecoration {
*/
readonly uri: string;
}
namespace ErrorDecoration {
export function rangeOf(
{ id, uri }: ErrorDecoration,
editorProvider: (uri: string) => Promise<MonacoEditor | undefined>
): Promise<monaco.Range | undefined>;
export function rangeOf(
{ id, uri }: ErrorDecoration,
editorProvider: MonacoEditor
): monaco.Range | undefined;
export function rangeOf(
{ id, uri }: ErrorDecoration,
editorProvider:
| ((uri: string) => Promise<MonacoEditor | undefined>)
| MonacoEditor
): MaybePromise<monaco.Range | undefined> {
if (editorProvider instanceof MonacoEditor) {
const control = editorProvider.getControl();
const model = control.getModel();
if (model) {
return control
.getDecorationsInRange(fullRange(model))
?.find(({ id: candidateId }) => id === candidateId)?.range;
}
return undefined;
export namespace ErrorDecorationRef {
export function is(arg: unknown): arg is ErrorDecorationRef {
if (typeof arg === 'object') {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const object = arg as any;
return (
'uri' in object &&
typeof object['uri'] === 'string' &&
'id' in object &&
typeof object['id'] === 'string'
);
}
return editorProvider(uri).then((editor) => {
if (editor) {
return rangeOf({ id, uri }, editor);
}
return undefined;
});
return false;
}
// export async function rangeOf(
// { id, uri }: ErrorDecoration,
// editorProvider:
// | ((uri: string) => Promise<MonacoEditor | undefined>)
// | MonacoEditor
// ): Promise<monaco.Range | undefined> {
// const editor =
// editorProvider instanceof MonacoEditor
// ? editorProvider
// : await editorProvider(uri);
// if (editor) {
// const control = editor.getControl();
// const model = control.getModel();
// if (model) {
// return control
// .getDecorationsInRange(fullRange(model))
// ?.find(({ id: candidateId }) => id === candidateId)?.range;
// }
// }
// return undefined;
// }
export function sameAs(
left: ErrorDecoration,
right: ErrorDecoration
left: ErrorDecorationRef,
right: ErrorDecorationRef
): boolean {
return left.id === right.id && left.uri === right.uri;
}
}
interface ErrorDecoration extends ErrorDecorationRef {
/**
* The range of the error location the error in the compiler output from the CLI.
*/
readonly rangesInOutput: monaco.Range[];
}
namespace ErrorDecoration {
export function rangeOf(
editorOrModel: MonacoEditor | ITextModel | undefined,
decorations: ErrorDecoration
): monaco.Range | undefined;
export function rangeOf(
editorOrModel: MonacoEditor | ITextModel | undefined,
decorations: ErrorDecoration[]
): (monaco.Range | undefined)[];
export function rangeOf(
editorOrModel: MonacoEditor | ITextModel | undefined,
decorations: ErrorDecoration | ErrorDecoration[]
): MaybePromise<MaybeArray<monaco.Range | undefined>> {
if (editorOrModel) {
const allDecorations = getAllDecorations(editorOrModel);
if (allDecorations) {
if (Array.isArray(decorations)) {
return decorations.map(({ id: decorationId }) =>
findRangeOf(decorationId, allDecorations)
);
} else {
return findRangeOf(decorations.id, allDecorations);
}
}
}
return Array.isArray(decorations)
? decorations.map(() => undefined)
: undefined;
}
function findRangeOf(
decorationId: string,
allDecorations: { id: string; range?: monaco.Range }[]
): monaco.Range | undefined {
return allDecorations.find(
({ id: candidateId }) => candidateId === decorationId
)?.range;
}
function getAllDecorations(
editorOrModel: MonacoEditor | ITextModel
): { id: string; range?: monaco.Range }[] {
if (editorOrModel instanceof MonacoEditor) {
const model = editorOrModel.getControl().getModel();
if (!model) {
return [];
}
return model.getAllDecorations();
}
return editorOrModel.getAllDecorations();
}
}
@injectable()
export class CompilerErrors
extends Contribution
implements monaco.languages.CodeLensProvider
implements monaco.languages.CodeLensProvider, monaco.languages.LinkProvider
{
@inject(EditorManager)
private readonly editorManager: EditorManager;
@@ -119,11 +139,14 @@ export class CompilerErrors
private readonly p2m: ProtocolToMonacoConverter;
@inject(MonacoToProtocolConverter)
private readonly mp2: MonacoToProtocolConverter;
private readonly m2p: MonacoToProtocolConverter;
@inject(CoreErrorHandler)
private readonly coreErrorHandler: CoreErrorHandler;
private revealStrategy = ErrorRevealStrategy.Default;
private experimental = false;
private readonly errors: ErrorDecoration[] = [];
private readonly onDidChangeEmitter = new monaco.Emitter<this>();
private readonly currentErrorDidChangEmitter = new Emitter<ErrorDecoration>();
@@ -131,8 +154,8 @@ export class CompilerErrors
this.currentErrorDidChangEmitter.event;
private readonly toDisposeOnCompilerErrorDidChange =
new DisposableCollection();
private shell: ApplicationShell | undefined;
private revealStrategy = ErrorRevealStrategy.Default;
private currentError: ErrorDecoration | undefined;
private get currentErrorIndex(): number {
const current = this.currentError;
@@ -140,46 +163,75 @@ export class CompilerErrors
return -1;
}
return this.errors.findIndex((error) =>
ErrorDecoration.sameAs(error, current)
ErrorDecorationRef.sameAs(error, current)
);
}
override onStart(app: FrontendApplication): void {
this.shell = app.shell;
monaco.languages.registerCodeLensProvider(InoSelector, this);
monaco.languages.registerLinkProvider(ArduinoOutputSelector, this);
this.coreErrorHandler.onCompilerErrorsDidChange((errors) =>
this.filter(errors).then(this.handleCompilerErrorsDidChange.bind(this))
this.handleCompilerErrorsDidChange(errors)
);
this.onCurrentErrorDidChange(async (error) => {
const range = await ErrorDecoration.rangeOf(error, (uri) =>
this.monacoEditor(uri)
);
if (!range) {
const monacoEditor = await this.monacoEditor(error.uri);
const monacoRange = ErrorDecoration.rangeOf(monacoEditor, error);
if (!monacoRange) {
console.warn(
'compiler-errors',
`Could not find range of decoration: ${error.id}`
);
return;
}
const range = this.m2p.asRange(monacoRange);
const editor = await this.revealLocationInEditor({
uri: error.uri,
range: this.mp2.asRange(range),
range,
});
if (!editor) {
console.warn(
'compiler-errors',
`Failed to mark error ${error.id} as the current one.`
);
} else {
const monacoEditor = this.monacoEditor(editor);
if (monacoEditor) {
monacoEditor.cursor = range.start;
}
}
});
}
override onReady(): MaybePromise<void> {
this.preferences.ready.then(() => {
this.preferences.onPreferenceChanged(({ preferenceName, newValue }) => {
if (preferenceName === 'arduino.compile.revealRange') {
this.revealStrategy = ErrorRevealStrategy.is(newValue)
? newValue
: ErrorRevealStrategy.Default;
this.experimental = Boolean(
this.preferences['arduino.compile.experimental']
);
const strategy = this.preferences['arduino.compile.revealRange'];
this.revealStrategy = ErrorRevealStrategy.is(strategy)
? strategy
: ErrorRevealStrategy.Default;
this.preferences.onPreferenceChanged(
({ preferenceName, newValue, oldValue }) => {
if (newValue === oldValue) {
return;
}
switch (preferenceName) {
case 'arduino.compile.revealRange': {
this.revealStrategy = ErrorRevealStrategy.is(newValue)
? newValue
: ErrorRevealStrategy.Default;
return;
}
case 'arduino.compile.experimental': {
this.experimental = Boolean(newValue);
this.onDidChangeEmitter.fire(this);
return;
}
}
}
});
);
});
}
@@ -196,9 +248,13 @@ export class CompilerErrors
}
const nextError =
this.errors[index === this.errors.length - 1 ? 0 : index + 1];
this.markAsCurrentError(nextError);
return this.markAsCurrentError(nextError, {
forceReselect: true,
reveal: true,
});
},
isEnabled: () => !!this.currentError && this.errors.length > 1,
isEnabled: () =>
this.experimental && !!this.currentError && this.errors.length > 1,
});
registry.registerCommand(CompilerErrors.Commands.PREVIOUS_ERROR, {
execute: () => {
@@ -212,9 +268,24 @@ export class CompilerErrors
}
const previousError =
this.errors[index === 0 ? this.errors.length - 1 : index - 1];
this.markAsCurrentError(previousError);
return this.markAsCurrentError(previousError, {
forceReselect: true,
reveal: true,
});
},
isEnabled: () => !!this.currentError && this.errors.length > 1,
isEnabled: () =>
this.experimental && !!this.currentError && this.errors.length > 1,
});
registry.registerCommand(CompilerErrors.Commands.MARK_AS_CURRENT, {
execute: (arg: unknown) => {
if (ErrorDecorationRef.is(arg)) {
return this.markAsCurrentError(
{ id: arg.id, uri: new URI(arg.uri).toString() }, // Make sure the URI fragments are encoded. On Windows, `C:` is encoded as `C%3A`.
{ forceReselect: true, reveal: true }
);
}
},
isEnabled: () => !!this.errors.length,
});
}
@@ -229,13 +300,13 @@ export class CompilerErrors
): Promise<monaco.languages.CodeLensList> {
const lenses: monaco.languages.CodeLens[] = [];
if (
this.experimental &&
this.currentError &&
this.currentError.uri === model.uri.toString() &&
this.errors.length > 1
) {
const range = await ErrorDecoration.rangeOf(this.currentError, (uri) =>
this.monacoEditor(uri)
);
const monacoEditor = await this.monacoEditor(model.uri);
const range = ErrorDecoration.rangeOf(monacoEditor, this.currentError);
if (range) {
lenses.push(
{
@@ -268,14 +339,81 @@ export class CompilerErrors
};
}
async provideLinks(
model: monaco.editor.ITextModel,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_token: monaco.CancellationToken
): Promise<monaco.languages.ILinksList> {
const links: monaco.languages.ILink[] = [];
if (
model.uri.scheme === OutputUri.SCHEME &&
model.uri.path === '/Arduino'
) {
links.push(
...this.errors
.filter((decoration) => !!decoration.rangesInOutput.length)
.map(({ rangesInOutput, id, uri }) =>
rangesInOutput.map(
(range) =>
<monaco.languages.ILink>{
range,
url: monaco.Uri.parse(`command://`).with({
query: JSON.stringify({ id, uri }),
path: CompilerErrors.Commands.MARK_AS_CURRENT.id,
}),
tooltip: nls.localize(
'arduino/editor/revealError',
'Reveal Error'
),
}
)
)
.reduce((acc, curr) => acc.concat(curr), [])
);
} else {
console.warn('unexpected URI: ' + model.uri.toString());
}
return { links };
}
async resolveLink(
link: monaco.languages.ILink,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_token: monaco.CancellationToken
): Promise<monaco.languages.ILink | undefined> {
if (!this.experimental) {
return undefined;
}
const { url } = link;
if (url) {
const candidateUri = new URI(
typeof url === 'string' ? url : url.toString()
);
const candidateId = candidateUri.path.toString();
const error = this.errors.find((error) => error.id === candidateId);
if (error) {
const monacoEditor = await this.monacoEditor(error.uri);
const range = ErrorDecoration.rangeOf(monacoEditor, error);
if (range) {
return {
range,
url: monaco.Uri.parse(error.uri),
};
}
}
}
return undefined;
}
private async handleCompilerErrorsDidChange(
errors: CoreError.ErrorLocation[]
): Promise<void> {
this.toDisposeOnCompilerErrorDidChange.dispose();
const compilerErrorsPerResource = this.groupByResource(
await this.filter(errors)
const groupedErrors = this.groupBy(
errors,
(error: CoreError.ErrorLocation) => error.location.uri
);
const decorations = await this.decorateEditors(compilerErrorsPerResource);
const decorations = await this.decorateEditors(groupedErrors);
this.errors.push(...decorations.errors);
this.toDisposeOnCompilerErrorDidChange.pushAll([
Disposable.create(() => (this.errors.length = 0)),
@@ -283,17 +421,17 @@ export class CompilerErrors
...(await Promise.all([
decorations.dispose,
this.trackEditors(
compilerErrorsPerResource,
groupedErrors,
(editor) =>
editor.editor.onSelectionChanged((selection) =>
editor.onSelectionChanged((selection) =>
this.handleSelectionChange(editor, selection)
),
(editor) =>
editor.onDidDispose(() =>
this.handleEditorDidDispose(editor.editor.uri.toString())
editor.onDispose(() =>
this.handleEditorDidDispose(editor.uri.toString())
),
(editor) =>
editor.editor.onDocumentContentChanged((event) =>
editor.onDocumentContentChanged((event) =>
this.handleDocumentContentChange(editor, event)
)
),
@@ -301,24 +439,13 @@ export class CompilerErrors
]);
const currentError = this.errors[0];
if (currentError) {
await this.markAsCurrentError(currentError);
await this.markAsCurrentError(currentError, {
forceReselect: true,
reveal: true,
});
}
}
private async filter(
errors: CoreError.ErrorLocation[]
): Promise<CoreError.ErrorLocation[]> {
if (!errors.length) {
return [];
}
await this.preferences.ready;
if (this.preferences['arduino.compile.experimental']) {
return errors;
}
// Always shows maximum one error; hence the code lens navigation is unavailable.
return [errors[0]];
}
private async decorateEditors(
errors: Map<string, CoreError.ErrorLocation[]>
): Promise<{ dispose: Disposable; errors: ErrorDecoration[] }> {
@@ -342,11 +469,11 @@ export class CompilerErrors
uri: string,
errors: CoreError.ErrorLocation[]
): Promise<{ dispose: Disposable; errors: ErrorDecoration[] }> {
const editor = await this.editorManager.getByUri(new URI(uri));
const editor = await this.monacoEditor(uri);
if (!editor) {
return { dispose: Disposable.NULL, errors: [] };
}
const oldDecorations = editor.editor.deltaDecorations({
const oldDecorations = editor.deltaDecorations({
oldDecorations: [],
newDecorations: errors.map((error) =>
this.compilerErrorDecoration(error.location.range)
@@ -355,13 +482,19 @@ export class CompilerErrors
return {
dispose: Disposable.create(() => {
if (editor) {
editor.editor.deltaDecorations({
editor.deltaDecorations({
oldDecorations,
newDecorations: [],
});
}
}),
errors: oldDecorations.map((id) => ({ id, uri })),
errors: oldDecorations.map((id, index) => ({
id,
uri,
rangesInOutput: errors[index].rangesInOutput.map((range) =>
this.p2m.asRange(range)
),
})),
};
}
@@ -371,7 +504,7 @@ export class CompilerErrors
options: {
isWholeLine: true,
className: 'compiler-error',
stickiness: TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges,
stickiness: TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
},
};
}
@@ -379,11 +512,10 @@ export class CompilerErrors
/**
* Tracks the selection in all editors that have an error. If the editor selection overlaps one of the compiler error's range, mark as current error.
*/
private handleSelectionChange(editor: EditorWidget, selection: Range): void {
const monacoEditor = this.monacoEditor(editor);
if (!monacoEditor) {
return;
}
private handleSelectionChange(
monacoEditor: MonacoEditor,
selection: Range
): void {
const uri = monacoEditor.uri.toString();
const monacoSelection = this.p2m.asRange(selection);
console.log(
@@ -418,12 +550,13 @@ export class CompilerErrors
console.trace('No match');
return undefined;
};
const error = this.errors
.filter((error) => error.uri === uri)
.map((error) => ({
error,
range: ErrorDecoration.rangeOf(error, monacoEditor),
}))
const errorsPerResource = this.errors.filter((error) => error.uri === uri);
const rangesPerResource = ErrorDecoration.rangeOf(
monacoEditor,
errorsPerResource
);
const error = rangesPerResource
.map((range, index) => ({ error: errorsPerResource[index], range }))
.map(({ error, range }) => {
if (range) {
const priority = calculatePriority(range, monacoSelection);
@@ -464,66 +597,77 @@ export class CompilerErrors
}
/**
* If a document change "destroys" the range of the decoration, the decoration must be removed.
* If the text document changes in the line where compiler errors are, the compiler errors will be removed.
*/
private handleDocumentContentChange(
editor: EditorWidget,
monacoEditor: MonacoEditor,
event: TextDocumentChangeEvent
): void {
const monacoEditor = this.monacoEditor(editor);
if (!monacoEditor) {
return;
}
// A decoration location can be "destroyed", hence should be deleted when:
// - deleting range (start != end AND text is empty)
// - inserting text into range (start != end AND text is not empty)
// Filter unrelated delta changes to spare the CPU.
const relevantChanges = event.contentChanges.filter(
({ range: { start, end } }) =>
start.line !== end.line || start.character !== end.character
const errorsPerResource = this.errors.filter(
(error) => error.uri === event.document.uri
);
if (!relevantChanges.length) {
return;
let editorOrModel: MonacoEditor | ITextModel = monacoEditor;
const doc = event.document;
if (doc instanceof MonacoEditorModel) {
editorOrModel = doc.textEditorModel;
}
const resolvedMarkers = this.errors
.filter((error) => error.uri === event.document.uri)
.map((error, index) => {
const range = ErrorDecoration.rangeOf(error, monacoEditor);
if (range) {
return { error, range, index };
}
return undefined;
})
.filter(notEmpty);
const decorationIdsToRemove = relevantChanges
const rangesPerResource = ErrorDecoration.rangeOf(
editorOrModel,
errorsPerResource
);
const resolvedDecorations = rangesPerResource.map((range, index) => ({
error: errorsPerResource[index],
range,
}));
const decoratorsToRemove = event.contentChanges
.map(({ range }) => this.p2m.asRange(range))
.map((changeRange) =>
resolvedMarkers.filter(({ range: decorationRange }) =>
changeRange.containsRange(decorationRange)
)
.map((changedRange) =>
resolvedDecorations
.filter(({ range: decorationRange }) => {
if (!decorationRange) {
return false;
}
const affects =
changedRange.startLineNumber <= decorationRange.startLineNumber &&
changedRange.endLineNumber >= decorationRange.endLineNumber;
console.log(
'compiler-errors',
`decoration range: ${decorationRange.toString()}, change range: ${changedRange.toString()}, affects: ${affects}`
);
return affects;
})
.map(({ error }) => {
const index = this.errors.findIndex((candidate) =>
ErrorDecorationRef.sameAs(candidate, error)
);
return index !== -1 ? { error, index } : undefined;
})
.filter(notEmpty)
)
.reduce((acc, curr) => acc.concat(curr), [])
.map(({ error, index }) => {
this.errors.splice(index, 1);
return error.id;
});
if (!decorationIdsToRemove.length) {
return;
.sort((left, right) => left.index - right.index); // highest index last
if (decoratorsToRemove.length) {
let i = decoratorsToRemove.length;
while (i--) {
this.errors.splice(decoratorsToRemove[i].index, 1);
}
monacoEditor.getControl().deltaDecorations(
decoratorsToRemove.map(({ error }) => error.id),
[]
);
this.onDidChangeEmitter.fire(this);
}
monacoEditor.getControl().deltaDecorations(decorationIdsToRemove, []);
this.onDidChangeEmitter.fire(this);
}
private async trackEditors(
errors: Map<string, CoreError.ErrorLocation[]>,
...track: ((editor: EditorWidget) => Disposable)[]
...track: ((editor: MonacoEditor) => Disposable)[]
): Promise<Disposable> {
return new DisposableCollection(
...(await Promise.all(
Array.from(errors.keys()).map(async (uri) => {
const editor = await this.editorManager.getByUri(new URI(uri));
const editor = await this.monacoEditor(uri);
if (!editor) {
return Disposable.NULL;
}
@@ -533,15 +677,18 @@ export class CompilerErrors
);
}
private async markAsCurrentError(error: ErrorDecoration): Promise<void> {
private async markAsCurrentError(
ref: ErrorDecorationRef,
options?: { forceReselect?: boolean; reveal?: boolean }
): Promise<void> {
const index = this.errors.findIndex((candidate) =>
ErrorDecoration.sameAs(candidate, error)
ErrorDecorationRef.sameAs(candidate, ref)
);
if (index < 0) {
console.warn(
'compiler-errors',
`Failed to mark error ${
error.id
ref.id
} as the current one. Error is unknown. Known errors are: ${this.errors.map(
({ id }) => id
)}`
@@ -550,15 +697,18 @@ export class CompilerErrors
}
const newError = this.errors[index];
if (
options?.forceReselect ||
!this.currentError ||
!ErrorDecoration.sameAs(this.currentError, newError)
!ErrorDecorationRef.sameAs(this.currentError, newError)
) {
this.currentError = this.errors[index];
console.log(
'compiler-errors',
`Current error changed to ${this.currentError.id}`
);
this.currentErrorDidChangEmitter.fire(this.currentError);
if (options?.reveal) {
this.currentErrorDidChangEmitter.fire(this.currentError);
}
this.onDidChangeEmitter.fire(this);
}
}
@@ -593,32 +743,33 @@ export class CompilerErrors
}
console.warn(
'compiler-errors',
`could not found editor widget for URI: ${uri}`
`could not find editor widget for URI: ${uri}`
);
return undefined;
}
private groupByResource(
errors: CoreError.ErrorLocation[]
): Map<string, CoreError.ErrorLocation[]> {
return errors.reduce((acc, curr) => {
const {
location: { uri },
} = curr;
let errors = acc.get(uri);
if (!errors) {
errors = [];
acc.set(uri, errors);
private groupBy<K, V>(
elements: V[],
extractKey: (element: V) => K
): Map<K, V[]> {
return elements.reduce((acc, curr) => {
const key = extractKey(curr);
let values = acc.get(key);
if (!values) {
values = [];
acc.set(key, values);
}
errors.push(curr);
values.push(curr);
return acc;
}, new Map<string, CoreError.ErrorLocation[]>());
}, new Map<K, V[]>());
}
private monacoEditor(widget: EditorWidget): MonacoEditor | undefined;
private monacoEditor(uri: string): Promise<MonacoEditor | undefined>;
private monacoEditor(
uriOrWidget: string | EditorWidget
uri: string | monaco.Uri
): Promise<MonacoEditor | undefined>;
private monacoEditor(
uriOrWidget: string | monaco.Uri | EditorWidget
): MaybePromise<MonacoEditor | undefined> {
if (uriOrWidget instanceof EditorWidget) {
const editor = uriOrWidget.editor;
@@ -646,5 +797,8 @@ export namespace CompilerErrors {
export const PREVIOUS_ERROR: Command = {
id: 'arduino-editor-previous-error',
};
export const MARK_AS_CURRENT: Command = {
id: 'arduino-editor-mark-as-current-error',
};
}
}

View File

@@ -6,15 +6,18 @@ import {
} from '@theia/core/shared/inversify';
import URI from '@theia/core/lib/common/uri';
import { ILogger } from '@theia/core/lib/common/logger';
import {
Disposable,
DisposableCollection,
} from '@theia/core/lib/common/disposable';
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 { EnvVariablesServer } from '@theia/core/lib/common/env-variables';
import { open, OpenerService } from '@theia/core/lib/browser/opener-service';
import {
MenuModelRegistry,
MenuContribution,
@@ -41,10 +44,9 @@ import { SettingsService } from '../dialogs/settings/settings';
import {
CurrentSketch,
SketchesServiceClientImpl,
} from '../../common/protocol/sketches-service-client-impl';
} from '../sketches-service-client-impl';
import {
SketchesService,
ConfigService,
FileSystemExt,
Sketch,
CoreService,
@@ -59,6 +61,14 @@ import { ClipboardService } from '@theia/core/lib/browser/clipboard-service';
import { ExecuteWithProgress } from '../../common/protocol/progressible';
import { BoardsServiceProvider } from '../boards/boards-service-provider';
import { BoardsDataStore } from '../boards/boards-data-store';
import { NotificationManager } from '@theia/messages/lib/browser/notifications-manager';
import { MessageType } from '@theia/core/lib/common/message-service-protocol';
import { WorkspaceService } from '../theia/workspace/workspace-service';
import { MainMenuManager } from '../../common/main-menu-manager';
import { ConfigServiceClient } from '../config/config-service-client';
import { ApplicationShell } from '@theia/core/lib/browser/shell/application-shell';
import { DialogService } from '../dialog-service';
import { ApplicationConnectionStatusContribution } from '../theia/core/connection-status-service';
export {
Command,
@@ -104,6 +114,12 @@ export abstract class Contribution
@inject(FrontendApplicationStateService)
protected readonly appStateService: FrontendApplicationStateService;
@inject(MainMenuManager)
protected readonly menuManager: MainMenuManager;
@inject(DialogService)
protected readonly dialogService: DialogService;
@postConstruct()
protected init(): void {
this.appStateService.reachedState('ready').then(() => this.onReady());
@@ -136,11 +152,11 @@ export abstract class SketchContribution extends Contribution {
@inject(FileSystemExt)
protected readonly fileSystemExt: FileSystemExt;
@inject(ConfigService)
protected readonly configService: ConfigService;
@inject(ConfigServiceClient)
protected readonly configService: ConfigServiceClient;
@inject(SketchesService)
protected readonly sketchService: SketchesService;
protected readonly sketchesService: SketchesService;
@inject(OpenerService)
protected readonly openerService: OpenerService;
@@ -154,6 +170,12 @@ export abstract class SketchContribution extends Contribution {
@inject(OutputChannelManager)
protected readonly outputChannelManager: OutputChannelManager;
@inject(EnvVariablesServer)
protected readonly envVariableServer: EnvVariablesServer;
@inject(ApplicationConnectionStatusContribution)
protected readonly connectionStatusService: ApplicationConnectionStatusContribution;
protected async sourceOverride(): Promise<Record<string, string>> {
const override: Record<string, string> = {};
const sketch = await this.sketchServiceClient.currentSketch();
@@ -167,6 +189,25 @@ export abstract class SketchContribution extends Contribution {
}
return override;
}
/**
* Defaults to `directories.user` if defined and not CLI config errors were detected.
* Otherwise, the URI of the user home directory.
*/
protected async defaultUri(): Promise<URI> {
const errors = this.configService.tryGetMessages();
let defaultUri = this.configService.tryGetSketchDirUri();
if (!defaultUri || errors?.length) {
// Fall back to user home when the `directories.user` is not available or there are known CLI config errors
defaultUri = new URI(await this.envVariableServer.getHomeDirUri());
}
return defaultUri;
}
protected async defaultPath(): Promise<string> {
const defaultUri = await this.defaultUri();
return this.fileService.fsPath(defaultUri);
}
}
@injectable()
@@ -186,6 +227,25 @@ export abstract class CoreServiceContribution extends SketchContribution {
@inject(ResponseServiceClient)
private readonly responseService: ResponseServiceClient;
@inject(NotificationManager)
private readonly notificationManager: NotificationManager;
@inject(ApplicationShell)
private readonly shell: ApplicationShell;
/**
* This is the internal (Theia) ID of the notification that is currently visible.
* It's stored here as a field to be able to close it before executing any new core command (such as verify, upload, etc.)
*/
private visibleNotificationId: string | undefined;
protected clearVisibleNotification(): void {
if (this.visibleNotificationId) {
this.notificationManager.clear(this.visibleNotificationId);
this.visibleNotificationId = undefined;
}
}
protected handleError(error: unknown): void {
this.tryToastErrorMessage(error);
}
@@ -204,10 +264,17 @@ export abstract class CoreServiceContribution extends SketchContribution {
} catch {}
}
if (message) {
if (message.includes('Missing FQBN (Fully Qualified Board Name)')) {
message = nls.localize(
'arduino/coreContribution/noBoardSelected',
'No board selected. Please select your Arduino board from the Tools > Board menu.'
);
}
const copyAction = nls.localize(
'arduino/coreContribution/copyError',
'Copy error messages'
);
this.visibleNotificationId = this.notificationId(message, copyAction);
this.messageService.error(message, copyAction).then(async (action) => {
if (action === copyAction) {
const content = await this.outputChannelManager.contentOfChannel(
@@ -228,6 +295,9 @@ export abstract class CoreServiceContribution extends SketchContribution {
keepOutput?: boolean;
task: (progressId: string, coreService: CoreService) => Promise<T>;
}): Promise<T> {
const toDisposeOnComplete = new DisposableCollection(
this.maybeActivateMonitorWidget()
);
const { progressText, keepOutput, task } = options;
this.outputChannelManager
.getChannel('Arduino')
@@ -239,8 +309,31 @@ export abstract class CoreServiceContribution extends SketchContribution {
run: ({ progressId }) => task(progressId, this.coreService),
keepOutput,
});
toDisposeOnComplete.dispose();
return result;
}
// TODO: cleanup!
// this dependency does not belong here
// support core command contribution handlers, the monitor-widget should implement it and register itself as a handler
// the monitor widget should reveal itself after a successful core command execution
private maybeActivateMonitorWidget(): Disposable {
const currentWidget = this.shell.bottomPanel.currentTitle?.owner;
if (currentWidget?.id === 'serial-monitor') {
return Disposable.create(() =>
this.shell.bottomPanel.activateWidget(currentWidget)
);
}
return Disposable.NULL;
}
private notificationId(message: string, ...actions: string[]): string {
return this.notificationManager['getMessageId']({
text: message,
actions,
type: MessageType.Error,
});
}
}
export namespace Contribution {

View File

@@ -0,0 +1,118 @@
import { FrontendApplication } from '@theia/core/lib/browser/frontend-application';
import { ApplicationShell } from '@theia/core/lib/browser/shell';
import type { Command, CommandRegistry } from '@theia/core/lib/common/command';
import { Progress } from '@theia/core/lib/common/message-service-protocol';
import { nls } from '@theia/core/lib/common/nls';
import { inject, injectable } from '@theia/core/shared/inversify';
import { Create } from '../create/typings';
import { ApplicationConnectionStatusContribution } from '../theia/core/connection-status-service';
import { CloudSketchbookTree } from '../widgets/cloud-sketchbook/cloud-sketchbook-tree';
import { SketchbookTree } from '../widgets/sketchbook/sketchbook-tree';
import { SketchbookTreeModel } from '../widgets/sketchbook/sketchbook-tree-model';
import { CloudSketchContribution, pushingSketch } from './cloud-contribution';
import {
CreateNewCloudSketchCallback,
NewCloudSketch,
NewCloudSketchParams,
} from './new-cloud-sketch';
import { saveOntoCopiedSketch } from './save-as-sketch';
interface CreateCloudCopyParams {
readonly model: SketchbookTreeModel;
readonly node: SketchbookTree.SketchDirNode;
}
function isCreateCloudCopyParams(arg: unknown): arg is CreateCloudCopyParams {
return (
typeof arg === 'object' &&
(<CreateCloudCopyParams>arg).model !== undefined &&
(<CreateCloudCopyParams>arg).model instanceof SketchbookTreeModel &&
(<CreateCloudCopyParams>arg).node !== undefined &&
SketchbookTree.SketchDirNode.is((<CreateCloudCopyParams>arg).node)
);
}
@injectable()
export class CreateCloudCopy extends CloudSketchContribution {
@inject(ApplicationConnectionStatusContribution)
private readonly connectionStatus: ApplicationConnectionStatusContribution;
private shell: ApplicationShell;
override onStart(app: FrontendApplication): void {
this.shell = app.shell;
}
override registerCommands(registry: CommandRegistry): void {
registry.registerCommand(CreateCloudCopy.Commands.CREATE_CLOUD_COPY, {
execute: (args: CreateCloudCopyParams) => this.createCloudCopy(args),
isEnabled: (args: unknown) =>
Boolean(this.createFeatures.session) && isCreateCloudCopyParams(args),
isVisible: (args: unknown) =>
Boolean(this.createFeatures.enabled) &&
Boolean(this.createFeatures.session) &&
this.connectionStatus.offlineStatus !== 'internet' &&
isCreateCloudCopyParams(args),
});
}
/**
* - creates new cloud sketch with the name of the params sketch,
* - pulls the cloud sketch,
* - copies files from params sketch to pulled cloud sketch in the cache folder,
* - pushes the cloud sketch, and
* - opens in new window.
*/
private async createCloudCopy(params: CreateCloudCopyParams): Promise<void> {
const sketch = await this.sketchesService.loadSketch(
params.node.fileStat.resource.toString()
);
const callback: CreateNewCloudSketchCallback = async (
newSketch: Create.Sketch,
newNode: CloudSketchbookTree.CloudSketchDirNode,
progress: Progress
) => {
const treeModel = await this.treeModel();
if (!treeModel) {
throw new Error('Could not retrieve the cloud sketchbook tree model.');
}
progress.report({
message: nls.localize(
'arduino/createCloudCopy/copyingSketchFilesMessage',
'Copying local sketch files...'
),
});
const localCacheFolderUri = newNode.uri.toString();
await this.sketchesService.copy(sketch, {
destinationUri: localCacheFolderUri,
onlySketchFiles: true,
});
await saveOntoCopiedSketch(
sketch,
localCacheFolderUri,
this.shell,
this.editorManager
);
progress.report({ message: pushingSketch(newSketch.name) });
await treeModel.sketchbookTree().push(newNode, true, true);
};
return this.commandService.executeCommand(
NewCloudSketch.Commands.NEW_CLOUD_SKETCH.id,
<NewCloudSketchParams>{
initialValue: params.node.fileStat.name,
callback,
skipShowErrorMessageOnOpen: false,
}
);
}
}
export namespace CreateCloudCopy {
export namespace Commands {
export const CREATE_CLOUD_COPY: Command = {
id: 'arduino-create-cloud-copy',
iconClass: 'fa fa-arduino-cloud-upload',
};
}
}

View File

@@ -3,7 +3,14 @@ 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 {
Board,
BoardIdentifier,
BoardsService,
ExecutableService,
isBoardIdentifierChangeEvent,
Sketch,
} from '../../common/protocol';
import { BoardsServiceProvider } from '../boards/boards-service-provider';
import {
URI,
@@ -13,12 +20,11 @@ import {
TabBarToolbarRegistry,
} from './contribution';
import { MaybePromise, MenuModelRegistry, nls } from '@theia/core/lib/common';
import { CurrentSketch } from '../../common/protocol/sketches-service-client-impl';
import { CurrentSketch } from '../sketches-service-client-impl';
import { ArduinoMenus } from '../menu/arduino-menus';
import { MainMenuManager } from '../../common/main-menu-manager';
const COMPILE_FOR_DEBUG_KEY = 'arduino-compile-for-debug';
@injectable()
export class Debug extends SketchContribution {
@inject(HostedPluginSupport)
@@ -36,9 +42,6 @@ export class Debug extends SketchContribution {
@inject(BoardsServiceProvider)
private readonly boardsServiceProvider: BoardsServiceProvider;
@inject(MainMenuManager)
private readonly mainMenuManager: MainMenuManager;
/**
* If `undefined`, debugging is enabled. Otherwise, the reason why it's disabled.
*/
@@ -87,9 +90,11 @@ export class Debug extends SketchContribution {
: Debug.Commands.START_DEBUGGING.label
}`)
);
this.boardsServiceProvider.onBoardsConfigChanged(({ selectedBoard }) =>
this.refreshState(selectedBoard)
);
this.boardsServiceProvider.onBoardsConfigDidChange((event) => {
if (isBoardIdentifierChangeEvent(event)) {
this.refreshState(event.selectedBoard);
}
});
this.notificationCenter.onPlatformDidInstall(() => this.refreshState());
this.notificationCenter.onPlatformDidUninstall(() => this.refreshState());
}
@@ -168,7 +173,7 @@ export class Debug extends SketchContribution {
}
private async startDebug(
board: Board | undefined = this.boardsServiceProvider.boardsConfig
board: BoardIdentifier | undefined = this.boardsServiceProvider.boardsConfig
.selectedBoard
): Promise<void> {
if (!board) {
@@ -186,7 +191,7 @@ export class Debug extends SketchContribution {
if (!CurrentSketch.isValid(sketch)) {
return;
}
const ideTempFolderUri = await this.sketchService.getIdeTempFolderUri(
const ideTempFolderUri = await this.sketchesService.getIdeTempFolderUri(
sketch
);
const [cliPath, sketchPath, configPath] = await Promise.all([
@@ -203,7 +208,28 @@ export class Debug extends SketchContribution {
sketchPath,
configPath,
};
return this.commandService.executeCommand('arduino.debug.start', config);
try {
await this.commandService.executeCommand('arduino.debug.start', config);
} catch (err) {
if (await this.isSketchNotVerifiedError(err, sketch)) {
const yes = nls.localize('vscode/extensionsUtils/yes', 'Yes');
const answer = await this.messageService.error(
nls.localize(
'arduino/debug/sketchIsNotCompiled',
"Sketch '{0}' must be verified before starting a debug session. Please verify the sketch and start debugging again. Do you want to verify the sketch now?",
sketch.name
),
yes
);
if (answer === yes) {
this.commandService.executeCommand('arduino-verify-sketch');
}
} else {
this.messageService.error(
err instanceof Error ? err.message : String(err)
);
}
}
}
get compileForDebug(): boolean {
@@ -215,7 +241,24 @@ export class Debug extends SketchContribution {
const oldState = this.compileForDebug;
const newState = !oldState;
window.localStorage.setItem(COMPILE_FOR_DEBUG_KEY, String(newState));
this.mainMenuManager.update();
this.menuManager.update();
}
private async isSketchNotVerifiedError(
err: unknown,
sketch: Sketch
): Promise<boolean> {
if (err instanceof Error) {
try {
const tempBuildPaths = await this.sketchesService.tempBuildPath(sketch);
return tempBuildPaths.some((tempBuildPath) =>
err.message.includes(tempBuildPath)
);
} catch {
return false;
}
}
return false;
}
}
export namespace Debug {

View File

@@ -0,0 +1,168 @@
import { Dialog } from '@theia/core/lib/browser/dialogs';
import { NavigatableWidget } from '@theia/core/lib/browser/navigatable-types';
import { ApplicationShell } from '@theia/core/lib/browser/shell/application-shell';
import { WindowService } from '@theia/core/lib/browser/window/window-service';
import { nls } from '@theia/core/lib/common/nls';
import type { MaybeArray } from '@theia/core/lib/common/types';
import URI from '@theia/core/lib/common/uri';
import type { Widget } from '@theia/core/shared/@phosphor/widgets';
import { inject, injectable } from '@theia/core/shared/inversify';
import { SketchesError } from '../../common/protocol';
import { Sketch } from '../contributions/contribution';
import { isNotFound } from '../create/typings';
import { Command, CommandRegistry } from './contribution';
import { CloudSketchContribution } from './cloud-contribution';
import { AppService } from '../app-service';
export interface DeleteSketchParams {
/**
* Either the URI of the sketch folder or the sketch to delete.
*/
readonly toDelete: string | Sketch;
/**
* If `true`, the currently opened sketch is expected to be deleted.
* Hence, the editors must be closed, the sketch will be scheduled
* for deletion, and the browser window will close or navigate away.
* If `false`, the sketch will be scheduled for deletion,
* but the current window remains open. If `force`, the window will
* navigate away, but IDE2 won't open any confirmation dialogs.
*/
readonly willNavigateAway?: boolean | 'force';
}
@injectable()
export class DeleteSketch extends CloudSketchContribution {
@inject(ApplicationShell)
private readonly shell: ApplicationShell;
@inject(WindowService)
private readonly windowService: WindowService;
@inject(AppService)
private readonly appService: AppService;
override registerCommands(registry: CommandRegistry): void {
registry.registerCommand(DeleteSketch.Commands.DELETE_SKETCH, {
execute: (params: DeleteSketchParams) => this.deleteSketch(params),
});
}
private async deleteSketch(params: DeleteSketchParams): Promise<void> {
const { toDelete, willNavigateAway } = params;
let sketch: Sketch;
if (typeof toDelete === 'string') {
const resolvedSketch = await this.loadSketch(toDelete);
if (!resolvedSketch) {
console.info(
`Failed to load the sketch. It was not found at '${toDelete}'. Skipping deletion.`
);
return;
}
sketch = resolvedSketch;
} else {
sketch = toDelete;
}
if (!willNavigateAway) {
this.scheduleDeletion(sketch);
return;
}
const cloudUri = this.createFeatures.cloudUri(sketch);
if (willNavigateAway !== 'force') {
const { response } = await this.dialogService.showMessageBox({
title: nls.localizeByDefault('Delete'),
type: 'question',
buttons: [Dialog.CANCEL, Dialog.OK],
message: cloudUri
? nls.localize(
'theia/workspace/deleteCloudSketch',
"The cloud sketch '{0}' will be permanently deleted from the Arduino servers and the local caches. This action is irreversible. Do you want to delete the current sketch?",
sketch.name
)
: nls.localize(
'theia/workspace/deleteCurrentSketch',
"The sketch '{0}' will be permanently deleted. This action is irreversible. Do you want to delete the current sketch?",
sketch.name
),
});
// cancel
if (response === 0) {
return;
}
}
if (cloudUri) {
const posixPath = cloudUri.path.toString();
const cloudSketch = this.createApi.sketchCache.getSketch(posixPath);
if (!cloudSketch) {
throw new Error(
`Cloud sketch with path '${posixPath}' was not cached. Cache: ${this.createApi.sketchCache.toString()}`
);
}
try {
// IDE2 cannot use DELETE directory as the server responses with HTTP 500 if it's missing.
// https://github.com/arduino/arduino-ide/issues/1825#issuecomment-1406301406
await this.createApi.deleteSketch(cloudSketch.path);
} catch (err) {
if (!isNotFound(err)) {
throw err;
} else {
console.info(
`Could not delete the cloud sketch with path '${posixPath}'. It does not exist.`
);
}
}
}
await Promise.all([
...Sketch.uris(sketch).map((uri) =>
this.closeWithoutSaving(new URI(uri))
),
]);
this.windowService.setSafeToShutDown();
this.scheduleDeletion(sketch);
return window.close();
}
private scheduleDeletion(sketch: Sketch): void {
this.appService.scheduleDeletion(sketch);
}
private async loadSketch(uri: string): Promise<Sketch | undefined> {
try {
const sketch = await this.sketchesService.loadSketch(uri);
return sketch;
} catch (err) {
if (SketchesError.NotFound.is(err)) {
return undefined;
}
throw err;
}
}
// fix: https://github.com/eclipse-theia/theia/issues/12107
private async closeWithoutSaving(uri: URI): Promise<void> {
const affected = getAffected(this.shell.widgets, uri);
const toClose = [...affected].map(([, widget]) => widget);
await this.shell.closeMany(toClose, { save: false });
}
}
export namespace DeleteSketch {
export namespace Commands {
export const DELETE_SKETCH: Command = {
id: 'arduino-delete-sketch',
};
}
}
function getAffected<T extends Widget>(
widgets: Iterable<T>,
context: MaybeArray<URI>
): [URI, T & NavigatableWidget][] {
const uris = Array.isArray(context) ? context : [context];
const result: [URI, T & NavigatableWidget][] = [];
for (const widget of widgets) {
if (NavigatableWidget.is(widget)) {
const resourceUri = widget.getResourceUri();
if (resourceUri && uris.some((uri) => uri.isEqualOrParent(resourceUri))) {
result.push([resourceUri, widget]);
}
}
}
return result;
}

View File

@@ -49,30 +49,6 @@ export class EditContributions extends Contribution {
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') }
@@ -81,9 +57,11 @@ export class EditContributions extends Contribution {
execute: async () => {
const value = await this.currentValue();
if (value !== undefined) {
this.clipboardService.writeText(`\`\`\`cpp
this.clipboardService.writeText(`
\`\`\`cpp
${value}
\`\`\``);
\`\`\`
`);
}
},
});
@@ -141,22 +119,10 @@ ${value}
label: nls.localize('arduino/editor/decreaseIndent', 'Decrease Indent'),
order: '2',
});
registry.registerMenuAction(ArduinoMenus.EDIT__FONT_CONTROL_GROUP, {
commandId: EditContributions.Commands.INCREASE_FONT_SIZE.id,
label: nls.localize(
'arduino/editor/increaseFontSize',
'Increase Font Size'
),
order: '0',
});
registry.registerMenuAction(ArduinoMenus.EDIT__FONT_CONTROL_GROUP, {
commandId: EditContributions.Commands.DECREASE_FONT_SIZE.id,
label: nls.localize(
'arduino/editor/decreaseFontSize',
'Decrease Font Size'
),
order: '1',
registry.registerMenuAction(ArduinoMenus.EDIT__CODE_CONTROL_GROUP, {
commandId: EditContributions.Commands.AUTO_FORMAT.id,
label: nls.localize('arduino/editor/autoFormat', 'Auto Format'),
order: '3',
});
registry.registerMenuAction(ArduinoMenus.EDIT__FIND_GROUP, {
@@ -215,15 +181,6 @@ ${value}
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',
@@ -248,10 +205,13 @@ ${value}
});
}
protected async current(): Promise<ICodeEditor | StandaloneCodeEditor | undefined> {
protected async current(): Promise<
ICodeEditor | StandaloneCodeEditor | undefined
> {
return (
this.codeEditorService.getFocusedCodeEditor() ||
this.codeEditorService.getActiveCodeEditor() || undefined
this.codeEditorService.getActiveCodeEditor() ||
undefined
);
}
@@ -307,12 +267,6 @@ export namespace EditContributions {
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

@@ -1,18 +1,17 @@
import * as PQueue from 'p-queue';
import PQueue from 'p-queue';
import { inject, injectable } from '@theia/core/shared/inversify';
import { CommandHandler } from '@theia/core/lib/common/command';
import {
MenuPath,
CompositeMenuNode,
SubMenuOptions,
} from '@theia/core/lib/common/menu';
import { CommandHandler, CommandService } from '@theia/core/lib/common/command';
import { MenuPath, SubMenuOptions } 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 {
ArduinoMenus,
examplesLabel,
PlaceholderMenuNode,
} from '../menu/arduino-menus';
import { BoardsServiceProvider } from '../boards/boards-service-provider';
import { ExamplesService } from '../../common/protocol/examples-service';
import {
@@ -21,58 +20,134 @@ import {
MenuModelRegistry,
} from './contribution';
import { NotificationCenter } from '../notification-center';
import { Board, SketchRef, SketchContainer } from '../../common/protocol';
import { nls } from '@theia/core/lib/common';
import {
Board,
SketchRef,
SketchContainer,
SketchesError,
CoreService,
SketchesService,
Sketch,
isBoardIdentifierChangeEvent,
BoardIdentifier,
} from '../../common/protocol';
import { nls } from '@theia/core/lib/common/nls';
import { unregisterSubmenu } from '../menu/arduino-menus';
import { MaybePromise } from '@theia/core/lib/common/types';
import { ApplicationError } from '@theia/core/lib/common/application-error';
/**
* Creates a cloned copy of the example sketch and opens it in a new window.
*/
export async function openClonedExample(
uri: string,
services: {
sketchesService: SketchesService;
commandService: CommandService;
},
onError: {
onDidFailClone?: (
err: ApplicationError<
number,
{
uri: string;
}
>,
uri: string
) => MaybePromise<unknown>;
onDidFailOpen?: (
err: ApplicationError<
number,
{
uri: string;
}
>,
sketch: Sketch
) => MaybePromise<unknown>;
} = {}
): Promise<void> {
const { sketchesService, commandService } = services;
const { onDidFailClone, onDidFailOpen } = onError;
try {
const sketch = await sketchesService.cloneExample(uri);
try {
await commandService.executeCommand(
OpenSketch.Commands.OPEN_SKETCH.id,
sketch
);
} catch (openError) {
if (SketchesError.NotFound.is(openError)) {
if (onDidFailOpen) {
await onDidFailOpen(openError, sketch);
return;
}
}
throw openError;
}
} catch (cloneError) {
if (SketchesError.NotFound.is(cloneError)) {
if (onDidFailClone) {
await onDidFailClone(cloneError, uri);
return;
}
}
throw cloneError;
}
}
@injectable()
export abstract class Examples extends SketchContribution {
@inject(CommandRegistry)
protected readonly commandRegistry: CommandRegistry;
private readonly commandRegistry: CommandRegistry;
@inject(MenuModelRegistry)
protected readonly menuRegistry: MenuModelRegistry;
@inject(MainMenuManager)
protected readonly menuManager: MainMenuManager;
@inject(ExamplesService)
protected readonly examplesService: ExamplesService;
@inject(CoreService)
protected readonly coreService: CoreService;
@inject(BoardsServiceProvider)
protected readonly boardsServiceClient: BoardsServiceProvider;
protected readonly boardsServiceProvider: BoardsServiceProvider;
@inject(NotificationCenter)
protected readonly notificationCenter: NotificationCenter;
protected readonly toDispose = new DisposableCollection();
protected override init(): void {
super.init();
this.boardsServiceClient.onBoardsConfigChanged(({ selectedBoard }) =>
this.handleBoardChanged(selectedBoard)
this.boardsServiceProvider.onBoardsConfigDidChange((event) => {
if (isBoardIdentifierChangeEvent(event)) {
this.handleBoardChanged(event.selectedBoard);
}
});
this.notificationCenter.onDidReinitialize(() =>
this.update({
board: this.boardsServiceProvider.boardsConfig.selectedBoard,
// No force refresh. The core client was already refreshed.
})
);
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-vars
protected handleBoardChanged(board: Board | undefined): void {
// NOOP
}
protected abstract update(options?: {
board?: BoardIdentifier | undefined;
forceRefresh?: boolean;
}): void;
override 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,
nls.localize('arduino/examples/menu', 'Examples'),
examplesLabel,
{
order: '4',
}
@@ -108,6 +183,11 @@ export abstract class Examples extends SketchContribution {
const { label } = sketchContainerOrPlaceholder;
submenuPath = [...menuPath, label];
this.menuRegistry.registerSubmenu(submenuPath, label, subMenuOptions);
this.toDispose.push(
Disposable.create(() =>
unregisterSubmenu(submenuPath, this.menuRegistry)
)
);
sketches.push(...sketchContainerOrPlaceholder.sketches);
children.push(...sketchContainerOrPlaceholder.children);
} else {
@@ -147,12 +227,29 @@ export abstract class Examples extends SketchContribution {
}
protected createHandler(uri: string): CommandHandler {
const forceUpdate = () =>
this.update({
board: this.boardsServiceProvider.boardsConfig.selectedBoard,
forceRefresh: true,
});
return {
execute: async () => {
const sketch = await this.sketchService.cloneExample(uri);
return this.commandService.executeCommand(
OpenSketch.Commands.OPEN_SKETCH.id,
sketch
await openClonedExample(
uri,
{
sketchesService: this.sketchesService,
commandService: this.commandRegistry,
},
{
onDidFailClone: () => {
// Do not toast the error message. It's handled by the `Open Sketch` command.
forceUpdate();
},
onDidFailOpen: (err) => {
this.messageService.error(err.message);
forceUpdate();
},
}
);
},
};
@@ -162,10 +259,10 @@ export abstract class Examples extends SketchContribution {
@injectable()
export class BuiltInExamples extends Examples {
override async onReady(): Promise<void> {
this.register(); // no `await`
this.update(); // no `await`
}
protected async register(): Promise<void> {
protected override async update(): Promise<void> {
let sketchContainers: SketchContainer[] | undefined;
try {
sketchContainers = await this.examplesService.builtIns();
@@ -196,30 +293,32 @@ export class BuiltInExamples extends Examples {
@injectable()
export class LibraryExamples extends Examples {
@inject(NotificationCenter)
protected readonly notificationCenter: NotificationCenter;
protected readonly queue = new PQueue({ autoStart: true, concurrency: 1 });
private readonly queue = new PQueue({ autoStart: true, concurrency: 1 });
override onStart(): void {
this.notificationCenter.onLibraryDidInstall(() => this.register());
this.notificationCenter.onLibraryDidUninstall(() => this.register());
this.notificationCenter.onLibraryDidInstall(() => this.update());
this.notificationCenter.onLibraryDidUninstall(() => this.update());
}
override async onReady(): Promise<void> {
this.register(); // no `await`
this.update(); // no `await`
}
protected override handleBoardChanged(board: Board | undefined): void {
this.register(board);
this.update({ board });
}
protected async register(
board: Board | undefined = this.boardsServiceClient.boardsConfig
.selectedBoard
protected override async update(
options: { board?: Board; forceRefresh?: boolean } = {
board: this.boardsServiceProvider.boardsConfig.selectedBoard,
}
): Promise<void> {
const { board, forceRefresh } = options;
return this.queue.add(async () => {
this.toDispose.dispose();
if (forceRefresh) {
await this.coreService.refresh();
}
const fqbn = board?.fqbn;
const name = board?.name;
// Shows all examples when no board is selected, or the platform of the currently selected board is not installed.

View File

@@ -1,8 +1,14 @@
import { LocalStorageService } from '@theia/core/lib/browser';
import { inject, injectable } from '@theia/core/shared/inversify';
import { BoardsService, LibraryService } from '../../common/protocol';
import {
BoardsService,
LibraryLocation,
LibraryService,
} from '../../common/protocol';
import { Contribution } from './contribution';
const Arduino_BuiltIn = 'Arduino_BuiltIn';
@injectable()
export class FirstStartupInstaller extends Contribution {
@inject(LocalStorageService)
@@ -21,8 +27,8 @@ export class FirstStartupInstaller extends Contribution {
id: 'arduino:avr',
});
const builtInLibrary = (
await this.libraryService.search({ query: 'Arduino_BuiltIn' })
)[0];
await this.libraryService.search({ query: Arduino_BuiltIn })
).find(({ name }) => name === Arduino_BuiltIn); // Filter by `name` to ensure "exact match". See: https://github.com/arduino/arduino-ide/issues/1526.
let avrPackageError: Error | undefined;
let builtInLibraryError: Error | undefined;
@@ -43,7 +49,7 @@ export class FirstStartupInstaller extends Contribution {
// If arduino:avr installation fails because it's already installed we don't want to retry on next start-up
console.error(e);
} else {
// But if there is any other error (e.g.: no interntet cconnection), we want to retry next time
// But if there is any other error (e.g.: no Internet connection), we want to retry next time
avrPackageError = e;
}
}
@@ -57,6 +63,7 @@ export class FirstStartupInstaller extends Contribution {
item: builtInLibrary,
installDependencies: true,
noOverwrite: true, // We don't want to automatically replace custom libraries the user might already have in place
installLocation: LibraryLocation.BUILTIN,
});
} catch (e) {
// There's no error code, I need to parse the error message: https://github.com/arduino/arduino-cli/commit/2ea3608453b17b1157f8a1dc892af2e13e40f4f0#diff-1de7569144d4e260f8dde0e0d00a4e2a218c57966d583da1687a70d518986649R95
@@ -64,7 +71,7 @@ export class FirstStartupInstaller extends Contribution {
// If Arduino_BuiltIn installation fails because it's already installed we don't want to retry on next start-up
console.log('error installing core', e);
} else {
// But if there is any other error (e.g.: no interntet cconnection), we want to retry next time
// But if there is any other error (e.g.: no Internet connection), we want to retry next time
builtInLibraryError = e;
}
}
@@ -79,7 +86,7 @@ export class FirstStartupInstaller extends Contribution {
}
if (builtInLibraryError) {
this.messageService.error(
`Could not install ${builtInLibrary.name} library: ${builtInLibraryError}`
`Could not install ${Arduino_BuiltIn} library: ${builtInLibraryError}`
);
}

View File

@@ -2,8 +2,7 @@ import { MaybePromise } from '@theia/core';
import { inject, injectable } from '@theia/core/shared/inversify';
import * as monaco from '@theia/monaco-editor-core';
import { Formatter } from '../../common/protocol/formatter';
import { InoSelector } from '../ino-selectors';
import { fullRange } from '../utils/monaco';
import { InoSelector } from '../selectors';
import { Contribution, URI } from './contribution';
@injectable()
@@ -40,7 +39,7 @@ export class Format
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_token: monaco.CancellationToken
): Promise<monaco.languages.TextEdit[]> {
const range = fullRange(model);
const range = model.getFullModelRange();
const text = await this.format(model, range, options);
return [{ range, text }];
}

View File

@@ -41,7 +41,9 @@ export class Help extends Contribution {
);
registry.registerCommand(
Help.Commands.ENVIRONMENT,
createOpenHandler('https://www.arduino.cc/en/Guide/Environment')
createOpenHandler(
'https://docs.arduino.cc/software/ide-v2/tutorials/getting-started-ide-v2'
)
);
registry.registerCommand(
Help.Commands.TROUBLESHOOTING,

View File

@@ -1,4 +1,4 @@
import * as PQueue from 'p-queue';
import PQueue from 'p-queue';
import { inject, injectable } from '@theia/core/shared/inversify';
import URI from '@theia/core/lib/common/uri';
import { MonacoEditor } from '@theia/monaco/lib/browser/monaco-editor';
@@ -17,7 +17,7 @@ import { SketchContribution, Command, CommandRegistry } from './contribution';
import { NotificationCenter } from '../notification-center';
import { nls } from '@theia/core/lib/common';
import * as monaco from '@theia/monaco-editor-core';
import { CurrentSketch } from '../../common/protocol/sketches-service-client-impl';
import { CurrentSketch } from '../sketches-service-client-impl';
@injectable()
export class IncludeLibrary extends SketchContribution {
@@ -37,7 +37,7 @@ export class IncludeLibrary extends SketchContribution {
protected readonly notificationCenter: NotificationCenter;
@inject(BoardsServiceProvider)
protected readonly boardsServiceClient: BoardsServiceProvider;
protected readonly boardsServiceProvider: BoardsServiceProvider;
@inject(LibraryService)
protected readonly libraryService: LibraryService;
@@ -46,13 +46,14 @@ export class IncludeLibrary extends SketchContribution {
protected readonly toDispose = new DisposableCollection();
override onStart(): void {
this.boardsServiceClient.onBoardsConfigChanged(() =>
this.boardsServiceProvider.onBoardsConfigDidChange(() =>
this.updateMenuActions()
);
this.notificationCenter.onLibraryDidInstall(() => this.updateMenuActions());
this.notificationCenter.onLibraryDidUninstall(() =>
this.updateMenuActions()
);
this.notificationCenter.onDidReinitialize(() => this.updateMenuActions());
}
override async onReady(): Promise<void> {
@@ -97,7 +98,7 @@ export class IncludeLibrary extends SketchContribution {
this.toDispose.dispose();
this.mainMenuManager.update();
const libraries: LibraryPackage[] = [];
const fqbn = this.boardsServiceClient.boardsConfig.selectedBoard?.fqbn;
const fqbn = this.boardsServiceProvider.boardsConfig.selectedBoard?.fqbn;
// Show all libraries, when no board is selected.
// Otherwise, show libraries only for the selected board.
libraries.push(...(await this.libraryService.list({ fqbn })));

View File

@@ -16,7 +16,7 @@ export class IndexesUpdateProgress extends Contribution {
| undefined;
override onStart(): void {
this.notificationCenter.onIndexWillUpdate((progressId) =>
this.notificationCenter.onIndexUpdateWillStart(({ progressId }) =>
this.getOrCreateProgress(progressId)
);
this.notificationCenter.onIndexUpdateDidProgress((progress) => {
@@ -24,7 +24,7 @@ export class IndexesUpdateProgress extends Contribution {
delegate.report(progress)
);
});
this.notificationCenter.onIndexDidUpdate((progressId) => {
this.notificationCenter.onIndexUpdateDidComplete(({ progressId }) => {
this.cancelProgress(progressId);
});
this.notificationCenter.onIndexUpdateDidFail(({ progressId, message }) => {

View File

@@ -1,15 +1,24 @@
import { Mutex } from 'async-mutex';
import {
Disposable,
DisposableCollection,
} from '@theia/core/lib/common/disposable';
import { inject, injectable } from '@theia/core/shared/inversify';
import { Mutex } from 'async-mutex';
import {
ArduinoDaemon,
assertSanitizedFqbn,
BoardIdentifier,
BoardsService,
ExecutableService,
isBoardIdentifierChangeEvent,
sanitizeFqbn,
} from '../../common/protocol';
import { HostedPluginEvents } from '../hosted-plugin-events';
import { SketchContribution, URI } from './contribution';
import { CurrentSketch } from '../../common/protocol/sketches-service-client-impl';
import { BoardsConfig } from '../boards/boards-config';
import { CurrentSketch } from '../sketches-service-client-impl';
import { BoardsServiceProvider } from '../boards/boards-service-provider';
import { HostedPluginEvents } from '../hosted-plugin-events';
import { NotificationCenter } from '../notification-center';
import { SketchContribution, URI } from './contribution';
import { BoardsDataStore } from '../boards/boards-data-store';
@injectable()
export class InoLanguage extends SketchContribution {
@@ -28,12 +37,19 @@ export class InoLanguage extends SketchContribution {
@inject(BoardsServiceProvider)
private readonly boardsServiceProvider: BoardsServiceProvider;
@inject(NotificationCenter)
private readonly notificationCenter: NotificationCenter;
@inject(BoardsDataStore)
private readonly boardDataStore: BoardsDataStore;
private readonly toDispose = new DisposableCollection();
private readonly languageServerStartMutex = new Mutex();
private languageServerFqbn?: string;
private languageServerStartMutex = new Mutex();
override onReady(): void {
const start = (
{ selectedBoard }: BoardsConfig.Config,
selectedBoard: BoardIdentifier | undefined,
forceStart = false
) => {
if (selectedBoard) {
@@ -43,25 +59,65 @@ export class InoLanguage extends SketchContribution {
}
}
};
this.boardsServiceProvider.onBoardsConfigChanged(start);
this.hostedPluginEvents.onPluginsDidStart(() =>
start(this.boardsServiceProvider.boardsConfig)
);
this.hostedPluginEvents.onPluginsWillUnload(
() => (this.languageServerFqbn = undefined)
);
this.preferences.onPreferenceChanged(
({ preferenceName, oldValue, newValue }) => {
if (oldValue !== newValue) {
switch (preferenceName) {
case 'arduino.language.log':
case 'arduino.language.realTimeDiagnostics':
start(this.boardsServiceProvider.boardsConfig, true);
const forceRestart = () => {
start(this.boardsServiceProvider.boardsConfig.selectedBoard, true);
};
this.toDispose.pushAll([
this.boardsServiceProvider.onBoardsConfigDidChange((event) => {
if (isBoardIdentifierChangeEvent(event)) {
start(event.selectedBoard);
}
}),
this.hostedPluginEvents.onPluginsDidStart(() =>
start(this.boardsServiceProvider.boardsConfig.selectedBoard)
),
this.hostedPluginEvents.onPluginsWillUnload(
() => (this.languageServerFqbn = undefined)
),
this.preferences.onPreferenceChanged(
({ preferenceName, oldValue, newValue }) => {
if (oldValue !== newValue) {
switch (preferenceName) {
case 'arduino.language.log':
case 'arduino.language.realTimeDiagnostics':
forceRestart();
}
}
}
}
),
this.notificationCenter.onLibraryDidInstall(() => forceRestart()),
this.notificationCenter.onLibraryDidUninstall(() => forceRestart()),
this.notificationCenter.onPlatformDidInstall(() => forceRestart()),
this.notificationCenter.onPlatformDidUninstall(() => forceRestart()),
this.notificationCenter.onDidReinitialize(() => forceRestart()),
this.boardDataStore.onChanged((dataChangePerFqbn) => {
if (this.languageServerFqbn) {
const sanitizedFqbn = sanitizeFqbn(this.languageServerFqbn);
if (!sanitizeFqbn) {
throw new Error(
`Failed to sanitize the FQBN of the running language server. FQBN with the board settings was: ${this.languageServerFqbn}`
);
}
const matchingFqbn = dataChangePerFqbn.find(
(fqbn) => sanitizedFqbn === fqbn
);
const { boardsConfig } = this.boardsServiceProvider;
if (
matchingFqbn &&
boardsConfig.selectedBoard?.fqbn === matchingFqbn
) {
start(boardsConfig.selectedBoard);
}
}
}),
]);
this.boardsServiceProvider.ready.then(() =>
start(this.boardsServiceProvider.boardsConfig.selectedBoard)
);
start(this.boardsServiceProvider.boardsConfig);
}
onStop(): void {
this.toDispose.dispose();
}
private async startLanguageServer(
@@ -74,6 +130,7 @@ export class InoLanguage extends SketchContribution {
return;
}
const release = await this.languageServerStartMutex.acquire();
const toDisposeOnRelease = new DisposableCollection();
try {
await this.hostedPluginEvents.didStart;
const details = await this.boardsService.getBoardDetails({ fqbn });
@@ -101,11 +158,18 @@ export class InoLanguage extends SketchContribution {
}
return;
}
if (!forceStart && fqbn === this.languageServerFqbn) {
assertSanitizedFqbn(fqbn);
const fqbnWithConfig = await this.boardDataStore.appendConfigToFqbn(fqbn);
if (!fqbnWithConfig) {
throw new Error(
`Failed to append boards config to the FQBN. Original FQBN was: ${fqbn}`
);
}
if (!forceStart && fqbnWithConfig === this.languageServerFqbn) {
// NOOP
return;
}
this.logger.info(`Starting language server: ${fqbn}`);
this.logger.info(`Starting language server: ${fqbnWithConfig}`);
const log = this.preferences.get('arduino.language.log');
const realTimeDiagnostics = this.preferences.get(
'arduino.language.realTimeDiagnostics'
@@ -126,12 +190,13 @@ export class InoLanguage extends SketchContribution {
]);
this.languageServerFqbn = await Promise.race([
new Promise<undefined>((_, reject) =>
setTimeout(
new Promise<undefined>((_, reject) => {
const timer = setTimeout(
() => reject(new Error(`Timeout after ${20_000} ms.`)),
20_000
)
),
);
toDisposeOnRelease.push(Disposable.create(() => clearTimeout(timer)));
}),
this.commandService.executeCommand<string>(
'arduino.languageserver.start',
{
@@ -141,7 +206,7 @@ export class InoLanguage extends SketchContribution {
log: currentSketchPath ? currentSketchPath : log,
cliDaemonInstance: '1',
board: {
fqbn,
fqbn: fqbnWithConfig,
name: name ? `"${name}"` : undefined,
},
realTimeDiagnostics,
@@ -150,9 +215,10 @@ export class InoLanguage extends SketchContribution {
),
]);
} catch (e) {
console.log(`Failed to start language server for ${fqbn}`, e);
console.log(`Failed to start language server. Original FQBN: ${fqbn}`, e);
this.languageServerFqbn = undefined;
} finally {
toDisposeOnRelease.dispose();
release();
}
}

View File

@@ -0,0 +1,173 @@
import { injectable } from '@theia/core/shared/inversify';
import {
Contribution,
Command,
MenuModelRegistry,
KeybindingRegistry,
} from './contribution';
import { ArduinoMenus } from '../menu/arduino-menus';
import { CommandRegistry, MaybePromise, nls } from '@theia/core/lib/common';
import { Settings } from '../dialogs/settings/settings';
import debounce from 'lodash.debounce';
@injectable()
export class InterfaceScale extends Contribution {
private fontScalingEnabled: InterfaceScale.FontScalingEnabled = {
increase: true,
decrease: true,
};
private currentSettings: Settings;
private updateSettingsDebounced = debounce(
async () => {
await this.settingsService.update(this.currentSettings);
await this.settingsService.save();
},
100,
{ maxWait: 200 }
);
override onStart(): MaybePromise<void> {
const updateCurrent = (settings: Settings) => {
this.currentSettings = settings;
this.updateFontScalingEnabled();
};
this.settingsService.onDidChange((settings) => updateCurrent(settings));
this.settingsService.settings().then((settings) => updateCurrent(settings));
}
override registerCommands(registry: CommandRegistry): void {
registry.registerCommand(InterfaceScale.Commands.INCREASE_FONT_SIZE, {
execute: () => this.updateFontSize('increase'),
isEnabled: () => this.fontScalingEnabled.increase,
});
registry.registerCommand(InterfaceScale.Commands.DECREASE_FONT_SIZE, {
execute: () => this.updateFontSize('decrease'),
isEnabled: () => this.fontScalingEnabled.decrease,
});
}
override registerMenus(registry: MenuModelRegistry): void {
registry.registerMenuAction(ArduinoMenus.EDIT__FONT_CONTROL_GROUP, {
commandId: InterfaceScale.Commands.INCREASE_FONT_SIZE.id,
label: nls.localize(
'arduino/editor/increaseFontSize',
'Increase Font Size'
),
order: '0',
});
registry.registerMenuAction(ArduinoMenus.EDIT__FONT_CONTROL_GROUP, {
commandId: InterfaceScale.Commands.DECREASE_FONT_SIZE.id,
label: nls.localize(
'arduino/editor/decreaseFontSize',
'Decrease Font Size'
),
order: '1',
});
}
private updateFontScalingEnabled(): void {
let fontScalingEnabled = {
increase: true,
decrease: true,
};
if (this.currentSettings.autoScaleInterface) {
fontScalingEnabled = {
increase:
this.currentSettings.interfaceScale + InterfaceScale.ZoomLevel.STEP <=
InterfaceScale.ZoomLevel.MAX,
decrease:
this.currentSettings.interfaceScale - InterfaceScale.ZoomLevel.STEP >=
InterfaceScale.ZoomLevel.MIN,
};
} else {
fontScalingEnabled = {
increase:
this.currentSettings.editorFontSize + InterfaceScale.FontSize.STEP <=
InterfaceScale.FontSize.MAX,
decrease:
this.currentSettings.editorFontSize - InterfaceScale.FontSize.STEP >=
InterfaceScale.FontSize.MIN,
};
}
const isChanged = Object.keys(fontScalingEnabled).some(
(key: keyof InterfaceScale.FontScalingEnabled) =>
fontScalingEnabled[key] !== this.fontScalingEnabled[key]
);
if (isChanged) {
this.fontScalingEnabled = fontScalingEnabled;
this.menuManager.update();
}
}
private updateFontSize(mode: 'increase' | 'decrease'): void {
if (this.currentSettings.autoScaleInterface) {
mode === 'increase'
? (this.currentSettings.interfaceScale += InterfaceScale.ZoomLevel.STEP)
: (this.currentSettings.interfaceScale -=
InterfaceScale.ZoomLevel.STEP);
} else {
mode === 'increase'
? (this.currentSettings.editorFontSize += InterfaceScale.FontSize.STEP)
: (this.currentSettings.editorFontSize -= InterfaceScale.FontSize.STEP);
}
this.updateFontScalingEnabled();
this.updateSettingsDebounced();
}
override registerKeybindings(registry: KeybindingRegistry): void {
registry.registerKeybinding({
command: InterfaceScale.Commands.INCREASE_FONT_SIZE.id,
keybinding: 'CtrlCmd+=',
});
registry.registerKeybinding({
command: InterfaceScale.Commands.DECREASE_FONT_SIZE.id,
keybinding: 'CtrlCmd+-',
});
}
}
export namespace InterfaceScale {
export namespace Commands {
export const INCREASE_FONT_SIZE: Command = {
id: 'arduino-increase-font-size',
};
export const DECREASE_FONT_SIZE: Command = {
id: 'arduino-decrease-font-size',
};
}
export namespace ZoomLevel {
export const MIN = -8;
export const MAX = 9;
export const STEP = 1;
export function toPercentage(scale: number): number {
return scale * 20 + 100;
}
export function fromPercentage(percentage: number): number {
return (percentage - 100) / 20;
}
export namespace Step {
export function toPercentage(step: number): number {
return step * 20;
}
export function fromPercentage(percentage: number): number {
return percentage / 20;
}
}
}
export namespace FontSize {
export const MIN = 8;
export const MAX = 72;
export const STEP = 2;
}
export interface FontScalingEnabled {
increase: boolean;
decrease: boolean;
}
}

View File

@@ -0,0 +1,204 @@
import { KeybindingRegistry } from '@theia/core/lib/browser/keybinding';
import { CompositeTreeNode } from '@theia/core/lib/browser/tree';
import { DisposableCollection } from '@theia/core/lib/common/disposable';
import { MenuModelRegistry } from '@theia/core/lib/common/menu';
import { Progress } from '@theia/core/lib/common/message-service-protocol';
import { nls } from '@theia/core/lib/common/nls';
import { injectable } from '@theia/core/shared/inversify';
import { CreateUri } from '../create/create-uri';
import { Create, isConflict } from '../create/typings';
import { ArduinoMenus } from '../menu/arduino-menus';
import {
TaskFactoryImpl,
WorkspaceInputDialogWithProgress,
} from '../theia/workspace/workspace-input-dialog';
import { CloudSketchbookTree } from '../widgets/cloud-sketchbook/cloud-sketchbook-tree';
import { CloudSketchbookTreeModel } from '../widgets/cloud-sketchbook/cloud-sketchbook-tree-model';
import { SketchbookCommands } from '../widgets/sketchbook/sketchbook-commands';
import {
CloudSketchContribution,
pullingSketch,
sketchAlreadyExists,
synchronizingSketchbook,
} from './cloud-contribution';
import { Command, CommandRegistry, Sketch } from './contribution';
export interface CreateNewCloudSketchCallback {
(
newSketch: Create.Sketch,
newNode: CloudSketchbookTree.CloudSketchDirNode,
progress: Progress
): Promise<void>;
}
export interface NewCloudSketchParams {
/**
* Value to populate the dialog `<input>` when it opens.
*/
readonly initialValue?: string | undefined;
/**
* Additional callback to call when the new cloud sketch has been created.
*/
readonly callback?: CreateNewCloudSketchCallback;
/**
* If `true`, the validation error message will not be visible in the input dialog, but the `OK` button will be disabled. Defaults to `true`.
*/
readonly skipShowErrorMessageOnOpen?: boolean;
}
@injectable()
export class NewCloudSketch extends CloudSketchContribution {
private readonly toDispose = new DisposableCollection();
override onReady(): void {
this.toDispose.pushAll([
this.createFeatures.onDidChangeEnabled(() => this.menuManager.update()),
this.createFeatures.onDidChangeSession(() => this.menuManager.update()),
]);
if (this.createFeatures.session) {
this.menuManager.update();
}
}
onStop(): void {
this.toDispose.dispose();
}
override registerCommands(registry: CommandRegistry): void {
registry.registerCommand(NewCloudSketch.Commands.NEW_CLOUD_SKETCH, {
execute: (params: NewCloudSketchParams) =>
this.createNewSketch(
params?.skipShowErrorMessageOnOpen === false ? false : true,
params?.initialValue,
params?.callback
),
isEnabled: () => Boolean(this.createFeatures.session),
isVisible: () => this.createFeatures.enabled,
});
}
override registerMenus(registry: MenuModelRegistry): void {
registry.registerMenuAction(ArduinoMenus.FILE__SKETCH_GROUP, {
commandId: NewCloudSketch.Commands.NEW_CLOUD_SKETCH.id,
label: nls.localize('arduino/cloudSketch/new', 'New Cloud Sketch'),
order: '1',
});
}
override registerKeybindings(registry: KeybindingRegistry): void {
registry.registerKeybinding({
command: NewCloudSketch.Commands.NEW_CLOUD_SKETCH.id,
keybinding: 'CtrlCmd+Alt+N',
});
}
private async createNewSketch(
skipShowErrorMessageOnOpen: boolean,
initialValue?: string | undefined,
callback?: CreateNewCloudSketchCallback
): Promise<void> {
const treeModel = await this.treeModel();
if (treeModel) {
const rootNode = treeModel.root;
return this.openWizard(
rootNode,
treeModel,
skipShowErrorMessageOnOpen,
initialValue,
callback
);
}
}
private async openWizard(
rootNode: CompositeTreeNode,
treeModel: CloudSketchbookTreeModel,
skipShowErrorMessageOnOpen: boolean,
initialValue?: string | undefined,
callback?: CreateNewCloudSketchCallback
): Promise<void> {
const existingNames = rootNode.children
.filter(CloudSketchbookTree.CloudSketchDirNode.is)
.map(({ fileStat }) => fileStat.name);
const taskFactory = new TaskFactoryImpl((value) =>
this.createNewSketchWithProgress(treeModel, value, callback)
);
try {
const dialog = new WorkspaceInputDialogWithProgress(
{
title: nls.localize(
'arduino/newCloudSketch/newSketchTitle',
'Name of the new Cloud Sketch'
),
parentUri: CreateUri.root,
initialValue,
validate: (input) => {
if (existingNames.includes(input)) {
return sketchAlreadyExists(input);
}
return Sketch.validateCloudSketchFolderName(input) ?? '';
},
},
this.labelProvider,
taskFactory
);
await dialog.open(skipShowErrorMessageOnOpen);
if (dialog.taskResult) {
this.openInNewWindow(dialog.taskResult);
}
} catch (err) {
if (isConflict(err)) {
await treeModel.refresh();
return this.createNewSketch(
false,
taskFactory.value ?? initialValue,
callback
);
}
throw err;
}
}
private createNewSketchWithProgress(
treeModel: CloudSketchbookTreeModel,
value: string,
callback?: CreateNewCloudSketchCallback
): (
progress: Progress
) => Promise<CloudSketchbookTree.CloudSketchDirNode | undefined> {
return async (progress: Progress) => {
progress.report({
message: nls.localize(
'arduino/cloudSketch/creating',
"Creating cloud sketch '{0}'...",
value
),
});
const sketch = await this.createApi.createSketch(value);
progress.report({ message: synchronizingSketchbook });
await treeModel.refresh();
progress.report({ message: pullingSketch(sketch.name) });
const node = await this.pull(sketch);
if (callback && node) {
await callback(sketch, node, progress);
}
return node;
};
}
private openInNewWindow(
node: CloudSketchbookTree.CloudSketchDirNode
): Promise<void> {
return this.commandService.executeCommand(
SketchbookCommands.OPEN_NEW_WINDOW.id,
{ node, treeWidgetId: 'cloud-sketchbook-composite-widget' }
);
}
}
export namespace NewCloudSketch {
export namespace Commands {
export const NEW_CLOUD_SKETCH: Command = {
id: 'arduino-new-cloud-sketch',
};
}
}

View File

@@ -1,7 +1,6 @@
import { nls } from '@theia/core/lib/common';
import { injectable } from '@theia/core/shared/inversify';
import { ArduinoMenus } from '../menu/arduino-menus';
import { ArduinoToolbar } from '../toolbar/arduino-toolbar';
import {
SketchContribution,
URI,
@@ -17,17 +16,12 @@ export class NewSketch extends SketchContribution {
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),
});
}
override registerMenus(registry: MenuModelRegistry): void {
registry.registerMenuAction(ArduinoMenus.FILE__SKETCH_GROUP, {
commandId: NewSketch.Commands.NEW_SKETCH.id,
label: nls.localize('arduino/sketch/new', 'New'),
label: nls.localize('arduino/sketch/new', 'New Sketch'),
order: '0',
});
}
@@ -41,7 +35,7 @@ export class NewSketch extends SketchContribution {
async newSketch(): Promise<void> {
try {
const sketch = await this.sketchService.createNewSketch();
const sketch = await this.sketchesService.createNewSketch();
this.workspaceService.open(new URI(sketch.uri));
} catch (e) {
await this.messageService.error(e.toString());
@@ -54,8 +48,5 @@ export namespace NewSketch {
export const NEW_SKETCH: Command = {
id: 'arduino-new-sketch',
};
export const NEW_SKETCH__TOOLBAR: Command = {
id: 'arduino-new-sketch--toolbar',
};
}
}

View File

@@ -1,25 +1,18 @@
import { CommandRegistry } from '@theia/core';
import type { Command, CommandRegistry } from '@theia/core/lib/common/command';
import { inject, injectable } from '@theia/core/shared/inversify';
import type { EditBoardsConfigActionParams } from '../../common/protocol/board-list';
import { BoardsConfigDialog } from '../boards/boards-config-dialog';
import { BoardsServiceProvider } from '../boards/boards-service-provider';
import { Contribution, Command } from './contribution';
import { Contribution } from './contribution';
@injectable()
export class OpenBoardsConfig extends Contribution {
@inject(BoardsServiceProvider)
private readonly boardsServiceProvider: BoardsServiceProvider;
@inject(BoardsConfigDialog)
private readonly boardsConfigDialog: BoardsConfigDialog;
override registerCommands(registry: CommandRegistry): void {
registry.registerCommand(OpenBoardsConfig.Commands.OPEN_DIALOG, {
execute: async (query?: string | undefined) => {
const boardsConfig = await this.boardsConfigDialog.open(query);
if (boardsConfig) {
return (this.boardsServiceProvider.boardsConfig = boardsConfig);
}
},
execute: async (params?: EditBoardsConfigActionParams) =>
this.boardsConfigDialog.open(params),
});
}
}

View File

@@ -15,6 +15,7 @@ import { MainMenuManager } from '../../common/main-menu-manager';
import { OpenSketch } from './open-sketch';
import { NotificationCenter } from '../notification-center';
import { nls } from '@theia/core/lib/common';
import { SketchesError } from '../../common/protocol';
@injectable()
export class OpenRecentSketch extends SketchContribution {
@@ -33,7 +34,7 @@ export class OpenRecentSketch extends SketchContribution {
@inject(NotificationCenter)
protected readonly notificationCenter: NotificationCenter;
protected toDisposeBeforeRegister = new Map<string, DisposableCollection>();
protected toDispose = new DisposableCollection();
override onStart(): void {
this.notificationCenter.onRecentSketchesDidChange(({ sketches }) =>
@@ -42,8 +43,12 @@ export class OpenRecentSketch extends SketchContribution {
}
override async onReady(): Promise<void> {
this.sketchService
.recentlyOpenedSketches()
this.update();
}
private update(forceUpdate?: boolean): void {
this.sketchesService
.recentlyOpenedSketches(forceUpdate)
.then((sketches) => this.refreshMenu(sketches));
}
@@ -62,19 +67,25 @@ export class OpenRecentSketch extends SketchContribution {
protected register(sketches: Sketch[]): void {
const order = 0;
this.toDispose.dispose();
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
),
execute: async () => {
try {
await this.commandRegistry.executeCommand(
OpenSketch.Commands.OPEN_SKETCH.id,
sketch
);
} catch (err) {
if (SketchesError.NotFound.is(err)) {
this.update(true);
} else {
throw err;
}
}
},
};
this.commandRegistry.registerCommand(command, handler);
this.menuRegistry.registerMenuAction(
@@ -85,8 +96,7 @@ export class OpenRecentSketch extends SketchContribution {
order: String(order),
}
);
this.toDisposeBeforeRegister.set(
sketch.uri,
this.toDispose.pushAll([
new DisposableCollection(
Disposable.create(() =>
this.commandRegistry.unregisterCommand(command)
@@ -94,8 +104,8 @@ export class OpenRecentSketch extends SketchContribution {
Disposable.create(() =>
this.menuRegistry.unregisterMenuAction(command)
)
)
);
),
]);
}
}
}

View File

@@ -1,32 +1,34 @@
import { nls } from '@theia/core/lib/common/nls';
import { inject, injectable } from '@theia/core/shared/inversify';
import type { Settings } from '../dialogs/settings/settings';
import { SettingsDialog } from '../dialogs/settings/settings-dialog';
import { ArduinoMenus } from '../menu/arduino-menus';
import {
Command,
MenuModelRegistry,
CommandRegistry,
SketchContribution,
KeybindingRegistry,
MenuModelRegistry,
SketchContribution,
} from './contribution';
import { ArduinoMenus } from '../menu/arduino-menus';
import { Settings as Preferences } from '../dialogs/settings/settings';
import { SettingsDialog } from '../dialogs/settings/settings-dialog';
import { nls } from '@theia/core/lib/common';
@injectable()
export class Settings extends SketchContribution {
export class OpenSettings extends SketchContribution {
@inject(SettingsDialog)
protected readonly settingsDialog: SettingsDialog;
private readonly settingsDialog: SettingsDialog;
protected settingsOpened = false;
private settingsOpened = false;
override registerCommands(registry: CommandRegistry): void {
registry.registerCommand(Settings.Commands.OPEN, {
registry.registerCommand(OpenSettings.Commands.OPEN, {
execute: async () => {
let settings: Preferences | undefined = undefined;
let settings: Settings | undefined = undefined;
try {
this.settingsOpened = true;
this.menuManager.update();
settings = await this.settingsDialog.open();
} finally {
this.settingsOpened = false;
this.menuManager.update();
}
if (settings) {
await this.settingsService.update(settings);
@@ -41,7 +43,7 @@ export class Settings extends SketchContribution {
override registerMenus(registry: MenuModelRegistry): void {
registry.registerMenuAction(ArduinoMenus.FILE__PREFERENCES_GROUP, {
commandId: Settings.Commands.OPEN.id,
commandId: OpenSettings.Commands.OPEN.id,
label:
nls.localize(
'vscode/preferences.contribution/preferences',
@@ -57,13 +59,13 @@ export class Settings extends SketchContribution {
override registerKeybindings(registry: KeybindingRegistry): void {
registry.registerKeybinding({
command: Settings.Commands.OPEN.id,
command: OpenSettings.Commands.OPEN.id,
keybinding: 'CtrlCmd+,',
});
}
}
export namespace Settings {
export namespace OpenSettings {
export namespace Commands {
export const OPEN: Command = {
id: 'arduino-settings-open',

View File

@@ -1,5 +1,4 @@
import { injectable } from '@theia/core/shared/inversify';
import * as remote from '@theia/core/electron-shared/@electron/remote';
import URI from '@theia/core/lib/common/uri';
import { ArduinoMenus } from '../menu/arduino-menus';
import {
@@ -9,7 +8,7 @@ import {
MenuModelRegistry,
KeybindingRegistry,
} from './contribution';
import { nls } from '@theia/core/lib/common';
import { nls } from '@theia/core/lib/common/nls';
@injectable()
export class OpenSketchExternal extends SketchContribution {
@@ -41,7 +40,7 @@ export class OpenSketchExternal extends SketchContribution {
if (exists) {
const fsPath = await this.fileService.fsPath(new URI(uri));
if (fsPath) {
remote.shell.showItemInFolder(fsPath);
window.electronTheiaCore.showItemInFolder(fsPath);
}
}
}

View File

@@ -1,7 +1,8 @@
import { nls } from '@theia/core/lib/common/nls';
import { injectable } from '@theia/core/shared/inversify';
import type { EditorOpenerOptions } from '@theia/editor/lib/browser/editor-manager';
import { SketchesError } from '../../common/protocol';
import { Later } from '../../common/nls';
import { Sketch, SketchesError } from '../../common/protocol';
import {
Command,
CommandRegistry,
@@ -9,12 +10,18 @@ import {
URI,
} from './contribution';
import { SaveAsSketch } from './save-as-sketch';
import { promptMoveSketch } from './open-sketch';
import { ApplicationError } from '@theia/core/lib/common/application-error';
import { Deferred, wait } from '@theia/core/lib/common/promise-util';
import { EditorWidget } from '@theia/editor/lib/browser/editor-widget';
import { DisposableCollection } from '@theia/core/lib/common/disposable';
@injectable()
export class OpenSketchFiles extends SketchContribution {
override registerCommands(registry: CommandRegistry): void {
registry.registerCommand(OpenSketchFiles.Commands.OPEN_SKETCH_FILES, {
execute: (uri: URI) => this.openSketchFiles(uri),
execute: (uri: URI, focusMainSketchFile) =>
this.openSketchFiles(uri, focusMainSketchFile),
});
registry.registerCommand(OpenSketchFiles.Commands.ENSURE_OPENED, {
execute: (
@@ -27,13 +34,23 @@ export class OpenSketchFiles extends SketchContribution {
});
}
private async openSketchFiles(uri: URI): Promise<void> {
private async openSketchFiles(
uri: URI,
focusMainSketchFile = false
): Promise<void> {
try {
const sketch = await this.sketchService.loadSketch(uri.toString());
const sketch = await this.sketchesService.loadSketch(uri.toString());
const { mainFileUri, rootFolderFileUris } = sketch;
for (const uri of [mainFileUri, ...rootFolderFileUris]) {
await this.ensureOpened(uri);
}
if (focusMainSketchFile) {
await this.ensureOpened(mainFileUri, true, {
mode: 'activate',
preview: false,
counter: 0,
});
}
if (mainFileUri.endsWith('.pde')) {
const message = nls.localize(
'arduino/common/oldFormat',
@@ -41,24 +58,38 @@ export class OpenSketchFiles extends SketchContribution {
sketch.name
);
const yes = nls.localize('vscode/extensionsUtils/yes', 'Yes');
this.messageService
.info(message, nls.localize('arduino/common/later', 'Later'), yes)
.then(async (answer) => {
if (answer === yes) {
this.commandService.executeCommand(
SaveAsSketch.Commands.SAVE_AS_SKETCH.id,
{
execOnlyIfTemp: false,
openAfterMove: true,
wipeOriginal: false,
}
);
}
});
this.messageService.info(message, Later, yes).then((answer) => {
if (answer === yes) {
this.commandService.executeCommand(
SaveAsSketch.Commands.SAVE_AS_SKETCH.id,
{
execOnlyIfTemp: false,
openAfterMove: true,
wipeOriginal: false,
}
);
}
});
}
const { workspaceError } = this.workspaceService;
// This happens when the IDE2 has been started (from either a terminal or clicking on an `ino` file) with a /path/to/invalid/sketch. (#964)
if (SketchesError.InvalidName.is(workspaceError)) {
await this.promptMove(workspaceError);
}
} catch (err) {
// This happens when the user gracefully closed IDE2, all went well
// but the main sketch file was renamed outside of IDE2 and when the user restarts the IDE2
// the workspace path still exists, but the sketch path is not valid anymore. (#964)
if (SketchesError.InvalidName.is(err)) {
const movedSketch = await this.promptMove(err);
if (!movedSketch) {
// If user did not accept the move, or move was not possible, force reload with a fallback.
return this.openFallbackSketch();
}
}
if (SketchesError.NotFound.is(err)) {
this.openFallbackSketch();
return this.openFallbackSketch();
} else {
console.error(err);
const message =
@@ -72,8 +103,34 @@ export class OpenSketchFiles extends SketchContribution {
}
}
private async promptMove(
err: ApplicationError<
number,
{
invalidMainSketchUri: string;
}
>
): Promise<Sketch | undefined> {
const { invalidMainSketchUri } = err.data;
requestAnimationFrame(() => this.messageService.error(err.message));
await wait(250); // let IDE2 open the editor and toast the error message, then open the modal dialog
const movedSketch = await promptMoveSketch(invalidMainSketchUri, {
fileService: this.fileService,
sketchesService: this.sketchesService,
labelProvider: this.labelProvider,
dialogService: this.dialogService,
});
if (movedSketch) {
this.workspaceService.open(new URI(movedSketch.uri), {
preserveWindow: true,
});
return movedSketch;
}
return undefined;
}
private async openFallbackSketch(): Promise<void> {
const sketch = await this.sketchService.createNewSketch();
const sketch = await this.sketchesService.createNewSketch();
this.workspaceService.open(new URI(sketch.uri), { preserveWindow: true });
}
@@ -81,20 +138,84 @@ export class OpenSketchFiles extends SketchContribution {
uri: string,
forceOpen = false,
options?: EditorOpenerOptions
): Promise<unknown> {
): Promise<EditorWidget | undefined> {
const widget = this.editorManager.all.find(
(widget) => widget.editor.uri.toString() === uri
);
if (!widget || forceOpen) {
return this.editorManager.open(
if (widget && !forceOpen) {
return widget;
}
const disposables = new DisposableCollection();
const deferred = new Deferred<EditorWidget>();
// An editor can be in two primary states:
// - The editor is not yet opened. The `widget` is `undefined`. With `editorManager#open`, Theia will create an editor and fire an `editorManager#onCreated` event.
// - The editor is opened. Can be active, current, or open.
// - If the editor has the focus (the cursor blinks in the editor): it's the active editor.
// - If the editor does not have the focus (the focus is on a different widget or the context menu is opened in the editor): it's the current editor.
// - If the editor is not the top editor in the main area, it's opened.
if (!widget) {
// If the widget is `undefined`, IDE2 expects one `onCreate` event. Subscribe to the `onCreated` event
// and resolve the promise with the editor only when the new editor's visibility changes.
disposables.push(
this.editorManager.onCreated((editor) => {
if (editor.editor.uri.toString() === uri) {
if (editor.isAttached && editor.isVisible) {
deferred.resolve(editor);
} else {
disposables.push(
editor.onDidChangeVisibility((visible) => {
if (visible) {
// wait an animation frame. although the visible and attached props are true the editor is not there.
// let the browser render the widget
setTimeout(
() =>
requestAnimationFrame(() => deferred.resolve(editor)),
0
);
}
})
);
}
}
})
);
}
this.editorManager
.open(
new URI(uri),
options ?? {
mode: 'reveal',
preview: false,
counter: 0,
}
)
.then((editorWidget) => {
// If the widget was defined, it was already opened.
// The editor is expected to be attached to the shell and visible in the UI.
// The deferred promise does not have to wait for the `editorManager#onCreated` event.
// It can resolve earlier.
if (widget) {
deferred.resolve(editorWidget);
}
});
const timeout = 5_000; // number of ms IDE2 waits for the editor to show up in the UI
const result: EditorWidget | undefined | 'timeout' = await Promise.race([
deferred.promise,
wait(timeout).then(() => {
disposables.dispose();
return 'timeout' as const;
}),
]);
if (result === 'timeout') {
console.warn(
`Timeout after ${timeout} millis. The editor has not shown up in time. URI: ${uri}`
);
return undefined;
}
return result;
}
}
export namespace OpenSketchFiles {

View File

@@ -1,115 +1,50 @@
import { inject, injectable } from '@theia/core/shared/inversify';
import * as remote from '@theia/core/electron-shared/@electron/remote';
import { MaybePromise } from '@theia/core/lib/common/types';
import { Widget, ContextMenuRenderer } from '@theia/core/lib/browser';
import { nls } from '@theia/core/lib/common/nls';
import { injectable } from '@theia/core/shared/inversify';
import { FileService } from '@theia/filesystem/lib/browser/file-service';
import { LabelProvider } from '@theia/core/lib/browser/label-provider';
import {
Disposable,
DisposableCollection,
} from '@theia/core/lib/common/disposable';
SketchesError,
SketchesService,
SketchRef,
} from '../../common/protocol';
import { ArduinoMenus } from '../menu/arduino-menus';
import { ArduinoToolbar } from '../toolbar/arduino-toolbar';
import {
SketchContribution,
Sketch,
URI,
Command,
CommandRegistry,
MenuModelRegistry,
KeybindingRegistry,
MenuModelRegistry,
Sketch,
SketchContribution,
URI,
} from './contribution';
import { ExamplesService } from '../../common/protocol/examples-service';
import { BuiltInExamples } from './examples';
import { Sketchbook } from './sketchbook';
import { SketchContainer } from '../../common/protocol';
import { nls } from '@theia/core/lib/common';
import { DialogService } from '../dialog-service';
export type SketchLocation = string | URI | SketchRef;
export namespace SketchLocation {
export function toUri(location: SketchLocation): URI {
if (typeof location === 'string') {
return new URI(location);
} else if (SketchRef.is(location)) {
return toUri(location.uri);
} else {
return location;
}
}
export function is(arg: unknown): arg is SketchLocation {
return typeof arg === 'string' || arg instanceof URI || SketchRef.is(arg);
}
}
@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;
@inject(Sketchbook)
protected readonly sketchbook: Sketchbook;
protected readonly toDispose = new DisposableCollection();
override 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 container = await this.sketchService.getSketches({
exclude: ['**/hardware/**'],
});
if (SketchContainer.isEmpty(container)) {
this.openSketch();
} else {
this.toDispose.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: nls.localize(
'vscode/workspaceActions/openFileFolder',
'Open...'
),
}
);
this.toDispose.push(
Disposable.create(() =>
this.menuRegistry.unregisterMenuAction(
OpenSketch.Commands.OPEN_SKETCH
)
)
);
this.sketchbook.registerRecursively(
[...container.children, ...container.sketches],
ArduinoMenus.OPEN_SKETCH__CONTEXT__RECENT_GROUP,
this.toDispose
);
try {
const containers = await this.examplesService.builtIns();
for (const container of containers) {
this.builtInExamples.registerRecursively(
container,
ArduinoMenus.OPEN_SKETCH__CONTEXT__EXAMPLES_GROUP,
this.toDispose
);
}
} 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);
execute: async (arg) => {
const toOpen = !SketchLocation.is(arg)
? await this.selectSketch()
: arg;
if (toOpen) {
return this.openSketch(toOpen);
}
},
});
@@ -119,7 +54,7 @@ export class OpenSketch extends SketchContribution {
registry.registerMenuAction(ArduinoMenus.FILE__SKETCH_GROUP, {
commandId: OpenSketch.Commands.OPEN_SKETCH.id,
label: nls.localize('vscode/workspaceActions/openFileFolder', 'Open...'),
order: '1',
order: '2',
});
}
@@ -130,21 +65,25 @@ export class OpenSketch extends SketchContribution {
});
}
async openSketch(
toOpen: MaybePromise<Sketch | undefined> = this.selectSketch()
): Promise<void> {
const sketch = await toOpen;
if (sketch) {
this.workspaceService.open(new URI(sketch.uri));
private async openSketch(toOpen: SketchLocation | undefined): Promise<void> {
if (!toOpen) {
return;
}
const uri = SketchLocation.toUri(toOpen);
try {
await this.sketchesService.loadSketch(uri.toString());
} catch (err) {
if (SketchesError.NotFound.is(err)) {
this.messageService.error(err.message);
}
throw err;
}
this.workspaceService.open(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({
private async selectSketch(): Promise<Sketch | undefined> {
const defaultPath = await this.defaultPath();
const { filePaths } = await this.dialogService.showOpenDialog({
defaultPath,
properties: ['createDirectory', 'openFile'],
filters: [
@@ -164,50 +103,17 @@ export class OpenSketch extends SketchContribution {
}
const sketchFilePath = filePaths[0];
const sketchFileUri = await this.fileSystemExt.getUri(sketchFilePath);
const sketch = await this.sketchService.getSketchFolder(sketchFileUri);
const sketch = await this.sketchesService.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: nls.localize('arduino/sketch/moving', 'Moving'),
type: 'question',
buttons: [
nls.localize('vscode/issueMainService/cancel', 'Cancel'),
nls.localize('vscode/issueMainService/ok', 'OK'),
],
message: nls.localize(
'arduino/sketch/movingMsg',
'The file "{0}" needs to be inside a sketch folder named "{1}".\nCreate this folder, move the file, and continue?',
nameWithExt,
name
),
return promptMoveSketch(sketchFileUri, {
fileService: this.fileService,
sketchesService: this.sketchesService,
labelProvider: this.labelProvider,
dialogService: this.dialogService,
});
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: nls.localize('vscode/dialog/dialogErrorMessage', 'Error'),
message: nls.localize(
'arduino/sketch/cantOpen',
'A folder named "{0}" already exists. Can\'t open sketch.',
name
),
});
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());
}
}
}
}
@@ -217,8 +123,59 @@ export namespace OpenSketch {
export const OPEN_SKETCH: Command = {
id: 'arduino-open-sketch',
};
export const OPEN_SKETCH__TOOLBAR: Command = {
id: 'arduino-open-sketch--toolbar',
};
}
}
export async function promptMoveSketch(
sketchFileUri: string | URI,
options: {
fileService: FileService;
sketchesService: SketchesService;
labelProvider: LabelProvider;
dialogService: DialogService;
}
): Promise<Sketch | undefined> {
const { fileService, sketchesService, labelProvider, dialogService } =
options;
const uri =
sketchFileUri instanceof URI ? sketchFileUri : new URI(sketchFileUri);
const name = uri.path.name;
const nameWithExt = labelProvider.getName(uri);
const { response } = await dialogService.showMessageBox({
title: nls.localize('arduino/sketch/moving', 'Moving'),
type: 'question',
buttons: [
nls.localize('vscode/issueMainService/cancel', 'Cancel'),
nls.localize('vscode/issueMainService/ok', 'OK'),
],
message: nls.localize(
'arduino/sketch/movingMsg',
'The file "{0}" needs to be inside a sketch folder named "{1}".\nCreate this folder, move the file, and continue?',
nameWithExt,
name
),
});
if (response === 1) {
// OK
const newSketchUri = uri.parent.resolve(name);
const exists = await fileService.exists(newSketchUri);
if (exists) {
await dialogService.showMessageBox({
type: 'error',
title: nls.localize('vscode/dialog/dialogErrorMessage', 'Error'),
message: nls.localize(
'arduino/sketch/cantOpen',
'A folder named "{0}" already exists. Can\'t open sketch.',
name
),
});
return undefined;
}
await fileService.createFolder(newSketchUri);
await fileService.move(
uri,
new URI(newSketchUri.resolve(nameWithExt).toString())
);
return sketchesService.getSketchFolder(newSketchUri.toString());
}
}

View File

@@ -1,5 +1,4 @@
import { injectable } from '@theia/core/shared/inversify';
import * as remote from '@theia/core/electron-shared/@electron/remote';
import { inject, injectable } from '@theia/core/shared/inversify';
import { isOSX } from '@theia/core/lib/common/os';
import {
Contribution,
@@ -9,14 +8,18 @@ import {
CommandRegistry,
} from './contribution';
import { ArduinoMenus } from '../menu/arduino-menus';
import { nls } from '@theia/core/lib/common';
import { nls } from '@theia/core/lib/common/nls';
import { AppService } from '../app-service';
@injectable()
export class QuitApp extends Contribution {
@inject(AppService)
private readonly appService: AppService;
override registerCommands(registry: CommandRegistry): void {
if (!isOSX) {
registry.registerCommand(QuitApp.Commands.QUIT_APP, {
execute: () => remote.app.quit(),
execute: () => this.appService.quit(),
});
}
}

View File

@@ -0,0 +1,166 @@
import { CompositeTreeNode } from '@theia/core/lib/browser/tree';
import { Progress } from '@theia/core/lib/common/message-service-protocol';
import { nls } from '@theia/core/lib/common/nls';
import { injectable } from '@theia/core/shared/inversify';
import { CreateUri } from '../create/create-uri';
import { isConflict } from '../create/typings';
import {
TaskFactoryImpl,
WorkspaceInputDialogWithProgress,
} from '../theia/workspace/workspace-input-dialog';
import { CloudSketchbookTree } from '../widgets/cloud-sketchbook/cloud-sketchbook-tree';
import { CloudSketchbookTreeModel } from '../widgets/cloud-sketchbook/cloud-sketchbook-tree-model';
import {
CloudSketchContribution,
pullingSketch,
pushingSketch,
sketchAlreadyExists,
synchronizingSketchbook,
} from './cloud-contribution';
import { Command, CommandRegistry, Sketch, URI } from './contribution';
export interface RenameCloudSketchParams {
readonly cloudUri: URI;
readonly sketch: Sketch;
}
@injectable()
export class RenameCloudSketch extends CloudSketchContribution {
override registerCommands(registry: CommandRegistry): void {
registry.registerCommand(RenameCloudSketch.Commands.RENAME_CLOUD_SKETCH, {
execute: (params: RenameCloudSketchParams) =>
this.renameSketch(params, true),
});
}
private async renameSketch(
params: RenameCloudSketchParams,
skipShowErrorMessageOnOpen: boolean,
initValue: string = params.sketch.name
): Promise<string | undefined> {
const treeModel = await this.treeModel();
if (treeModel) {
const posixPath = params.cloudUri.path.toString();
const node = treeModel.getNode(posixPath);
const parentNode = node?.parent;
if (
CloudSketchbookTree.CloudSketchDirNode.is(node) &&
CompositeTreeNode.is(parentNode)
) {
return this.openWizard(
params,
node,
parentNode,
treeModel,
skipShowErrorMessageOnOpen,
initValue
);
}
}
return undefined;
}
private async openWizard(
params: RenameCloudSketchParams,
node: CloudSketchbookTree.CloudSketchDirNode,
parentNode: CompositeTreeNode,
treeModel: CloudSketchbookTreeModel,
skipShowErrorMessageOnOpen: boolean,
initialValue?: string | undefined
): Promise<string | undefined> {
const parentUri = CloudSketchbookTree.CloudSketchDirNode.is(parentNode)
? parentNode.uri
: CreateUri.root;
const existingNames = parentNode.children
.filter(CloudSketchbookTree.CloudSketchDirNode.is)
.map(({ fileStat }) => fileStat.name);
const taskFactory = new TaskFactoryImpl((value) =>
this.renameSketchWithProgress(params, node, treeModel, value)
);
try {
const dialog = new WorkspaceInputDialogWithProgress(
{
title: nls.localize(
'arduino/renameCloudSketch/renameSketchTitle',
'New name of the Cloud Sketch'
),
parentUri,
initialValue,
validate: (input) => {
if (existingNames.includes(input)) {
return sketchAlreadyExists(input);
}
return Sketch.validateCloudSketchFolderName(input) ?? '';
},
},
this.labelProvider,
taskFactory
);
await dialog.open(skipShowErrorMessageOnOpen);
return dialog.taskResult;
} catch (err) {
if (isConflict(err)) {
await treeModel.refresh();
return this.renameSketch(
params,
false,
taskFactory.value ?? initialValue
);
}
throw err;
}
}
private renameSketchWithProgress(
params: RenameCloudSketchParams,
node: CloudSketchbookTree.CloudSketchDirNode,
treeModel: CloudSketchbookTreeModel,
value: string
): (progress: Progress) => Promise<string | undefined> {
return async (progress: Progress) => {
const fromName = params.cloudUri.path.name;
const fromPosixPath = params.cloudUri.path.toString();
const toPosixPath = params.cloudUri.parent.resolve(value).path.toString();
// push
progress.report({ message: pushingSketch(params.sketch.name) });
await treeModel.sketchbookTree().push(node, true);
// rename
progress.report({
message: nls.localize(
'arduino/cloudSketch/renaming',
"Renaming cloud sketch from '{0}' to '{1}'...",
fromName,
value
),
});
await this.createApi.rename(fromPosixPath, toPosixPath);
// sync
progress.report({
message: synchronizingSketchbook,
});
this.createApi.sketchCache.init(); // invalidate the cache
await this.createApi.sketches(); // IDE2 must pull all sketches to find the new one
const sketch = this.createApi.sketchCache.getSketch(toPosixPath);
if (!sketch) {
return undefined;
}
await treeModel.refresh();
// pull
progress.report({ message: pullingSketch(sketch.name) });
const pulledNode = await this.pull(sketch);
return pulledNode
? node.uri.parent.resolve(sketch.name).toString()
: undefined;
};
}
}
export namespace RenameCloudSketch {
export namespace Commands {
export const RENAME_CLOUD_SKETCH: Command = {
id: 'arduino-rename-cloud-sketch',
};
}
}

View File

@@ -1,32 +1,37 @@
import { Dialog } from '@theia/core/lib/browser/dialogs';
import { NavigatableWidget } from '@theia/core/lib/browser/navigatable';
import { Saveable } from '@theia/core/lib/browser/saveable';
import { ApplicationShell } from '@theia/core/lib/browser/shell/application-shell';
import { WindowService } from '@theia/core/lib/browser/window/window-service';
import { nls } from '@theia/core/lib/common/nls';
import { inject, injectable } from '@theia/core/shared/inversify';
import * as remote from '@theia/core/electron-shared/@electron/remote';
import * as dateFormat from 'dateformat';
import { EditorManager } from '@theia/editor/lib/browser/editor-manager';
import { WorkspaceInput } from '@theia/workspace/lib/browser/workspace-service';
import { StartupTasks } from '../../electron-common/startup-task';
import { ArduinoMenus } from '../menu/arduino-menus';
import { CurrentSketch } from '../sketches-service-client-impl';
import { CloudSketchContribution } from './cloud-contribution';
import {
SketchContribution,
URI,
Command,
CommandRegistry,
MenuModelRegistry,
KeybindingRegistry,
MenuModelRegistry,
Sketch,
URI,
} from './contribution';
import { nls } from '@theia/core/lib/common';
import { ApplicationShell, NavigatableWidget, Saveable } from '@theia/core/lib/browser';
import { EditorManager } from '@theia/editor/lib/browser';
import { WindowService } from '@theia/core/lib/browser/window/window-service';
import { CurrentSketch } from '../../common/protocol/sketches-service-client-impl';
import { DeleteSketch } from './delete-sketch';
import {
RenameCloudSketch,
RenameCloudSketchParams,
} from './rename-cloud-sketch';
import { assertConnectedToBackend } from './save-sketch';
@injectable()
export class SaveAsSketch extends SketchContribution {
export class SaveAsSketch extends CloudSketchContribution {
@inject(ApplicationShell)
protected readonly applicationShell: ApplicationShell;
@inject(EditorManager)
protected override readonly editorManager: EditorManager;
private readonly shell: ApplicationShell;
@inject(WindowService)
protected readonly windowService: WindowService;
private readonly windowService: WindowService;
override registerCommands(registry: CommandRegistry): void {
registry.registerCommand(SaveAsSketch.Commands.SAVE_AS_SKETCH, {
@@ -37,7 +42,7 @@ export class SaveAsSketch extends SketchContribution {
override registerMenus(registry: MenuModelRegistry): void {
registry.registerMenuAction(ArduinoMenus.FILE__SKETCH_GROUP, {
commandId: SaveAsSketch.Commands.SAVE_AS_SKETCH.id,
label: nls.localize('vscode/fileCommands/saveAs', 'Save As...'),
label: nls.localizeByDefault('Save As...'),
order: '7',
});
}
@@ -52,111 +57,197 @@ export class SaveAsSketch extends SketchContribution {
/**
* Resolves `true` if the sketch was successfully saved as something.
*/
async saveAs(
private async saveAs(
{
execOnlyIfTemp,
openAfterMove,
wipeOriginal,
markAsRecentlyOpened,
}: SaveAsSketch.Options = SaveAsSketch.Options.DEFAULT
): Promise<boolean> {
assertConnectedToBackend({
connectionStatusService: this.connectionStatusService,
messageService: this.messageService,
});
const sketch = await this.sketchServiceClient.currentSketch();
if (!CurrentSketch.isValid(sketch)) {
return false;
}
const isTemp = await this.sketchService.isTemp(sketch);
if (!isTemp && !!execOnlyIfTemp) {
return false;
let destinationUri: string | undefined;
const cloudUri = this.createFeatures.cloudUri(sketch);
if (cloudUri) {
destinationUri = await this.createCloudCopy({ cloudUri, sketch });
} else {
destinationUri = await this.createLocalCopy(sketch, execOnlyIfTemp);
}
// 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 = sketchDirUri.resolve(
exists
? `${sketch.name}_copy_${dateFormat(new Date(), 'yyyymmddHHMMss')}`
: sketch.name
);
const defaultPath = await this.fileService.fsPath(defaultUri);
const { filePath, canceled } = await remote.dialog.showSaveDialog({
title: nls.localize(
'arduino/sketch/saveFolderAs',
'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, {
const copiedSketch = await this.sketchesService.copy(sketch, {
destinationUri,
});
if (workspaceUri) {
await this.saveOntoCopiedSketch(sketch.mainFileUri, sketch.uri, workspaceUri);
const newWorkspaceUri = copiedSketch.uri;
await saveOntoCopiedSketch(
sketch,
newWorkspaceUri,
this.shell,
this.editorManager
);
if (markAsRecentlyOpened) {
this.sketchesService.markAsRecentlyOpened(newWorkspaceUri);
}
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 */
}
}
const options: WorkspaceInput & StartupTasks = {
preserveWindow: true,
tasks: [],
};
if (openAfterMove) {
this.windowService.setSafeToShutDown();
this.workspaceService.open(new URI(workspaceUri), {
preserveWindow: true,
});
if (wipeOriginal || (openAfterMove && execOnlyIfTemp)) {
options.tasks.push({
command: DeleteSketch.Commands.DELETE_SKETCH.id,
args: [{ toDelete: sketch.uri }],
});
}
this.workspaceService.open(new URI(newWorkspaceUri), options);
}
return !!workspaceUri;
return !!newWorkspaceUri;
}
private async saveOntoCopiedSketch(mainFileUri: string, sketchUri: string, newSketchUri: string): Promise<void> {
const widgets = this.applicationShell.widgets;
const snapshots = new Map<string, object>();
for (const widget of widgets) {
const saveable = Saveable.getDirty(widget);
const uri = NavigatableWidget.getUri(widget);
const uriString = uri?.toString();
let relativePath: string;
if (uri && uriString!.includes(sketchUri) && saveable && saveable.createSnapshot) {
// The main file will change its name during the copy process
// We need to store the new name in the map
if (mainFileUri === uriString) {
const lastPart = new URI(newSketchUri).path.base + uri.path.ext;
relativePath = '/' + lastPart;
} else {
relativePath = uri.toString().substring(sketchUri.length);
private async createCloudCopy(
params: RenameCloudSketchParams
): Promise<string | undefined> {
return this.commandService.executeCommand<string>(
RenameCloudSketch.Commands.RENAME_CLOUD_SKETCH.id,
params
);
}
private async createLocalCopy(
sketch: Sketch,
execOnlyIfTemp?: boolean
): Promise<string | undefined> {
const isTemp = await this.sketchesService.isTemp(sketch);
if (!isTemp && !!execOnlyIfTemp) {
return undefined;
}
const sketchUri = new URI(sketch.uri);
const sketchbookDirUri = await this.defaultUri();
// If the sketch is temp, IDE2 proposes the default sketchbook folder URI.
// If the sketch is not temp, but not contained in the default sketchbook folder, IDE2 proposes the default location.
// Otherwise, it proposes the parent folder of the current sketch.
const containerDirUri = isTemp
? sketchbookDirUri
: !sketchbookDirUri.isEqualOrParent(sketchUri)
? sketchbookDirUri
: sketchUri.parent;
const exists = await this.fileService.exists(
containerDirUri.resolve(sketch.name)
);
// If target does not exist, propose a `directories.user`/${sketch.name} path
// If target exists, propose `directories.user`/${sketch.name}_copy_${yyyymmddHHMMss}
// IDE2 must never prompt an invalid sketch folder name (https://github.com/arduino/arduino-ide/pull/1833#issuecomment-1412569252)
const defaultUri = containerDirUri.resolve(
Sketch.toValidSketchFolderName(sketch.name, exists)
);
const defaultPath = await this.fileService.fsPath(defaultUri);
return await this.promptLocalSketchFolderDestination(sketch, defaultPath);
}
/**
* Prompts for the new sketch folder name until a valid one is give,
* then resolves with the destination sketch folder URI string,
* or `undefined` if the operation was canceled.
*/
private async promptLocalSketchFolderDestination(
sketch: Sketch,
defaultPath: string
): Promise<string | undefined> {
let sketchFolderDestinationUri: string | undefined;
while (!sketchFolderDestinationUri) {
const { filePath } = await this.dialogService.showSaveDialog({
title: nls.localize(
'arduino/sketch/saveFolderAs',
'Save sketch folder as...'
),
defaultPath,
});
if (!filePath) {
return undefined;
}
const destinationUri = await this.fileSystemExt.getUri(filePath);
// The new location of the sketch cannot be inside the location of current sketch.
// https://github.com/arduino/arduino-ide/issues/1882
let dialogContent: InvalidSketchFolderDialogContent | undefined;
if (new URI(sketch.uri).isEqualOrParent(new URI(destinationUri))) {
dialogContent = {
message: nls.localize(
'arduino/sketch/invalidSketchFolderLocationMessage',
"Invalid sketch folder location: '{0}'",
filePath
),
details: nls.localize(
'arduino/sketch/invalidSketchFolderLocationDetails',
'You cannot save a sketch into a folder inside itself.'
),
question: nls.localize(
'arduino/sketch/editInvalidSketchFolderLocationQuestion',
'Do you want to try saving the sketch to a different location?'
),
};
}
if (!dialogContent) {
const sketchFolderName = new URI(destinationUri).path.base;
const errorMessage = Sketch.validateSketchFolderName(sketchFolderName);
if (errorMessage) {
dialogContent = {
message: nls.localize(
'arduino/sketch/invalidSketchFolderNameMessage',
"Invalid sketch folder name: '{0}'",
sketchFolderName
),
details: errorMessage,
question: nls.localize(
'arduino/sketch/editInvalidSketchFolderQuestion',
'Do you want to try saving the sketch with a different name?'
),
};
}
snapshots.set(relativePath, saveable.createSnapshot());
}
if (dialogContent) {
const message = `
${dialogContent.message}
${dialogContent.details}
${dialogContent.question}`.trim();
defaultPath = filePath;
const { response } = await this.dialogService.showMessageBox({
message,
buttons: [Dialog.CANCEL, Dialog.YES],
});
// cancel
if (response === 0) {
return undefined;
}
} else {
sketchFolderDestinationUri = destinationUri;
}
}
await Promise.all(Array.from(snapshots.entries()).map(async ([path, snapshot]) => {
const widgetUri = new URI(newSketchUri + path);
try {
const widget = await this.editorManager.getOrCreateByUri(widgetUri);
const saveable = Saveable.get(widget);
if (saveable && saveable.applySnapshot) {
saveable.applySnapshot(snapshot);
await saveable.save();
}
} catch (e) {
console.error(e);
}
}));
return sketchFolderDestinationUri;
}
}
interface InvalidSketchFolderDialogContent {
readonly message: string;
readonly details: string;
readonly question: string;
}
export namespace SaveAsSketch {
export namespace Commands {
export const SAVE_AS_SKETCH: Command = {
@@ -170,12 +261,59 @@ export namespace SaveAsSketch {
* Ignored if `openAfterMove` is `false`.
*/
readonly wipeOriginal?: boolean;
readonly markAsRecentlyOpened?: boolean;
}
export namespace Options {
export const DEFAULT: Options = {
execOnlyIfTemp: false,
openAfterMove: true,
wipeOriginal: false,
markAsRecentlyOpened: false,
};
}
}
export async function saveOntoCopiedSketch(
sketch: Sketch,
newSketchFolderUri: string,
shell: ApplicationShell,
editorManager: EditorManager
): Promise<void> {
const widgets = shell.widgets;
const snapshots = new Map<string, Saveable.Snapshot>();
for (const widget of widgets) {
const saveable = Saveable.getDirty(widget);
const uri = NavigatableWidget.getUri(widget);
if (!uri) {
continue;
}
const uriString = uri.toString();
let relativePath: string;
if (uriString.includes(sketch.uri) && saveable && saveable.createSnapshot) {
// The main file will change its name during the copy process
// We need to store the new name in the map
if (sketch.mainFileUri === uriString) {
const lastPart = new URI(newSketchFolderUri).path.base + uri.path.ext;
relativePath = '/' + lastPart;
} else {
relativePath = uri.toString().substring(sketch.uri.length);
}
snapshots.set(relativePath, saveable.createSnapshot());
}
}
await Promise.all(
Array.from(snapshots.entries()).map(async ([path, snapshot]) => {
const widgetUri = new URI(newSketchFolderUri + path);
try {
const widget = await editorManager.getOrCreateByUri(widgetUri);
const saveable = Saveable.get(widget);
if (saveable && saveable.applySnapshot) {
saveable.applySnapshot(snapshot);
await saveable.save();
}
} catch (e) {
console.error(e);
}
})
);
}

View File

@@ -1,17 +1,18 @@
import { injectable } from '@theia/core/shared/inversify';
import { CommonCommands } from '@theia/core/lib/browser/common-frontend-contribution';
import { MessageService } from '@theia/core/lib/common/message-service';
import { nls } from '@theia/core/lib/common/nls';
import { injectable } from '@theia/core/shared/inversify';
import { ArduinoMenus } from '../menu/arduino-menus';
import { ArduinoToolbar } from '../toolbar/arduino-toolbar';
import { SaveAsSketch } from './save-as-sketch';
import { CurrentSketch } from '../sketches-service-client-impl';
import { ApplicationConnectionStatusContribution } from '../theia/core/connection-status-service';
import {
SketchContribution,
Command,
CommandRegistry,
MenuModelRegistry,
KeybindingRegistry,
MenuModelRegistry,
SketchContribution,
} from './contribution';
import { nls } from '@theia/core/lib/common';
import { CurrentSketch } from '../../common/protocol/sketches-service-client-impl';
import { SaveAsSketch } from './save-as-sketch';
@injectable()
export class SaveSketch extends SketchContribution {
@@ -19,19 +20,13 @@ export class SaveSketch extends SketchContribution {
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),
});
}
override registerMenus(registry: MenuModelRegistry): void {
registry.registerMenuAction(ArduinoMenus.FILE__SKETCH_GROUP, {
commandId: SaveSketch.Commands.SAVE_SKETCH.id,
label: nls.localize('vscode/fileCommands/save', 'Save'),
order: '6',
order: '7',
});
}
@@ -43,11 +38,15 @@ export class SaveSketch extends SketchContribution {
}
async saveSketch(): Promise<void> {
assertConnectedToBackend({
connectionStatusService: this.connectionStatusService,
messageService: this.messageService,
});
const sketch = await this.sketchServiceClient.currentSketch();
if (!CurrentSketch.isValid(sketch)) {
return;
}
const isTemp = await this.sketchService.isTemp(sketch);
const isTemp = await this.sketchesService.isTemp(sketch);
if (isTemp) {
return this.commandService.executeCommand(
SaveAsSketch.Commands.SAVE_AS_SKETCH.id,
@@ -68,8 +67,20 @@ export namespace SaveSketch {
export const SAVE_SKETCH: Command = {
id: 'arduino-save-sketch',
};
export const SAVE_SKETCH__TOOLBAR: Command = {
id: 'arduino-save-sketch--toolbar',
};
}
}
// https://github.com/arduino/arduino-ide/issues/2081
export function assertConnectedToBackend(param: {
connectionStatusService: ApplicationConnectionStatusContribution;
messageService: MessageService;
}): void {
if (param.connectionStatusService.offlineStatus === 'backend') {
const message = nls.localize(
'theia/core/couldNotSave',
'Could not save the sketch. Please copy your unsaved work into your favorite text editor, and restart the IDE.'
);
param.messageService.error(message);
throw new Error(message);
}
}

View File

@@ -4,7 +4,10 @@ import {
} from '@theia/core/lib/browser/status-bar/status-bar';
import { nls } from '@theia/core/lib/common/nls';
import { inject, injectable } from '@theia/core/shared/inversify';
import { BoardsConfig } from '../boards/boards-config';
import type {
BoardList,
BoardListItem,
} from '../../common/protocol/board-list';
import { BoardsServiceProvider } from '../boards/boards-service-provider';
import { Contribution } from './contribution';
@@ -12,21 +15,21 @@ import { Contribution } from './contribution';
export class SelectedBoard extends Contribution {
@inject(StatusBar)
private readonly statusBar: StatusBar;
@inject(BoardsServiceProvider)
private readonly boardsServiceProvider: BoardsServiceProvider;
override onStart(): void {
this.boardsServiceProvider.onBoardsConfigChanged((config) =>
this.update(config)
this.boardsServiceProvider.onBoardListDidChange(() =>
this.update(this.boardsServiceProvider.boardList)
);
}
override onReady(): void {
this.update(this.boardsServiceProvider.boardsConfig);
this.update(this.boardsServiceProvider.boardList);
}
private update({ selectedBoard, selectedPort }: BoardsConfig.Config): void {
private update(boardList: BoardList): void {
const { selectedBoard, selectedPort } = boardList.boardsConfig;
this.statusBar.setElement('arduino-selected-board', {
alignment: StatusBarAlignment.RIGHT,
text: selectedBoard
@@ -38,17 +41,30 @@ export class SelectedBoard extends Contribution {
className: 'arduino-selected-board',
});
if (selectedBoard) {
const notConnectedLabel = nls.localize(
'arduino/common/notConnected',
'[not connected]'
);
let portLabel = notConnectedLabel;
if (selectedPort) {
portLabel = nls.localize(
'arduino/common/selectedOn',
'on {0}',
selectedPort.address
);
const selectedItem: BoardListItem | undefined =
boardList.items[boardList.selectedIndex];
if (!selectedItem) {
portLabel += ` ${notConnectedLabel}`; // append ` [not connected]` when the port is selected but it's not detected by the CLI
}
}
this.statusBar.setElement('arduino-selected-port', {
alignment: StatusBarAlignment.RIGHT,
text: selectedPort
? nls.localize(
'arduino/common/selectedOn',
'on {0}',
selectedPort.address
)
: nls.localize('arduino/common/notConnected', '[not connected]'),
text: portLabel,
className: 'arduino-selected-port',
});
} else {
this.statusBar.removeElement('arduino-selected-port');
}
}
}

View File

@@ -1,50 +1,34 @@
import { inject, injectable } from '@theia/core/shared/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 { ApplicationShell } from '@theia/core/lib/browser/shell/application-shell';
import {
Disposable,
DisposableCollection,
} from '@theia/core/lib/common/disposable';
import { nls } from '@theia/core/lib/common/nls';
import { inject, injectable } from '@theia/core/shared/inversify';
import { WorkspaceCommands } from '@theia/workspace/lib/browser/workspace-commands';
import { ArduinoMenus } from '../menu/arduino-menus';
import { CurrentSketch } from '../sketches-service-client-impl';
import {
URI,
SketchContribution,
Command,
CommandRegistry,
MenuModelRegistry,
KeybindingRegistry,
TabBarToolbarRegistry,
MenuModelRegistry,
open,
SketchContribution,
TabBarToolbarRegistry,
URI,
} from './contribution';
import { ArduinoMenus, PlaceholderMenuNode } from '../menu/arduino-menus';
import { EditorManager } from '@theia/editor/lib/browser/editor-manager';
import {
CurrentSketch,
SketchesServiceClientImpl,
} from '../../common/protocol/sketches-service-client-impl';
import { LocalCacheFsProvider } from '../local-cache/local-cache-fs-provider';
import { nls } from '@theia/core/lib/common';
@injectable()
export class SketchControl extends SketchContribution {
@inject(ApplicationShell)
protected readonly shell: ApplicationShell;
private readonly shell: ApplicationShell;
@inject(MenuModelRegistry)
protected readonly menuRegistry: MenuModelRegistry;
private readonly menuRegistry: MenuModelRegistry;
@inject(ContextMenuRenderer)
protected readonly contextMenuRenderer: ContextMenuRenderer;
@inject(EditorManager)
protected override readonly editorManager: EditorManager;
@inject(SketchesServiceClientImpl)
protected readonly sketchesServiceClient: SketchesServiceClientImpl;
@inject(LocalCacheFsProvider)
protected readonly localCacheFsProvider: LocalCacheFsProvider;
private readonly contextMenuRenderer: ContextMenuRenderer;
protected readonly toDisposeBeforeCreateNewContextMenu =
new DisposableCollection();
@@ -57,107 +41,57 @@ export class SketchControl extends SketchContribution {
this.shell.getWidgets('main').indexOf(widget) !== -1,
execute: async () => {
this.toDisposeBeforeCreateNewContextMenu.dispose();
let parentElement: HTMLElement | undefined = undefined;
const target = document.getElementById(
SketchControl.Commands.OPEN_SKETCH_CONTROL__TOOLBAR.id
);
if (target instanceof HTMLElement) {
parentElement = target.parentElement ?? undefined;
}
if (!parentElement) {
return;
}
const sketch = await this.sketchServiceClient.currentSketch();
if (!CurrentSketch.isValid(sketch)) {
return;
}
const target = document.getElementById(
SketchControl.Commands.OPEN_SKETCH_CONTROL__TOOLBAR.id
this.menuRegistry.registerMenuAction(
ArduinoMenus.SKETCH_CONTROL__CONTEXT__MAIN_GROUP,
{
commandId: WorkspaceCommands.FILE_RENAME.id,
label: nls.localize('vscode/fileActions/rename', 'Rename'),
order: '1',
}
);
this.toDisposeBeforeCreateNewContextMenu.push(
Disposable.create(() =>
this.menuRegistry.unregisterMenuAction(
WorkspaceCommands.FILE_RENAME
)
)
);
this.menuRegistry.registerMenuAction(
ArduinoMenus.SKETCH_CONTROL__CONTEXT__MAIN_GROUP,
{
commandId: WorkspaceCommands.FILE_DELETE.id,
label: nls.localize('vscode/fileActions/delete', 'Delete'),
order: '2',
}
);
this.toDisposeBeforeCreateNewContextMenu.push(
Disposable.create(() =>
this.menuRegistry.unregisterMenuAction(
WorkspaceCommands.FILE_DELETE
)
)
);
if (!(target instanceof HTMLElement)) {
return;
}
const { parentElement } = target;
if (!parentElement) {
return;
}
const { mainFileUri, rootFolderFileUris } = sketch;
const uris = [mainFileUri, ...rootFolderFileUris];
const parentSketchUri = this.editorManager.currentEditor
?.getResourceUri()
?.toString();
const parentSketch = await this.sketchService.getSketchFolder(
parentSketchUri || ''
);
// if the current file is in the current opened sketch, show extra menus
if (
sketch &&
parentSketch &&
parentSketch.uri === sketch.uri &&
this.allowRename(parentSketch.uri)
) {
this.menuRegistry.registerMenuAction(
ArduinoMenus.SKETCH_CONTROL__CONTEXT__MAIN_GROUP,
{
commandId: WorkspaceCommands.FILE_RENAME.id,
label: nls.localize('vscode/fileActions/rename', 'Rename'),
order: '1',
}
);
this.toDisposeBeforeCreateNewContextMenu.push(
Disposable.create(() =>
this.menuRegistry.unregisterMenuAction(
WorkspaceCommands.FILE_RENAME
)
)
);
} else {
const renamePlaceholder = new PlaceholderMenuNode(
ArduinoMenus.SKETCH_CONTROL__CONTEXT__MAIN_GROUP,
nls.localize('vscode/fileActions/rename', 'Rename')
);
this.menuRegistry.registerMenuNode(
ArduinoMenus.SKETCH_CONTROL__CONTEXT__MAIN_GROUP,
renamePlaceholder
);
this.toDisposeBeforeCreateNewContextMenu.push(
Disposable.create(() =>
this.menuRegistry.unregisterMenuNode(renamePlaceholder.id)
)
);
}
if (
sketch &&
parentSketch &&
parentSketch.uri === sketch.uri &&
this.allowDelete(parentSketch.uri)
) {
this.menuRegistry.registerMenuAction(
ArduinoMenus.SKETCH_CONTROL__CONTEXT__MAIN_GROUP,
{
commandId: WorkspaceCommands.FILE_DELETE.id, // TODO: customize delete. Wipe sketch if deleting main file. Close window.
label: nls.localize('vscode/fileActions/delete', 'Delete'),
order: '2',
}
);
this.toDisposeBeforeCreateNewContextMenu.push(
Disposable.create(() =>
this.menuRegistry.unregisterMenuAction(
WorkspaceCommands.FILE_DELETE
)
)
);
} else {
const deletePlaceholder = new PlaceholderMenuNode(
ArduinoMenus.SKETCH_CONTROL__CONTEXT__MAIN_GROUP,
nls.localize('vscode/fileActions/delete', 'Delete')
);
this.menuRegistry.registerMenuNode(
ArduinoMenus.SKETCH_CONTROL__CONTEXT__MAIN_GROUP,
deletePlaceholder
);
this.toDisposeBeforeCreateNewContextMenu.push(
Disposable.create(() =>
this.menuRegistry.unregisterMenuNode(deletePlaceholder.id)
)
);
}
for (let i = 0; i < uris.length; i++) {
const uri = new URI(uris[i]);
@@ -176,7 +110,7 @@ export class SketchControl extends SketchContribution {
{
commandId: command.id,
label: this.labelProvider.getName(uri),
order: `${i}`,
order: String(i).padStart(4),
}
);
this.toDisposeBeforeCreateNewContextMenu.push(
@@ -193,6 +127,7 @@ export class SketchControl extends SketchContribution {
parentElement.getBoundingClientRect().top +
parentElement.offsetHeight,
},
showDisabled: true,
};
this.contextMenuRenderer.render(options);
},
@@ -235,7 +170,7 @@ export class SketchControl extends SketchContribution {
});
registry.registerKeybinding({
command: CommonCommands.PREVIOUS_TAB.id,
keybinding: 'CtrlCmd+Alt+Left', // TODO: check why electron does not show the keybindings in the UI.
keybinding: 'CtrlCmd+Alt+Left',
});
registry.registerKeybinding({
command: CommonCommands.NEXT_TAB.id,
@@ -249,27 +184,6 @@ export class SketchControl extends SketchContribution {
command: SketchControl.Commands.OPEN_SKETCH_CONTROL__TOOLBAR.id,
});
}
protected isCloudSketch(uri: string): boolean {
try {
const cloudCacheLocation = this.localCacheFsProvider.from(new URI(uri));
if (cloudCacheLocation) {
return true;
}
return false;
} catch {
return false;
}
}
protected allowRename(uri: string): boolean {
return !this.isCloudSketch(uri);
}
protected allowDelete(uri: string): boolean {
return !this.isCloudSketch(uri);
}
}
export namespace SketchControl {

View File

@@ -3,8 +3,8 @@ import { DisposableCollection } from '@theia/core/lib/common/disposable';
import { inject, injectable } from '@theia/core/shared/inversify';
import { FileSystemFrontendContribution } from '@theia/filesystem/lib/browser/filesystem-frontend-contribution';
import { FileChangeType } from '@theia/filesystem/lib/common/files';
import { CurrentSketch } from '../../common/protocol/sketches-service-client-impl';
import { Sketch, SketchContribution, URI } from './contribution';
import { CurrentSketch } from '../sketches-service-client-impl';
import { Sketch, SketchContribution } from './contribution';
import { OpenSketchFiles } from './open-sketch-files';
@injectable()
@@ -30,11 +30,7 @@ export class SketchFilesTracker extends SketchContribution {
override onReady(): void {
this.sketchServiceClient.currentSketch().then(async (sketch) => {
if (
CurrentSketch.isValid(sketch) &&
!(await this.sketchService.isTemp(sketch))
) {
this.toDisposeOnStop.push(this.fileService.watch(new URI(sketch.uri)));
if (CurrentSketch.isValid(sketch)) {
this.toDisposeOnStop.push(
this.fileService.onDidFilesChange(async (event) => {
for (const { type, resource } of event.changes) {
@@ -42,7 +38,7 @@ export class SketchFilesTracker extends SketchContribution {
type === FileChangeType.ADDED &&
resource.parent.toString() === sketch.uri
) {
const reloadedSketch = await this.sketchService.loadSketch(
const reloadedSketch = await this.sketchesService.loadSketch(
sketch.uri
);
if (Sketch.isInSketch(resource, reloadedSketch)) {

View File

@@ -1,44 +1,27 @@
import { inject, injectable } from '@theia/core/shared/inversify';
import { injectable } from '@theia/core/shared/inversify';
import { CommandHandler } from '@theia/core/lib/common/command';
import { CommandRegistry, MenuModelRegistry } from './contribution';
import { MenuModelRegistry } from './contribution';
import { ArduinoMenus } from '../menu/arduino-menus';
import { MainMenuManager } from '../../common/main-menu-manager';
import { NotificationCenter } from '../notification-center';
import { Examples } from './examples';
import {
SketchContainer,
SketchesError,
SketchRef,
} from '../../common/protocol';
import { SketchContainer, SketchesError } from '../../common/protocol';
import { OpenSketch } from './open-sketch';
import { nls } from '@theia/core/lib/common';
import { nls } from '@theia/core/lib/common/nls';
@injectable()
export class Sketchbook extends Examples {
@inject(CommandRegistry)
protected override readonly commandRegistry: CommandRegistry;
@inject(MenuModelRegistry)
protected override readonly menuRegistry: MenuModelRegistry;
@inject(MainMenuManager)
protected readonly mainMenuManager: MainMenuManager;
@inject(NotificationCenter)
protected readonly notificationCenter: NotificationCenter;
override onStart(): void {
this.sketchServiceClient.onSketchbookDidChange(() => this.update());
this.configService.onDidChangeSketchDirUri(() => this.update());
}
override async onReady(): Promise<void> {
this.update();
}
private update() {
this.sketchService.getSketches({}).then((container) => {
protected override update(): void {
this.sketchesService.getSketches({}).then((container) => {
this.register(container);
this.mainMenuManager.update();
this.menuManager.update();
});
}
@@ -50,7 +33,7 @@ export class Sketchbook extends Examples {
);
}
protected register(container: SketchContainer): void {
private register(container: SketchContainer): void {
this.toDispose.dispose();
this.registerRecursively(
[...container.children, ...container.sketches],
@@ -62,23 +45,18 @@ export class Sketchbook extends Examples {
protected override createHandler(uri: string): CommandHandler {
return {
execute: async () => {
let sketch: SketchRef | undefined = undefined;
try {
sketch = await this.sketchService.loadSketch(uri);
} catch (err) {
if (SketchesError.NotFound.is(err)) {
// To handle the following:
// Open IDE2, delete a sketch from sketchbook, click on File > Sketchbook > the deleted sketch.
// Filesystem watcher misses out delete events on macOS; hence IDE2 has no chance to update the menu items.
this.messageService.error(err.message);
this.update();
}
}
if (sketch) {
await this.commandService.executeCommand(
OpenSketch.Commands.OPEN_SKETCH.id,
sketch
uri
);
} catch (err) {
if (SketchesError.NotFound.is(err)) {
// Force update the menu items to remove the absent sketch.
this.update();
} else {
throw err;
}
}
},
};

View File

@@ -0,0 +1,65 @@
import { DisposableCollection } from '@theia/core/lib/common/disposable';
import {
inject,
injectable,
postConstruct,
} from '@theia/core/shared/inversify';
import {
hasStartupTasks,
StartupTasks,
} from '../../electron-common/startup-task';
import { AppService } from '../app-service';
import { Contribution } from './contribution';
@injectable()
export class StartupTasksExecutor extends Contribution {
@inject(AppService)
private readonly appService: AppService;
private readonly toDispose = new DisposableCollection();
@postConstruct()
protected override init(): void {
super.init();
this.toDispose.push(
this.appService.registerStartupTasksHandler((tasks) =>
this.handleStartupTasks(tasks)
)
);
}
onStop(): void {
this.toDispose.dispose();
}
private async handleStartupTasks(tasks: StartupTasks): Promise<void> {
console.debug(
`Received the startup tasks from the electron main process. Args: ${JSON.stringify(
tasks
)}`
);
if (!hasStartupTasks(tasks)) {
console.warn(`Could not detect 'tasks' from the signal. Skipping.`);
return;
}
await this.appStateService.reachedState('ready');
console.log(`Executing startup tasks:`);
tasks.tasks.forEach(({ command, args = [] }) => {
console.log(
` - '${command}' ${
args.length ? `, args: ${JSON.stringify(args)}` : ''
}`
);
this.commandService
.executeCommand(command, ...args)
.catch((err) =>
console.error(
`Error occurred when executing the startup task '${command}'${
args?.length ? ` with args: '${JSON.stringify(args)}` : ''
}.`,
err
)
);
});
}
}

View File

@@ -0,0 +1,176 @@
import { DisposableCollection } from '@theia/core/lib/common/disposable';
import URI from '@theia/core/lib/common/uri';
import { inject, injectable } from '@theia/core/shared/inversify';
import { HostedPluginSupport } from '@theia/plugin-ext/lib/hosted/browser/hosted-plugin';
import type { ArduinoState } from 'vscode-arduino-api';
import {
BoardsService,
CompileSummary,
isCompileSummary,
BoardsConfig,
PortIdentifier,
resolveDetectedPort,
} from '../../common/protocol';
import {
toApiBoardDetails,
toApiCompileSummary,
toApiPort,
} from '../../common/protocol/arduino-context-mapper';
import { BoardsDataStore } from '../boards/boards-data-store';
import { BoardsServiceProvider } from '../boards/boards-service-provider';
import { CurrentSketch } from '../sketches-service-client-impl';
import { SketchContribution } from './contribution';
interface UpdateStateParams<T extends ArduinoState> {
readonly key: keyof T;
readonly value: T[keyof T];
}
/**
* Contribution for updating the Arduino state, such as the FQBN, selected port, and sketch path changes via commands, so other VS Code extensions can access it.
* See [`vscode-arduino-api`](https://github.com/dankeboy36/vscode-arduino-api#api) for more details.
*/
@injectable()
export class UpdateArduinoState extends SketchContribution {
@inject(BoardsService)
private readonly boardsService: BoardsService;
@inject(BoardsServiceProvider)
private readonly boardsServiceProvider: BoardsServiceProvider;
@inject(BoardsDataStore)
private readonly boardsDataStore: BoardsDataStore;
@inject(HostedPluginSupport)
private readonly hostedPluginSupport: HostedPluginSupport;
private readonly toDispose = new DisposableCollection();
override onStart(): void {
this.toDispose.pushAll([
this.boardsServiceProvider.onBoardsConfigDidChange(() =>
this.updateBoardsConfig(this.boardsServiceProvider.boardsConfig)
),
this.sketchServiceClient.onCurrentSketchDidChange((sketch) =>
this.updateSketchPath(sketch)
),
this.configService.onDidChangeDataDirUri((dataDirUri) =>
this.updateDataDirPath(dataDirUri)
),
this.configService.onDidChangeSketchDirUri((userDirUri) =>
this.updateUserDirPath(userDirUri)
),
this.commandService.onDidExecuteCommand(({ commandId, args }) => {
if (
commandId === 'arduino.languageserver.notifyBuildDidComplete' &&
isCompileSummary(args[0])
) {
this.updateCompileSummary(args[0]);
}
}),
this.boardsDataStore.onChanged((fqbn) => {
const selectedFqbn =
this.boardsServiceProvider.boardsConfig.selectedBoard?.fqbn;
if (selectedFqbn && fqbn.includes(selectedFqbn)) {
this.updateBoardDetails(selectedFqbn);
}
}),
]);
}
override onReady(): void {
this.updateBoardsConfig(this.boardsServiceProvider.boardsConfig); // TODO: verify!
this.updateSketchPath(this.sketchServiceClient.tryGetCurrentSketch());
this.updateUserDirPath(this.configService.tryGetSketchDirUri());
this.updateDataDirPath(this.configService.tryGetDataDirUri());
}
onStop(): void {
this.toDispose.dispose();
}
private async updateSketchPath(
sketch: CurrentSketch | undefined
): Promise<void> {
const sketchPath = CurrentSketch.isValid(sketch)
? new URI(sketch.uri).path.fsPath()
: undefined;
return this.updateState({ key: 'sketchPath', value: sketchPath });
}
private async updateCompileSummary(
compileSummary: CompileSummary
): Promise<void> {
const apiCompileSummary = toApiCompileSummary(compileSummary);
return this.updateState({
key: 'compileSummary',
value: apiCompileSummary,
});
}
private async updateBoardsConfig(boardsConfig: BoardsConfig): Promise<void> {
const fqbn = boardsConfig.selectedBoard?.fqbn;
const port = boardsConfig.selectedPort;
await this.updateFqbn(fqbn);
await this.updateBoardDetails(fqbn);
await this.updatePort(port);
}
private async updateFqbn(fqbn: string | undefined): Promise<void> {
await this.updateState({ key: 'fqbn', value: fqbn });
}
private async updateBoardDetails(fqbn: string | undefined): Promise<void> {
const unset = () =>
this.updateState({ key: 'boardDetails', value: undefined });
if (!fqbn) {
return unset();
}
const [details, persistedData] = await Promise.all([
this.boardsService.getBoardDetails({ fqbn }),
this.boardsDataStore.getData(fqbn),
]);
if (!details) {
return unset();
}
const apiBoardDetails = toApiBoardDetails({
...details,
configOptions:
BoardsDataStore.Data.EMPTY === persistedData
? details.configOptions
: persistedData.configOptions.slice(),
});
return this.updateState({
key: 'boardDetails',
value: apiBoardDetails,
});
}
private async updatePort(port: PortIdentifier | undefined): Promise<void> {
const resolvedPort =
port &&
resolveDetectedPort(port, this.boardsServiceProvider.detectedPorts);
const apiPort = resolvedPort && toApiPort(resolvedPort);
return this.updateState({ key: 'port', value: apiPort });
}
private async updateUserDirPath(userDirUri: URI | undefined): Promise<void> {
const userDirPath = userDirUri?.path.fsPath();
return this.updateState({
key: 'userDirPath',
value: userDirPath,
});
}
private async updateDataDirPath(dataDirUri: URI | undefined): Promise<void> {
const dataDirPath = dataDirUri?.path.fsPath();
return this.updateState({
key: 'dataDirPath',
value: dataDirPath,
});
}
private async updateState<T extends ArduinoState>(
params: UpdateStateParams<T>
): Promise<void> {
await this.hostedPluginSupport.didStart;
return this.commandService.executeCommand('arduinoAPI.updateState', params);
}
}

View File

@@ -0,0 +1,193 @@
import { LocalStorageService } from '@theia/core/lib/browser/storage-service';
import { nls } from '@theia/core/lib/common/nls';
import { inject, injectable } from '@theia/core/shared/inversify';
import { CoreService, IndexType } from '../../common/protocol';
import { NotificationCenter } from '../notification-center';
import { WindowServiceExt } from '../theia/core/window-service-ext';
import { Command, CommandRegistry, Contribution } from './contribution';
@injectable()
export class UpdateIndexes extends Contribution {
@inject(WindowServiceExt)
private readonly windowService: WindowServiceExt;
@inject(LocalStorageService)
private readonly localStorage: LocalStorageService;
@inject(CoreService)
private readonly coreService: CoreService;
@inject(NotificationCenter)
private readonly notificationCenter: NotificationCenter;
protected override init(): void {
super.init();
this.notificationCenter.onIndexUpdateDidComplete(({ summary }) =>
Promise.all(
Object.entries(summary).map(([type, updatedAt]) =>
this.setLastUpdateDateTime(type as IndexType, updatedAt)
)
)
);
}
override onReady(): void {
this.checkForUpdates();
}
override registerCommands(registry: CommandRegistry): void {
registry.registerCommand(UpdateIndexes.Commands.UPDATE_INDEXES, {
execute: () => this.updateIndexes(IndexType.All, true),
});
registry.registerCommand(UpdateIndexes.Commands.UPDATE_PLATFORM_INDEX, {
execute: () => this.updateIndexes(['platform'], true),
});
registry.registerCommand(UpdateIndexes.Commands.UPDATE_LIBRARY_INDEX, {
execute: () => this.updateIndexes(['library'], true),
});
}
private async checkForUpdates(): Promise<void> {
const checkForUpdates = this.preferences['arduino.checkForUpdates'];
if (!checkForUpdates) {
console.debug(
'[update-indexes]: `arduino.checkForUpdates` is `false`. Skipping updating the indexes.'
);
return;
}
if (await this.windowService.isFirstWindow()) {
const summary = await this.coreService.indexUpdateSummaryBeforeInit();
if (summary.message) {
this.messageService.error(summary.message);
}
const typesToCheck = IndexType.All.filter((type) => !(type in summary));
if (Object.keys(summary).length) {
console.debug(
`[update-indexes]: Detected an index update summary before the core gRPC client initialization. Updating local storage with ${JSON.stringify(
summary
)}`
);
} else {
console.debug(
'[update-indexes]: No index update summary was available before the core gRPC client initialization. Checking the status of the all the index types.'
);
}
await Promise.allSettled([
...Object.entries(summary).map(([type, updatedAt]) =>
this.setLastUpdateDateTime(type as IndexType, updatedAt)
),
this.updateIndexes(typesToCheck),
]);
}
}
private async updateIndexes(
types: IndexType[],
force = false
): Promise<void> {
const updatedAt = new Date().toISOString();
return Promise.all(
types.map((type) => this.needsIndexUpdate(type, updatedAt, force))
).then((needsIndexUpdateResults) => {
const typesToUpdate = needsIndexUpdateResults.filter(IndexType.is);
if (typesToUpdate.length) {
console.debug(
`[update-indexes]: Requesting the index update of type: ${JSON.stringify(
typesToUpdate
)} with date time: ${updatedAt}.`
);
return this.coreService.updateIndex({ types: typesToUpdate });
}
});
}
private async needsIndexUpdate(
type: IndexType,
now: string,
force = false
): Promise<IndexType | false> {
if (force) {
console.debug(
`[update-indexes]: Update for index type: '${type}' was forcefully requested.`
);
return type;
}
const lastUpdateIsoDateTime = await this.getLastUpdateDateTime(type);
if (!lastUpdateIsoDateTime) {
console.debug(
`[update-indexes]: No last update date time was persisted for index type: '${type}'. Index update is required.`
);
return type;
}
const lastUpdateDateTime = Date.parse(lastUpdateIsoDateTime);
if (Number.isNaN(lastUpdateDateTime)) {
console.debug(
`[update-indexes]: Invalid last update date time was persisted for index type: '${type}'. Last update date time was: ${lastUpdateDateTime}. Index update is required.`
);
return type;
}
const diff = new Date(now).getTime() - lastUpdateDateTime;
const needsIndexUpdate = diff >= this.threshold;
console.debug(
`[update-indexes]: Update for index type '${type}' is ${
needsIndexUpdate ? '' : 'not '
}required. Now: ${now}, Last index update date time: ${new Date(
lastUpdateDateTime
).toISOString()}, diff: ${diff} ms, threshold: ${this.threshold} ms.`
);
return needsIndexUpdate ? type : false;
}
private async getLastUpdateDateTime(
type: IndexType
): Promise<string | undefined> {
const key = this.storageKeyOf(type);
return this.localStorage.getData<string>(key);
}
private async setLastUpdateDateTime(
type: IndexType,
updatedAt: string
): Promise<void> {
const key = this.storageKeyOf(type);
return this.localStorage.setData<string>(key, updatedAt).finally(() => {
console.debug(
`[update-indexes]: Updated the last index update date time of '${type}' to ${updatedAt}.`
);
});
}
private storageKeyOf(type: IndexType): string {
return `index-last-update-time--${type}`;
}
private get threshold(): number {
return 4 * 60 * 60 * 1_000; // four hours in millis
}
}
export namespace UpdateIndexes {
export namespace Commands {
export const UPDATE_INDEXES: Command & { label: string } = {
id: 'arduino-update-indexes',
label: nls.localize(
'arduino/updateIndexes/updateIndexes',
'Update Indexes'
),
category: 'Arduino',
};
export const UPDATE_PLATFORM_INDEX: Command & { label: string } = {
id: 'arduino-update-package-index',
label: nls.localize(
'arduino/updateIndexes/updatePackageIndex',
'Update Package Index'
),
category: 'Arduino',
};
export const UPDATE_LIBRARY_INDEX: Command & { label: string } = {
id: 'arduino-update-library-index',
label: nls.localize(
'arduino/updateIndexes/updateLibraryIndex',
'Update Library Index'
),
category: 'Arduino',
};
}
}

View File

@@ -12,12 +12,14 @@ import {
PreferenceScope,
PreferenceService,
} from '@theia/core/lib/browser/preferences/preference-service';
import { ArduinoPreferences } from '../arduino-preferences';
import {
arduinoCert,
certificateList,
} from '../dialogs/certificate-uploader/utils';
import { ArduinoFirmwareUploader } from '../../common/protocol/arduino-firmware-uploader';
import {
ArduinoFirmwareUploader,
UploadCertificateParams,
} from '../../common/protocol/arduino-firmware-uploader';
import { nls } from '@theia/core/lib/common';
@injectable()
@@ -31,22 +33,29 @@ export class UploadCertificate extends Contribution {
@inject(PreferenceService)
protected readonly preferenceService: PreferenceService;
@inject(ArduinoPreferences)
protected readonly arduinoPreferences: ArduinoPreferences;
@inject(ArduinoFirmwareUploader)
protected readonly arduinoFirmwareUploader: ArduinoFirmwareUploader;
protected dialogOpened = false;
override onStart(): void {
this.preferences.onPreferenceChanged(({ preferenceName }) => {
if (preferenceName === 'arduino.board.certificates') {
this.menuManager.update();
}
});
}
override registerCommands(registry: CommandRegistry): void {
registry.registerCommand(UploadCertificate.Commands.OPEN, {
execute: async () => {
try {
this.dialogOpened = true;
this.menuManager.update();
await this.dialog.open();
} finally {
this.dialogOpened = false;
this.menuManager.update();
}
},
isEnabled: () => !this.dialogOpened,
@@ -54,7 +63,7 @@ export class UploadCertificate extends Contribution {
registry.registerCommand(UploadCertificate.Commands.REMOVE_CERT, {
execute: async (certToRemove) => {
const certs = this.arduinoPreferences.get('arduino.board.certificates');
const certs = this.preferences.get('arduino.board.certificates');
this.preferenceService.set(
'arduino.board.certificates',
@@ -68,14 +77,9 @@ export class UploadCertificate extends Contribution {
});
registry.registerCommand(UploadCertificate.Commands.UPLOAD_CERT, {
execute: async ({ fqbn, address, urls }) => {
return this.arduinoFirmwareUploader.uploadCertificates(
`-b ${fqbn} -a ${address} ${urls
.map((url: string) => `-u ${url}`)
.join(' ')}`
);
execute: async (params: UploadCertificateParams) => {
return this.arduinoFirmwareUploader.uploadCertificates(params);
},
isEnabled: () => true,
});
registry.registerCommand(UploadCertificate.Commands.OPEN_CERT_CONTEXT, {
@@ -89,7 +93,6 @@ export class UploadCertificate extends Contribution {
args: [args.cert],
});
},
isEnabled: () => true,
});
}

View File

@@ -21,9 +21,11 @@ export class UploadFirmware extends Contribution {
execute: async () => {
try {
this.dialogOpened = true;
this.menuManager.update();
await this.dialog.open();
} finally {
this.dialogOpened = false;
this.menuManager.update();
}
},
isEnabled: () => !this.dialogOpened,
@@ -45,7 +47,7 @@ export namespace UploadFirmware {
id: 'arduino-upload-firmware-open',
label: nls.localize(
'arduino/firmware/updater',
'WiFi101 / WiFiNINA Firmware Updater'
'Firmware Updater'
),
category: 'Arduino',
};

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