Compare commits

..

46 Commits

Author SHA1 Message Date
Francesco Stasi
40a73af82b Updated to 2.0.0-beta.9 2021-07-08 16:41:04 +02:00
Francesco Stasi
461ca06445 Include arduino_secrets when needed (#438)
* include arduino_secrets when needed

Co-authored-by: Alberto Iannaccone <a.iannaccone@arduino.cc>
2021-07-08 16:39:16 +02:00
Francesco Stasi
773675e3c5 Updated to 2.0.0-beta.8 2021-07-06 18:28:11 +02:00
Akos Kitta
4c536ec8fc [atl-1217] sketchbook explorer local & remote 2021-07-06 14:55:39 +02:00
Francesco Stasi
e6cbefb880 eslint to fix unused imports 2021-06-22 17:34:12 +02:00
Francesco Stasi
0592199858 Use eslint&prettier for code linting&formatting 2021-06-22 10:58:18 +02:00
Francesco Stasi
2a3873a923 force electron-builder version resolution 2021-06-16 12:33:07 +02:00
per1234
05c0505228 Use latest release of built-in examples
A new release is available for the example sketches provided via the IDE's **File > Examples > Built-in examples** menu.
2021-05-18 17:04:38 -07:00
Francesco Stasi
8c4e66f536 Update CLI and bump to beta-7
# Conflicts:
#	package.json
2021-05-17 12:08:49 +02:00
Francesco Stasi
cd0f1b3163 Updated to 2.0.0-beta.6 2021-05-12 12:20:55 +02:00
Francesco Stasi
4fa2024266 [atl-1280] Board packages hints
handle cornercase when 2 packages are associated to the same board

updated cli version and grpc

support deprecated cores in the boards manager

bump cli version

Bump ArduinoCLI version to latest release

Add package version in notification
2021-05-11 14:07:54 +02:00
Francesco Stasi
852bf9b73e https://arduino.atlassian.net/browse/ATL-1247 2021-05-11 13:50:27 +02:00
Francesco Stasi
db48ed616b https://arduino.atlassian.net/browse/ATL-1222 2021-05-05 17:44:10 +02:00
per1234
0dd1e45233 Correct sketchbook folder selection button text
The previous text used past tense, which is not appropriate for a button.
2021-04-27 07:29:48 -07:00
Akos Kitta
2a55ddd757 Updated to 2.0.0-beta.5.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-04-15 12:40:49 +02:00
Akos Kitta
3240bf7f3d [dev]: Fixed the launch config.
So that the IDE correctly loads the VS Code extensions.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-04-14 17:44:06 +02:00
Akos Kitta
0d0ad9efae Workarond for arduino/arduino-cli#1262.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-04-14 17:44:06 +02:00
Akos Kitta
9aff90b0af ATL-786: Progress indication for install.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-04-14 17:44:06 +02:00
Akos Kitta
8071298598 Updated to the 0.18.1 CLI.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-04-14 17:44:06 +02:00
Akos Kitta
c86d82d273 ATL-1206: Reuse selected board for new sketches.
Closes #95.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-04-14 17:44:06 +02:00
Akos Kitta
fa9334eb7a ATL-1207: Open editor if file was added to sketch.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-04-14 17:44:06 +02:00
Akos Kitta
c50d45c663 GH-297: Fixed the open from Sketchbook handler.
When running the handler for the `Sketchbook` menu, do not clone the
sketch.

Closes #297

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-04-14 17:44:06 +02:00
Akos Kitta
c20f832ddf Notify user if platform/lib install was successful
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-04-14 17:44:06 +02:00
Akos Kitta
cb2ef78c0a ATL-1195: Show all libraries if no board selected.
Like for the examples, we show all libraries if no board is selected,
or the platform for the selected board is not installed.
Otherwise, we show the libs for the current board.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-04-14 17:44:06 +02:00
Akos Kitta
68af4c38fe ATL-1195: Show examples if no board is selected.
Show all examples:
 - when no board is selected,
 - when the core is not installed for the selected board.

Otherwise, show examples for the currently selected board only.
Only get libraries from the cores when the FQBN is defined.
Otherwise, we retrieve user installed libraries only.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-04-14 17:44:06 +02:00
Akos Kitta
a8df2444a9 ATL-1145: Suppress error if Git is not on $PATH.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-03-31 19:14:56 +02:00
Francesco Stasi
d45dd6beef ATL-1151: settings panel to reflect actual state 2021-03-31 16:35:50 +02:00
Francesco Stasi
1ab5634789 ATL-970: notifications should last longer 2021-03-31 16:29:50 +02:00
Akos Kitta
80bddc238d ATL-988: Aligned the hover size to the expression.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-03-31 15:20:56 +02:00
Akos Kitta
8a692d0ce5 ATL-1068: Escape ampersand in the menu label.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-03-31 15:20:56 +02:00
Akos Kitta
98671225ac Can edit user-storage files. E.g.: keymaps.json.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-03-31 13:47:25 +02:00
Akos Kitta
f106c97f1e Fixed bug when no 3rd party URLs are defined.
Instead of adding an empty string URL, we add nothing.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-03-31 13:47:25 +02:00
Akos Kitta
369a8f4307 Update index after modifying the 3rd party URLs.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-03-31 13:47:25 +02:00
Akos Kitta
4e7f8291e8 Removed the min window height and width.
Made the boards config dialog slightly smaller.

Closes #216.

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-03-31 13:47:25 +02:00
Akos Kitta
26a1db3cf8 ATL-1137: Show error when could not connect to CLI
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-03-31 13:46:04 +02:00
Francesco Stasi
a3f7b795a0 ATL-1128: make the new tab button easier to click 2021-03-30 09:54:57 +02:00
Francesco Stasi
b422fc5298 chore: update CLI version, gRPC and bit of documentation 2021-03-29 14:05:56 +02:00
Akos Kitta
ab320eb0b0 GH-259: Use Ubuntu 18.04 for the build job.
Closes #259

Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-03-29 12:39:46 +02:00
Francesco Stasi
b17b7a6de7 ATL-1136: Add .adoc and .md file support 2021-03-29 10:03:51 +02:00
Francesco Stasi
562b77aec3 Add keymaps customization support 2021-03-26 15:33:38 +01:00
Akos Kitta
cdd5cfdfc1 ATL-1150: Bumped the cortex-debug to 0.3.10.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-03-25 18:46:34 +01:00
Akos Kitta
f712ec986f ATL-1106: Made all non-workspace editors read-only.
Signed-off-by: Akos Kitta <kittaakos@typefox.io>
2021-03-25 16:45:44 +01:00
per1234
c75b954041 Update development documentation to reflect change in workflow artifacts
The "Arduino IDE" workflow was updated to produce individual artifacts for each operating system, but the development
documentation was not updated accordingly at that time.
2021-03-25 02:34:39 -07:00
per1234
3fb087f1ad Delete job transfer workflow artifact
The "Arduino IDE" GitHub Actions workflow uses a workflow artifact to transfer the build artifacts between jobs. Now that
separate tester build artifacts are produced, the monolithic job transfer artifact is superfluous once the workflow run
is finished. Deleting it avoids potential confusion for beta testers and unnecessary storage space usage.
2021-03-24 02:04:11 -07:00
per1234
27292774d7 Create separate tester artifacts for each build
Previously, a single workflow artifact was created by the "Arduino IDE" GitHub Actions workflow. This artifact contained
the builds for each operating system, including all three versions of the Windows build. This resulted in beta testers
needing to do a >1 GB download for every build, even though they likely needed only ~200 MB of what they downloaded.

Producing separate workflows makes it easier for beta testers to participate in the development and is less wasteful of
resources.
2021-03-24 02:04:11 -07:00
per1234
da424f34cc Don't use magic string for job transfer artifact name
Previously, the build CI/CD workflow had many occurrences of the string "build-artifacts" used for the workflow artifact
name. This made the workflow more difficult to understand and maintain. Now a single workflow scoped environment variable
is used to define the artifact name.
2021-03-24 02:04:11 -07:00
297 changed files with 27100 additions and 14984 deletions

65
.eslintrc.js Normal file
View File

@@ -0,0 +1,65 @@
module.exports = {
parser: '@typescript-eslint/parser', // Specifies the ESLint parser
parserOptions: {
ecmaVersion: 2020, // Allows for the parsing of modern ECMAScript features
sourceType: 'module', // Allows for the use of imports
ecmaFeatures: {
jsx: true, // Allows for the parsing of JSX
},
},
ignorePatterns: [
'node_modules/*',
'**/node_modules/*',
'.node_modules/*',
'.github/*',
'.browser_modules/*',
'docs/*',
'scripts/*',
'electron/*',
'electron-app/*',
'browser-app/*',
'plugins/*',
'arduino-ide-extension/src/node/cli-protocol',
],
settings: {
react: {
version: 'detect', // Tells eslint-plugin-react to automatically detect the version of React to use
},
},
extends: [
'plugin:@typescript-eslint/recommended', // Uses the recommended rules from the @typescript-eslint/eslint-plugin
'plugin:react/recommended', // Uses the recommended rules from @eslint-plugin-react
'plugin:react-hooks/recommended', // Uses recommended rules from react hooks
'plugin:prettier/recommended',
'prettier', // Uses eslint-config-prettier to disable ESLint rules from @typescript-eslint/eslint-plugin that would conflict with prettier
],
plugins: ['prettier', 'unused-imports'],
rules: {
'@typescript-eslint/no-unused-expressions': 'off',
'@typescript-eslint/no-namespace': 'off',
'@typescript-eslint/no-var-requires': 'off',
'@typescript-eslint/no-empty-function': 'warn',
'@typescript-eslint/no-empty-interface': 'warn',
'no-unused-vars': 'off',
'unused-imports/no-unused-imports': 'error',
'unused-imports/no-unused-vars': [
'warn',
{
vars: 'all',
varsIgnorePattern: '^_',
args: 'after-used',
argsIgnorePattern: '^_',
},
],
'react/display-name': 'warn',
eqeqeq: ['error', 'smart'],
'guard-for-in': 'off',
'id-blacklist': 'off',
'id-match': 'off',
'no-underscore-dangle': 'off',
'no-unused-expressions': 'off',
'no-var': 'error',
radix: 'error',
'prettier/prettier': 'warn',
},
};

View File

@@ -13,6 +13,9 @@ on:
schedule:
- cron: '0 3 * * *' # run every day at 3AM (https://docs.github.com/en/actions/reference/events-that-trigger-workflows#scheduled-events-schedule)
env:
JOB_TRANSFER_ARTIFACT: build-artifacts
jobs:
build:
@@ -21,7 +24,7 @@ jobs:
matrix:
config:
- os: windows-latest
- os: ubuntu-latest
- os: ubuntu-18.04 # https://github.com/arduino/arduino-ide/issues/259
- os: macos-latest
runs-on: ${{ matrix.config.os }}
timeout-minutes: 90
@@ -79,9 +82,42 @@ jobs:
- name: Upload [GitHub Actions]
uses: actions/upload-artifact@v2
with:
name: build-artifacts
name: ${{ env.JOB_TRANSFER_ARTIFACT }}
path: electron/build/dist/build-artifacts/
artifacts:
name: ${{ matrix.artifact.name }} artifact
needs: build
if: always() && needs.build.result != 'skipped'
runs-on: ubuntu-latest
strategy:
matrix:
artifact:
- path: "*Linux_64bit.zip"
name: Linux_X86-64
- path: "*macOS_64bit.dmg"
name: macOS
- path: "*Windows_64bit.exe"
name: Windows_X86-64_interactive_installer
- path: "*Windows_64bit.msi"
name: Windows_X86-64_MSI
- path: "*Windows_64bit.zip"
name: Windows_X86-64_zip
steps:
- name: Download job transfer artifact
uses: actions/download-artifact@v2
with:
name: ${{ env.JOB_TRANSFER_ARTIFACT }}
path: ${{ env.JOB_TRANSFER_ARTIFACT }}
- name: Upload tester build artifact
uses: actions/upload-artifact@v2
with:
name: ${{ matrix.artifact.name }}
path: ${{ env.JOB_TRANSFER_ARTIFACT }}/${{ matrix.artifact.path }}
changelog:
needs: build
runs-on: ubuntu-latest
@@ -121,7 +157,7 @@ jobs:
if: github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main')
uses: actions/upload-artifact@v2
with:
name: build-artifacts
name: ${{ env.JOB_TRANSFER_ARTIFACT }}
path: CHANGELOG.txt
publish:
@@ -132,14 +168,14 @@ jobs:
- name: Download [GitHub Actions]
uses: actions/download-artifact@v2
with:
name: build-artifacts
path: build-artifacts
name: ${{ env.JOB_TRANSFER_ARTIFACT }}
path: ${{ env.JOB_TRANSFER_ARTIFACT }}
- name: Publish Nightly [S3]
uses: docker://plugins/s3
env:
PLUGIN_SOURCE: "build-artifacts/*"
PLUGIN_STRIP_PREFIX: "build-artifacts/"
PLUGIN_SOURCE: "${{ env.JOB_TRANSFER_ARTIFACT }}/*"
PLUGIN_STRIP_PREFIX: "${{ env.JOB_TRANSFER_ARTIFACT }}/"
PLUGIN_TARGET: "/arduino-ide/nightly"
PLUGIN_BUCKET: ${{ secrets.DOWNLOADS_BUCKET }}
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
@@ -153,8 +189,8 @@ jobs:
- name: Download [GitHub Actions]
uses: actions/download-artifact@v2
with:
name: build-artifacts
path: build-artifacts
name: ${{ env.JOB_TRANSFER_ARTIFACT }}
path: ${{ env.JOB_TRANSFER_ARTIFACT }}
- name: Get Tag
id: tag_name
@@ -166,7 +202,7 @@ jobs:
with:
repo_token: ${{ secrets.GITHUB_TOKEN }}
release_name: ${{ steps.tag_name.outputs.TAG_NAME }}
file: build-artifacts/*
file: ${{ env.JOB_TRANSFER_ARTIFACT }}/*
tag: ${{ github.ref }}
file_glob: true
body: ${{ needs.changelog.outputs.BODY }}
@@ -174,9 +210,25 @@ jobs:
- name: Publish Release [S3]
uses: docker://plugins/s3
env:
PLUGIN_SOURCE: "build-artifacts/*"
PLUGIN_STRIP_PREFIX: "build-artifacts/"
PLUGIN_SOURCE: "${{ env.JOB_TRANSFER_ARTIFACT }}/*"
PLUGIN_STRIP_PREFIX: "${{ env.JOB_TRANSFER_ARTIFACT }}/"
PLUGIN_TARGET: "/arduino-ide"
PLUGIN_BUCKET: ${{ secrets.DOWNLOADS_BUCKET }}
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
clean:
# This job must run after all jobs that use the transfer artifact.
needs:
- build
- publish
- release
- artifacts
if: always() && needs.build.result != 'skipped'
runs-on: ubuntu-latest
steps:
- name: Remove unneeded job transfer artifact
uses: geekyeggo/delete-artifact@v1
with:
name: ${{ env.JOB_TRANSFER_ARTIFACT }}

13
.prettierrc Normal file
View File

@@ -0,0 +1,13 @@
{
"singleQuote": true,
"tabWidth": 4,
"useTabs": false,
"overrides": [
{
"files": "*.{json,yml}",
"options": {
"tabWidth": 2
}
}
]
}

35
.vscode/launch.json vendored
View File

@@ -1,22 +1,6 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "attach",
"name": "Attach by Process ID",
"processId": "${command:PickProcess}"
},
{
"type": "node",
"request": "launch",
"name": "Electron Packager",
"program": "${workspaceRoot}/electron/packager/index.js",
"cwd": "${workspaceFolder}/electron/packager"
},
{
"type": "node",
"request": "launch",
@@ -29,15 +13,17 @@
"NODE_PRESERVE_SYMLINKS": "1"
}
},
"program": "${workspaceRoot}/electron-app/src-gen/frontend/electron-main.js",
"cwd": "${workspaceFolder}/electron-app",
"protocol": "inspector",
"args": [
".",
"--log-level=debug",
"--hostname=localhost",
"--no-cluster",
"--app-project-path=${workspaceRoot}/electron-app",
"--remote-debugging-port=9222",
"--no-app-auto-install",
"--plugins=local-dir:plugins"
"--plugins=local-dir:../plugins"
],
"env": {
"NODE_ENV": "development"
@@ -104,6 +90,19 @@
"smartStep": true,
"internalConsoleOptions": "openOnSessionStart",
"outputCapture": "std"
},
{
"type": "node",
"request": "attach",
"name": "Attach by Process ID",
"processId": "${command:PickProcess}"
},
{
"type": "node",
"request": "launch",
"name": "Electron Packager",
"program": "${workspaceRoot}/electron/packager/index.js",
"cwd": "${workspaceFolder}/electron/packager"
}
]
}

18
.vscode/settings.json vendored
View File

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

4
.vscode/tasks.json vendored
View File

@@ -1,6 +1,4 @@
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
@@ -35,7 +33,7 @@
"panel": "new",
"clear": false
}
}
},
{
"label": "Arduino IDE - Watch Browser App",
"type": "shell",

View File

@@ -61,7 +61,7 @@ yarn start
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 can be downloaded from the GitHub Actions page. Note: [due to a limitation](https://github.com/actions/upload-artifact/issues/80#issuecomment-630030144) with the GH Actions UI, you cannot download a particular build, but you have to get all together inside the `build-artifacts.zip`.
- _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:

View File

@@ -1,19 +0,0 @@
FROM gitpod/workspace-full-vnc
USER root
RUN apt-get update -q --fix-missing && \
apt-get install -y -q software-properties-common && \
apt-get install -y -q --no-install-recommends \
build-essential \
libssl-dev \
golang-go \
libxkbfile-dev \
libnss3-dev
RUN set -ex && \
tmpdir=$(mktemp -d) && \
curl -L -o $tmpdir/protoc.zip https://github.com/protocolbuffers/protobuf/releases/download/v3.6.1/protoc-3.6.1-linux-x86_64.zip && \
mkdir -p /usr/lib/protoc && cd /usr/lib/protoc && unzip $tmpdir/protoc.zip && \
chmod -R 755 /usr/lib/protoc/include/google && \
ln -s /usr/lib/protoc/bin/* /usr/bin && \
rm $tmpdir/protoc.zip

View File

@@ -54,3 +54,7 @@ The Config Service knows about your system, like for example the default sketch
### `"arduino"` configuration in the `package.json`:
- `"cli"`:
- `"version"` type `string` | `{ owner: string, repo: string, commitish?: string }`: if the type is a `string` and is a valid semver, it will get the corresponding [released](https://github.com/arduino/arduino-cli/releases) CLI. If the type is `string` and is a [date in `YYYYMMDD`](https://arduino.github.io/arduino-cli/latest/installation/#nightly-builds) format, it will get a nightly CLI. If the type is an object, a CLI, build from the sources in the `owner/repo` will be used. If `commitish` is not defined, the HEAD of the default branch will be used. In any other cases an error is thrown.
#### Rebuild gRPC protocol interfaces
- 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`

View File

@@ -1,6 +1,6 @@
{
"name": "arduino-ide-extension",
"version": "2.0.0-beta.4",
"version": "2.0.0-beta.9",
"description": "An extension for Theia building the Arduino IDE",
"license": "AGPL-3.0-or-later",
"scripts": {
@@ -10,7 +10,7 @@
"download-ls": "node ./scripts/download-ls.js",
"download-examples": "node ./scripts/download-examples.js",
"generate-protocol": "node ./scripts/generate-protocol.js",
"lint": "tslint -c ./tslint.json --project ./tsconfig.json",
"lint": "eslint",
"build": "tsc && ncp ./src/node/cli-protocol/ ./lib/node/cli-protocol/ && yarn lint",
"watch": "tsc -w",
"test": "mocha \"./lib/test/**/*.test.js\"",
@@ -23,6 +23,7 @@
"@theia/editor": "next",
"@theia/filesystem": "next",
"@theia/git": "next",
"@theia/keymaps": "next",
"@theia/markers": "next",
"@theia/monaco": "next",
"@theia/navigator": "next",
@@ -32,13 +33,18 @@
"@theia/search-in-workspace": "next",
"@theia/terminal": "next",
"@theia/workspace": "next",
"@types/atob": "^2.1.2",
"@types/auth0-js": "^9.14.0",
"@types/btoa": "^1.2.3",
"@types/dateformat": "^3.0.1",
"@types/deepmerge": "^2.2.0",
"@types/glob": "^5.0.35",
"@types/google-protobuf": "^3.7.2",
"@types/js-yaml": "^3.12.2",
"@types/keytar": "^4.4.0",
"@types/lodash.debounce": "^4.0.6",
"@types/ncp": "^2.0.4",
"@types/node-fetch": "^2.5.7",
"@types/ps-tree": "^1.1.0",
"@types/react-select": "^3.0.0",
"@types/react-tabs": "^2.3.2",
@@ -47,15 +53,24 @@
"@types/which": "^1.3.1",
"ajv": "^6.5.3",
"async-mutex": "^0.3.0",
"atob": "^2.1.2",
"auth0-js": "^9.14.0",
"btoa": "^1.2.1",
"css-element-queries": "^1.2.0",
"dateformat": "^3.0.3",
"deepmerge": "^4.2.2",
"deepmerge": "2.0.1",
"fuzzy": "^0.1.3",
"glob": "^7.1.6",
"google-protobuf": "^3.11.4",
"lodash.debounce": "^4.0.8",
"hash.js": "^1.1.7",
"is-valid-path": "^0.1.1",
"js-yaml": "^3.13.1",
"jwt-decode": "^3.1.2",
"keytar": "7.2.0",
"lodash.debounce": "^4.0.8",
"ncp": "^2.0.0",
"node-fetch": "^2.6.1",
"open": "^8.0.6",
"p-queue": "^5.0.0",
"ps-tree": "^1.2.0",
"react-disable": "^0.1.0",
@@ -121,7 +136,7 @@
],
"arduino": {
"cli": {
"version": "0.17.0"
"version": "0.18.3"
}
}
}

View File

@@ -1,7 +1,7 @@
// @ts-check
// The version to use.
const version = '1.9.0';
const version = '1.9.1';
(async () => {

View File

@@ -4,20 +4,18 @@ import { Command } from '@theia/core/lib/common/command';
* @deprecated all these commands should go under contributions and have their command, menu, keybinding, and toolbar contributions.
*/
export namespace ArduinoCommands {
export const TOGGLE_COMPILE_FOR_DEBUG: Command = {
id: 'arduino-toggle-compile-for-debug'
id: 'arduino-toggle-compile-for-debug',
};
/**
* Unlike `OPEN_SKETCH`, it opens all files from a sketch folder. (ino, cpp, etc...)
*/
export const OPEN_SKETCH_FILES: Command = {
id: 'arduino-open-sketch-files'
id: 'arduino-open-sketch-files',
};
export const OPEN_BOARDS_DIALOG: Command = {
id: 'arduino-open-boards-dialog'
id: 'arduino-open-boards-dialog',
};
}

View File

@@ -1,5 +1,5 @@
import { Mutex } from 'async-mutex';
import { MAIN_MENU_BAR, MenuContribution, MenuModelRegistry, SelectionService, ILogger } from '@theia/core';
import { MAIN_MENU_BAR, MenuContribution, MenuModelRegistry, SelectionService, ILogger, DisposableCollection } from '@theia/core';
import {
ContextMenuRenderer,
FrontendApplication, FrontendApplicationContribution,
@@ -12,7 +12,7 @@ import { TabBarToolbarContribution, TabBarToolbarRegistry } from '@theia/core/li
import { CommandContribution, CommandRegistry } from '@theia/core/lib/common/command';
import { MessageService } from '@theia/core/lib/common/message-service';
import URI from '@theia/core/lib/common/uri';
import { EditorMainMenu, EditorManager } from '@theia/editor/lib/browser';
import { EditorMainMenu, EditorManager, EditorOpenerOptions } from '@theia/editor/lib/browser';
import { FileDialogService } from '@theia/filesystem/lib/browser/file-dialog';
import { ProblemContribution } from '@theia/markers/lib/browser/problem/problem-contribution';
import { MonacoMenus } from '@theia/monaco/lib/browser/monaco-menu';
@@ -26,7 +26,7 @@ import { inject, injectable, postConstruct } from 'inversify';
import * as React from 'react';
import { remote } from 'electron';
import { MainMenuManager } from '../common/main-menu-manager';
import { BoardsService, CoreService, Port, SketchesService, ExecutableService } from '../common/protocol';
import { BoardsService, CoreService, Port, SketchesService, ExecutableService, Sketch } from '../common/protocol';
import { ArduinoDaemon } from '../common/protocol/arduino-daemon';
import { ConfigService } from '../common/protocol/config-service';
import { FileSystemExt } from '../common/protocol/filesystem-ext';
@@ -44,10 +44,13 @@ import { WorkspaceService } from './theia/workspace/workspace-service';
import { ArduinoToolbar } from './toolbar/arduino-toolbar';
import { HostedPluginSupport } from '@theia/plugin-ext/lib/hosted/browser/hosted-plugin';
import { FileService } from '@theia/filesystem/lib/browser/file-service';
import { OutputService } from '../common/protocol/output-service';
import { ResponseService } from '../common/protocol/response-service';
import { ArduinoPreferences } from './arduino-preferences';
import { SketchesServiceClientImpl } from '../common/protocol/sketches-service-client-impl';
import { SaveAsSketch } from './contributions/save-as-sketch';
import { FileChangeType } from '@theia/filesystem/lib/browser';
import { FrontendApplicationStateService } from '@theia/core/lib/browser/frontend-application-state';
import { SketchbookWidgetContribution } from './widgets/sketchbook/sketchbook-widget-contribution';
@injectable()
export class ArduinoFrontendContribution implements FrontendApplicationContribution,
@@ -81,7 +84,7 @@ export class ArduinoFrontendContribution implements FrontendApplicationContribut
protected readonly fileDialogService: FileDialogService;
@inject(FileService)
protected readonly fileSystem: FileService;
protected readonly fileService: FileService;
@inject(SketchesService)
protected readonly sketchService: SketchesService;
@@ -122,6 +125,9 @@ export class ArduinoFrontendContribution implements FrontendApplicationContribut
@inject(SearchInWorkspaceFrontendContribution)
protected readonly siwContribution: SearchInWorkspaceFrontendContribution;
@inject(SketchbookWidgetContribution)
protected readonly sketchbookWidgetContribution: SketchbookWidgetContribution;
@inject(EditorMode)
protected readonly editorMode: EditorMode;
@@ -149,8 +155,8 @@ export class ArduinoFrontendContribution implements FrontendApplicationContribut
@inject(ExecutableService)
protected executableService: ExecutableService;
@inject(OutputService)
protected readonly outputService: OutputService;
@inject(ResponseService)
protected readonly responseService: ResponseService;
@inject(ArduinoPreferences)
protected readonly arduinoPreferences: ArduinoPreferences;
@@ -158,7 +164,11 @@ export class ArduinoFrontendContribution implements FrontendApplicationContribut
@inject(SketchesServiceClientImpl)
protected readonly sketchServiceClient: SketchesServiceClientImpl;
@inject(FrontendApplicationStateService)
protected readonly appStateService: FrontendApplicationStateService;
protected invalidConfigPopup: Promise<void | 'No' | 'Yes' | undefined> | undefined;
protected toDisposeOnStop = new DisposableCollection();
@postConstruct()
protected async init(): Promise<void> {
@@ -182,6 +192,23 @@ export class ArduinoFrontendContribution implements FrontendApplicationContribut
}
this.boardsServiceClientImpl.onBoardsConfigChanged(updateStatusBar);
updateStatusBar(this.boardsServiceClientImpl.boardsConfig);
this.appStateService.reachedState('ready').then(async () => {
const sketch = await this.sketchServiceClient.currentSketch();
if (sketch && (!await this.sketchService.isTemp(sketch))) {
this.toDisposeOnStop.push(this.fileService.watch(new URI(sketch.uri)));
this.toDisposeOnStop.push(this.fileService.onDidFilesChange(async event => {
for (const { type, resource } of event.changes) {
if (type === FileChangeType.ADDED && resource.parent.toString() === sketch.uri) {
const reloadedSketch = await this.sketchService.loadSketch(sketch.uri)
if (Sketch.isInSketch(resource, reloadedSketch)) {
this.ensureOpened(resource.toString(), true, { mode: 'open' });
}
}
}
}));
}
});
}
onStart(app: FrontendApplication): void {
@@ -192,7 +219,8 @@ export class ArduinoFrontendContribution implements FrontendApplicationContribut
this.outlineContribution,
this.problemContribution,
this.scmContribution,
this.siwContribution] as Array<FrontendApplicationContribution>) {
this.siwContribution,
this.sketchbookWidgetContribution] as Array<FrontendApplicationContribution>) {
if (viewContribution.initializeLayout) {
viewContribution.initializeLayout(app);
}
@@ -225,6 +253,10 @@ export class ArduinoFrontendContribution implements FrontendApplicationContribut
app.shell.leftPanelHandler.removeMenu('settings-menu');
}
onStop(): void {
this.toDisposeOnStop.dispose();
}
protected languageServerFqbn?: string;
protected languageServerStartMutex = new Mutex();
protected async startLanguageServer(fqbn: string, name: string | undefined): Promise<void> {
@@ -257,14 +289,15 @@ export class ArduinoFrontendContribution implements FrontendApplicationContribut
if (log) {
const currentSketch = await this.sketchServiceClient.currentSketch();
if (currentSketch) {
currentSketchPath = await this.fileSystem.fsPath(new URI(currentSketch.uri));
currentSketchPath = await this.fileService.fsPath(new URI(currentSketch.uri));
}
}
const { clangdUri, cliUri, lsUri } = await this.executableService.list();
const [clangdPath, cliPath, lsPath] = await Promise.all([
this.fileSystem.fsPath(new URI(clangdUri)),
this.fileSystem.fsPath(new URI(cliUri)),
this.fileSystem.fsPath(new URI(lsUri)),
const [clangdPath, cliPath, lsPath, cliConfigPath] = await Promise.all([
this.fileService.fsPath(new URI(clangdUri)),
this.fileService.fsPath(new URI(cliUri)),
this.fileService.fsPath(new URI(lsUri)),
this.fileService.fsPath(new URI(await this.configService.getCliConfigFileUri()))
]);
this.languageServerFqbn = await Promise.race([
new Promise<undefined>((_, reject) => setTimeout(() => reject(new Error(`Timeout after ${20_000} ms.`)), 20_000)),
@@ -273,6 +306,7 @@ export class ArduinoFrontendContribution implements FrontendApplicationContribut
cliPath,
clangdPath,
log: currentSketchPath ? currentSketchPath : log,
cliConfigPath,
board: {
fqbn,
name: name ? `"${name}"` : undefined
@@ -367,10 +401,10 @@ export class ArduinoFrontendContribution implements FrontendApplicationContribut
}
}
protected async ensureOpened(uri: string, forceOpen: boolean = false): Promise<any> {
protected async ensureOpened(uri: string, forceOpen = false, options?: EditorOpenerOptions | undefined): Promise<any> {
const widget = this.editorManager.all.find(widget => widget.editor.uri.toString() === uri);
if (!widget || forceOpen) {
return this.editorManager.open(new URI(uri));
return this.editorManager.open(new URI(uri), options);
}
}
@@ -420,13 +454,13 @@ export class ArduinoFrontendContribution implements FrontendApplicationContribut
description: 'Background color of the toolbar items when hovering over them. Such as Upload, Verify, etc.'
},
{
id: 'arduino.toolbar.toggleBackground',
defaults: {
dark: 'editor.selectionBackground',
light: 'editor.selectionBackground',
hc: 'textPreformat.foreground'
},
description: 'Toggle color of the toolbar items when they are currently toggled (the command is in progress)'
id: 'arduino.toolbar.toggleBackground',
defaults: {
dark: 'editor.selectionBackground',
light: 'editor.selectionBackground',
hc: 'textPreformat.foreground'
},
description: 'Toggle color of the toolbar items when they are currently toggled (the command is in progress)'
},
{
id: 'arduino.output.foreground',

View File

@@ -3,14 +3,29 @@ import { ContainerModule } from 'inversify';
import { WidgetFactory } from '@theia/core/lib/browser/widget-manager';
import { CommandContribution } from '@theia/core/lib/common/command';
import { bindViewContribution } from '@theia/core/lib/browser/shell/view-contribution';
import { TabBarToolbarContribution, TabBarToolbarFactory } from '@theia/core/lib/browser/shell/tab-bar-toolbar';
import {
TabBarToolbarContribution,
TabBarToolbarFactory,
} from '@theia/core/lib/browser/shell/tab-bar-toolbar';
import { WebSocketConnectionProvider } from '@theia/core/lib/browser/messaging/ws-connection-provider';
import { FrontendApplicationContribution, FrontendApplication as TheiaFrontendApplication } from '@theia/core/lib/browser/frontend-application'
import {
FrontendApplicationContribution,
FrontendApplication as TheiaFrontendApplication,
} from '@theia/core/lib/browser/frontend-application';
import { LibraryListWidget } from './library/library-list-widget';
import { ArduinoFrontendContribution } from './arduino-frontend-contribution';
import { LibraryService, LibraryServicePath } from '../common/protocol/library-service';
import { BoardsService, BoardsServicePath } from '../common/protocol/boards-service';
import { SketchesService, SketchesServicePath } from '../common/protocol/sketches-service';
import {
LibraryService,
LibraryServicePath,
} from '../common/protocol/library-service';
import {
BoardsService,
BoardsServicePath,
} from '../common/protocol/boards-service';
import {
SketchesService,
SketchesServicePath,
} from '../common/protocol/sketches-service';
import { SketchesServiceClientImpl } from '../common/protocol/sketches-service-client-impl';
import { CoreService, CoreServicePath } from '../common/protocol/core-service';
import { BoardsListWidget } from './boards/boards-list-widget';
@@ -24,6 +39,8 @@ import { ProblemContribution as TheiaProblemContribution } from '@theia/markers/
import { ProblemContribution } from './theia/markers/problem-contribution';
import { FileNavigatorContribution } from './theia/navigator/navigator-contribution';
import { FileNavigatorContribution as TheiaFileNavigatorContribution } from '@theia/navigator/lib/browser/navigator-contribution';
import { KeymapsFrontendContribution } from './theia/keymaps/keymaps-frontend-contribution';
import { KeymapsFrontendContribution as TheiaKeymapsFrontendContribution } from '@theia/keymaps/lib/browser/keymaps-frontend-contribution';
import { ArduinoToolbarContribution } from './toolbar/arduino-toolbar-contribution';
import { EditorContribution as TheiaEditorContribution } from '@theia/editor/lib/browser/editor-contribution';
import { EditorContribution } from './theia/editor/editor-contribution';
@@ -37,12 +54,15 @@ import {
TabBarRendererFactory,
ContextMenuRenderer,
createTreeContainer,
TreeWidget
TreeWidget,
} from '@theia/core/lib/browser';
import { MenuContribution } from '@theia/core/lib/common/menu';
import { ApplicationShell } from './theia/core/application-shell';
import { FrontendApplication } from './theia/core/frontend-application';
import { BoardsConfigDialog, BoardsConfigDialogProps } from './boards/boards-config-dialog';
import {
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';
@@ -50,8 +70,15 @@ import { SearchInWorkspaceFrontendContribution as TheiaSearchInWorkspaceFrontend
import { SearchInWorkspaceFrontendContribution } from './theia/search-in-workspace/search-in-workspace-frontend-contribution';
import { LibraryListWidgetFrontendContribution } from './library/library-widget-frontend-contribution';
import { MonitorServiceClientImpl } from './monitor/monitor-service-client-impl';
import { MonitorServicePath, MonitorService, MonitorServiceClient } from '../common/protocol/monitor-service';
import { ConfigService, ConfigServicePath } from '../common/protocol/config-service';
import {
MonitorServicePath,
MonitorService,
MonitorServiceClient,
} from '../common/protocol/monitor-service';
import {
ConfigService,
ConfigServicePath,
} from '../common/protocol/config-service';
import { MonitorWidget } from './monitor/monitor-widget';
import { MonitorViewContribution } from './monitor/monitor-view-contribution';
import { MonitorConnection } from './monitor/monitor-connection';
@@ -66,24 +93,35 @@ import { EditorMode } from './editor-mode';
import { ListItemRenderer } from './widgets/component-list/list-item-renderer';
import { ColorContribution } from '@theia/core/lib/browser/color-application-contribution';
import { MonacoThemingService } from '@theia/monaco/lib/browser/monaco-theming-service';
import { ArduinoDaemonPath, ArduinoDaemon } from '../common/protocol/arduino-daemon';
import { EditorManager as TheiaEditorManager, EditorCommandContribution as TheiaEditorCommandContribution } from '@theia/editor/lib/browser';
import { EditorManager } from './theia/editor/editor-manager';
import { FrontendConnectionStatusService, ApplicationConnectionStatusContribution } from './theia/core/connection-status-service';
import {
ArduinoDaemonPath,
ArduinoDaemon,
} from '../common/protocol/arduino-daemon';
import { EditorCommandContribution as TheiaEditorCommandContribution } from '@theia/editor/lib/browser';
import {
FrontendConnectionStatusService,
ApplicationConnectionStatusContribution,
} from './theia/core/connection-status-service';
import {
FrontendConnectionStatusService as TheiaFrontendConnectionStatusService,
ApplicationConnectionStatusContribution as TheiaApplicationConnectionStatusContribution
ApplicationConnectionStatusContribution as TheiaApplicationConnectionStatusContribution,
} from '@theia/core/lib/browser/connection-status-service';
import { BoardsDataMenuUpdater } from './boards/boards-data-menu-updater';
import { BoardsDataStore } from './boards/boards-data-store';
import { ILogger } from '@theia/core';
import { FileSystemExt, FileSystemExtPath } from '../common/protocol/filesystem-ext';
import {
FileSystemExt,
FileSystemExtPath,
} from '../common/protocol/filesystem-ext';
import {
WorkspaceFrontendContribution as TheiaWorkspaceFrontendContribution,
FileMenuContribution as TheiaFileMenuContribution,
WorkspaceCommandContribution as TheiaWorkspaceCommandContribution
WorkspaceCommandContribution as TheiaWorkspaceCommandContribution,
} from '@theia/workspace/lib/browser';
import { WorkspaceFrontendContribution, ArduinoFileMenuContribution } from './theia/workspace/workspace-frontend-contribution';
import {
WorkspaceFrontendContribution,
ArduinoFileMenuContribution,
} from './theia/workspace/workspace-frontend-contribution';
import { Contribution } from './contributions/contribution';
import { NewSketch } from './contributions/new-sketch';
import { OpenSketch } from './contributions/open-sketch';
@@ -110,19 +148,31 @@ import { EditorWidgetFactory } from './theia/editor/editor-widget-factory';
import { OutputWidget as TheiaOutputWidget } from '@theia/output/lib/browser/output-widget';
import { OutputWidget } from './theia/output/output-widget';
import { BurnBootloader } from './contributions/burn-bootloader';
import { ExamplesServicePath, ExamplesService } from '../common/protocol/examples-service';
import {
ExamplesServicePath,
ExamplesService,
} from '../common/protocol/examples-service';
import { BuiltInExamples, LibraryExamples } from './contributions/examples';
import { IncludeLibrary } from './contributions/include-library';
import { OutputChannelManager as TheiaOutputChannelManager } from '@theia/output/lib/common/output-channel';
import { OutputChannelManager } from './theia/output/output-channel';
import { OutputChannelRegistryMainImpl as TheiaOutputChannelRegistryMainImpl, OutputChannelRegistryMainImpl } from './theia/plugin-ext/output-channel-registry-main';
import {
OutputChannelRegistryMainImpl as TheiaOutputChannelRegistryMainImpl,
OutputChannelRegistryMainImpl,
} from './theia/plugin-ext/output-channel-registry-main';
import { ExecutableService, ExecutableServicePath } from '../common/protocol';
import { MonacoTextModelService as TheiaMonacoTextModelService } from '@theia/monaco/lib/browser/monaco-text-model-service';
import { MonacoTextModelService } from './theia/monaco/monaco-text-model-service';
import { OutputServiceImpl } from './output-service-impl';
import { OutputServicePath, OutputService } from '../common/protocol/output-service';
import { ResponseServiceImpl } from './response-service-impl';
import {
ResponseServicePath,
ResponseService,
} from '../common/protocol/response-service';
import { NotificationCenter } from './notification-center';
import { NotificationServicePath, NotificationServiceServer } from '../common/protocol';
import {
NotificationServicePath,
NotificationServiceServer,
} from '../common/protocol';
import { About } from './contributions/about';
import { IconThemeService } from '@theia/core/lib/browser/icon-theme-service';
import { TabBarRenderer } from './theia/core/tab-bars';
@@ -138,8 +188,13 @@ import { DebugFrontendApplicationContribution as TheiaDebugFrontendApplicationCo
import { BoardSelection } from './contributions/board-selection';
import { OpenRecentSketch } from './contributions/open-recent-sketch';
import { Help } from './contributions/help';
import { bindArduinoPreferences } from './arduino-preferences'
import { SettingsService, SettingsDialog, SettingsWidget, SettingsDialogProps } from './settings';
import { bindArduinoPreferences } from './arduino-preferences';
import {
SettingsService,
SettingsDialog,
SettingsWidget,
SettingsDialogProps,
} from './settings';
import { AddFile } from './contributions/add-file';
import { ArchiveSketch } from './contributions/archive-sketch';
import { OutputToolbarContribution as TheiaOutputToolbarContribution } from '@theia/output/lib/browser/output-toolbar-contribution';
@@ -153,6 +208,34 @@ import { SearchInWorkspaceWidget as TheiaSearchInWorkspaceWidget } from '@theia/
import { SearchInWorkspaceWidget } from './theia/search-in-workspace/search-in-workspace-widget';
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 { DebugEditorModel } from './theia/debug/debug-editor-model';
import { DebugEditorModelFactory } from '@theia/debug/lib/browser/editor/debug-editor-model';
import { StorageWrapper } from './storage-wrapper';
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';
import { NotificationsRenderer } from './theia/messages/notifications-renderer';
import { SketchbookWidgetContribution } from './widgets/sketchbook/sketchbook-widget-contribution';
import { LocalCacheFsProvider } from './local-cache/local-cache-fs-provider';
import { CloudSketchbookWidget } from './widgets/cloud-sketchbook/cloud-sketchbook-widget';
import { CloudSketchbookTreeWidget } from './widgets/cloud-sketchbook/cloud-sketchbook-tree-widget';
import { createCloudSketchbookTreeWidget } from './widgets/cloud-sketchbook/cloud-sketchbook-tree-container';
import { CreateApi } from './create/create-api';
import { ShareSketchDialog } from './dialogs.ts/cloud-share-sketch-dialog';
import { AuthenticationClientService } from './auth/authentication-client-service';
import {
AuthenticationService,
AuthenticationServicePath,
} from '../common/protocol/authentication-service';
import { CreateFsProvider } from './create/create-fs-provider';
import { FileServiceContribution } from '@theia/filesystem/lib/browser/file-service';
import { CloudSketchbookContribution } from './widgets/cloud-sketchbook/cloud-sketchbook-contributions';
import { CloudSketchbookCompositeWidget } from './widgets/cloud-sketchbook/cloud-sketchbook-composite-widget';
import { SketchbookWidget } from './widgets/sketchbook/sketchbook-widget';
import { SketchbookTreeWidget } from './widgets/sketchbook/sketchbook-tree-widget';
import { createSketchbookTreeWidget } from './widgets/sketchbook/sketchbook-tree-container';
const ElementQueries = require('css-element-queries/src/ElementQueries');
@@ -160,7 +243,7 @@ MonacoThemingService.register({
id: 'arduino-theme',
label: 'Light (Arduino)',
uiTheme: 'vs',
json: require('../../src/browser/data/arduino.color-theme.json')
json: require('../../src/browser/data/arduino.color-theme.json'),
});
export default new ContainerModule((bind, unbind, isBound, rebind) => {
@@ -172,7 +255,9 @@ export default new ContainerModule((bind, unbind, isBound, rebind) => {
bind(CommandContribution).toService(ArduinoFrontendContribution);
bind(MenuContribution).toService(ArduinoFrontendContribution);
bind(TabBarToolbarContribution).toService(ArduinoFrontendContribution);
bind(FrontendApplicationContribution).toService(ArduinoFrontendContribution);
bind(FrontendApplicationContribution).toService(
ArduinoFrontendContribution
);
bind(ColorContribution).toService(ArduinoFrontendContribution);
bind(ArduinoToolbarContribution).toSelf().inSingletonScope();
@@ -182,40 +267,75 @@ export default new ContainerModule((bind, unbind, isBound, rebind) => {
bind(ListItemRenderer).toSelf().inSingletonScope();
// Library service
bind(LibraryService).toDynamicValue(context => WebSocketConnectionProvider.createProxy(context.container, LibraryServicePath)).inSingletonScope();
bind(LibraryService)
.toDynamicValue((context) =>
WebSocketConnectionProvider.createProxy(
context.container,
LibraryServicePath
)
)
.inSingletonScope();
// Library list widget
bind(LibraryListWidget).toSelf();
bindViewContribution(bind, LibraryListWidgetFrontendContribution);
bind(WidgetFactory).toDynamicValue(context => ({
bind(WidgetFactory).toDynamicValue((context) => ({
id: LibraryListWidget.WIDGET_ID,
createWidget: () => context.container.get(LibraryListWidget)
createWidget: () => context.container.get(LibraryListWidget),
}));
bind(FrontendApplicationContribution).toService(LibraryListWidgetFrontendContribution);
bind(FrontendApplicationContribution).toService(
LibraryListWidgetFrontendContribution
);
// Sketch list service
bind(SketchesService).toDynamicValue(context => WebSocketConnectionProvider.createProxy(context.container, SketchesServicePath)).inSingletonScope();
bind(SketchesService)
.toDynamicValue((context) =>
WebSocketConnectionProvider.createProxy(
context.container,
SketchesServicePath
)
)
.inSingletonScope();
bind(SketchesServiceClientImpl).toSelf().inSingletonScope();
bind(FrontendApplicationContribution).toService(SketchesServiceClientImpl);
// Config service
bind(ConfigService).toDynamicValue(context => WebSocketConnectionProvider.createProxy(context.container, ConfigServicePath)).inSingletonScope();
bind(ConfigService)
.toDynamicValue((context) =>
WebSocketConnectionProvider.createProxy(
context.container,
ConfigServicePath
)
)
.inSingletonScope();
// Boards service
bind(BoardsService).toDynamicValue(context => WebSocketConnectionProvider.createProxy(context.container, BoardsServicePath)).inSingletonScope();
bind(BoardsService)
.toDynamicValue((context) =>
WebSocketConnectionProvider.createProxy(
context.container,
BoardsServicePath
)
)
.inSingletonScope();
// Boards service client to receive and delegate notifications from the backend.
bind(BoardsServiceProvider).toSelf().inSingletonScope();
bind(FrontendApplicationContribution).toService(BoardsServiceProvider);
// To be able to track, and update the menu based on the core settings (aka. board details) of the currently selected board.
bind(FrontendApplicationContribution).to(BoardsDataMenuUpdater).inSingletonScope();
bind(FrontendApplicationContribution)
.to(BoardsDataMenuUpdater)
.inSingletonScope();
bind(BoardsDataStore).toSelf().inSingletonScope();
bind(FrontendApplicationContribution).toService(BoardsDataStore);
// Logger for the Arduino daemon
bind(ILogger).toDynamicValue(ctx => {
const parentLogger = ctx.container.get<ILogger>(ILogger);
return parentLogger.child('store');
}).inSingletonScope().whenTargetNamed('store');
bind(ILogger)
.toDynamicValue((ctx) => {
const parentLogger = ctx.container.get<ILogger>(ILogger);
return parentLogger.child('store');
})
.inSingletonScope()
.whenTargetNamed('store');
// Boards auto-installer
bind(BoardsAutoInstaller).toSelf().inSingletonScope();
@@ -224,21 +344,30 @@ export default new ContainerModule((bind, unbind, isBound, rebind) => {
// Boards list widget
bind(BoardsListWidget).toSelf();
bindViewContribution(bind, BoardsListWidgetFrontendContribution);
bind(WidgetFactory).toDynamicValue(context => ({
bind(WidgetFactory).toDynamicValue((context) => ({
id: BoardsListWidget.WIDGET_ID,
createWidget: () => context.container.get(BoardsListWidget)
createWidget: () => context.container.get(BoardsListWidget),
}));
bind(FrontendApplicationContribution).toService(BoardsListWidgetFrontendContribution);
bind(FrontendApplicationContribution).toService(
BoardsListWidgetFrontendContribution
);
// Board select dialog
bind(BoardsConfigDialogWidget).toSelf().inSingletonScope();
bind(BoardsConfigDialog).toSelf().inSingletonScope();
bind(BoardsConfigDialogProps).toConstantValue({
title: 'Select Board'
})
title: 'Select Board',
});
// Core service
bind(CoreService).toDynamicValue(context => WebSocketConnectionProvider.createProxy(context.container, CoreServicePath)).inSingletonScope();
bind(CoreService)
.toDynamicValue((context) =>
WebSocketConnectionProvider.createProxy(
context.container,
CoreServicePath
)
)
.inSingletonScope();
// Serial monitor
bind(MonitorModel).toSelf().inSingletonScope();
@@ -246,84 +375,130 @@ export default new ContainerModule((bind, unbind, isBound, rebind) => {
bind(MonitorWidget).toSelf();
bindViewContribution(bind, MonitorViewContribution);
bind(TabBarToolbarContribution).toService(MonitorViewContribution);
bind(WidgetFactory).toDynamicValue(context => ({
bind(WidgetFactory).toDynamicValue((context) => ({
id: MonitorWidget.ID,
createWidget: () => context.container.get(MonitorWidget)
createWidget: () => context.container.get(MonitorWidget),
}));
// Frontend binding for the serial monitor service
bind(MonitorService).toDynamicValue(context => {
const connection = context.container.get(WebSocketConnectionProvider);
const client = context.container.get(MonitorServiceClientImpl);
return connection.createProxy(MonitorServicePath, client);
}).inSingletonScope();
bind(MonitorService)
.toDynamicValue((context) => {
const connection = context.container.get(
WebSocketConnectionProvider
);
const client = context.container.get(MonitorServiceClientImpl);
return connection.createProxy(MonitorServicePath, client);
})
.inSingletonScope();
bind(MonitorConnection).toSelf().inSingletonScope();
// Serial monitor service client to receive and delegate notifications from the backend.
bind(MonitorServiceClientImpl).toSelf().inSingletonScope();
bind(MonitorServiceClient).toDynamicValue(context => {
const client = context.container.get(MonitorServiceClientImpl);
WebSocketConnectionProvider.createProxy(context.container, MonitorServicePath, client);
return client;
}).inSingletonScope();
bind(MonitorServiceClient)
.toDynamicValue((context) => {
const client = context.container.get(MonitorServiceClientImpl);
WebSocketConnectionProvider.createProxy(
context.container,
MonitorServicePath,
client
);
return client;
})
.inSingletonScope();
bind(WorkspaceService).toSelf().inSingletonScope();
rebind(TheiaWorkspaceService).toService(WorkspaceService);
bind(WorkspaceVariableContribution).toSelf().inSingletonScope();
rebind(TheiaWorkspaceVariableContribution).toService(WorkspaceVariableContribution);
rebind(TheiaWorkspaceVariableContribution).toService(
WorkspaceVariableContribution
);
// Customizing default Theia layout based on the editor mode: `pro-mode` or `classic`.
bind(EditorMode).toSelf().inSingletonScope();
bind(FrontendApplicationContribution).toService(EditorMode);
// Layout and shell customizations.
rebind(TheiaOutlineViewContribution).to(OutlineViewContribution).inSingletonScope();
rebind(TheiaOutlineViewContribution)
.to(OutlineViewContribution)
.inSingletonScope();
rebind(TheiaProblemContribution).to(ProblemContribution).inSingletonScope();
rebind(TheiaFileNavigatorContribution).to(FileNavigatorContribution).inSingletonScope();
rebind(TheiaFileNavigatorContribution)
.to(FileNavigatorContribution)
.inSingletonScope();
rebind(TheiaKeymapsFrontendContribution)
.to(KeymapsFrontendContribution)
.inSingletonScope();
rebind(TheiaEditorContribution).to(EditorContribution).inSingletonScope();
rebind(TheiaMonacoStatusBarContribution).to(MonacoStatusBarContribution).inSingletonScope();
rebind(TheiaMonacoStatusBarContribution)
.to(MonacoStatusBarContribution)
.inSingletonScope();
rebind(TheiaApplicationShell).to(ApplicationShell).inSingletonScope();
rebind(TheiaScmContribution).to(ScmContribution).inSingletonScope();
rebind(TheiaSearchInWorkspaceFrontendContribution).to(SearchInWorkspaceFrontendContribution).inSingletonScope();
rebind(TheiaSearchInWorkspaceFrontendContribution)
.to(SearchInWorkspaceFrontendContribution)
.inSingletonScope();
rebind(TheiaFrontendApplication).to(FrontendApplication).inSingletonScope();
rebind(TheiaWorkspaceFrontendContribution).to(WorkspaceFrontendContribution).inSingletonScope();
rebind(TheiaFileMenuContribution).to(ArduinoFileMenuContribution).inSingletonScope();
rebind(TheiaCommonFrontendContribution).to(CommonFrontendContribution).inSingletonScope();
rebind(TheiaPreferencesContribution).to(PreferencesContribution).inSingletonScope();
rebind(TheiaWorkspaceFrontendContribution)
.to(WorkspaceFrontendContribution)
.inSingletonScope();
rebind(TheiaFileMenuContribution)
.to(ArduinoFileMenuContribution)
.inSingletonScope();
rebind(TheiaCommonFrontendContribution)
.to(CommonFrontendContribution)
.inSingletonScope();
rebind(TheiaPreferencesContribution)
.to(PreferencesContribution)
.inSingletonScope();
rebind(TheiaKeybindingRegistry).to(KeybindingRegistry).inSingletonScope();
rebind(TheiaWorkspaceCommandContribution).to(WorkspaceCommandContribution).inSingletonScope();
rebind(TheiaWorkspaceDeleteHandler).to(WorkspaceDeleteHandler).inSingletonScope();
rebind(TheiaWorkspaceCommandContribution)
.to(WorkspaceCommandContribution)
.inSingletonScope();
rebind(TheiaWorkspaceDeleteHandler)
.to(WorkspaceDeleteHandler)
.inSingletonScope();
rebind(TheiaEditorWidgetFactory).to(EditorWidgetFactory).inSingletonScope();
rebind(TabBarToolbarFactory).toFactory(({ container: parentContainer }) => () => {
const container = parentContainer.createChild();
container.bind(TabBarToolbar).toSelf().inSingletonScope();
return container.get(TabBarToolbar);
});
rebind(TabBarToolbarFactory).toFactory(
({ container: parentContainer }) =>
() => {
const container = parentContainer.createChild();
container.bind(TabBarToolbar).toSelf().inSingletonScope();
return container.get(TabBarToolbar);
}
);
bind(OutputWidget).toSelf().inSingletonScope();
rebind(TheiaOutputWidget).toService(OutputWidget);
bind(OutputChannelManager).toSelf().inSingletonScope();
rebind(TheiaOutputChannelManager).toService(OutputChannelManager);
bind(OutputChannelRegistryMainImpl).toSelf().inTransientScope();
rebind(TheiaOutputChannelRegistryMainImpl).toService(OutputChannelRegistryMainImpl);
rebind(TheiaOutputChannelRegistryMainImpl).toService(
OutputChannelRegistryMainImpl
);
bind(MonacoTextModelService).toSelf().inSingletonScope();
rebind(TheiaMonacoTextModelService).toService(MonacoTextModelService);
bind(MonacoEditorProvider).toSelf().inSingletonScope();
rebind(TheiaMonacoEditorProvider).toService(MonacoEditorProvider);
bind(SearchInWorkspaceWidget).toSelf();
rebind(TheiaSearchInWorkspaceWidget).toService(SearchInWorkspaceWidget);
rebind(TheiaSearchInWorkspaceResultTreeWidget).toDynamicValue(({ container }) => {
const childContainer = createTreeContainer(container);
childContainer.bind(SearchInWorkspaceResultTreeWidget).toSelf()
childContainer.rebind(TreeWidget).toService(SearchInWorkspaceResultTreeWidget);
return childContainer.get(SearchInWorkspaceResultTreeWidget);
});
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(ApplicationConnectionStatusContribution);
rebind(TheiaApplicationConnectionStatusContribution).toService(
ApplicationConnectionStatusContribution
);
bind(FrontendConnectionStatusService).toSelf().inSingletonScope();
rebind(TheiaFrontendConnectionStatusService).toService(FrontendConnectionStatusService);
// Editor customizations. Sets the editor to `readOnly` if under the data dir.
bind(EditorManager).toSelf().inSingletonScope();
rebind(TheiaEditorManager).toService(EditorManager);
rebind(TheiaFrontendConnectionStatusService).toService(
FrontendConnectionStatusService
);
// Decorator customizations
bind(TabBarDecoratorService).toSelf().inSingletonScope();
@@ -341,16 +516,44 @@ export default new ContainerModule((bind, unbind, isBound, rebind) => {
bind(OutputToolbarContribution).toSelf().inSingletonScope();
rebind(TheiaOutputToolbarContribution).toService(OutputToolbarContribution);
bind(ArduinoDaemon).toDynamicValue(context => WebSocketConnectionProvider.createProxy(context.container, ArduinoDaemonPath)).inSingletonScope();
bind(ArduinoDaemon)
.toDynamicValue((context) =>
WebSocketConnectionProvider.createProxy(
context.container,
ArduinoDaemonPath
)
)
.inSingletonScope();
// File-system extension
bind(FileSystemExt).toDynamicValue(context => WebSocketConnectionProvider.createProxy(context.container, FileSystemExtPath)).inSingletonScope();
bind(FileSystemExt)
.toDynamicValue((context) =>
WebSocketConnectionProvider.createProxy(
context.container,
FileSystemExtPath
)
)
.inSingletonScope();
// Examples service@
bind(ExamplesService).toDynamicValue(context => WebSocketConnectionProvider.createProxy(context.container, ExamplesServicePath)).inSingletonScope();
bind(ExamplesService)
.toDynamicValue((context) =>
WebSocketConnectionProvider.createProxy(
context.container,
ExamplesServicePath
)
)
.inSingletonScope();
// Executable URIs known by the backend
bind(ExecutableService).toDynamicValue(context => WebSocketConnectionProvider.createProxy(context.container, ExecutableServicePath)).inSingletonScope();
bind(ExecutableService)
.toDynamicValue((context) =>
WebSocketConnectionProvider.createProxy(
context.container,
ExecutableServicePath
)
)
.inSingletonScope();
Contribution.configure(bind, NewSketch);
Contribution.configure(bind, OpenSketch);
@@ -378,22 +581,44 @@ export default new ContainerModule((bind, unbind, isBound, rebind) => {
Contribution.configure(bind, ArchiveSketch);
Contribution.configure(bind, AddZipLibrary);
bind(OutputServiceImpl).toSelf().inSingletonScope().onActivation(({ container }, outputService) => {
WebSocketConnectionProvider.createProxy(container, OutputServicePath, outputService);
return outputService;
});
bind(OutputService).toService(OutputServiceImpl);
bind(ResponseServiceImpl)
.toSelf()
.inSingletonScope()
.onActivation(({ container }, responseService) => {
WebSocketConnectionProvider.createProxy(
container,
ResponseServicePath,
responseService
);
return responseService;
});
bind(ResponseService).toService(ResponseServiceImpl);
bind(NotificationCenter).toSelf().inSingletonScope();
bind(FrontendApplicationContribution).toService(NotificationCenter);
bind(NotificationServiceServer).toDynamicValue(context => WebSocketConnectionProvider.createProxy(context.container, NotificationServicePath)).inSingletonScope();
bind(NotificationServiceServer)
.toDynamicValue((context) =>
WebSocketConnectionProvider.createProxy(
context.container,
NotificationServicePath
)
)
.inSingletonScope();
// Enable the dirty indicator on uncloseable widgets.
rebind(TabBarRendererFactory).toFactory(context => () => {
const contextMenuRenderer = context.container.get<ContextMenuRenderer>(ContextMenuRenderer);
const decoratorService = context.container.get<TabBarDecoratorService>(TabBarDecoratorService);
const iconThemeService = context.container.get<IconThemeService>(IconThemeService);
return new TabBarRenderer(contextMenuRenderer, decoratorService, iconThemeService);
rebind(TabBarRendererFactory).toFactory((context) => () => {
const contextMenuRenderer =
context.container.get<ContextMenuRenderer>(ContextMenuRenderer);
const decoratorService = context.container.get<TabBarDecoratorService>(
TabBarDecoratorService
);
const iconThemeService =
context.container.get<IconThemeService>(IconThemeService);
return new TabBarRenderer(
contextMenuRenderer,
decoratorService,
iconThemeService
);
});
// Workaround for https://github.com/eclipse-theia/theia/issues/8722
@@ -410,11 +635,24 @@ export default new ContainerModule((bind, unbind, isBound, rebind) => {
rebind(TheiaDebugSessionManager).toService(DebugSessionManager);
// To remove the `Run` menu item from the application menu.
bind(DebugFrontendApplicationContribution).toSelf().inSingletonScope();
rebind(TheiaDebugFrontendApplicationContribution).toService(DebugFrontendApplicationContribution);
rebind(TheiaDebugFrontendApplicationContribution).toService(
DebugFrontendApplicationContribution
);
// To be able to use a `launch.json` from outside of the workspace.
bind(DebugConfigurationManager).toSelf().inSingletonScope();
rebind(TheiaDebugConfigurationManager).toService(DebugConfigurationManager);
// Patch for the debug hover: https://github.com/eclipse-theia/theia/pull/9256/
rebind(DebugEditorModelFactory)
.toDynamicValue(
({ container }) =>
<DebugEditorModelFactory>(
((editor) =>
DebugEditorModel.createModel(container, editor))
)
)
.inSingletonScope();
// Preferences
bindArduinoPreferences(bind);
@@ -424,6 +662,61 @@ export default new ContainerModule((bind, unbind, isBound, rebind) => {
bind(SettingsWidget).toSelf().inSingletonScope();
bind(SettingsDialog).toSelf().inSingletonScope();
bind(SettingsDialogProps).toConstantValue({
title: 'Preferences'
title: 'Preferences',
});
bind(StorageWrapper).toSelf().inSingletonScope();
bind(CommandContribution).toService(StorageWrapper);
bind(NotificationManager).toSelf().inSingletonScope();
rebind(TheiaNotificationManager).toService(NotificationManager);
bind(NotificationsRenderer).toSelf().inSingletonScope();
rebind(TheiaNotificationsRenderer).toService(NotificationsRenderer);
// UI for the Sketchbook
bind(SketchbookWidget).toSelf();
bind(SketchbookTreeWidget).toDynamicValue(({ container }) =>
createSketchbookTreeWidget(container)
);
bindViewContribution(bind, SketchbookWidgetContribution);
bind(FrontendApplicationContribution).toService(
SketchbookWidgetContribution
);
bind(WidgetFactory).toDynamicValue(({ container }) => ({
id: 'arduino-sketchbook-widget',
createWidget: () => container.get(SketchbookWidget),
}));
bind(CloudSketchbookWidget).toSelf();
rebind(SketchbookWidget).toService(CloudSketchbookWidget);
bind(CloudSketchbookTreeWidget).toDynamicValue(({ container }) =>
createCloudSketchbookTreeWidget(container)
);
bind(CreateApi).toSelf().inSingletonScope();
bind(ShareSketchDialog).toSelf().inSingletonScope();
bind(AuthenticationClientService).toSelf().inSingletonScope();
bind(CommandContribution).toService(AuthenticationClientService);
bind(FrontendApplicationContribution).toService(
AuthenticationClientService
);
bind(AuthenticationService)
.toDynamicValue((context) =>
WebSocketConnectionProvider.createProxy(
context.container,
AuthenticationServicePath
)
)
.inSingletonScope();
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) => ({
id: 'cloud-sketchbook-composite-widget',
createWidget: () => ctx.container.get(CloudSketchbookCompositeWidget),
}));
});

View File

@@ -1,50 +1,117 @@
import { interfaces } from 'inversify';
import { createPreferenceProxy, PreferenceProxy, PreferenceService, PreferenceContribution, PreferenceSchema } from '@theia/core/lib/browser/preferences';
import {
createPreferenceProxy,
PreferenceProxy,
PreferenceService,
PreferenceContribution,
PreferenceSchema,
} from '@theia/core/lib/browser/preferences';
import { CompilerWarningLiterals, CompilerWarnings } from '../common/protocol';
export const ArduinoConfigSchema: PreferenceSchema = {
'type': 'object',
'properties': {
type: 'object',
properties: {
'arduino.language.log': {
'type': 'boolean',
'description': "True if the Arduino Language Server should generate log files into the sketch folder. Otherwise, false. It's false by default.",
'default': false
type: 'boolean',
description:
"True if the Arduino Language Server should generate log files into the sketch folder. Otherwise, false. It's false by default.",
default: false,
},
'arduino.compile.verbose': {
'type': 'boolean',
'description': 'True for verbose compile output. False by default',
'default': false
type: 'boolean',
description: 'True for verbose compile output. False by default',
default: false,
},
'arduino.compile.warnings': {
'enum': [...CompilerWarningLiterals],
'description': "Tells gcc which warning level to use. It's 'None' by default",
'default': 'None'
enum: [...CompilerWarningLiterals],
description:
"Tells gcc which warning level to use. It's 'None' by default",
default: 'None',
},
'arduino.upload.verbose': {
'type': 'boolean',
'description': 'True for verbose upload output. False by default.',
'default': false
type: 'boolean',
description: 'True for verbose upload output. False by default.',
default: false,
},
'arduino.upload.verify': {
'type': 'boolean',
'default': false
type: 'boolean',
default: false,
},
'arduino.window.autoScale': {
'type': 'boolean',
'description': 'True if the user interface automatically scales with the font size.',
'default': true
type: 'boolean',
description:
'True if the user interface automatically scales with the font size.',
default: true,
},
'arduino.window.zoomLevel': {
'type': 'number',
'description': 'Adjust the zoom level of the window. The original size is 0 and each increment above (e.g. 1) or below (e.g. -1) represents zooming 20% larger or smaller. You can also enter decimals to adjust the zoom level with a finer granularity.',
'default': 0
type: 'number',
description:
'Adjust the zoom level of the window. The original size is 0 and each increment above (e.g. 1) or below (e.g. -1) represents zooming 20% larger or smaller. You can also enter decimals to adjust the zoom level with a finer granularity.',
default: 0,
},
'arduino.ide.autoUpdate': {
'type': 'boolean',
'description': 'True to enable automatic update checks. The IDE will check for updates automatically and periodically.',
'default': true
}
}
type: 'boolean',
description:
'True to enable automatic update checks. The IDE will check for updates automatically and periodically.',
default: true,
},
'arduino.sketchbook.showAllFiles': {
type: 'boolean',
description:
'True to show all sketch files inside the sketch. It is false by default.',
default: false,
},
'arduino.cloud.enabled': {
type: 'boolean',
description:
'True if the sketch sync functions are enabled. Defaults to true.',
default: true,
},
'arduino.cloud.pull.warn': {
type: 'boolean',
description:
'True if users should be warned before pulling a cloud sketch. Defaults to true.',
default: true,
},
'arduino.cloud.push.warn': {
type: 'boolean',
description:
'True if users should be warned before pushing a cloud sketch. Defaults to true.',
default: true,
},
'arduino.cloud.pushpublic.warn': {
type: 'boolean',
description:
'True if users should be warned before pushing a public sketch to the cloud. Defaults to true.',
default: true,
},
'arduino.cloud.sketchSyncEnpoint': {
type: 'string',
description:
'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: 'The OAuth2 client ID.',
default: 'C34Ya6ex77jTNxyKWj01lCe1vAHIaPIo',
},
'arduino.auth.domain': {
type: 'string',
description: 'The OAuth2 domain.',
default: 'login.arduino.cc',
},
'arduino.auth.audience': {
type: 'string',
description: 'The 0Auth2 audience.',
default: 'https://api.arduino.cc',
},
'arduino.auth.registerUri': {
type: 'string',
description: 'The URI used to register a new user.',
default: 'https://auth.arduino.cc/login#/register',
},
},
};
export interface ArduinoConfiguration {
@@ -56,19 +123,34 @@ export interface ArduinoConfiguration {
'arduino.window.autoScale': boolean;
'arduino.window.zoomLevel': number;
'arduino.ide.autoUpdate': boolean;
'arduino.sketchbook.showAllFiles': boolean;
'arduino.cloud.enabled': boolean;
'arduino.cloud.pull.warn': boolean;
'arduino.cloud.push.warn': boolean;
'arduino.cloud.pushpublic.warn': boolean;
'arduino.cloud.sketchSyncEnpoint': string;
'arduino.auth.clientID': string;
'arduino.auth.domain': string;
'arduino.auth.audience': string;
'arduino.auth.registerUri': string;
}
export const ArduinoPreferences = Symbol('ArduinoPreferences');
export type ArduinoPreferences = PreferenceProxy<ArduinoConfiguration>;
export function createArduinoPreferences(preferences: PreferenceService): ArduinoPreferences {
export function createArduinoPreferences(
preferences: PreferenceService
): ArduinoPreferences {
return createPreferenceProxy(preferences, ArduinoConfigSchema);
}
export function bindArduinoPreferences(bind: interfaces.Bind): void {
bind(ArduinoPreferences).toDynamicValue(ctx => {
const preferences = ctx.container.get<PreferenceService>(PreferenceService);
bind(ArduinoPreferences).toDynamicValue((ctx) => {
const preferences =
ctx.container.get<PreferenceService>(PreferenceService);
return createArduinoPreferences(preferences);
});
bind(PreferenceContribution).toConstantValue({ schema: ArduinoConfigSchema });
bind(PreferenceContribution).toConstantValue({
schema: ArduinoConfigSchema,
});
}

View File

@@ -7,7 +7,7 @@ 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
@@ -24,20 +24,24 @@ namespace ArduinoWorkspaceRootResolver {
readonly isValid: (uri: string) => MaybePromise<boolean>;
}
export interface ResolveOptions {
readonly hash?: string
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) {}
constructor(protected options: ArduinoWorkspaceRootResolver.InitOptions) {
}
async resolve(options: ArduinoWorkspaceRootResolver.ResolveOptions): Promise<{ uri: string } | undefined> {
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)) {
for (const uri of [
this.hashToUri(hash),
...recentWorkspaces,
...recentSketches,
].filter(notEmpty)) {
const valid = await this.isValid(uri);
if (valid) {
return { uri };
@@ -56,13 +60,14 @@ export class ArduinoWorkspaceRootResolver {
// - 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('#')) {
if (hash && hash.length > 1 && hash.startsWith('#')) {
const path = hash.slice(1); // Trim the leading `#`.
return new URI(toUnix(path.slice(isWindows && hash.startsWith('/') ? 1 : 0))).withScheme('file').toString();
return new URI(
toUnix(path.slice(isWindows && hash.startsWith('/') ? 1 : 0))
)
.withScheme('file')
.toString();
}
return undefined;
}
}

View File

@@ -0,0 +1,93 @@
import { inject, injectable } from 'inversify';
import { Emitter } from '@theia/core/lib/common/event';
import { JsonRpcProxy } from '@theia/core/lib/common/messaging/proxy-factory';
import { WindowService } from '@theia/core/lib/browser/window/window-service';
import { DisposableCollection } from '@theia/core/lib/common/disposable';
import { FrontendApplicationContribution } from '@theia/core/lib/browser/frontend-application';
import {
CommandRegistry,
CommandContribution,
} from '@theia/core/lib/common/command';
import {
AuthenticationService,
AuthenticationServiceClient,
AuthenticationSession,
} 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()
export class AuthenticationClientService
implements
FrontendApplicationContribution,
CommandContribution,
AuthenticationServiceClient
{
@inject(AuthenticationService)
protected readonly service: JsonRpcProxy<AuthenticationService>;
@inject(WindowService)
protected readonly windowService: WindowService;
@inject(ArduinoPreferences)
protected readonly arduinoPreferences: ArduinoPreferences;
protected authOptions: AuthOptions;
protected _session: AuthenticationSession | undefined;
protected readonly toDispose = new DisposableCollection();
protected readonly onSessionDidChangeEmitter = new Emitter<
AuthenticationSession | undefined
>();
readonly onSessionDidChange = this.onSessionDidChangeEmitter.event;
onStart(): void {
this.toDispose.push(this.onSessionDidChangeEmitter);
this.service.setClient(this);
this.service
.session()
.then((session) => this.notifySessionDidChange(session));
this.setOptions();
this.arduinoPreferences.onPreferenceChanged((event) => {
if (event.preferenceName.startsWith('arduino.auth.')) {
this.setOptions();
}
});
}
setOptions(): void {
this.service.setOptions({
redirectUri: `http://localhost:${serverPort}/callback`,
responseType: 'code',
clientID: this.arduinoPreferences['arduino.auth.clientID'],
domain: this.arduinoPreferences['arduino.auth.domain'],
audience: this.arduinoPreferences['arduino.auth.audience'],
registerUri: this.arduinoPreferences['arduino.auth.registerUri'],
scopes: ['openid', 'profile', 'email', 'offline_access'],
});
}
protected updateSession(session?: AuthenticationSession | undefined) {
this._session = session;
this.onSessionDidChangeEmitter.fire(this._session);
}
get session(): AuthenticationSession | undefined {
return this._session;
}
registerCommands(registry: CommandRegistry): void {
registry.registerCommand(CloudUserCommands.LOGIN, {
execute: () => this.service.login(),
});
registry.registerCommand(CloudUserCommands.LOGOUT, {
execute: () => this.service.logout(),
});
}
notifySessionDidChange(session: AuthenticationSession | undefined): void {
this.updateSession(session);
}
}

View File

@@ -0,0 +1,18 @@
import { Command } from '@theia/core/lib/common/command';
export namespace CloudUserCommands {
export const LOGIN: Command = {
id: 'arduino-cloud--login',
label: 'Sign in',
};
export const LOGOUT: Command = {
id: 'arduino-cloud--logout',
label: 'Sign Out',
};
export const OPEN_PROFILE_CONTEXT_MENU: Command = {
id: 'arduino-cloud-sketchbook--open-profile-menu',
label: 'Contextual menu',
};
}

View File

@@ -1,11 +1,16 @@
import { injectable, inject } from 'inversify';
import { MessageService } from '@theia/core/lib/common/message-service';
import { FrontendApplicationContribution } from '@theia/core/lib/browser/frontend-application';
import { BoardsService, BoardsPackage } from '../../common/protocol/boards-service';
import {
BoardsService,
BoardsPackage,
Board,
} from '../../common/protocol/boards-service';
import { BoardsServiceProvider } from './boards-service-provider';
import { BoardsListWidgetFrontendContribution } from './boards-widget-frontend-contribution';
import { InstallationProgressDialog } from '../widgets/progress-dialog';
import { BoardsConfig } from './boards-config';
import { Installable } from '../../common/protocol';
import { ResponseServiceImpl } from '../response-service-impl';
/**
* Listens on `BoardsConfig.Config` changes, if a board is selected which does not
@@ -13,7 +18,6 @@ import { BoardsConfig } from './boards-config';
*/
@injectable()
export class BoardsAutoInstaller implements FrontendApplicationContribution {
@inject(MessageService)
protected readonly messageService: MessageService;
@@ -23,40 +27,102 @@ export class BoardsAutoInstaller implements FrontendApplicationContribution {
@inject(BoardsServiceProvider)
protected readonly boardsServiceClient: BoardsServiceProvider;
@inject(ResponseServiceImpl)
protected readonly responseService: ResponseServiceImpl;
@inject(BoardsListWidgetFrontendContribution)
protected readonly boardsManagerFrontendContribution: BoardsListWidgetFrontendContribution;
// Workaround for https://github.com/eclipse-theia/theia/issues/9349
protected notifications: Board[] = [];
onStart(): void {
this.boardsServiceClient.onBoardsConfigChanged(this.ensureCoreExists.bind(this));
this.boardsServiceClient.onBoardsConfigChanged(
this.ensureCoreExists.bind(this)
);
this.ensureCoreExists(this.boardsServiceClient.boardsConfig);
}
protected ensureCoreExists(config: BoardsConfig.Config): void {
const { selectedBoard } = config;
if (selectedBoard) {
this.boardsService.search({}).then(packages => {
const candidates = packages
.filter(pkg => BoardsPackage.contains(selectedBoard, pkg))
.filter(({ installable, installedVersion }) => installable && !installedVersion);
for (const candidate of candidates) {
// tslint:disable-next-line:max-line-length
this.messageService.info(`The \`"${candidate.name}"\` core has to be installed for the currently selected \`"${selectedBoard.name}"\` board. Do you want to install it now?`, 'Install Manually', 'Yes').then(async answer => {
if (answer === 'Yes') {
const dialog = new InstallationProgressDialog(candidate.name, candidate.availableVersions[0]);
dialog.open();
try {
await this.boardsService.install({ item: candidate });
} finally {
dialog.close();
}
}
if (answer) {
this.boardsManagerFrontendContribution.openView({ reveal: true }).then(widget => widget.refresh(candidate.name.toLocaleLowerCase()));
}
});
if (
selectedBoard &&
!this.notifications.find((board) =>
Board.sameAs(board, selectedBoard)
)
) {
this.notifications.push(selectedBoard);
this.boardsService.search({}).then((packages) => {
// 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
)
) {
return;
}
})
// 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
);
const candidate = candidates[0];
if (candidate) {
const version = candidate.availableVersions[0]
? `[v ${candidate.availableVersions[0]}]`
: '';
// tslint:disable-next-line:max-line-length
this.messageService
.info(
`The \`"${candidate.name} ${version}"\` core has to be installed for the currently selected \`"${selectedBoard.name}"\` board. Do you want to install it now?`,
'Install Manually',
'Yes'
)
.then(async (answer) => {
const index = this.notifications.findIndex(
(board) => Board.sameAs(board, selectedBoard)
);
if (index !== -1) {
this.notifications.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) {
this.boardsManagerFrontendContribution
.openView({ reveal: true })
.then((widget) =>
widget.refresh(
candidate.name.toLocaleLowerCase()
)
);
}
});
}
});
}
}
}

View File

@@ -9,7 +9,6 @@ import { NotificationCenter } from '../notification-center';
@injectable()
export class BoardsConfigDialogWidget extends ReactWidget {
@inject(BoardsService)
protected readonly boardsService: BoardsService;
@@ -20,7 +19,8 @@ export class BoardsConfigDialogWidget extends ReactWidget {
protected readonly notificationCenter: NotificationCenter;
protected readonly onFilterTextDidChangeEmitter = new Emitter<string>();
protected readonly onBoardConfigChangedEmitter = new Emitter<BoardsConfig.Config>();
protected readonly onBoardConfigChangedEmitter =
new Emitter<BoardsConfig.Config>();
readonly onBoardConfigChanged = this.onBoardConfigChangedEmitter.event;
protected focusNode: HTMLElement | undefined;
@@ -30,7 +30,7 @@ export class BoardsConfigDialogWidget extends ReactWidget {
this.id = 'select-board-dialog';
this.toDispose.pushAll([
this.onBoardConfigChangedEmitter,
this.onFilterTextDidChangeEmitter
this.onFilterTextDidChangeEmitter,
]);
}
@@ -40,21 +40,26 @@ export class BoardsConfigDialogWidget extends ReactWidget {
protected fireConfigChanged = (config: BoardsConfig.Config) => {
this.onBoardConfigChangedEmitter.fire(config);
}
};
protected setFocusNode = (element: HTMLElement | undefined) => {
this.focusNode = element;
}
};
protected render(): React.ReactNode {
return <div className='selectBoardContainer'>
<BoardsConfig
boardsServiceProvider={this.boardsServiceClient}
notificationCenter={this.notificationCenter}
onConfigChange={this.fireConfigChanged}
onFocusNodeSet={this.setFocusNode}
onFilteredTextDidChangeEvent={this.onFilterTextDidChangeEmitter.event} />
</div>;
return (
<div className="selectBoardContainer">
<BoardsConfig
boardsServiceProvider={this.boardsServiceClient}
notificationCenter={this.notificationCenter}
onConfigChange={this.fireConfigChanged}
onFocusNodeSet={this.setFocusNode}
onFilteredTextDidChangeEvent={
this.onFilterTextDidChangeEmitter.event
}
/>
</div>
);
}
protected onActivateRequest(msg: Message): void {
@@ -64,5 +69,4 @@ export class BoardsConfigDialogWidget extends ReactWidget {
}
(this.focusNode || this.node).focus();
}
}

View File

@@ -1,18 +1,21 @@
import { injectable, inject, postConstruct } from 'inversify';
import { Message } from '@phosphor/messaging';
import { AbstractDialog, DialogProps, Widget, DialogError } from '@theia/core/lib/browser';
import {
AbstractDialog,
DialogProps,
Widget,
DialogError,
} from '@theia/core/lib/browser';
import { BoardsConfig } from './boards-config';
import { BoardsService } from '../../common/protocol/boards-service';
import { BoardsServiceProvider } from './boards-service-provider';
import { BoardsConfigDialogWidget } from './boards-config-dialog-widget';
@injectable()
export class BoardsConfigDialogProps extends DialogProps {
}
export class BoardsConfigDialogProps extends DialogProps {}
@injectable()
export class BoardsConfigDialog extends AbstractDialog<BoardsConfig.Config> {
@inject(BoardsConfigDialogWidget)
protected readonly widget: BoardsConfigDialogWidget;
@@ -24,7 +27,10 @@ export class BoardsConfigDialog extends AbstractDialog<BoardsConfig.Config> {
protected config: BoardsConfig.Config = {};
constructor(@inject(BoardsConfigDialogProps) protected readonly props: BoardsConfigDialogProps) {
constructor(
@inject(BoardsConfigDialogProps)
protected readonly props: BoardsConfigDialogProps
) {
super(props);
this.contentNode.classList.add('select-board-dialog');
@@ -36,16 +42,20 @@ export class BoardsConfigDialog extends AbstractDialog<BoardsConfig.Config> {
@postConstruct()
protected init(): void {
this.toDispose.push(this.boardsServiceClient.onBoardsConfigChanged(config => {
this.config = config;
this.update();
}));
this.toDispose.push(
this.boardsServiceClient.onBoardsConfigChanged((config) => {
this.config = config;
this.update();
})
);
}
/**
* Pass in an empty string if you want to reset the search term. Using `undefined` has no effect.
*/
async open(query: string | undefined = undefined): Promise<BoardsConfig.Config | undefined> {
async open(
query: string | undefined = undefined
): Promise<BoardsConfig.Config | undefined> {
if (typeof query === 'string') {
this.widget.search(query);
}
@@ -67,9 +77,9 @@ export class BoardsConfigDialog extends AbstractDialog<BoardsConfig.Config> {
for (const paragraph of [
'Select both a Board and a Port if you want to upload a sketch.',
'If you only select a Board you will be able just to compile, but not to upload your sketch.'
'If you only select a Board you will be able just to compile, but not to upload your sketch.',
]) {
const p = document.createElement('p');
const p = document.createElement('div');
p.textContent = paragraph;
text.appendChild(p);
}
@@ -82,10 +92,12 @@ export class BoardsConfigDialog extends AbstractDialog<BoardsConfig.Config> {
Widget.detach(this.widget);
}
Widget.attach(this.widget, this.contentNode);
this.toDisposeOnDetach.push(this.widget.onBoardConfigChanged(config => {
this.config = config;
this.update();
}));
this.toDisposeOnDetach.push(
this.widget.onBoardConfigChanged((config) => {
this.config = config;
this.update();
})
);
super.onAfterAttach(msg);
this.update();
}
@@ -119,5 +131,4 @@ export class BoardsConfigDialog extends AbstractDialog<BoardsConfig.Config> {
get value(): BoardsConfig.Config {
return this.config;
}
}

View File

@@ -3,12 +3,16 @@ 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 {
Board,
Port,
AttachedBoardsChangeEvent,
BoardWithPackage,
} from '../../common/protocol/boards-service';
import { NotificationCenter } from '../notification-center';
import { BoardsServiceProvider } from './boards-service-provider';
export namespace BoardsConfig {
export interface Config {
selectedBoard?: Board;
selectedPort?: Port;
@@ -28,18 +32,16 @@ export namespace BoardsConfig {
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
item: T;
label: string;
selected: boolean;
onClick: (item: T) => void;
missing?: boolean;
details?: string;
}> {
render(): React.ReactNode {
const { selected, label, missing, details } = this.props;
const classNames = ['item'];
@@ -47,25 +49,36 @@ export abstract class Item<T> extends React.Component<{
classNames.push('selected');
}
if (missing === true) {
classNames.push('missing')
classNames.push('missing');
}
return <div onClick={this.onClick} className={classNames.join(' ')} title={`${label}${!details ? '' : details}`}>
<div className='label'>
{label}
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>
{!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> {
export class BoardsConfig extends React.Component<
BoardsConfig.Props,
BoardsConfig.State
> {
protected toDispose = new DisposableCollection();
constructor(props: BoardsConfig.Props) {
@@ -77,24 +90,51 @@ export class BoardsConfig extends React.Component<BoardsConfig.Props, BoardsConf
knownPorts: [],
showAllPorts: false,
query: '',
...boardsConfig
}
...boardsConfig,
};
}
componentDidMount() {
this.updateBoards();
this.updatePorts(this.props.boardsServiceProvider.availableBoards.map(({ port }) => port).filter(notEmpty));
this.updatePorts(
this.props.boardsServiceProvider.availableBoards
.map(({ port }) => port)
.filter(notEmpty)
);
this.toDispose.pushAll([
this.props.notificationCenter.onAttachedBoardsChanged(event => this.updatePorts(event.newState.ports, AttachedBoardsChangeEvent.diff(event).detached.ports)),
this.props.boardsServiceProvider.onBoardsConfigChanged(({ selectedBoard, selectedPort }) => {
this.setState({ selectedBoard, selectedPort }, () => this.fireConfigChanged());
}),
this.props.notificationCenter.onPlatformInstalled(() => this.updateBoards(this.state.query)),
this.props.notificationCenter.onPlatformUninstalled(() => this.updateBoards(this.state.query)),
this.props.notificationCenter.onIndexUpdated(() => this.updateBoards(this.state.query)),
this.props.notificationCenter.onDaemonStarted(() => this.updateBoards(this.state.query)),
this.props.notificationCenter.onDaemonStopped(() => this.setState({ searchResults: [] })),
this.props.onFilteredTextDidChangeEvent(query => this.setState({ query }, () => this.updateBoards(this.state.query)))
this.props.notificationCenter.onAttachedBoardsChanged((event) =>
this.updatePorts(
event.newState.ports,
AttachedBoardsChangeEvent.diff(event).detached.ports
)
),
this.props.boardsServiceProvider.onBoardsConfigChanged(
({ selectedBoard, selectedPort }) => {
this.setState({ selectedBoard, selectedPort }, () =>
this.fireConfigChanged()
);
}
),
this.props.notificationCenter.onPlatformInstalled(() =>
this.updateBoards(this.state.query)
),
this.props.notificationCenter.onPlatformUninstalled(() =>
this.updateBoards(this.state.query)
),
this.props.notificationCenter.onIndexUpdated(() =>
this.updateBoards(this.state.query)
),
this.props.notificationCenter.onDaemonStarted(() =>
this.updateBoards(this.state.query)
),
this.props.notificationCenter.onDaemonStopped(() =>
this.setState({ searchResults: [] })
),
this.props.onFilteredTextDidChangeEvent((query) =>
this.setState({ query }, () =>
this.updateBoards(this.state.query)
)
),
]);
}
@@ -107,73 +147,96 @@ export class BoardsConfig extends React.Component<BoardsConfig.Props, BoardsConf
this.props.onConfigChange({ selectedBoard, selectedPort });
}
protected updateBoards = (eventOrQuery: React.ChangeEvent<HTMLInputElement> | string = '') => {
const query = typeof eventOrQuery === 'string'
? eventOrQuery
: eventOrQuery.target.value.toLowerCase();
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 }));
}
this.queryBoards({ query }).then((searchResults) =>
this.setState({ searchResults })
);
};
protected updatePorts = (ports: Port[] = [], removedPorts: Port[] = []) => {
this.queryPorts(Promise.resolve(ports)).then(({ knownPorts }) => {
let { selectedPort } = this.state;
// If the currently selected port is not available anymore, unset the selected port.
if (removedPorts.some(port => Port.equals(port, selectedPort))) {
if (removedPorts.some((port) => Port.equals(port, selectedPort))) {
selectedPort = undefined;
}
this.setState({ knownPorts, selectedPort }, () => this.fireConfigChanged());
this.setState({ knownPorts, selectedPort }, () =>
this.fireConfigChanged()
);
});
}
};
protected queryBoards = (options: { query?: string } = {}): Promise<Array<BoardWithPackage>> => {
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);
return this.props.boardsServiceProvider.availableBoards
.map(({ port }) => port)
.filter(notEmpty);
}
protected queryPorts = async (availablePorts: MaybePromise<Port[]> = this.availablePorts) => {
protected queryPorts = async (
availablePorts: MaybePromise<Port[]> = this.availablePorts
) => {
const ports = await availablePorts;
return { knownPorts: ports.sort(Port.compare) };
}
};
protected toggleFilterPorts = () => {
this.setState({ showAllPorts: !this.state.showAllPorts });
}
};
protected selectPort = (selectedPort: Port | undefined) => {
this.setState({ selectedPort }, () => this.fireConfigChanged());
}
};
protected selectBoard = (selectedBoard: BoardWithPackage | undefined) => {
this.setState({ selectedBoard }, () => this.fireConfigChanged());
}
};
protected focusNodeSet = (element: HTMLElement | null) => {
this.props.onFocusNodeSet(element || undefined);
}
};
render(): React.ReactNode {
return <div className='body'>
{this.renderContainer('boards', this.renderBoards.bind(this))}
{this.renderContainer('ports', this.renderPorts.bind(this), this.renderPortsFooter.bind(this))}
</div>;
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() : '')}
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>
</div>;
);
}
protected renderBoards(): React.ReactNode {
@@ -181,98 +244,111 @@ export class BoardsConfig extends React.Component<BoardsConfig.Props, BoardsConf
// 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 toKey = ({ name, packageName, fqbn }: Board.Detailed) =>
!!fqbn
? `${name}-${packageName}-${fqbn}`
: `${name}-${packageName}`;
for (const board of Board.decorateBoards(
selectedBoard,
searchResults
)) {
const key = toKey(board);
if (!distinctBoards.has(key)) {
distinctBoards.set(key, board);
}
}
return <React.Fragment>
<div className='search'>
<input
type='search'
value={query}
className='theia-input'
placeholder='SEARCH BOARD'
onChange={this.updateBoards}
ref={this.focusNodeSet}
/>
<i className='fa fa-search'></i>
</div>
<div className='boards list'>
{Array.from(distinctBoards.values()).map(board => <Item<BoardWithPackage>
key={`${board.name}-${board.packageName}`}
item={board}
label={board.name}
details={board.details}
selected={board.selected}
onClick={this.selectBoard}
missing={board.missing}
/>)}
</div>
</React.Fragment>;
return (
<React.Fragment>
<div className="search">
<input
type="search"
value={query}
className="theia-input"
placeholder="SEARCH BOARD"
onChange={this.updateBoards}
ref={this.focusNodeSet}
/>
<i className="fa fa-search"></i>
</div>
<div className="boards list">
{Array.from(distinctBoards.values()).map((board) => (
<Item<BoardWithPackage>
key={`${board.name}-${board.packageName}`}
item={board}
label={board.name}
details={board.details}
selected={board.selected}
onClick={this.selectBoard}
missing={board.missing}
/>
))}
</div>
</React.Fragment>
);
}
protected renderPorts(): React.ReactNode {
const filter = this.state.showAllPorts ? () => true : Port.isBoardPort;
const ports = this.state.knownPorts.filter(filter);
return !ports.length ?
(
<div className='loading noselect'>
No ports discovered
</div>
) :
(
<div className='ports list'>
{ports.map(port => <Item<Port>
return !ports.length ? (
<div className="loading noselect">No ports discovered</div>
) : (
<div className="ports list">
{ports.map((port) => (
<Item<Port>
key={Port.toString(port)}
item={port}
label={Port.toString(port)}
selected={Port.equals(this.state.selectedPort, port)}
onClick={this.selectPort}
/>)}
</div>
);
/>
))}
</div>
);
}
protected renderPortsFooter(): React.ReactNode {
return <div className='noselect'>
<label
title='Shows all available ports when enabled'>
<input
type='checkbox'
defaultChecked={this.state.showAllPorts}
onChange={this.toggleFilterPorts}
/>
<span>Show all ports</span>
</label>
</div>;
return (
<div className="noselect">
<label title="Shows all available ports when enabled">
<input
type="checkbox"
defaultChecked={this.state.showAllPorts}
onChange={this.toggleFilterPorts}
/>
<span>Show all ports</span>
</label>
</div>
);
}
}
export namespace BoardsConfig {
export namespace Config {
export function sameAs(config: Config, other: Config | Board): boolean {
const { selectedBoard, selectedPort } = config;
if (Board.is(other)) {
return !!selectedBoard
&& Board.equals(other, selectedBoard)
&& Port.sameAs(selectedPort, other.port);
return (
!!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;
return (
left.selectedBoard === right.selectedBoard &&
left.selectedPort === right.selectedPort
);
}
export function toString(config: Config, options: { default: string } = { default: '' }): string {
export function toString(
config: Config,
options: { default: string } = { default: '' }
): string {
const { selectedBoard, selectedPort: port } = config;
if (!selectedBoard) {
return options.default;
@@ -281,6 +357,55 @@ export namespace BoardsConfig {
return `${name}${port ? ' at ' + Port.toString(port) : ''}`;
}
}
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

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

View File

@@ -3,14 +3,22 @@ import { ILogger } from '@theia/core/lib/common/logger';
import { deepClone } from '@theia/core/lib/common/objects';
import { MaybePromise } from '@theia/core/lib/common/types';
import { Event, Emitter } from '@theia/core/lib/common/event';
import { FrontendApplicationContribution, LocalStorageService } from '@theia/core/lib/browser';
import {
FrontendApplicationContribution,
LocalStorageService,
} from '@theia/core/lib/browser';
import { notEmpty } from '../../common/utils';
import { BoardsService, ConfigOption, Installable, BoardDetails, Programmer } from '../../common/protocol';
import {
BoardsService,
ConfigOption,
Installable,
BoardDetails,
Programmer,
} from '../../common/protocol';
import { NotificationCenter } from '../notification-center';
@injectable()
export class BoardsDataStore implements FrontendApplicationContribution {
@inject(ILogger)
@named('store')
protected readonly logger: ILogger;
@@ -33,9 +41,14 @@ export class BoardsDataStore implements FrontendApplicationContribution {
return;
}
let shouldFireChanged = false;
for (const fqbn of item.boards.map(({ fqbn }) => fqbn).filter(notEmpty).filter(fqbn => !!fqbn)) {
for (const fqbn of item.boards
.map(({ fqbn }) => fqbn)
.filter(notEmpty)
.filter((fqbn) => !!fqbn)) {
const key = this.getStorageKey(fqbn, version);
let data = await this.storageService.getData<ConfigOption[] | undefined>(key);
let data = await this.storageService.getData<
ConfigOption[] | undefined
>(key);
if (!data || !data.length) {
const details = await this.getBoardDetailsSafe(fqbn);
if (details) {
@@ -59,20 +72,27 @@ export class BoardsDataStore implements FrontendApplicationContribution {
async appendConfigToFqbn(
fqbn: string | undefined,
boardsPackageVersion: MaybePromise<Installable.Version | undefined> = this.getBoardsPackageVersion(fqbn)): Promise<string | undefined> {
boardsPackageVersion: MaybePromise<
Installable.Version | undefined
> = this.getBoardsPackageVersion(fqbn)
): Promise<string | undefined> {
if (!fqbn) {
return undefined;
}
const { configOptions } = await this.getData(fqbn, boardsPackageVersion);
const { configOptions } = await this.getData(
fqbn,
boardsPackageVersion
);
return ConfigOption.decorate(fqbn, configOptions);
}
async getData(
fqbn: string | undefined,
boardsPackageVersion: MaybePromise<Installable.Version | undefined> = this.getBoardsPackageVersion(fqbn)): Promise<BoardsDataStore.Data> {
boardsPackageVersion: MaybePromise<
Installable.Version | undefined
> = this.getBoardsPackageVersion(fqbn)
): Promise<BoardsDataStore.Data> {
if (!fqbn) {
return BoardsDataStore.Data.EMPTY;
}
@@ -82,7 +102,9 @@ export class BoardsDataStore implements FrontendApplicationContribution {
return BoardsDataStore.Data.EMPTY;
}
const key = this.getStorageKey(fqbn, version);
let data = await this.storageService.getData<BoardsDataStore.Data | undefined>(key, undefined);
let data = await this.storageService.getData<
BoardsDataStore.Data | undefined
>(key, undefined);
if (BoardsDataStore.Data.is(data)) {
return data;
}
@@ -92,18 +114,28 @@ export class BoardsDataStore implements FrontendApplicationContribution {
return BoardsDataStore.Data.EMPTY;
}
data = { configOptions: boardDetails.configOptions, programmers: boardDetails.programmers };
data = {
configOptions: boardDetails.configOptions,
programmers: boardDetails.programmers,
};
await this.storageService.setData(key, data);
return data;
}
async selectProgrammer(
{ fqbn, selectedProgrammer }: { fqbn: string, selectedProgrammer: Programmer },
boardsPackageVersion: MaybePromise<Installable.Version | undefined> = this.getBoardsPackageVersion(fqbn)): Promise<boolean> {
{
fqbn,
selectedProgrammer,
}: { fqbn: string; selectedProgrammer: Programmer },
boardsPackageVersion: MaybePromise<
Installable.Version | undefined
> = this.getBoardsPackageVersion(fqbn)
): Promise<boolean> {
const data = deepClone(await this.getData(fqbn, boardsPackageVersion));
const { programmers } = data;
if (!programmers.find(p => Programmer.equals(selectedProgrammer, p))) {
if (
!programmers.find((p) => Programmer.equals(selectedProgrammer, p))
) {
return false;
}
@@ -112,18 +144,28 @@ export class BoardsDataStore implements FrontendApplicationContribution {
return false;
}
await this.setData({ fqbn, data: { ...data, selectedProgrammer }, version });
await this.setData({
fqbn,
data: { ...data, selectedProgrammer },
version,
});
this.fireChanged();
return true;
}
async selectConfigOption(
{ fqbn, option, selectedValue }: { fqbn: string, option: string, selectedValue: string },
boardsPackageVersion: MaybePromise<Installable.Version | undefined> = this.getBoardsPackageVersion(fqbn)): Promise<boolean> {
{
fqbn,
option,
selectedValue,
}: { fqbn: string; option: string; selectedValue: string },
boardsPackageVersion: MaybePromise<
Installable.Version | undefined
> = this.getBoardsPackageVersion(fqbn)
): Promise<boolean> {
const data = deepClone(await this.getData(fqbn, boardsPackageVersion));
const { configOptions } = data;
const configOption = configOptions.find(c => c.option === option);
const configOption = configOptions.find((c) => c.option === option);
if (!configOption) {
return false;
}
@@ -149,26 +191,46 @@ export class BoardsDataStore implements FrontendApplicationContribution {
return true;
}
protected async setData(
{ fqbn, data, version }: { fqbn: string, data: BoardsDataStore.Data, version: Installable.Version }): Promise<void> {
protected async setData({
fqbn,
data,
version,
}: {
fqbn: string;
data: BoardsDataStore.Data;
version: Installable.Version;
}): Promise<void> {
const key = this.getStorageKey(fqbn, version);
return this.storageService.setData(key, data);
}
protected getStorageKey(fqbn: string, version: Installable.Version): string {
protected getStorageKey(
fqbn: string,
version: Installable.Version
): string {
return `.arduinoIDE-configOptions-${version}-${fqbn}`;
}
protected async getBoardDetailsSafe(fqbn: string): Promise<BoardDetails | undefined> {
protected async getBoardDetailsSafe(
fqbn: string
): Promise<BoardDetails | undefined> {
try {
const details = this.boardsService.getBoardDetails({ fqbn });
return details;
} catch (err) {
if (err instanceof Error && err.message.includes('loading board data') && err.message.includes('is not installed')) {
this.logger.warn(`The boards package is not installed for board with FQBN: ${fqbn}`);
if (
err instanceof Error &&
err.message.includes('loading board data') &&
err.message.includes('is not installed')
) {
this.logger.warn(
`The boards package is not installed for board with FQBN: ${fqbn}`
);
} else {
this.logger.error(`An unexpected error occurred while retrieving the board details for ${fqbn}.`, err);
this.logger.error(
`An unexpected error occurred while retrieving the board details for ${fqbn}.`,
err
);
}
return undefined;
}
@@ -178,17 +240,20 @@ export class BoardsDataStore implements FrontendApplicationContribution {
this.onChangedEmitter.fire();
}
protected async getBoardsPackageVersion(fqbn: string | undefined): Promise<Installable.Version | undefined> {
protected async getBoardsPackageVersion(
fqbn: string | undefined
): Promise<Installable.Version | undefined> {
if (!fqbn) {
return undefined;
}
const boardsPackage = await this.boardsService.getContainerBoardPackage({ fqbn });
const boardsPackage = await this.boardsService.getContainerBoardPackage(
{ fqbn }
);
if (!boardsPackage) {
return undefined;
}
return boardsPackage.installedVersion;
}
}
export namespace BoardsDataStore {
@@ -200,12 +265,16 @@ export namespace BoardsDataStore {
export namespace Data {
export const EMPTY: Data = {
configOptions: [],
programmers: []
programmers: [],
};
export function is(arg: any): arg is Data {
return !!arg
&& 'configOptions' in arg && Array.isArray(arg['configOptions'])
&& 'programmers' in arg && Array.isArray(arg['programmers'])
return (
!!arg &&
'configOptions' in arg &&
Array.isArray(arg['configOptions']) &&
'programmers' in arg &&
Array.isArray(arg['programmers'])
);
}
}
}

View File

@@ -1,18 +1,21 @@
import { inject, injectable, postConstruct } from 'inversify';
import { BoardsPackage, BoardsService } from '../../common/protocol/boards-service';
import {
BoardsPackage,
BoardsService,
} from '../../common/protocol/boards-service';
import { ListWidget } from '../widgets/component-list/list-widget';
import { ListItemRenderer } from '../widgets/component-list/list-item-renderer';
@injectable()
export class BoardsListWidget extends ListWidget<BoardsPackage> {
static WIDGET_ID = 'boards-list-widget';
static WIDGET_LABEL = 'Boards Manager';
constructor(
@inject(BoardsService) protected service: BoardsService,
@inject(ListItemRenderer) protected itemRenderer: ListItemRenderer<BoardsPackage>) {
@inject(ListItemRenderer)
protected itemRenderer: ListItemRenderer<BoardsPackage>
) {
super({
id: BoardsListWidget.WIDGET_ID,
label: BoardsListWidget.WIDGET_LABEL,
@@ -20,7 +23,8 @@ export class BoardsListWidget extends ListWidget<BoardsPackage> {
searchable: service,
installable: service,
itemLabel: (item: BoardsPackage) => item.name,
itemRenderer
itemDeprecated: (item: BoardsPackage) => item.deprecated,
itemRenderer,
});
}
@@ -28,9 +32,42 @@ export class BoardsListWidget extends ListWidget<BoardsPackage> {
protected init(): void {
super.init();
this.toDispose.pushAll([
this.notificationCenter.onPlatformInstalled(() => this.refresh(undefined)),
this.notificationCenter.onPlatformUninstalled(() => this.refresh(undefined)),
this.notificationCenter.onPlatformInstalled(() =>
this.refresh(undefined)
),
this.notificationCenter.onPlatformUninstalled(() =>
this.refresh(undefined)
),
]);
}
protected async install({
item,
progressId,
version,
}: {
item: BoardsPackage;
progressId: string;
version: string;
}): Promise<void> {
await super.install({ item, progressId, version });
this.messageService.info(
`Successfully installed platform ${item.name}:${version}`,
{ timeout: 3000 }
);
}
protected async uninstall({
item,
progressId,
}: {
item: BoardsPackage;
progressId: string;
}): Promise<void> {
await super.uninstall({ item, progressId });
this.messageService.info(
`Successfully uninstalled platform ${item.name}:${item.installedVersion}`,
{ timeout: 3000 }
);
}
}

View File

@@ -1,8 +1,8 @@
import { injectable, inject } from 'inversify';
import { Emitter } from '@theia/core/lib/common/event';
import { ILogger } from '@theia/core/lib/common/logger';
import { CommandService } from '@theia/core/lib/common/command';
import { MessageService } from '@theia/core/lib/common/message-service';
import { StorageService } from '@theia/core/lib/browser/storage-service';
import { FrontendApplicationContribution } from '@theia/core/lib/browser/frontend-application';
import { RecursiveRequired } from '../../common/types';
import {
@@ -11,26 +11,22 @@ import {
BoardsService,
BoardsPackage,
AttachedBoardsChangeEvent,
BoardWithPackage
BoardWithPackage,
} from '../../common/protocol';
import { BoardsConfig } from './boards-config';
import { naturalCompare } from '../../common/utils';
import { NotificationCenter } from '../notification-center';
import { CommandService } from '@theia/core';
import { ArduinoCommands } from '../arduino-commands';
import { StorageWrapper } from '../storage-wrapper';
@injectable()
export class BoardsServiceProvider implements FrontendApplicationContribution {
@inject(ILogger)
protected logger: ILogger;
@inject(MessageService)
protected messageService: MessageService;
@inject(StorageService)
protected storageService: StorageService;
@inject(BoardsService)
protected boardsService: BoardsService;
@@ -40,8 +36,11 @@ export class BoardsServiceProvider implements FrontendApplicationContribution {
@inject(NotificationCenter)
protected notificationCenter: NotificationCenter;
protected readonly onBoardsConfigChangedEmitter = new Emitter<BoardsConfig.Config>();
protected readonly onAvailableBoardsChangedEmitter = new Emitter<AvailableBoard[]>();
protected readonly onBoardsConfigChangedEmitter =
new Emitter<BoardsConfig.Config>();
protected readonly onAvailableBoardsChangedEmitter = new Emitter<
AvailableBoard[]
>();
/**
* Used for the auto-reconnecting. Sometimes, the attached board gets disconnected after uploading something to it.
@@ -50,7 +49,9 @@ export class BoardsServiceProvider implements FrontendApplicationContribution {
* We have to listen on such changes and auto-reconnect the same board on another port.
* See: https://arduino.slack.com/archives/CJJHJCJSJ/p1568645417013000?thread_ts=1568640504.009400&cid=CJJHJCJSJ
*/
protected latestValidBoardsConfig: RecursiveRequired<BoardsConfig.Config> | undefined = undefined;
protected latestValidBoardsConfig:
| RecursiveRequired<BoardsConfig.Config>
| undefined = undefined;
protected latestBoardsConfig: BoardsConfig.Config | undefined = undefined;
protected _boardsConfig: BoardsConfig.Config = {};
protected _attachedBoards: Board[] = []; // This does not contain the `Unknown` boards. They're visible from the available ports only.
@@ -65,17 +66,24 @@ export class BoardsServiceProvider implements FrontendApplicationContribution {
* This even also emitted when the board package for the currently selected board was uninstalled.
*/
readonly onBoardsConfigChanged = this.onBoardsConfigChangedEmitter.event;
readonly onAvailableBoardsChanged = this.onAvailableBoardsChangedEmitter.event;
readonly onAvailableBoardsChanged =
this.onAvailableBoardsChangedEmitter.event;
onStart(): void {
this.notificationCenter.onAttachedBoardsChanged(this.notifyAttachedBoardsChanged.bind(this));
this.notificationCenter.onPlatformInstalled(this.notifyPlatformInstalled.bind(this));
this.notificationCenter.onPlatformUninstalled(this.notifyPlatformUninstalled.bind(this));
this.notificationCenter.onAttachedBoardsChanged(
this.notifyAttachedBoardsChanged.bind(this)
);
this.notificationCenter.onPlatformInstalled(
this.notifyPlatformInstalled.bind(this)
);
this.notificationCenter.onPlatformUninstalled(
this.notifyPlatformUninstalled.bind(this)
);
Promise.all([
this.boardsService.getAttachedBoards(),
this.boardsService.getAvailablePorts(),
this.loadState()
this.loadState(),
]).then(([attachedBoards, availablePorts]) => {
this._attachedBoards = attachedBoards;
this._availablePorts = availablePorts;
@@ -83,7 +91,9 @@ export class BoardsServiceProvider implements FrontendApplicationContribution {
});
}
protected notifyAttachedBoardsChanged(event: AttachedBoardsChangeEvent): void {
protected notifyAttachedBoardsChanged(
event: AttachedBoardsChangeEvent
): void {
if (!AttachedBoardsChangeEvent.isEmpty(event)) {
this.logger.info('Attached boards and available ports changed:');
this.logger.info(AttachedBoardsChangeEvent.toString(event));
@@ -99,12 +109,20 @@ export class BoardsServiceProvider implements FrontendApplicationContribution {
const { selectedBoard } = this.boardsConfig;
const { installedVersion, id } = event.item;
if (selectedBoard) {
const installedBoard = event.item.boards.find(({ name }) => name === selectedBoard.name);
if (installedBoard && (!selectedBoard.fqbn || selectedBoard.fqbn === installedBoard.fqbn)) {
this.logger.info(`Board package ${id}[${installedVersion}] was installed. Updating the FQBN of the currently selected ${selectedBoard.name} board. [FQBN: ${installedBoard.fqbn}]`);
const installedBoard = event.item.boards.find(
({ name }) => name === selectedBoard.name
);
if (
installedBoard &&
(!selectedBoard.fqbn ||
selectedBoard.fqbn === installedBoard.fqbn)
) {
this.logger.info(
`Board package ${id}[${installedVersion}] was installed. Updating the FQBN of the currently selected ${selectedBoard.name} board. [FQBN: ${installedBoard.fqbn}]`
);
this.boardsConfig = {
...this.boardsConfig,
selectedBoard: installedBoard
selectedBoard: installedBoard,
};
return;
}
@@ -112,13 +130,26 @@ export class BoardsServiceProvider implements FrontendApplicationContribution {
// This logic handles it "gracefully" by unselecting the board, so that we can avoid no FQBN is set error.
// https://github.com/arduino/arduino-cli/issues/620
// https://github.com/arduino/arduino-pro-ide/issues/374
if (BoardWithPackage.is(selectedBoard) && selectedBoard.packageId === event.item.id && !installedBoard) {
this.messageService.warn(`Could not find previously selected board '${selectedBoard.name}' in installed platform '${event.item.name}'. Please manually reselect the board you want to use. Do you want to reselect it now?`, 'Reselect later', 'Yes').then(async answer => {
if (answer === 'Yes') {
this.commandService.executeCommand(ArduinoCommands.OPEN_BOARDS_DIALOG.id, selectedBoard.name);
}
});
this.boardsConfig = {}
if (
BoardWithPackage.is(selectedBoard) &&
selectedBoard.packageId === event.item.id &&
!installedBoard
) {
this.messageService
.warn(
`Could not find previously selected board '${selectedBoard.name}' in installed platform '${event.item.name}'. Please manually reselect the board you want to use. Do you want to reselect it now?`,
'Reselect later',
'Yes'
)
.then(async (answer) => {
if (answer === 'Yes') {
this.commandService.executeCommand(
ArduinoCommands.OPEN_BOARDS_DIALOG.id,
selectedBoard.name
);
}
});
this.boardsConfig = {};
return;
}
// Trigger a board re-set. See: https://github.com/arduino/arduino-cli/issues/954
@@ -131,8 +162,13 @@ export class BoardsServiceProvider implements FrontendApplicationContribution {
this.logger.info('Boards package uninstalled: ', JSON.stringify(event));
const { selectedBoard } = this.boardsConfig;
if (selectedBoard && selectedBoard.fqbn) {
const uninstalledBoard = event.item.boards.find(({ name }) => name === selectedBoard.name);
if (uninstalledBoard && uninstalledBoard.fqbn === selectedBoard.fqbn) {
const uninstalledBoard = event.item.boards.find(
({ name }) => name === selectedBoard.name
);
if (
uninstalledBoard &&
uninstalledBoard.fqbn === selectedBoard.fqbn
) {
// We should not unset the FQBN, if the selected board is an attached, recognized board.
// Attach Uno and install AVR, select Uno. Uninstall the AVR core while Uno is selected. We do not want to discard the FQBN of the Uno board.
// Dev note: We cannot assume the `selectedBoard` is a type of `AvailableBoard`.
@@ -140,43 +176,68 @@ export class BoardsServiceProvider implements FrontendApplicationContribution {
// it is just a FQBN, so we need to find the `selected` board among the `AvailableBoards`
const selectedAvailableBoard = AvailableBoard.is(selectedBoard)
? selectedBoard
: this._availableBoards.find(availableBoard => Board.sameAs(availableBoard, selectedBoard));
if (selectedAvailableBoard && selectedAvailableBoard.selected && selectedAvailableBoard.state === AvailableBoard.State.recognized) {
: this._availableBoards.find((availableBoard) =>
Board.sameAs(availableBoard, selectedBoard)
);
if (
selectedAvailableBoard &&
selectedAvailableBoard.selected &&
selectedAvailableBoard.state ===
AvailableBoard.State.recognized
) {
return;
}
this.logger.info(`Board package ${event.item.id} was uninstalled. Discarding the FQBN of the currently selected ${selectedBoard.name} board.`);
this.logger.info(
`Board package ${event.item.id} was uninstalled. Discarding the FQBN of the currently selected ${selectedBoard.name} board.`
);
const selectedBoardWithoutFqbn = {
name: selectedBoard.name
name: selectedBoard.name,
// No FQBN
};
this.boardsConfig = {
...this.boardsConfig,
selectedBoard: selectedBoardWithoutFqbn
selectedBoard: selectedBoardWithoutFqbn,
};
}
}
}
protected async tryReconnect(): Promise<boolean> {
if (this.latestValidBoardsConfig && !this.canUploadTo(this.boardsConfig)) {
for (const board of this.availableBoards.filter(({ state }) => state !== AvailableBoard.State.incomplete)) {
if (this.latestValidBoardsConfig.selectedBoard.fqbn === board.fqbn
&& this.latestValidBoardsConfig.selectedBoard.name === board.name
&& Port.sameAs(this.latestValidBoardsConfig.selectedPort, board.port)) {
if (
this.latestValidBoardsConfig &&
!this.canUploadTo(this.boardsConfig)
) {
for (const board of this.availableBoards.filter(
({ state }) => state !== AvailableBoard.State.incomplete
)) {
if (
this.latestValidBoardsConfig.selectedBoard.fqbn ===
board.fqbn &&
this.latestValidBoardsConfig.selectedBoard.name ===
board.name &&
Port.sameAs(
this.latestValidBoardsConfig.selectedPort,
board.port
)
) {
this.boardsConfig = this.latestValidBoardsConfig;
return true;
}
}
// If we could not find an exact match, we compare the board FQBN-name pairs and ignore the port, as it might have changed.
// See documentation on `latestValidBoardsConfig`.
for (const board of this.availableBoards.filter(({ state }) => state !== AvailableBoard.State.incomplete)) {
if (this.latestValidBoardsConfig.selectedBoard.fqbn === board.fqbn
&& this.latestValidBoardsConfig.selectedBoard.name === board.name) {
for (const board of this.availableBoards.filter(
({ state }) => state !== AvailableBoard.State.incomplete
)) {
if (
this.latestValidBoardsConfig.selectedBoard.fqbn ===
board.fqbn &&
this.latestValidBoardsConfig.selectedBoard.name ===
board.name
) {
this.boardsConfig = {
...this.latestValidBoardsConfig,
selectedPort: board.port
selectedPort: board.port,
};
return true;
}
@@ -187,7 +248,15 @@ export class BoardsServiceProvider implements FrontendApplicationContribution {
set boardsConfig(config: BoardsConfig.Config) {
this.doSetBoardsConfig(config);
this.saveState().finally(() => this.reconcileAvailableBoards().finally(() => this.onBoardsConfigChangedEmitter.fire(this._boardsConfig)));
this.saveState().finally(() =>
this.reconcileAvailableBoards().finally(() =>
this.onBoardsConfigChangedEmitter.fire(this._boardsConfig)
)
);
}
get boardsConfig(): BoardsConfig.Config {
return this._boardsConfig;
}
protected doSetBoardsConfig(config: BoardsConfig.Config): void {
@@ -199,29 +268,33 @@ export class BoardsServiceProvider implements FrontendApplicationContribution {
}
}
async searchBoards({ query, cores }: { query?: string, cores?: string[] }): Promise<BoardWithPackage[]> {
async searchBoards({
query,
cores,
}: {
query?: string;
cores?: string[];
}): Promise<BoardWithPackage[]> {
const boards = await this.boardsService.searchBoards({ query });
return boards;
}
get boardsConfig(): BoardsConfig.Config {
return this._boardsConfig;
}
/**
* `true` if the `config.selectedBoard` is defined; hence can compile against the board. Otherwise, `false`.
*/
canVerify(
config: BoardsConfig.Config | undefined = this.boardsConfig,
options: { silent: boolean } = { silent: true }): config is BoardsConfig.Config & { selectedBoard: Board } {
options: { silent: boolean } = { silent: true }
): config is BoardsConfig.Config & { selectedBoard: Board } {
if (!config) {
return false;
}
if (!config.selectedBoard) {
if (!options.silent) {
this.messageService.warn('No boards selected.', { timeout: 3000 });
this.messageService.warn('No boards selected.', {
timeout: 3000,
});
}
return false;
}
@@ -234,8 +307,8 @@ export class BoardsServiceProvider implements FrontendApplicationContribution {
*/
canUploadTo(
config: BoardsConfig.Config | undefined = this.boardsConfig,
options: { silent: boolean } = { silent: true }): config is RecursiveRequired<BoardsConfig.Config> {
options: { silent: boolean } = { silent: true }
): config is RecursiveRequired<BoardsConfig.Config> {
if (!this.canVerify(config, options)) {
return false;
}
@@ -243,14 +316,20 @@ export class BoardsServiceProvider implements FrontendApplicationContribution {
const { name } = config.selectedBoard;
if (!config.selectedPort) {
if (!options.silent) {
this.messageService.warn(`No ports selected for board: '${name}'.`, { timeout: 3000 });
this.messageService.warn(
`No ports selected for board: '${name}'.`,
{ timeout: 3000 }
);
}
return false;
}
if (!config.selectedBoard.fqbn) {
if (!options.silent) {
this.messageService.warn(`The FQBN is not available for the selected board ${name}. Do you have the corresponding core installed?`, { timeout: 3000 });
this.messageService.warn(
`The FQBN is not available for the selected board ${name}. Do you have the corresponding core installed?`,
{ timeout: 3000 }
);
}
return false;
}
@@ -262,25 +341,46 @@ export class BoardsServiceProvider implements FrontendApplicationContribution {
return this._availableBoards;
}
async waitUntilAvailable(what: Board & { port: Port }, timeout?: number): Promise<void> {
const find = (needle: Board & { port: Port }, haystack: AvailableBoard[]) =>
haystack.find(board => Board.equals(needle, board) && Port.equals(needle.port, board.port));
const timeoutTask = !!timeout && timeout > 0
? new Promise<void>((_, reject) => setTimeout(() => reject(new Error(`Timeout after ${timeout} ms.`)), timeout))
: new Promise<void>(() => { /* never */ });
const waitUntilTask = new Promise<void>(resolve => {
async waitUntilAvailable(
what: Board & { port: Port },
timeout?: number
): Promise<void> {
const find = (
needle: Board & { port: Port },
haystack: AvailableBoard[]
) =>
haystack.find(
(board) =>
Board.equals(needle, board) &&
Port.equals(needle.port, board.port)
);
const timeoutTask =
!!timeout && timeout > 0
? new Promise<void>((_, reject) =>
setTimeout(
() =>
reject(new Error(`Timeout after ${timeout} ms.`)),
timeout
)
)
: new Promise<void>(() => {
/* never */
});
const waitUntilTask = new Promise<void>((resolve) => {
let candidate = find(what, this.availableBoards);
if (candidate) {
resolve();
return;
}
const disposable = this.onAvailableBoardsChanged(availableBoards => {
candidate = find(what, availableBoards);
if (candidate) {
disposable.dispose();
resolve();
const disposable = this.onAvailableBoardsChanged(
(availableBoards) => {
candidate = find(what, availableBoards);
if (candidate) {
disposable.dispose();
resolve();
}
}
});
);
});
return await Promise.race([waitUntilTask, timeoutTask]);
}
@@ -289,54 +389,90 @@ export class BoardsServiceProvider implements FrontendApplicationContribution {
const attachedBoards = this._attachedBoards;
const availablePorts = this._availablePorts;
// Unset the port on the user's config, if it is not available anymore.
if (this.boardsConfig.selectedPort && !availablePorts.some(port => Port.sameAs(port, this.boardsConfig.selectedPort))) {
this.doSetBoardsConfig({ selectedBoard: this.boardsConfig.selectedBoard, selectedPort: undefined });
if (
this.boardsConfig.selectedPort &&
!availablePorts.some((port) =>
Port.sameAs(port, this.boardsConfig.selectedPort)
)
) {
this.doSetBoardsConfig({
selectedBoard: this.boardsConfig.selectedBoard,
selectedPort: undefined,
});
this.onBoardsConfigChangedEmitter.fire(this._boardsConfig);
}
const boardsConfig = this.boardsConfig;
const currentAvailableBoards = this._availableBoards;
const availableBoards: AvailableBoard[] = [];
const availableBoardPorts = availablePorts.filter(Port.isBoardPort);
const attachedSerialBoards = attachedBoards.filter(({ port }) => !!port);
const attachedSerialBoards = attachedBoards.filter(
({ port }) => !!port
);
for (const boardPort of availableBoardPorts) {
let state = AvailableBoard.State.incomplete; // Initial pessimism.
let board = attachedSerialBoards.find(({ port }) => Port.sameAs(boardPort, port));
let board = attachedSerialBoards.find(({ port }) =>
Port.sameAs(boardPort, port)
);
if (board) {
state = AvailableBoard.State.recognized;
} else {
// If the selected board is not recognized because it is a 3rd party board: https://github.com/arduino/arduino-cli/issues/623
// We still want to show it without the red X in the boards toolbar: https://github.com/arduino/arduino-pro-ide/issues/198#issuecomment-599355836
const lastSelectedBoard = await this.getLastSelectedBoardOnPort(boardPort);
const lastSelectedBoard = await this.getLastSelectedBoardOnPort(
boardPort
);
if (lastSelectedBoard) {
board = {
...lastSelectedBoard,
port: boardPort
port: boardPort,
};
state = AvailableBoard.State.guessed;
}
}
if (!board) {
availableBoards.push({ name: 'Unknown', port: boardPort, state });
availableBoards.push({
name: 'Unknown',
port: boardPort,
state,
});
} else {
const selected = BoardsConfig.Config.sameAs(boardsConfig, board);
availableBoards.push({ ...board, state, selected, port: boardPort });
const selected = BoardsConfig.Config.sameAs(
boardsConfig,
board
);
availableBoards.push({
...board,
state,
selected,
port: boardPort,
});
}
}
if (boardsConfig.selectedBoard && !availableBoards.some(({ selected }) => selected)) {
if (
boardsConfig.selectedBoard &&
!availableBoards.some(({ selected }) => selected)
) {
availableBoards.push({
...boardsConfig.selectedBoard,
port: boardsConfig.selectedPort,
selected: true,
state: AvailableBoard.State.incomplete
state: AvailableBoard.State.incomplete,
});
}
const sortedAvailableBoards = availableBoards.sort(AvailableBoard.compare);
let hasChanged = sortedAvailableBoards.length !== currentAvailableBoards.length;
const sortedAvailableBoards = availableBoards.sort(
AvailableBoard.compare
);
let hasChanged =
sortedAvailableBoards.length !== currentAvailableBoards.length;
for (let i = 0; !hasChanged && i < sortedAvailableBoards.length; i++) {
hasChanged = AvailableBoard.compare(sortedAvailableBoards[i], currentAvailableBoards[i]) !== 0;
hasChanged =
AvailableBoard.compare(
sortedAvailableBoards[i],
currentAvailableBoards[i]
) !== 0;
}
if (hasChanged) {
this._availableBoards = sortedAvailableBoards;
@@ -344,12 +480,14 @@ export class BoardsServiceProvider implements FrontendApplicationContribution {
}
}
protected async getLastSelectedBoardOnPort(port: Port | string | undefined): Promise<Board | undefined> {
protected async getLastSelectedBoardOnPort(
port: Port | string | undefined
): Promise<Board | undefined> {
if (!port) {
return undefined;
}
const key = this.getLastSelectedBoardOnPortKey(port);
return this.storageService.getData<Board>(key);
return this.getData<Board>(key);
}
protected async saveState(): Promise<void> {
@@ -360,21 +498,28 @@ export class BoardsServiceProvider implements FrontendApplicationContribution {
const { selectedBoard, selectedPort } = this.boardsConfig;
if (selectedBoard && selectedPort) {
const key = this.getLastSelectedBoardOnPortKey(selectedPort);
await this.storageService.setData(key, selectedBoard);
await this.setData(key, selectedBoard);
}
await Promise.all([
this.storageService.setData('latest-valid-boards-config', this.latestValidBoardsConfig),
this.storageService.setData('latest-boards-config', this.latestBoardsConfig)
this.setData(
'latest-valid-boards-config',
this.latestValidBoardsConfig
),
this.setData('latest-boards-config', this.latestBoardsConfig),
]);
}
protected getLastSelectedBoardOnPortKey(port: Port | string): string {
// TODO: we lose the port's `protocol` info (`serial`, `network`, etc.) here if the `port` is a `string`.
return `last-selected-board-on-port:${typeof port === 'string' ? port : Port.toString(port)}`;
return `last-selected-board-on-port:${
typeof port === 'string' ? port : Port.toString(port)
}`;
}
protected async loadState(): Promise<void> {
const storedLatestValidBoardsConfig = await this.storageService.getData<RecursiveRequired<BoardsConfig.Config>>('latest-valid-boards-config');
const storedLatestValidBoardsConfig = await this.getData<
RecursiveRequired<BoardsConfig.Config>
>('latest-valid-boards-config');
if (storedLatestValidBoardsConfig) {
this.latestValidBoardsConfig = storedLatestValidBoardsConfig;
if (this.canUploadTo(this.latestValidBoardsConfig)) {
@@ -382,13 +527,36 @@ export class BoardsServiceProvider implements FrontendApplicationContribution {
}
} else {
// If we could not restore the latest valid config, try to restore something, the board at least.
const storedLatestBoardsConfig = await this.storageService.getData<BoardsConfig.Config | undefined>('latest-boards-config');
let storedLatestBoardsConfig = await this.getData<
BoardsConfig.Config | undefined
>('latest-boards-config');
// Try to get from the URL if it was not persisted.
if (!storedLatestBoardsConfig) {
storedLatestBoardsConfig = BoardsConfig.Config.getConfig(
new URL(window.location.href)
);
}
if (storedLatestBoardsConfig) {
this.latestBoardsConfig = storedLatestBoardsConfig;
this.boardsConfig = this.latestBoardsConfig;
}
}
}
private setData<T>(key: string, value: T): Promise<void> {
return this.commandService.executeCommand(
StorageWrapper.Commands.SET_DATA.id,
key,
value
);
}
private getData<T>(key: string): Promise<T | undefined> {
return this.commandService.executeCommand<T>(
StorageWrapper.Commands.GET_DATA.id,
key
);
}
}
/**
@@ -404,7 +572,6 @@ export interface AvailableBoard extends Board {
}
export namespace AvailableBoard {
export enum State {
/**
* Retrieved from the CLI via the `board list` command.
@@ -417,14 +584,16 @@ export namespace AvailableBoard {
/**
* We do not know anything about this board, probably a 3rd party. The user has not selected a board for this port yet.
*/
'incomplete'
'incomplete',
}
export function is(board: any): board is AvailableBoard {
return Board.is(board) && 'state' in board;
}
export function hasPort(board: AvailableBoard): board is AvailableBoard & { port: Port } {
export function hasPort(
board: AvailableBoard
): board is AvailableBoard & { port: Port } {
return !!board.port;
}
@@ -458,6 +627,5 @@ export namespace AvailableBoard {
return 1;
}
return left.state - right.state;
}
};
}

View File

@@ -5,7 +5,10 @@ import { DisposableCollection } from '@theia/core/lib/common/disposable';
import { Port } from '../../common/protocol';
import { BoardsConfig } from './boards-config';
import { ArduinoCommands } from '../arduino-commands';
import { BoardsServiceProvider, AvailableBoard } from './boards-service-provider';
import {
BoardsServiceProvider,
AvailableBoard,
} from './boards-service-provider';
export interface BoardsDropDownListCoords {
readonly top: number;
@@ -17,13 +20,14 @@ export interface BoardsDropDownListCoords {
export namespace BoardsDropDown {
export interface Props {
readonly coords: BoardsDropDownListCoords | 'hidden';
readonly items: Array<AvailableBoard & { onClick: () => void, port: Port }>;
readonly items: Array<
AvailableBoard & { onClick: () => void; port: Port }
>;
readonly openBoardsConfig: () => void;
}
}
export class BoardsDropDown extends React.Component<BoardsDropDown.Props> {
protected dropdownElement: HTMLElement;
constructor(props: BoardsDropDown.Props) {
@@ -47,35 +51,61 @@ export class BoardsDropDown extends React.Component<BoardsDropDown.Props> {
if (coords === 'hidden') {
return '';
}
return <div className='arduino-boards-dropdown-list'
style={{
position: 'absolute',
...coords
}}>
{this.renderItem({
label: 'Select Other Board & Port',
onClick: () => this.props.openBoardsConfig()
})}
{items.map(({ name, port, selected, onClick }) => ({ label: `${name} at ${Port.toString(port)}`, selected, onClick })).map(this.renderItem)}
</div>
}
protected renderItem({ label, selected, onClick }: { label: string, selected?: boolean, onClick: () => void }): React.ReactNode {
return <div key={label} className={`arduino-boards-dropdown-item ${selected ? 'selected' : ''}`} onClick={onClick}>
<div>
{label}
return (
<div
className="arduino-boards-dropdown-list"
style={{
position: 'absolute',
...coords,
}}
>
{this.renderItem({
label: 'Select Other Board & Port',
onClick: () => this.props.openBoardsConfig(),
})}
{items
.map(({ name, port, selected, onClick }) => ({
label: `${name} at ${Port.toString(port)}`,
selected,
onClick,
}))
.map(this.renderItem)}
</div>
{selected ? <span className='fa fa-check' /> : ''}
</div>
);
}
protected renderItem({
label,
selected,
onClick,
}: {
label: string;
selected?: boolean;
onClick: () => void;
}): React.ReactNode {
return (
<div
key={label}
className={`arduino-boards-dropdown-item ${
selected ? 'selected' : ''
}`}
onClick={onClick}
>
<div>{label}</div>
{selected ? <span className="fa fa-check" /> : ''}
</div>
);
}
}
export class BoardsToolBarItem extends React.Component<BoardsToolBarItem.Props, BoardsToolBarItem.State> {
export class BoardsToolBarItem extends React.Component<
BoardsToolBarItem.Props,
BoardsToolBarItem.State
> {
static TOOLBAR_ID: 'boards-toolbar';
protected readonly toDispose: DisposableCollection = new DisposableCollection();
protected readonly toDispose: DisposableCollection =
new DisposableCollection();
constructor(props: BoardsToolBarItem.Props) {
super(props);
@@ -83,7 +113,7 @@ export class BoardsToolBarItem extends React.Component<BoardsToolBarItem.Props,
const { availableBoards } = props.boardsServiceClient;
this.state = {
availableBoards,
coords: 'hidden'
coords: 'hidden',
};
document.addEventListener('click', () => {
@@ -92,7 +122,9 @@ export class BoardsToolBarItem extends React.Component<BoardsToolBarItem.Props,
}
componentDidMount() {
this.props.boardsServiceClient.onAvailableBoardsChanged(availableBoards => this.setState({ availableBoards }));
this.props.boardsServiceClient.onAvailableBoardsChanged(
(availableBoards) => this.setState({ availableBoards })
);
}
componentWillUnmount(): void {
@@ -109,8 +141,8 @@ export class BoardsToolBarItem extends React.Component<BoardsToolBarItem.Props,
top: rect.top,
left: rect.left,
width: rect.width,
paddingTop: rect.height
}
paddingTop: rect.height,
},
});
} else {
this.setState({ coords: 'hidden' });
@@ -123,63 +155,76 @@ export class BoardsToolBarItem extends React.Component<BoardsToolBarItem.Props,
render(): React.ReactNode {
const { coords, availableBoards } = this.state;
const boardsConfig = this.props.boardsServiceClient.boardsConfig;
const title = BoardsConfig.Config.toString(boardsConfig, { default: 'no board selected' });
const title = BoardsConfig.Config.toString(boardsConfig, {
default: 'no board selected',
});
const decorator = (() => {
const selectedBoard = availableBoards.find(({ selected }) => selected);
const selectedBoard = availableBoards.find(
({ selected }) => selected
);
if (!selectedBoard || !selectedBoard.port) {
return 'fa fa-times notAttached'
return 'fa fa-times notAttached';
}
if (selectedBoard.state === AvailableBoard.State.guessed) {
return 'fa fa-exclamation-triangle guessed'
return 'fa fa-exclamation-triangle guessed';
}
return ''
return '';
})();
return <React.Fragment>
<div className='arduino-boards-toolbar-item-container'>
<div className='arduino-boards-toolbar-item' title={title}>
<div className='inner-container' onClick={this.show}>
<span className={decorator} />
<div className='label noWrapInfo'>
<div className='noWrapInfo noselect'>
{title}
return (
<React.Fragment>
<div className="arduino-boards-toolbar-item-container">
<div className="arduino-boards-toolbar-item" title={title}>
<div className="inner-container" onClick={this.show}>
<span className={decorator} />
<div className="label noWrapInfo">
<div className="noWrapInfo noselect">
{title}
</div>
</div>
<span className="fa fa-caret-down caret" />
</div>
<span className='fa fa-caret-down caret' />
</div>
</div>
</div>
<BoardsDropDown
coords={coords}
items={availableBoards.filter(AvailableBoard.hasPort).map(board => ({
...board,
onClick: () => {
if (board.state === AvailableBoard.State.incomplete) {
this.props.boardsServiceClient.boardsConfig = {
selectedPort: board.port
};
this.openDialog();
} else {
this.props.boardsServiceClient.boardsConfig = {
selectedBoard: board,
selectedPort: board.port
}
}
}
}))}
openBoardsConfig={this.openDialog}>
</BoardsDropDown>
</React.Fragment>;
<BoardsDropDown
coords={coords}
items={availableBoards
.filter(AvailableBoard.hasPort)
.map((board) => ({
...board,
onClick: () => {
if (
board.state ===
AvailableBoard.State.incomplete
) {
this.props.boardsServiceClient.boardsConfig =
{
selectedPort: board.port,
};
this.openDialog();
} else {
this.props.boardsServiceClient.boardsConfig =
{
selectedBoard: board,
selectedPort: board.port,
};
}
},
}))}
openBoardsConfig={this.openDialog}
></BoardsDropDown>
</React.Fragment>
);
}
protected openDialog = () => {
this.props.commands.executeCommand(ArduinoCommands.OPEN_BOARDS_DIALOG.id);
this.props.commands.executeCommand(
ArduinoCommands.OPEN_BOARDS_DIALOG.id
);
this.setState({ coords: 'hidden' });
};
}
export namespace BoardsToolBarItem {
export interface Props {
readonly boardsServiceClient: BoardsServiceProvider;
readonly commands: CommandRegistry;
@@ -189,5 +234,4 @@ export namespace BoardsToolBarItem {
availableBoards: AvailableBoard[];
coords: BoardsDropDownListCoords | 'hidden';
}
}

View File

@@ -5,22 +5,20 @@ import { ListWidgetFrontendContribution } from '../widgets/component-list/list-w
@injectable()
export class BoardsListWidgetFrontendContribution extends ListWidgetFrontendContribution<BoardsPackage> {
constructor() {
super({
widgetId: BoardsListWidget.WIDGET_ID,
widgetName: BoardsListWidget.WIDGET_LABEL,
defaultWidgetOptions: {
area: 'left',
rank: 2
rank: 2,
},
toggleCommandId: `${BoardsListWidget.WIDGET_ID}:toggle`,
toggleKeybinding: 'CtrlCmd+Shift+B'
toggleKeybinding: 'CtrlCmd+Shift+B',
});
}
async initializeLayout(): Promise<void> {
this.openView();
}
}

View File

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

View File

@@ -1,18 +1,23 @@
import { inject, injectable } from 'inversify';
import { remote } from 'electron';
import { ArduinoMenus } from '../menu/arduino-menus';
import { SketchContribution, Command, CommandRegistry, MenuModelRegistry, URI } from './contribution';
import {
SketchContribution,
Command,
CommandRegistry,
MenuModelRegistry,
URI,
} from './contribution';
import { FileDialogService } from '@theia/filesystem/lib/browser';
@injectable()
export class AddFile extends SketchContribution {
@inject(FileDialogService)
protected readonly fileDialogService: FileDialogService;
registerCommands(registry: CommandRegistry): void {
registry.registerCommand(AddFile.Commands.ADD_FILE, {
execute: () => this.addFile()
execute: () => this.addFile(),
});
}
@@ -20,7 +25,7 @@ export class AddFile extends SketchContribution {
registry.registerMenuAction(ArduinoMenus.SKETCH__UTILS_GROUP, {
commandId: AddFile.Commands.ADD_FILE.id,
label: 'Add File...',
order: '2'
order: '2',
});
}
@@ -33,7 +38,7 @@ export class AddFile extends SketchContribution {
title: 'Add File',
canSelectFiles: true,
canSelectFolders: false,
canSelectMany: false
canSelectMany: false,
});
if (!toAddUri) {
return;
@@ -47,22 +52,24 @@ export class AddFile extends SketchContribution {
type: 'question',
title: 'Replace',
buttons: ['Cancel', 'OK'],
message: `Replace the existing version of ${filename}?`
message: `Replace the existing version of ${filename}?`,
});
if (response === 0) { // Cancel
if (response === 0) {
// Cancel
return;
}
}
await this.fileService.copy(toAddUri, targetUri, { overwrite: true });
this.messageService.info('One file added to the sketch.', { timeout: 2000 });
this.messageService.info('One file added to the sketch.', {
timeout: 2000,
});
}
}
export namespace AddFile {
export namespace Commands {
export const ADD_FILE: Command = {
id: 'arduino-add-file'
id: 'arduino-add-file',
};
}
}

View File

@@ -1,36 +1,48 @@
import { inject, injectable } from 'inversify';
import { remote } from 'electron';
import { ArduinoMenus } from '../menu/arduino-menus';
import { SketchContribution, Command, CommandRegistry, MenuModelRegistry } from './contribution';
import { EnvVariablesServer } from '@theia/core/lib/common/env-variables';
import URI from '@theia/core/lib/common/uri';
import { InstallationProgressDialog } from '../widgets/progress-dialog';
import { LibraryService } from '../../common/protocol';
import { ConfirmDialog } from '@theia/core/lib/browser';
import { ConfirmDialog } from '@theia/core/lib/browser/dialogs';
import { EnvVariablesServer } from '@theia/core/lib/common/env-variables';
import { ArduinoMenus } from '../menu/arduino-menus';
import { ResponseServiceImpl } from '../response-service-impl';
import { Installable, LibraryService } from '../../common/protocol';
import {
SketchContribution,
Command,
CommandRegistry,
MenuModelRegistry,
} from './contribution';
@injectable()
export class AddZipLibrary extends SketchContribution {
@inject(EnvVariablesServer)
protected readonly envVariableServer: EnvVariablesServer;
@inject(ResponseServiceImpl)
protected readonly responseService: ResponseServiceImpl;
@inject(LibraryService)
protected readonly libraryService: LibraryService;
registerCommands(registry: CommandRegistry): void {
registry.registerCommand(AddZipLibrary.Commands.ADD_ZIP_LIBRARY, {
execute: () => this.addZipLibrary()
execute: () => this.addZipLibrary(),
});
}
registerMenus(registry: MenuModelRegistry): void {
const includeLibMenuPath = [...ArduinoMenus.SKETCH__UTILS_GROUP, '0_include'];
const includeLibMenuPath = [
...ArduinoMenus.SKETCH__UTILS_GROUP,
'0_include',
];
// TODO: do we need it? calling `registerSubmenu` multiple times is noop, so it does not hurt.
registry.registerSubmenu(includeLibMenuPath, 'Include Library', { order: '1' });
registry.registerSubmenu(includeLibMenuPath, 'Include Library', {
order: '1',
});
registry.registerMenuAction([...includeLibMenuPath, '1_install'], {
commandId: AddZipLibrary.Commands.ADD_ZIP_LIBRARY.id,
label: 'Add .ZIP Library...',
order: '1'
order: '1',
});
}
@@ -44,9 +56,9 @@ export class AddZipLibrary extends SketchContribution {
filters: [
{
name: 'Library',
extensions: ['zip']
}
]
extensions: ['zip'],
},
],
});
if (!canceled && filePaths.length) {
const zipUri = await this.fileSystemExt.getUri(filePaths[0]);
@@ -58,7 +70,7 @@ export class AddZipLibrary extends SketchContribution {
msg: error.message,
title: 'Do you want to overwrite the existing library?',
ok: 'Yes',
cancel: 'No'
cancel: 'No',
}).open();
if (result) {
await this.doInstall(zipUri, true);
@@ -68,46 +80,60 @@ export class AddZipLibrary extends SketchContribution {
}
}
private async doInstall(zipUri: string, overwrite?: boolean): Promise<void> {
const dialog = new InstallationProgressDialog('Installing library', 'zip');
private async doInstall(
zipUri: string,
overwrite?: boolean
): Promise<void> {
try {
this.outputChannelManager.getChannel('Arduino').clear();
dialog.open();
await this.libraryService.installZip({ zipUri, overwrite });
await Installable.doWithProgress({
messageService: this.messageService,
progressText: `Processing ${new URI(zipUri).path.base}`,
responseService: this.responseService,
run: () =>
this.libraryService.installZip({ zipUri, overwrite }),
});
this.messageService.info(
`Successfully installed library from ${
new URI(zipUri).path.base
} archive`,
{ timeout: 3000 }
);
} catch (error) {
if (error instanceof Error) {
const match = error.message.match(/library (.*?) already installed/);
const match = error.message.match(
/library (.*?) already installed/
);
if (match && match.length >= 2) {
const name = match[1].trim();
if (name) {
throw new AlreadyInstalledError(`A library folder named ${name} already exists. Do you want to overwrite it?`, name);
throw new AlreadyInstalledError(
`A library folder named ${name} already exists. Do you want to overwrite it?`,
name
);
} else {
throw new AlreadyInstalledError('A library already exists. Do you want to overwrite it?');
throw new AlreadyInstalledError(
'A library already exists. Do you want to overwrite it?'
);
}
}
}
this.messageService.error(error.toString());
throw error;
} finally {
dialog.close();
}
}
}
class AlreadyInstalledError extends Error {
constructor(message: string, readonly libraryName?: string) {
super(message);
Object.setPrototypeOf(this, AlreadyInstalledError.prototype);
}
}
export namespace AddZipLibrary {
export namespace Commands {
export const ADD_ZIP_LIBRARY: Command = {
id: 'arduino-add-zip-library'
id: 'arduino-add-zip-library',
};
}
}

View File

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

View File

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

View File

@@ -5,11 +5,15 @@ import { ArduinoMenus } from '../menu/arduino-menus';
import { BoardsDataStore } from '../boards/boards-data-store';
import { MonitorConnection } from '../monitor/monitor-connection';
import { BoardsServiceProvider } from '../boards/boards-service-provider';
import { SketchContribution, Command, CommandRegistry, MenuModelRegistry } from './contribution';
import {
SketchContribution,
Command,
CommandRegistry,
MenuModelRegistry,
} from './contribution';
@injectable()
export class BurnBootloader extends SketchContribution {
@inject(CoreService)
protected readonly coreService: CoreService;
@@ -27,7 +31,7 @@ export class BurnBootloader extends SketchContribution {
registerCommands(registry: CommandRegistry): void {
registry.registerCommand(BurnBootloader.Commands.BURN_BOOTLOADER, {
execute: () => this.burnBootloader()
execute: () => this.burnBootloader(),
});
}
@@ -35,7 +39,7 @@ export class BurnBootloader extends SketchContribution {
registry.registerMenuAction(ArduinoMenus.TOOLS__BOARD_SETTINGS_GROUP, {
commandId: BurnBootloader.Commands.BURN_BOOTLOADER.id,
label: 'Burn Bootloader',
order: 'z99'
order: 'z99',
});
}
@@ -47,21 +51,28 @@ export class BurnBootloader extends SketchContribution {
try {
const { boardsConfig } = this.boardsServiceClientImpl;
const port = boardsConfig.selectedPort?.address;
const [fqbn, { selectedProgrammer: programmer }, verify, verbose] = await Promise.all([
this.boardsDataStore.appendConfigToFqbn(boardsConfig.selectedBoard?.fqbn),
this.boardsDataStore.getData(boardsConfig.selectedBoard?.fqbn),
this.preferences.get('arduino.upload.verify'),
this.preferences.get('arduino.upload.verbose')
]);
const [fqbn, { selectedProgrammer: programmer }, verify, verbose] =
await Promise.all([
this.boardsDataStore.appendConfigToFqbn(
boardsConfig.selectedBoard?.fqbn
),
this.boardsDataStore.getData(
boardsConfig.selectedBoard?.fqbn
),
this.preferences.get('arduino.upload.verify'),
this.preferences.get('arduino.upload.verbose'),
]);
this.outputChannelManager.getChannel('Arduino').clear();
await this.coreService.burnBootloader({
fqbn,
programmer,
port,
verify,
verbose
verbose,
});
this.messageService.info('Done burning bootloader.', {
timeout: 3000,
});
this.messageService.info('Done burning bootloader.', { timeout: 1000 });
} catch (e) {
this.messageService.error(e.toString());
} finally {
@@ -70,13 +81,12 @@ export class BurnBootloader extends SketchContribution {
}
}
}
}
export namespace BurnBootloader {
export namespace Commands {
export const BURN_BOOTLOADER: Command = {
id: 'arduino-burn-bootloader'
id: 'arduino-burn-bootloader',
};
}
}

View File

@@ -7,14 +7,20 @@ import { ApplicationShell } from '@theia/core/lib/browser/shell/application-shel
import { FrontendApplication } from '@theia/core/lib/browser/frontend-application';
import { ArduinoMenus } from '../menu/arduino-menus';
import { SaveAsSketch } from './save-as-sketch';
import { SketchContribution, Command, CommandRegistry, MenuModelRegistry, KeybindingRegistry, URI } from './contribution';
import {
SketchContribution,
Command,
CommandRegistry,
MenuModelRegistry,
KeybindingRegistry,
URI,
} from './contribution';
/**
* Closes the `current` closeable editor, or any closeable current widget from the main area, or the current sketch window.
*/
@injectable()
export class Close extends SketchContribution {
@inject(EditorManager)
protected readonly editorManager: EditorManager;
@@ -27,7 +33,6 @@ export class Close extends SketchContribution {
registerCommands(registry: CommandRegistry): void {
registry.registerCommand(Close.Commands.CLOSE, {
execute: async () => {
// Close current editor if closeable.
const { currentEditor } = this.editorManager;
if (currentEditor && currentEditor.title.closable) {
@@ -38,8 +43,13 @@ export class Close extends SketchContribution {
// 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) {
const currentWidgetInMain = toArray(
this.shell.mainPanel.widgets()
).find((widget) => widget === currentWidget);
if (
currentWidgetInMain &&
currentWidgetInMain.title.closable
) {
return currentWidgetInMain.close();
}
}
@@ -54,25 +64,32 @@ export class Close extends SketchContribution {
if (!uri) {
return;
}
if (isTemp && await this.wasTouched(uri)) {
if (isTemp && (await this.wasTouched(uri))) {
const { response } = await remote.dialog.showMessageBox({
type: 'question',
buttons: ["Don't Save", 'Cancel', 'Save'],
message: 'Do you want to save changes to this sketch before closing?',
detail: "If you don't save, your changes will be lost."
message:
'Do you want to save changes to this sketch before closing?',
detail: "If you don't save, your changes will be lost.",
});
if (response === 1) { // Cancel
if (response === 1) {
// Cancel
return;
}
if (response === 2) { // Save
const saved = await this.commandService.executeCommand(SaveAsSketch.Commands.SAVE_AS_SKETCH.id, { openAfterMove: false, execOnlyIfTemp: true });
if (!saved) { // If it was not saved, do bail the close.
if (response === 2) {
// Save
const saved = await this.commandService.executeCommand(
SaveAsSketch.Commands.SAVE_AS_SKETCH.id,
{ openAfterMove: false, execOnlyIfTemp: true }
);
if (!saved) {
// If it was not saved, do bail the close.
return;
}
}
}
window.close();
}
},
});
}
@@ -80,14 +97,14 @@ export class Close extends SketchContribution {
registry.registerMenuAction(ArduinoMenus.FILE__SKETCH_GROUP, {
commandId: Close.Commands.CLOSE.id,
label: 'Close',
order: '5'
order: '5',
});
}
registerKeybindings(registry: KeybindingRegistry): void {
registry.registerKeybinding({
command: Close.Commands.CLOSE.id,
keybinding: 'CtrlCmd+W'
keybinding: 'CtrlCmd+W',
});
}
@@ -99,7 +116,10 @@ export class Close extends SketchContribution {
if (editorWidget) {
const { editor } = editorWidget;
if (editor instanceof MonacoEditor) {
const versionId = editor.getControl().getModel()?.getVersionId();
const versionId = editor
.getControl()
.getModel()
?.getVersionId();
if (Number.isInteger(versionId) && versionId! > 1) {
return true;
}
@@ -107,13 +127,12 @@ export class Close extends SketchContribution {
}
return false;
}
}
export namespace Close {
export namespace Commands {
export const CLOSE: Command = {
id: 'arduino-close'
id: 'arduino-close',
};
}
}

View File

@@ -10,22 +10,59 @@ import { MessageService } from '@theia/core/lib/common/message-service';
import { WorkspaceService } from '@theia/workspace/lib/browser/workspace-service';
import { open, OpenerService } from '@theia/core/lib/browser/opener-service';
import { OutputChannelManager } from '@theia/output/lib/common/output-channel';
import { MenuModelRegistry, MenuContribution } from '@theia/core/lib/common/menu';
import { KeybindingRegistry, KeybindingContribution } from '@theia/core/lib/browser/keybinding';
import { TabBarToolbarContribution, TabBarToolbarRegistry } from '@theia/core/lib/browser/shell/tab-bar-toolbar';
import { FrontendApplicationContribution, FrontendApplication } from '@theia/core/lib/browser/frontend-application';
import { Command, CommandRegistry, CommandContribution, CommandService } from '@theia/core/lib/common/command';
import {
MenuModelRegistry,
MenuContribution,
} from '@theia/core/lib/common/menu';
import {
KeybindingRegistry,
KeybindingContribution,
} from '@theia/core/lib/browser/keybinding';
import {
TabBarToolbarContribution,
TabBarToolbarRegistry,
} from '@theia/core/lib/browser/shell/tab-bar-toolbar';
import {
FrontendApplicationContribution,
FrontendApplication,
} from '@theia/core/lib/browser/frontend-application';
import {
Command,
CommandRegistry,
CommandContribution,
CommandService,
} from '@theia/core/lib/common/command';
import { EditorMode } from '../editor-mode';
import { SettingsService } from '../settings';
import { SketchesServiceClientImpl } from '../../common/protocol/sketches-service-client-impl';
import { SketchesService, ConfigService, FileSystemExt, Sketch } from '../../common/protocol';
import {
SketchesService,
ConfigService,
FileSystemExt,
Sketch,
} from '../../common/protocol';
import { ArduinoPreferences } from '../arduino-preferences';
export { Command, CommandRegistry, MenuModelRegistry, KeybindingRegistry, TabBarToolbarRegistry, URI, Sketch, open };
export {
Command,
CommandRegistry,
MenuModelRegistry,
KeybindingRegistry,
TabBarToolbarRegistry,
URI,
Sketch,
open,
};
@injectable()
export abstract class Contribution implements CommandContribution, MenuContribution, KeybindingContribution, TabBarToolbarContribution, FrontendApplicationContribution {
export abstract class Contribution
implements
CommandContribution,
MenuContribution,
KeybindingContribution,
TabBarToolbarContribution,
FrontendApplicationContribution
{
@inject(ILogger)
protected readonly logger: ILogger;
@@ -47,26 +84,19 @@ export abstract class Contribution implements CommandContribution, MenuContribut
@inject(SettingsService)
protected readonly settingsService: SettingsService;
onStart(app: FrontendApplication): MaybePromise<void> {
}
onStart(app: FrontendApplication): MaybePromise<void> {}
registerCommands(registry: CommandRegistry): void {
}
registerCommands(registry: CommandRegistry): void {}
registerMenus(registry: MenuModelRegistry): void {
}
registerMenus(registry: MenuModelRegistry): void {}
registerKeybindings(registry: KeybindingRegistry): void {
}
registerToolbarItems(registry: TabBarToolbarRegistry): void {
}
registerKeybindings(registry: KeybindingRegistry): void {}
registerToolbarItems(registry: TabBarToolbarRegistry): void {}
}
@injectable()
export abstract class SketchContribution extends Contribution {
@inject(FileService)
protected readonly fileService: FileService;
@@ -100,18 +130,23 @@ export abstract class SketchContribution extends Contribution {
if (sketch) {
for (const editor of this.editorManager.all) {
const uri = editor.editor.uri;
if (Saveable.isDirty(editor) && Sketch.isInSketch(uri, sketch)) {
if (
Saveable.isDirty(editor) &&
Sketch.isInSketch(uri, sketch)
) {
override[uri.toString()] = editor.editor.document.getText();
}
}
}
return override;
}
}
export namespace Contribution {
export function configure<T>(bind: interfaces.Bind, serviceIdentifier: typeof Contribution): void {
export function configure<T>(
bind: interfaces.Bind,
serviceIdentifier: typeof Contribution
): void {
bind(serviceIdentifier).toSelf().inSingletonScope();
bind(CommandContribution).toService(serviceIdentifier);
bind(MenuContribution).toService(serviceIdentifier);

View File

@@ -5,11 +5,16 @@ import { ArduinoToolbar } from '../toolbar/arduino-toolbar';
import { NotificationCenter } from '../notification-center';
import { Board, BoardsService, ExecutableService } from '../../common/protocol';
import { BoardsServiceProvider } from '../boards/boards-service-provider';
import { URI, Command, CommandRegistry, SketchContribution, TabBarToolbarRegistry } from './contribution';
import {
URI,
Command,
CommandRegistry,
SketchContribution,
TabBarToolbarRegistry,
} from './contribution';
@injectable()
export class Debug extends SketchContribution {
@inject(HostedPluginSupport)
protected hostedPluginSupport: HostedPluginSupport;
@@ -29,8 +34,11 @@ export class Debug extends SketchContribution {
* If `undefined`, debugging is enabled. Otherwise, the reason why it's disabled.
*/
protected _disabledMessages?: string = 'No board selected'; // Initial pessimism.
protected disabledMessageDidChangeEmitter = new Emitter<string | undefined>();
protected onDisabledMessageDidChange = this.disabledMessageDidChangeEmitter.event;
protected disabledMessageDidChangeEmitter = new Emitter<
string | undefined
>();
protected onDisabledMessageDidChange =
this.disabledMessageDidChangeEmitter.event;
protected get disabledMessage(): string | undefined {
return this._disabledMessages;
@@ -43,14 +51,28 @@ export class Debug extends SketchContribution {
protected readonly debugToolbarItem = {
id: Debug.Commands.START_DEBUGGING.id,
command: Debug.Commands.START_DEBUGGING.id,
tooltip: `${this.disabledMessage ? `Debug - ${this.disabledMessage}` : 'Start Debugging'}`,
tooltip: `${
this.disabledMessage
? `Debug - ${this.disabledMessage}`
: 'Start Debugging'
}`,
priority: 3,
onDidChange: this.onDisabledMessageDidChange as Event<void>
onDidChange: this.onDisabledMessageDidChange as Event<void>,
};
onStart(): void {
this.onDisabledMessageDidChange(() => this.debugToolbarItem.tooltip = `${this.disabledMessage ? `Debug - ${this.disabledMessage}` : 'Start Debugging'}`);
const refreshState = async (board: Board | undefined = this.boardsServiceProvider.boardsConfig.selectedBoard) => {
this.onDisabledMessageDidChange(
() =>
(this.debugToolbarItem.tooltip = `${
this.disabledMessage
? `Debug - ${this.disabledMessage}`
: 'Start Debugging'
}`)
);
const refreshState = async (
board: Board | undefined = this.boardsServiceProvider.boardsConfig
.selectedBoard
) => {
if (!board) {
this.disabledMessage = 'No board selected';
return;
@@ -71,8 +93,10 @@ export class Debug extends SketchContribution {
} else {
this.disabledMessage = undefined;
}
}
this.boardsServiceProvider.onBoardsConfigChanged(({ selectedBoard }) => refreshState(selectedBoard));
};
this.boardsServiceProvider.onBoardsConfigChanged(({ selectedBoard }) =>
refreshState(selectedBoard)
);
this.notificationCenter.onPlatformInstalled(() => refreshState());
this.notificationCenter.onPlatformUninstalled(() => refreshState());
refreshState();
@@ -81,8 +105,9 @@ export class Debug extends SketchContribution {
registerCommands(registry: CommandRegistry): void {
registry.registerCommand(Debug.Commands.START_DEBUGGING, {
execute: () => this.startDebug(),
isVisible: widget => ArduinoToolbar.is(widget) && widget.side === 'left',
isEnabled: () => !this.disabledMessage
isVisible: (widget) =>
ArduinoToolbar.is(widget) && widget.side === 'left',
isEnabled: () => !this.disabledMessage,
});
}
@@ -90,7 +115,10 @@ export class Debug extends SketchContribution {
registry.registerItem(this.debugToolbarItem);
}
protected async startDebug(board: Board | undefined = this.boardsServiceProvider.boardsConfig.selectedBoard): Promise<void> {
protected async startDebug(
board: Board | undefined = this.boardsServiceProvider.boardsConfig
.selectedBoard
): Promise<void> {
if (!board) {
return;
}
@@ -101,29 +129,33 @@ export class Debug extends SketchContribution {
await this.hostedPluginSupport.didStart;
const [sketch, executables] = await Promise.all([
this.sketchServiceClient.currentSketch(),
this.executableService.list()
this.executableService.list(),
]);
if (!sketch) {
return;
}
const ideTempFolderUri = await this.sketchService.getIdeTempFolderUri(sketch);
const ideTempFolderUri = await this.sketchService.getIdeTempFolderUri(
sketch
);
const [cliPath, sketchPath, configPath] = await Promise.all([
this.fileService.fsPath(new URI(executables.cliUri)),
this.fileService.fsPath(new URI(sketch.uri)),
this.fileService.fsPath(new URI(ideTempFolderUri)),
])
]);
const config = {
cliPath,
board: {
fqbn,
name
name,
},
sketchPath,
configPath
configPath,
};
return this.commandService.executeCommand('arduino.debug.start', config);
return this.commandService.executeCommand(
'arduino.debug.start',
config
);
}
}
export namespace Debug {
@@ -131,7 +163,7 @@ export namespace Debug {
export const START_DEBUGGING: Command = {
id: 'arduino-start-debug',
label: 'Start Debugging',
category: 'Arduino'
}
category: 'Arduino',
};
}
}

View File

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

View File

@@ -1,19 +1,30 @@
import * as PQueue from 'p-queue';
import { inject, injectable, postConstruct } from 'inversify';
import { MenuPath, CompositeMenuNode, SubMenuOptions } from '@theia/core/lib/common/menu';
import { Disposable, DisposableCollection } from '@theia/core/lib/common/disposable';
import { CommandHandler } from '@theia/core/lib/common/command';
import {
MenuPath,
CompositeMenuNode,
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 { BoardsServiceProvider } from '../boards/boards-service-provider';
import { ExamplesService } from '../../common/protocol/examples-service';
import { SketchContribution, CommandRegistry, MenuModelRegistry } from './contribution';
import {
SketchContribution,
CommandRegistry,
MenuModelRegistry,
} from './contribution';
import { NotificationCenter } from '../notification-center';
import { Board, Sketch, SketchContainer } from '../../common/protocol';
@injectable()
export abstract class Examples extends SketchContribution {
@inject(CommandRegistry)
protected readonly commandRegistry: CommandRegistry;
@@ -33,7 +44,9 @@ export abstract class Examples extends SketchContribution {
@postConstruct()
init(): void {
this.boardsServiceClient.onBoardsConfigChanged(({ selectedBoard }) => this.handleBoardChanged(selectedBoard));
this.boardsServiceClient.onBoardsConfigChanged(({ selectedBoard }) =>
this.handleBoardChanged(selectedBoard)
);
}
protected handleBoardChanged(board: Board | undefined): void {
@@ -45,8 +58,13 @@ export abstract class Examples extends SketchContribution {
// 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 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) {
@@ -55,19 +73,33 @@ export abstract class Examples extends SketchContribution {
}
// Registering the same submenu multiple times has no side-effect.
// TODO: unregister submenu? https://github.com/eclipse-theia/theia/issues/7300
registry.registerSubmenu(ArduinoMenus.FILE__EXAMPLES_SUBMENU, 'Examples', { order: '4' });
registry.registerSubmenu(
ArduinoMenus.FILE__EXAMPLES_SUBMENU,
'Examples',
{ order: '4' }
);
}
registerRecursively(
sketchContainerOrPlaceholder: SketchContainer | (Sketch | SketchContainer)[] | string,
sketchContainerOrPlaceholder:
| SketchContainer
| (Sketch | SketchContainer)[]
| string,
menuPath: MenuPath,
pushToDispose: DisposableCollection = new DisposableCollection(),
subMenuOptions?: SubMenuOptions | undefined): void {
subMenuOptions?: SubMenuOptions | undefined
): void {
if (typeof sketchContainerOrPlaceholder === 'string') {
const placeholder = new PlaceholderMenuNode(menuPath, sketchContainerOrPlaceholder);
const placeholder = new PlaceholderMenuNode(
menuPath,
sketchContainerOrPlaceholder
);
this.menuRegistry.registerMenuNode(menuPath, placeholder);
pushToDispose.push(Disposable.create(() => this.menuRegistry.unregisterMenuNode(placeholder.id)));
pushToDispose.push(
Disposable.create(() =>
this.menuRegistry.unregisterMenuNode(placeholder.id)
)
);
} else {
const sketches: Sketch[] = [];
const children: SketchContainer[] = [];
@@ -76,7 +108,11 @@ export abstract class Examples extends SketchContribution {
if (SketchContainer.is(sketchContainerOrPlaceholder)) {
const { label } = sketchContainerOrPlaceholder;
submenuPath = [...menuPath, label];
this.menuRegistry.registerSubmenu(submenuPath, label, subMenuOptions);
this.menuRegistry.registerSubmenu(
submenuPath,
label,
subMenuOptions
);
sketches.push(...sketchContainerOrPlaceholder.sketches);
children.push(...sketchContainerOrPlaceholder.children);
} else {
@@ -88,29 +124,48 @@ export abstract class Examples extends SketchContribution {
}
}
}
children.forEach(child => this.registerRecursively(child, submenuPath, pushToDispose));
children.forEach((child) =>
this.registerRecursively(child, submenuPath, pushToDispose)
);
for (const sketch of sketches) {
const { uri } = sketch;
const commandId = `arduino-open-example-${submenuPath.join(':')}--${uri}`;
const commandId = `arduino-open-example-${submenuPath.join(
':'
)}--${uri}`;
const command = { id: commandId };
const handler = {
execute: async () => {
const sketch = await this.sketchService.cloneExample(uri);
this.commandService.executeCommand(OpenSketch.Commands.OPEN_SKETCH.id, sketch);
}
};
pushToDispose.push(this.commandRegistry.registerCommand(command, handler));
this.menuRegistry.registerMenuAction(submenuPath, { commandId, label: sketch.name, order: sketch.name.toLocaleLowerCase() });
pushToDispose.push(Disposable.create(() => this.menuRegistry.unregisterMenuAction(command)));
const handler = this.createHandler(uri);
pushToDispose.push(
this.commandRegistry.registerCommand(command, handler)
);
this.menuRegistry.registerMenuAction(submenuPath, {
commandId,
label: sketch.name,
order: sketch.name.toLocaleLowerCase(),
});
pushToDispose.push(
Disposable.create(() =>
this.menuRegistry.unregisterMenuAction(command)
)
);
}
}
}
protected createHandler(uri: string): CommandHandler {
return {
execute: async () => {
const sketch = await this.sketchService.cloneExample(uri);
return this.commandService.executeCommand(
OpenSketch.Commands.OPEN_SKETCH.id,
sketch
);
},
};
}
}
@injectable()
export class BuiltInExamples extends Examples {
onStart(): void {
this.register(); // no `await`
}
@@ -121,21 +176,25 @@ export class BuiltInExamples extends Examples {
sketchContainers = await this.examplesService.builtIns();
} catch (e) {
console.error('Could not initialize built-in examples.', e);
this.messageService.error('Could not initialize built-in examples.');
this.messageService.error(
'Could not initialize built-in examples.'
);
return;
}
this.toDispose.dispose();
for (const container of ['Built-in examples', ...sketchContainers]) {
this.registerRecursively(container, ArduinoMenus.EXAMPLES__BUILT_IN_GROUP, this.toDispose);
this.registerRecursively(
container,
ArduinoMenus.EXAMPLES__BUILT_IN_GROUP,
this.toDispose
);
}
this.menuManager.update();
}
}
@injectable()
export class LibraryExamples extends Examples {
@inject(NotificationCenter)
protected readonly notificationCenter: NotificationCenter;
@@ -151,34 +210,49 @@ export class LibraryExamples extends Examples {
this.register(board);
}
protected async register(board: Board | undefined = this.boardsServiceClient.boardsConfig.selectedBoard): Promise<void> {
protected async register(
board: Board | undefined = this.boardsServiceClient.boardsConfig
.selectedBoard
): Promise<void> {
return this.queue.add(async () => {
this.toDispose.dispose();
if (!board || !board.fqbn) {
return;
}
const { fqbn, name } = board;
const { user, current, any } = await this.examplesService.installed({ fqbn });
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.
const { user, current, any } = await this.examplesService.installed(
{ fqbn }
);
if (user.length) {
(user as any).unshift('Examples from Custom Libraries');
}
if (current.length) {
if (name && fqbn && current.length) {
(current as any).unshift(`Examples for ${name}`);
}
if (any.length) {
(any as any).unshift('Examples for any board');
}
for (const container of user) {
this.registerRecursively(container, ArduinoMenus.EXAMPLES__USER_LIBS_GROUP, this.toDispose);
this.registerRecursively(
container,
ArduinoMenus.EXAMPLES__USER_LIBS_GROUP,
this.toDispose
);
}
for (const container of current) {
this.registerRecursively(container, ArduinoMenus.EXAMPLES__CURRENT_BOARD_GROUP, this.toDispose);
this.registerRecursively(
container,
ArduinoMenus.EXAMPLES__CURRENT_BOARD_GROUP,
this.toDispose
);
}
for (const container of any) {
this.registerRecursively(container, ArduinoMenus.EXAMPLES__ANY_BOARD_GROUP, this.toDispose);
this.registerRecursively(
container,
ArduinoMenus.EXAMPLES__ANY_BOARD_GROUP,
this.toDispose
);
}
this.menuManager.update();
});
}
}

View File

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

View File

@@ -4,7 +4,10 @@ import URI from '@theia/core/lib/common/uri';
import { MonacoEditor } from '@theia/monaco/lib/browser/monaco-editor';
import { EditorManager } from '@theia/editor/lib/browser';
import { MenuModelRegistry, MenuPath } from '@theia/core/lib/common/menu';
import { Disposable, DisposableCollection } from '@theia/core/lib/common/disposable';
import {
Disposable,
DisposableCollection,
} from '@theia/core/lib/common/disposable';
import { ArduinoMenus, PlaceholderMenuNode } from '../menu/arduino-menus';
import { LibraryPackage, LibraryService } from '../../common/protocol';
import { MainMenuManager } from '../../common/main-menu-manager';
@@ -15,7 +18,6 @@ import { NotificationCenter } from '../notification-center';
@injectable()
export class IncludeLibrary extends SketchContribution {
@inject(CommandRegistry)
protected readonly commandRegistry: CommandRegistry;
@@ -42,29 +44,40 @@ export class IncludeLibrary extends SketchContribution {
onStart(): void {
this.updateMenuActions();
this.boardsServiceClient.onBoardsConfigChanged(() => this.updateMenuActions())
this.notificationCenter.onLibraryInstalled(() => this.updateMenuActions());
this.notificationCenter.onLibraryUninstalled(() => this.updateMenuActions());
this.boardsServiceClient.onBoardsConfigChanged(() =>
this.updateMenuActions()
);
this.notificationCenter.onLibraryInstalled(() =>
this.updateMenuActions()
);
this.notificationCenter.onLibraryUninstalled(() =>
this.updateMenuActions()
);
}
registerMenus(registry: MenuModelRegistry): void {
// `Include Library` submenu
const includeLibMenuPath = [...ArduinoMenus.SKETCH__UTILS_GROUP, '0_include'];
registry.registerSubmenu(includeLibMenuPath, 'Include Library', { order: '1' });
const includeLibMenuPath = [
...ArduinoMenus.SKETCH__UTILS_GROUP,
'0_include',
];
registry.registerSubmenu(includeLibMenuPath, 'Include Library', {
order: '1',
});
// `Manage Libraries...` group.
registry.registerMenuAction([...includeLibMenuPath, '0_manage'], {
commandId: `${LibraryListWidget.WIDGET_ID}:toggle`,
label: 'Manage Libraries...'
label: 'Manage Libraries...',
});
}
registerCommands(registry: CommandRegistry): void {
registry.registerCommand(IncludeLibrary.Commands.INCLUDE_LIBRARY, {
execute: async arg => {
execute: async (arg) => {
if (LibraryPackage.is(arg)) {
this.includeLibrary(arg);
}
}
},
});
}
@@ -72,14 +85,17 @@ export class IncludeLibrary extends SketchContribution {
return this.queue.add(async () => {
this.toDispose.dispose();
this.mainMenuManager.update();
const libraries: LibraryPackage[] = []
const fqbn = this.boardsServiceClient.boardsConfig.selectedBoard?.fqbn;
// Do not show board specific examples, when no board is selected.
if (fqbn) {
libraries.push(...await this.libraryService.list({ fqbn }));
}
const libraries: LibraryPackage[] = [];
const fqbn =
this.boardsServiceClient.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 })));
const includeLibMenuPath = [...ArduinoMenus.SKETCH__UTILS_GROUP, '0_include'];
const includeLibMenuPath = [
...ArduinoMenus.SKETCH__UTILS_GROUP,
'0_include',
];
// `Add .ZIP Library...`
// TODO: implement it
@@ -95,30 +111,50 @@ export class IncludeLibrary extends SketchContribution {
}
for (const library of user) {
this.toDispose.push(this.registerLibrary(library, userMenuPath));
this.toDispose.push(
this.registerLibrary(library, userMenuPath)
);
}
for (const library of rest) {
this.toDispose.push(this.registerLibrary(library, packageMenuPath));
this.toDispose.push(
this.registerLibrary(library, packageMenuPath)
);
}
this.mainMenuManager.update();
});
}
protected registerLibrary(libraryOrPlaceholder: LibraryPackage | string, menuPath: MenuPath): Disposable {
protected registerLibrary(
libraryOrPlaceholder: LibraryPackage | string,
menuPath: MenuPath
): Disposable {
if (typeof libraryOrPlaceholder === 'string') {
const placeholder = new PlaceholderMenuNode(menuPath, libraryOrPlaceholder);
const placeholder = new PlaceholderMenuNode(
menuPath,
libraryOrPlaceholder
);
this.menuRegistry.registerMenuNode(menuPath, placeholder);
return Disposable.create(() => this.menuRegistry.unregisterMenuNode(placeholder.id));
return Disposable.create(() =>
this.menuRegistry.unregisterMenuNode(placeholder.id)
);
}
const commandId = `arduino-include-library--${libraryOrPlaceholder.name}:${libraryOrPlaceholder.author}`;
const command = { id: commandId };
const handler = { execute: () => this.commandRegistry.executeCommand(IncludeLibrary.Commands.INCLUDE_LIBRARY.id, libraryOrPlaceholder) };
const handler = {
execute: () =>
this.commandRegistry.executeCommand(
IncludeLibrary.Commands.INCLUDE_LIBRARY.id,
libraryOrPlaceholder
),
};
const menuAction = { commandId, label: libraryOrPlaceholder.name };
this.menuRegistry.registerMenuAction(menuPath, menuAction);
return new DisposableCollection(
this.commandRegistry.registerCommand(command, handler),
Disposable.create(() => this.menuRegistry.unregisterMenuAction(menuAction)),
Disposable.create(() =>
this.menuRegistry.unregisterMenuAction(menuAction)
)
);
}
@@ -132,13 +168,19 @@ export class IncludeLibrary extends SketchContribution {
let codeEditor: monaco.editor.IStandaloneCodeEditor | undefined;
const editor = this.editorManager.currentEditor?.editor;
if (editor instanceof MonacoEditor) {
if (sketch.additionalFileUris.some(uri => uri === editor.uri.toString())) {
if (
sketch.additionalFileUris.some(
(uri) => uri === editor.uri.toString()
)
) {
codeEditor = editor.getControl();
}
}
if (!codeEditor) {
const widget = await this.editorManager.open(new URI(sketch.mainFileUri));
const widget = await this.editorManager.open(
new URI(sketch.mainFileUri)
);
if (widget.editor instanceof MonacoEditor) {
codeEditor = widget.editor.getControl();
}
@@ -156,22 +198,29 @@ export class IncludeLibrary extends SketchContribution {
const eol = textModel.getEOL();
const includes = library.includes.slice();
includes.push(''); // For the trailing new line.
const text = includes.map(include => include ? `#include <${include}>` : eol).join(eol);
const text = includes
.map((include) => (include ? `#include <${include}>` : eol))
.join(eol);
textModel.pushStackElement(); // Start a fresh operation.
textModel.pushEditOperations(cursorState, [{
range: new monaco.Range(1, 1, 1, 1),
text,
forceMoveMarkers: true
}], () => cursorState);
textModel.pushEditOperations(
cursorState,
[
{
range: new monaco.Range(1, 1, 1, 1),
text,
forceMoveMarkers: true,
},
],
() => cursorState
);
textModel.pushStackElement(); // Make it undoable.
}
}
export namespace IncludeLibrary {
export namespace Commands {
export const INCLUDE_LIBRARY: Command = {
id: 'arduino-include-library'
id: 'arduino-include-library',
};
}
}

View File

@@ -1,18 +1,27 @@
import { injectable } from 'inversify';
import { ArduinoMenus } from '../menu/arduino-menus';
import { ArduinoToolbar } from '../toolbar/arduino-toolbar';
import { SketchContribution, URI, Command, CommandRegistry, MenuModelRegistry, KeybindingRegistry, TabBarToolbarRegistry } from './contribution';
import {
SketchContribution,
URI,
Command,
CommandRegistry,
MenuModelRegistry,
KeybindingRegistry,
TabBarToolbarRegistry,
} from './contribution';
@injectable()
export class NewSketch extends SketchContribution {
registerCommands(registry: CommandRegistry): void {
registry.registerCommand(NewSketch.Commands.NEW_SKETCH, {
execute: () => this.newSketch()
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)
isVisible: (widget) =>
ArduinoToolbar.is(widget) && widget.side === 'left',
execute: () =>
registry.executeCommand(NewSketch.Commands.NEW_SKETCH.id),
});
}
@@ -20,14 +29,14 @@ export class NewSketch extends SketchContribution {
registry.registerMenuAction(ArduinoMenus.FILE__SKETCH_GROUP, {
commandId: NewSketch.Commands.NEW_SKETCH.id,
label: 'New',
order: '0'
order: '0',
});
}
registerKeybindings(registry: KeybindingRegistry): void {
registry.registerKeybinding({
command: NewSketch.Commands.NEW_SKETCH.id,
keybinding: 'CtrlCmd+N'
keybinding: 'CtrlCmd+N',
});
}
@@ -36,7 +45,7 @@ export class NewSketch extends SketchContribution {
id: NewSketch.Commands.NEW_SKETCH__TOOLBAR.id,
command: NewSketch.Commands.NEW_SKETCH__TOOLBAR.id,
tooltip: 'New',
priority: 3
priority: 3,
});
}
@@ -48,16 +57,15 @@ export class NewSketch extends SketchContribution {
await this.messageService.error(e.toString());
}
}
}
export namespace NewSketch {
export namespace Commands {
export const NEW_SKETCH: Command = {
id: 'arduino-new-sketch'
id: 'arduino-new-sketch',
};
export const NEW_SKETCH__TOOLBAR: Command = {
id: 'arduino-new-sketch--toolbar'
id: 'arduino-new-sketch--toolbar',
};
}
}

View File

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

View File

@@ -2,14 +2,19 @@ import { injectable } from 'inversify';
import { remote } from 'electron';
import URI from '@theia/core/lib/common/uri';
import { ArduinoMenus } from '../menu/arduino-menus';
import { SketchContribution, Command, CommandRegistry, MenuModelRegistry, KeybindingRegistry } from './contribution';
import {
SketchContribution,
Command,
CommandRegistry,
MenuModelRegistry,
KeybindingRegistry,
} from './contribution';
@injectable()
export class OpenSketchExternal extends SketchContribution {
registerCommands(registry: CommandRegistry): void {
registry.registerCommand(OpenSketchExternal.Commands.OPEN_EXTERNAL, {
execute: () => this.openExternal()
execute: () => this.openExternal(),
});
}
@@ -17,14 +22,14 @@ export class OpenSketchExternal extends SketchContribution {
registry.registerMenuAction(ArduinoMenus.SKETCH__UTILS_GROUP, {
commandId: OpenSketchExternal.Commands.OPEN_EXTERNAL.id,
label: 'Show Sketch Folder',
order: '0'
order: '0',
});
}
registerKeybindings(registry: KeybindingRegistry): void {
registry.registerKeybinding({
command: OpenSketchExternal.Commands.OPEN_EXTERNAL.id,
keybinding: 'CtrlCmd+Alt+K'
keybinding: 'CtrlCmd+Alt+K',
});
}
@@ -40,13 +45,12 @@ export class OpenSketchExternal extends SketchContribution {
}
}
}
}
export namespace OpenSketchExternal {
export namespace Commands {
export const OPEN_EXTERNAL: Command = {
id: 'arduino-open-sketch-external'
id: 'arduino-open-sketch-external',
};
}
}

View File

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

View File

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

View File

@@ -2,14 +2,20 @@ import { injectable } from 'inversify';
import { remote } from 'electron';
import * as dateFormat from 'dateformat';
import { ArduinoMenus } from '../menu/arduino-menus';
import { SketchContribution, URI, Command, CommandRegistry, MenuModelRegistry, KeybindingRegistry } from './contribution';
import {
SketchContribution,
URI,
Command,
CommandRegistry,
MenuModelRegistry,
KeybindingRegistry,
} from './contribution';
@injectable()
export class SaveAsSketch extends SketchContribution {
registerCommands(registry: CommandRegistry): void {
registry.registerCommand(SaveAsSketch.Commands.SAVE_AS_SKETCH, {
execute: args => this.saveAs(args)
execute: (args) => this.saveAs(args),
});
}
@@ -17,21 +23,27 @@ export class SaveAsSketch extends SketchContribution {
registry.registerMenuAction(ArduinoMenus.FILE__SKETCH_GROUP, {
commandId: SaveAsSketch.Commands.SAVE_AS_SKETCH.id,
label: 'Save As...',
order: '7'
order: '7',
});
}
registerKeybindings(registry: KeybindingRegistry): void {
registry.registerKeybinding({
command: SaveAsSketch.Commands.SAVE_AS_SKETCH.id,
keybinding: 'CtrlCmd+Shift+S'
keybinding: 'CtrlCmd+Shift+S',
});
}
/**
* Resolves `true` if the sketch was successfully saved as something.
*/
async saveAs({ execOnlyIfTemp, openAfterMove, wipeOriginal }: SaveAsSketch.Options = SaveAsSketch.Options.DEFAULT): Promise<boolean> {
async saveAs(
{
execOnlyIfTemp,
openAfterMove,
wipeOriginal,
}: SaveAsSketch.Options = SaveAsSketch.Options.DEFAULT
): Promise<boolean> {
const sketch = await this.sketchServiceClient.currentSketch();
if (!sketch) {
return false;
@@ -44,13 +56,29 @@ export class SaveAsSketch extends SketchContribution {
// If target does not exist, propose a `directories.user`/${sketch.name} path
// If target exists, propose `directories.user`/${sketch.name}_copy_${yyyymmddHHMMss}
const sketchDirUri = new URI((await this.configService.getConfiguration()).sketchDirUri);
const exists = await this.fileService.exists(sketchDirUri.resolve(sketch.name));
const sketchDirUri = new URI(
(await this.configService.getConfiguration()).sketchDirUri
);
const exists = await this.fileService.exists(
sketchDirUri.resolve(sketch.name)
);
const defaultUri = exists
? sketchDirUri.resolve(sketchDirUri.resolve(`${sketch.name}_copy_${dateFormat(new Date(), 'yyyymmddHHMMss')}`).toString())
? sketchDirUri.resolve(
sketchDirUri
.resolve(
`${sketch.name}_copy_${dateFormat(
new Date(),
'yyyymmddHHMMss'
)}`
)
.toString()
)
: sketchDirUri.resolve(sketch.name);
const defaultPath = await this.fileService.fsPath(defaultUri);
const { filePath, canceled } = await remote.dialog.showSaveDialog({ title: 'Save sketch folder as...', defaultPath });
const { filePath, canceled } = await remote.dialog.showSaveDialog({
title: 'Save sketch folder as...',
defaultPath,
});
if (!filePath || canceled) {
return false;
}
@@ -58,24 +86,31 @@ export class SaveAsSketch extends SketchContribution {
if (!destinationUri) {
return false;
}
const workspaceUri = await this.sketchService.copy(sketch, { destinationUri });
const workspaceUri = await this.sketchService.copy(sketch, {
destinationUri,
});
if (workspaceUri && openAfterMove) {
if (wipeOriginal || (openAfterMove && execOnlyIfTemp)) {
try {
await this.fileService.delete(new URI(sketch.uri), { recursive: true });
} catch { /* NOOP: from time to time, it's not possible to wipe the old resource from the temp dir on Windows */ }
await this.fileService.delete(new URI(sketch.uri), {
recursive: true,
});
} catch {
/* NOOP: from time to time, it's not possible to wipe the old resource from the temp dir on Windows */
}
}
this.workspaceService.open(new URI(workspaceUri), { preserveWindow: true });
this.workspaceService.open(new URI(workspaceUri), {
preserveWindow: true,
});
}
return !!workspaceUri;
}
}
export namespace SaveAsSketch {
export namespace Commands {
export const SAVE_AS_SKETCH: Command = {
id: 'arduino-save-as-sketch'
id: 'arduino-save-as-sketch',
};
}
export interface Options {
@@ -90,7 +125,7 @@ export namespace SaveAsSketch {
export const DEFAULT: Options = {
execOnlyIfTemp: false,
openAfterMove: true,
wipeOriginal: false
wipeOriginal: false,
};
}
}

View File

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

View File

@@ -1,11 +1,16 @@
import { inject, injectable } from 'inversify';
import { Command, MenuModelRegistry, CommandRegistry, SketchContribution, KeybindingRegistry } from './contribution';
import {
Command,
MenuModelRegistry,
CommandRegistry,
SketchContribution,
KeybindingRegistry,
} from './contribution';
import { ArduinoMenus } from '../menu/arduino-menus';
import { Settings as Preferences, SettingsDialog } from '../settings';
@injectable()
export class Settings extends SketchContribution {
@inject(SettingsDialog)
protected readonly settingsDialog: SettingsDialog;
@@ -28,16 +33,20 @@ export class Settings extends SketchContribution {
await this.settingsService.reset();
}
},
isEnabled: () => !this.settingsOpened
isEnabled: () => !this.settingsOpened,
});
}
registerMenus(registry: MenuModelRegistry): void {
registry.registerMenuAction(ArduinoMenus.FILE__SETTINGS_GROUP, {
registry.registerMenuAction(ArduinoMenus.FILE__PREFERENCES_GROUP, {
commandId: Settings.Commands.OPEN.id,
label: 'Preferences...',
order: '0'
order: '0',
});
registry.registerSubmenu(
ArduinoMenus.FILE__ADVANCED_SUBMENU,
'Advanced'
);
}
registerKeybindings(registry: KeybindingRegistry): void {
@@ -46,7 +55,6 @@ export class Settings extends SketchContribution {
keybinding: 'CtrlCmd+,',
});
}
}
export namespace Settings {
@@ -54,7 +62,7 @@ export namespace Settings {
export const OPEN: Command = {
id: 'arduino-settings-open',
label: 'Open Preferences...',
category: 'Arduino'
}
category: 'Arduino',
};
}
}

View File

@@ -3,13 +3,27 @@ import { CommonCommands } from '@theia/core/lib/browser/common-frontend-contribu
import { ApplicationShell } from '@theia/core/lib/browser/shell/application-shell';
import { WorkspaceCommands } from '@theia/workspace/lib/browser';
import { ContextMenuRenderer } from '@theia/core/lib/browser/context-menu-renderer';
import { Disposable, DisposableCollection } from '@theia/core/lib/common/disposable';
import { URI, SketchContribution, Command, CommandRegistry, MenuModelRegistry, KeybindingRegistry, TabBarToolbarRegistry, open } from './contribution';
import { ArduinoMenus } from '../menu/arduino-menus';
import {
Disposable,
DisposableCollection,
} from '@theia/core/lib/common/disposable';
import {
URI,
SketchContribution,
Command,
CommandRegistry,
MenuModelRegistry,
KeybindingRegistry,
TabBarToolbarRegistry,
open,
} from './contribution';
import { ArduinoMenus, PlaceholderMenuNode } from '../menu/arduino-menus';
import { EditorManager } from '@theia/editor/lib/browser/editor-manager';
import { SketchesServiceClientImpl } from '../../common/protocol/sketches-service-client-impl';
import { LocalCacheFsProvider } from '../local-cache/local-cache-fs-provider';
@injectable()
export class SketchControl extends SketchContribution {
@inject(ApplicationShell)
protected readonly shell: ApplicationShell;
@@ -19,111 +33,251 @@ export class SketchControl extends SketchContribution {
@inject(ContextMenuRenderer)
protected readonly contextMenuRenderer: ContextMenuRenderer;
protected readonly toDisposeBeforeCreateNewContextMenu = new DisposableCollection();
@inject(EditorManager)
protected readonly editorManager: EditorManager;
@inject(SketchesServiceClientImpl)
protected readonly sketchesServiceClient: SketchesServiceClientImpl;
@inject(LocalCacheFsProvider)
protected readonly localCacheFsProvider: LocalCacheFsProvider;
protected readonly toDisposeBeforeCreateNewContextMenu =
new DisposableCollection();
registerCommands(registry: CommandRegistry): void {
registry.registerCommand(SketchControl.Commands.OPEN_SKETCH_CONTROL__TOOLBAR, {
isVisible: widget => this.shell.getWidgets('main').indexOf(widget) !== -1,
execute: async () => {
this.toDisposeBeforeCreateNewContextMenu.dispose();
const sketch = await this.sketchServiceClient.currentSketch();
if (!sketch) {
return;
}
const target = document.getElementById(SketchControl.Commands.OPEN_SKETCH_CONTROL__TOOLBAR.id);
if (!(target instanceof HTMLElement)) {
return;
}
const { parentElement } = target;
if (!parentElement) {
return;
}
const { mainFileUri, rootFolderFileUris } = await this.sketchService.loadSketch(sketch.uri);
const uris = [mainFileUri, ...rootFolderFileUris];
for (let i = 0; i < uris.length; i++) {
const uri = new URI(uris[i]);
const command = { id: `arduino-focus-file--${uri.toString()}` };
const handler = { execute: () => open(this.openerService, uri) };
this.toDisposeBeforeCreateNewContextMenu.push(registry.registerCommand(command, handler));
this.menuRegistry.registerMenuAction(ArduinoMenus.SKETCH_CONTROL__CONTEXT__RESOURCES_GROUP, {
commandId: command.id,
label: this.labelProvider.getName(uri),
order: `${i}`
});
this.toDisposeBeforeCreateNewContextMenu.push(Disposable.create(() => this.menuRegistry.unregisterMenuAction(command)));
}
const options = {
menuPath: ArduinoMenus.SKETCH_CONTROL__CONTEXT,
anchor: {
x: parentElement.getBoundingClientRect().left,
y: parentElement.getBoundingClientRect().top + parentElement.offsetHeight
registry.registerCommand(
SketchControl.Commands.OPEN_SKETCH_CONTROL__TOOLBAR,
{
isVisible: (widget) =>
this.shell.getWidgets('main').indexOf(widget) !== -1,
execute: async () => {
this.toDisposeBeforeCreateNewContextMenu.dispose();
const sketch =
await this.sketchServiceClient.currentSketch();
if (!sketch) {
return;
}
}
this.contextMenuRenderer.render(options);
const target = document.getElementById(
SketchControl.Commands.OPEN_SKETCH_CONTROL__TOOLBAR.id
);
if (!(target instanceof HTMLElement)) {
return;
}
const { parentElement } = target;
if (!parentElement) {
return;
}
const { mainFileUri, rootFolderFileUris } =
await this.sketchService.loadSketch(sketch.uri);
const uris = [mainFileUri, ...rootFolderFileUris];
const currentSketch =
await this.sketchesServiceClient.currentSketch();
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 (
currentSketch &&
parentsketch &&
parentsketch.uri === currentSketch.uri &&
(await this.allowRename(parentsketch.uri))
) {
this.menuRegistry.registerMenuAction(
ArduinoMenus.SKETCH_CONTROL__CONTEXT__MAIN_GROUP,
{
commandId: WorkspaceCommands.FILE_RENAME.id,
label: '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,
'Rename'
);
this.menuRegistry.registerMenuNode(
ArduinoMenus.SKETCH_CONTROL__CONTEXT__MAIN_GROUP,
renamePlaceholder
);
this.toDisposeBeforeCreateNewContextMenu.push(
Disposable.create(() =>
this.menuRegistry.unregisterMenuNode(
renamePlaceholder.id
)
)
);
}
if (
currentSketch &&
parentsketch &&
parentsketch.uri === currentSketch.uri &&
(await 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: '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,
'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]);
// focus on the opened sketch
const command = {
id: `arduino-focus-file--${uri.toString()}`,
};
const handler = {
execute: () => open(this.openerService, uri),
};
this.toDisposeBeforeCreateNewContextMenu.push(
registry.registerCommand(command, handler)
);
this.menuRegistry.registerMenuAction(
ArduinoMenus.SKETCH_CONTROL__CONTEXT__RESOURCES_GROUP,
{
commandId: command.id,
label: this.labelProvider.getName(uri),
order: `${i}`,
}
);
this.toDisposeBeforeCreateNewContextMenu.push(
Disposable.create(() =>
this.menuRegistry.unregisterMenuAction(command)
)
);
}
const options = {
menuPath: ArduinoMenus.SKETCH_CONTROL__CONTEXT,
anchor: {
x: parentElement.getBoundingClientRect().left,
y:
parentElement.getBoundingClientRect().top +
parentElement.offsetHeight,
},
};
this.contextMenuRenderer.render(options);
},
}
});
);
}
registerMenus(registry: MenuModelRegistry): void {
registry.registerMenuAction(ArduinoMenus.SKETCH_CONTROL__CONTEXT__MAIN_GROUP, {
commandId: WorkspaceCommands.NEW_FILE.id,
label: 'New Tab',
order: '0'
});
registry.registerMenuAction(ArduinoMenus.SKETCH_CONTROL__CONTEXT__MAIN_GROUP, {
commandId: WorkspaceCommands.FILE_RENAME.id,
label: 'Rename',
order: '1'
});
registry.registerMenuAction(ArduinoMenus.SKETCH_CONTROL__CONTEXT__MAIN_GROUP, {
commandId: WorkspaceCommands.FILE_DELETE.id, // TODO: customize delete. Wipe sketch if deleting main file. Close window.
label: 'Delete',
order: '2'
});
registry.registerMenuAction(
ArduinoMenus.SKETCH_CONTROL__CONTEXT__MAIN_GROUP,
{
commandId: WorkspaceCommands.NEW_FILE.id,
label: 'New Tab',
order: '0',
}
);
registry.registerMenuAction(ArduinoMenus.SKETCH_CONTROL__CONTEXT__NAVIGATION_GROUP, {
commandId: CommonCommands.PREVIOUS_TAB.id,
label: 'Previous Tab',
order: '0'
});
registry.registerMenuAction(ArduinoMenus.SKETCH_CONTROL__CONTEXT__NAVIGATION_GROUP, {
commandId: CommonCommands.NEXT_TAB.id,
label: 'Next Tab',
order: '0'
});
registry.registerMenuAction(
ArduinoMenus.SKETCH_CONTROL__CONTEXT__NAVIGATION_GROUP,
{
commandId: CommonCommands.PREVIOUS_TAB.id,
label: 'Previous Tab',
order: '0',
}
);
registry.registerMenuAction(
ArduinoMenus.SKETCH_CONTROL__CONTEXT__NAVIGATION_GROUP,
{
commandId: CommonCommands.NEXT_TAB.id,
label: 'Next Tab',
order: '0',
}
);
}
registerKeybindings(registry: KeybindingRegistry): void {
registry.registerKeybinding({
command: WorkspaceCommands.NEW_FILE.id,
keybinding: 'CtrlCmd+Shift+N'
keybinding: 'CtrlCmd+Shift+N',
});
registry.registerKeybinding({
command: CommonCommands.PREVIOUS_TAB.id,
keybinding: 'CtrlCmd+Alt+Left' // TODO: check why electron does not show the keybindings in the UI.
keybinding: 'CtrlCmd+Alt+Left', // TODO: check why electron does not show the keybindings in the UI.
});
registry.registerKeybinding({
command: CommonCommands.NEXT_TAB.id,
keybinding: 'CtrlCmd+Alt+Right'
keybinding: 'CtrlCmd+Alt+Right',
});
}
registerToolbarItems(registry: TabBarToolbarRegistry): void {
registry.registerItem({
id: SketchControl.Commands.OPEN_SKETCH_CONTROL__TOOLBAR.id,
command: SketchControl.Commands.OPEN_SKETCH_CONTROL__TOOLBAR.id
command: SketchControl.Commands.OPEN_SKETCH_CONTROL__TOOLBAR.id,
});
}
protected async isCloudSketch(uri: string) {
const cloudCacheLocation = this.localCacheFsProvider.from(new URI(uri));
if (cloudCacheLocation) {
return true;
}
return false;
}
protected async allowRename(uri: string) {
return !this.isCloudSketch(uri);
}
protected async allowDelete(uri: string) {
return !this.isCloudSketch(uri);
}
}
export namespace SketchControl {
export namespace Commands {
export const OPEN_SKETCH_CONTROL__TOOLBAR: Command = {
id: 'arduino-open-sketch-control--toolbar',
iconClass: 'fa fa-caret-down'
iconClass: 'fa fa-caret-down',
};
}
}

View File

@@ -1,14 +1,15 @@
import { inject, injectable } from 'inversify';
import { CommandHandler } from '@theia/core/lib/common/command';
import { CommandRegistry, 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 } from '../../common/protocol';
import { OpenSketch } from './open-sketch';
@injectable()
export class Sketchbook extends Examples {
@inject(CommandRegistry)
protected readonly commandRegistry: CommandRegistry;
@@ -22,12 +23,12 @@ export class Sketchbook extends Examples {
protected readonly notificationCenter: NotificationCenter;
onStart(): void {
this.sketchService.getSketches({}).then(container => {
this.sketchService.getSketches({}).then((container) => {
this.register(container);
this.mainMenuManager.update();
});
this.sketchServiceClient.onSketchbookDidChange(() => {
this.sketchService.getSketches({}).then(container => {
this.sketchService.getSketches({}).then((container) => {
this.register(container);
this.mainMenuManager.update();
});
@@ -35,12 +36,31 @@ export class Sketchbook extends Examples {
}
registerMenus(registry: MenuModelRegistry): void {
registry.registerSubmenu(ArduinoMenus.FILE__SKETCHBOOK_SUBMENU, 'Sketchbook', { order: '3' });
registry.registerSubmenu(
ArduinoMenus.FILE__SKETCHBOOK_SUBMENU,
'Sketchbook',
{ order: '3' }
);
}
protected register(container: SketchContainer): void {
this.toDispose.dispose();
this.registerRecursively([...container.children, ...container.sketches], ArduinoMenus.FILE__SKETCHBOOK_SUBMENU, this.toDispose);
this.registerRecursively(
[...container.children, ...container.sketches],
ArduinoMenus.FILE__SKETCHBOOK_SUBMENU,
this.toDispose
);
}
protected createHandler(uri: string): CommandHandler {
return {
execute: async () => {
const sketch = await this.sketchService.loadSketch(uri);
return this.commandService.executeCommand(
OpenSketch.Commands.OPEN_SKETCH.id,
sketch
);
},
};
}
}

View File

@@ -6,11 +6,17 @@ import { ArduinoToolbar } from '../toolbar/arduino-toolbar';
import { BoardsDataStore } from '../boards/boards-data-store';
import { MonitorConnection } from '../monitor/monitor-connection';
import { BoardsServiceProvider } from '../boards/boards-service-provider';
import { SketchContribution, Command, CommandRegistry, MenuModelRegistry, KeybindingRegistry, TabBarToolbarRegistry } from './contribution';
import {
SketchContribution,
Command,
CommandRegistry,
MenuModelRegistry,
KeybindingRegistry,
TabBarToolbarRegistry,
} from './contribution';
@injectable()
export class UploadSketch extends SketchContribution {
@inject(CoreService)
protected readonly coreService: CoreService;
@@ -33,15 +39,20 @@ export class UploadSketch extends SketchContribution {
execute: () => this.uploadSketch(),
isEnabled: () => !this.uploadInProgress,
});
registry.registerCommand(UploadSketch.Commands.UPLOAD_SKETCH_USING_PROGRAMMER, {
execute: () => this.uploadSketch(true),
isEnabled: () => !this.uploadInProgress,
});
registry.registerCommand(
UploadSketch.Commands.UPLOAD_SKETCH_USING_PROGRAMMER,
{
execute: () => this.uploadSketch(true),
isEnabled: () => !this.uploadInProgress,
}
);
registry.registerCommand(UploadSketch.Commands.UPLOAD_SKETCH_TOOLBAR, {
isVisible: widget => ArduinoToolbar.is(widget) && widget.side === 'left',
isVisible: (widget) =>
ArduinoToolbar.is(widget) && widget.side === 'left',
isEnabled: () => !this.uploadInProgress,
isToggled: () => this.uploadInProgress,
execute: () => registry.executeCommand(UploadSketch.Commands.UPLOAD_SKETCH.id)
execute: () =>
registry.executeCommand(UploadSketch.Commands.UPLOAD_SKETCH.id),
});
}
@@ -49,23 +60,23 @@ export class UploadSketch extends SketchContribution {
registry.registerMenuAction(ArduinoMenus.SKETCH__MAIN_GROUP, {
commandId: UploadSketch.Commands.UPLOAD_SKETCH.id,
label: 'Upload',
order: '1'
order: '1',
});
registry.registerMenuAction(ArduinoMenus.SKETCH__MAIN_GROUP, {
commandId: UploadSketch.Commands.UPLOAD_SKETCH_USING_PROGRAMMER.id,
label: 'Upload Using Programmer',
order: '2'
order: '2',
});
}
registerKeybindings(registry: KeybindingRegistry): void {
registry.registerKeybinding({
command: UploadSketch.Commands.UPLOAD_SKETCH.id,
keybinding: 'CtrlCmd+U'
keybinding: 'CtrlCmd+U',
});
registry.registerKeybinding({
command: UploadSketch.Commands.UPLOAD_SKETCH_USING_PROGRAMMER.id,
keybinding: 'CtrlCmd+Shift+U'
keybinding: 'CtrlCmd+Shift+U',
});
}
@@ -75,12 +86,11 @@ export class UploadSketch extends SketchContribution {
command: UploadSketch.Commands.UPLOAD_SKETCH_TOOLBAR.id,
tooltip: 'Upload',
priority: 1,
onDidChange: this.onDidChange
onDidChange: this.onDidChange,
});
}
async uploadSketch(usingProgrammer: boolean = false): Promise<void> {
async uploadSketch(usingProgrammer = false): Promise<void> {
// even with buttons disabled, better to double check if an upload is already in progress
if (this.uploadInProgress) {
return;
@@ -105,12 +115,20 @@ export class UploadSketch extends SketchContribution {
}
try {
const { boardsConfig } = this.boardsServiceClientImpl;
const [fqbn, { selectedProgrammer }, verify, verbose, sourceOverride] = await Promise.all([
this.boardsDataStore.appendConfigToFqbn(boardsConfig.selectedBoard?.fqbn),
const [
fqbn,
{ selectedProgrammer },
verify,
verbose,
sourceOverride,
] = await Promise.all([
this.boardsDataStore.appendConfigToFqbn(
boardsConfig.selectedBoard?.fqbn
),
this.boardsDataStore.getData(boardsConfig.selectedBoard?.fqbn),
this.preferences.get('arduino.upload.verify'),
this.preferences.get('arduino.upload.verbose'),
this.sourceOverride()
this.sourceOverride(),
]);
let options: CoreService.Upload.Options | undefined = undefined;
@@ -129,7 +147,7 @@ export class UploadSketch extends SketchContribution {
port,
verbose,
verify,
sourceOverride
sourceOverride,
};
} else {
options = {
@@ -139,7 +157,7 @@ export class UploadSketch extends SketchContribution {
port,
verbose,
verify,
sourceOverride
sourceOverride,
};
}
this.outputChannelManager.getChannel('Arduino').clear();
@@ -148,7 +166,7 @@ export class UploadSketch extends SketchContribution {
} else {
await this.coreService.upload(options);
}
this.messageService.info('Done uploading.', { timeout: 1000 });
this.messageService.info('Done uploading.', { timeout: 3000 });
} catch (e) {
this.messageService.error(e.toString());
} finally {
@@ -158,7 +176,10 @@ export class UploadSketch extends SketchContribution {
if (monitorConfig) {
const { board, port } = monitorConfig;
try {
await this.boardsServiceClientImpl.waitUntilAvailable(Object.assign(board, { port }), 10_000);
await this.boardsServiceClientImpl.waitUntilAvailable(
Object.assign(board, { port }),
10_000
);
if (shouldAutoConnect) {
// Enabling auto-connect will trigger a connect.
this.monitorConnection.autoConnect = true;
@@ -166,24 +187,25 @@ export class UploadSketch extends SketchContribution {
await this.monitorConnection.connect(monitorConfig);
}
} catch (waitError) {
this.messageService.error(`Could not reconnect to serial monitor. ${waitError.toString()}`);
this.messageService.error(
`Could not reconnect to serial monitor. ${waitError.toString()}`
);
}
}
}
}
}
export namespace UploadSketch {
export namespace Commands {
export const UPLOAD_SKETCH: Command = {
id: 'arduino-upload-sketch'
id: 'arduino-upload-sketch',
};
export const UPLOAD_SKETCH_USING_PROGRAMMER: Command = {
id: 'arduino-upload-sketch-using-programmer'
id: 'arduino-upload-sketch-using-programmer',
};
export const UPLOAD_SKETCH_TOOLBAR: Command = {
id: 'arduino-upload-sketch--toolbar'
id: 'arduino-upload-sketch--toolbar',
};
}
}

View File

@@ -5,11 +5,17 @@ import { ArduinoMenus } from '../menu/arduino-menus';
import { ArduinoToolbar } from '../toolbar/arduino-toolbar';
import { BoardsDataStore } from '../boards/boards-data-store';
import { BoardsServiceProvider } from '../boards/boards-service-provider';
import { SketchContribution, Command, CommandRegistry, MenuModelRegistry, KeybindingRegistry, TabBarToolbarRegistry } from './contribution';
import {
SketchContribution,
Command,
CommandRegistry,
MenuModelRegistry,
KeybindingRegistry,
TabBarToolbarRegistry,
} from './contribution';
@injectable()
export class VerifySketch extends SketchContribution {
@inject(CoreService)
protected readonly coreService: CoreService;
@@ -34,10 +40,12 @@ export class VerifySketch extends SketchContribution {
isEnabled: () => !this.verifyInProgress,
});
registry.registerCommand(VerifySketch.Commands.VERIFY_SKETCH_TOOLBAR, {
isVisible: widget => ArduinoToolbar.is(widget) && widget.side === 'left',
isVisible: (widget) =>
ArduinoToolbar.is(widget) && widget.side === 'left',
isEnabled: () => !this.verifyInProgress,
isToggled: () => this.verifyInProgress,
execute: () => registry.executeCommand(VerifySketch.Commands.VERIFY_SKETCH.id)
execute: () =>
registry.executeCommand(VerifySketch.Commands.VERIFY_SKETCH.id),
});
}
@@ -45,23 +53,23 @@ export class VerifySketch extends SketchContribution {
registry.registerMenuAction(ArduinoMenus.SKETCH__MAIN_GROUP, {
commandId: VerifySketch.Commands.VERIFY_SKETCH.id,
label: 'Verify/Compile',
order: '0'
order: '0',
});
registry.registerMenuAction(ArduinoMenus.SKETCH__MAIN_GROUP, {
commandId: VerifySketch.Commands.EXPORT_BINARIES.id,
label: 'Export compiled Binary',
order: '3'
order: '3',
});
}
registerKeybindings(registry: KeybindingRegistry): void {
registry.registerKeybinding({
command: VerifySketch.Commands.VERIFY_SKETCH.id,
keybinding: 'CtrlCmd+R'
keybinding: 'CtrlCmd+R',
});
registry.registerKeybinding({
command: VerifySketch.Commands.EXPORT_BINARIES.id,
keybinding: 'CtrlCmd+Alt+S'
keybinding: 'CtrlCmd+Alt+S',
});
}
@@ -71,34 +79,37 @@ export class VerifySketch extends SketchContribution {
command: VerifySketch.Commands.VERIFY_SKETCH_TOOLBAR.id,
tooltip: 'Verify',
priority: 0,
onDidChange: this.onDidChange
onDidChange: this.onDidChange,
});
}
async verifySketch(exportBinaries?: boolean): Promise<void> {
// even with buttons disabled, better to double check if a verify is already in progress
if (this.verifyInProgress) {
return;
}
// toggle the toolbar button and menu item state.
// verifyInProgress will be set to false whether the compilation fails or not
this.verifyInProgress = true;
this.onDidChangeEmitter.fire();
const sketch = await this.sketchServiceClient.currentSketch();
if (!sketch) {
return;
}
try {
const { boardsConfig } = this.boardsServiceClientImpl;
const [fqbn, sourceOverride] = await Promise.all([
this.boardsDataStore.appendConfigToFqbn(boardsConfig.selectedBoard?.fqbn),
this.sourceOverride()
this.boardsDataStore.appendConfigToFqbn(
boardsConfig.selectedBoard?.fqbn
),
this.sourceOverride(),
]);
const verbose = this.preferences.get('arduino.compile.verbose');
const compilerWarnings = this.preferences.get('arduino.compile.warnings');
const compilerWarnings = this.preferences.get(
'arduino.compile.warnings'
);
this.outputChannelManager.getChannel('Arduino').clear();
await this.coreService.compile({
sketchUri: sketch.uri,
@@ -107,9 +118,9 @@ export class VerifySketch extends SketchContribution {
verbose,
exportBinaries,
sourceOverride,
compilerWarnings
compilerWarnings,
});
this.messageService.info('Done compiling.', { timeout: 1000 });
this.messageService.info('Done compiling.', { timeout: 3000 });
} catch (e) {
this.messageService.error(e.toString());
} finally {
@@ -117,19 +128,18 @@ export class VerifySketch extends SketchContribution {
this.onDidChangeEmitter.fire();
}
}
}
export namespace VerifySketch {
export namespace Commands {
export const VERIFY_SKETCH: Command = {
id: 'arduino-verify-sketch'
id: 'arduino-verify-sketch',
};
export const EXPORT_BINARIES: Command = {
id: 'arduino-export-binaries'
id: 'arduino-export-binaries',
};
export const VERIFY_SKETCH_TOOLBAR: Command = {
id: 'arduino-verify-sketch--toolbar'
id: 'arduino-verify-sketch--toolbar',
};
}
}

View File

@@ -0,0 +1,599 @@
import { injectable } from 'inversify';
import * as createPaths from './create-paths';
import { posix, splitSketchPath } from './create-paths';
import { AuthenticationClientService } from '../auth/authentication-client-service';
import { ArduinoPreferences } from '../arduino-preferences';
export interface ResponseResultProvider {
(response: Response): Promise<any>;
}
export namespace ResponseResultProvider {
export const NOOP: ResponseResultProvider = async () => undefined;
export const TEXT: ResponseResultProvider = (response) => response.text();
export const JSON: ResponseResultProvider = (response) => response.json();
}
type ResourceType = 'f' | 'd';
export let sketchCache: Create.Sketch[] = [];
@injectable()
export class CreateApi {
protected authenticationService: AuthenticationClientService;
protected arduinoPreferences: ArduinoPreferences;
public init(
authenticationService: AuthenticationClientService,
arduinoPreferences: ArduinoPreferences
): CreateApi {
this.authenticationService = authenticationService;
this.arduinoPreferences = arduinoPreferences;
return this;
}
public sketchCompareByPath = (param: string) => {
return (sketch: Create.Sketch) => {
const [, spath] = splitSketchPath(sketch.path);
return param === spath;
};
};
async findSketchInCache(
compareFn: (sketch: Create.Sketch) => boolean,
trustCache = true
): Promise<Create.Sketch | undefined> {
const sketch = sketchCache.find((sketch) => compareFn(sketch));
if (trustCache) {
return Promise.resolve(sketch);
}
return await this.sketch({ id: sketch?.id });
}
getSketchSecretStat(sketch: Create.Sketch): Create.Resource {
return {
href: `${sketch.href}${posix.sep}${Create.arduino_secrets_file}`,
modified_at: sketch.modified_at,
name: `${Create.arduino_secrets_file}`,
path: `${sketch.path}${posix.sep}${Create.arduino_secrets_file}`,
mimetype: 'text/x-c++src; charset=utf-8',
type: 'file',
sketchId: sketch.id,
};
}
async sketch(opt: {
id?: string;
path?: string;
}): Promise<Create.Sketch | undefined> {
let url;
if (opt.id) {
url = new URL(`${this.domain()}/sketches/byID/${opt.id}`);
} else if (opt.path) {
url = new URL(`${this.domain()}/sketches/byPath${opt.path}`);
} else {
return;
}
url.searchParams.set('user_id', 'me');
const headers = await this.headers();
const result = await this.run<Create.Sketch>(url, {
method: 'GET',
headers,
});
return result;
}
async sketches(): Promise<Create.Sketch[]> {
const url = new URL(`${this.domain()}/sketches`);
url.searchParams.set('user_id', 'me');
const headers = await this.headers();
const result = await this.run<{ sketches: Create.Sketch[] }>(url, {
method: 'GET',
headers,
});
sketchCache = result.sketches;
return result.sketches;
}
async createSketch(
posixPath: string,
content: string = CreateApi.defaultInoContent
): Promise<Create.Sketch> {
const url = new URL(`${this.domain()}/sketches`);
const headers = await this.headers();
const payload = {
ino: btoa(content),
path: posixPath,
user_id: 'me',
};
const init = {
method: 'PUT',
body: JSON.stringify(payload),
headers,
};
const result = await this.run<Create.Sketch>(url, init);
return result;
}
async readDirectory(
posixPath: string,
options: { recursive?: boolean; match?: string; secrets?: boolean } = {}
): Promise<Create.Resource[]> {
const url = new URL(
`${this.domain()}/files/d/$HOME/sketches_v2${posixPath}`
);
if (options.recursive) {
url.searchParams.set('deep', 'true');
}
if (options.match) {
url.searchParams.set('name_like', options.match);
}
const headers = await this.headers();
const sketchProm = options.secrets
? this.sketches()
: Promise.resolve(sketchCache);
return Promise.all([
this.run<Create.RawResource[]>(url, {
method: 'GET',
headers,
}),
sketchProm,
])
.then(async ([result, sketches]) => {
if (options.secrets) {
// for every sketch with secrets, create a fake arduino_secrets.h
result.forEach(async (res) => {
if (res.type !== 'sketch') {
return;
}
const [, spath] = createPaths.splitSketchPath(res.path);
const sketch = await this.findSketchInCache(
this.sketchCompareByPath(spath)
);
if (
sketch &&
sketch.secrets &&
sketch.secrets.length > 0
) {
result.push(this.getSketchSecretStat(sketch));
}
});
if (posixPath !== posix.sep) {
const sketch = await this.findSketchInCache(
this.sketchCompareByPath(posixPath)
);
if (
sketch &&
sketch.secrets &&
sketch.secrets.length > 0
) {
result.push(this.getSketchSecretStat(sketch));
}
}
}
const sketchesMap: Record<string, Create.Sketch> =
sketches.reduce((prev, curr) => {
return { ...prev, [curr.path]: curr };
}, {});
// add the sketch id and isPublic to the resource
return result.map((resource) => {
return {
...resource,
sketchId: sketchesMap[resource.path]?.id || '',
isPublic:
sketchesMap[resource.path]?.is_public || false,
};
});
})
.catch((reason) => {
if (reason?.status === 404) return [] as Create.Resource[];
else throw reason;
});
}
async createDirectory(posixPath: string): Promise<void> {
const url = new URL(
`${this.domain()}/files/d/$HOME/sketches_v2${posixPath}`
);
const headers = await this.headers();
await this.run(url, {
method: 'POST',
headers,
});
}
async stat(posixPath: string): Promise<Create.Resource> {
// The root is a directory read.
if (posixPath === '/') {
throw new Error('Stating the root is not supported');
}
// The RESTful API has different endpoints for files and directories.
// The RESTful API does not provide specific error codes, only HTP 500.
// We query the parent directory and look for the file with the last segment.
const parentPosixPath = createPaths.parentPosix(posixPath);
const basename = createPaths.basename(posixPath);
let resources;
if (basename === Create.arduino_secrets_file) {
const sketch = await this.findSketchInCache(
this.sketchCompareByPath(parentPosixPath)
);
resources = sketch ? [this.getSketchSecretStat(sketch)] : [];
} else {
resources = await this.readDirectory(parentPosixPath, {
match: basename,
});
}
resources.sort((left, right) => left.path.length - right.path.length);
const resource = resources.find(({ name }) => name === basename);
if (!resource) {
throw new CreateError(`Not found: ${posixPath}.`, 404);
}
return resource;
}
private async toggleSecretsInclude(
path: string,
data: string,
mode: 'add' | 'remove'
) {
const includeString = `#include "${Create.arduino_secrets_file}"`;
const includeRegexp = new RegExp(includeString + '\\s*', 'g');
const basename = createPaths.basename(path);
if (mode === 'add') {
const doesIncludeSecrets = includeRegexp.test(data);
if (doesIncludeSecrets) {
return data;
}
const sketch = await this.findSketchInCache((sketch) => {
const [, spath] = splitSketchPath(sketch.path);
return spath === createPaths.parentPosix(path);
}, true);
if (
sketch &&
(sketch.name + '.ino' === basename ||
sketch.name + '.pde' === basename) &&
sketch.secrets &&
sketch.secrets.length > 0
) {
return includeString + '\n' + data;
}
} else if (mode === 'remove') {
return data.replace(includeRegexp, '');
}
return data;
}
async readFile(posixPath: string): Promise<string> {
const basename = createPaths.basename(posixPath);
if (basename === Create.arduino_secrets_file) {
const parentPosixPath = createPaths.parentPosix(posixPath);
const sketch = await this.findSketchInCache(
this.sketchCompareByPath(parentPosixPath),
false
);
let file = '';
if (sketch && sketch.secrets) {
for (const item of sketch?.secrets) {
file += `#define ${item.name} "${item.value}"\r\n`;
}
}
return file;
}
const url = new URL(
`${this.domain()}/files/f/$HOME/sketches_v2${posixPath}`
);
const headers = await this.headers();
const result = await this.run<{ data: string; path: string }>(url, {
method: 'GET',
headers,
});
let { data } = result;
// add includes to main arduino file
data = await this.toggleSecretsInclude(posixPath, atob(data), 'add');
return data;
}
async writeFile(
posixPath: string,
content: string | Uint8Array
): Promise<void> {
const basename = createPaths.basename(posixPath);
if (basename === Create.arduino_secrets_file) {
const parentPosixPath = createPaths.parentPosix(posixPath);
const sketch = await this.findSketchInCache(
this.sketchCompareByPath(parentPosixPath)
);
if (sketch) {
const url = new URL(`${this.domain()}/sketches/${sketch.id}`);
const headers = await this.headers();
// parse the secret file
const secrets = (
typeof content === 'string'
? content
: new TextDecoder().decode(content)
)
.split(/\r?\n/)
.reduce((prev, curr) => {
// check if the line contains a secret
const secret = curr.split('SECRET_')[1] || null;
if (!secret) {
return prev;
}
const regexp = /(\S*)\s+([\S\s]*)/g;
const tokens = regexp.exec(secret) || [];
const name =
tokens[1].length > 0 ? `SECRET_${tokens[1]}` : '';
let value = '';
if (tokens[2].length > 0) {
value = JSON.parse(
JSON.stringify(
tokens[2]
.replace(/^['"]?/g, '')
.replace(/['"]?$/g, '')
)
);
}
if (name.length === 0) {
return prev;
}
return [...prev, { name, value }];
}, []);
const payload = {
id: sketch.id,
libraries: sketch.libraries,
secrets: { data: secrets },
};
// replace the sketch in the cache, so other calls will not overwrite each other
sketchCache = sketchCache.filter((skt) => skt.id !== sketch.id);
sketchCache.push({ ...sketch, secrets });
const init = {
method: 'POST',
body: JSON.stringify(payload),
headers,
};
await this.run(url, init);
}
return;
}
const url = new URL(
`${this.domain()}/files/f/$HOME/sketches_v2${posixPath}`
);
const headers = await this.headers();
let data: string =
typeof content === 'string'
? content
: new TextDecoder().decode(content);
data = await this.toggleSecretsInclude(posixPath, data, 'remove');
const payload = { data: btoa(data) };
const init = {
method: 'POST',
body: JSON.stringify(payload),
headers,
};
await this.run(url, init);
}
async deleteFile(posixPath: string): Promise<void> {
await this.delete(posixPath, 'f');
}
async deleteDirectory(posixPath: string): Promise<void> {
await this.delete(posixPath, 'd');
}
private async delete(posixPath: string, type: ResourceType): Promise<void> {
const url = new URL(
`${this.domain()}/files/${type}/$HOME/sketches_v2${posixPath}`
);
const headers = await this.headers();
await this.run(url, {
method: 'DELETE',
headers,
});
}
async rename(fromPosixPath: string, toPosixPath: string): Promise<void> {
const url = new URL(`${this.domain('v3')}/files/mv`);
const headers = await this.headers();
const payload = {
from: `$HOME/sketches_v2${fromPosixPath}`,
to: `$HOME/sketches_v2${toPosixPath}`,
};
const init = {
method: 'POST',
body: JSON.stringify(payload),
headers,
};
await this.run(url, init, ResponseResultProvider.NOOP);
}
async editSketch({
id,
params,
}: {
id: string;
params: Record<string, unknown>;
}): Promise<Create.Sketch> {
const url = new URL(`${this.domain()}/sketches/${id}`);
const headers = await this.headers();
const result = await this.run<Create.Sketch>(url, {
method: 'POST',
body: JSON.stringify({ id, ...params }),
headers,
});
return result;
}
async copy(fromPosixPath: string, toPosixPath: string): Promise<void> {
const payload = {
from: `$HOME/sketches_v2${fromPosixPath}`,
to: `$HOME/sketches_v2${toPosixPath}`,
};
const url = new URL(`${this.domain('v3')}/files/cp`);
const headers = await this.headers();
const init = {
method: 'POST',
body: JSON.stringify(payload),
headers,
};
await this.run(url, init, ResponseResultProvider.NOOP);
}
private async run<T>(
requestInfo: RequestInfo | URL,
init: RequestInit | undefined,
resultProvider: ResponseResultProvider = ResponseResultProvider.JSON
): Promise<T> {
const response = await fetch(
requestInfo instanceof URL ? requestInfo.toString() : requestInfo,
init
);
if (!response.ok) {
let details: string | undefined = undefined;
try {
details = await response.json();
} catch (e) {
console.error('Cloud not get the error details.', e);
}
const { statusText, status } = response;
throw new CreateError(statusText, status, details);
}
const result = await resultProvider(response);
return result;
}
private async headers(): Promise<Record<string, string>> {
const token = await this.token();
return {
'content-type': 'application/json',
accept: 'application/json',
authorization: `Bearer ${token}`,
};
}
private domain(apiVersion = 'v2'): string {
const endpoint =
this.arduinoPreferences['arduino.cloud.sketchSyncEnpoint'];
return `${endpoint}/${apiVersion}`;
}
private async token(): Promise<string> {
return this.authenticationService.session?.accessToken || '';
}
}
export namespace CreateApi {
export const defaultInoContent = `/*
*/
void setup() {
}
void loop() {
}
`;
}
export namespace Create {
export interface Sketch {
readonly name: string;
readonly path: string;
readonly modified_at: string;
readonly created_at: string;
readonly secrets?: { name: string; value: string }[];
readonly id: string;
readonly is_public: boolean;
// readonly board_fqbn: '',
// readonly board_name: '',
// readonly board_type: 'serial' | 'network' | 'cloud' | '',
readonly href?: string;
readonly libraries: string[];
// readonly tutorials: string[] | null;
// readonly types: string[] | null;
// readonly user_id: string;
}
export type ResourceType = 'sketch' | 'folder' | 'file';
export const arduino_secrets_file = 'arduino_secrets.h';
export interface Resource {
readonly name: string;
/**
* Note: this path is **not** the POSIX path we use. It has the leading segments with the `user_id`.
*/
readonly path: string;
readonly type: ResourceType;
readonly sketchId: string;
readonly modified_at: string; // As an ISO-8601 formatted string: `YYYY-MM-DDTHH:mm:ss.sssZ`
readonly children?: number; // For 'sketch' and 'folder' types.
readonly size?: number; // For 'sketch' type only.
readonly isPublic?: boolean; // For 'sketch' type only.
readonly mimetype?: string; // For 'file' type.
readonly href?: string;
}
export namespace Resource {
export function is(arg: any): arg is Resource {
return (
!!arg &&
'name' in arg &&
typeof arg['name'] === 'string' &&
'path' in arg &&
typeof arg['path'] === 'string' &&
'type' in arg &&
typeof arg['type'] === 'string' &&
'modified_at' in arg &&
typeof arg['modified_at'] === 'string' &&
(arg['type'] === 'sketch' ||
arg['type'] === 'folder' ||
arg['type'] === 'file')
);
}
}
export type RawResource = Omit<Resource, 'sketchId' | 'isPublic'>;
}
export class CreateError extends Error {
constructor(
message: string,
readonly status: number,
readonly details?: string
) {
super(message);
Object.setPrototypeOf(this, CreateError.prototype);
}
}

View File

@@ -0,0 +1,208 @@
import { inject, injectable } from 'inversify';
import URI from '@theia/core/lib/common/uri';
import { Event } from '@theia/core/lib/common/event';
import {
Disposable,
DisposableCollection,
} from '@theia/core/lib/common/disposable';
import { FrontendApplicationContribution } from '@theia/core/lib/browser/frontend-application';
import {
Stat,
FileType,
FileChange,
FileWriteOptions,
FileDeleteOptions,
FileOverwriteOptions,
FileSystemProvider,
FileSystemProviderError,
FileSystemProviderErrorCode,
FileSystemProviderCapabilities,
WatchOptions,
} from '@theia/filesystem/lib/common/files';
import {
FileService,
FileServiceContribution,
} from '@theia/filesystem/lib/browser/file-service';
import { AuthenticationClientService } from '../auth/authentication-client-service';
import { Create, CreateApi } from './create-api';
import { CreateUri } from './create-uri';
import { SketchesService } from '../../common/protocol';
import { ArduinoPreferences } from '../arduino-preferences';
export const REMOTE_ONLY_FILES = ['sketch.json'];
@injectable()
export class CreateFsProvider
implements
FileSystemProvider,
FrontendApplicationContribution,
FileServiceContribution
{
@inject(AuthenticationClientService)
protected readonly authenticationService: AuthenticationClientService;
@inject(CreateApi)
protected readonly createApi: CreateApi;
@inject(SketchesService)
protected readonly sketchesService: SketchesService;
@inject(ArduinoPreferences)
protected readonly arduinoPreferences: ArduinoPreferences;
protected readonly toDispose = new DisposableCollection();
readonly onFileWatchError: Event<void> = Event.None;
readonly onDidChangeFile: Event<readonly FileChange[]> = Event.None;
readonly onDidChangeCapabilities: Event<void> = Event.None;
readonly capabilities: FileSystemProviderCapabilities =
FileSystemProviderCapabilities.FileReadWrite |
FileSystemProviderCapabilities.PathCaseSensitive |
FileSystemProviderCapabilities.Access;
onStop(): void {
this.toDispose.dispose();
}
registerFileSystemProviders(service: FileService): void {
service.onWillActivateFileSystemProvider((event) => {
if (event.scheme === CreateUri.scheme) {
event.waitUntil(
(async () => {
service.registerProvider(CreateUri.scheme, this);
})()
);
}
});
}
watch(uri: URI, opts: WatchOptions): Disposable {
return Disposable.NULL;
}
async stat(uri: URI): Promise<Stat> {
if (CreateUri.equals(CreateUri.root, uri)) {
this.getCreateApi; // This will throw when not logged in.
return {
type: FileType.Directory,
ctime: 0,
mtime: 0,
size: 0,
};
}
const resource = await this.getCreateApi.stat(uri.path.toString());
const mtime = Date.parse(resource.modified_at);
return {
type: this.toFileType(resource.type),
ctime: mtime,
mtime,
size: 0,
};
}
async mkdir(uri: URI): Promise<void> {
await this.getCreateApi.createDirectory(uri.path.toString());
}
async readdir(uri: URI): Promise<[string, FileType][]> {
const resources = await this.getCreateApi.readDirectory(
uri.path.toString(),
{
secrets: true,
}
);
return resources
.filter((res) => !REMOTE_ONLY_FILES.includes(res.name))
.map(({ name, type }) => [name, this.toFileType(type)]);
}
async delete(uri: URI, opts: FileDeleteOptions): Promise<void> {
return;
if (!opts.recursive) {
throw new Error(
'Arduino Create file-system provider does not support non-recursive deletion.'
);
}
const stat = await this.stat(uri);
if (!stat) {
throw new FileSystemProviderError(
'File not found.',
FileSystemProviderErrorCode.FileNotFound
);
}
switch (stat.type) {
case FileType.Directory: {
await this.getCreateApi.deleteDirectory(uri.path.toString());
break;
}
case FileType.File: {
await this.getCreateApi.deleteFile(uri.path.toString());
break;
}
default: {
throw new FileSystemProviderError(
`Unexpected file type '${
stat.type
}' for resource: ${uri.toString()}`,
FileSystemProviderErrorCode.Unknown
);
}
}
}
async rename(
oldUri: URI,
newUri: URI,
options: FileOverwriteOptions
): Promise<void> {
await this.getCreateApi.rename(
oldUri.path.toString(),
newUri.path.toString()
);
}
async readFile(uri: URI): Promise<Uint8Array> {
const content = await this.getCreateApi.readFile(uri.path.toString());
return new TextEncoder().encode(content);
}
async writeFile(
uri: URI,
content: Uint8Array,
options: FileWriteOptions
): Promise<void> {
await this.getCreateApi.writeFile(uri.path.toString(), content);
}
async access(uri: URI, mode?: number): Promise<void> {
this.getCreateApi; // Will throw if not logged in.
}
public toFileType(type: Create.ResourceType): FileType {
switch (type) {
case 'file':
return FileType.File;
case 'sketch':
case 'folder':
return FileType.Directory;
default:
return FileType.Unknown;
}
}
private get getCreateApi(): CreateApi {
const { session } = this.authenticationService;
if (!session) {
throw new FileSystemProviderError(
'Not logged in.',
FileSystemProviderErrorCode.NoPermissions
);
}
return this.createApi.init(
this.authenticationService,
this.arduinoPreferences
);
}
}

View File

@@ -0,0 +1,59 @@
export const posix = { sep: '/' };
// TODO: poor man's `path.join(path, '..')` in the browser.
export function parentPosix(path: string): string {
const segments = path.split(posix.sep) || [];
segments.pop();
let modified = segments.join(posix.sep);
if (path.charAt(path.length - 1) === posix.sep) {
modified += posix.sep;
}
return modified;
}
export function basename(path: string): string {
const segments = path.split(posix.sep) || [];
return segments.pop()!;
}
export function posixSegments(posixPath: string): string[] {
return posixPath.split(posix.sep).filter((segment) => !!segment);
}
/**
* Splits the `raw` path into two segments, a root that contains user information and the relevant POSIX path. \
* For examples:
* ```
* `29ad0829759028dde9b877343fa3b0e1:testrest/sketches_v2/xxx_folder/xxx_sub_folder/sketch_in_folder/sketch_in_folder.ino`
* ```
* will be:
* ```
* ['29ad0829759028dde9b877343fa3b0e1:testrest/sketches_v2', '/xxx_folder/xxx_sub_folder/sketch_in_folder/sketch_in_folder.ino']
* ```
*/
export function splitSketchPath(
raw: string,
sep = '/sketches_v2/'
): [string, string] {
if (!sep) {
throw new Error('Invalid separator. Cannot be zero length.');
}
const index = raw.indexOf(sep);
if (index === -1) {
throw new Error(`Invalid path pattern. Raw path was '${raw}'.`);
}
const createRoot = raw.substring(0, index + sep.length - 1); // TODO: validate the `createRoot` format.
const posixPath = raw.substr(index + sep.length - 1);
if (!posixPath) {
throw new Error(`Could not extract POSIX path from '${raw}'.`);
}
return [createRoot, posixPath];
}
export function toPosixPath(raw: string): string {
if (raw === posix.sep) {
return posix.sep; // Handles the root resource case.
}
const [, posixPath] = splitSketchPath(raw);
return posixPath;
}

View File

@@ -0,0 +1,39 @@
import { URI as Uri } from 'vscode-uri';
import URI from '@theia/core/lib/common/uri';
import { Create } from './create-api';
import { toPosixPath, parentPosix, posix } from './create-paths';
export namespace CreateUri {
export const scheme = 'arduino-create';
export const root = toUri(posix.sep);
export function toUri(posixPathOrResource: string | Create.Resource): URI {
const posixPath =
typeof posixPathOrResource === 'string'
? posixPathOrResource
: toPosixPath(posixPathOrResource.path);
return new URI(
Uri.parse(posixPath).with({ scheme, authority: 'create' })
);
}
export function is(uri: URI): boolean {
return uri.scheme === scheme;
}
export function equals(left: URI, right: URI): boolean {
return is(left) && is(right) && left.toString() === right.toString();
}
export function parent(uri: URI): URI {
if (!is(uri)) {
throw new Error(
`Invalid URI scheme. Expected '${scheme}' got '${uri.scheme}' instead.`
);
}
if (equals(uri, root)) {
return uri;
}
return toUri(parentPosix(uri.path.toString()));
}
}

View File

@@ -28,7 +28,8 @@
"scope": [
"meta.function.c",
"entity.name.function",
"meta.function-call.c"
"meta.function-call.c",
"variable.other"
],
"settings": {
"foreground": "#D35400"
@@ -42,16 +43,19 @@
"meta.block.c",
"meta.function.c",
"entity.name.function.preprocessor.c",
"meta.preprocessor.macro.c"
"meta.preprocessor.macro.c",
"variable",
"variable.name"
],
"settings": {
"foreground": "#434f54"
}
},
{
"name": "strings",
"name": "constants",
"scope": [
"string.quoted.double"
"string.quoted.double",
"constant"
],
"settings": {
"foreground": "#005C5F"
@@ -81,7 +85,12 @@
],
"colors": {
"list.highlightForeground": "#005c5f",
"list.activeSelectionBackground": "#005c5f",
"list.activeSelectionForeground": "#424242",
"list.activeSelectionBackground": "#DAE3E3",
"list.inactiveSelectionForeground": "#424242",
"list.inactiveSelectionBackground": "#DAE3E3",
"list.hoverBackground": "#ECF1F1",
"progressBar.background": "#005c5f",
"editor.background": "#ffffff",
"editorCursor.foreground": "#434f54",
"editor.foreground": "#434f54",
@@ -105,6 +114,7 @@
"activityBar.foreground": "#616161",
"statusBar.background": "#005c5f",
"secondaryButton.background": "#b5c8c9",
"secondaryButton.foreground": "#ececec",
"secondaryButton.hoverBackground": "#dae3e3",
"arduino.branding.primary": "#00979d",
"arduino.branding.secondary": "#b5c8c9",

View File

@@ -0,0 +1,175 @@
import * as React from 'react';
import { inject, injectable } from 'inversify';
import { Widget } from '@phosphor/widgets';
import { Message } from '@phosphor/messaging';
import { clipboard } from 'electron';
import {
AbstractDialog,
ReactWidget,
DialogProps,
} from '@theia/core/lib/browser';
import { CreateApi } from '../create/create-api';
const RadioButton = (props: {
id: string;
changed: (evt: React.BaseSyntheticEvent) => void;
value: string;
isSelected: boolean;
isDisabled: boolean;
label: string;
}) => {
return (
<p className="RadioButton">
<input
id={props.id}
onChange={props.changed}
value={props.value}
type="radio"
checked={props.isSelected}
disabled={props.isDisabled}
/>
<label htmlFor={props.id}>{props.label}</label>
</p>
);
};
export const ShareSketchComponent = ({
treeNode,
createApi,
domain = 'https://create.arduino.cc',
}: {
treeNode: any;
createApi: CreateApi;
domain?: string;
}): React.ReactElement => {
// const [publicVisibility, setPublicVisibility] = React.useState<boolean>(
// treeNode.isPublic
// );
const [loading, setloading] = React.useState<boolean>(false);
const radioChangeHandler = async (event: React.BaseSyntheticEvent) => {
setloading(true);
const sketch = await createApi.editSketch({
id: treeNode.sketchId,
params: {
is_public: event.target.value === 'private' ? false : true,
},
});
// setPublicVisibility(sketch.is_public);
treeNode.isPublic = sketch.is_public;
setloading(false);
};
const sketchLink = `${domain}/editor/_/${treeNode.sketchId}/preview`;
const embedLink = `<iframe src="${sketchLink}?embed" style="height:510px;width:100%;margin:10px 0" frameborder=0></iframe>`;
return (
<div id="widget-container arduino-sharesketch-dialog">
<p>Choose visibility of your Sketch:</p>
<RadioButton
changed={radioChangeHandler}
id="1"
isSelected={treeNode.isPublic === false}
label="Private. Only you can view the Sketch."
value="private"
isDisabled={loading}
/>
<RadioButton
changed={radioChangeHandler}
id="2"
isSelected={treeNode.isPublic === true}
label="Public. Anyone with the link can view the Sketch."
value="public"
isDisabled={loading}
/>
{treeNode.isPublic && (
<div>
<p>Link:</p>
<div className="sketch-link">
<input
type="text"
readOnly
value={sketchLink}
className="theia-input"
/>
<button
onClick={() => clipboard.writeText(sketchLink)}
value="copy"
className="theia-button secondary"
>
Copy
</button>
</div>
<p>Embed:</p>
<div className="sketch-link-embed">
<textarea
readOnly
value={embedLink}
className="theia-input stretch"
/>
</div>
</div>
)}
</div>
);
};
@injectable()
export class ShareSketchWidget extends ReactWidget {
constructor(private treeNode: any, private createApi: CreateApi) {
super();
}
protected render(): React.ReactNode {
return (
<ShareSketchComponent
treeNode={this.treeNode}
createApi={this.createApi}
/>
);
}
}
@injectable()
export class ShareSketchDialogProps extends DialogProps {
readonly node: any;
readonly createApi: CreateApi;
}
@injectable()
export class ShareSketchDialog extends AbstractDialog<void> {
protected widget: ShareSketchWidget;
constructor(
@inject(ShareSketchDialogProps)
protected readonly props: ShareSketchDialogProps
) {
super({ title: props.title });
this.contentNode.classList.add('arduino-share-sketch-dialog');
this.widget = new ShareSketchWidget(props.node, props.createApi);
}
get value(): void {
return;
}
protected onAfterAttach(msg: Message): void {
if (this.widget.isAttached) {
Widget.detach(this.widget);
}
Widget.attach(this.widget, this.contentNode);
super.onAfterAttach(msg);
this.update();
}
protected onUpdateRequest(msg: Message): void {
super.onUpdateRequest(msg);
this.widget.update();
}
protected onActivateRequest(msg: Message): void {
super.onActivateRequest(msg);
this.widget.activate();
}
}

View File

@@ -0,0 +1,69 @@
import { inject, injectable } from 'inversify';
import { Widget } from '@phosphor/widgets';
import { CancellationTokenSource } from '@theia/core/lib/common/cancellation';
import {
ConfirmDialog,
ConfirmDialogProps,
DialogError,
} from '@theia/core/lib/browser/dialogs';
@injectable()
export class DoNotAskAgainConfirmDialogProps extends ConfirmDialogProps {
readonly onAccept: () => Promise<void>;
}
@injectable()
export class DoNotAskAgainConfirmDialog extends ConfirmDialog {
protected readonly doNotAskAgainCheckbox: HTMLInputElement;
constructor(
@inject(DoNotAskAgainConfirmDialogProps)
protected readonly props: DoNotAskAgainConfirmDialogProps
) {
super(props);
this.controlPanel.removeChild(this.errorMessageNode);
const doNotAskAgainNode = document.createElement('div');
doNotAskAgainNode.setAttribute('style', 'flex: 2');
this.controlPanel.insertBefore(
doNotAskAgainNode,
this.controlPanel.firstChild
);
const doNotAskAgainLabel = document.createElement('label');
doNotAskAgainLabel.classList.add('flex-line');
doNotAskAgainNode.appendChild(doNotAskAgainLabel);
doNotAskAgainLabel.textContent = "Don't ask again";
this.doNotAskAgainCheckbox = document.createElement('input');
this.doNotAskAgainCheckbox.setAttribute('align-self', 'center');
doNotAskAgainLabel.appendChild(this.doNotAskAgainCheckbox);
this.doNotAskAgainCheckbox.type = 'checkbox';
}
protected async accept(): Promise<void> {
if (!this.resolve) {
return;
}
this.acceptCancellationSource.cancel();
this.acceptCancellationSource = new CancellationTokenSource();
const token = this.acceptCancellationSource.token;
const value = this.value;
const error = await this.isValid(value, 'open');
if (token.isCancellationRequested) {
return;
}
if (!DialogError.getResult(error)) {
this.setErrorMessage(error);
} else {
if (this.doNotAskAgainCheckbox.checked) {
await this.props.onAccept();
}
this.resolve(value);
Widget.detach(this);
}
}
protected setErrorMessage(error: DialogError): void {
if (this.acceptButton) {
this.acceptButton.disabled = !DialogError.getResult(error);
}
}
}

View File

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

View File

@@ -2,21 +2,24 @@ import { injectable, postConstruct, inject } from 'inversify';
import { Message } from '@phosphor/messaging';
import { addEventListener } from '@theia/core/lib/browser/widgets/widget';
import { AbstractDialog, DialogProps } from '@theia/core/lib/browser/dialogs';
import { LibraryPackage, LibraryService } from '../../common/protocol/library-service';
import {
LibraryPackage,
LibraryService,
} from '../../common/protocol/library-service';
import { ListWidget } from '../widgets/component-list/list-widget';
import { Installable } from '../../common/protocol';
import { ListItemRenderer } from '../widgets/component-list/list-item-renderer';
@injectable()
export class LibraryListWidget extends ListWidget<LibraryPackage> {
static WIDGET_ID = 'library-list-widget';
static WIDGET_LABEL = 'Library Manager';
constructor(
@inject(LibraryService) protected service: LibraryService,
@inject(ListItemRenderer) protected itemRenderer: ListItemRenderer<LibraryPackage>) {
@inject(ListItemRenderer)
protected itemRenderer: ListItemRenderer<LibraryPackage>
) {
super({
id: LibraryListWidget.WIDGET_ID,
label: LibraryListWidget.WIDGET_LABEL,
@@ -24,7 +27,8 @@ export class LibraryListWidget extends ListWidget<LibraryPackage> {
searchable: service,
installable: service,
itemLabel: (item: LibraryPackage) => item.name,
itemRenderer
itemDeprecated: (item: LibraryPackage) => item.deprecated,
itemRenderer,
});
}
@@ -32,17 +36,39 @@ export class LibraryListWidget extends ListWidget<LibraryPackage> {
protected init(): void {
super.init();
this.toDispose.pushAll([
this.notificationCenter.onLibraryInstalled(() => this.refresh(undefined)),
this.notificationCenter.onLibraryUninstalled(() => this.refresh(undefined)),
this.notificationCenter.onLibraryInstalled(() =>
this.refresh(undefined)
),
this.notificationCenter.onLibraryUninstalled(() =>
this.refresh(undefined)
),
]);
}
protected async install({ item, version }: { item: LibraryPackage, version: Installable.Version }): Promise<void> {
const dependencies = await this.service.listDependencies({ item, version, filterSelf: true });
protected async install({
item,
progressId,
version,
}: {
item: LibraryPackage;
progressId: string;
version: Installable.Version;
}): Promise<void> {
const dependencies = await this.service.listDependencies({
item,
version,
filterSelf: true,
});
let installDependencies: boolean | undefined = undefined;
if (dependencies.length) {
const message = document.createElement('div');
message.innerHTML = `The library <b>${item.name}:${version}</b> needs ${dependencies.length === 1 ? 'another dependency' : 'some other dependencies'} currently not installed:`;
message.innerHTML = `The library <b>${
item.name
}:${version}</b> needs ${
dependencies.length === 1
? 'another dependency'
: 'some other dependencies'
} currently not installed:`;
const listContainer = document.createElement('div');
listContainer.style.maxHeight = '300px';
listContainer.style.overflowY = 'auto';
@@ -57,24 +83,26 @@ export class LibraryListWidget extends ListWidget<LibraryPackage> {
listContainer.appendChild(list);
message.appendChild(listContainer);
const question = document.createElement('div');
question.textContent = `Would you like to install ${dependencies.length === 1 ? 'the missing dependency' : 'all the missing dependencies'}?`;
question.textContent = `Would you like to install ${
dependencies.length === 1
? 'the missing dependency'
: 'all the missing dependencies'
}?`;
message.appendChild(question);
const result = await new MessageBoxDialog({
title: `Dependencies for library ${item.name}:${version}`,
message,
buttons: [
'Install all',
`Install ${item.name} only`,
'Cancel'
],
maxWidth: 740 // Aligned with `settings-dialog.css`.
buttons: ['Install all', `Install ${item.name} only`, 'Cancel'],
maxWidth: 740, // Aligned with `settings-dialog.css`.
}).open();
if (result) {
const { response } = result;
if (response === 0) { // All
if (response === 0) {
// All
installDependencies = true;
} else if (response === 1) { // Current only
} else if (response === 1) {
// Current only
installDependencies = false;
}
}
@@ -84,27 +112,52 @@ export class LibraryListWidget extends ListWidget<LibraryPackage> {
}
if (typeof installDependencies === 'boolean') {
return this.service.install({ item, version, installDependencies });
await this.service.install({
item,
version,
progressId,
installDependencies,
});
this.messageService.info(
`Successfully installed library ${item.name}:${version}`,
{ timeout: 3000 }
);
}
}
protected async uninstall({
item,
progressId,
}: {
item: LibraryPackage;
progressId: string;
}): Promise<void> {
await super.uninstall({ item, progressId });
this.messageService.info(
`Successfully uninstalled library ${item.name}:${item.installedVersion}`,
{ timeout: 3000 }
);
}
}
class MessageBoxDialog extends AbstractDialog<MessageBoxDialog.Result> {
protected response: number;
constructor(protected readonly options: MessageBoxDialog.Options) {
super(options);
this.contentNode.appendChild(this.createMessageNode(this.options.message));
this.contentNode.appendChild(
this.createMessageNode(this.options.message)
);
(options.buttons || ['OK']).forEach((text, index) => {
const button = this.createButton(text);
button.classList.add(index === 0 ? 'main' : 'secondary');
this.controlPanel.appendChild(button);
this.toDisposeOnDetach.push(addEventListener(button, 'click', () => {
this.response = index;
this.accept();
}));
this.toDisposeOnDetach.push(
addEventListener(button, 'click', () => {
this.response = index;
this.accept();
})
);
});
}
@@ -130,7 +183,6 @@ class MessageBoxDialog extends AbstractDialog<MessageBoxDialog.Result> {
this.response = 0;
super.handleEnter(event);
}
}
export namespace MessageBoxDialog {
export interface Options extends DialogProps {

View File

@@ -6,18 +6,20 @@ import { LibraryListWidget } from './library-list-widget';
import { ArduinoMenus } from '../menu/arduino-menus';
@injectable()
export class LibraryListWidgetFrontendContribution extends AbstractViewContribution<LibraryListWidget> implements FrontendApplicationContribution {
export class LibraryListWidgetFrontendContribution
extends AbstractViewContribution<LibraryListWidget>
implements FrontendApplicationContribution
{
constructor() {
super({
widgetId: LibraryListWidget.WIDGET_ID,
widgetName: LibraryListWidget.WIDGET_LABEL,
defaultWidgetOptions: {
area: 'left',
rank: 3
rank: 3,
},
toggleCommandId: `${LibraryListWidget.WIDGET_ID}:toggle`,
toggleKeybinding: 'CtrlCmd+Shift+I'
toggleKeybinding: 'CtrlCmd+Shift+I',
});
}
@@ -30,9 +32,8 @@ export class LibraryListWidgetFrontendContribution extends AbstractViewContribut
menus.registerMenuAction(ArduinoMenus.TOOLS__MAIN_GROUP, {
commandId: this.toggleCommand.id,
label: 'Manage Libraries...',
order: '3'
order: '3',
});
}
}
}

View File

@@ -0,0 +1,167 @@
import { inject, injectable } from 'inversify';
import { URI as Uri } from 'vscode-uri';
import URI from '@theia/core/lib/common/uri';
import { Deferred } from '@theia/core/lib/common/promise-util';
import {
FileSystemProvider,
FileSystemProviderError,
FileSystemProviderErrorCode,
} from '@theia/filesystem/lib/common/files';
import { DisposableCollection } from '@theia/core/lib/common/disposable';
import { DelegatingFileSystemProvider } from '@theia/filesystem/lib/common/delegating-file-system-provider';
import {
FileService,
FileServiceContribution,
} from '@theia/filesystem/lib/browser/file-service';
import { AuthenticationClientService } from '../auth/authentication-client-service';
import { AuthenticationSession } from '../../common/protocol/authentication-service';
import { ConfigService } from '../../common/protocol';
export namespace LocalCacheUri {
export const scheme = 'arduino-local-cache';
export const root = new URI(
Uri.parse('/').with({ scheme, authority: 'create' })
);
}
@injectable()
export class LocalCacheFsProvider
implements
FileServiceContribution,
DelegatingFileSystemProvider.URIConverter
{
@inject(ConfigService)
protected readonly configService: ConfigService;
@inject(AuthenticationClientService)
protected readonly authenticationService: AuthenticationClientService;
// TODO: do we need this? Cannot we `await` on the `init` call from `registerFileSystemProviders`?
readonly ready = new Deferred<void>();
private _localCacheRoot: URI;
registerFileSystemProviders(fileService: FileService): void {
fileService.onWillActivateFileSystemProvider(async (event) => {
if (event.scheme === LocalCacheUri.scheme) {
event.waitUntil(
(async () => {
this.init(fileService);
const provider = await this.createProvider(fileService);
fileService.registerProvider(
LocalCacheUri.scheme,
provider
);
})()
);
}
});
}
to(resource: URI): URI | undefined {
const relativePath = LocalCacheUri.root.relative(resource);
if (relativePath) {
return this.currentUserUri.resolve(relativePath).normalizePath();
}
return undefined;
}
from(resource: URI): URI | undefined {
const relativePath = this.currentUserUri.relative(resource);
if (relativePath) {
return LocalCacheUri.root.resolve(relativePath);
}
return undefined;
}
protected async createProvider(
fileService: FileService
): Promise<FileSystemProvider> {
const delegate = await fileService.activateProvider('file');
await this.ready.promise;
return new DelegatingFileSystemProvider(
delegate,
{
uriConverter: this,
},
new DisposableCollection(
delegate.watch(this.localCacheRoot, {
excludes: [],
recursive: true,
})
)
);
}
protected async init(fileService: FileService): Promise<void> {
const config = await this.configService.getConfiguration();
this._localCacheRoot = new URI(config.dataDirUri);
for (const segment of ['RemoteSketchbook', 'ArduinoCloud']) {
this._localCacheRoot = this._localCacheRoot.resolve(segment);
await fileService.createFolder(this._localCacheRoot);
}
this.session(fileService).then(() => this.ready.resolve());
this.authenticationService.onSessionDidChange(async (session) => {
if (session) {
await this.ensureExists(session, fileService);
}
});
}
private get currentUserUri(): URI {
const { session } = this.authenticationService;
if (!session) {
throw new FileSystemProviderError(
'Not logged in.',
FileSystemProviderErrorCode.NoPermissions
);
}
return this.toUri(session);
}
private get localCacheRoot(): URI {
return this._localCacheRoot;
}
private async session(
fileService: FileService
): Promise<AuthenticationSession> {
return new Promise<AuthenticationSession>(async (resolve) => {
const { session } = this.authenticationService;
if (session) {
await this.ensureExists(session, fileService);
resolve(session);
return;
}
const toDispose = new DisposableCollection();
toDispose.push(
this.authenticationService.onSessionDidChange(
async (session) => {
if (session) {
await this.ensureExists(session, fileService);
toDispose.dispose();
resolve(session);
}
}
)
);
});
}
private async ensureExists(
session: AuthenticationSession,
fileService: FileService
): Promise<URI> {
const uri = this.toUri(session);
const exists = await fileService.exists(uri);
if (!exists) {
await fileService.createFolder(uri);
}
return uri;
}
private toUri(session: AuthenticationSession): URI {
// Hack: instead of getting the UUID only, we get `auth0|UUID` after the authentication. `|` cannot be part of filesystem path or filename.
return this._localCacheRoot.resolve(session.id.split('|')[1]);
}
}

View File

@@ -1,37 +1,82 @@
import { isOSX } from '@theia/core/lib/common/os';
import { CommonMenus } from '@theia/core/lib/browser/common-frontend-contribution';
import { MAIN_MENU_BAR, MenuModelRegistry, MenuNode, MenuPath, SubMenuOptions } from '@theia/core/lib/common/menu';
import {
MAIN_MENU_BAR,
MenuModelRegistry,
MenuNode,
MenuPath,
SubMenuOptions,
} from '@theia/core/lib/common/menu';
export namespace ArduinoMenus {
// Main menu
// -- File
export const FILE__SKETCH_GROUP = [...CommonMenus.FILE, '0_sketch'];
export const FILE__PRINT_GROUP = [...CommonMenus.FILE, '1_print'];
// XXX: on macOS, the settings group is not under `File`
export const FILE__SETTINGS_GROUP = [...(isOSX ? MAIN_MENU_BAR : CommonMenus.FILE), '2_settings'];
// XXX: on macOS, the "Preferences" and "Advanced" group is not under `File`
// The empty path ensures no top level menu is created for the preferences, even if they contains sub menus
export const FILE__PREFERENCES_GROUP = [
...(isOSX ? [''] : CommonMenus.FILE),
'2_preferences',
];
export const FILE__ADVANCED_GROUP = [
...(isOSX ? [''] : CommonMenus.FILE),
'3_advanced',
];
export const FILE__ADVANCED_SUBMENU = [
...FILE__ADVANCED_GROUP,
'0_advanced_sub',
];
export const FILE__QUIT_GROUP = [...CommonMenus.FILE, '3_quit'];
// -- File / Open Recent
export const FILE__OPEN_RECENT_SUBMENU = [...FILE__SKETCH_GROUP, '0_open_recent'];
export const FILE__OPEN_RECENT_SUBMENU = [
...FILE__SKETCH_GROUP,
'0_open_recent',
];
// -- File / Sketchbook
export const FILE__SKETCHBOOK_SUBMENU = [...FILE__SKETCH_GROUP, '1_sketchbook'];
export const FILE__SKETCHBOOK_SUBMENU = [
...FILE__SKETCH_GROUP,
'1_sketchbook',
];
// -- File / Examples
export const FILE__EXAMPLES_SUBMENU = [...FILE__SKETCH_GROUP, '2_examples'];
export const EXAMPLES__BUILT_IN_GROUP = [...FILE__EXAMPLES_SUBMENU, '0_built_ins'];
export const EXAMPLES__ANY_BOARD_GROUP = [...FILE__EXAMPLES_SUBMENU, '1_any_board'];
export const EXAMPLES__CURRENT_BOARD_GROUP = [...FILE__EXAMPLES_SUBMENU, '2_current_board'];
export const EXAMPLES__USER_LIBS_GROUP = [...FILE__EXAMPLES_SUBMENU, '3_user_libs'];
export const EXAMPLES__BUILT_IN_GROUP = [
...FILE__EXAMPLES_SUBMENU,
'0_built_ins',
];
export const EXAMPLES__ANY_BOARD_GROUP = [
...FILE__EXAMPLES_SUBMENU,
'1_any_board',
];
export const EXAMPLES__CURRENT_BOARD_GROUP = [
...FILE__EXAMPLES_SUBMENU,
'2_current_board',
];
export const EXAMPLES__USER_LIBS_GROUP = [
...FILE__EXAMPLES_SUBMENU,
'3_user_libs',
];
// -- Edit
// `Copy`, `Copy to Forum`, `Paste`, etc.
// Note: `1_undo` is the first group from Theia, we start with `2`
export const EDIT__TEXT_CONTROL_GROUP = [...CommonMenus.EDIT, '2_text_control'];
export const EDIT__TEXT_CONTROL_GROUP = [
...CommonMenus.EDIT,
'2_text_control',
];
// `Comment/Uncomment`, etc.
export const EDIT__CODE_CONTROL_GROUP = [...CommonMenus.EDIT, '3_code_control'];
export const EDIT__FONT_CONTROL_GROUP = [...CommonMenus.EDIT, '4_font_control'];
export const EDIT__CODE_CONTROL_GROUP = [
...CommonMenus.EDIT,
'3_code_control',
];
export const EDIT__FONT_CONTROL_GROUP = [
...CommonMenus.EDIT,
'4_font_control',
];
export const EDIT__FIND_GROUP = [...CommonMenus.EDIT, '5_find'];
// -- Sketch
@@ -58,35 +103,62 @@ export namespace ArduinoMenus {
export const HELP__CONTROL_GROUP = [...CommonMenus.HELP, '2_control'];
// `About` group
// XXX: on macOS, the about group is not under `Help`
export const HELP__ABOUT_GROUP = [...(isOSX ? MAIN_MENU_BAR : CommonMenus.HELP), '999_about'];
export const HELP__ABOUT_GROUP = [
...(isOSX ? MAIN_MENU_BAR : CommonMenus.HELP),
'999_about',
];
// ------------
// Context menus
// -- Open
export const OPEN_SKETCH__CONTEXT = ['arduino-open-sketch--context'];
export const OPEN_SKETCH__CONTEXT__OPEN_GROUP = [...OPEN_SKETCH__CONTEXT, '0_open'];
export const OPEN_SKETCH__CONTEXT__RECENT_GROUP = [...OPEN_SKETCH__CONTEXT, '1_recent'];
export const OPEN_SKETCH__CONTEXT__EXAMPLES_GROUP = [...OPEN_SKETCH__CONTEXT, '2_examples'];
export const OPEN_SKETCH__CONTEXT__OPEN_GROUP = [
...OPEN_SKETCH__CONTEXT,
'0_open',
];
export const OPEN_SKETCH__CONTEXT__RECENT_GROUP = [
...OPEN_SKETCH__CONTEXT,
'1_recent',
];
export const OPEN_SKETCH__CONTEXT__EXAMPLES_GROUP = [
...OPEN_SKETCH__CONTEXT,
'2_examples',
];
// -- Sketch control
export const SKETCH_CONTROL__CONTEXT = ['arduino-sketch-control--context'];
// `New Tab`, `Rename`, `Delete`
export const SKETCH_CONTROL__CONTEXT__MAIN_GROUP = [...SKETCH_CONTROL__CONTEXT, '0_main'];
export const SKETCH_CONTROL__CONTEXT__MAIN_GROUP = [
...SKETCH_CONTROL__CONTEXT,
'0_main',
];
// `Previous Tab`, `Next Tab`
export const SKETCH_CONTROL__CONTEXT__NAVIGATION_GROUP = [...SKETCH_CONTROL__CONTEXT, '1_navigation'];
export const SKETCH_CONTROL__CONTEXT__NAVIGATION_GROUP = [
...SKETCH_CONTROL__CONTEXT,
'1_navigation',
];
// Sketch files opened in editors
export const SKETCH_CONTROL__CONTEXT__RESOURCES_GROUP = [...SKETCH_CONTROL__CONTEXT, '2_resources'];
export const SKETCH_CONTROL__CONTEXT__RESOURCES_GROUP = [
...SKETCH_CONTROL__CONTEXT,
'2_resources',
];
}
/**
* This is a hack. It removes a submenu with all its children if any.
* Theia cannot dispose submenu entries with a proper API: https://github.com/eclipse-theia/theia/issues/7299
*/
export function unregisterSubmenu(menuPath: string[], menuRegistry: MenuModelRegistry): void {
export function unregisterSubmenu(
menuPath: string[],
menuRegistry: MenuModelRegistry
): void {
if (menuPath.length < 2) {
throw new Error(`Expected at least two item as a menu-path. Got ${JSON.stringify(menuPath)} instead.`);
throw new Error(
`Expected at least two item as a menu-path. Got ${JSON.stringify(
menuPath
)} instead.`
);
}
const toRemove = menuPath[menuPath.length - 1];
const parentMenuPath = menuPath.slice(0, menuPath.length - 1);
@@ -95,7 +167,9 @@ export function unregisterSubmenu(menuPath: string[], menuRegistry: MenuModelReg
const parent = menuRegistry.getMenu(parentMenuPath);
const index = parent.children.findIndex(({ id }) => id === toRemove);
if (index === -1) {
throw new Error(`Could not find menu with menu-path: ${JSON.stringify(menuPath)}.`);
throw new Error(
`Could not find menu with menu-path: ${JSON.stringify(menuPath)}.`
);
}
(parent.children as Array<MenuNode>).splice(index, 1);
}
@@ -104,8 +178,11 @@ export function unregisterSubmenu(menuPath: string[], menuRegistry: MenuModelReg
* Special menu node that is not backed by any commands and is always disabled.
*/
export class PlaceholderMenuNode implements MenuNode {
constructor(protected readonly menuPath: MenuPath, readonly label: string, protected options: SubMenuOptions = { order: '0' }) { }
constructor(
protected readonly menuPath: MenuPath,
readonly label: string,
protected options: SubMenuOptions = { order: '0' }
) {}
get icon(): string | undefined {
return this.options?.iconClass;
@@ -118,5 +195,4 @@ export class PlaceholderMenuNode implements MenuNode {
get id(): string {
return [...this.menuPath, 'placeholder'].join('-');
}
}

View File

@@ -3,9 +3,19 @@ import { deepClone } from '@theia/core/lib/common/objects';
import { Emitter, Event } from '@theia/core/lib/common/event';
import { MessageService } from '@theia/core/lib/common/message-service';
import { FrontendApplicationStateService } from '@theia/core/lib/browser/frontend-application-state';
import { MonitorService, MonitorConfig, MonitorError, Status } from '../../common/protocol/monitor-service';
import {
MonitorService,
MonitorConfig,
MonitorError,
Status,
} from '../../common/protocol/monitor-service';
import { BoardsServiceProvider } from '../boards/boards-service-provider';
import { Port, Board, BoardsService, AttachedBoardsChangeEvent } from '../../common/protocol/boards-service';
import {
Port,
Board,
BoardsService,
AttachedBoardsChangeEvent,
} from '../../common/protocol/boards-service';
import { MonitorServiceClientImpl } from './monitor-service-client-impl';
import { BoardsConfig } from '../boards/boards-config';
import { MonitorModel } from './monitor-model';
@@ -13,7 +23,6 @@ import { NotificationCenter } from '../notification-center';
@injectable()
export class MonitorConnection {
@inject(MonitorModel)
protected readonly monitorModel: MonitorModel;
@@ -43,8 +52,10 @@ export class MonitorConnection {
* Note: The idea is to toggle this property from the UI (`Monitor` view)
* and the boards config and the boards attachment/detachment logic can be at on place, here.
*/
protected _autoConnect: boolean = false;
protected readonly onConnectionChangedEmitter = new Emitter<MonitorConnection.State | undefined>();
protected _autoConnect = false;
protected readonly onConnectionChangedEmitter = new Emitter<
MonitorConnection.State | undefined
>();
/**
* This emitter forwards all read events **iff** the connection is established.
*/
@@ -60,7 +71,7 @@ export class MonitorConnection {
@postConstruct()
protected init(): void {
this.monitorServiceClient.onError(async error => {
this.monitorServiceClient.onError(async (error) => {
let shouldReconnect = false;
if (this.state) {
const { code, config } = error;
@@ -68,21 +79,40 @@ export class MonitorConnection {
const options = { timeout: 3000 };
switch (code) {
case MonitorError.ErrorCodes.CLIENT_CANCEL: {
console.debug(`Connection was canceled by client: ${MonitorConnection.State.toString(this.state)}.`);
console.debug(
`Connection was canceled by client: ${MonitorConnection.State.toString(
this.state
)}.`
);
break;
}
case MonitorError.ErrorCodes.DEVICE_BUSY: {
this.messageService.warn(`Connection failed. Serial port is busy: ${Port.toString(port)}.`, options);
this.messageService.warn(
`Connection failed. Serial port is busy: ${Port.toString(
port
)}.`,
options
);
shouldReconnect = this.autoConnect;
this.monitorErrors.push(error);
break;
}
case MonitorError.ErrorCodes.DEVICE_NOT_CONFIGURED: {
this.messageService.info(`Disconnected ${Board.toString(board, { useFqbn: false })} from ${Port.toString(port)}.`, options);
this.messageService.info(
`Disconnected ${Board.toString(board, {
useFqbn: false,
})} from ${Port.toString(port)}.`,
options
);
break;
}
case undefined: {
this.messageService.error(`Unexpected error. Reconnecting ${Board.toString(board)} on port ${Port.toString(port)}.`, options);
this.messageService.error(
`Unexpected error. Reconnecting ${Board.toString(
board
)} on port ${Port.toString(port)}.`,
options
);
console.error(JSON.stringify(error));
shouldReconnect = this.connected && this.autoConnect;
break;
@@ -93,32 +123,62 @@ export class MonitorConnection {
this.onConnectionChangedEmitter.fire(this.state);
if (shouldReconnect) {
if (this.monitorErrors.length >= 10) {
this.messageService.warn(`Failed to reconnect ${Board.toString(board, { useFqbn: false })} to the the serial-monitor after 10 consecutive attempts. The ${Port.toString(port)} serial port is busy. after 10 consecutive attempts.`);
this.messageService.warn(
`Failed to reconnect ${Board.toString(board, {
useFqbn: false,
})} to the the serial-monitor after 10 consecutive attempts. The ${Port.toString(
port
)} serial port is busy. after 10 consecutive attempts.`
);
this.monitorErrors.length = 0;
} else {
const attempts = (this.monitorErrors.length || 1);
const attempts = this.monitorErrors.length || 1;
if (this.reconnectTimeout !== undefined) {
// Clear the previous timer.
window.clearTimeout(this.reconnectTimeout);
}
const timeout = attempts * 1000;
this.messageService.warn(`Reconnecting ${Board.toString(board, { useFqbn: false })} to ${Port.toString(port)} in ${attempts} seconds...`, { timeout });
this.reconnectTimeout = window.setTimeout(() => this.connect(oldState.config), timeout);
this.messageService.warn(
`Reconnecting ${Board.toString(board, {
useFqbn: false,
})} to ${Port.toString(
port
)} in ${attempts} seconds...`,
{ timeout }
);
this.reconnectTimeout = window.setTimeout(
() => this.connect(oldState.config),
timeout
);
}
}
}
});
this.boardsServiceProvider.onBoardsConfigChanged(this.handleBoardConfigChange.bind(this));
this.notificationCenter.onAttachedBoardsChanged(event => {
this.boardsServiceProvider.onBoardsConfigChanged(
this.handleBoardConfigChange.bind(this)
);
this.notificationCenter.onAttachedBoardsChanged((event) => {
if (this.autoConnect && this.connected) {
const { boardsConfig } = this.boardsServiceProvider;
if (this.boardsServiceProvider.canUploadTo(boardsConfig, { silent: false })) {
if (
this.boardsServiceProvider.canUploadTo(boardsConfig, {
silent: false,
})
) {
const { attached } = AttachedBoardsChangeEvent.diff(event);
if (attached.boards.some(board => !!board.port && BoardsConfig.Config.sameAs(boardsConfig, board))) {
const { selectedBoard: board, selectedPort: port } = boardsConfig;
if (
attached.boards.some(
(board) =>
!!board.port &&
BoardsConfig.Config.sameAs(boardsConfig, board)
)
) {
const { selectedBoard: board, selectedPort: port } =
boardsConfig;
const { baudRate } = this.monitorModel;
this.disconnect()
.then(() => this.connect({ board, port, baudRate }));
this.disconnect().then(() =>
this.connect({ board, port, baudRate })
);
}
}
}
@@ -151,10 +211,12 @@ export class MonitorConnection {
if (!oldValue && value) {
// We have to make sure the previous boards config has been restored.
// Otherwise, we might start the auto-connection without configured boards.
this.applicationState.reachedState('started_contributions').then(() => {
const { boardsConfig } = this.boardsServiceProvider;
this.handleBoardConfigChange(boardsConfig);
});
this.applicationState
.reachedState('started_contributions')
.then(() => {
const { boardsConfig } = this.boardsServiceProvider;
this.handleBoardConfigChange(boardsConfig);
});
} else if (oldValue && !value) {
if (this.reconnectTimeout !== undefined) {
window.clearTimeout(this.reconnectTimeout);
@@ -170,7 +232,11 @@ export class MonitorConnection {
return disconnectStatus;
}
}
console.info(`>>> Creating serial monitor connection for ${Board.toString(config.board)} on port ${Port.toString(config.port)}...`);
console.info(
`>>> Creating serial monitor connection for ${Board.toString(
config.board
)} on port ${Port.toString(config.port)}...`
);
const connectStatus = await this.monitorService.connect(config);
if (Status.isOK(connectStatus)) {
const requestMessage = () => {
@@ -180,10 +246,15 @@ export class MonitorConnection {
requestMessage();
}
});
}
};
requestMessage();
this.state = { config };
console.info(`<<< Serial monitor connection created for ${Board.toString(config.board, { useFqbn: false })} on port ${Port.toString(config.port)}.`);
console.info(
`<<< Serial monitor connection created for ${Board.toString(
config.board,
{ useFqbn: false }
)} on port ${Port.toString(config.port)}.`
);
}
this.onConnectionChangedEmitter.fire(this.state);
return Status.isOK(connectStatus);
@@ -200,9 +271,17 @@ export class MonitorConnection {
console.log('>>> Disposing existing monitor connection...');
const status = await this.monitorService.disconnect();
if (Status.isOK(status)) {
console.log(`<<< Disposed connection. Was: ${MonitorConnection.State.toString(stateCopy)}`);
console.log(
`<<< Disposed connection. Was: ${MonitorConnection.State.toString(
stateCopy
)}`
);
} else {
console.warn(`<<< Could not dispose connection. Activate connection: ${MonitorConnection.State.toString(stateCopy)}`);
console.warn(
`<<< Could not dispose connection. Activate connection: ${MonitorConnection.State.toString(
stateCopy
)}`
);
}
this.state = undefined;
this.onConnectionChangedEmitter.fire(this.state);
@@ -218,8 +297,9 @@ export class MonitorConnection {
if (!this.connected) {
return Status.NOT_CONNECTED;
}
return new Promise<Status>(resolve => {
this.monitorService.send(data + this.monitorModel.lineEnding)
return new Promise<Status>((resolve) => {
this.monitorService
.send(data + this.monitorModel.lineEnding)
.then(() => resolve(Status.OK));
});
}
@@ -232,14 +312,24 @@ export class MonitorConnection {
return this.onReadEmitter.event;
}
protected async handleBoardConfigChange(boardsConfig: BoardsConfig.Config): Promise<void> {
protected async handleBoardConfigChange(
boardsConfig: BoardsConfig.Config
): Promise<void> {
if (this.autoConnect) {
if (this.boardsServiceProvider.canUploadTo(boardsConfig, { silent: false })) {
if (
this.boardsServiceProvider.canUploadTo(boardsConfig, {
silent: false,
})
) {
// Instead of calling `getAttachedBoards` and filtering for `AttachedSerialBoard` we have to check the available ports.
// The connected board might be unknown. See: https://github.com/arduino/arduino-pro-ide/issues/127#issuecomment-563251881
this.boardsService.getAvailablePorts().then(ports => {
if (ports.some(port => Port.equals(port, boardsConfig.selectedPort))) {
new Promise<void>(resolve => {
this.boardsService.getAvailablePorts().then((ports) => {
if (
ports.some((port) =>
Port.equals(port, boardsConfig.selectedPort)
)
) {
new Promise<void>((resolve) => {
// First, disconnect if connected.
if (this.connected) {
this.disconnect().then(() => resolve());
@@ -248,7 +338,8 @@ export class MonitorConnection {
resolve();
}).then(() => {
// Then (re-)connect.
const { selectedBoard: board, selectedPort: port } = boardsConfig;
const { selectedBoard: board, selectedPort: port } =
boardsConfig;
const { baudRate } = this.monitorModel;
this.connect({ board, port, baudRate });
});
@@ -257,11 +348,9 @@ export class MonitorConnection {
}
}
}
}
export namespace MonitorConnection {
export interface State {
readonly config: MonitorConfig;
}
@@ -273,5 +362,4 @@ export namespace MonitorConnection {
return `${Board.toString(board)} ${Port.toString(port)}`;
}
}
}

View File

@@ -1,12 +1,14 @@
import { injectable, inject } from 'inversify';
import { Emitter, Event } from '@theia/core/lib/common/event';
import { MonitorConfig } from '../../common/protocol/monitor-service';
import { FrontendApplicationContribution, LocalStorageService } from '@theia/core/lib/browser';
import {
FrontendApplicationContribution,
LocalStorageService,
} from '@theia/core/lib/browser';
import { BoardsServiceProvider } from '../boards/boards-service-provider';
@injectable()
export class MonitorModel implements FrontendApplicationContribution {
protected static STORAGE_ID = 'arduino-monitor-model';
@inject(LocalStorageService)
@@ -15,7 +17,9 @@ export class MonitorModel implements FrontendApplicationContribution {
@inject(BoardsServiceProvider)
protected readonly boardsServiceClient: BoardsServiceProvider;
protected readonly onChangeEmitter: Emitter<MonitorModel.State.Change<keyof MonitorModel.State>>;
protected readonly onChangeEmitter: Emitter<
MonitorModel.State.Change<keyof MonitorModel.State>
>;
protected _autoscroll: boolean;
protected _timestamp: boolean;
protected _baudRate: MonitorConfig.BaudRate;
@@ -26,15 +30,19 @@ export class MonitorModel implements FrontendApplicationContribution {
this._timestamp = false;
this._baudRate = MonitorConfig.BaudRate.DEFAULT;
this._lineEnding = MonitorModel.EOL.DEFAULT;
this.onChangeEmitter = new Emitter<MonitorModel.State.Change<keyof MonitorModel.State>>();
this.onChangeEmitter = new Emitter<
MonitorModel.State.Change<keyof MonitorModel.State>
>();
}
onStart(): void {
this.localStorageService.getData<MonitorModel.State>(MonitorModel.STORAGE_ID).then(state => {
if (state) {
this.restoreState(state);
}
});
this.localStorageService
.getData<MonitorModel.State>(MonitorModel.STORAGE_ID)
.then((state) => {
if (state) {
this.restoreState(state);
}
});
}
get onChange(): Event<MonitorModel.State.Change<keyof MonitorModel.State>> {
@@ -48,7 +56,12 @@ export class MonitorModel implements FrontendApplicationContribution {
toggleAutoscroll(): void {
this._autoscroll = !this._autoscroll;
this.storeState();
this.storeState().then(() => this.onChangeEmitter.fire({ property: 'autoscroll', value: this._autoscroll }));
this.storeState().then(() =>
this.onChangeEmitter.fire({
property: 'autoscroll',
value: this._autoscroll,
})
);
}
get timestamp(): boolean {
@@ -57,7 +70,12 @@ export class MonitorModel implements FrontendApplicationContribution {
toggleTimestamp(): void {
this._timestamp = !this._timestamp;
this.storeState().then(() => this.onChangeEmitter.fire({ property: 'timestamp', value: this._timestamp }));
this.storeState().then(() =>
this.onChangeEmitter.fire({
property: 'timestamp',
value: this._timestamp,
})
);
}
get baudRate(): MonitorConfig.BaudRate {
@@ -66,7 +84,12 @@ export class MonitorModel implements FrontendApplicationContribution {
set baudRate(baudRate: MonitorConfig.BaudRate) {
this._baudRate = baudRate;
this.storeState().then(() => this.onChangeEmitter.fire({ property: 'baudRate', value: this._baudRate }));
this.storeState().then(() =>
this.onChangeEmitter.fire({
property: 'baudRate',
value: this._baudRate,
})
);
}
get lineEnding(): MonitorModel.EOL {
@@ -75,7 +98,12 @@ export class MonitorModel implements FrontendApplicationContribution {
set lineEnding(lineEnding: MonitorModel.EOL) {
this._lineEnding = lineEnding;
this.storeState().then(() => this.onChangeEmitter.fire({ property: 'lineEnding', value: this._lineEnding }));
this.storeState().then(() =>
this.onChangeEmitter.fire({
property: 'lineEnding',
value: this._lineEnding,
})
);
}
protected restoreState(state: MonitorModel.State): void {
@@ -90,14 +118,12 @@ export class MonitorModel implements FrontendApplicationContribution {
autoscroll: this._autoscroll,
timestamp: this._timestamp,
baudRate: this._baudRate,
lineEnding: this._lineEnding
lineEnding: this._lineEnding,
});
}
}
export namespace MonitorModel {
export interface State {
autoscroll: boolean;
timestamp: boolean;
@@ -115,5 +141,4 @@ export namespace MonitorModel {
export namespace EOL {
export const DEFAULT: EOL = '\n';
}
}

View File

@@ -1,15 +1,16 @@
import { injectable } from 'inversify';
import { Emitter } from '@theia/core/lib/common/event';
import { MonitorServiceClient, MonitorError } from '../../common/protocol/monitor-service';
import {
MonitorServiceClient,
MonitorError,
} from '../../common/protocol/monitor-service';
@injectable()
export class MonitorServiceClientImpl implements MonitorServiceClient {
protected readonly onErrorEmitter = new Emitter<MonitorError>();
readonly onError = this.onErrorEmitter.event;
notifyError(error: MonitorError): void {
this.onErrorEmitter.fire(error);
}
}

View File

@@ -3,7 +3,10 @@ import { injectable, inject } from 'inversify';
import { AbstractViewContribution } from '@theia/core/lib/browser';
import { MonitorWidget } from './monitor-widget';
import { MenuModelRegistry, Command, CommandRegistry } from '@theia/core';
import { TabBarToolbarContribution, TabBarToolbarRegistry } from '@theia/core/lib/browser/shell/tab-bar-toolbar';
import {
TabBarToolbarContribution,
TabBarToolbarRegistry,
} from '@theia/core/lib/browser/shell/tab-bar-toolbar';
import { ArduinoToolbar } from '../toolbar/arduino-toolbar';
import { MonitorModel } from './monitor-model';
import { ArduinoMenus } from '../menu/arduino-menus';
@@ -12,25 +15,28 @@ export namespace SerialMonitor {
export namespace Commands {
export const AUTOSCROLL: Command = {
id: 'serial-monitor-autoscroll',
label: 'Autoscroll'
}
label: 'Autoscroll',
};
export const TIMESTAMP: Command = {
id: 'serial-monitor-timestamp',
label: 'Timestamp'
}
label: 'Timestamp',
};
export const CLEAR_OUTPUT: Command = {
id: 'serial-monitor-clear-output',
label: 'Clear Output',
iconClass: 'clear-all'
}
iconClass: 'clear-all',
};
}
}
@injectable()
export class MonitorViewContribution extends AbstractViewContribution<MonitorWidget> implements TabBarToolbarContribution {
export class MonitorViewContribution
extends AbstractViewContribution<MonitorWidget>
implements TabBarToolbarContribution
{
static readonly TOGGLE_SERIAL_MONITOR = MonitorWidget.ID + ':toggle';
static readonly TOGGLE_SERIAL_MONITOR_TOOLBAR = MonitorWidget.ID + ':toggle-toolbar';
static readonly TOGGLE_SERIAL_MONITOR_TOOLBAR =
MonitorWidget.ID + ':toggle-toolbar';
@inject(MonitorModel) protected readonly model: MonitorModel;
@@ -39,11 +45,11 @@ export class MonitorViewContribution extends AbstractViewContribution<MonitorWid
widgetId: MonitorWidget.ID,
widgetName: 'Serial Monitor',
defaultWidgetOptions: {
area: 'bottom'
area: 'bottom',
},
toggleCommandId: MonitorViewContribution.TOGGLE_SERIAL_MONITOR,
toggleKeybinding: 'CtrlCmd+Shift+M'
})
toggleKeybinding: 'CtrlCmd+Shift+M',
});
}
registerMenus(menus: MenuModelRegistry): void {
@@ -51,7 +57,7 @@ export class MonitorViewContribution extends AbstractViewContribution<MonitorWid
menus.registerMenuAction(ArduinoMenus.TOOLS__MAIN_GROUP, {
commandId: this.toggleCommand.id,
label: 'Serial Monitor',
order: '5'
order: '5',
});
}
}
@@ -60,38 +66,44 @@ export class MonitorViewContribution extends AbstractViewContribution<MonitorWid
registry.registerItem({
id: 'monitor-autoscroll',
render: () => this.renderAutoScrollButton(),
isVisible: widget => widget instanceof MonitorWidget,
onDidChange: this.model.onChange as any // XXX: it's a hack. See: https://github.com/eclipse-theia/theia/pull/6696/
isVisible: (widget) => widget instanceof MonitorWidget,
onDidChange: this.model.onChange as any, // XXX: it's a hack. See: https://github.com/eclipse-theia/theia/pull/6696/
});
registry.registerItem({
id: 'monitor-timestamp',
render: () => this.renderTimestampButton(),
isVisible: widget => widget instanceof MonitorWidget,
onDidChange: this.model.onChange as any // XXX: it's a hack. See: https://github.com/eclipse-theia/theia/pull/6696/
isVisible: (widget) => widget instanceof MonitorWidget,
onDidChange: this.model.onChange as any, // XXX: it's a hack. See: https://github.com/eclipse-theia/theia/pull/6696/
});
registry.registerItem({
id: SerialMonitor.Commands.CLEAR_OUTPUT.id,
command: SerialMonitor.Commands.CLEAR_OUTPUT.id,
tooltip: 'Clear Output'
tooltip: 'Clear Output',
});
}
registerCommands(commands: CommandRegistry): void {
commands.registerCommand(SerialMonitor.Commands.CLEAR_OUTPUT, {
isEnabled: widget => widget instanceof MonitorWidget,
isVisible: widget => widget instanceof MonitorWidget,
execute: widget => {
isEnabled: (widget) => widget instanceof MonitorWidget,
isVisible: (widget) => widget instanceof MonitorWidget,
execute: (widget) => {
if (widget instanceof MonitorWidget) {
widget.clearConsole();
}
}
},
});
if (this.toggleCommand) {
commands.registerCommand(this.toggleCommand, { execute: () => this.toggle() });
commands.registerCommand({ id: MonitorViewContribution.TOGGLE_SERIAL_MONITOR_TOOLBAR }, {
isVisible: widget => ArduinoToolbar.is(widget) && widget.side === 'right',
execute: () => this.toggle()
commands.registerCommand(this.toggleCommand, {
execute: () => this.toggle(),
});
commands.registerCommand(
{ id: MonitorViewContribution.TOGGLE_SERIAL_MONITOR_TOOLBAR },
{
isVisible: (widget) =>
ArduinoToolbar.is(widget) && widget.side === 'right',
execute: () => this.toggle(),
}
);
}
}
@@ -105,13 +117,17 @@ export class MonitorViewContribution extends AbstractViewContribution<MonitorWid
}
protected renderAutoScrollButton(): React.ReactNode {
return <React.Fragment key='autoscroll-toolbar-item'>
<div
title='Toggle Autoscroll'
className={`item enabled fa fa-angle-double-down arduino-monitor ${this.model.autoscroll ? 'toggled' : ''}`}
onClick={this.toggleAutoScroll}
></div>
</React.Fragment>;
return (
<React.Fragment key="autoscroll-toolbar-item">
<div
title="Toggle Autoscroll"
className={`item enabled fa fa-angle-double-down arduino-monitor ${
this.model.autoscroll ? 'toggled' : ''
}`}
onClick={this.toggleAutoScroll}
></div>
</React.Fragment>
);
}
protected readonly toggleAutoScroll = () => this.doToggleAutoScroll();
@@ -120,18 +136,21 @@ export class MonitorViewContribution extends AbstractViewContribution<MonitorWid
}
protected renderTimestampButton(): React.ReactNode {
return <React.Fragment key='line-ending-toolbar-item'>
<div
title='Toggle Timestamp'
className={`item enabled fa fa-clock-o arduino-monitor ${this.model.timestamp ? 'toggled' : ''}`}
onClick={this.toggleTimestamp}
></div>
</React.Fragment>;
return (
<React.Fragment key="line-ending-toolbar-item">
<div
title="Toggle Timestamp"
className={`item enabled fa fa-clock-o arduino-monitor ${
this.model.timestamp ? 'toggled' : ''
}`}
onClick={this.toggleTimestamp}
></div>
</React.Fragment>
);
}
protected readonly toggleTimestamp = () => this.doToggleTimestamp();
protected async doToggleTimestamp(): Promise<void> {
this.model.toggleTimestamp();
}
}

View File

@@ -5,8 +5,16 @@ import { OptionsType } from 'react-select/src/types';
import { isOSX } from '@theia/core/lib/common/os';
import { Event, Emitter } from '@theia/core/lib/common/event';
import { Key, KeyCode } from '@theia/core/lib/browser/keys';
import { DisposableCollection, Disposable } from '@theia/core/lib/common/disposable'
import { ReactWidget, Message, Widget, MessageLoop } from '@theia/core/lib/browser/widgets';
import {
DisposableCollection,
Disposable,
} from '@theia/core/lib/common/disposable';
import {
ReactWidget,
Message,
Widget,
MessageLoop,
} from '@theia/core/lib/browser/widgets';
import { Board, Port } from '../../common/protocol/boards-service';
import { MonitorConfig } from '../../common/protocol/monitor-service';
import { ArduinoSelect } from '../widgets/arduino-select';
@@ -16,7 +24,6 @@ import { MonitorServiceClientImpl } from './monitor-service-client-impl';
@injectable()
export class MonitorWidget extends ReactWidget {
static readonly ID = 'serial-monitor';
@inject(MonitorModel)
@@ -49,18 +56,24 @@ export class MonitorWidget extends ReactWidget {
this.title.closable = true;
this.scrollOptions = undefined;
this.toDispose.push(this.clearOutputEmitter);
this.toDispose.push(Disposable.create(() => {
this.monitorConnection.autoConnect = false;
if (this.monitorConnection.connected) {
this.monitorConnection.disconnect();
}
}));
this.toDispose.push(
Disposable.create(() => {
this.monitorConnection.autoConnect = false;
if (this.monitorConnection.connected) {
this.monitorConnection.disconnect();
}
})
);
}
@postConstruct()
protected init(): void {
this.update();
this.toDispose.push(this.monitorConnection.onConnectionChanged(() => this.clearConsole()));
this.toDispose.push(
this.monitorConnection.onConnectionChanged(() =>
this.clearConsole()
)
);
}
clearConsole(): void {
@@ -106,72 +119,93 @@ export class MonitorWidget extends ReactWidget {
return;
}
this.focusNode = element;
requestAnimationFrame(() => MessageLoop.sendMessage(this, Widget.Msg.ActivateRequest));
}
requestAnimationFrame(() =>
MessageLoop.sendMessage(this, Widget.Msg.ActivateRequest)
);
};
protected get lineEndings(): OptionsType<SelectOption<MonitorModel.EOL>> {
return [
{
label: 'No Line Ending',
value: ''
value: '',
},
{
label: 'New Line',
value: '\n'
value: '\n',
},
{
label: 'Carriage Return',
value: '\r'
value: '\r',
},
{
label: 'Both NL & CR',
value: '\r\n'
}
value: '\r\n',
},
];
}
protected get baudRates(): OptionsType<SelectOption<MonitorConfig.BaudRate>> {
const baudRates: Array<MonitorConfig.BaudRate> = [300, 1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200];
return baudRates.map(baudRate => ({ label: baudRate + ' baud', value: baudRate }));
protected get baudRates(): OptionsType<
SelectOption<MonitorConfig.BaudRate>
> {
const baudRates: Array<MonitorConfig.BaudRate> = [
300, 1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200,
];
return baudRates.map((baudRate) => ({
label: baudRate + ' baud',
value: baudRate,
}));
}
protected render(): React.ReactNode {
const { baudRates, lineEndings } = this;
const lineEnding = lineEndings.find(item => item.value === this.monitorModel.lineEnding) || lineEndings[1]; // Defaults to `\n`.
const baudRate = baudRates.find(item => item.value === this.monitorModel.baudRate) || baudRates[4]; // Defaults to `9600`.
return <div className='serial-monitor'>
<div className='head'>
<div className='send'>
<SerialMonitorSendInput
monitorConfig={this.monitorConnection.monitorConfig}
resolveFocus={this.onFocusResolved}
onSend={this.onSend} />
</div>
<div className='config'>
<div className='select'>
<ArduinoSelect
maxMenuHeight={this.widgetHeight - 40}
options={lineEndings}
defaultValue={lineEnding}
onChange={this.onChangeLineEnding} />
const lineEnding =
lineEndings.find(
(item) => item.value === this.monitorModel.lineEnding
) || lineEndings[1]; // Defaults to `\n`.
const baudRate =
baudRates.find(
(item) => item.value === this.monitorModel.baudRate
) || baudRates[4]; // Defaults to `9600`.
return (
<div className="serial-monitor">
<div className="head">
<div className="send">
<SerialMonitorSendInput
monitorConfig={this.monitorConnection.monitorConfig}
resolveFocus={this.onFocusResolved}
onSend={this.onSend}
/>
</div>
<div className='select'>
<ArduinoSelect
className='select'
maxMenuHeight={this.widgetHeight - 40}
options={baudRates}
defaultValue={baudRate}
onChange={this.onChangeBaudRate} />
<div className="config">
<div className="select">
<ArduinoSelect
maxMenuHeight={this.widgetHeight - 40}
options={lineEndings}
defaultValue={lineEnding}
onChange={this.onChangeLineEnding}
/>
</div>
<div className="select">
<ArduinoSelect
className="select"
maxMenuHeight={this.widgetHeight - 40}
options={baudRates}
defaultValue={baudRate}
onChange={this.onChangeBaudRate}
/>
</div>
</div>
</div>
<div className="body">
<SerialMonitorOutput
monitorModel={this.monitorModel}
monitorConnection={this.monitorConnection}
clearConsoleEvent={this.clearOutputEmitter.event}
/>
</div>
</div>
<div className='body'>
<SerialMonitorOutput
monitorModel={this.monitorModel}
monitorConnection={this.monitorConnection}
clearConsoleEvent={this.clearOutputEmitter.event} />
</div>
</div>;
);
}
protected readonly onSend = (value: string) => this.doSend(value);
@@ -179,14 +213,17 @@ export class MonitorWidget extends ReactWidget {
this.monitorConnection.send(value);
}
protected readonly onChangeLineEnding = (option: SelectOption<MonitorModel.EOL>) => {
protected readonly onChangeLineEnding = (
option: SelectOption<MonitorModel.EOL>
) => {
this.monitorModel.lineEnding = option.value;
}
};
protected readonly onChangeBaudRate = (option: SelectOption<MonitorConfig.BaudRate>) => {
protected readonly onChangeBaudRate = (
option: SelectOption<MonitorConfig.BaudRate>
) => {
this.monitorModel.baudRate = option.value;
}
};
}
export namespace SerialMonitorSendInput {
@@ -200,8 +237,10 @@ export namespace SerialMonitorSendInput {
}
}
export class SerialMonitorSendInput extends React.Component<SerialMonitorSendInput.Props, SerialMonitorSendInput.State> {
export class SerialMonitorSendInput extends React.Component<
SerialMonitorSendInput.Props,
SerialMonitorSendInput.State
> {
constructor(props: Readonly<SerialMonitorSendInput.Props>) {
super(props);
this.state = { text: '' };
@@ -211,30 +250,39 @@ export class SerialMonitorSendInput extends React.Component<SerialMonitorSendInp
}
render(): React.ReactNode {
return <input
ref={this.setRef}
type='text'
className={`theia-input ${this.props.monitorConfig ? '' : 'warning'}`}
placeholder={this.placeholder}
value={this.state.text}
onChange={this.onChange}
onKeyDown={this.onKeyDown} />
return (
<input
ref={this.setRef}
type="text"
className={`theia-input ${
this.props.monitorConfig ? '' : 'warning'
}`}
placeholder={this.placeholder}
value={this.state.text}
onChange={this.onChange}
onKeyDown={this.onKeyDown}
/>
);
}
protected get placeholder(): string {
const { monitorConfig } = this.props;
if (!monitorConfig) {
return 'Not connected. Select a board and a port to connect automatically.'
return 'Not connected. Select a board and a port to connect automatically.';
}
const { board, port } = monitorConfig;
return `Message (${isOSX ? '⌘' : 'Ctrl'}+Enter to send message to '${Board.toString(board, { useFqbn: false })}' on '${Port.toString(port)}')`;
return `Message (${
isOSX ? '⌘' : 'Ctrl'
}+Enter to send message to '${Board.toString(board, {
useFqbn: false,
})}' on '${Port.toString(port)}')`;
}
protected setRef = (element: HTMLElement | null) => {
if (this.props.resolveFocus) {
this.props.resolveFocus(element || undefined);
}
}
};
protected onChange(event: React.ChangeEvent<HTMLInputElement>): void {
this.setState({ text: event.target.value });
@@ -254,7 +302,6 @@ export class SerialMonitorSendInput extends React.Component<SerialMonitorSendInp
}
}
}
}
export namespace SerialMonitorOutput {
@@ -269,8 +316,10 @@ export namespace SerialMonitorOutput {
}
}
export class SerialMonitorOutput extends React.Component<SerialMonitorOutput.Props, SerialMonitorOutput.State> {
export class SerialMonitorOutput extends React.Component<
SerialMonitorOutput.Props,
SerialMonitorOutput.State
> {
/**
* Do not touch it. It is used to be able to "follow" the serial monitor log.
*/
@@ -279,16 +328,26 @@ export class SerialMonitorOutput extends React.Component<SerialMonitorOutput.Pro
constructor(props: Readonly<SerialMonitorOutput.Props>) {
super(props);
this.state = { content: '', timestamp: this.props.monitorModel.timestamp };
this.state = {
content: '',
timestamp: this.props.monitorModel.timestamp,
};
}
render(): React.ReactNode {
return <React.Fragment>
<div style={({ whiteSpace: 'pre', fontFamily: 'monospace' })}>
{this.state.content}
</div>
<div style={{ float: 'left', clear: 'both' }} ref={element => { this.anchor = element; }} />
</React.Fragment>;
return (
<React.Fragment>
<div style={{ whiteSpace: 'pre', fontFamily: 'monospace' }}>
{this.state.content}
</div>
<div
style={{ float: 'left', clear: 'both' }}
ref={(element) => {
this.anchor = element;
}}
/>
</React.Fragment>
);
}
componentDidMount(): void {
@@ -296,8 +355,11 @@ export class SerialMonitorOutput extends React.Component<SerialMonitorOutput.Pro
this.toDisposeBeforeUnmount.pushAll([
this.props.monitorConnection.onRead(({ message }) => {
const rawLines = message.split('\n');
const lines: string[] = []
const timestamp = () => this.state.timestamp ? `${dateFormat(new Date(), 'H:M:ss.l')} -> ` : '';
const lines: string[] = [];
const timestamp = () =>
this.state.timestamp
? `${dateFormat(new Date(), 'H:M:ss.l')} -> `
: '';
for (let i = 0; i < rawLines.length; i++) {
if (i === 0 && this.state.content.length !== 0) {
lines.push(rawLines[i]);
@@ -314,7 +376,7 @@ export class SerialMonitorOutput extends React.Component<SerialMonitorOutput.Pro
const { timestamp } = this.props.monitorModel;
this.setState({ timestamp });
}
})
}),
]);
}
@@ -332,7 +394,6 @@ export class SerialMonitorOutput extends React.Component<SerialMonitorOutput.Pro
this.anchor.scrollIntoView();
}
}
}
export interface SelectOption<T> {

View File

@@ -3,25 +3,48 @@ import { Emitter } from '@theia/core/lib/common/event';
import { JsonRpcProxy } from '@theia/core/lib/common/messaging/proxy-factory';
import { DisposableCollection } from '@theia/core/lib/common/disposable';
import { FrontendApplicationContribution } from '@theia/core/lib/browser/frontend-application';
import { NotificationServiceClient, NotificationServiceServer } from '../common/protocol/notification-service';
import { AttachedBoardsChangeEvent, BoardsPackage, LibraryPackage, Config, Sketch } from '../common/protocol';
import {
NotificationServiceClient,
NotificationServiceServer,
} from '../common/protocol/notification-service';
import {
AttachedBoardsChangeEvent,
BoardsPackage,
LibraryPackage,
Config,
Sketch,
} from '../common/protocol';
@injectable()
export class NotificationCenter implements NotificationServiceClient, FrontendApplicationContribution {
export class NotificationCenter
implements NotificationServiceClient, FrontendApplicationContribution
{
@inject(NotificationServiceServer)
protected readonly server: JsonRpcProxy<NotificationServiceServer>;
protected readonly indexUpdatedEmitter = new Emitter<void>();
protected readonly daemonStartedEmitter = new Emitter<void>();
protected readonly daemonStoppedEmitter = new Emitter<void>();
protected readonly configChangedEmitter = new Emitter<{ config: Config | undefined }>();
protected readonly platformInstalledEmitter = new Emitter<{ item: BoardsPackage }>();
protected readonly platformUninstalledEmitter = new Emitter<{ item: BoardsPackage }>();
protected readonly libraryInstalledEmitter = new Emitter<{ item: LibraryPackage }>();
protected readonly libraryUninstalledEmitter = new Emitter<{ item: LibraryPackage }>();
protected readonly attachedBoardsChangedEmitter = new Emitter<AttachedBoardsChangeEvent>();
protected readonly recentSketchesChangedEmitter = new Emitter<{ sketches: Sketch[] }>();
protected readonly configChangedEmitter = new Emitter<{
config: Config | undefined;
}>();
protected readonly platformInstalledEmitter = new Emitter<{
item: BoardsPackage;
}>();
protected readonly platformUninstalledEmitter = new Emitter<{
item: BoardsPackage;
}>();
protected readonly libraryInstalledEmitter = new Emitter<{
item: LibraryPackage;
}>();
protected readonly libraryUninstalledEmitter = new Emitter<{
item: LibraryPackage;
}>();
protected readonly attachedBoardsChangedEmitter =
new Emitter<AttachedBoardsChangeEvent>();
protected readonly recentSketchesChangedEmitter = new Emitter<{
sketches: Sketch[];
}>();
protected readonly toDispose = new DisposableCollection(
this.indexUpdatedEmitter,
@@ -94,5 +117,4 @@ export class NotificationCenter implements NotificationServiceClient, FrontendAp
notifyRecentSketchesChanged(event: { sketches: Sketch[] }): void {
this.recentSketchesChangedEmitter.fire(event);
}
}

View File

@@ -1,22 +0,0 @@
import { inject, injectable } from 'inversify';
import { OutputContribution } from '@theia/output/lib/browser/output-contribution';
import { OutputChannelManager } from '@theia/output/lib/common/output-channel';
import { OutputService, OutputMessage } from '../common/protocol/output-service';
@injectable()
export class OutputServiceImpl implements OutputService {
@inject(OutputContribution)
protected outputContribution: OutputContribution;
@inject(OutputChannelManager)
protected outputChannelManager: OutputChannelManager;
append(message: OutputMessage): void {
const { chunk } = message;
const channel = this.outputChannelManager.getChannel('Arduino');
channel.show({ preserveFocus: true });
channel.append(chunk);
}
}

View File

@@ -0,0 +1,37 @@
import { inject, injectable } from 'inversify';
import { Emitter } from '@theia/core/lib/common/event';
import { OutputContribution } from '@theia/output/lib/browser/output-contribution';
import { OutputChannelManager } from '@theia/output/lib/common/output-channel';
import {
ResponseService,
OutputMessage,
ProgressMessage,
} from '../common/protocol/response-service';
@injectable()
export class ResponseServiceImpl implements ResponseService {
@inject(OutputContribution)
protected outputContribution: OutputContribution;
@inject(OutputChannelManager)
protected outputChannelManager: OutputChannelManager;
protected readonly progressDidChangeEmitter =
new Emitter<ProgressMessage>();
readonly onProgressDidChange = this.progressDidChangeEmitter.event;
appendToOutput(message: OutputMessage): void {
const { chunk } = message;
const channel = this.outputChannelManager.getChannel('Arduino');
channel.show({ preserveFocus: true });
channel.append(chunk);
}
clearArduinoChannel(): void {
this.outputChannelManager.getChannel('Arduino').clear();
}
reportProgress(progress: ProgressMessage): void {
this.progressDidChangeEmitter.fire(progress);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,37 @@
import { injectable, inject } from 'inversify';
import { StorageService } from '@theia/core/lib/browser/storage-service';
import {
Command,
CommandContribution,
CommandRegistry,
} from '@theia/core/lib/common/command';
/**
* This is a workaround to break cycles in the dependency injection. Provides commands for `setData` and `getData`.
*/
@injectable()
export class StorageWrapper implements CommandContribution {
@inject(StorageService)
protected storageService: StorageService;
registerCommands(commands: CommandRegistry): void {
commands.registerCommand(StorageWrapper.Commands.GET_DATA, {
execute: (key: string, defaultValue?: any) =>
this.storageService.getData(key, defaultValue),
});
commands.registerCommand(StorageWrapper.Commands.SET_DATA, {
execute: (key: string, value: any) =>
this.storageService.setData(key, value),
});
}
}
export namespace StorageWrapper {
export namespace Commands {
export const SET_DATA: Command = {
id: 'arduino-store-wrapper-set',
};
export const GET_DATA: Command = {
id: 'arduino-store-wrapper-get',
};
}
}

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" width="1em" height="1em" style="-ms-transform: rotate(360deg); -webkit-transform: rotate(360deg); transform: rotate(360deg);" preserveAspectRatio="xMidYMid meet" viewBox="0 0 16 16"><g fill="#626262"><path d="M16 7.992C16 3.58 12.416 0 8 0S0 3.58 0 7.992c0 2.43 1.104 4.62 2.832 6.09c.016.016.032.016.032.032c.144.112.288.224.448.336c.08.048.144.111.224.175A7.98 7.98 0 0 0 8.016 16a7.98 7.98 0 0 0 4.48-1.375c.08-.048.144-.111.224-.16c.144-.111.304-.223.448-.335c.016-.016.032-.016.032-.032c1.696-1.487 2.8-3.676 2.8-6.106zm-8 7.001c-1.504 0-2.88-.48-4.016-1.279c.016-.128.048-.255.08-.383a4.17 4.17 0 0 1 .416-.991c.176-.304.384-.576.64-.816c.24-.24.528-.463.816-.639c.304-.176.624-.304.976-.4A4.15 4.15 0 0 1 8 10.342a4.185 4.185 0 0 1 2.928 1.166c.368.368.656.8.864 1.295c.112.288.192.592.24.911A7.03 7.03 0 0 1 8 14.993zm-2.448-7.4a2.49 2.49 0 0 1-.208-1.024c0-.351.064-.703.208-1.023c.144-.32.336-.607.576-.847c.24-.24.528-.431.848-.575c.32-.144.672-.208 1.024-.208c.368 0 .704.064 1.024.208c.32.144.608.336.848.575c.24.24.432.528.576.847c.144.32.208.672.208 1.023c0 .368-.064.704-.208 1.023a2.84 2.84 0 0 1-.576.848a2.84 2.84 0 0 1-.848.575a2.715 2.715 0 0 1-2.064 0a2.84 2.84 0 0 1-.848-.575a2.526 2.526 0 0 1-.56-.848zm7.424 5.306c0-.032-.016-.048-.016-.08a5.22 5.22 0 0 0-.688-1.406a4.883 4.883 0 0 0-1.088-1.135a5.207 5.207 0 0 0-1.04-.608a2.82 2.82 0 0 0 .464-.383a4.2 4.2 0 0 0 .624-.784a3.624 3.624 0 0 0 .528-1.934a3.71 3.71 0 0 0-.288-1.47a3.799 3.799 0 0 0-.816-1.199a3.845 3.845 0 0 0-1.2-.8a3.72 3.72 0 0 0-1.472-.287a3.72 3.72 0 0 0-1.472.288a3.631 3.631 0 0 0-1.2.815a3.84 3.84 0 0 0-.8 1.199a3.71 3.71 0 0 0-.288 1.47c0 .352.048.688.144 1.007c.096.336.224.64.4.927c.16.288.384.544.624.784c.144.144.304.271.48.383a5.12 5.12 0 0 0-1.04.624c-.416.32-.784.703-1.088 1.119a4.999 4.999 0 0 0-.688 1.406c-.016.032-.016.064-.016.08C1.776 11.636.992 9.91.992 7.992C.992 4.14 4.144.991 8 .991s7.008 3.149 7.008 7.001a6.96 6.96 0 0 1-2.032 4.907z"/></g></svg>

After

Width:  |  Height:  |  Size: 2.0 KiB

View File

@@ -1,5 +1,5 @@
div#select-board-dialog {
margin: 5px 20px 50px 20px;
margin: 5px;
}
div#select-board-dialog .selectBoardContainer .body {
@@ -7,8 +7,8 @@ div#select-board-dialog .selectBoardContainer .body {
overflow: hidden;
}
div.dialogContent.select-board-dialog > div.head {
padding-left: 21px;
.select-board-dialog .head {
margin: 5px;
}
div.dialogContent.select-board-dialog > div.head .title {
@@ -16,11 +16,7 @@ div.dialogContent.select-board-dialog > div.head .title {
letter-spacing: .02em;
font-size: 1.2em;
color: var(--theia-arduino-branding-primary);
margin: 17px 0;
}
div#select-board-dialog .selectBoardContainer .head .text {
margin-bottom: 21px;
margin-bottom: 10px;
}
div#select-board-dialog .selectBoardContainer .body .list .item.selected {
@@ -57,6 +53,8 @@ div#select-board-dialog .selectBoardContainer .body .list .item.selected i {
#select-board-dialog .selectBoardContainer .body .container {
flex: 1;
padding: 0px 10px 0px 0px;
min-width: 240px;
max-width: 240px;
}
#select-board-dialog .selectBoardContainer .body .left.container .content {
@@ -82,15 +80,17 @@ div#select-board-dialog .selectBoardContainer .body .list .item.selected i {
color: var(--theia-arduino-branding-secondary);
padding: 10px 5px 10px 10px;
text-transform: uppercase;
/* The max, min-height comes from `.body .list` 265px + 47px top padding - 2 * 10px top padding */
max-height: 292px;
min-height: 292px;
/* The max, min-height comes from `.body .list` 200px + 47px top padding - 2 * 10px top padding */
max-height: 227px;
min-height: 227px;
}
#select-board-dialog .selectBoardContainer .body .list .item {
padding: 10px 5px 10px 10px;
display: flex;
justify-content: end;
white-space: nowrap;
overflow-x: hidden;
}
#select-board-dialog .selectBoardContainer .body .list .item .selected-icon {
@@ -114,9 +114,17 @@ div#select-board-dialog .selectBoardContainer .body .list .item.selected i {
background: var(--theia-secondaryButton-hoverBackground);
}
#select-board-dialog .selectBoardContainer .body .list .label {
max-width: 215px;
width: 215px;
white-space: pre;
overflow: hidden;
text-overflow: ellipsis;
}
#select-board-dialog .selectBoardContainer .body .list {
max-height: 265px;
min-height: 265px;
max-height: 200px;
min-height: 200px;
overflow-y: auto;
}
@@ -132,14 +140,8 @@ div#select-board-dialog .selectBoardContainer .body .list .item.selected i {
}
.p-Widget.dialogOverlay .dialogContent.select-board-dialog {
width: 740px;
width: 500px;
}
.dialogControl {
margin: 0 20px 30px 0;
}
.arduino-boards-toolbar-item-container {
margin-left: 3px;
}

View File

@@ -0,0 +1,14 @@
<svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M3.54383 11.5H0.612583C0.129139 9.86839 0.129139 8.13161 0.612583 6.5H3.54383C3.42911 7.32835 3.37272 8.16374 3.37508 9C3.37272 9.83626 3.42911 10.6716 3.54383 11.5Z" fill="#616161"/>
<path d="M3.775 12.75C4.08097 14.3119 4.72054 15.7893 5.65 17.0812C3.6488 16.2492 2.02597 14.7065 1.09375 12.75H3.775Z" fill="#616161"/>
<path d="M3.775 5.25001H1.09375C2.02597 3.29347 3.6488 1.75079 5.65 0.918762C4.72054 2.21073 4.08097 3.68814 3.775 5.25001Z" fill="#616161"/>
<path d="M8.375 0.34375V5.25H5.0625C5.69375 2.6875 6.93125 0.775 8.375 0.34375Z" fill="#616161"/>
<path d="M4.81248 6.5H8.37498V11.5H4.81248C4.56251 9.84271 4.56251 8.15729 4.81248 6.5Z" fill="#616161"/>
<path d="M5.0625 12.75H8.375V17.6562C6.93125 17.225 5.69375 15.3125 5.0625 12.75Z" fill="#616161"/>
<path d="M12.9375 12.75C12.3125 15.3125 11.0625 17.225 9.625 17.6562V12.75H12.9375Z" fill="#616161"/>
<path d="M12.9375 5.25H9.625V0.34375C11.0688 0.775 12.3063 2.6875 12.9375 5.25Z" fill="#616161"/>
<path d="M13.1875 11.5H9.625V6.5H13.1875C13.3115 7.32757 13.3742 8.16318 13.375 9C13.3742 9.83682 13.3115 10.6724 13.1875 11.5Z" fill="#616161"/>
<path d="M14.2251 12.75H16.9063C15.9741 14.7065 14.3513 16.2492 12.3501 17.0812C13.2796 15.7893 13.9191 14.3119 14.2251 12.75Z" fill="#616161"/>
<path d="M14.2251 5.25001C13.9191 3.68814 13.2796 2.21073 12.3501 0.918762C14.3513 1.75079 15.9741 3.29347 16.9063 5.25001H14.2251Z" fill="#616161"/>
<path d="M17.7503 9C17.7517 9.84653 17.6296 10.6887 17.3878 11.5H14.4565C14.5713 10.6716 14.6277 9.83626 14.6253 9C14.6277 8.16374 14.5713 7.32835 14.4565 6.5H17.3878C17.6296 7.31126 17.7517 8.15347 17.7503 9Z" fill="#616161"/>
</svg>

After

Width:  |  Height:  |  Size: 1.7 KiB

View File

@@ -0,0 +1,184 @@
.sign-in-title {
margin: 20px 0;
font-weight: bold;
}
.sign-in-desc {
margin: 20px;
line-height: 150%;
}
.sign-in-cta {
margin-left: 0 !important;
}
.sign-in-learnmore {
margin-bottom: 20px;
}
.cloud-sketchbook-tree-icon {
background: url("./cloud-sketchbook-tree-icon.svg") center center no-repeat;
width: var(--theia-icon-size);
height: var(--theia-icon-size);
background-size: auto 90%;
}
.sketchbook-trees-container
.p-TabBar[data-orientation="horizontal"]
> .p-TabBar-content {
justify-content: center;
border-bottom: 1px solid var(--theia-tree-indentGuidesStroke);
}
.sketchbook-trees-container
.p-Widget.p-TabBar.p-DockPanel-tabBar
> ul
> li.p-TabBar-tab
> div.p-TabBar-tabLabel {
display: none;
width: 0px;
max-width: 0px;
}
.sketchbook-trees-container
.p-Widget.p-TabBar.p-DockPanel-tabBar
> ul
> li.p-TabBar-tab
> div.p-TabBar-tabCloseIcon {
display: none;
width: 0px;
max-width: 0px;
}
.sketchbook-trees-container
.p-TabBar[data-orientation="horizontal"]
.p-TabBar-tab {
min-width: 55px;
}
.sketchbook-trees-container
.p-Widget.p-TabBar.p-DockPanel-tabBar
> ul
> li.p-TabBar-tab {
padding-left: 20px;
}
.sketchbook-trees-container
.p-Widget.p-TabBar.p-DockPanel-tabBar
> ul
> li.p-TabBar-tab.p-mod-current {
border-bottom: 2px solid var(--theia-statusBar-background);
}
.sketchbook-trees-container .center {
height: 100%;
display: flex;
align-items: center;
}
.cloud-sketchbook-welcome {
flex-direction: column;
text-align: center;
}
.cloud-sketchbook-welcome > .item {
align-items: flex-end;
}
.cloud-sketchbook-welcome > .item .link {
cursor: pointer;
color: var(--theia-arduino-branding-primary);
}
.pull-sketch-icon {
background: url("./pull-sketch-icon.svg") center center no-repeat;
width: var(--theia-icon-size);
height: var(--theia-icon-size);
}
.push-sketch-icon {
background: url("./push-sketch-icon.svg") center center no-repeat;
width: var(--theia-icon-size);
height: var(--theia-icon-size);
}
.account-icon {
background: url("./account-icon.svg") center center no-repeat;
width: var(--theia-icon-size);
height: var(--theia-icon-size);
border-radius: 50%;
overflow: hidden;
}
.account-icon > img {
max-width: 100%;
max-height: 100%;
}
.connected-status-icon {
background: url("./connected-status-icon.svg") center center no-repeat;
width: var(--theia-icon-size);
height: var(--theia-icon-size);
}
.offline-status-icon {
background: url("./offline-status-icon.svg") center center no-repeat;
width: var(--theia-icon-size);
height: var(--theia-icon-size);
}
.refresh-icon {
background: url("./refresh-icon.svg") center center no-repeat;
width: var(--theia-icon-size);
height: var(--theia-icon-size);
}
@keyframes rotating {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
.rotating {
animation: rotating 1s ease-in-out infinite;
}
.cloud-connection-status {
border-top: 1px solid var(--theia-tree-indentGuidesStroke);
border-bottom: none;
}
.cloud-connection-status .item {
padding: 8px;
}
.cloud-connection-status .status {
flex-grow: 2;
}
.cloud-connection-status .actions {
border-left: 1px solid var(--theia-tree-indentGuidesStroke);
border-right: 1px solid var(--theia-tree-indentGuidesStroke);
}
.composite-node {
height: 100%;
display: flex;
flex-direction: column-reverse;
}
.composite-node .tree-container {
height: 100%;
}
.arduino-share-sketch-dialog .sketch-link {
display: flex;
}
.arduino-share-sketch-dialog .sketch-link input {
flex: 1;
}
.arduino-share-sketch-dialog .sketch-link-embed textarea {
width: 100%;
}

View File

@@ -0,0 +1,3 @@
<svg width="8" height="8" viewBox="0 0 8 8" fill="none" xmlns="http://www.w3.org/2000/svg">
<circle cx="4" cy="4" r="4" fill="#1DA086"/>
</svg>

After

Width:  |  Height:  |  Size: 144 B

View File

@@ -0,0 +1,36 @@
/* TODO: remove after https://github.com/eclipse-theia/theia/pull/9256/ */
/* To fix colors in Theia. */
.theia-debug-hover-title.number,
.theia-debug-console-variable.number {
color: var(--theia-variable-number-variable-color);
}
.theia-debug-hover-title.boolean,
.theia-debug-console-variable.boolean {
color: var(--theia-variable-boolean-variable-color);
}
.theia-debug-hover-title.string,
.theia-debug-console-variable.string {
color: var(--theia-variable-string-variable-color);
}
/* To unset the default debug hover dimension. */
.theia-debug-hover {
min-width: unset;
min-height: unset;
width: unset;
height: unset;
}
/* To adjust the left padding in the hover title. */
.theia-debug-hover-title {
padding-left: 5px;
}
/* Use the default Theia dimensions only iff the expression is complex (`!!expression.hasChildren~) */
.theia-debug-hover.complex-value {
min-width: 324px;
min-height: 324px;
width: 324px;
height: 324px;
}

View File

@@ -7,6 +7,9 @@
@import './terminal.css';
@import './editor.css';
@import './settings-dialog.css';
@import './debug.css';
@import './sketchbook.css';
@import './cloud-sketchbook.css';
.theia-input.warning:focus {
outline-width: 1px;
@@ -60,9 +63,32 @@ button.theia-button {
button.theia-button.secondary {
background-color: var(--theia-secondaryButton-background);
color: var(--theia-foreground);
color: var(--theia-secondaryButton-foreground);
}
button.theia-button.main {
color: var(--theia-button-foreground);
}
/* To make the progress-bar slightly thicker, and use the color from the status bar */
.theia-progress-bar-container {
width: 100%;
height: 4px;
}
.theia-progress-bar {
height: 4px;
width: 3%;
animation: progress-animation 1.3s 0s infinite cubic-bezier(0.645, 0.045, 0.355, 1);
}
.theia-notification-item-progressbar {
height: 4px;
width: 66%;
}
.flex-line {
display: flex;
align-items: center;
white-space: nowrap;
}

View File

@@ -175,7 +175,6 @@
#arduino-open-sketch-control--toolbar--container {
background-color: var(--theia-arduino-toolbar-background);
padding: 8px 8px 8px 8px; /* based on pure heuristics */
}
#arduino-open-sketch-control--toolbar {
@@ -183,6 +182,7 @@
width: unset;
line-height: unset;
color: var(--theia-titleBar-activeBackground);
padding: 5px 8px; /* based on pure heuristics */
}
/* Output */

View File

@@ -0,0 +1,3 @@
<svg width="8" height="8" viewBox="0 0 8 8" fill="none" xmlns="http://www.w3.org/2000/svg">
<circle cx="4" cy="4" r="4" fill="#95A5A6"/>
</svg>

After

Width:  |  Height:  |  Size: 144 B

View File

@@ -0,0 +1,8 @@
<svg width="14" height="12" viewBox="0 0 14 12" fill="none" xmlns="http://www.w3.org/2000/svg">
<path
d="M9.35506 9.855L7.35506 11.855C7.26028 11.948 7.13283 12 7.00008 12C6.86733 12 6.73988 11.948 6.6451 11.855L4.6451 9.855C4.59848 9.80838 4.5615 9.75304 4.53627 9.69213C4.51104 9.63122 4.49805 9.56594 4.49805 9.50001C4.49804 9.36687 4.55093 9.23917 4.64508 9.14502C4.73923 9.05087 4.86692 8.99797 5.00006 8.99797C5.06599 8.99797 5.13127 9.01095 5.19218 9.03618C5.25309 9.06141 5.30844 9.09838 5.35506 9.145L6.50006 10.2949V4.5C6.50006 4.36739 6.55274 4.24021 6.64651 4.14645C6.74027 4.05268 6.86745 4 7.00006 4C7.13267 4 7.25984 4.05268 7.35361 4.14645C7.44738 4.24021 7.50006 4.36739 7.50006 4.5V10.2949L8.64506 9.145C8.73921 9.05085 8.86691 8.99795 9.00006 8.99795C9.13321 8.99795 9.26091 9.05085 9.35506 9.145C9.44921 9.23915 9.5021 9.36685 9.5021 9.5C9.5021 9.63315 9.44921 9.76085 9.35506 9.855Z"
fill="#008184" />
<path
d="M10.75 7.99999H9C8.86739 7.99999 8.74022 7.94732 8.64645 7.85355C8.55268 7.75978 8.5 7.6326 8.5 7.49999C8.5 7.36738 8.55268 7.24021 8.64645 7.14644C8.74022 7.05267 8.86739 6.99999 9 6.99999H10.75C11.198 6.99957 11.6289 6.82748 11.9539 6.51912C12.279 6.21076 12.4735 5.78957 12.4975 5.34218C12.5215 4.89478 12.3732 4.45519 12.083 4.11381C11.7929 3.77243 11.3829 3.55521 10.9375 3.50683C10.8238 3.49477 10.7176 3.44408 10.6368 3.36321C10.5559 3.28235 10.5052 3.17621 10.4932 3.06249C10.4474 2.63252 10.2439 2.23477 9.92194 1.94616C9.59996 1.65755 9.1824 1.49858 8.75 1.49999C8.42739 1.49788 8.11079 1.58727 7.83692 1.7578C7.74186 1.81745 7.62955 1.84351 7.51793 1.83182C7.40632 1.82014 7.30184 1.77139 7.22119 1.69335C6.76046 1.24566 6.14241 0.996689 5.5 0.999993C4.89213 1.00014 4.30514 1.22176 3.84885 1.6234C3.39257 2.02505 3.09826 2.57918 3.021 3.18212C3.0093 3.27543 2.97153 3.36354 2.91202 3.43635C2.85252 3.50915 2.77368 3.56371 2.68458 3.59374C2.29236 3.72766 1.9604 3.99644 1.7478 4.35221C1.5352 4.70798 1.45576 5.12765 1.52363 5.53651C1.5915 5.94537 1.80227 6.31687 2.11841 6.58487C2.43455 6.85287 2.83555 6.99998 3.25 6.99999H5C5.13261 6.99999 5.25979 7.05267 5.35356 7.14644C5.44732 7.24021 5.5 7.36738 5.5 7.49999C5.5 7.6326 5.44732 7.75978 5.35356 7.85355C5.25979 7.94732 5.13261 7.99999 5 7.99999H3.25C2.62484 7.99986 2.01838 7.78676 1.53053 7.39582C1.04269 7.00488 0.702574 6.45942 0.566223 5.84931C0.429872 5.2392 0.505423 4.60084 0.780426 4.03942C1.05543 3.47799 1.51348 3.02699 2.0791 2.76073C2.24864 1.97926 2.68041 1.27929 3.3027 0.777092C3.92499 0.274892 4.70035 0.000678213 5.5 -6.73109e-06C6.27505 -0.00288261 7.02853 0.255097 7.63916 0.732413C8.00591 0.57151 8.40329 0.492395 8.8037 0.500566C9.20411 0.508738 9.59793 0.604 9.95781 0.779733C10.3177 0.955465 10.635 1.20745 10.8876 1.51818C11.1403 1.82892 11.3223 2.19094 11.4209 2.57909C12.0715 2.74321 12.6398 3.13936 13.0188 3.69306C13.3979 4.24676 13.5616 4.91986 13.4792 5.58579C13.3967 6.25172 13.0739 6.8646 12.5713 7.30919C12.0687 7.75378 11.421 7.99945 10.75 7.99999Z"
fill="#008184" />
</svg>

After

Width:  |  Height:  |  Size: 3.0 KiB

View File

@@ -0,0 +1,8 @@
<svg width="14" height="11" viewBox="0 0 14 11" fill="none" xmlns="http://www.w3.org/2000/svg">
<path
d="M9.35509 5.85499C9.26032 5.94794 9.13286 6.00001 9.00011 6.00001C8.86736 6.00001 8.73991 5.94794 8.64513 5.85499L7.50009 4.70494V10.5C7.50009 10.6326 7.44741 10.7598 7.35365 10.8535C7.25988 10.9473 7.1327 11 7.00009 11C6.86748 11 6.74031 10.9473 6.64654 10.8535C6.55277 10.7598 6.50009 10.6326 6.50009 10.5V4.70494L5.35509 5.85499C5.26094 5.94914 5.13324 6.00204 5.00009 6.00204C4.86694 6.00204 4.73924 5.94914 4.64509 5.85499C4.55094 5.76084 4.49805 5.63314 4.49805 5.49999C4.49805 5.36684 4.55094 5.23914 4.64509 5.14499L6.64509 3.14499C6.73947 3.05128 6.86707 2.99869 7.00007 2.99869C7.13307 2.99869 7.26068 3.05128 7.35505 3.14499L9.35505 5.14499C9.44875 5.23938 9.50134 5.36698 9.50135 5.49998C9.50136 5.63298 9.44878 5.76059 9.35509 5.85499Z"
fill="#008184" />
<path
d="M10.75 7.99999H9C8.86739 7.99999 8.74022 7.94732 8.64645 7.85355C8.55268 7.75978 8.5 7.6326 8.5 7.49999C8.5 7.36738 8.55268 7.24021 8.64645 7.14644C8.74022 7.05267 8.86739 6.99999 9 6.99999H10.75C11.198 6.99957 11.6289 6.82748 11.9539 6.51912C12.279 6.21076 12.4735 5.78957 12.4975 5.34218C12.5215 4.89478 12.3732 4.45519 12.083 4.11381C11.7929 3.77243 11.3829 3.55521 10.9375 3.50683C10.8238 3.49477 10.7176 3.44408 10.6368 3.36321C10.5559 3.28235 10.5052 3.17621 10.4932 3.06249C10.4474 2.63252 10.2439 2.23477 9.92194 1.94616C9.59996 1.65755 9.1824 1.49858 8.75 1.49999C8.42739 1.49788 8.11079 1.58727 7.83692 1.7578C7.74185 1.81743 7.62955 1.84349 7.51794 1.8318C7.40633 1.82012 7.30185 1.77138 7.22119 1.69335C6.76046 1.24566 6.14241 0.996689 5.5 0.999993C4.89213 1.00014 4.30514 1.22176 3.84885 1.6234C3.39257 2.02505 3.09826 2.57918 3.021 3.18212C3.0093 3.27543 2.97153 3.36354 2.91202 3.43635C2.85252 3.50915 2.77368 3.56371 2.68458 3.59374C2.29236 3.72766 1.9604 3.99644 1.7478 4.35221C1.5352 4.70798 1.45576 5.12765 1.52363 5.53651C1.5915 5.94537 1.80227 6.31687 2.11841 6.58487C2.43455 6.85287 2.83555 6.99998 3.25 6.99999H5C5.13261 6.99999 5.25979 7.05267 5.35356 7.14644C5.44732 7.24021 5.5 7.36738 5.5 7.49999C5.5 7.6326 5.44732 7.75978 5.35356 7.85355C5.25979 7.94732 5.13261 7.99999 5 7.99999H3.25C2.62484 7.99986 2.01838 7.78676 1.53053 7.39582C1.04269 7.00488 0.702574 6.45942 0.566223 5.84931C0.429872 5.2392 0.505423 4.60084 0.780426 4.03942C1.05543 3.47799 1.51348 3.02699 2.0791 2.76073C2.24864 1.97926 2.68041 1.27929 3.3027 0.777092C3.92499 0.274892 4.70035 0.000678213 5.5 -6.73109e-06C6.27505 -0.00288261 7.02853 0.255097 7.63916 0.732413C8.00591 0.57151 8.40329 0.492395 8.8037 0.500566C9.20411 0.508738 9.59793 0.604 9.95781 0.779733C10.3177 0.955465 10.635 1.20745 10.8876 1.51818C11.1403 1.82892 11.3223 2.19094 11.4209 2.57909C12.0715 2.74321 12.6398 3.13936 13.0188 3.69306C13.3979 4.24676 13.5616 4.91986 13.4792 5.58579C13.3967 6.25172 13.0739 6.8646 12.5713 7.30919C12.0687 7.75378 11.421 7.99945 10.75 7.99999Z"
fill="#008184" />
</svg>

After

Width:  |  Height:  |  Size: 2.9 KiB

View File

@@ -0,0 +1,3 @@
<svg width="15" height="15" viewBox="0 0 15 15" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M7.00129 14.9989C8.85781 14.9989 10.6383 14.2614 11.951 12.9486C13.2638 11.6359 14.0013 9.85539 14.0013 7.99887C14.0013 7.86626 13.9486 7.73909 13.8548 7.64532C13.7611 7.55155 13.6339 7.49887 13.5013 7.49887C13.3687 7.49887 13.2415 7.55155 13.1477 7.64532C13.054 7.73909 13.0013 7.86626 13.0013 7.99887C13.001 9.3709 12.5305 10.7014 11.6682 11.7686C10.8059 12.8358 9.60391 13.5752 8.26254 13.8636C6.92117 14.152 5.52147 13.972 4.29674 13.3535C3.072 12.7351 2.09622 11.7156 1.53204 10.4649C0.967851 9.21424 0.849341 7.808 1.19626 6.48056C1.54318 5.15311 2.33457 3.98466 3.43852 3.16996C4.54248 2.35526 5.8923 1.94352 7.26302 2.00337C8.63374 2.06322 9.94255 2.59105 10.9713 3.49887L8.50129 3.49887C8.36868 3.49887 8.24151 3.55155 8.14774 3.64532C8.05397 3.73909 8.00129 3.86626 8.00129 3.99887C8.00129 4.13148 8.05397 4.25866 8.14774 4.35242C8.24151 4.44619 8.36868 4.49887 8.50129 4.49887L12.0013 4.49887C12.1339 4.49887 12.2611 4.44619 12.3548 4.35243C12.4486 4.25866 12.5013 4.13148 12.5013 3.99887L12.5013 0.498871C12.5013 0.366263 12.4486 0.239086 12.3548 0.145318C12.2611 0.0515498 12.1339 -0.00112862 12.0013 -0.00112863C11.8687 -0.00112863 11.7415 0.0515498 11.6477 0.145318C11.554 0.239086 11.5013 0.366263 11.5013 0.498871L11.5013 2.63887C10.6394 1.91492 9.61569 1.40949 8.5169 1.16542C7.4181 0.921352 6.27666 0.945851 5.18935 1.23684C4.10204 1.52783 3.10093 2.07673 2.27092 2.83699C1.44091 3.59725 0.806473 4.54645 0.421403 5.60411C0.0363342 6.66176 -0.0880083 7.79668 0.0589193 8.91262C0.205847 10.0286 0.619712 11.0926 1.26542 12.0146C1.91113 12.9365 2.76964 13.6891 3.76814 14.2087C4.76665 14.7282 5.87572 14.9992 7.00129 14.9989Z" fill="#424242"/>
</svg>

After

Width:  |  Height:  |  Size: 1.7 KiB

View File

@@ -0,0 +1,4 @@
<svg width="8" height="7" viewBox="0 0 8 7" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M2.5 6.18999C2.415 6.18999 2.33 6.16999 2.25 6.12499C1.17 5.49999 0.5 4.33999 0.5 3.09499C0.5 1.84999 1.17 0.689992 2.25 0.0649925C2.49 -0.0700075 2.795 0.00999246 2.935 0.249992C3.07 0.489992 2.99 0.794992 2.75 0.934992C1.98 1.37499 1.5 2.20499 1.5 3.09499C1.5 3.98499 1.98 4.81499 2.75 5.25499C2.99 5.39499 3.07 5.69999 2.935 5.93999C2.84 6.09999 2.675 6.18999 2.5 6.18999Z" fill="#008184"/>
<path d="M5.49993 6.18999C5.32493 6.18999 5.15993 6.09999 5.06493 5.93999C4.92493 5.69999 5.00993 5.39499 5.24993 5.25499C6.01993 4.81499 6.49993 3.98499 6.49993 3.09499C6.49993 2.20499 6.01993 1.37499 5.24993 0.934992C5.00993 0.794992 4.92993 0.489992 5.06493 0.249992C5.20493 0.00999246 5.50993 -0.0700075 5.74993 0.0649925C6.82993 0.689992 7.49993 1.84999 7.49993 3.09499C7.49993 4.33999 6.82993 5.49999 5.74993 6.12499C5.66993 6.16999 5.58493 6.18999 5.49993 6.18999Z" fill="#008184"/>
</svg>

After

Width:  |  Height:  |  Size: 992 B

View File

@@ -0,0 +1,10 @@
<svg width="12" height="2" viewBox="0 0 12 2" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M6 2C6.55228 2 7 1.55228 7 1C7 0.447715 6.55228 0 6 0C5.44772 0 5 0.447715 5 1C5 1.55228 5.44772 2 6 2Z"
fill="#008184" />
<path
d="M10.5 2C11.0523 2 11.5 1.55228 11.5 1C11.5 0.447715 11.0523 0 10.5 0C9.94772 0 9.5 0.447715 9.5 1C9.5 1.55228 9.94772 2 10.5 2Z"
fill="#008184" />
<path
d="M1.5 2C2.05228 2 2.5 1.55228 2.5 1C2.5 0.447715 2.05228 0 1.5 0C0.947715 0 0.5 0.447715 0.5 1C0.5 1.55228 0.947715 2 1.5 2Z"
fill="#008184" />
</svg>

After

Width:  |  Height:  |  Size: 567 B

View File

@@ -0,0 +1,11 @@
<svg width="20" height="14" viewBox="0 0 20 14" fill="none" xmlns="http://www.w3.org/2000/svg">
<path
d="M19.2492 12.2509L17.4992 9.9197V1.37595C17.4987 1.21033 17.4327 1.05164 17.3156 0.934533C17.1985 0.817426 17.0398 0.751424 16.8742 0.750946H3.12422C2.95861 0.751441 2.79992 0.817448 2.68282 0.934551C2.56572 1.05165 2.49971 1.21034 2.49922 1.37595V9.9197L0.749217 12.2509C0.679462 12.3442 0.637219 12.455 0.627276 12.571C0.617334 12.687 0.640091 12.8035 0.692967 12.9072C0.745302 13.0099 0.824858 13.0964 0.922952 13.157C1.02105 13.2176 1.13391 13.2501 1.24922 13.2509H18.7492C18.8645 13.2501 18.9774 13.2176 19.0755 13.157C19.1736 13.0964 19.2531 13.0099 19.3055 12.9072C19.3583 12.8035 19.3811 12.687 19.3712 12.571C19.3612 12.455 19.319 12.3442 19.2492 12.2509ZM3.74922 2.00095H16.2492V9.50095H3.74922V2.00095ZM2.49922 12.0009L3.43672 10.7509H16.5617L17.4992 12.0009H2.49922Z"
fill="#616161" />
<path
d="M7.49987 7.62501C7.37627 7.62498 7.25546 7.58831 7.15271 7.51964C7.04995 7.45096 6.96986 7.35336 6.92257 7.23917C6.87527 7.12498 6.8629 6.99934 6.887 6.87812C6.91111 6.7569 6.97061 6.64554 7.05799 6.55814L9.55799 4.05814C9.67587 3.94429 9.83374 3.88129 9.99762 3.88271C10.1615 3.88414 10.3182 3.94987 10.4341 4.06575C10.55 4.18163 10.6157 4.33839 10.6172 4.50226C10.6186 4.66613 10.5556 4.82401 10.4417 4.94189L7.94174 7.44189C7.88379 7.50002 7.81491 7.54612 7.73908 7.57755C7.66325 7.60898 7.58195 7.62511 7.49987 7.62501Z"
fill="#616161" />
<path
d="M6.24987 5.12501C6.12627 5.12498 6.00546 5.08831 5.90271 5.01964C5.79995 4.95096 5.71986 4.85336 5.67257 4.73917C5.62527 4.62498 5.6129 4.49934 5.637 4.37812C5.66111 4.2569 5.72061 4.14554 5.80799 4.05814L6.43299 3.43314C6.55087 3.31929 6.70874 3.25629 6.87262 3.25771C7.03649 3.25914 7.19325 3.32487 7.30913 3.44075C7.42501 3.55663 7.49074 3.71339 7.49216 3.87726C7.49359 4.04113 7.43059 4.19901 7.31674 4.31688L6.69174 4.94189C6.63379 5.00002 6.56491 5.04612 6.48908 5.07755C6.41325 5.10898 6.33195 5.12511 6.24987 5.12501Z"
fill="#616161" />
</svg>

After

Width:  |  Height:  |  Size: 2.0 KiB

View File

@@ -0,0 +1,38 @@
.sketchbook-tab-icon {
-webkit-mask: url('./sketchbook.svg');
mask: url('./sketchbook.svg');
}
.sketch-folder-icon {
background: url('./sketch-folder-icon.svg') center center no-repeat;
background-position-x: 1px;
width: var(--theia-icon-size);
height: var(--theia-icon-size);
}
.sketchbook-tree-icon {
background: url('./sketchbook-tree-icon.svg') center center no-repeat;
width: 19px !important;
height: var(--theia-icon-size);
}
.sketchbook-trees-container {
height: 100%;
}
.sketchbook-tree__opts {
background: url('./sketchbook-opts-icon.svg') center center no-repeat;
width: var(--theia-icon-size);
height: var(--theia-icon-size);
}
.active-sketch {
font-weight: 500;
background-color: var(--theia-button-disabledBackground) !important;
color: var(--theia-list-inactiveSelectionForeground) !important;
}
#arduino-sketchbook-tree-widget .theia-TreeNodeSegmentGrow {
flex: 1;
}

View File

@@ -0,0 +1,3 @@
<svg width="22" height="18" viewBox="0 0 22 18" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M20.625 3.75001H11.3587L8.12125 0.503765C8.03949 0.422668 7.94253 0.358509 7.83592 0.314965C7.72931 0.271421 7.61516 0.249349 7.5 0.250015H1.375C1.14294 0.250015 0.920376 0.342202 0.756282 0.506296C0.592187 0.670391 0.5 0.89295 0.5 1.12501V16.875C0.5 17.1071 0.592187 17.3296 0.756282 17.4937C0.920376 17.6578 1.14294 17.75 1.375 17.75H20.625C20.8571 17.75 21.0796 17.6578 21.2437 17.4937C21.4078 17.3296 21.5 17.1071 21.5 16.875V4.62501C21.5 4.39295 21.4078 4.17039 21.2437 4.0063C21.0796 3.8422 20.8571 3.75001 20.625 3.75001ZM2.25 2.00001H7.14125L8.89125 3.75001H2.25V2.00001ZM19.75 16H2.25V5.50001H19.75V16Z" fill="#4E5B61"/>
</svg>

After

Width:  |  Height:  |  Size: 742 B

View File

@@ -1,18 +1,22 @@
import { injectable, inject } from 'inversify';
import { EditorWidget } from '@theia/editor/lib/browser';
import { CommandService } from '@theia/core/lib/common/command';
import { MessageService } from '@theia/core/lib/common/message-service';
import { OutputWidget } from '@theia/output/lib/browser/output-widget';
import { ConnectionStatusService, ConnectionStatus } from '@theia/core/lib/browser/connection-status-service';
import { ApplicationShell as TheiaApplicationShell, Widget } from '@theia/core/lib/browser';
import {
ConnectionStatusService,
ConnectionStatus,
} from '@theia/core/lib/browser/connection-status-service';
import {
ApplicationShell as TheiaApplicationShell,
Widget,
} from '@theia/core/lib/browser';
import { Sketch } from '../../../common/protocol';
import { SaveAsSketch } from '../../contributions/save-as-sketch';
import { SketchesServiceClientImpl } from '../../../common/protocol/sketches-service-client-impl';
@injectable()
export class ApplicationShell extends TheiaApplicationShell {
@inject(CommandService)
protected readonly commandService: CommandService;
@@ -32,7 +36,7 @@ export class ApplicationShell extends TheiaApplicationShell {
}
if (widget instanceof EditorWidget) {
// Make the editor un-closeable asynchronously.
this.sketchesServiceClient.currentSketch().then(sketch => {
this.sketchesServiceClient.currentSketch().then((sketch) => {
if (sketch) {
if (Sketch.isInSketch(widget.editor.uri, sketch)) {
widget.title.closable = false;
@@ -42,15 +46,20 @@ export class ApplicationShell extends TheiaApplicationShell {
}
}
async addWidget(widget: Widget, options: Readonly<TheiaApplicationShell.WidgetOptions> = {}): Promise<void> {
async addWidget(
widget: Widget,
options: Readonly<TheiaApplicationShell.WidgetOptions> = {}
): Promise<void> {
// By default, Theia open a widget **next** to the currently active in the target area.
// Instead of this logic, we want to open the new widget after the last of the target area.
if (!widget.id) {
console.error('Widgets added to the application shell must have a unique id property.');
console.error(
'Widgets added to the application shell must have a unique id property.'
);
return;
}
let ref: Widget | undefined = options.ref;
let area: TheiaApplicationShell.Area = options.area || 'main';
const area: TheiaApplicationShell.Area = options.area || 'main';
if (!ref && (area === 'main' || area === 'bottom')) {
const tabBar = this.getTabBarFor(area);
if (tabBar) {
@@ -64,13 +73,20 @@ export class ApplicationShell extends TheiaApplicationShell {
}
async saveAll(): Promise<void> {
if (this.connectionStatusService.currentStatus === ConnectionStatus.OFFLINE) {
this.messageService.error('Could not save the sketch. Please copy your unsaved work into your favorite text editor, and restart the IDE.');
if (
this.connectionStatusService.currentStatus ===
ConnectionStatus.OFFLINE
) {
this.messageService.error(
'Could not save the sketch. Please copy your unsaved work into your favorite text editor, and restart the IDE.'
);
return; // Theia does not reject on failed save: https://github.com/eclipse-theia/theia/pull/8803
}
await super.saveAll();
const options = { execOnlyIfTemp: true, openAfterMove: true };
await this.commandService.executeCommand(SaveAsSketch.Commands.SAVE_AS_SKETCH.id, options);
await this.commandService.executeCommand(
SaveAsSketch.Commands.SAVE_AS_SKETCH.id,
options
);
}
}

View File

@@ -1,10 +1,15 @@
import { injectable } from 'inversify';
import { BrowserMainMenuFactory as TheiaBrowserMainMenuFactory, MenuBarWidget } from '@theia/core/lib/browser/menu/browser-menu-plugin';
import {
BrowserMainMenuFactory as TheiaBrowserMainMenuFactory,
MenuBarWidget,
} from '@theia/core/lib/browser/menu/browser-menu-plugin';
import { MainMenuManager } from '../../../common/main-menu-manager';
@injectable()
export class BrowserMainMenuFactory extends TheiaBrowserMainMenuFactory implements MainMenuManager {
export class BrowserMainMenuFactory
extends TheiaBrowserMainMenuFactory
implements MainMenuManager
{
protected menuBar: MenuBarWidget | undefined;
createMenuBar(): MenuBarWidget {
@@ -18,5 +23,4 @@ export class BrowserMainMenuFactory extends TheiaBrowserMainMenuFactory implemen
this.fillMenuBar(this.menuBar);
}
}
}

View File

@@ -1,6 +1,9 @@
import '../../../../src/browser/style/browser-menu.css';
import { ContainerModule } from 'inversify';
import { BrowserMenuBarContribution, BrowserMainMenuFactory as TheiaBrowserMainMenuFactory } from '@theia/core/lib/browser/menu/browser-menu-plugin';
import {
BrowserMenuBarContribution,
BrowserMainMenuFactory as TheiaBrowserMainMenuFactory,
} from '@theia/core/lib/browser/menu/browser-menu-plugin';
import { MainMenuManager } from '../../../common/main-menu-manager';
import { ArduinoMenuContribution } from './browser-menu-plugin';
import { BrowserMainMenuFactory } from './browser-main-menu-factory';
@@ -9,5 +12,7 @@ export default new ContainerModule((bind, unbind, isBound, rebind) => {
bind(BrowserMainMenuFactory).toSelf().inSingletonScope();
bind(MainMenuManager).toService(BrowserMainMenuFactory);
rebind(TheiaBrowserMainMenuFactory).toService(BrowserMainMenuFactory);
rebind(BrowserMenuBarContribution).to(ArduinoMenuContribution).inSingletonScope();
rebind(BrowserMenuBarContribution)
.to(ArduinoMenuContribution)
.inSingletonScope();
});

View File

@@ -4,10 +4,8 @@ import { BrowserMenuBarContribution } from '@theia/core/lib/browser/menu/browser
@injectable()
export class ArduinoMenuContribution extends BrowserMenuBarContribution {
onStart(app: FrontendApplication): void {
const menu = this.factory.createMenuBar();
app.shell.addWidget(menu, { area: 'top' });
}
}

View File

@@ -21,6 +21,10 @@ export class CommonFrontendContribution extends TheiaCommonFrontendContribution
CommonCommands.SELECT_ICON_THEME,
CommonCommands.SELECT_COLOR_THEME,
CommonCommands.ABOUT_COMMAND,
CommonCommands.CLOSE_TAB,
CommonCommands.CLOSE_OTHER_TABS,
CommonCommands.CLOSE_ALL_TABS,
CommonCommands.COLLAPSE_PANEL,
CommonCommands.SAVE_WITHOUT_FORMATTING // Patched for https://github.com/eclipse-theia/theia/pull/8877
]) {
registry.unregisterMenuAction(command);

View File

@@ -4,14 +4,13 @@ import { StatusBarAlignment } from '@theia/core/lib/browser/status-bar/status-ba
import {
FrontendConnectionStatusService as TheiaFrontendConnectionStatusService,
ApplicationConnectionStatusContribution as TheiaApplicationConnectionStatusContribution,
ConnectionStatus
ConnectionStatus,
} from '@theia/core/lib/browser/connection-status-service';
import { ArduinoDaemon } from '../../../common/protocol';
import { NotificationCenter } from '../../notification-center';
@injectable()
export class FrontendConnectionStatusService extends TheiaFrontendConnectionStatusService {
@inject(ArduinoDaemon)
protected readonly daemon: ArduinoDaemon;
@@ -25,20 +24,18 @@ export class FrontendConnectionStatusService extends TheiaFrontendConnectionStat
this.schedulePing();
try {
this.isRunning = await this.daemon.isRunning();
} catch { }
this.notificationCenter.onDaemonStarted(() => this.isRunning = true);
this.notificationCenter.onDaemonStopped(() => this.isRunning = false);
} catch {}
this.notificationCenter.onDaemonStarted(() => (this.isRunning = true));
this.notificationCenter.onDaemonStopped(() => (this.isRunning = false));
this.wsConnectionProvider.onIncomingMessageActivity(() => {
this.updateStatus(this.isRunning);
this.schedulePing();
});
}
}
@injectable()
export class ApplicationConnectionStatusContribution extends TheiaApplicationConnectionStatusContribution {
@inject(ArduinoDaemon)
protected readonly daemon: ArduinoDaemon;
@@ -51,9 +48,9 @@ export class ApplicationConnectionStatusContribution extends TheiaApplicationCon
protected async init(): Promise<void> {
try {
this.isRunning = await this.daemon.isRunning();
} catch { }
this.notificationCenter.onDaemonStarted(() => this.isRunning = true);
this.notificationCenter.onDaemonStopped(() => this.isRunning = false);
} catch {}
this.notificationCenter.onDaemonStarted(() => (this.isRunning = true));
this.notificationCenter.onDaemonStopped(() => (this.isRunning = false));
}
protected onStateChange(state: ConnectionStatus): void {
@@ -67,12 +64,21 @@ export class ApplicationConnectionStatusContribution extends TheiaApplicationCon
this.statusBar.setElement('connection-status', {
alignment: StatusBarAlignment.LEFT,
text: this.isRunning ? 'Offline' : '$(bolt) CLI Daemon Offline',
tooltip: this.isRunning ? 'Cannot connect to the backend.' : 'Cannot connect to the CLI daemon.',
priority: 5000
tooltip: this.isRunning
? 'Cannot connect to the backend.'
: 'Cannot connect to the CLI daemon.',
priority: 5000,
});
this.toDisposeOnOnline.push(Disposable.create(() => this.statusBar.removeElement('connection-status')));
this.toDisposeOnOnline.push(
Disposable.create(() =>
this.statusBar.removeElement('connection-status')
)
);
document.body.classList.add('theia-mod-offline');
this.toDisposeOnOnline.push(Disposable.create(() => document.body.classList.remove('theia-mod-offline')));
this.toDisposeOnOnline.push(
Disposable.create(() =>
document.body.classList.remove('theia-mod-offline')
)
);
}
}

View File

@@ -8,7 +8,6 @@ import { ArduinoCommands } from '../../arduino-commands';
@injectable()
export class FrontendApplication extends TheiaFrontendApplication {
@inject(FileService)
protected readonly fileService: FileService;
@@ -27,10 +26,14 @@ export class FrontendApplication extends TheiaFrontendApplication {
for (const root of roots) {
const exists = await this.fileService.exists(root.resource);
if (exists) {
this.sketchesService.markAsRecentlyOpened(root.resource.toString()); // no await, will get the notification later and rebuild the menu
await this.commandService.executeCommand(ArduinoCommands.OPEN_SKETCH_FILES.id, root.resource);
this.sketchesService.markAsRecentlyOpened(
root.resource.toString()
); // no await, will get the notification later and rebuild the menu
await this.commandService.executeCommand(
ArduinoCommands.OPEN_SKETCH_FILES.id,
root.resource
);
}
}
}
}

View File

@@ -1,11 +1,13 @@
import { injectable } from 'inversify';
import { Command } from '@theia/core/lib/common/command';
import { Keybinding } from '@theia/core/lib/common/keybinding';
import { KeybindingRegistry as TheiaKeybindingRegistry, KeybindingScope } from '@theia/core/lib/browser/keybinding';
import {
KeybindingRegistry as TheiaKeybindingRegistry,
KeybindingScope,
} from '@theia/core/lib/browser/keybinding';
@injectable()
export class KeybindingRegistry extends TheiaKeybindingRegistry {
// https://github.com/eclipse-theia/theia/issues/8209
unregisterKeybinding(key: string): void;
unregisterKeybinding(keybinding: Keybinding): void;
@@ -14,9 +16,10 @@ export class KeybindingRegistry extends TheiaKeybindingRegistry {
const keymap = this.keymaps[KeybindingScope.DEFAULT];
const filter = Command.is(arg)
? ({ command }: Keybinding) => command === arg.id
: ({ keybinding }: Keybinding) => Keybinding.is(arg)
? keybinding === arg.keybinding
: keybinding === arg;
: ({ keybinding }: Keybinding) =>
Keybinding.is(arg)
? keybinding === arg.keybinding
: keybinding === arg;
for (const binding of keymap.filter(filter)) {
const idx = keymap.indexOf(binding);
if (idx !== -1) {
@@ -24,5 +27,4 @@ export class KeybindingRegistry extends TheiaKeybindingRegistry {
}
}
}
}

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