Compare commits

..

No commits in common. "main" and "0.1.1" have entirely different histories.
main ... 0.1.1

727 changed files with 56019 additions and 151121 deletions

View File

@ -1,66 +0,0 @@
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/*',
'.github/*',
'.browser_modules/*',
'docs/*',
'scripts/*',
'electron-app/lib/*',
'electron-app/src-gen/*',
'electron-app/gen-webpack*.js',
'!electron-app/webpack.config.js',
'electron-app/plugins/*',
'arduino-ide-extension/src/node/cli-protocol',
'**/lib/*',
],
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

@ -1,74 +0,0 @@
name: Bug report
description: Report a problem with the code or documentation in this repository.
labels:
- 'type: imperfection'
body:
- type: textarea
id: description
attributes:
label: Describe the problem
validations:
required: true
- type: textarea
id: reproduce
attributes:
label: To reproduce
description: Provide the specific set of steps we can follow to reproduce the problem.
validations:
required: true
- type: textarea
id: expected
attributes:
label: Expected behavior
description: What would you expect to happen after following those instructions?
validations:
required: true
- type: input
id: project-version
attributes:
label: Arduino IDE version
description: |
Which version of the Arduino IDE are you using?
See **Help > About Arduino IDE** in the Arduino IDE menus (**Arduino IDE > About Arduino IDE** on macOS).
This should be the latest [nightly build](https://www.arduino.cc/en/software#nightly-builds).
validations:
required: true
- type: dropdown
id: os
attributes:
label: Operating system
description: Which operating system(s) are you using on your computer?
multiple: true
options:
- Windows
- Linux
- macOS
- N/A
validations:
required: true
- type: input
id: os-version
attributes:
label: Operating system version
description: Which version of the operating system are you using on your computer?
validations:
required: true
- type: textarea
id: additional
attributes:
label: Additional context
description: Add any additional information here.
validations:
required: false
- type: checkboxes
id: checklist
attributes:
label: Issue checklist
description: Please double-check that you have done each of the following things before submitting the issue.
options:
- label: I searched for previous reports in [the issue tracker](https://github.com/arduino/arduino-ide/issues?q=)
required: true
- label: I verified the problem still occurs when using the latest [nightly build](https://www.arduino.cc/en/software#nightly-builds)
required: true
- label: My report contains all necessary details
required: true

View File

@ -1,19 +0,0 @@
# Source:
# https://github.com/arduino/tooling-project-assets/blob/main/issue-templates/template-choosers/general/config.yml
blank_issues_enabled: false
contact_links:
- name: Learn about using this project
url: https://github.com/arduino/arduino-ide#readme
about: Detailed usage documentation is available here.
- name: Support request
url: https://forum.arduino.cc/
about: We can help you out on the Arduino Forum!
- name: Issue report guide
url: https://github.com/arduino/arduino-ide/blob/main/docs/contributor-guide/issues.md#issue-report-guide
about: Learn about submitting issue reports to this repository.
- name: Contributor guide
url: https://github.com/arduino/arduino-ide/blob/main/docs/CONTRIBUTING.md#contributor-guide
about: Learn about contributing to this project.
- name: Discuss development work on the project
url: https://groups.google.com/a/arduino.cc/g/developers
about: Arduino Developers Mailing List

View File

@ -1,69 +0,0 @@
name: Feature request
description: Suggest an enhancement to this project.
labels:
- 'type: enhancement'
body:
- type: textarea
id: description
attributes:
label: Describe the request
validations:
required: true
- type: textarea
id: current
attributes:
label: Describe the current behavior
description: |
What is the current behavior of the Arduino IDE in relation to your request?
How can we reproduce that behavior?
validations:
required: true
- type: input
id: project-version
attributes:
label: Arduino IDE version
description: |
Which version of the Arduino IDE are you using?
See **Help > About Arduino IDE** in the Arduino IDE menus (**Arduino IDE > About Arduino IDE** on macOS).
This should be the latest [nightly build](https://www.arduino.cc/en/software#nightly-builds).
validations:
required: true
- type: dropdown
id: os
attributes:
label: Operating system
description: Which operating system(s) are you using on your computer?
multiple: true
options:
- Windows
- Linux
- macOS
- N/A
validations:
required: true
- type: input
id: os-version
attributes:
label: Operating system version
description: Which version of the operating system are you using on your computer?
validations:
required: true
- type: textarea
id: additional
attributes:
label: Additional context
description: Add any additional information here.
validations:
required: false
- type: checkboxes
id: checklist
attributes:
label: Issue checklist
description: Please double-check that you have done each of the following things before submitting the issue.
options:
- label: I searched for previous requests in [the issue tracker](https://github.com/arduino/arduino-ide/issues?q=)
required: true
- label: I verified the feature was still missing when using the latest [nightly build](https://www.arduino.cc/en/software#nightly-builds)
required: true
- label: My request contains all necessary details
required: true

View File

@ -1,18 +0,0 @@
### Motivation
<!-- Why this pull request? -->
### Change description
<!-- What does your code do? -->
### Other information
<!-- Any additional information that could help the review process -->
### Reviewer checklist
- [ ] PR addresses a single concern.
- [ ] The PR has no duplicates (please search among the [Pull Requests](https://github.com/arduino/arduino-ide/pulls) before creating one)
- [ ] PR title and description are properly filled.
- [ ] Docs have been added / updated (for bug fixes / features)

View File

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

View File

@ -1,27 +0,0 @@
# Used by the "Sync Labels" workflow
# See: https://github.com/Financial-Times/github-label-sync#label-config-file
- name: 'topic: accessibility'
color: '00ffff'
description: Enabling the use of the software by everyone
- name: 'topic: CLI'
color: '00ffff'
description: Related to Arduino CLI
- name: 'topic: cloud'
color: '00ffff'
description: Related to Arduino Cloud and cloud sketches
- name: 'topic: debugger'
color: '00ffff'
description: Related to the integrated debugger
- name: 'topic: language server'
color: '00ffff'
description: Related to the Arduino Language Server
- name: 'topic: serial monitor'
color: '00ffff'
description: Related to the Serial Monitor
- name: 'topic: theia'
color: '00ffff'
description: Related to the Theia IDE framework
- name: 'topic: theme'
color: '00ffff'
description: Related to GUI theming

View File

@ -1,63 +0,0 @@
# The Arduino IDE Linux build workflow job runs in this container.
# syntax=docker/dockerfile:1
# See: https://hub.docker.com/_/ubuntu/tags
FROM ubuntu:18.10
# This is required in order to use the Ubuntu package repositories for EOL Ubuntu versions:
# https://help.ubuntu.com/community/EOLUpgrades#Update_sources.list
RUN \
sed \
--in-place \
--regexp-extended \
--expression='s/([a-z]{2}\.)?archive.ubuntu.com|security.ubuntu.com/old-releases.ubuntu.com/g' \
"/etc/apt/sources.list"
RUN \
apt-get \
--yes \
update
RUN \
apt-get \
--yes \
install \
"git"
# The repository path must be added to safe.directory, otherwise any Git operations on it would fail with a
# "dubious ownership" error. actions/checkout configures this, but it is not applied to containers.
RUN \
git config \
--add \
--global \
"safe.directory" "/__w/arduino-ide/arduino-ide"
ENV \
GIT_CONFIG_GLOBAL="/root/.gitconfig"
# Install Python
# The Python installed by actions/setup-python has dependency on a higher version of glibc than available in the
# container.
RUN \
apt-get \
--yes \
install \
"python3.7-minimal=3.7.3-2~18.10"
# Install Theia's package dependencies
# These are pre-installed in the GitHub Actions hosted runner machines.
RUN \
apt-get \
--yes \
install \
"libsecret-1-dev=0.18.6-3" \
"libx11-dev=2:1.6.7-1" \
"libxkbfile-dev=1:1.0.9-2"
# Target python3 symlink to Python 3.7 installation. It would otherwise target version 3.6 due to the installation of
# the `python3` package as a transitive dependency.
RUN \
ln \
--symbolic \
--force \
"$(which python3.7)" \
"/usr/bin/python3"

View File

@ -1,694 +1,133 @@
name: Arduino IDE
name: Arduino Pro IDE
on:
create:
push:
branches:
- main
- '[0-9]+.[0-9]+.x'
paths-ignore:
- '.github/**'
- '!.github/workflows/build.yml'
- '.vscode/**'
- 'docs/**'
- 'scripts/**'
- '!scripts/merge-channel-files.js'
- 'static/**'
- '*.md'
- master
tags:
- '[0-9]+.[0-9]+.[0-9]+*'
workflow_dispatch:
inputs:
paid-runners:
description: Include builds on non-free runners
type: boolean
default: false
pull_request:
paths-ignore:
- '.github/**'
- '!.github/workflows/build.yml'
- '.vscode/**'
- 'docs/**'
- 'scripts/**'
- '!scripts/merge-channel-files.js'
- 'static/**'
- '*.md'
branches:
- master
schedule:
- cron: '0 3 * * *' # run every day at 3AM (https://docs.github.com/en/actions/reference/events-that-trigger-workflows#scheduled-events-schedule)
workflow_run:
workflows:
- Push Container Images
branches:
- main
types:
- completed
env:
# See vars.GO_VERSION field of https://github.com/arduino/arduino-cli/blob/master/DistTasks.yml
GO_VERSION: '1.21'
# See: https://github.com/actions/setup-node/#readme
NODE_VERSION: '18.17'
YARN_VERSION: '1.22'
JOB_TRANSFER_ARTIFACT_PREFIX: build-artifacts-
CHANGELOG_ARTIFACTS: changelog
STAGED_CHANNEL_FILE_ARTIFACT_PREFIX: staged-channel-file-
BASE_BUILD_DATA: |
- config:
# Human identifier for the job.
name: Windows
runs-on: [self-hosted, windows-sign-pc]
# The value is a string representing a JSON document.
# Setting this to null causes the job to run directly in the runner machine instead of in a container.
container: |
null
# Name of the secret that contains the certificate.
certificate-secret: INSTALLER_CERT_WINDOWS_CER
# Name of the secret that contains the certificate password.
certificate-password-secret: INSTALLER_CERT_WINDOWS_PASSWORD
# File extension for the certificate.
certificate-extension: pfx
# Container for windows cert signing
certificate-container: INSTALLER_CERT_WINDOWS_CONTAINER
# Arbitrary identifier used to give the workflow artifact uploaded by each "build" matrix job a unique name.
job-transfer-artifact-suffix: Windows_64bit
# Quoting on the value is required here to allow the same comparison expression syntax to be used for this
# and the companion needs.select-targets.outputs.merge-channel-files property (output values always have string
# type).
mergeable-channel-file: 'false'
# as this runs on a self hosted runner, we need to avoid building with the default working directory path,
# otherwise paths in the build job will be too long for `light.exe`
# we use the below as a Symbolic link (just changing the wd will break the checkout action)
# this is a work around (see: https://github.com/actions/checkout/issues/197).
working-directory: 'C:\a'
artifacts:
- 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
- config:
name: Linux
runs-on: ubuntu-latest
container: |
{
\"image\": \"ghcr.io/arduino/arduino-ide/linux:main\"
}
job-transfer-artifact-suffix: Linux_64bit
mergeable-channel-file: 'false'
artifacts:
- path: '*Linux_64bit.zip'
name: Linux_X86-64_zip
- path: '*Linux_64bit.AppImage'
name: Linux_X86-64_app_image
- config:
name: macOS x86
runs-on: macos-13
container: |
null
# APPLE_SIGNING_CERTIFICATE_P12 secret was produced by following the procedure from:
# https://www.kencochrane.com/2020/08/01/build-and-sign-golang-binaries-for-macos-with-github-actions/#exporting-the-developer-certificate
certificate-secret: APPLE_SIGNING_CERTIFICATE_P12
certificate-password-secret: KEYCHAIN_PASSWORD
certificate-extension: p12
job-transfer-artifact-suffix: macOS_64bit
mergeable-channel-file: 'true'
artifacts:
- path: '*macOS_64bit.dmg'
name: macOS_X86-64_dmg
- path: '*macOS_64bit.zip'
name: macOS_X86-64_zip
- config:
name: macOS ARM
runs-on: macos-latest
container: |
null
certificate-secret: APPLE_SIGNING_CERTIFICATE_P12
certificate-password-secret: KEYCHAIN_PASSWORD
certificate-extension: p12
job-transfer-artifact-suffix: macOS_arm64
mergeable-channel-file: 'true'
artifacts:
- path: '*macOS_arm64.dmg'
name: macOS_arm64_dmg
- path: '*macOS_arm64.zip'
name: macOS_arm64_zip
PAID_RUNNER_BUILD_DATA: |
# This system was implemented to allow selective use of paid GitHub-hosted runners, due to the Apple Silicon runner
# incurring a charge at that time. Free Apple Silicon runners are now available so the configuration was moved to
# `BASE_BUILD_DATA`, but the system was left in place for future use.
jobs:
run-determination:
runs-on: ubuntu-latest
outputs:
result: ${{ steps.determination.outputs.result }}
permissions: {}
steps:
- name: Determine if the rest of the workflow should run
id: determination
run: |
RELEASE_BRANCH_REGEX="refs/heads/[0-9]+.[0-9]+.x"
# The `create` event trigger doesn't support `branches` filters, so it's necessary to use Bash instead.
if [[
"${{ github.event_name }}" != "create" ||
"${{ github.ref }}" =~ $RELEASE_BRANCH_REGEX
]]; then
# Run the other jobs.
RESULT="true"
else
# There is no need to run the other jobs.
RESULT="false"
fi
echo "result=$RESULT" >> $GITHUB_OUTPUT
build-type-determination:
needs: run-determination
if: needs.run-determination.outputs.result == 'true'
runs-on: ubuntu-latest
outputs:
is-release: ${{ steps.determination.outputs.is-release }}
is-nightly: ${{ steps.determination.outputs.is-nightly }}
channel-name: ${{ steps.determination.outputs.channel-name }}
publish-to-s3: ${{ steps.determination.outputs.publish-to-s3 }}
environment: production
permissions: {}
steps:
- name: Determine the type of build
id: determination
run: |
if [[
"${{ startsWith(github.ref, 'refs/tags/') }}" == "true"
]]; then
is_release="true"
is_nightly="false"
channel_name="stable"
elif [[
"${{ github.event_name }}" == "schedule" ||
(
"${{ github.event_name }}" == "workflow_dispatch" &&
"${{ github.ref }}" == "refs/heads/main"
)
]]; then
is_release="false"
is_nightly="true"
channel_name="nightly"
else
is_release="false"
is_nightly="false"
channel_name="nightly"
fi
echo "is-release=$is_release" >> $GITHUB_OUTPUT
echo "is-nightly=$is_nightly" >> $GITHUB_OUTPUT
echo "channel-name=$channel_name" >> $GITHUB_OUTPUT
# Only attempt upload to Amazon S3 if the credentials are available.
echo "publish-to-s3=${{ secrets.AWS_ROLE_ARN != '' }}" >> $GITHUB_OUTPUT
select-targets:
needs: build-type-determination
runs-on: ubuntu-latest
outputs:
artifact-matrix: ${{ steps.assemble.outputs.artifact-matrix }}
build-matrix: ${{ steps.assemble.outputs.build-matrix }}
merge-channel-files: ${{ steps.assemble.outputs.merge-channel-files }}
permissions: {}
steps:
- name: Assemble target data
id: assemble
run: |
# Only run the builds that incur runner charges on release or select manually triggered runs.
if [[
"${{ needs.build-type-determination.outputs.is-release }}" == "true" ||
"${{ github.event.inputs.paid-runners }}" == "true"
]]; then
build_matrix="$(
(
echo "${{ env.BASE_BUILD_DATA }}";
echo "${{ env.PAID_RUNNER_BUILD_DATA }}"
) | \
yq \
--output-format json \
'[.[].config]'
)"
artifact_matrix="$(
(
echo "${{ env.BASE_BUILD_DATA }}";
echo "${{ env.PAID_RUNNER_BUILD_DATA }}"
) | \
yq \
--output-format json \
'map(.artifacts[] + (.config | pick(["job-transfer-artifact-suffix"])))'
)"
# The build matrix produces two macOS jobs (x86 and ARM) so the "channel update info files"
# generated by each must be merged.
merge_channel_files="true"
else
build_matrix="$(
echo "${{ env.BASE_BUILD_DATA }}" | \
yq \
--output-format json \
'[.[].config]'
)"
artifact_matrix="$(
echo "${{ env.BASE_BUILD_DATA }}" | \
yq \
--output-format json \
'map(.artifacts[] + (.config | pick(["job-transfer-artifact-suffix"])))'
)"
merge_channel_files="false"
fi
# Set workflow step outputs.
# See: https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#multiline-strings
delimiter="$RANDOM"
echo "build-matrix<<$delimiter" >> $GITHUB_OUTPUT
echo "$build_matrix" >> $GITHUB_OUTPUT
echo "$delimiter" >> $GITHUB_OUTPUT
delimiter="$RANDOM"
echo "artifact-matrix<<$delimiter" >> $GITHUB_OUTPUT
echo "$artifact_matrix" >> $GITHUB_OUTPUT
echo "$delimiter" >> $GITHUB_OUTPUT
echo "merge-channel-files=$merge_channel_files" >> $GITHUB_OUTPUT
build:
name: build (${{ matrix.config.name }})
needs:
- build-type-determination
- select-targets
env:
# Location of artifacts generated by build.
BUILD_ARTIFACTS_PATH: electron-app/dist/build-artifacts
# to skip passing signing credentials to electron-builder
IS_WINDOWS_CONFIG: ${{ matrix.config.name == 'Windows' }}
INSTALLER_CERT_WINDOWS_CER: "/tmp/cert.cer"
# We are hardcoding the path for signtool because is not present on the windows PATH env var by default.
# Keep in mind that this path could change when upgrading to a new runner version
SIGNTOOL_PATH: "C:/Program Files (x86)/Windows Kits/10/bin/10.0.19041.0/x86/signtool.exe"
WIN_CERT_PASSWORD: ${{ secrets[matrix.config.certificate-password-secret] }}
WIN_CERT_CONTAINER_NAME: ${{ secrets[matrix.config.certificate-container] }}
PUPPETEER_SKIP_DOWNLOAD: true
strategy:
matrix:
config: ${{ fromJson(needs.select-targets.outputs.build-matrix) }}
runs-on: ${{ matrix.config.runs-on }}
container: ${{ fromJSON(matrix.config.container) }}
defaults:
run:
# Avoid problems caused by different default shell for container jobs (sh) vs non-container jobs (bash).
shell: bash
config:
- os: windows-2016
- os: ubuntu-latest
- os: macos-latest
# - os: rsora-rpi-arm # self-hosted armhf
runs-on: ${{ matrix.config.os }}
timeout-minutes: 90
env:
CERTIFICATE_PATH: /tmp/macos_signing_certificate.p12
steps:
- name: Symlink custom working directory
shell: cmd
if: runner.os == 'Windows' && matrix.config.working-directory
run: |
if not exist "${{ matrix.config.working-directory }}" mklink /d "${{ matrix.config.working-directory }}" "C:\actions-runner\_work\arduino-ide\arduino-ide"
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v2
- name: Install Node.js
if: runner.name != 'WINDOWS-SIGN-PC'
uses: actions/setup-node@v4
- name: Install Node.js 10.x
uses: actions/setup-node@v1
with:
node-version: ${{ env.NODE_VERSION }}
node-version: '10.x'
registry-url: 'https://registry.npmjs.org'
# Yarn is a prerequisite for the action's cache feature, so caching should be disabled when running in the
# container where Yarn is not pre-installed.
cache: ${{ fromJSON(matrix.config.container) == null && 'yarn' || null }}
- name: Install Yarn
if: runner.name != 'WINDOWS-SIGN-PC'
- name: Install Python 2.7
uses: actions/setup-python@v2
with:
python-version: '2.7'
- name: Generate signing certificate file [macOS]
if: runner.OS == 'macOS'
run: |
npm \
install \
--global \
"yarn@${{ env.YARN_VERSION }}"
- name: Install Python 3.x
if: fromJSON(matrix.config.container) == null && runner.name != 'WINDOWS-SIGN-PC'
uses: actions/setup-python@v5
with:
python-version: '3.11.x'
- name: Install Go
if: runner.name != 'WINDOWS-SIGN-PC'
uses: actions/setup-go@v5
with:
go-version: ${{ env.GO_VERSION }}
- name: Install Taskfile
if: runner.name != 'WINDOWS-SIGN-PC'
uses: arduino/setup-task@v2
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
version: 3.x
# APPLE_SIGNING_CERTIFICATE_P12 secret was produced by following the procedure from:
# https://www.kencochrane.com/2020/08/01/build-and-sign-golang-binaries-for-macos-with-github-actions/#exporting-the-developer-certificate
echo "${{ secrets.APPLE_SIGNING_CERTIFICATE_P12 }}" | base64 --decode > "${{ env.CERTIFICATE_PATH }}"
- name: Package
shell: bash
env:
PUPPETEER_SKIP_CHROMIUM_DOWNLOAD: true
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
AC_USERNAME: ${{ secrets.AC_USERNAME }}
AC_PASSWORD: ${{ secrets.AC_PASSWORD }}
AC_TEAM_ID: ${{ secrets.AC_TEAM_ID }}
IS_NIGHTLY: ${{ needs.build-type-determination.outputs.is-nightly }}
IS_RELEASE: ${{ needs.build-type-determination.outputs.is-release }}
CAN_SIGN: ${{ secrets[matrix.config.certificate-secret] != '' }}
working-directory: ${{ matrix.config.working-directory || './' }}
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
IS_NIGHTLY: ${{ github.event_name == 'schedule' }}
IS_RELEASE: ${{ startsWith(github.ref, 'refs/tags/') }}
run: |
# See: https://www.electron.build/code-signing
if [ $CAN_SIGN = false ] || [ $IS_WINDOWS_CONFIG = true ]; then
echo "Skipping the app signing: certificate not provided."
else
export CSC_LINK="${{ runner.temp }}/signing_certificate.${{ matrix.config.certificate-extension }}"
echo "${{ secrets[matrix.config.certificate-secret] }}" | base64 --decode > "$CSC_LINK"
export CSC_KEY_PASSWORD="${{ secrets[matrix.config.certificate-password-secret] }}"
export CSC_FOR_PULL_REQUEST=true
fi
npx node-gyp install
yarn install
yarn --cwd arduino-ide-extension build
yarn --cwd electron-app rebuild
yarn --cwd electron-app build
yarn --cwd electron-app package
# Both macOS jobs generate a "channel update info file" with same path and name. The second job to complete would
# overwrite the file generated by the first in the workflow artifact.
- name: Stage channel file for merge
if: >
needs.select-targets.outputs.merge-channel-files == 'true' &&
matrix.config.mergeable-channel-file == 'true'
working-directory: ${{ matrix.config.working-directory || './' }}
run: |
staged_channel_files_path="${{ runner.temp }}/staged-channel-files"
mkdir "$staged_channel_files_path"
mv \
"${{ env.BUILD_ARTIFACTS_PATH }}/${{ needs.build-type-determination.outputs.channel-name }}-mac.yml" \
"${staged_channel_files_path}/${{ needs.build-type-determination.outputs.channel-name }}-mac-${{ runner.arch }}.yml"
# Set workflow environment variable for use in other steps.
# See: https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#setting-an-environment-variable
echo "STAGED_CHANNEL_FILES_PATH=$staged_channel_files_path" >> "$GITHUB_ENV"
- name: Upload staged-for-merge channel file artifact
uses: actions/upload-artifact@v4
if: >
needs.select-targets.outputs.merge-channel-files == 'true' &&
matrix.config.mergeable-channel-file == 'true'
with:
if-no-files-found: error
name: ${{ env.STAGED_CHANNEL_FILE_ARTIFACT_PREFIX }}${{ matrix.config.job-transfer-artifact-suffix }}
path: ${{ matrix.config.working-directory && format('{0}/{1}', matrix.config.working-directory, env.STAGED_CHANNEL_FILES_PATH) || env.STAGED_CHANNEL_FILES_PATH }}
- name: Upload builds to job transfer artifact
uses: actions/upload-artifact@v4
with:
name: ${{ env.JOB_TRANSFER_ARTIFACT_PREFIX }}${{ matrix.config.job-transfer-artifact-suffix }}
path: ${{ matrix.config.working-directory && format('{0}/{1}', matrix.config.working-directory, env.BUILD_ARTIFACTS_PATH) || env.BUILD_ARTIFACTS_PATH }}
- name: Manual Clean up for self-hosted runners
if: runner.os == 'Windows' && matrix.config.working-directory
shell: cmd
run: |
rmdir /s /q "${{ matrix.config.working-directory }}\${{ env.BUILD_ARTIFACTS_PATH }}"
merge-channel-files:
needs:
- build-type-determination
- select-targets
- build
if: needs.select-targets.outputs.merge-channel-files == 'true'
runs-on: ubuntu-latest
permissions: {}
steps:
- name: Set environment variables
run: |
# See: https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#setting-an-environment-variable
echo "CHANNEL_FILES_PATH=${{ runner.temp }}/channel-files" >> "$GITHUB_ENV"
- name: Checkout
uses: actions/checkout@v4
- name: Download staged-for-merge channel file artifacts
uses: actions/download-artifact@v4
with:
merge-multiple: true
path: ${{ env.CHANNEL_FILES_PATH }}
pattern: ${{ env.STAGED_CHANNEL_FILE_ARTIFACT_PREFIX }}*
- name: Remove no longer needed artifacts
uses: geekyeggo/delete-artifact@v5
with:
name: ${{ env.STAGED_CHANNEL_FILE_ARTIFACT_PREFIX }}*
- name: Install Node.js
uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
registry-url: 'https://registry.npmjs.org'
cache: 'yarn'
- name: Install Go
uses: actions/setup-go@v5
with:
go-version: ${{ env.GO_VERSION }}
- name: Install Task
uses: arduino/setup-task@v2
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
version: 3.x
- name: Install dependencies (Linux only)
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y libx11-dev libxkbfile-dev libsecret-1-dev
- name: Install dependencies
run: yarn
- name: Merge "channel update info files"
run: |
node \
./scripts/merge-channel-files.js \
--channel "${{ needs.build-type-determination.outputs.channel-name }}" \
--input "${{ env.CHANNEL_FILES_PATH }}"
- name: Upload merged channel files job transfer artifact
uses: actions/upload-artifact@v4
with:
if-no-files-found: error
name: ${{ env.JOB_TRANSFER_ARTIFACT_PREFIX }}channel-files
path: ${{ env.CHANNEL_FILES_PATH }}
artifacts:
name: ${{ matrix.artifact.name }} artifact
needs:
- select-targets
- build
if: always() && needs.build.result != 'skipped'
runs-on: ubuntu-latest
env:
BUILD_ARTIFACTS_FOLDER: build-artifacts
strategy:
matrix:
artifact: ${{ fromJson(needs.select-targets.outputs.artifact-matrix) }}
steps:
- name: Download job transfer artifact that contains ${{ matrix.artifact.name }} tester build
uses: actions/download-artifact@v4
with:
name: ${{ env.JOB_TRANSFER_ARTIFACT_PREFIX }}${{ matrix.artifact.job-transfer-artifact-suffix }}
path: ${{ env.BUILD_ARTIFACTS_FOLDER }}
- name: Upload tester build artifact
uses: actions/upload-artifact@v4
with:
name: ${{ matrix.artifact.name }}
path: ${{ env.BUILD_ARTIFACTS_FOLDER }}/${{ matrix.artifact.path }}
changelog:
needs:
- build-type-determination
- build
runs-on: ubuntu-latest
outputs:
BODY: ${{ steps.changelog.outputs.BODY }}
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0 # To fetch all history for all branches and tags.
- name: Generate Changelog
id: changelog
env:
IS_RELEASE: ${{ needs.build-type-determination.outputs.is-release }}
run: |
export LATEST_TAG=$(git describe --abbrev=0)
export GIT_LOG=$(git log --pretty=" - %s [%h]" $LATEST_TAG..HEAD | sed 's/ *$//g')
if [ "$IS_RELEASE" = true ]; then
export BODY=$(echo -e "$GIT_LOG")
else
export LATEST_TAG_WITH_LINK=$(echo "[$LATEST_TAG](https://github.com/arduino/arduino-ide/releases/tag/$LATEST_TAG)")
if [ -z "$GIT_LOG" ]; then
export BODY="There were no changes since version $LATEST_TAG_WITH_LINK."
else
export BODY=$(echo -e "Changes since version $LATEST_TAG_WITH_LINK:\n$GIT_LOG")
# electron-builder will try to sign during the Windows job if these environment variables are defined
if [ "${{ runner.OS }}" = "macOS" ]; then
# See: https://www.electron.build/code-signing
export CSC_LINK="${{ env.CERTIFICATE_PATH }}"
export CSC_KEY_PASSWORD="${{ secrets.KEYCHAIN_PASSWORD }}"
fi
fi
echo -e "$BODY"
yarn --cwd ./electron/packager/
yarn --cwd ./electron/packager/ package
# Set workflow step output
# See: https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#multiline-strings
DELIMITER="$RANDOM"
echo "BODY<<$DELIMITER" >> $GITHUB_OUTPUT
echo "$BODY" >> $GITHUB_OUTPUT
echo "$DELIMITER" >> $GITHUB_OUTPUT
echo "$BODY" > CHANGELOG.txt
- name: Upload changelog job transfer artifact
if: needs.build-type-determination.outputs.is-nightly == 'true'
uses: actions/upload-artifact@v4
- name: Upload [GitHub Actions]
uses: actions/upload-artifact@v2
with:
name: ${{ env.JOB_TRANSFER_ARTIFACT_PREFIX }}changelog
path: CHANGELOG.txt
name: build-artifacts
path: electron/build/dist/build-artifacts/
publish:
needs:
- build-type-determination
- merge-channel-files
- changelog
if: >
always() &&
needs.build-type-determination.result == 'success' &&
(
needs.merge-channel-files.result == 'skipped' ||
needs.merge-channel-files.result == 'success'
) &&
needs.changelog.result == 'success' &&
needs.build-type-determination.outputs.publish-to-s3 == 'true' &&
needs.build-type-determination.outputs.is-nightly == 'true'
needs: build
if: github.event_name == 'schedule'
runs-on: ubuntu-latest
env:
ARTIFACTS_FOLDER: build-artifacts
environment: production
permissions:
id-token: write
contents: read
steps:
- name: Download all job transfer artifacts
uses: actions/download-artifact@v4
- name: Download [GitHub Actions]
uses: actions/download-artifact@v2
with:
merge-multiple: true
path: ${{ env.ARTIFACTS_FOLDER }}
pattern: ${{ env.JOB_TRANSFER_ARTIFACT_PREFIX }}*
- name: Configure AWS Credentials for Nightly [S3]
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ secrets.AWS_ROLE_ARN }}
aws-region: us-east-1
name: build-artifacts
path: build-artifacts
- name: Publish Nightly [S3]
run: |
aws s3 sync ${{ env.ARTIFACTS_FOLDER }} s3://${{ secrets.DOWNLOADS_BUCKET }}/arduino-ide/nightly
uses: kittaakos/upload-s3-action@v0.0.1
with:
aws_key_id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws_secret_access_key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws_bucket: ${{ secrets.DOWNLOADS_BUCKET }}
source_dir: build-artifacts/
destination_dir: arduino-pro-ide/nightly/
release:
needs:
- build-type-determination
- merge-channel-files
- changelog
if: >
always() &&
needs.build-type-determination.result == 'success' &&
(
needs.merge-channel-files.result == 'skipped' ||
needs.merge-channel-files.result == 'success'
) &&
needs.changelog.result == 'success' &&
needs.build-type-determination.outputs.is-release == 'true'
needs: build
if: startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
env:
ARTIFACTS_FOLDER: build-artifacts
environment: production
permissions:
id-token: write
contents: write
steps:
- name: Download all job transfer artifacts
uses: actions/download-artifact@v4
- name: Download [GitHub Actions]
uses: actions/download-artifact@v2
with:
merge-multiple: true
path: ${{ env.ARTIFACTS_FOLDER }}
pattern: ${{ env.JOB_TRANSFER_ARTIFACT_PREFIX }}*
name: build-artifacts
path: build-artifacts
- name: Get Tag
id: tag_name
run: |
echo "TAG_NAME=${GITHUB_REF#refs/tags/}" >> $GITHUB_OUTPUT
- name: Create Release [GitHub]
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: ${{ github.ref }}
release_name: ${{ github.ref }}
- name: Publish Release [GitHub]
uses: svenstaro/upload-release-action@2.9.0
uses: svenstaro/upload-release-action@v1-release
with:
repo_token: ${{ secrets.GITHUB_TOKEN }}
release_name: ${{ steps.tag_name.outputs.TAG_NAME }}
file: ${{ env.ARTIFACTS_FOLDER }}/*
file: build-artifacts/*
tag: ${{ github.ref }}
file_glob: true
body: ${{ needs.changelog.outputs.BODY }}
- name: Configure AWS Credentials for Release [S3]
if: needs.build-type-determination.outputs.publish-to-s3 == 'true'
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ secrets.AWS_ROLE_ARN }}
aws-region: us-east-1
- name: Publish Release [S3]
if: needs.build-type-determination.outputs.publish-to-s3 == 'true'
run: |
aws s3 sync ${{ env.ARTIFACTS_FOLDER }} s3://${{ secrets.DOWNLOADS_BUCKET }}/arduino-ide
clean:
# This job must run after all jobs that use the transfer artifact.
needs:
- build
- merge-channel-files
- publish
- release
- artifacts
if: always() && needs.build.result != 'skipped'
runs-on: ubuntu-latest
steps:
- name: Remove unneeded job transfer artifacts
uses: geekyeggo/delete-artifact@v5
uses: kittaakos/upload-s3-action@v0.0.1
with:
name: ${{ env.JOB_TRANSFER_ARTIFACT_PREFIX }}*
aws_key_id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws_secret_access_key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws_bucket: ${{ secrets.DOWNLOADS_BUCKET }}
source_dir: build-artifacts/
destination_dir: arduino-pro-ide/

View File

@ -1,192 +0,0 @@
# Source: https://github.com/arduino/tooling-project-assets/blob/main/workflow-templates/check-certificates.md
name: Check Certificates
# See: https://docs.github.com/en/actions/reference/events-that-trigger-workflows
on:
create:
push:
paths:
- '.github/workflows/check-certificates.ya?ml'
pull_request:
paths:
- '.github/workflows/check-certificates.ya?ml'
schedule:
# Run every 10 hours.
- cron: '0 */10 * * *'
workflow_dispatch:
repository_dispatch:
env:
# Begin notifications when there are less than this many days remaining before expiration.
EXPIRATION_WARNING_PERIOD: 30
jobs:
run-determination:
runs-on: ubuntu-latest
outputs:
result: ${{ steps.determination.outputs.result }}
steps:
- name: Determine if the rest of the workflow should run
id: determination
run: |
RELEASE_BRANCH_REGEX="refs/heads/[0-9]+.[0-9]+.x"
REPO_SLUG="arduino/arduino-ide"
if [[
(
# Only run on branch creation when it is a release branch.
# The `create` event trigger doesn't support `branches` filters, so it's necessary to use Bash instead.
"${{ github.event_name }}" != "create" ||
"${{ github.ref }}" =~ $RELEASE_BRANCH_REGEX
) &&
(
# Only run when the workflow will have access to the certificate secrets.
# This could be done via a GitHub Actions workflow conditional, but makes more sense to do it here as well.
(
"${{ github.event_name }}" != "pull_request" &&
"${{ github.repository }}" == "$REPO_SLUG"
) ||
(
"${{ github.event_name }}" == "pull_request" &&
"${{ github.event.pull_request.head.repo.full_name }}" == "$REPO_SLUG"
)
)
]]; then
# Run the other jobs.
RESULT="true"
else
# There is no need to run the other jobs.
RESULT="false"
fi
echo "result=$RESULT" >> $GITHUB_OUTPUT
check-certificates:
name: ${{ matrix.certificate.identifier }}
needs: run-determination
if: needs.run-determination.outputs.result == 'true'
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
certificate:
# Additional certificate definitions can be added to this list.
- identifier: macOS signing certificate # Text used to identify certificate in notifications.
certificate-secret: APPLE_SIGNING_CERTIFICATE_P12 # Name of the secret that contains the certificate.
password-secret: KEYCHAIN_PASSWORD # Name of the secret that contains the certificate password.
type: pkcs12
- identifier: Windows signing certificate
certificate-secret: INSTALLER_CERT_WINDOWS_CER
# The password for the Windows certificate is not needed, because its not a container, but a single certificate.
type: x509
steps:
- name: Set certificate path environment variable
run: |
# See: https://docs.github.com/en/actions/reference/workflow-commands-for-github-actions#setting-an-environment-variable
echo "CERTIFICATE_PATH=${{ runner.temp }}/certificate.p12" >> "$GITHUB_ENV"
- name: Decode certificate
env:
CERTIFICATE: ${{ secrets[matrix.certificate.certificate-secret] }}
run: |
echo "${{ env.CERTIFICATE }}" | base64 --decode > "${{ env.CERTIFICATE_PATH }}"
- name: Verify certificate
env:
CERTIFICATE_PASSWORD: ${{ secrets[matrix.certificate.password-secret] }}
run: |
(
openssl ${{ matrix.certificate.type }} \
-in "${{ env.CERTIFICATE_PATH }}" \
-legacy \
-noout \
-passin env:CERTIFICATE_PASSWORD
) || (
echo "::error::Verification of ${{ matrix.certificate.identifier }} failed!!!"
exit 1
)
- name: Slack notification of certificate verification failure
if: failure()
env:
SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK }}
SLACK_MESSAGE: |
:warning::warning::warning::warning:
WARNING: ${{ github.repository }} ${{ matrix.certificate.identifier }} verification failed!!!
:warning::warning::warning::warning:
SLACK_COLOR: danger
MSG_MINIMAL: true
uses: rtCamp/action-slack-notify@v2
- name: Get days remaining before certificate expiration date
env:
CERTIFICATE_PASSWORD: ${{ secrets[matrix.certificate.password-secret] }}
id: get-days-before-expiration
run: |
if [[ ${{ matrix.certificate.type }} == "pkcs12" ]]; then
EXPIRATION_DATE="$(
(
openssl pkcs12 \
-in "${{ env.CERTIFICATE_PATH }}" \
-clcerts \
-legacy \
-nodes \
-passin env:CERTIFICATE_PASSWORD
) | (
openssl x509 \
-noout \
-enddate
) | (
grep \
--max-count=1 \
--only-matching \
--perl-regexp \
'notAfter=(\K.*)'
)
)"
elif [[ ${{ matrix.certificate.type }} == "x509" ]]; then
EXPIRATION_DATE="$(
(
openssl x509 \
-in ${{ env.CERTIFICATE_PATH }} \
-noout \
-enddate
) | (
grep \
--max-count=1 \
--only-matching \
--perl-regexp \
'notAfter=(\K.*)'
)
)"
fi
DAYS_BEFORE_EXPIRATION="$((($(date --utc --date="$EXPIRATION_DATE" +%s) - $(date --utc +%s)) / 60 / 60 / 24))"
# Display the expiration information in the log.
echo "Certificate expiration date: $EXPIRATION_DATE"
echo "Days remaining before expiration: $DAYS_BEFORE_EXPIRATION"
echo "days=$DAYS_BEFORE_EXPIRATION" >> $GITHUB_OUTPUT
- name: Check if expiration notification period has been reached
id: check-expiration
run: |
if [[ ${{ steps.get-days-before-expiration.outputs.days }} -lt ${{ env.EXPIRATION_WARNING_PERIOD }} ]]; then
echo "::error::${{ matrix.certificate.identifier }} will expire in ${{ steps.get-days-before-expiration.outputs.days }} days!!!"
exit 1
fi
- name: Slack notification of pending certificate expiration
# Don't send spurious expiration notification if verification fails.
if: failure() && steps.check-expiration.outcome == 'failure'
env:
SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK }}
SLACK_MESSAGE: |
:warning::warning::warning::warning:
WARNING: ${{ github.repository }} ${{ matrix.certificate.identifier }} will expire in ${{ steps.get-days-before-expiration.outputs.days }} days!!!
:warning::warning::warning::warning:
SLACK_COLOR: danger
MSG_MINIMAL: true
uses: rtCamp/action-slack-notify@v2

View File

@ -1,58 +0,0 @@
name: Check Containers
on:
pull_request:
paths:
- ".github/workflows/check-containers.ya?ml"
- "**.Dockerfile"
- "**/Dockerfile"
push:
paths:
- ".github/workflows/check-containers.ya?ml"
- "**.Dockerfile"
- "**/Dockerfile"
repository_dispatch:
schedule:
# Run periodically to catch breakage caused by external changes.
- cron: "0 7 * * MON"
workflow_dispatch:
jobs:
run:
name: Run (${{ matrix.image.path }})
runs-on: ubuntu-latest
permissions: {}
services:
registry:
image: registry:2
ports:
- 5000:5000
env:
IMAGE_NAME: name/app:latest
REGISTRY: localhost:5000
strategy:
fail-fast: false
matrix:
image:
- path: .github/workflows/assets/linux.Dockerfile
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Build and push to local registry
uses: docker/build-push-action@v6
with:
context: .
file: ${{ matrix.image.path }}
push: true
tags: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
- name: Run container
run: |
docker \
run \
--rm \
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}

View File

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

View File

@ -1,94 +0,0 @@
# Source: https://github.com/arduino/tooling-project-assets/blob/main/workflow-templates/check-javascript-task.md
name: Check JavaScript
env:
# See: https://github.com/actions/setup-node/#readme
NODE_VERSION: 18.17
# See: https://docs.github.com/actions/writing-workflows/choosing-when-your-workflow-runs/events-that-trigger-workflows
on:
create:
push:
paths:
- '.github/workflows/check-javascript.ya?ml'
- '**/.eslintignore'
- '**/.eslintrc*'
- '**/.npmrc'
- '**/package.json'
- '**/package-lock.json'
- '**/yarn.lock'
- '**.jsx?'
pull_request:
paths:
- '.github/workflows/check-javascript.ya?ml'
- '**/.eslintignore'
- '**/.eslintrc*'
- '**/.npmrc'
- '**/package.json'
- '**/package-lock.json'
- '**/yarn.lock'
- '**.jsx?'
workflow_dispatch:
repository_dispatch:
jobs:
run-determination:
runs-on: ubuntu-latest
permissions: {}
outputs:
result: ${{ steps.determination.outputs.result }}
steps:
- name: Determine if the rest of the workflow should run
id: determination
run: |
RELEASE_BRANCH_REGEX="refs/heads/[0-9]+.[0-9]+.x"
# The `create` event trigger doesn't support `branches` filters, so it's necessary to use Bash instead.
if [[
"${{ github.event_name }}" != "create" ||
"${{ github.ref }}" =~ $RELEASE_BRANCH_REGEX
]]; then
# Run the other jobs.
RESULT="true"
else
# There is no need to run the other jobs.
RESULT="false"
fi
echo "result=$RESULT" >> $GITHUB_OUTPUT
check:
needs: run-determination
if: needs.run-determination.outputs.result == 'true'
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
cache: yarn
node-version: ${{ env.NODE_VERSION }}
- name: Install Dependencies (Linux only)
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y libx11-dev libxkbfile-dev libsecret-1-dev
- name: Install npm package dependencies
env:
# Avoid failure of @vscode/ripgrep installation due to GitHub API rate limiting:
# https://github.com/microsoft/vscode-ripgrep#github-api-limit-note
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
yarn install
- name: Lint
run: |
yarn \
--cwd arduino-ide-extension \
lint

View File

@ -1,97 +0,0 @@
name: Check Yarn
# See: https://docs.github.com/en/actions/reference/events-that-trigger-workflows
on:
create:
push:
paths:
- ".github/workflows/check-yarn.ya?ml"
- "**/.yarnrc"
- "**/package.json"
- "**/package-lock.json"
- "**/yarn.lock"
pull_request:
paths:
- ".github/workflows/check-yarn.ya?ml"
- "**/.yarnrc"
- "**/package.json"
- "**/package-lock.json"
- "**/yarn.lock"
schedule:
# Run every Tuesday at 8 AM UTC to catch breakage resulting from changes to the JSON schema.
- cron: "0 8 * * TUE"
workflow_dispatch:
repository_dispatch:
jobs:
run-determination:
runs-on: ubuntu-latest
permissions: {}
outputs:
result: ${{ steps.determination.outputs.result }}
steps:
- name: Determine if the rest of the workflow should run
id: determination
run: |
RELEASE_BRANCH_REGEX="refs/heads/[0-9]+.[0-9]+.x"
# The `create` event trigger doesn't support `branches` filters, so it's necessary to use Bash instead.
if [[
"${{ github.event_name }}" != "create" ||
"${{ github.ref }}" =~ $RELEASE_BRANCH_REGEX
]]; then
# Run the other jobs.
RESULT="true"
else
# There is no need to run the other jobs.
RESULT="false"
fi
echo "result=$RESULT" >> $GITHUB_OUTPUT
check-sync:
name: check-sync (${{ matrix.project.path }})
needs: run-determination
if: needs.run-determination.outputs.result == 'true'
runs-on: ubuntu-latest
permissions:
contents: read
strategy:
fail-fast: false
matrix:
project:
- path: .
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
cache: yarn
node-version: ${{ env.NODE_VERSION }}
- name: Install Dependencies (Linux only)
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y libx11-dev libxkbfile-dev libsecret-1-dev
- name: Install npm package dependencies
env:
# Avoid failure of @vscode/ripgrep installation due to GitHub API rate limiting:
# https://github.com/microsoft/vscode-ripgrep#github-api-limit-note
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
yarn \
install \
--ignore-scripts
- name: Check yarn.lock
run: |
git \
diff \
--color \
--exit-code \
"${{ matrix.project.path }}/yarn.lock"

View File

@ -1,66 +0,0 @@
name: Compose full changelog
on:
release:
types:
- edited
env:
CHANGELOG_ARTIFACTS: changelog
# See: https://github.com/actions/setup-node/#readme
NODE_VERSION: '18.17'
jobs:
create-changelog:
if: github.repository == 'arduino/arduino-ide'
runs-on: ubuntu-latest
permissions:
id-token: write
contents: read
environment: production
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install Node.js
uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
registry-url: 'https://registry.npmjs.org'
- name: Install Dependencies (Linux only)
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y libx11-dev libxkbfile-dev libsecret-1-dev
- name: Get Tag
id: tag_name
run: |
echo "TAG_NAME=${GITHUB_REF#refs/tags/}" >> $GITHUB_OUTPUT
- name: Create full changelog
id: full-changelog
run: |
yarn add @octokit/rest@19.0.13 --ignore-workspace-root-check
mkdir "${{ github.workspace }}/${{ env.CHANGELOG_ARTIFACTS }}"
# Get the changelog file name to build
CHANGELOG_FILE_NAME="${{ steps.tag_name.outputs.TAG_NAME }}-$(date +%s).md"
# Create manifest file pointing to latest changelog file name
echo "$CHANGELOG_FILE_NAME" >> "${{ github.workspace }}/${{ env.CHANGELOG_ARTIFACTS }}/latest.txt"
# Compose changelog
yarn run compose-changelog "${{ github.workspace }}/${{ env.CHANGELOG_ARTIFACTS }}/$CHANGELOG_FILE_NAME"
- name: Configure AWS Credentials for Changelog [S3]
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ secrets.AWS_ROLE_ARN }}
aws-region: us-east-1
- name: Publish Changelog [S3]
run: |
aws s3 sync ${{ env.CHANGELOG_ARTIFACTS }} s3://${{ secrets.DOWNLOADS_BUCKET }}/arduino-ide/changelog

View File

@ -1,52 +0,0 @@
name: i18n-nightly-push
env:
# See vars.GO_VERSION field of https://github.com/arduino/arduino-cli/blob/master/DistTasks.yml
GO_VERSION: '1.21'
on:
schedule:
# run every day at 1AM
- cron: '0 1 * * *'
jobs:
push-to-transifex:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install Node.js 18.17
uses: actions/setup-node@v4
with:
node-version: '18.17'
registry-url: 'https://registry.npmjs.org'
cache: 'yarn'
- name: Install Go
uses: actions/setup-go@v5
with:
go-version: ${{ env.GO_VERSION }}
- name: Install Task
uses: arduino/setup-task@v2
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
version: 3.x
- name: Install dependencies (Linux only)
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y libx11-dev libxkbfile-dev libsecret-1-dev
- name: Install dependencies
run: yarn install --immutable
- name: Run i18n:push script
run: yarn run i18n:push
env:
TRANSIFEX_ORGANIZATION: ${{ secrets.TRANSIFEX_ORGANIZATION }}
TRANSIFEX_PROJECT: ${{ secrets.TRANSIFEX_PROJECT }}
TRANSIFEX_RESOURCE: ${{ secrets.TRANSIFEX_RESOURCE }}
TRANSIFEX_API_KEY: ${{ secrets.TRANSIFEX_API_KEY }}

View File

@ -1,60 +0,0 @@
name: i18n-weekly-pull
env:
# See vars.GO_VERSION field of https://github.com/arduino/arduino-cli/blob/master/DistTasks.yml
GO_VERSION: '1.21'
on:
schedule:
# run every monday at 2AM
- cron: '0 2 * * 1'
jobs:
pull-from-transifex:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install Node.js 18.17
uses: actions/setup-node@v4
with:
node-version: '18.17'
registry-url: 'https://registry.npmjs.org'
cache: 'yarn'
- name: Install Go
uses: actions/setup-go@v5
with:
go-version: ${{ env.GO_VERSION }}
- name: Install Task
uses: arduino/setup-task@v2
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
version: 3.x
- name: Install dependencies (Linux only)
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y libx11-dev libxkbfile-dev libsecret-1-dev
- name: Install dependencies
run: yarn install --immutable
- name: Run i18n:pull script
run: yarn run i18n:pull
env:
TRANSIFEX_ORGANIZATION: ${{ secrets.TRANSIFEX_ORGANIZATION }}
TRANSIFEX_PROJECT: ${{ secrets.TRANSIFEX_PROJECT }}
TRANSIFEX_RESOURCE: ${{ secrets.TRANSIFEX_RESOURCE }}
TRANSIFEX_API_KEY: ${{ secrets.TRANSIFEX_API_KEY }}
- name: Create Pull Request
uses: peter-evans/create-pull-request@v7
with:
commit-message: Updated translation files
title: Update translation files
branch: i18n/translations-update
author: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

View File

@ -1,70 +0,0 @@
name: Push Container Images
on:
pull_request:
paths:
- ".github/workflows/push-container-images.ya?ml"
push:
paths:
- ".github/workflows/push-container-images.ya?ml"
- "**.Dockerfile"
- "**/Dockerfile"
repository_dispatch:
schedule:
# Run periodically to catch breakage caused by external changes.
- cron: "0 8 * * MON"
workflow_dispatch:
jobs:
push:
name: Push (${{ matrix.image.name }})
# Only run the job when GITHUB_TOKEN has the privileges required for Container registry login.
if: >
(
github.event_name != 'pull_request' &&
github.repository == 'arduino/arduino-ide'
) ||
(
github.event_name == 'pull_request' &&
github.event.pull_request.head.repo.full_name == 'arduino/arduino-ide'
)
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
strategy:
fail-fast: false
matrix:
image:
- path: .github/workflows/assets/linux.Dockerfile
name: ${{ github.repository }}/linux
registry: ghcr.io
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Log in to the Container registry
uses: docker/login-action@v3
with:
password: ${{ secrets.GITHUB_TOKEN }}
registry: ${{ matrix.image.registry }}
username: ${{ github.repository_owner }}
- name: Extract metadata for image
id: metadata
uses: docker/metadata-action@v5
with:
images: ${{ matrix.image.registry }}/${{ matrix.image.name }}
- name: Build and push image
uses: docker/build-push-action@v6
with:
context: .
file: ${{ matrix.image.path }}
labels: ${{ steps.metadata.outputs.labels }}
# Workflow is triggered on relevant events for the sake of a "dry run" validation but image is only pushed to
# registry on commit to the main branch.
push: ${{ github.ref == 'refs/heads/main' }}
tags: ${{ steps.metadata.outputs.tags }}

View File

@ -1,140 +0,0 @@
# Source: https://github.com/arduino/tooling-project-assets/blob/main/workflow-templates/sync-labels.md
name: Sync Labels
# See: https://docs.github.com/en/actions/reference/events-that-trigger-workflows
on:
push:
paths:
- '.github/workflows/sync-labels.ya?ml'
- '.github/label-configuration-files/*.ya?ml'
pull_request:
paths:
- '.github/workflows/sync-labels.ya?ml'
- '.github/label-configuration-files/*.ya?ml'
schedule:
# Run daily at 8 AM UTC to sync with changes to shared label configurations.
- cron: '0 8 * * *'
workflow_dispatch:
repository_dispatch:
env:
CONFIGURATIONS_FOLDER: .github/label-configuration-files
CONFIGURATIONS_ARTIFACT_PREFIX: label-configuration-file-
jobs:
check:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Download JSON schema for labels configuration file
id: download-schema
uses: carlosperate/download-file-action@v2
with:
file-url: https://raw.githubusercontent.com/arduino/tooling-project-assets/main/workflow-templates/assets/sync-labels/arduino-tooling-gh-label-configuration-schema.json
location: ${{ runner.temp }}/label-configuration-schema
- name: Install JSON schema validator
run: |
sudo npm install \
--global \
ajv-cli \
ajv-formats
- name: Validate local labels configuration
run: |
# See: https://github.com/ajv-validator/ajv-cli#readme
ajv validate \
--all-errors \
-c ajv-formats \
-s "${{ steps.download-schema.outputs.file-path }}" \
-d "${{ env.CONFIGURATIONS_FOLDER }}/*.{yml,yaml}"
download:
needs: check
runs-on: ubuntu-latest
strategy:
matrix:
filename:
# Filenames of the shared configurations to apply to the repository in addition to the local configuration.
# https://github.com/arduino/tooling-project-assets/blob/main/workflow-templates/assets/sync-labels
- universal.yml
- tooling.yml
steps:
- name: Download
uses: carlosperate/download-file-action@v2
with:
file-url: https://raw.githubusercontent.com/arduino/tooling-project-assets/main/workflow-templates/assets/sync-labels/${{ matrix.filename }}
- name: Pass configuration files to next job via workflow artifact
uses: actions/upload-artifact@v4
with:
path: |
*.yaml
*.yml
if-no-files-found: error
name: ${{ env.CONFIGURATIONS_ARTIFACT_PREFIX }}${{ matrix.filename }}
sync:
needs: download
runs-on: ubuntu-latest
steps:
- name: Set environment variables
run: |
# See: https://docs.github.com/en/actions/reference/workflow-commands-for-github-actions#setting-an-environment-variable
echo "MERGED_CONFIGURATION_PATH=${{ runner.temp }}/labels.yml" >> "$GITHUB_ENV"
- name: Determine whether to dry run
id: dry-run
if: >
github.event_name == 'pull_request' ||
(
(
github.event_name == 'push' ||
github.event_name == 'workflow_dispatch'
) &&
github.ref != format('refs/heads/{0}', github.event.repository.default_branch)
)
run: |
# Use of this flag in the github-label-sync command will cause it to only check the validity of the
# configuration.
echo "flag=--dry-run" >> $GITHUB_OUTPUT
- name: Checkout repository
uses: actions/checkout@v4
- name: Download configuration file artifacts
uses: actions/download-artifact@v4
with:
merge-multiple: true
pattern: ${{ env.CONFIGURATIONS_ARTIFACT_PREFIX }}*
path: ${{ env.CONFIGURATIONS_FOLDER }}
- name: Remove unneeded artifacts
uses: geekyeggo/delete-artifact@v5
with:
name: ${{ env.CONFIGURATIONS_ARTIFACT_PREFIX }}*
- name: Merge label configuration files
run: |
# Merge all configuration files
shopt -s extglob
cat "${{ env.CONFIGURATIONS_FOLDER }}"/*.@(yml|yaml) > "${{ env.MERGED_CONFIGURATION_PATH }}"
- name: Install github-label-sync
run: sudo npm install --global github-label-sync
- name: Sync labels
env:
GITHUB_ACCESS_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
# See: https://github.com/Financial-Times/github-label-sync
github-label-sync \
--labels "${{ env.MERGED_CONFIGURATION_PATH }}" \
${{ steps.dry-run.outputs.flag }} \
${{ github.repository }}

View File

@ -1,140 +0,0 @@
name: Test JavaScript
env:
# See vars.GO_VERSION field of https://github.com/arduino/arduino-cli/blob/master/DistTasks.yml
GO_VERSION: '1.21'
# See: https://github.com/actions/setup-node/#readme
NODE_VERSION: 18.17
on:
push:
paths:
- ".github/workflows/test-javascript.ya?ml"
- "**/.mocharc.js"
- "**/.mocharc.jsonc?"
- "**/.mocharc.ya?ml"
- "**/package.json"
- "**/package-lock.json"
- "**/yarn.lock"
- "tests/testdata/**"
- "**/tsconfig.json"
- "**.[jt]sx?"
pull_request:
paths:
- ".github/workflows/test-javascript.ya?ml"
- "**/.mocharc.js"
- "**/.mocharc.jsonc?"
- "**/.mocharc.ya?ml"
- "**/package.json"
- "**/package-lock.json"
- "**/yarn.lock"
- "tests/testdata/**"
- "**/tsconfig.json"
- "**.[jt]sx?"
workflow_dispatch:
repository_dispatch:
jobs:
run-determination:
runs-on: ubuntu-latest
permissions: {}
outputs:
result: ${{ steps.determination.outputs.result }}
steps:
- name: Determine if the rest of the workflow should run
id: determination
run: |
RELEASE_BRANCH_REGEX="refs/heads/[0-9]+.[0-9]+.x"
# The `create` event trigger doesn't support `branches` filters, so it's necessary to use Bash instead.
if [[
"${{ github.event_name }}" != "create" ||
"${{ github.ref }}" =~ $RELEASE_BRANCH_REGEX
]]; then
# Run the other jobs.
RESULT="true"
else
# There is no need to run the other jobs.
RESULT="false"
fi
echo "result=$RESULT" >> $GITHUB_OUTPUT
test:
name: test (${{ matrix.project.path }}, ${{ matrix.operating-system }})
needs: run-determination
if: needs.run-determination.outputs.result == 'true'
runs-on: ${{ matrix.operating-system }}
defaults:
run:
shell: bash
permissions:
contents: read
strategy:
fail-fast: false
matrix:
project:
- path: .
operating-system:
- macos-latest
- ubuntu-latest
- windows-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
cache: yarn
node-version: ${{ env.NODE_VERSION }}
# See: https://github.com/eclipse-theia/theia/blob/master/doc/Developing.md#prerequisites
- name: Install Python
uses: actions/setup-python@v5
with:
python-version: '3.11.x'
- name: Install Go
uses: actions/setup-go@v5
with:
go-version: ${{ env.GO_VERSION }}
- name: Install Taskfile
uses: arduino/setup-task@v2
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
version: 3.x
- name: Install Dependencies (Linux only)
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y libx11-dev libxkbfile-dev libsecret-1-dev
- name: Install npm package dependencies
env:
# Avoid failure of @vscode/ripgrep installation due to GitHub API rate limiting:
# https://github.com/microsoft/vscode-ripgrep#github-api-limit-note
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
yarn install
- name: Compile TypeScript
run: |
yarn \
--cwd arduino-ide-extension \
build
- name: Run tests
env:
# These secrets are optional. Dependent tests will be skipped if not available.
CREATE_USERNAME: ${{ secrets.CREATE_USERNAME }}
CREATE_PASSWORD: ${{ secrets.CREATE_PASSWORD }}
CREATE_CLIENT_SECRET: ${{ secrets.CREATE_CLIENT_SECRET }}
run: |
yarn test
yarn \
--cwd arduino-ide-extension \
test:slow

View File

@ -1,69 +0,0 @@
name: themes-weekly-pull
on:
schedule:
# run every friday at 5AM
- cron: '0 5 * * 5'
workflow_dispatch:
env:
# See vars.GO_VERSION field of https://github.com/arduino/arduino-cli/blob/master/DistTasks.yml
GO_VERSION: '1.21'
NODE_VERSION: '18.17'
jobs:
pull-from-jsonbin:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install Node.js
uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
registry-url: 'https://registry.npmjs.org'
cache: 'yarn'
- name: Install Go
uses: actions/setup-go@v5
with:
go-version: ${{ env.GO_VERSION }}
- name: Install Task
uses: arduino/setup-task@v2
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
version: 3.x
- name: Install dependencies (Linux only)
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y libx11-dev libxkbfile-dev libsecret-1-dev
- name: Install dependencies
run: yarn install --immutable
- name: Run themes:pull script
run: yarn run themes:pull
env:
JSONBIN_MASTER_KEY: ${{ secrets.JSONBIN_MASTER_KEY }}
JSONBIN_ID: ${{ secrets.JSONBIN_ID }}
- name: Generate dark tokens
run: npx token-transformer scripts/themes/tokens/arduino-tokens.json scripts/themes/tokens/dark.json core,ide-default,ide-dark,theia core,ide-default,ide-dark
- name: Generate default tokens
run: npx token-transformer scripts/themes/tokens/arduino-tokens.json scripts/themes/tokens/default.json core,ide-default,theia core,ide-default
- name: Run themes:generate script
run: yarn run themes:generate
- name: Create Pull Request
uses: peter-evans/create-pull-request@v7
with:
commit-message: Updated themes
title: Update themes
branch: themes/themes-update
author: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

21
.gitignore vendored
View File

@ -1,22 +1,17 @@
node_modules/
# .node_modules is a hack for the electron builder.
.node_modules/
lib/
downloads/
arduino-ide-extension/src/node/resources
arduino-ide-extension/Examples/
build/
!electron/build/
src-gen/
gen-webpack.config.js
gen-webpack.node.config.js
*webpack.config.js
.DS_Store
# switching from `electron` to `browser` in dev mode.
.browser_modules
yarn*.log
# For the VS Code extensions used by Theia.
electron-app/plugins
# the tokens folder for the themes
scripts/themes/tokens
# content trace files for electron
electron-app/traces
# any Arduino LS generated log files
inols*.log
# The electron-builder output.
electron-app/dist
plugins
# the config files for the CLI
arduino-ide-extension/data/cli/config

24
.gitpod.yml Normal file
View File

@ -0,0 +1,24 @@
image:
file: Dockerfile
ports:
- port: 3000
onOpen: open-preview
- port: 5900
onOpen: ignore
- port: 6080
onOpen: ignore
tasks:
- init: >
yarn &&
yarn --cwd ./browser-app start
github:
prebuilds:
master: true
branches: true
pullRequests: true
pullRequestsFromForks: true
addComment: false
addBadge: false

View File

@ -1,11 +0,0 @@
lib
dist
plugins
src-gen
i18n
gen-webpack*
.browser_modules
arduino-ide-extension/src/node/resources
cli-protocol
*color-theme.json
arduino-icons.json

View File

@ -1,28 +0,0 @@
{
"singleQuote": true,
"tabWidth": 2,
"useTabs": false,
"printWidth": 80,
"endOfLine": "auto",
"overrides": [
{
"files": "*.json",
"options": {
"tabWidth": 2
}
},
{
"files": "*.css",
"options": {
"tabWidth": 4,
"singleQuote": false
}
},
{
"files": "*.html",
"options": {
"tabWidth": 4
}
}
]
}

211
.vscode/launch.json vendored
View File

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

21
.vscode/settings.json vendored
View File

@ -1,12 +1,21 @@
{
"tslint.enable": true,
"tslint.configFile": "./tslint.json",
"editor.formatOnSave": true,
"files.exclude": {
"**/lib": false
},
"search.exclude": {
"arduino-ide-extension/src/test/node/__test_sketchbook__": true
"editor.insertSpaces": true,
"editor.detectIndentation": false,
"[typescript]": {
"editor.tabSize": 4
},
"typescript.tsdk": "node_modules/typescript/lib",
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
}
"[json]": {
"editor.tabSize": 2
},
"[jsonc]": {
"editor.tabSize": 2
},
"files.insertFinalNewline": true,
"typescript.tsdk": "node_modules/typescript/lib"
}

54
.vscode/tasks.json vendored
View File

@ -1,22 +1,21 @@
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "Rebuild App",
"label": "Arduino Pro IDE - Start Browser App",
"type": "shell",
"command": "yarn rebuild",
"command": "yarn --cwd ./browser-app start",
"group": "build",
"options": {
"cwd": "${workspaceFolder}/electron-app"
},
"presentation": {
"reveal": "always",
"panel": "new",
"clear": false
"clear": true
}
},
{
"label": "Watch Extension",
"label": "Arduino Pro IDE - Watch IDE Extension",
"type": "shell",
"command": "yarn --cwd ./arduino-ide-extension watch",
"group": "build",
@ -27,7 +26,29 @@
}
},
{
"label": "Watch App",
"label": "Arduino Pro IDE - Watch Debugger Extension",
"type": "shell",
"command": "yarn --cwd ./arduino-debugger-extension watch",
"group": "build",
"presentation": {
"reveal": "always",
"panel": "new",
"clear": false
}
},
{
"label": "Arduino Pro IDE - Watch Browser App",
"type": "shell",
"command": "yarn --cwd ./browser-app watch",
"group": "build",
"presentation": {
"reveal": "always",
"panel": "new",
"clear": false
}
},
{
"label": "Arduino Pro IDE - Watch Electron App",
"type": "shell",
"command": "yarn --cwd ./electron-app watch",
"group": "build",
@ -38,9 +59,22 @@
}
},
{
"label": "Watch All",
"label": "Arduino Pro IDE - Watch All [Browser]",
"type": "shell",
"dependsOn": ["Watch Extension", "Watch App"]
"dependsOn": [
"Arduino Pro IDE - Watch IDE Extension",
"Arduino Pro IDE - Watch Debugger Extension",
"Arduino Pro IDE - Watch Browser App"
]
},
{
"label": "Arduino Pro IDE - Watch All [Electron]",
"type": "shell",
"dependsOn": [
"Arduino Pro IDE - Watch IDE Extension",
"Arduino Pro IDE - Watch Debugger Extension",
"Arduino Pro IDE - Watch Electron App"
]
}
]
}

View File

@ -1,3 +0,0 @@
# Development Guide
This documentation has been moved [**here**](docs/development.md#development-guide).

19
Dockerfile Normal file
View File

@ -0,0 +1,19 @@
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

@ -1,661 +0,0 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

136
README.md
View File

@ -1,55 +1,129 @@
<img src="https://content.arduino.cc/website/Arduino_logo_teal.svg" height="100" align="right" />
# Arduino Pro IDE
# Arduino IDE 2.x
[![Arduino Pro IDE](https://github.com/bcmi-labs/arduino-editor/workflows/Arduino%20Pro%20IDE/badge.svg)](https://github.com/bcmi-labs/arduino-editor/actions?query=workflow%3A%22Arduino+Pro+IDE%22)
[![Build status](https://github.com/arduino/arduino-ide/actions/workflows/build.yml/badge.svg)](https://github.com/arduino/arduino-ide/actions/workflows/build.yml)
[![Check JavaScript status](https://github.com/arduino/arduino-ide/actions/workflows/check-javascript.yml/badge.svg)](https://github.com/arduino/arduino-ide/actions/workflows/check-javascript.yml)
[![Test JavaScript status](https://github.com/arduino/arduino-ide/actions/workflows/test-javascript.yml/badge.svg)](https://github.com/arduino/arduino-ide/actions/workflows/test-javascript.yml)
### Download
This repository contains the source code of the Arduino IDE 2.x. If you're looking for the old IDE, go to the [repository of the 1.x version](https://github.com/arduino/Arduino).
You can download the latest version of the Arduino Pro IDE application for the supported platforms from the [GitHub release page](https://github.com/arduino/arduino-pro-ide/releases) or following the links in the following table.
The Arduino IDE 2.x is a major rewrite, sharing no code with the IDE 1.x. It is based on the [Theia IDE](https://theia-ide.org/) framework and built with [Electron](https://www.electronjs.org/). The backend operations such as compilation and uploading are offloaded to an [arduino-cli](https://github.com/arduino/arduino-cli) instance running in daemon mode. This new IDE was developed with the goal of preserving the same interface and user experience of the previous major version in order to provide a frictionless upgrade.
#### Latest version
![](static/screenshot.png)
Platform | 32 bit | 64 bit |
--------- | ------------------------ | ------------------------ |
Linux | | [Linux 64 bit] |
Linux ARM | [🚧 Work in progress...] | [🚧 Work in progress...] |
Windows | | [Windows 64 bit] |
macOS | | [macOS 64 bit] |
## Download
[🚧 Work in progress...]: https://github.com/arduino/arduino-pro-ide/issues/287
[Linux 64 bit]: https://downloads.arduino.cc/arduino-pro-ide/arduino-pro-ide_latest_Linux_64bit.zip
[Windows 64 bit]: https://downloads.arduino.cc/arduino-pro-ide/arduino-pro-ide_latest_Windows_64bit.zip
[macOS 64 bit]: https://downloads.arduino.cc/arduino-pro-ide/arduino-pro-ide_latest_macOS_64bit.dmg
You can download the latest release version and nightly builds from the [software download page on the Arduino website](https://www.arduino.cc/en/software).
#### Previous versions
## Support
These are available from the [GitHub releases page](https://github.com/arduino/arduino-pro-ide/releases).
If you need assistance, see the [Help Center](https://support.arduino.cc/hc/en-us/categories/360002212660-Software-and-Downloads) and browse the [forum](https://forum.arduino.cc/index.php?board=150.0).
#### Nightly builds
## Bugs & Issues
These builds are generated every day at 03:00 GMT from the `master` branch and
should be considered unstable. In order to get the latest nightly build
available for the supported platform, use the following links:
If you want to report an issue, you can submit it to the [issue tracker](https://github.com/arduino/arduino-ide/issues) of this repository.
Platform | 32 bit | 64 bit |
--------- | ------------------------ | ------------------------ |
Linux | | [Nightly Linux 64 bit] |
Linux ARM | [🚧 Work in progress...] | [🚧 Work in progress...] |
Windows | | [Nightly Windows 64 bit] |
macOS | | [Nightly macOS 64 bit] |
See [**the issue report guide**](docs/contributor-guide/issues.md#issue-report-guide) for instructions.
[🚧 Work in progress...]: https://github.com/arduino/arduino-pro-ide/issues/287
[Nightly Linux 64 bit]: https://downloads.arduino.cc/arduino-pro-ide/nightly/arduino-pro-ide_nightly-latest_Linux_64bit.zip
[Nightly Windows 64 bit]: https://downloads.arduino.cc/arduino-pro-ide/nightly/arduino-pro-ide_nightly-latest_Windows_64bit.zip
[Nightly macOS 64 bit]: https://downloads.arduino.cc/arduino-pro-ide/nightly/arduino-pro-ide_nightly-latest_macOS_64bit.dmg
### Security
> These links return an HTTP `302: Found` response, redirecting to latest
generated builds by replacing `latest` with the latest available build
date, using the format YYYYMMDD (i.e for 2019/Aug/06 `latest` is
replaced with `20190806` )
If you think you found a vulnerability or other security-related bug in this project, please read our
[security policy](https://github.com/arduino/arduino-ide/security/policy) and report the bug to our Security Team 🛡️
Thank you!
### Build from source
e-mail contact: security@arduino.cc
If youre familiar with TypeScript, the [Theia IDE](https://theia-ide.org/), and if you want to contribute to the
project, you should be able to build the Arduino Pro IDE locally. Please refer to the [Theia IDE prerequisites](https://github.com/theia-ide/theia/blob/master/doc/) documentation for the setup instructions.
## Contributions and development
### Build
```sh
yarn
```
Contributions are very welcome! There are several ways to participate in this project, including:
### Rebuild the native dependencies
```sh
yarn rebuild:electron
```
- Fixing bugs
- Beta testing
- Translation
### Start
```sh
yarn start
```
See [**the contributor guide**](docs/CONTRIBUTING.md#contributor-guide) for more information.
### CI
See the [**development guide**](docs/development.md) for a technical overview of the application and instructions for building the code.
This project is built on [GitHub Actions](https://github.com/bcmi-labs/arduino-editor/actions?query=workflow%3A%22Arduino+Pro+IDE%22).
## Donations
- _Snapshot_ builds run when changes are pushed to the `master` branch, or when a PR is created against the `master` branch. For the sake of the review and verification process, the build artifacts can be downloaded from the GitHub Actions page. Note: [due to a limitation](https://github.com/actions/upload-artifact/issues/80#issuecomment-630030144) with the GH Actions UI, you cannot download a particular build, but you have to get all together inside the `build-artifacts.zip`.
- _Nightly_ builds run every day at 03:00 GMT from the `master` branch.
- _Release_ builds run when a new tag is pushed to the remote. The tag must follow the [semver](https://semver.org/). For instance, `1.2.3` is a correct tag, but `v2.3.4` won't work. Steps to trigger a new release build:
- Create a local tag:
```sh
git tag -a 1.2.3 -m "Creating a new tag for the `1.2.3` release."
```
- Push it to the remote:
```sh
git push origin 1.2.3
```
This open source code was written by the Arduino team and is maintained on a daily basis with the help of the community. We invest a considerable amount of time in development, testing and optimization. Please consider [donating](https://www.arduino.cc/en/donate/) or [sponsoring](https://github.com/sponsors/arduino) to support our work, as well as [buying original Arduino boards](https://store.arduino.cc/) which is the best way to make sure our effort can continue in the long term.
### FAQ
## License
- Q: Can I manually change the version of the [`arduino-cli`](https://github.com/arduino/arduino-cli/) used by the IDE?
- A: Yes. It is possible but not recommended. The CLI exposes a set of functionality via [gRPC](https://github.com/arduino/arduino-cli/tree/master/rpc) and the IDE uses this API to communicate with the CLI. Before we build a new version of IDE, we pin a specific version of CLI and use the corresponding `proto` files to generate TypeScript modules for gRPC. This means, a particular version of IDE is compliant only with the pinned version of CLI. Mismatching IDE and CLI versions might not be able to communicate with each other. This could cause unpredictable IDE behavior.
The code contained in this repository and the executable distributions are licensed under the terms of the GNU AGPLv3. The executable distributions contain third-party code licensed under other compatible licenses such as GPLv2, MIT and BSD-3. If you have questions about licensing please contact us at [license@arduino.cc](mailto:license@arduino.cc).
- Q: I have understood that not all versions of the CLI is compatible with my version of IDE but how can I manually update the `arduino-cli` inside the IDE?
- A: [Get](https://arduino.github.io/arduino-cli/installation) the desired version of `arduino-cli` for your platform and manually replace the one inside the IDE. The CLI can be found inside the IDE at:
- Windows: `C:\path\to\Arduino Pro IDE\resources\app\node_modules\arduino-ide-extension\build\arduino-cli.exe`,
- macOS: `/path/to/Arduino Pro IDE.app/Contents/Resources/app/node_modules/arduino-ide-extension/build/arduino-cli`, and
- Linux: `/path/to/Arduino Pro IDE/resources/app/node_modules/arduino-ide-extension/build/arduino-cli`.
### Architecture overview
The Pro IDE consists of three major parts:
- the _Electron main_ process,
- the _backend_, and
- the _frontend_.
The _Electron main_ process is responsible for:
- creating the application,
- managing the application lifecycle via listeners, and
- creating and managing the web pages for the app.
In Electron, the process that runs the main entry JavaScript file is called the main process. The _Electron main_ process can display a GUI by creating web pages. An Electron app always has exactly on main process.
By default, whenever the _Electron main_ process creates a web page, it will instantiate a new `BrowserWindow` instance. Since Electron uses Chromium for displaying web pages, Chromium's multi-process architecture is also used. Each web page in Electron runs in its own process, which is called the renderer process. Each `BrowserWindow` instance runs the web page in its own renderer process. When a `BrowserWindow` instance is destroyed, the corresponding renderer process is also terminated. The main process manages all web pages and their corresponding renderer processes. Each renderer process is isolated and only cares about the web page running in it.<sup>[[1]]</sup>
In normal browsers, web pages usually run in a sandboxed environment, and accessing native resources are disallowed. However, Electron has the power to use Node.js APIs in the web pages allowing lower-level OS interactions. Due to security reasons, accessing native resources is an undesired behavior in the Pro IDE. So by convention, we do not use Node.js APIs. (Note: the Node.js integration is [not yet disabled](https://github.com/eclipse-theia/theia/issues/2018) although it is not used). In the Pro IDE, only the _backend_ allows OS interaction.
The _backend_ process is responsible for:
- providing access to the filesystem,
- communicating with the Arduino CLI via gRPC,
- running your terminal,
- exposing additional RESTful APIs,
- performing the Git commands in the local repositories,
- hosting and running any VS Code extensions, or
- executing VS Code tasks<sup>[[2]]</sup>.
The _Electron main_ process spawns the _backend_ process. There is always exactly one _backend_ process. However, due to performance considerations, the _backend_ spawns several sub-processes for the filesystem watching, Git repository discovery, etc. The communication between the _backend_ process and its sub-processes is established via IPC. Besides spawning sub-processes, the _backend_ will start an HTTP server on a random available port, and serves the web application as static content. When the sub-processes are up and running, and the HTTP server is also listening, the _backend_ process sends the HTTP server port to the _Electron main_ process via IPC. The _Electron main_ process will load the _backend_'s endpoint in the `BrowserWindow`.
The _frontend_ is running as an Electron renderer process and can invoke services implemented on the _backend_. The communication between the _backend_ and the _frontend_ is done via JSON-RPC over a websocket connection. This means, the services running in the _frontend_ are all proxies, and will ask the corresponding service implementation on the _backend_.
[1]: https://www.electronjs.org/docs/tutorial/application-architecture#differences-between-main-process-and-renderer-process
[2]: https://code.visualstudio.com/Docs/editor/tasks

View File

@ -0,0 +1,30 @@
{
"name": "arduino-debugger-extension",
"version": "0.1.1",
"description": "An extension for debugging Arduino programs",
"license": "MIT",
"dependencies": {
"@theia/debug": "next",
"arduino-ide-extension": "0.1.1",
"cdt-gdb-adapter": "^0.0.14",
"vscode-debugadapter": "^1.26.0",
"vscode-debugprotocol": "^1.26.0"
},
"scripts": {
"prepare": "yarn run clean && yarn run build",
"clean": "rimraf lib",
"lint": "tslint -c ./tslint.json --project ./tsconfig.json",
"build": "tsc && yarn lint",
"watch": "tsc -w"
},
"files": [
"lib",
"src"
],
"theiaExtensions": [
{
"backend": "lib/node/arduino-debug-backend-module",
"frontend": "lib/browser/arduino-debug-frontend-module"
}
]
}

View File

@ -0,0 +1,39 @@
import { DebugConfigurationManager } from "@theia/debug/lib/browser/debug-configuration-manager";
import { injectable } from "inversify";
@injectable()
export class ArduinoDebugConfigurationManager extends DebugConfigurationManager {
get defaultDebugger(): Promise<string | undefined> {
return this.debug.getDebuggersForLanguage('ino').then(debuggers => {
if (debuggers.length === 0)
return undefined;
return debuggers[0].type;
});
}
protected async selectDebugType(): Promise<string | undefined> {
const widget = this.editorManager.currentEditor;
if (!widget) {
return this.defaultDebugger;
}
const { languageId } = widget.editor.document;
const debuggers = await this.debug.getDebuggersForLanguage(languageId);
if (debuggers.length === 0) {
return this.defaultDebugger;
}
return this.quickPick.show(debuggers.map(
({ label, type }) => ({ label, value: type }),
{ placeholder: 'Select Environment' })
);
}
async createDefaultConfiguration(): Promise<void> {
const { model } = this;
if (model) {
await this.doCreate(model);
await this.updateModels();
}
}
}

View File

@ -0,0 +1,133 @@
import { injectable, inject } from 'inversify';
import { MenuModelRegistry, Path, MessageService, Command, CommandRegistry } from '@theia/core';
import { KeybindingRegistry } from '@theia/core/lib/browser';
import { TabBarToolbarRegistry } from '@theia/core/lib/browser/shell/tab-bar-toolbar';
import { DebugFrontendApplicationContribution, DebugCommands } from '@theia/debug/lib/browser/debug-frontend-application-contribution';
import { DebugSessionOptions } from "@theia/debug/lib/browser/debug-session-options";
import { WorkspaceService } from '@theia/workspace/lib/browser/workspace-service';
import { FileSystem } from '@theia/filesystem/lib/common';
import URI from '@theia/core/lib/common/uri';
import { EditorManager } from '@theia/editor/lib/browser';
import { EditorMode } from "arduino-ide-extension/lib/browser/editor-mode";
import { SketchesService } from 'arduino-ide-extension/lib/common/protocol/sketches-service';
import { ArduinoToolbar } from 'arduino-ide-extension/lib/browser/toolbar/arduino-toolbar';
import { ArduinoDebugConfigurationManager } from './arduino-debug-configuration-manager';
export namespace ArduinoDebugCommands {
export const START_DEBUG: Command = {
id: 'arduino-start-debug',
label: 'Start Debugging'
}
}
@injectable()
export class ArduinoDebugFrontendApplicationContribution extends DebugFrontendApplicationContribution {
@inject(EditorMode)
protected readonly editorMode: EditorMode;
@inject(WorkspaceService)
protected readonly workspaceService: WorkspaceService;
@inject(SketchesService)
protected readonly sketchesService: SketchesService;
@inject(FileSystem)
protected readonly fileSystem: FileSystem;
@inject(EditorManager)
protected readonly editorManager: EditorManager;
@inject(MessageService)
protected readonly messageService: MessageService;
async start(noDebug?: boolean, debugSessionOptions?: DebugSessionOptions): Promise<void> {
const configurations = this.configurations as ArduinoDebugConfigurationManager;
let current = debugSessionOptions ? debugSessionOptions : configurations.current;
// If no configurations are currently present, create them
if (!current) {
await configurations.createDefaultConfiguration();
current = configurations.current;
}
if (current) {
if (noDebug !== undefined) {
current = {
...current,
configuration: {
...current.configuration,
noDebug
}
};
}
if (current.configuration.type === 'arduino') {
const wsStat = this.workspaceService.workspace;
let sketchFileURI: URI | undefined;
if (wsStat && await this.sketchesService.isSketchFolder(wsStat.uri)) {
const wsPath = new Path(wsStat.uri);
const sketchFilePath = wsPath.join(wsPath.name + '.ino').toString();
sketchFileURI = new URI(sketchFilePath);
} else if (this.editorManager.currentEditor) {
const editorURI = this.editorManager.currentEditor.getResourceUri();
if (editorURI && editorURI.path && editorURI.path.ext === '.ino') {
sketchFileURI = editorURI;
}
}
if (sketchFileURI) {
await this.editorManager.open(sketchFileURI);
await this.manager.start(current);
} else {
this.messageService.error('Please open a sketch file to start debugging.')
}
} else {
await this.manager.start(current);
}
}
}
initializeLayout(): Promise<void> {
if (this.editorMode.proMode) {
return super.initializeLayout();
}
return Promise.resolve();
}
registerMenus(menus: MenuModelRegistry): void {
if (this.editorMode.proMode) {
super.registerMenus(menus);
menus.unregisterMenuAction(DebugCommands.START_NO_DEBUG);
}
}
registerKeybindings(keybindings: KeybindingRegistry): void {
if (this.editorMode.proMode) {
super.registerKeybindings(keybindings);
keybindings.unregisterKeybinding({
command: DebugCommands.START_NO_DEBUG.id,
keybinding: 'ctrl+f5'
});
}
}
registerToolbarItems(toolbar: TabBarToolbarRegistry): void {
super.registerToolbarItems(toolbar);
toolbar.registerItem({
id: ArduinoDebugCommands.START_DEBUG.id,
command: ArduinoDebugCommands.START_DEBUG.id,
tooltip: 'Start Debugging',
priority: 3
});
}
registerCommands(registry: CommandRegistry): void {
super.registerCommands(registry);
registry.registerCommand(ArduinoDebugCommands.START_DEBUG, {
isVisible: widget => ArduinoToolbar.is(widget) && widget.side === 'left',
isEnabled: widget => ArduinoToolbar.is(widget) && widget.side === 'left',
execute: () => {
registry.executeCommand(DebugCommands.START.id);
}
});
}
}

View File

@ -0,0 +1,19 @@
import { ContainerModule } from 'inversify';
import { VariableContribution } from '@theia/variable-resolver/lib/browser';
import { ArduinoVariableResolver } from './arduino-variable-resolver';
import { DebugSessionManager } from '@theia/debug/lib/browser/debug-session-manager';
import { DebugFrontendApplicationContribution } from '@theia/debug/lib/browser/debug-frontend-application-contribution';
import { DebugConfigurationManager } from '@theia/debug/lib/browser/debug-configuration-manager';
import { ArduinoDebugConfigurationManager } from './arduino-debug-configuration-manager';
import { ArduinoDebugFrontendApplicationContribution } from './arduino-debug-frontend-application-contribution';
import { ArduinoDebugSessionManager } from './arduino-debug-session-manager';
import '../../src/browser/style/index.css';
export default new ContainerModule((bind, unbind, isBound, rebind) => {
bind(ArduinoVariableResolver).toSelf().inSingletonScope();
bind(VariableContribution).toService(ArduinoVariableResolver);
rebind(DebugSessionManager).to(ArduinoDebugSessionManager).inSingletonScope();
rebind(DebugConfigurationManager).to(ArduinoDebugConfigurationManager).inSingletonScope();
rebind(DebugFrontendApplicationContribution).to(ArduinoDebugFrontendApplicationContribution);
});

View File

@ -0,0 +1,14 @@
import { DebugSessionManager } from "@theia/debug/lib/browser/debug-session-manager";
import { DebugSessionOptions } from "@theia/debug/lib/browser/debug-session-options";
export class ArduinoDebugSessionManager extends DebugSessionManager {
start(options: DebugSessionOptions) {
if (options.configuration.type === 'arduino' && this.sessions.find(s => s.configuration.type === 'arduino')) {
this.messageService.info('A debug session is already running. You must stop the running session before starting a new one.')
return Promise.resolve(undefined);
}
return super.start(options);
}
}

View File

@ -0,0 +1,46 @@
import { VariableContribution, VariableRegistry, Variable } from '@theia/variable-resolver/lib/browser';
import { injectable, inject } from 'inversify';
import { MessageService } from '@theia/core/lib/common/message-service';
import { BoardsServiceClientImpl } from 'arduino-ide-extension/lib/browser/boards/boards-service-client-impl';
@injectable()
export class ArduinoVariableResolver implements VariableContribution {
@inject(BoardsServiceClientImpl)
protected readonly boardsServiceClient: BoardsServiceClientImpl;
@inject(MessageService)
protected readonly messageService: MessageService
registerVariables(variables: VariableRegistry): void {
variables.registerVariable(<Variable>{
name: 'fqbn',
description: 'Qualified name of the selected board',
resolve: this.resolveFqbn.bind(this),
});
variables.registerVariable({
name: 'port',
description: 'Selected upload port',
resolve: this.resolvePort.bind(this)
});
}
protected async resolveFqbn(): Promise<string | undefined> {
const { boardsConfig } = this.boardsServiceClient;
if (!boardsConfig || !boardsConfig.selectedBoard) {
this.messageService.error('No board selected. Please select a board for debugging.');
return undefined;
}
return boardsConfig.selectedBoard.fqbn;
}
protected async resolvePort(): Promise<string | undefined> {
const { boardsConfig } = this.boardsServiceClient;
if (!boardsConfig || !boardsConfig.selectedPort) {
return undefined;
}
return boardsConfig.selectedPort.address;
}
}

View File

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

After

Width:  |  Height:  |  Size: 2.3 KiB

View File

@ -0,0 +1,16 @@
.arduino-start-debug-icon {
-webkit-mask: url('debug-dark.svg') 50%;
mask: url('debug-dark.svg') 50%;
-webkit-mask-size: 100%;
mask-size: 100%;
-webkit-mask-repeat: no-repeat;
mask-repeat: no-repeat;
display: flex;
justify-content: center;
align-items: center;
color: var(--theia-ui-button-font-color);
}
.arduino-start-debug {
border-radius: 12px;
}

View File

@ -0,0 +1,89 @@
import * as path from 'path';
import { injectable, inject } from 'inversify';
import { DebugAdapterContribution, DebugAdapterExecutable } from '@theia/debug/lib/common/debug-model';
import { DebugConfiguration } from '@theia/debug/lib/common/debug-configuration';
import { IJSONSchema } from '@theia/core/lib/common/json-schema';
import { ArduinoDaemonImpl } from 'arduino-ide-extension/lib/node/arduino-daemon-impl';
@injectable()
export class ArduinoDebugAdapterContribution implements DebugAdapterContribution {
readonly type = 'arduino';
readonly label = 'Arduino';
readonly languages = ['c', 'cpp', 'ino'];
@inject(ArduinoDaemonImpl) daemon: ArduinoDaemonImpl;
getSchemaAttributes(): IJSONSchema[] {
return [
{
'properties': {
'sketch': {
'type': 'string',
'description': 'path to the sketch root ino file',
'default': '${file}',
},
'pauseAtMain': {
'description': 'If enabled the debugger will pause at the start of the main function.',
'type': 'boolean',
'default': false
},
'debugDebugAdapter': {
'type': 'boolean',
'description': 'Start the debug adapter in debug mode (with --inspect-brk)',
'default': false
},
}
}
]
}
provideDebugAdapterExecutable(config: DebugConfiguration): DebugAdapterExecutable {
const debugAdapterMain = path.join(__dirname, 'debug-adapter', 'main');
if (config.debugDebugAdapter) {
return {
command: process.execPath,
args: ['--inspect-brk', debugAdapterMain],
}
}
return {
modulePath: debugAdapterMain,
args: [],
}
}
provideDebugConfigurations(): DebugConfiguration[] {
return [
<DebugConfiguration>{
name: this.label,
type: this.type,
request: 'launch'
}
];
}
async resolveDebugConfiguration(config: DebugConfiguration): Promise<DebugConfiguration> {
const startFunction = config.pauseAtMain ? 'main' : 'setup';
const res: ActualDebugConfig = {
...config,
arduinoCli: await this.daemon.getExecPath(),
fqbn: '${fqbn}',
uploadPort: '${port}',
initCommands: [
`-break-insert -t --function ${startFunction}`
]
}
if (!res.sketch) {
res.sketch = '${file}';
}
return res;
}
}
interface ActualDebugConfig extends DebugConfiguration {
arduinoCli?: string;
sketch?: string;
fqbn?: string;
uploadPort?: string;
}

View File

@ -0,0 +1,7 @@
import { ContainerModule } from 'inversify';
import { DebugAdapterContribution } from '@theia/debug/lib/common/debug-model';
import { ArduinoDebugAdapterContribution } from './arduino-debug-adapter-contribution';
export default new ContainerModule((bind, unbind, isBound, rebind) => {
bind(DebugAdapterContribution).to(ArduinoDebugAdapterContribution).inSingletonScope();
});

View File

@ -0,0 +1,140 @@
import { DebugProtocol } from 'vscode-debugprotocol';
import { GDBDebugSession, FrameVariableReference } from 'cdt-gdb-adapter/dist/GDBDebugSession';
import { GDBBackend } from 'cdt-gdb-adapter/dist/GDBBackend';
import * as mi from 'cdt-gdb-adapter/dist/mi';
import { ArduinoGDBBackend } from './arduino-gdb-backend';
import { ArduinoVariableHandler } from './arduino-variable-handler';
import { Scope, OutputEvent } from 'vscode-debugadapter';
export interface ArduinoLaunchRequestArguments extends DebugProtocol.LaunchRequestArguments {
arduinoCli?: string;
sketch?: string;
fqbn?: string;
uploadPort?: string;
}
const GLOBAL_HANDLE_ID = 0xFE;
const STATIC_HANDLES_START = 0x010000;
const STATIC_HANDLES_FINISH = 0x01FFFF;
export class ArduinoDebugSession extends GDBDebugSession {
private _variableHandler: ArduinoVariableHandler;
get arduinoBackend(): ArduinoGDBBackend {
return this.gdb as ArduinoGDBBackend;
}
protected get variableHandler() {
if (this._variableHandler) {
return this._variableHandler;
}
if (!this.gdb) {
throw new Error("GDB backend is not ready.");
}
const handler = new ArduinoVariableHandler(this, this.frameHandles, this.variableHandles);
this._variableHandler = handler;
return handler;
}
protected createBackend(): GDBBackend {
return new ArduinoGDBBackend();
}
protected async configurationDoneRequest(response: DebugProtocol.ConfigurationDoneResponse): Promise<void> {
try {
await this.gdb.sendCommand('-interpreter-exec console "monitor reset halt"')
await mi.sendExecContinue(this.gdb);
this.sendResponse(response);
} catch (err) {
this.sendErrorResponse(response, 100, err.message);
}
}
protected pauseRequest(response: DebugProtocol.PauseResponse, args: DebugProtocol.PauseArguments): Promise<void> {
if (process.platform === 'win32') {
const message = 'Pause is not supported on Windows. Please stop the debug session and set a breakpoint instead.';
this.sendEvent(new OutputEvent(message));
this.sendErrorResponse(response, 1, message);
return Promise.resolve();
}
return super.pauseRequest(response, args);
}
protected async disconnectRequest(response: DebugProtocol.DisconnectResponse): Promise<void> {
try {
if (this.isRunning) {
if (process.platform === 'win32') {
// We cannot pause on Windows
this.arduinoBackend.kill();
this.sendResponse(response);
return;
}
// Need to pause first
const waitPromise = new Promise(resolve => this.waitPaused = resolve);
this.gdb.pause();
await waitPromise;
}
await this.gdb.sendGDBExit();
this.sendResponse(response);
} catch (err) {
this.sendErrorResponse(response, 1, err.message);
}
}
protected scopesRequest(response: DebugProtocol.ScopesResponse, args: DebugProtocol.ScopesArguments): void {
try {
const frame: FrameVariableReference = {
type: 'frame',
frameHandle: args.frameId,
};
// const pins: ObjectVariableReference = {
// type: "object",
// varobjName: "__pins",
// frameHandle: 42000,
// }
response.body = {
scopes: [
// new Scope('Pins', this.variableHandles.create(pins), false),
new Scope('Local', this.variableHandles.create(frame), false),
new Scope('Global', GLOBAL_HANDLE_ID, false),
// new Scope('Static', STATIC_HANDLES_START + parseInt(args.frameId as any, 10), false)
],
};
this.sendResponse(response);
} catch (err) {
this.sendErrorResponse(response, 1, err.message);
}
}
protected async variablesRequest(response: DebugProtocol.VariablesResponse, args: DebugProtocol.VariablesArguments): Promise<void> {
try {
response.body = {
variables: [] as DebugProtocol.Variable[]
};
const ref = this.variableHandles.get(args.variablesReference);
if (args.variablesReference === GLOBAL_HANDLE_ID) {
// Use hardcoded global handle to load and store global variables
response.body.variables = await this.variableHandler.getGlobalVariables();
} else if (args.variablesReference >= STATIC_HANDLES_START && args.variablesReference <= STATIC_HANDLES_FINISH) {
// Use STATIC_HANDLES_START to shift the framehandles back
const frameHandle = args.variablesReference - STATIC_HANDLES_START;
response.body.variables = await this.variableHandler.getStaticVariables(frameHandle);
} else if (ref && ref.type === 'frame') {
// List variables for current frame
response.body.variables = await this.handleVariableRequestFrame(ref);
} else if (ref && ref.varobjName === '__pins') {
response.body.variables = await this.variableHandler.handlePinStatusRequest();
} else if (ref && ref.type === 'object') {
// List data under any variable
response.body.variables = await this.handleVariableRequestObject(ref);
}
this.sendResponse(response);
} catch (err) {
this.sendErrorResponse(response, 1, err.message);
}
}
}

View File

@ -0,0 +1,72 @@
import * as path from 'path';
import * as fs from 'arduino-ide-extension/lib/node/fs-extra'
import { spawn } from 'child_process';
import { GDBBackend } from 'cdt-gdb-adapter/dist/GDBBackend';
import { MIFrameInfo } from 'cdt-gdb-adapter/dist/mi';
import { ArduinoLaunchRequestArguments } from './arduino-debug-session';
import { ArduinoParser } from './arduino-parser';
export class ArduinoGDBBackend extends GDBBackend {
constructor() {
super();
this.parser = new ArduinoParser(this);
}
spawn(requestArgs: ArduinoLaunchRequestArguments): Promise<void> {
if (!requestArgs.sketch) {
throw new Error('Missing argument: sketch');
}
if (!requestArgs.fqbn) {
throw new Error('Missing argument: fqbn')
}
const sketchFS = fs.statSync(requestArgs.sketch);
const sketchDir = sketchFS.isFile() ? path.dirname(requestArgs.sketch) : requestArgs.sketch;
const command = requestArgs.arduinoCli || 'arduino-cli';
const args = [
'debug',
'-p', requestArgs.uploadPort || 'none',
'-b', requestArgs.fqbn,
'--interpreter', 'mi2',
sketchDir
];
const proc = spawn(command, args);
this.proc = proc;
this.out = proc.stdin;
return (this.parser as ArduinoParser).parseFull(proc);
}
sendFileExecAndSymbols(): Promise<void> {
// The program file is already sent by `arduino-cli`
return Promise.resolve();
}
sendExecInterrupt(threadId?: number) {
let command = '-exec-interrupt';
if (threadId) {
command += ` --thread ${threadId}`;
}
return this.sendCommand(command);
}
sendStackInfoFrame(threadId: number, frameId: number): Promise<{ frame: MIFrameInfo }> {
const command = `-stack-info-frame --thread ${threadId} --frame ${frameId}`;
return this.sendCommand(command);
}
sendTargetDetach(): Promise<void> {
return this.sendCommand('-target-detach');
}
kill(): void {
if (!this.proc) {
return;
}
if (process.platform === 'win32') {
spawn('taskkill', ['/pid', this.proc.pid.toString(), '/f', '/t']);
} else {
this.proc.kill('SIGKILL');
}
}
}

View File

@ -0,0 +1,76 @@
import { ChildProcessWithoutNullStreams } from 'child_process';
import { Readable } from 'stream';
import { MIParser } from "cdt-gdb-adapter/dist/MIParser";
const LINE_REGEX = /(.*)(\r?\n)/;
export class ArduinoParser extends MIParser {
protected rejectReady?: (error: Error) => void;
parseFull(proc: ChildProcessWithoutNullStreams): Promise<void> {
return new Promise((resolve, reject) => {
// Detect errors when the child process could not be spawned
proc.on('error', reject);
this.waitReady = () => {
this.rejectReady = undefined;
resolve();
}
this.rejectReady = (error: Error) => {
this.waitReady = undefined;
reject(error);
}
// Detect unexpected termination
proc.on('exit', () => {
if (this.rejectReady) {
this.rejectReady(new Error('The gdb debugger terminated unexpectedly.'));
}
});
this.readInputStream(proc.stdout);
this.readErrorStream(proc.stderr);
});
}
private readInputStream(stream: Readable) {
let buff = '';
stream.on('data', chunk => {
buff += chunk.toString();
let regexArray = LINE_REGEX.exec(buff);
while (regexArray) {
const line = regexArray[1];
this.line = line;
this.pos = 0;
this.handleLine();
// Detect error emitted as log message
if (this.rejectReady && line.toLowerCase().startsWith('&"error')) {
this.pos = 1;
this.rejectReady(new Error(this.handleCString() || regexArray[1]));
this.rejectReady = undefined;
}
buff = buff.substring(regexArray[1].length + regexArray[2].length);
regexArray = LINE_REGEX.exec(buff);
}
});
}
private readErrorStream(stream: Readable) {
let buff = '';
stream.on('data', chunk => {
buff += chunk.toString();
let regexArray = LINE_REGEX.exec(buff);
while (regexArray) {
const line = regexArray[1];
this.gdb.emit('consoleStreamOutput', line + '\n', 'stderr');
// Detect error emitted on the stderr stream
if (this.rejectReady && line.toLowerCase().startsWith('error')) {
this.rejectReady(new Error(line));
this.rejectReady = undefined;
}
buff = buff.substring(regexArray[1].length + regexArray[2].length);
regexArray = LINE_REGEX.exec(buff);
}
});
}
}

View File

@ -0,0 +1,115 @@
import * as path from 'path';
import { DebugProtocol } from "vscode-debugprotocol";
import { Handles } from 'vscode-debugadapter/lib/handles';
import { FrameReference, VariableReference } from "cdt-gdb-adapter/dist/GDBDebugSession";
import { VarManager } from 'cdt-gdb-adapter/dist/varManager';
import * as mi from 'cdt-gdb-adapter/dist/mi';
import { ArduinoDebugSession } from "./arduino-debug-session";
import { ArduinoGDBBackend } from './arduino-gdb-backend';
export class ArduinoVariableHandler {
protected readonly gdb: ArduinoGDBBackend;
protected readonly varMgr: VarManager;
protected globalHandle: number;
constructor(protected readonly session: ArduinoDebugSession,
protected frameHandles: Handles<FrameReference>,
protected variableHandles: Handles<VariableReference>) {
this.gdb = session.arduinoBackend;
this.varMgr = new VarManager(this.gdb);
}
createGlobalHandle() {
this.globalHandle = this.frameHandles.create({
threadId: -1,
frameId: -1
});
}
/** TODO */
async getGlobalVariables(): Promise<DebugProtocol.Variable[]> {
throw new Error('Global variables are not supported yet.');
const frame = this.frameHandles.get(this.globalHandle);
const symbolInfo: any[] = [] // this.symbolTable.getGlobalVariables();
const variables: DebugProtocol.Variable[] = [];
for (const symbol of symbolInfo) {
const name = `global_var_${symbol.name}`;
const variable = await this.getVariables(frame, name, symbol.name, -1);
variables.push(variable);
}
return variables;
}
/** TODO */
async getStaticVariables(frameHandle: number): Promise<DebugProtocol.Variable[]> {
throw new Error('Static variables are not supported yet.');
const frame = this.frameHandles.get(frameHandle);
const result = await this.gdb.sendStackInfoFrame(frame.threadId, frame.frameId);
const file = path.normalize(result.frame.file || '');
const symbolInfo: any[] = [] // this.symbolTable.getStaticVariables(file);
const variables: DebugProtocol.Variable[] = [];
// Fetch stack depth to obtain frameId/threadId/depth tuple
const stackDepth = await mi.sendStackInfoDepth(this.gdb, { maxDepth: 100 });
const depth = parseInt(stackDepth.depth, 10);
for (const symbol of symbolInfo) {
const name = `${file}_static_var_${symbol.name}`;
const variable = await this.getVariables(frame, name, symbol.name, depth);
variables.push(variable);
}
return variables;
}
private async getVariables(frame: FrameReference, name: string, expression: string, depth: number): Promise<DebugProtocol.Variable> {
let global = this.varMgr.getVar(frame.frameId, frame.threadId, depth, name);
if (global) {
// Update value if it is already loaded
const vup = await mi.sendVarUpdate(this.gdb, { name });
const update = vup.changelist[0];
if (update && update.in_scope === 'true' && update.name === global.varname) {
global.value = update.value;
}
} else {
// create var in GDB and store it in the varMgr
const varCreateResponse = await mi.sendVarCreate(this.gdb, {
name,
frame: 'current',
expression,
});
global = this.varMgr.addVar(frame.frameId, frame.threadId, depth, name, true, false, varCreateResponse);
}
return {
name: expression,
value: (global.value === void 0) ? '<unknown>' : global.value,
type: global.type,
variablesReference: parseInt(global.numchild, 10) > 0
? this.variableHandles.create({
frameHandle: this.globalHandle,
type: 'object',
varobjName: global.varname,
})
: 0,
};
}
async handlePinStatusRequest(): Promise<DebugProtocol.Variable[]> {
const variables: DebugProtocol.Variable[] = [];
variables.push({
name: "D2",
type: "gpio",
value: "0x00",
variablesReference: 0
})
return variables;
}
}

View File

@ -0,0 +1,10 @@
import * as process from 'process';
import { logger } from 'vscode-debugadapter/lib/logger';
import { ArduinoDebugSession } from './arduino-debug-session';
import { DebugSession } from 'vscode-debugadapter';
process.on('uncaughtException', (err: any) => {
logger.error(JSON.stringify(err));
});
DebugSession.run(ArduinoDebugSession);

View File

@ -0,0 +1,31 @@
{
"compilerOptions": {
"declaration": true,
"declarationMap": true,
"noImplicitAny": true,
"noEmitOnError": true,
"noImplicitThis": true,
"noUnusedLocals": true,
"strictNullChecks": true,
"experimentalDecorators": true,
"downlevelIteration": true,
"emitDecoratorMetadata": true,
"module": "commonjs",
"moduleResolution": "node",
"target": "es6",
"outDir": "lib",
"lib": [
"es6",
"dom"
],
"jsx": "react",
"sourceMap": true,
"skipLibCheck": true
},
"include": [
"src"
],
"files": [
"../node_modules/@theia/monaco/src/typings/monaco/index.d.ts"
]
}

View File

@ -0,0 +1,37 @@
{
"rules": {
"class-name": true,
"comment-format": [true, "check-space"],
"curly": false,
"forin": false,
"indent": [true, "spaces"],
"max-line-length": [true, 180],
"no-trailing-whitespace": false,
"no-unused-expression": true,
"no-var-keyword": true,
"one-line": [true,
"check-open-brace",
"check-catch",
"check-else",
"check-whitespace"
],
"radix": true,
"trailing-comma": [false],
"triple-equals": [true, "allow-null-check"],
"typedef-whitespace": [true, {
"call-signature": "nospace",
"index-signature": "nospace",
"parameter": "nospace",
"property-declaration": "nospace",
"variable-declaration": "nospace"
}],
"variable-name": false,
"whitespace": [true,
"check-branch",
"check-decl",
"check-operator",
"check-separator",
"check-type"
]
}
}

View File

@ -1,6 +1,6 @@
## Arduino IDE Extension
Arduino IDE is based on Theia, and most of its IDE features, UIs and customizations are implemented in this Theia extension.
Arduino Pro IDE is based on Theia, and most of its IDE features, UIs and customizations are implemented in this Theia extension.
### IDE Services
@ -30,20 +30,17 @@ The Core Service is responsible for building your sketches and uploading them to
- compiling a sketch for a selected board type
- uploading a sketch to a connected board
#### Serial Service
#### Monitor Service
The Serial Service allows getting information back from sketches running on your Arduino boards.
The Monitor Service allows getting information back from sketches running on your Arduino boards.
- [src/common/protocol/serial-service.ts](./src/common/protocol/serial-service.ts) implements the common classes and interfaces
- [src/node/serial/serial-service-impl.ts](./src/node/serial/serial-service-impl.ts) implements the service backend:
- [src/common/protocol/monitor-service.ts](./src/common/protocol/monitor-service.ts) implements the common classes and interfaces
- [src/node/monitor-service-impl.ts](./src/node/monitor-service-impl.ts) implements the service backend:
- connecting to / disconnecting from a board
- receiving and sending data
- [src/browser/serial/serial-connection-manager.ts](./src/browser/serial/serial-connection-manager.ts) handles the serial connection in the frontend
- [src/browser/serial/monitor/monitor-widget.tsx](./src/browser/serial/monitor/monitor-widget.tsx) implements the serial monitor front-end:
- [src/browser/monitor/monitor-widget.tsx](./src/browser/monitor/monitor-widget.tsx) implements the serial monitor front-end:
- viewing the output from a connected board
- entering data to send to the board
- [src/browser/serial/plotter/plotter-frontend-contribution.ts](./src/browser/serial/plotter/plotter-frontend-contribution.ts) implements the serial plotter front-end:
- opening a new window running the [Serial Plotter Web App](https://github.com/arduino/arduino-serial-plotter-webapp)
#### Config Service
@ -53,34 +50,3 @@ The Config Service knows about your system, like for example the default sketch
- [src/node/config-service-impl.ts](./src/node/config-service-impl.ts) implements the service backend:
- getting the `arduino-cli` version and configuration
- checking whether a file is in a data or sketch directory
### `"arduino"` configuration in the `package.json`:
- `"cli"`:
- `"version"` type `string` | `{ owner: string, repo: string, commitish?: string }`: if the type is a `string` and is a valid semver, it will get the corresponding [released](https://github.com/arduino/arduino-cli/releases) CLI. If the type is `string` and is a [date in `YYYYMMDD`](https://arduino.github.io/arduino-cli/latest/installation/#nightly-builds) format, it will get a nightly CLI. If the type is an object, a CLI, build from the sources in the `owner/repo` will be used. If `commitish` is not defined, the HEAD of the default branch will be used. In any other cases an error is thrown.
#### 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`
### Update **clangd** and **ClangFormat**
The [**clangd** C++ language server](https://clangd.llvm.org/) and the [**ClangFormat** code formatter](https://clang.llvm.org/docs/ClangFormat.html) tool dependencies are managed in parallel. Updating them to a different version is done by the following procedure:
1. If the target version is not already [available from the `arduino/clang-static-binaries` repository](https://github.com/arduino/clang-static-binaries/releases), submit [an issue there](https://github.com/arduino/clang-static-binaries/issues) requesting a build and wait for that to be completed.
1. Validate the **ClangFormat** configuration for the target version by following the instructions [**here**](https://github.com/arduino/tooling-project-assets/tree/main/other/clang-format-configuration#clangformat-version-updates)
1. Submit a pull request in the `arduino/arduino-ide` repository to update the version in the `arduino.clangd.version` key of [`package.json`](package.json).
1. Submit a pull request in [the `arduino/tooling-project-assets` repository](https://github.com/arduino/tooling-project-assets) to update the version in the `vars.DEFAULT_CLANG_FORMAT_VERSION` field of [`Taskfile.yml`](https://github.com/arduino/tooling-project-assets/blob/main/Taskfile.yml).
### Customize Icons
ArduinoIde uses a customized version of FontAwesome.
In order to update/replace icons follow the following steps:
- import the file `arduino-icons.json` in [Icomoon](https://icomoon.io/app/#/projects)
- load it
- edit the icons as needed
- !! download the **new** `arduino-icons.json` file and put it in this repo
- Click on "Generate Font" in Icomoon, then download
- place the updated fonts in the `src/style/fonts` directory

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,117 @@
{
"$id": "http://arduino.cc/arduino-cli.json",
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"title": "Arduino CLI Configuration",
"properties": {
"board_manager": {
"type": "object",
"description": "Board Manager Configuration",
"properties": {
"additional_urls": {
"type": "array",
"description": "If your board requires 3rd party core packages to work, you can list the URLs to additional package indexes in the Arduino CLI configuration file.",
"items": {
"type": "string",
"description": "URL pointing to the 3rd party core package index JSON.",
"pattern": "^(.*)$"
},
"additionalProperties": false
}
},
"additionalProperties": false
},
"daemon": {
"type": "object",
"description": "CLI Daemon Configuration",
"properties": {
"port": {
"type": [
"string",
"number"
],
"description": "The CLI daemon port where the gRPC clients can connect to.",
"pattern": "^([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$",
"additionalProperties": false
}
},
"additionalProperties": false
},
"directories": {
"type": "object",
"description": "Directories Configuration",
"properties": {
"data": {
"type": "string",
"description": "Path to the the data folder where core packages will be stored.",
"pattern": "^(.*)$"
},
"downloads": {
"type": "string",
"description": "Path to the staging folder.",
"pattern": "^(.*)$"
},
"user": {
"type": "string",
"description": "Path to the sketchbooks.",
"pattern": "^(.*)$"
}
},
"additionalProperties": false
},
"logging": {
"type": "object",
"description": "Logging Configuration",
"properties": {
"file": {
"type": "string",
"description": "Path to the file where logs will be written.",
"pattern": "^(.*)$"
},
"format": {
"type": "string",
"description": "The output format for the logs, can be 'text' or 'json'",
"enum": [
"text",
"json"
]
},
"level": {
"type": "string",
"description": "Messages with this level and above will be logged.",
"enum": [
"trace",
"debug",
"info",
"warning",
"error",
"fatal",
"panic"
]
}
},
"additionalProperties": false
},
"telemetry": {
"type": "object",
"description": "Telemetry Configuration",
"properties": {
"addr": {
"type": "string",
"description": "Address to the telemetry endpoint. Must be a full address with host, address, and port. For instance, ':9090' represents 'localhost:9090'",
"pattern": "^(.*)$"
},
"enabled": {
"type": "boolean",
"description": "Whether the telemetry is enabled or not."
},
"additionalProperties": false
},
"additionalProperties": false
}
},
"// TODOs": [
"additionalProperties should be true. See the new telemetry entry"
],
"additionalProperties": false
}

File diff suppressed because it is too large Load Diff

View File

@ -1,141 +1,94 @@
{
"name": "arduino-ide-extension",
"version": "2.3.7",
"version": "0.1.1",
"description": "An extension for Theia building the Arduino IDE",
"license": "AGPL-3.0-or-later",
"license": "MIT",
"scripts": {
"prepare": "yarn download-cli && yarn download-fwuploader && yarn download-ls && yarn copy-i18n && yarn download-examples",
"prepare": "yarn download-cli && yarn download-ls && yarn run clean && yarn run build",
"clean": "rimraf lib",
"compose-changelog": "node ./scripts/compose-changelog.js",
"download-cli": "node ./scripts/download-cli.js",
"download-fwuploader": "node ./scripts/download-fwuploader.js",
"copy-i18n": "ncp ../i18n ./src/node/resources/i18n",
"download-ls": "node ./scripts/download-ls.js",
"download-examples": "node ./scripts/download-examples.js",
"generate-protocol": "node ./scripts/generate-protocol.js",
"lint": "eslint .",
"prebuild": "rimraf lib",
"build": "tsc",
"build:dev": "yarn build",
"postbuild": "ncp ./src/node/cli-protocol/ ./lib/node/cli-protocol/",
"lint": "tslint -c ./tslint.json --project ./tsconfig.json",
"build": "tsc && ncp ./src/node/cli-protocol/ ./lib/node/cli-protocol/ && yarn lint",
"watch": "tsc -w",
"test": "cross-env IDE2_TEST=true mocha \"./lib/test/**/*.test.js\"",
"test:slow": "cross-env IDE2_TEST=true mocha \"./lib/test/**/*.slow-test.js\" --slow 5000"
"test": "mocha \"./lib/test/**/*.test.js\"",
"test:watch": "mocha --watch --watch-files lib \"./lib/test/**/*.test.js\""
},
"dependencies": {
"@grpc/grpc-js": "^1.8.14",
"@theia/application-package": "1.57.0",
"@theia/core": "1.57.0",
"@theia/debug": "1.57.0",
"@theia/editor": "1.57.0",
"@theia/electron": "1.57.0",
"@theia/filesystem": "1.57.0",
"@theia/keymaps": "1.57.0",
"@theia/markers": "1.57.0",
"@theia/messages": "1.57.0",
"@theia/monaco": "1.57.0",
"@theia/monaco-editor-core": "1.83.101",
"@theia/navigator": "1.57.0",
"@theia/outline-view": "1.57.0",
"@theia/output": "1.57.0",
"@theia/plugin-ext": "1.57.0",
"@theia/plugin-ext-vscode": "1.57.0",
"@theia/preferences": "1.57.0",
"@theia/scm": "1.57.0",
"@theia/search-in-workspace": "1.57.0",
"@theia/terminal": "1.57.0",
"@theia/test": "1.57.0",
"@theia/typehierarchy": "1.57.0",
"@theia/workspace": "1.57.0",
"@tippyjs/react": "^4.2.5",
"@types/auth0-js": "^9.21.3",
"@types/btoa": "^1.2.3",
"@grpc/grpc-js": "^1.1.1",
"@theia/application-package": "next",
"@theia/core": "next",
"@theia/editor": "next",
"@theia/filesystem": "next",
"@theia/git": "next",
"@theia/languages": "next",
"@theia/markers": "next",
"@theia/monaco": "next",
"@theia/navigator": "next",
"@theia/outline-view": "next",
"@theia/preferences": "next",
"@theia/output": "next",
"@theia/search-in-workspace": "next",
"@theia/terminal": "next",
"@theia/workspace": "next",
"@types/dateformat": "^3.0.1",
"@types/deepmerge": "^2.2.0",
"@types/glob": "^5.0.35",
"@types/google-protobuf": "^3.7.2",
"@types/js-yaml": "^3.12.2",
"@types/jsdom": "^21.1.1",
"@types/lodash.debounce": "^4.0.6",
"@types/node-fetch": "^2.5.7",
"@types/p-queue": "^2.3.1",
"@types/ncp": "^2.0.4",
"@types/ps-tree": "^1.1.0",
"@types/react-select": "^3.0.0",
"@types/sinon": "^7.5.2",
"@types/temp": "^0.8.34",
"arduino-serial-plotter-webapp": "0.2.0",
"async-mutex": "^0.3.0",
"auth0-js": "^9.23.2",
"btoa": "^1.2.1",
"classnames": "^2.3.1",
"cross-fetch": "^3.1.5",
"@types/which": "^1.3.1",
"ajv": "^6.5.3",
"css-element-queries": "^1.2.0",
"dateformat": "^3.0.3",
"deepmerge": "^4.2.2",
"dompurify": "^2.4.7",
"drivelist": "^9.2.4",
"electron-updater": "^4.6.5",
"fast-deep-equal": "^3.1.3",
"fast-json-stable-stringify": "^2.1.0",
"fast-safe-stringify": "^2.1.1",
"filename-reserved-regex": "^2.0.0",
"fqbn": "^1.0.5",
"glob": "10.4.4",
"google-protobuf": "^3.20.1",
"hash.js": "^1.1.7",
"is-online": "^10.0.0",
"js-yaml": "^3.13.1",
"jsdom": "^21.1.1",
"jsonc-parser": "^2.2.0",
"just-diff": "^5.1.1",
"jwt-decode": "^3.1.2",
"keytar": "7.2.0",
"fuzzy": "^0.1.3",
"glob": "^7.1.6",
"google-protobuf": "^3.11.4",
"lodash.debounce": "^4.0.8",
"minimatch": "^3.1.2",
"node-fetch": "^2.6.1",
"node-log-rotate": "^0.1.5",
"open": "^8.0.6",
"p-debounce": "^2.1.0",
"p-queue": "^2.4.2",
"process": "^0.11.10",
"js-yaml": "^3.13.1",
"ncp": "^2.0.0",
"p-queue": "^5.0.0",
"ps-tree": "^1.2.0",
"query-string": "^7.0.1",
"react-disable": "^0.1.1",
"react-markdown": "^8.0.0",
"react-perfect-scrollbar": "^1.5.8",
"react-select": "^5.6.0",
"react-tabs": "^6.1.0",
"react-window": "^1.8.6",
"semver": "^7.3.2",
"react-select": "^3.0.4",
"semver": "^6.3.0",
"string-natural-compare": "^2.0.3",
"temp": "^0.9.1",
"temp-dir": "^2.0.0",
"tree-kill": "^1.2.1",
"util": "^0.12.5",
"vscode-arduino-api": "^0.1.2"
"upath": "^1.1.2",
"which": "^1.3.1"
},
"devDependencies": {
"@octokit/rest": "^18.12.0",
"@types/chai": "^4.2.7",
"@types/mocha": "^10.0.0",
"@types/react-window": "^1.8.5",
"@xhmikosr/downloader": "^13.0.1",
"@types/chai-string": "^1.4.2",
"@types/mocha": "^5.2.7",
"chai": "^4.2.0",
"cross-env": "^7.0.3",
"chai-string": "^1.5.0",
"decompress": "^4.2.0",
"decompress-tarbz2": "^4.1.1",
"decompress-targz": "^4.1.1",
"decompress-unzip": "^4.0.1",
"grpc_tools_node_protoc_ts": "^5.3.3",
"mocha": "^10.2.0",
"mockdate": "^3.0.5",
"download": "^7.1.0",
"grpc_tools_node_protoc_ts": "^4.1.0",
"mocha": "^7.0.0",
"moment": "^2.24.0",
"ncp": "^2.0.0",
"rimraf": "^5.0.0"
"protoc": "^1.0.4",
"shelljs": "^0.8.3",
"sinon": "^9.0.1",
"uuid": "^3.2.1",
"yargs": "^11.1.0"
},
"optionalDependencies": {
"@pingghost/protoc": "^1.0.2",
"grpc-tools": "^1.12.4"
"grpc-tools": "^1.9.0"
},
"mocha": {
"require": [
"reflect-metadata/Reflect",
"ignore-styles"
"reflect-metadata/Reflect"
],
"reporter": "spec",
"colors": true,
@ -146,46 +99,19 @@
"lib",
"src",
"build",
"data",
"examples"
"data"
],
"theiaExtensions": [
{
"preload": "lib/electron-browser/preload"
},
{
"backend": "lib/node/arduino-ide-backend-module",
"frontend": "lib/browser/arduino-ide-frontend-module"
},
{
"frontend": "lib/browser/theia/core/browser-menu-module",
"frontendElectron": "lib/electron-browser/theia/core/electron-menu-module"
},
{
"frontendElectron": "lib/electron-browser/theia/core/electron-window-module"
},
{
"frontendElectron": "lib/electron-browser/electron-arduino-module"
},
{
"electronMain": "lib/electron-main/arduino-electron-main-module"
"frontend": "lib/browser/boards/quick-open/boards-quick-open-module"
}
],
"arduino": {
"arduino-cli": {
"version": "1.2.0"
},
"arduino-fwuploader": {
"version": "2.4.1"
},
"arduino-language-server": {
"version": {
"owner": "arduino",
"repo": "arduino-language-server",
"commitish": "05ec308"
}
},
"clangd": {
"version": "14.0.0"
}
}
]
}

View File

@ -1,116 +0,0 @@
// @ts-check
(async () => {
const { Octokit } = require('@octokit/rest');
const fs = require('fs');
const path = require('path');
const octokit = new Octokit({
userAgent: 'Arduino IDE compose-changelog.js',
});
const response = await octokit.rest.repos
.listReleases({
owner: 'arduino',
repo: 'arduino-ide',
})
.catch((err) => {
console.error(err);
process.exit(1);
});
const releases = response.data;
let fullChangelog = releases.reduce((acc, item, index) => {
// Process each line separately
const body = item.body.split('\n').map(processLine).join('\n');
// item.name is the name of the release changelog
return (
acc +
`## ${item.name}\n\n${body}${
index !== releases.length - 1 ? '\n\n---\n\n' : '\n'
}`
);
}, '');
const args = process.argv.slice(2);
if (args.length === 0) {
console.error('Missing argument to destination file');
process.exit(1);
}
const changelogFile = path.resolve(args[0]);
await fs.writeFile(
changelogFile,
fullChangelog,
{
flag: 'w+',
},
(err) => {
if (err) {
console.error(err);
process.exit(1);
}
console.log('Changelog written to', changelogFile);
}
);
})();
// processLine applies different substitutions to line string.
// We're assuming that there are no more than one substitution
// per line to be applied.
const processLine = (line) => {
// Check if a link with one of the following format exists:
// * [#123](https://github.com/arduino/arduino-ide/pull/123)
// * [#123](https://github.com/arduino/arduino-ide/issues/123)
// * [#123](https://github.com/arduino/arduino-ide/pull/123/)
// * [#123](https://github.com/arduino/arduino-ide/issues/123/)
// If it does return the line as is.
let r =
/(\(|\[)#\d+(\)|\])(\(|\[)https:\/\/github\.com\/arduino\/arduino-ide\/(pull|issues)\/(\d+)\/?(\)|\])/gm;
if (r.test(line)) {
return line;
}
// Check if a issue or PR link with the following format exists:
// * #123
// If it does it's changed to:
// * [#123](https://github.com/arduino/arduino-ide/pull/123)
r = /(?<![\w\d\/_]{1})#((\d)+)(?![\w\d\/_]{1})/gm;
if (r.test(line)) {
return line.replace(
r,
`[#$1](https://github.com/arduino/arduino-ide/pull/$1)`
);
}
// Check if a link with one of the following format exists:
// * https://github.com/arduino/arduino-ide/pull/123
// * https://github.com/arduino/arduino-ide/issues/123
// * https://github.com/arduino/arduino-ide/pull/123/
// * https://github.com/arduino/arduino-ide/issues/123/
// If it does it's changed respectively to:
// * [#123](https://github.com/arduino/arduino-ide/pull/123)
// * [#123](https://github.com/arduino/arduino-ide/issues/123)
// * [#123](https://github.com/arduino/arduino-ide/pull/123/)
// * [#123](https://github.com/arduino/arduino-ide/issues/123/)
r =
/(https:\/\/github\.com\/arduino\/arduino-ide\/(pull|issues)\/(\d+)\/?)/gm;
if (r.test(line)) {
return line.replace(r, `[#$3]($1)`);
}
// Check if a link with the following format exists:
// * https://github.com/arduino/arduino-ide/compare/2.0.0-rc2...2.0.0-rc3
// * https://github.com/arduino/arduino-ide/compare/2.0.0-rc2...2.0.0-rc3/
// If it does it's changed to:
// * [`2.0.0-rc2...2.0.0-rc3`](https://github.com/arduino/arduino-ide/compare/2.0.0-rc2...2.0.0-rc3)
r =
/(https:\/\/github\.com\/arduino\/arduino-ide\/compare\/([^\/]*))\/?\s?/gm;
if (r.test(line)) {
return line.replace(r, '[`$2`]($1)');
}
// If nothing matches just return the line as is
return line;
};

View File

@ -1,95 +1,62 @@
// @ts-check
// The links to the downloads as of today (02.09.) are the followings:
// In order to get the latest nightly build for your platform use the following links replacing <DATE> with the current date, using the format YYYYMMDD (i.e for 2019/Aug/06 use 20190806 )
// Linux 64 bit: https://downloads.arduino.cc/arduino-cli/nightly/arduino-cli_nightly-<DATE>_Linux_64bit.tar.gz
// Linux ARM 64 bit: https://downloads.arduino.cc/arduino-cli/nightly/arduino-cli_nightly-<DATE>_Linux_ARM64.tar.gz
// Windows 64 bit: https://downloads.arduino.cc/arduino-cli/nightly/arduino-cli_nightly-<DATE>_Windows_64bit.zip
// Mac OSX: https://downloads.arduino.cc/arduino-cli/nightly/arduino-cli_nightly-<DATE>_macOS_64bit.tar.gz
// [...]
// redirecting to latest generated builds by replacing latest with the latest available build date, using the format YYYYMMDD (i.e for 2019/Aug/06 latest is replaced with 20190806
(async () => {
const path = require('path');
const semver = require('semver');
const moment = require('moment');
const downloader = require('./downloader');
const { taskBuildFromGit } = require('./utils');
(() => {
const version = (() => {
const pkg = require(path.join(__dirname, '..', 'package.json'));
if (!pkg) {
return undefined;
}
const DEFAULT_VERSION = '0.12.1'; // require('moment')().format('YYYYMMDD');
const { arduino } = pkg;
if (!arduino) {
return undefined;
}
const path = require('path');
const shell = require('shelljs');
const downloader = require('./downloader');
const cli = arduino['arduino-cli'];
if (!cli) {
return undefined;
}
const yargs = require('yargs')
.option('cli-version', {
alias: 'cv',
default: DEFAULT_VERSION,
describe: `The version of the 'arduino-cli' to download, or 'nightly-latest'. Defaults to ${DEFAULT_VERSION}.`
})
.option('force-download', {
alias: 'fd',
default: false,
describe: `If set, this script force downloads the 'arduino-cli' even if it already exists on the file system.`
})
.version(false).parse();
const { version } = cli;
return version;
})();
const version = yargs['cli-version'];
const force = yargs['force-download'];
const { platform, arch } = process;
if (!version) {
console.log(`Could not retrieve CLI version info from the 'package.json'.`);
process.exit(1);
}
const build = path.join(__dirname, '..', 'build');
const cli = path.join(build, `arduino-cli${platform === 'win32' ? '.exe' : ''}`);
const { platform, arch } = process;
const resourcesFolder = path.join(
__dirname,
'..',
'src',
'node',
'resources'
);
const cliName = `arduino-cli${platform === 'win32' ? '.exe' : ''}`;
const destinationPath = path.join(resourcesFolder, cliName);
if (typeof version === 'string') {
const suffix = (() => {
switch (platform) {
case 'darwin':
if (arch === 'arm64') {
return 'macOS_ARM64.tar.gz';
}
return 'macOS_64bit.tar.gz';
case 'win32':
return 'Windows_64bit.zip';
case 'linux': {
switch (arch) {
case 'arm':
return 'Linux_ARMv7.tar.gz';
case 'arm64':
return 'Linux_ARM64.tar.gz';
case 'x64':
return 'Linux_64bit.tar.gz';
default:
return undefined;
}
switch (platform) {
case 'darwin': return 'macOS_64bit.tar.gz';
case 'win32': return 'Windows_64bit.zip';
case 'linux': {
switch (arch) {
case 'arm': return 'Linux_ARMv7.tar.gz';
case 'arm64': return 'Linux_ARM64.tar.gz';
case 'x64': return 'Linux_64bit.tar.gz';
default: return undefined;
}
}
default: return undefined;
}
default:
return undefined;
}
})();
if (!suffix) {
console.log(`The CLI is not available for ${platform} ${arch}.`);
process.exit(1);
shell.echo(`The CLI is not available for ${platform} ${arch}.`);
shell.exit(1);
}
if (semver.valid(version)) {
const url = `https://downloads.arduino.cc/arduino-cli/arduino-cli_${version}_${suffix}`;
console.log(
`📦 Identified released version of the CLI. Downloading version ${version} from '${url}'`
);
await downloader.downloadUnzipFile(url, destinationPath, 'arduino-cli');
} else if (moment(version, 'YYYYMMDD', true).isValid()) {
const url = `https://downloads.arduino.cc/arduino-cli/nightly/arduino-cli_nightly-${version}_${suffix}`;
console.log(
`🌙 Identified nightly version of the CLI. Downloading version ${version} from '${url}'`
);
await downloader.downloadUnzipFile(url, destinationPath, 'arduino-cli');
} else {
console.log(`🔥 Could not interpret 'version': ${version}`);
process.exit(1);
}
} else {
taskBuildFromGit(version, destinationPath, 'CLI');
}
const url = `https://downloads.arduino.cc/arduino-cli${version.startsWith('nightly-') ? '/nightly' : ''}/arduino-cli_${version}_${suffix}`;
downloader.downloadUnzipFile(url, cli, 'arduino-cli', force);
})();

View File

@ -1,119 +0,0 @@
// @ts-check
// The version to use.
const version = '1.10.2';
(async () => {
const os = require('node:os');
const {
existsSync,
promises: fs,
mkdirSync,
readdirSync,
cpSync,
} = require('node:fs');
const path = require('node:path');
const { exec } = require('./utils');
const destination = path.join(
__dirname,
'..',
'src',
'node',
'resources',
'Examples'
);
if (existsSync(destination)) {
console.log(
`Skipping Git checkout of the examples because the repository already exists: ${destination}`
);
return;
}
const repository = await fs.mkdtemp(
path.join(os.tmpdir(), 'arduino-examples-')
);
exec(
'git',
['clone', 'https://github.com/arduino/arduino-examples.git', repository],
{ logStdout: true }
);
exec(
'git',
['-C', repository, 'checkout', `tags/${version}`, '-b', version],
{ logStdout: true }
);
mkdirSync(destination, { recursive: true });
const examplesPath = path.join(repository, 'examples');
const exampleResources = readdirSync(examplesPath);
for (const exampleResource of exampleResources) {
cpSync(
path.join(examplesPath, exampleResource),
path.join(destination, exampleResource),
{ recursive: true }
);
}
const isSketch = async (pathLike) => {
try {
const names = await fs.readdir(pathLike);
const dirName = path.basename(pathLike);
return names.indexOf(`${dirName}.ino`) !== -1;
} catch (e) {
if (e.code === 'ENOTDIR') {
return false;
}
throw e;
}
};
const examples = [];
const categories = await fs.readdir(destination);
const visit = async (pathLike, container) => {
const stat = await fs.lstat(pathLike);
if (stat.isDirectory()) {
if (await isSketch(pathLike)) {
container.sketches.push({
name: path.basename(pathLike),
relativePath: path.relative(destination, pathLike),
});
} else {
const names = await fs.readdir(pathLike);
for (const name of names) {
const childPath = path.join(pathLike, name);
if (await isSketch(childPath)) {
container.sketches.push({
name,
relativePath: path.relative(destination, childPath),
});
} else {
const child = {
label: name,
children: [],
sketches: [],
};
container.children.push(child);
await visit(childPath, child);
}
}
}
}
};
for (const category of categories) {
const example = {
label: category,
children: [],
sketches: [],
};
await visit(path.join(destination, category), example);
examples.push(example);
}
await fs.writeFile(
path.join(destination, 'examples.json'),
JSON.stringify(examples, null, 2),
{ encoding: 'utf8' }
);
console.log(`Generated output to ${path.join(destination, 'examples.json')}`);
})();

View File

@ -1,102 +0,0 @@
// @ts-check
(async () => {
const path = require('node:path');
const semver = require('semver');
const downloader = require('./downloader');
const { taskBuildFromGit } = require('./utils');
const version = (() => {
const pkg = require(path.join(__dirname, '..', 'package.json'));
if (!pkg) {
return undefined;
}
const { arduino } = pkg;
if (!arduino) {
return undefined;
}
const fwuploader = arduino['arduino-fwuploader'];
if (!fwuploader) {
return undefined;
}
const { version } = fwuploader;
return version;
})();
if (!version) {
console.log(
`Could not retrieve Firmware Uploader version info from the 'package.json'.`
);
process.exit(1);
}
const { platform, arch } = process;
const resourcesFolder = path.join(
__dirname,
'..',
'src',
'node',
'resources'
);
const fwuploderName = `arduino-fwuploader${
platform === 'win32' ? '.exe' : ''
}`;
const destinationPath = path.join(resourcesFolder, fwuploderName);
if (typeof version === 'string') {
const suffix = (() => {
switch (platform) {
case 'darwin':
switch (arch) {
case 'arm64':
return 'macOS_ARM64.tar.gz';
case 'x64':
return 'macOS_64bit.tar.gz';
default:
return undefined;
}
case 'win32':
return 'Windows_64bit.zip';
case 'linux': {
switch (arch) {
case 'arm':
return 'Linux_ARMv7.tar.gz';
case 'arm64':
return 'Linux_ARM64.tar.gz';
case 'x64':
return 'Linux_64bit.tar.gz';
default:
return undefined;
}
}
default:
return undefined;
}
})();
if (!suffix) {
console.log(
`The Firmware Uploader is not available for ${platform} ${arch}.`
);
process.exit(1);
}
if (semver.valid(version)) {
const url = `https://downloads.arduino.cc/arduino-fwuploader/arduino-fwuploader_${version}_${suffix}`;
console.log(
`📦 Identified released version of the Firmware Uploader. Downloading version ${version} from '${url}'`
);
await downloader.downloadUnzipFile(
url,
destinationPath,
'arduino-fwuploader'
);
} else {
console.log(`🔥 Could not interpret 'version': ${version}`);
process.exit(1);
}
} else {
taskBuildFromGit(version, destinationPath, 'Firmware Uploader');
}
})();

View File

@ -4,156 +4,69 @@
// - https://downloads.arduino.cc/arduino-language-server/clangd/clangd_${VERSION}_${SUFFIX}
(() => {
const path = require('path');
const downloader = require('./downloader');
const { goBuildFromGit } = require('./utils');
const [DEFAULT_LS_VERSION, DEFAULT_CLANGD_VERSION] = (() => {
const pkg = require(path.join(__dirname, '..', 'package.json'));
if (!pkg) return [undefined, undefined];
const DEFAULT_ALS_VERSION = 'nightly';
const DEFAULT_CLANGD_VERSION = '9.0.0';
const { arduino } = pkg;
if (!arduino) return [undefined, undefined];
const path = require('path');
const shell = require('shelljs');
const downloader = require('./downloader');
const { clangd } = arduino;
const languageServer = arduino['arduino-language-server'];
if (!languageServer) return [undefined, undefined];
if (!clangd) return [undefined, undefined];
const yargs = require('yargs')
.option('ls-version', {
alias: 'lv',
default: DEFAULT_ALS_VERSION,
choices: ['nightly'],
describe: `The version of the 'arduino-language-server' to download. Defaults to ${DEFAULT_ALS_VERSION}.`
})
.option('clangd-version', {
alias: 'cv',
default: DEFAULT_CLANGD_VERSION,
choices: ['8.0.1', '9.0.0'],
describe: `The version of 'clangd' to download. Defaults to ${DEFAULT_CLANGD_VERSION}.`
})
.option('force-download', {
alias: 'fd',
default: false,
describe: `If set, this script force downloads the 'arduino-language-server' even if it already exists on the file system.`
})
.version(false).parse();
return [languageServer.version, clangd.version];
})();
const alsVersion = yargs['ls-version'];
const clangdVersion = yargs['clangd-version']
const force = yargs['force-download'];
const { platform, arch } = process;
if (!DEFAULT_LS_VERSION) {
console.log(
`Could not retrieve Arduino Language Server version info from the 'package.json'.`
);
process.exit(1);
}
const build = path.join(__dirname, '..', 'build');
const alsTarget = path.join(build, `arduino-language-server${platform === 'win32' ? '.exe' : ''}`);
if (!DEFAULT_CLANGD_VERSION) {
console.log(
`Could not retrieve clangd version info from the 'package.json'.`
);
process.exit(1);
}
const yargs = require('@theia/core/shared/yargs')
.option('ls-version', {
alias: 'lv',
default: DEFAULT_LS_VERSION,
describe: `The version of the 'arduino-language-server' to download. Defaults to ${DEFAULT_LS_VERSION}.`,
})
.option('clangd-version', {
alias: 'cv',
default: DEFAULT_CLANGD_VERSION,
choices: [DEFAULT_CLANGD_VERSION, 'snapshot_20210124'],
describe: `The version of 'clangd' to download. Defaults to ${DEFAULT_CLANGD_VERSION}.`,
})
.option('force-download', {
alias: 'fd',
default: false,
describe: `If set, this script force downloads the 'arduino-language-server' even if it already exists on the file system.`,
})
.version(false)
.parse();
const lsVersion = yargs['ls-version'];
const clangdVersion = yargs['clangd-version'];
const force = yargs['force-download'];
const { platform, arch } = process;
const platformArch = platform + '-' + arch;
const resourcesFolder = path.join(
__dirname,
'..',
'src',
'node',
'resources'
);
const lsExecutablePath = path.join(
resourcesFolder,
`arduino-language-server${platform === 'win32' ? '.exe' : ''}`
);
let clangdExecutablePath, clangFormatExecutablePath, lsSuffix, clangdSuffix;
switch (platformArch) {
case 'darwin-x64':
clangdExecutablePath = path.join(resourcesFolder, 'clangd');
clangFormatExecutablePath = path.join(resourcesFolder, 'clang-format');
lsSuffix = 'macOS_64bit.tar.gz';
clangdSuffix = 'macOS_64bit';
break;
case 'darwin-arm64':
clangdExecutablePath = path.join(resourcesFolder, 'clangd');
clangFormatExecutablePath = path.join(resourcesFolder, 'clang-format');
lsSuffix = 'macOS_ARM64.tar.gz';
clangdSuffix = 'macOS_ARM64';
break;
case 'linux-x64':
clangdExecutablePath = path.join(resourcesFolder, 'clangd');
clangFormatExecutablePath = path.join(resourcesFolder, 'clang-format');
lsSuffix = 'Linux_64bit.tar.gz';
clangdSuffix = 'Linux_64bit';
break;
case 'linux-arm64':
clangdExecutablePath = path.join(resourcesFolder, 'clangd');
clangFormatExecutablePath = path.join(resourcesFolder, 'clang-format');
lsSuffix = 'Linux_ARM64.tar.gz';
clangdSuffix = 'Linux_ARM64';
break;
case 'win32-x64':
clangdExecutablePath = path.join(resourcesFolder, 'clangd.exe');
clangFormatExecutablePath = path.join(
resourcesFolder,
'clang-format.exe'
);
lsSuffix = 'Windows_64bit.zip';
clangdSuffix = 'Windows_64bit';
break;
default:
throw new Error(`Unsupported platform/arch: ${platformArch}.`);
}
if (!lsSuffix || !clangdSuffix) {
console.log(
`The arduino-language-server is not available for ${platform} ${arch}.`
);
process.exit(1);
}
if (typeof lsVersion === 'string') {
const lsUrl = `https://downloads.arduino.cc/arduino-language-server/${
lsVersion === 'nightly'
? 'nightly/arduino-language-server'
: 'arduino-language-server_' + lsVersion
}_${lsSuffix}`;
downloader.downloadUnzipAll(
lsUrl,
resourcesFolder,
lsExecutablePath,
force
);
} else {
goBuildFromGit(lsVersion, lsExecutablePath, 'language-server');
}
const clangdUrl = `https://downloads.arduino.cc/tools/clangd_${clangdVersion}_${clangdSuffix}.tar.bz2`;
downloader.downloadUnzipAll(
clangdUrl,
resourcesFolder,
clangdExecutablePath,
force,
{
strip: 1,
let clangdTarget, alsSuffix, clangdSuffix;
switch (platform) {
case 'darwin':
clangdTarget = path.join(build, 'bin', 'clangd')
alsSuffix = 'Darwin_amd64.zip';
clangdSuffix = 'macos.zip';
break;
case 'linux':
clangdTarget = path.join(build, 'bin', 'clangd')
alsSuffix = 'Linux_amd64.zip';
clangdSuffix = 'linux.zip'
break;
case 'win32':
clangdTarget = path.join(build, 'clangd.exe')
alsSuffix = 'Windows_NT_amd64.zip';
clangdSuffix = 'windows.zip';
break;
}
); // `strip`: the new clangd (12.x) is zipped into a folder, so we have to strip the outmost folder.
const clangdFormatUrl = `https://downloads.arduino.cc/tools/clang-format_${clangdVersion}_${clangdSuffix}.tar.bz2`;
downloader.downloadUnzipAll(
clangdFormatUrl,
resourcesFolder,
clangFormatExecutablePath,
force,
{
strip: 1,
if (!alsSuffix) {
shell.echo(`The arduino-language-server is not available for ${platform} ${arch}.`);
shell.exit(1);
}
);
const alsUrl = `https://downloads.arduino.cc/arduino-language-server/${alsVersion === 'nightly' ? 'nightly/arduino-language-server' : 'arduino-language-server_' + alsVersion}_${alsSuffix}`;
downloader.downloadUnzipAll(alsUrl, build, alsTarget, force);
const clangdUrl = `https://downloads.arduino.cc/arduino-language-server/clangd/clangd_${clangdVersion}_${clangdSuffix}`;
downloader.downloadUnzipAll(clangdUrl, build, clangdTarget, force);
})();

View File

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

View File

@ -1,289 +1,81 @@
// @ts-check
(async () => {
const os = require('node:os');
const path = require('node:path');
const decompress = require('decompress');
const unzip = require('decompress-unzip');
const { mkdirSync, promises: fs, rmSync, existsSync } = require('node:fs');
const { exec } = require('./utils');
const { glob } = require('glob');
const { SemVer, gte, valid: validSemVer, eq } = require('semver');
// Use a node-protoc fork until apple arm32 is supported
// https://github.com/YePpHa/node-protoc/pull/10
const protoc = path.dirname(require('@pingghost/protoc/protoc'));
const { owner, repo, commitish } = (() => {
const pkg = require(path.join(__dirname, '..', 'package.json'));
if (!pkg) {
console.log(`Could not parse the 'package.json'.`);
process.exit(1);
const os = require('os');
const path = require('path');
const glob = require('glob');
const { v4 } = require('uuid');
const shell = require('shelljs');
const protoc = path.dirname(require('protoc/protoc'));
shell.env.PATH = `${shell.env.PATH}${path.delimiter}${protoc}`;
shell.env.PATH = `${shell.env.PATH}${path.delimiter}${path.join(__dirname, '..', 'node_modules', '.bin')}`;
const repository = path.join(os.tmpdir(), `${v4()}-arduino-cli`);
if (shell.mkdir('-p', repository).code !== 0) {
shell.exit(1);
}
const defaultVersion = {
owner: 'arduino',
repo: 'arduino-cli',
commitish: undefined,
};
const { arduino } = pkg;
if (!arduino) {
return defaultVersion;
if (shell.exec(`git clone https://github.com/arduino/arduino-cli.git ${repository}`).code !== 0) {
shell.exit(1);
}
const cli = arduino['arduino-cli'];
if (!cli) {
return defaultVersion;
const { platform } = process;
const build = path.join(__dirname, '..', 'build');
const cli = path.join(build, `arduino-cli${platform === 'win32' ? '.exe' : ''}`);
const rawVersion = shell.exec(`${cli} version`).trim();
if (!rawVersion) {
shell.echo(`Could not retrieve the CLI version from ${cli}.`);
shell.exit(1);
}
const version = rawVersion.substring(rawVersion.lastIndexOf('Commit:') + 'Commit:'.length).trim();
if (version) {
if (shell.exec(`git -C ${repository} checkout ${version} -b ${version}`).code !== 0) {
shell.exit(1);
}
}
const { version } = cli;
if (!version) {
return defaultVersion;
shell.echo('>>> Generating TS/JS API from:');
if (shell.exec(`git -C ${repository} rev-parse --abbrev-ref HEAD`).code !== 0) {
shell.exit(1);
}
if (typeof version === 'string') {
return defaultVersion;
const rpc = path.join(repository, 'rpc');
const out = path.join(__dirname, '..', 'src', 'node', 'cli-protocol');
shell.mkdir('-p', out);
const protos = await new Promise(resolve =>
glob('**/*.proto', { cwd: rpc }, (error, matches) => {
if (error) {
shell.echo(error.stack);
resolve([]);
return;
}
resolve(matches.map(filename => path.join(rpc, filename)));
}));
if (!protos || protos.length === 0) {
shell.echo(`Could not find any .proto files under ${rpc}.`);
shell.exit(1);
}
// We assume an object with `owner`, `repo`, commitish?` properties.
const { owner, repo, commitish } = version;
if (!owner) {
console.log(`Could not retrieve 'owner' from ${JSON.stringify(version)}`);
process.exit(1);
}
if (!repo) {
console.log(`Could not retrieve 'repo' from ${JSON.stringify(version)}`);
process.exit(1);
}
return { owner, repo, commitish };
})();
const { platform } = process;
const resourcesFolder = path.join(
__dirname,
'..',
'src',
'node',
'resources'
);
const cli = path.join(
resourcesFolder,
`arduino-cli${platform === 'win32' ? '.exe' : ''}`
);
const versionJson = exec(cli, ['version', '--format', 'json'], {
logStdout: true,
}).trim();
if (!versionJson) {
console.log(`Could not retrieve the CLI version from ${cli}.`);
process.exit(1);
}
// As of today (28.01.2021), the `VersionString` can be one of the followings:
// - `nightly-YYYYMMDD` stands for the nightly build, we use the , the `commitish` from the `package.json` to check out the code.
// - `0.0.0-git` for local builds, we use the `commitish` from the `package.json` to check out the code and generate the APIs.
// - `git-snapshot` for local build executed via `task build`. We do not do this.
// - rest, we assume it is a valid semver and has the corresponding tagged code, we use the tag to generate the APIs from the `proto` files.
/*
{
"Application": "arduino-cli",
"VersionString": "nightly-20210126",
"Commit": "079bb6c6",
"Status": "alpha",
"Date": "2021-01-26T01:46:31Z"
}
*/
const versionObject = JSON.parse(versionJson);
async function globProtos(folder, pattern = '**/*.proto') {
let protos = [];
try {
const matches = await glob(pattern, { cwd: folder });
protos = matches.map((filename) => path.join(folder, filename));
} catch (error) {
console.log(error.stack ?? error.message);
}
return protos;
}
async function getProtosFromRepo(
commitish = '',
version = '',
owner = 'arduino',
repo = 'arduino-cli'
) {
const repoFolder = await fs.mkdtemp(path.join(os.tmpdir(), 'arduino-cli-'));
const url = `https://github.com/${owner}/${repo}.git`;
console.log(`>>> Cloning repository from '${url}'...`);
exec('git', ['clone', url, repoFolder], { logStdout: true });
console.log(`<<< Repository cloned.`);
if (validSemVer(version)) {
let versionTag = version;
// https://github.com/arduino/arduino-cli/pull/2374
if (
gte(new SemVer(version, { loose: true }), new SemVer('0.35.0-rc.1'))
) {
versionTag = `v${version}`;
}
console.log(`>>> Checking out tagged version: '${versionTag}'...`);
exec('git', ['-C', repoFolder, 'fetch', '--all', '--tags'], {
logStdout: true,
});
exec(
'git',
['-C', repoFolder, 'checkout', `tags/${versionTag}`, '-b', versionTag],
{ logStdout: true }
);
console.log(`<<< Checked out tagged version: '${versionTag}'.`);
} else if (commitish) {
console.log(`>>> Checking out commitish: '${commitish}'...`);
exec('git', ['-C', repoFolder, 'checkout', commitish], {
logStdout: true,
});
console.log(`<<< Checked out commitish: '${commitish}'.`);
} else {
console.log(
`WARN: no 'git checkout'. Generating from the HEAD revision.`
);
}
const rpcFolder = await fs.mkdtemp(
path.join(os.tmpdir(), 'arduino-cli-rpc')
);
// Copy the the repository rpc folder so we can remove the repository
await fs.cp(path.join(repoFolder, 'rpc'), path.join(rpcFolder), {
recursive: true,
});
rmSync(repoFolder, { recursive: true, maxRetries: 5, force: true });
// Patch for https://github.com/arduino/arduino-cli/issues/2755
// Google proto files are removed from source since v1.1.0
if (!existsSync(path.join(rpcFolder, 'google'))) {
// Include packaged google proto files from v1.1.1
// See https://github.com/arduino/arduino-cli/pull/2761
console.log(`>>> Missing google proto files. Including from v1.1.1...`);
const v111ProtoFolder = await getProtosFromZip('1.1.1');
// Create an return a folder name google in rpcFolder
const googleFolder = path.join(rpcFolder, 'google');
await fs.cp(path.join(v111ProtoFolder, 'google'), googleFolder, {
recursive: true,
});
console.log(`<<< Included google proto files from v1.1.1.`);
}
return rpcFolder;
}
async function getProtosFromZip(version) {
if (!version) {
console.log(`Could not download proto files: CLI version not provided.`);
process.exit(1);
}
console.log(`>>> Downloading proto files from zip for ${version}.`);
const url = `https://downloads.arduino.cc/arduino-cli/arduino-cli_${version}_proto.zip`;
const protos = await fs.mkdtemp(
path.join(os.tmpdir(), 'arduino-cli-proto')
);
const { default: download } = await import('@xhmikosr/downloader');
/** @type {import('node:buffer').Buffer} */
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const data = await download(url);
await decompress(data, protos, {
plugins: [unzip()],
filter: (file) => file.path.endsWith('.proto'),
});
console.log(
`<<< Finished downloading and extracting proto files for ${version}.`
);
return protos;
}
let protosFolder;
if (commitish) {
protosFolder = await getProtosFromRepo(commitish, undefined, owner, repo);
} else if (
versionObject.VersionString &&
validSemVer(versionObject.VersionString)
) {
const version = versionObject.VersionString;
// v1.1.0 does not contains google proto files in zip
// See https://github.com/arduino/arduino-cli/issues/2755
const isV110 = eq(new SemVer(version, { loose: true }), '1.1.0');
protosFolder = isV110
? await getProtosFromRepo(undefined, version)
: await getProtosFromZip(version);
} else if (versionObject.Commit) {
protosFolder = await getProtosFromRepo(versionObject.Commit);
}
if (!protosFolder) {
console.log(`Could not get proto files: missing commitish or version.`);
process.exit(1);
}
const protos = await globProtos(protosFolder);
if (!protos || protos.length === 0) {
rmSync(protosFolder, { recursive: true, maxRetries: 5, force: true });
console.log(`Could not find any .proto files under ${protosFolder}.`);
process.exit(1);
}
console.log('>>> Generating TS/JS API from:');
const out = path.join(__dirname, '..', 'src', 'node', 'cli-protocol');
// Must wipe the gen output folder. Otherwise, dangling service implementation remain in IDE2 code,
// although it has been removed from the proto file.
// For example, https://github.com/arduino/arduino-cli/commit/50a8bf5c3e61d5b661ccfcd6a055e82eeb510859.
// rmSync(out, { recursive: true, maxRetries: 5, force: true });
mkdirSync(out, { recursive: true });
try {
// Generate JS code from the `.proto` files.
exec(
'grpc_tools_node_protoc',
[
`--js_out=import_style=commonjs,binary:${out}`,
`--grpc_out=generate_package_definition:${out}`,
'-I',
protosFolder,
...protos,
],
{ logStdout: true }
);
if (shell.exec(`grpc_tools_node_protoc \
--js_out=import_style=commonjs,binary:${out} \
--grpc_out=generate_package_definition:${out} \
-I ${rpc} \
${protos.join(' ')}`).code !== 0) {
shell.exit(1);
}
// Generate the `.d.ts` files for JS.
exec(
path.join(protoc, `protoc${platform === 'win32' ? '.exe' : ''}`),
[
`--plugin=protoc-gen-ts=${path.resolve(
__dirname,
'..',
'node_modules',
'.bin',
`protoc-gen-ts${platform === 'win32' ? '.cmd' : ''}`
)}`,
`--ts_out=generate_package_definition:${out}`,
'-I',
protosFolder,
...protos,
],
{ logStdout: true }
);
} catch (error) {
console.log(error);
} finally {
rmSync(protosFolder, { recursive: true, maxRetries: 5, force: true });
}
if (shell.exec(`protoc \
--plugin=protoc-gen-ts=${path.resolve(__dirname, '..', 'node_modules', '.bin', `protoc-gen-ts${platform === 'win32' ? '.cmd' : ''}`)} \
--ts_out=generate_package_definition:${out} \
-I ${rpc} \
${protos.join(' ')}`).code !== 0) {
shell.exit(1);
}
shell.echo('<<< Generation was successful.');
console.log('<<< Generation was successful.');
})();

View File

@ -1,143 +0,0 @@
// @ts-check
const exec = (
/** @type {string} */ command,
/** @type {readonly string[]} */ args,
/** @type {Partial<import('node:child_process').ExecFileSyncOptionsWithStringEncoding> & { logStdout?: boolean }|undefined} */ options = undefined
) => {
try {
const stdout = require('node:child_process').execFileSync(command, args, {
encoding: 'utf8',
...(options ?? {}),
});
if (options?.logStdout) {
console.log(stdout.trim());
}
return stdout;
} catch (err) {
console.log(
`Failed to execute ${command} with args: ${JSON.stringify(args)}`
);
throw err;
}
};
exports.exec = exec;
/**
* Clones something from GitHub and builds it with [`Task`](https://taskfile.dev/).
*
* @param version {object} the version object.
* @param destinationPath {string} the absolute path of the output binary. For example, `C:\\folder\\arduino-cli.exe` or `/path/to/arduino-language-server`
* @param taskName {string} for the CLI logging . Can be `'CLI'` or `'language-server'`, etc.
*/
exports.taskBuildFromGit = (version, destinationPath, taskName) => {
return buildFromGit('task', version, destinationPath, taskName);
};
/**
* Clones something from GitHub and builds it with `Golang`.
*
* @param version {object} the version object.
* @param destinationPath {string} the absolute path of the output binary. For example, `C:\\folder\\arduino-cli.exe` or `/path/to/arduino-language-server`
* @param taskName {string} for the CLI logging . Can be `'CLI'` or `'language-server'`, etc.
*/
exports.goBuildFromGit = (version, destinationPath, taskName) => {
return buildFromGit('go', version, destinationPath, taskName);
};
/**
* The `command` must be either `'go'` or `'task'`.
* @param {string} command
* @param {{ owner: any; repo: any; commitish: any; }} version
* @param {string} destinationPath
* @param {string} taskName
*/
function buildFromGit(command, version, destinationPath, taskName) {
const fs = require('node:fs');
const path = require('node:path');
const temp = require('temp');
// We assume an object with `owner`, `repo`, commitish?` properties.
if (typeof version !== 'object') {
console.log(
`Expected a \`{ owner, repo, commitish }\` object. Got <${version}> instead.`
);
}
const { owner, repo, commitish } = version;
if (!owner) {
console.log(`Could not retrieve 'owner' from ${JSON.stringify(version)}`);
process.exit(1);
}
if (!repo) {
console.log(`Could not retrieve 'repo' from ${JSON.stringify(version)}`);
process.exit(1);
}
const url = `https://github.com/${owner}/${repo}.git`;
console.log(
`Building ${taskName} from ${url}. Commitish: ${
commitish ? commitish : 'HEAD'
}`
);
if (fs.existsSync(destinationPath)) {
console.log(
`Skipping the ${taskName} build because it already exists: ${destinationPath}`
);
return;
}
const resourcesFolder = path.join(
__dirname,
'..',
'src',
'node',
'resources'
);
fs.mkdirSync(resourcesFolder, { recursive: true });
const tempRepoPath = temp.mkdirSync();
console.log(`>>> Cloning ${taskName} source to ${tempRepoPath}...`);
exec('git', ['clone', url, tempRepoPath], { logStdout: true });
console.log(`<<< Cloned ${taskName} repo.`);
if (commitish) {
console.log(`>>> Checking out ${commitish}...`);
exec('git', ['-C', tempRepoPath, 'checkout', commitish], {
logStdout: true,
});
console.log(`<<< Checked out ${commitish}.`);
}
exec('git', ['-C', tempRepoPath, 'rev-parse', '--short', 'HEAD'], {
logStdout: true,
});
console.log(`>>> Building the ${taskName}...`);
exec(command, ['build'], {
cwd: tempRepoPath,
encoding: 'utf8',
logStdout: true,
});
console.log(`<<< Done ${taskName} build.`);
const binName = path.basename(destinationPath);
if (!fs.existsSync(path.join(tempRepoPath, binName))) {
console.log(
`Could not find the ${taskName} at ${path.join(tempRepoPath, binName)}.`
);
process.exit(1);
}
const binPath = path.join(tempRepoPath, binName);
console.log(
`>>> Copying ${taskName} from ${binPath} to ${destinationPath}...`
);
fs.copyFileSync(binPath, destinationPath);
console.log(`<<< Copied the ${taskName}.`);
console.log(`<<< Verifying ${taskName}...`);
if (!fs.existsSync(destinationPath)) {
process.exit(1);
}
console.log(`>>> Verified ${taskName}.`);
}

View File

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

View File

@ -0,0 +1,30 @@
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'
};
/**
* Unlike `OPEN_SKETCH`, it opens all files from a sketch folder. (ino, cpp, etc...)
*/
export const OPEN_SKETCH_FILES: Command = {
id: 'arduino-open-sketch-files'
};
export const OPEN_BOARDS_DIALOG: Command = {
id: 'arduino-open-boards-dialog'
};
export const TOGGLE_ADVANCED_MODE: Command = {
id: 'arduino-toggle-advanced-mode'
};
export const TOGGLE_ADVANCED_MODE_TOOLBAR: Command = {
id: 'arduino-toggle-advanced-mode-toolbar'
};
}

View File

@ -0,0 +1,53 @@
import { injectable, inject } from 'inversify';
import { ILogger } from '@theia/core/lib/common/logger';
import { Event, Emitter } from '@theia/core/lib/common/event';
import { MessageService } from '@theia/core/lib/common/message-service';
import { ArduinoDaemonClient } from '../common/protocol';
@injectable()
export class ArduinoDaemonClientImpl implements ArduinoDaemonClient {
@inject(ILogger)
protected readonly logger: ILogger;
@inject(MessageService)
protected readonly messageService: MessageService;
protected readonly onStartedEmitter = new Emitter<void>();
protected readonly onStoppedEmitter = new Emitter<void>();
protected _isRunning = false;
notifyStopped(): void {
if (this._isRunning) {
this._isRunning = false;
this.onStoppedEmitter.fire();
this.info('The CLI daemon process has stopped.');
}
}
notifyStarted(): void {
if (!this._isRunning) {
this._isRunning = true;
this.onStartedEmitter.fire();
this.info('The CLI daemon process has started.');
}
}
get onDaemonStarted(): Event<void> {
return this.onStartedEmitter.event;
}
get onDaemonStopped(): Event<void> {
return this.onStoppedEmitter.event;
}
get isRunning(): boolean {
return this._isRunning;
}
protected info(message: string): void {
this.messageService.info(message, { timeout: 3000 });
this.logger.info(message);
}
}

View File

@ -1,479 +1,347 @@
import { MAIN_MENU_BAR, MenuContribution, MenuModelRegistry, SelectionService } from '@theia/core';
import {
ContextMenuRenderer,
FrontendApplication, FrontendApplicationContribution,
OpenerService, StatusBar, StatusBarAlignment
} from '@theia/core/lib/browser';
import { ColorContribution } from '@theia/core/lib/browser/color-application-contribution';
import { ColorRegistry } from '@theia/core/lib/browser/color-registry';
import { CommonMenus } from '@theia/core/lib/browser/common-frontend-contribution';
import { FrontendApplicationContribution } from '@theia/core/lib/browser/frontend-application-contribution';
import { FrontendApplicationStateService } from '@theia/core/lib/browser/frontend-application-state';
import {
TabBarToolbarContribution,
TabBarToolbarRegistry,
} from '@theia/core/lib/browser/shell/tab-bar-toolbar';
import {
ColorTheme,
CssStyleCollector,
StylingParticipant,
} from '@theia/core/lib/browser/styling-service';
import {
CommandContribution,
CommandRegistry,
} from '@theia/core/lib/common/command';
import {
MAIN_MENU_BAR,
MenuContribution,
MenuModelRegistry,
} from '@theia/core/lib/common/menu';
import { TabBarToolbarContribution, TabBarToolbarRegistry } from '@theia/core/lib/browser/shell/tab-bar-toolbar';
import { CommandContribution, CommandRegistry } from '@theia/core/lib/common/command';
import { MessageService } from '@theia/core/lib/common/message-service';
import { nls } from '@theia/core/lib/common/nls';
import { isHighContrast } from '@theia/core/lib/common/theme';
import { ElectronWindowPreferences } from '@theia/core/lib/electron-browser/window/electron-window-preferences';
import {
inject,
injectable,
postConstruct,
} from '@theia/core/shared/inversify';
import React from '@theia/core/shared/react';
import { EditorCommands } from '@theia/editor/lib/browser/editor-command';
import { EditorMainMenu } from '@theia/editor/lib/browser/editor-menu';
import URI from '@theia/core/lib/common/uri';
import { EditorMainMenu, EditorManager } from '@theia/editor/lib/browser';
import { FileDialogService } from '@theia/filesystem/lib/browser/file-dialog';
import { FileSystem } from '@theia/filesystem/lib/common';
import { ProblemContribution } from '@theia/markers/lib/browser/problem/problem-contribution';
import { MonacoMenus } from '@theia/monaco/lib/browser/monaco-menu';
import { FileNavigatorCommands } from '@theia/navigator/lib/browser/navigator-contribution';
import { FileNavigatorContribution } from '@theia/navigator/lib/browser/navigator-contribution';
import { OutlineViewContribution } from '@theia/outline-view/lib/browser/outline-view-contribution';
import { OutputContribution } from '@theia/output/lib/browser/output-contribution';
import { ScmContribution } from '@theia/scm/lib/browser/scm-contribution';
import { SearchInWorkspaceFrontendContribution } from '@theia/search-in-workspace/lib/browser/search-in-workspace-frontend-contribution';
import { TerminalMenus } from '@theia/terminal/lib/browser/terminal-frontend-contribution';
import { BoardsServiceProvider } from './boards/boards-service-provider';
import { inject, injectable, postConstruct } from 'inversify';
import * as React from 'react';
import { MainMenuManager } from '../common/main-menu-manager';
import { BoardsService, BoardsServiceClient, CoreService, Port, SketchesService, ToolOutputServiceClient } from '../common/protocol';
import { ArduinoDaemon } from '../common/protocol/arduino-daemon';
import { ConfigService } from '../common/protocol/config-service';
import { FileSystemExt } from '../common/protocol/filesystem-ext';
import { ArduinoCommands } from './arduino-commands';
import { BoardsConfig } from './boards/boards-config';
import { BoardsConfigDialog } from './boards/boards-config-dialog';
import { BoardsDataStore } from './boards/boards-data-store';
import { BoardsServiceClientImpl } from './boards/boards-service-client-impl';
import { BoardsToolBarItem } from './boards/boards-toolbar-item';
import { EditorMode } from './editor-mode';
import { ArduinoMenus } from './menu/arduino-menus';
import { MonitorViewContribution } from './serial/monitor/monitor-view-contribution';
import { SerialPlotterContribution } from './serial/plotter/plotter-frontend-contribution';
import { MonitorConnection } from './monitor/monitor-connection';
import { MonitorViewContribution } from './monitor/monitor-view-contribution';
import { WorkspaceService } from './theia/workspace/workspace-service';
import { ArduinoToolbar } from './toolbar/arduino-toolbar';
@injectable()
export class ArduinoFrontendContribution
implements
FrontendApplicationContribution,
TabBarToolbarContribution,
CommandContribution,
MenuContribution,
ColorContribution,
StylingParticipant
{
@inject(MessageService)
private readonly messageService: MessageService;
export class ArduinoFrontendContribution implements FrontendApplicationContribution,
TabBarToolbarContribution, CommandContribution, MenuContribution, ColorContribution {
@inject(BoardsServiceProvider)
private readonly boardsServiceProvider: BoardsServiceProvider;
@inject(MessageService)
protected readonly messageService: MessageService;
@inject(CommandRegistry)
private readonly commandRegistry: CommandRegistry;
@inject(BoardsService)
protected readonly boardsService: BoardsService;
@inject(ElectronWindowPreferences)
private readonly electronWindowPreferences: ElectronWindowPreferences;
@inject(CoreService)
protected readonly coreService: CoreService;
@inject(FrontendApplicationStateService)
private readonly appStateService: FrontendApplicationStateService;
@inject(ToolOutputServiceClient)
protected readonly toolOutputServiceClient: ToolOutputServiceClient;
@postConstruct()
protected init(): void {
if (!window.navigator.onLine) {
// tslint:disable-next-line:max-line-length
this.messageService.warn(
nls.localize(
'arduino/common/offlineIndicator',
'You appear to be offline. Without an Internet connection, the Arduino CLI might not be able to download the required resources and could cause malfunction. Please connect to the Internet and restart the application.'
)
);
@inject(BoardsServiceClientImpl)
protected readonly boardsServiceClientImpl: BoardsServiceClientImpl;
// Unused but do not remove it. It's required by DI, otherwise `init` method is not called.
@inject(BoardsServiceClient)
protected readonly boardsServiceClient: BoardsServiceClient;
@inject(SelectionService)
protected readonly selectionService: SelectionService;
@inject(EditorManager)
protected readonly editorManager: EditorManager;
@inject(ContextMenuRenderer)
protected readonly contextMenuRenderer: ContextMenuRenderer;
@inject(FileDialogService)
protected readonly fileDialogService: FileDialogService;
@inject(FileSystem)
protected readonly fileSystem: FileSystem;
@inject(SketchesService)
protected readonly sketchService: SketchesService;
@inject(BoardsConfigDialog)
protected readonly boardsConfigDialog: BoardsConfigDialog;
@inject(MenuModelRegistry)
protected readonly menuRegistry: MenuModelRegistry;
@inject(CommandRegistry)
protected readonly commandRegistry: CommandRegistry;
@inject(StatusBar)
protected readonly statusBar: StatusBar;
@inject(WorkspaceService)
protected readonly workspaceService: WorkspaceService;
@inject(MonitorConnection)
protected readonly monitorConnection: MonitorConnection;
@inject(FileNavigatorContribution)
protected readonly fileNavigatorContributions: FileNavigatorContribution;
@inject(OutputContribution)
protected readonly outputContribution: OutputContribution;
@inject(OutlineViewContribution)
protected readonly outlineContribution: OutlineViewContribution;
@inject(ProblemContribution)
protected readonly problemContribution: ProblemContribution;
@inject(ScmContribution)
protected readonly scmContribution: ScmContribution;
@inject(SearchInWorkspaceFrontendContribution)
protected readonly siwContribution: SearchInWorkspaceFrontendContribution;
@inject(EditorMode)
protected readonly editorMode: EditorMode;
@inject(ArduinoDaemon)
protected readonly daemon: ArduinoDaemon;
@inject(OpenerService)
protected readonly openerService: OpenerService;
@inject(ConfigService)
protected readonly configService: ConfigService;
@inject(BoardsDataStore)
protected readonly boardsDataStore: BoardsDataStore;
@inject(MainMenuManager)
protected readonly mainMenuManager: MainMenuManager;
@inject(FileSystemExt)
protected readonly fileSystemExt: FileSystemExt;
@postConstruct()
protected async init(): Promise<void> {
if (!window.navigator.onLine) {
// tslint:disable-next-line:max-line-length
this.messageService.warn('You appear to be offline. Without an Internet connection, the Arduino CLI might not be able to download the required resources and could cause malfunction. Please connect to the Internet and restart the application.');
}
const updateStatusBar = ({ selectedBoard, selectedPort }: BoardsConfig.Config) => {
this.statusBar.setElement('arduino-selected-board', {
alignment: StatusBarAlignment.RIGHT,
text: selectedBoard ? `$(microchip) ${selectedBoard.name}` : '$(close) no board selected',
className: 'arduino-selected-board'
});
if (selectedBoard) {
this.statusBar.setElement('arduino-selected-port', {
alignment: StatusBarAlignment.RIGHT,
text: selectedPort ? `on ${Port.toString(selectedPort)}` : '[not connected]',
className: 'arduino-selected-port'
});
}
}
this.boardsServiceClientImpl.onBoardsConfigChanged(updateStatusBar);
updateStatusBar(this.boardsServiceClientImpl.boardsConfig);
}
}
onStart(): void {
this.electronWindowPreferences.onPreferenceChanged((event) => {
if (event.newValue !== event.oldValue) {
switch (event.preferenceName) {
case 'window.zoomLevel':
if (typeof event.newValue === 'number') {
window.electronTheiaCore.setZoomLevel(event.newValue || 0);
onStart(app: FrontendApplication): void {
// Initialize all `pro-mode` widgets. This is a NOOP if in normal mode.
for (const viewContribution of [
this.fileNavigatorContributions,
this.outputContribution,
this.outlineContribution,
this.problemContribution,
this.scmContribution,
this.siwContribution] as Array<FrontendApplicationContribution>) {
if (viewContribution.initializeLayout) {
viewContribution.initializeLayout(app);
}
break;
}
}
});
this.appStateService.reachedState('ready').then(() =>
this.electronWindowPreferences.ready.then(() => {
const zoomLevel =
this.electronWindowPreferences.get('window.zoomLevel');
window.electronTheiaCore.setZoomLevel(zoomLevel);
})
);
}
registerToolbarItems(registry: TabBarToolbarRegistry): void {
registry.registerItem({
id: BoardsToolBarItem.TOOLBAR_ID,
render: () => (
<BoardsToolBarItem
key="boardsToolbarItem"
commands={this.commandRegistry}
boardsServiceProvider={this.boardsServiceProvider}
/>
),
isVisible: (widget) =>
ArduinoToolbar.is(widget) && widget.side === 'left',
priority: 7,
});
registry.registerItem({
id: 'toggle-serial-plotter',
command: SerialPlotterContribution.Commands.OPEN_TOOLBAR.id,
tooltip: nls.localize(
'arduino/serial/openSerialPlotter',
'Serial Plotter'
),
});
registry.registerItem({
id: 'toggle-serial-monitor',
command: MonitorViewContribution.TOGGLE_SERIAL_MONITOR_TOOLBAR,
tooltip: nls.localize('arduino/common/serialMonitor', 'Serial Monitor'),
});
}
registerCommands(registry: CommandRegistry): void {
for (const command of [
EditorCommands.SPLIT_EDITOR_DOWN,
EditorCommands.SPLIT_EDITOR_LEFT,
EditorCommands.SPLIT_EDITOR_RIGHT,
EditorCommands.SPLIT_EDITOR_UP,
EditorCommands.SPLIT_EDITOR_VERTICAL,
EditorCommands.SPLIT_EDITOR_HORIZONTAL,
FileNavigatorCommands.REVEAL_IN_NAVIGATOR,
]) {
registry.unregisterCommand(command);
}
}
registerMenus(registry: MenuModelRegistry): void {
const menuId = (menuPath: string[]): string => {
const index = menuPath.length - 1;
const menuId = menuPath[index];
return menuId;
};
registry.getMenu(MAIN_MENU_BAR).removeNode(menuId(MonacoMenus.SELECTION));
registry.getMenu(MAIN_MENU_BAR).removeNode(menuId(EditorMainMenu.GO));
registry.getMenu(MAIN_MENU_BAR).removeNode(menuId(TerminalMenus.TERMINAL));
registry.getMenu(MAIN_MENU_BAR).removeNode(menuId(CommonMenus.VIEW));
registry.registerSubmenu(
ArduinoMenus.SKETCH,
nls.localize('arduino/menu/sketch', 'Sketch')
);
registry.registerSubmenu(
ArduinoMenus.TOOLS,
nls.localize('arduino/menu/tools', 'Tools')
);
}
registerColors(colors: ColorRegistry): void {
colors.register(
{
id: 'arduino.toolbar.button.background',
defaults: {
dark: 'button.background',
light: 'button.background',
hcDark: 'activityBar.inactiveForeground',
hcLight: 'activityBar.inactiveForeground',
},
description:
'Background color of the toolbar items. Such as Upload, Verify, etc.',
},
{
id: 'arduino.toolbar.button.hoverBackground',
defaults: {
dark: 'button.hoverBackground',
light: 'button.hoverBackground',
hcDark: 'button.background',
hcLight: 'button.background',
},
description:
'Background color of the toolbar items when hovering over them. Such as Upload, Verify, etc.',
},
{
id: 'arduino.toolbar.button.secondary.label',
defaults: {
dark: 'secondaryButton.foreground',
light: 'button.foreground',
hcDark: 'activityBar.inactiveForeground',
hcLight: 'activityBar.inactiveForeground',
},
description:
'Foreground color of the toolbar items. Such as Serial Monitor and Serial Plotter',
},
{
id: 'arduino.toolbar.button.secondary.hoverBackground',
defaults: {
dark: 'secondaryButton.hoverBackground',
light: 'button.hoverBackground',
hcDark: 'textLink.foreground',
hcLight: 'textLink.foreground',
},
description:
'Background color of the toolbar items when hovering over them, such as "Serial Monitor" and "Serial Plotter"',
},
{
id: 'arduino.toolbar.toggleBackground',
defaults: {
dark: 'editor.selectionBackground',
light: 'editor.selectionBackground',
hcDark: 'textPreformat.foreground',
hcLight: 'textPreformat.foreground',
},
description:
'Toggle color of the toolbar items when they are currently toggled (the command is in progress)',
},
{
id: 'arduino.toolbar.dropdown.border',
defaults: {
dark: 'dropdown.border',
light: 'dropdown.border',
hcDark: 'dropdown.border',
hcLight: 'dropdown.border',
},
description: 'Border color of the Board Selector.',
},
{
id: 'arduino.toolbar.dropdown.borderActive',
defaults: {
dark: 'focusBorder',
light: 'focusBorder',
hcDark: 'focusBorder',
hcLight: 'focusBorder',
},
description: "Border color of the Board Selector when it's active",
},
{
id: 'arduino.toolbar.dropdown.background',
defaults: {
dark: 'tab.unfocusedActiveBackground',
light: 'dropdown.background',
hcDark: 'dropdown.background',
hcLight: 'dropdown.background',
},
description: 'Background color of the Board Selector.',
},
{
id: 'arduino.toolbar.dropdown.label',
defaults: {
dark: 'dropdown.foreground',
light: 'dropdown.foreground',
hcDark: 'dropdown.foreground',
hcLight: 'dropdown.foreground',
},
description: 'Font color of the Board Selector.',
},
{
id: 'arduino.toolbar.dropdown.iconSelected',
defaults: {
dark: 'list.activeSelectionIconForeground',
light: 'list.activeSelectionIconForeground',
hcDark: 'list.activeSelectionIconForeground',
hcLight: 'list.activeSelectionIconForeground',
},
description:
'Color of the selected protocol icon in the Board Selector.',
},
{
id: 'arduino.toolbar.dropdown.option.backgroundHover',
defaults: {
dark: 'list.hoverBackground',
light: 'list.hoverBackground',
hcDark: 'list.hoverBackground',
hcLight: 'list.hoverBackground',
},
description: 'Background color on hover of the Board Selector options.',
},
{
id: 'arduino.toolbar.dropdown.option.backgroundSelected',
defaults: {
dark: 'list.activeSelectionBackground',
light: 'list.activeSelectionBackground',
hcDark: 'list.activeSelectionBackground',
hcLight: 'list.activeSelectionBackground',
},
description:
'Background color of the selected board in the Board Selector.',
}
);
}
registerThemeStyle(theme: ColorTheme, collector: CssStyleCollector): void {
const warningForeground = theme.getColor('warningForeground');
const warningBackground = theme.getColor('warningBackground');
const focusBorder = theme.getColor('focusBorder');
const contrastBorder = theme.getColor('contrastBorder');
const notificationsBackground = theme.getColor('notifications.background');
const buttonBorder = theme.getColor('button.border');
const buttonBackground = theme.getColor('button.background') || 'none';
const dropdownBackground = theme.getColor('dropdown.background');
const arduinoToolbarButtonBackground = theme.getColor(
'arduino.toolbar.button.background'
);
if (isHighContrast(theme.type)) {
// toolbar items
collector.addRule(`
.p-TabBar-toolbar .item.arduino-tool-item.enabled:hover > div.toggle-serial-monitor,
.p-TabBar-toolbar .item.arduino-tool-item.enabled:hover > div.toggle-serial-plotter {
background: transparent;
}
`);
if (contrastBorder) {
collector.addRule(`
.quick-input-widget {
outline: 1px solid ${contrastBorder};
outline-offset: -1px;
}
`);
}
if (focusBorder) {
// customized react-select widget
collector.addRule(`
.arduino-select__option--is-selected {
outline: 1px solid ${focusBorder};
}
`);
collector.addRule(`
.arduino-select__option--is-focused {
outline: 1px dashed ${focusBorder};
}
`);
// boards selector dropdown
collector.addRule(`
#select-board-dialog .selectBoardContainer .list .item:hover {
outline: 1px dashed ${focusBorder};
}
`);
// button hover
collector.addRule(`
.theia-button:hover,
button.theia-button:hover {
outline: 1px dashed ${focusBorder};
}
`);
collector.addRule(`
.theia-button {
border: 1px solid ${focusBorder};
}
`);
collector.addRule(`
.component-list-item .header .installed-version:hover:before {
background-color: transparent;
outline: 1px dashed ${focusBorder};
}
`);
// tree node
collector.addRule(`
.theia-TreeNode:hover {
outline: 1px dashed ${focusBorder};
}
`);
collector.addRule(`
.quick-input-list .monaco-list-row.focused,
.theia-Tree .theia-TreeNode.theia-mod-selected {
outline: 1px dotted ${focusBorder};
}
`);
collector.addRule(`
div#select-board-dialog .selectBoardContainer .list .item.selected,
.theia-Tree:focus .theia-TreeNode.theia-mod-selected,
.theia-Tree .ReactVirtualized__List:focus .theia-TreeNode.theia-mod-selected {
outline: 1px solid ${focusBorder};
}
`);
// quick input
collector.addRule(`
.quick-input-list .monaco-list-row:hover {
outline: 1px dashed ${focusBorder};
}
`);
// editor tab-bar
collector.addRule(`
.p-TabBar.theia-app-centers .p-TabBar-tab.p-mod-closable > .p-TabBar-tabCloseIcon:hover {
outline: 1px dashed ${focusBorder};
}
`);
collector.addRule(`
#theia-main-content-panel .p-TabBar .p-TabBar-tab:hover {
outline: 1px dashed ${focusBorder};
outline-offset: -4px;
}
`);
collector.addRule(`
#theia-main-content-panel .p-TabBar .p-TabBar-tab.p-mod-current {
outline: 1px solid ${focusBorder};
outline-offset: -4px;
}
`);
// boards selector dropdown
collector.addRule(`
.arduino-boards-dropdown-item:hover {
outline: 1px dashed ${focusBorder};
outline-offset: -2px;
}
`);
if (notificationsBackground) {
// notification
collector.addRule(`
.theia-notification-list-item:hover:not(:focus) {
background-color: ${notificationsBackground};
outline: 1px dashed ${focusBorder};
outline-offset: -2px;
}
`);
}
if (arduinoToolbarButtonBackground) {
// toolbar item
collector.addRule(`
.item.arduino-tool-item.toggled .arduino-upload-sketch--toolbar,
.item.arduino-tool-item.toggled .arduino-verify-sketch--toolbar {
background-color: ${arduinoToolbarButtonBackground} !important;
outline: 1px solid ${focusBorder};
}
`);
collector.addRule(`
.p-TabBar-toolbar .item.arduino-tool-item.enabled:hover > div {
background: ${arduinoToolbarButtonBackground};
outline: 1px dashed ${focusBorder};
}
`);
}
}
if (dropdownBackground) {
// boards selector dropdown
collector.addRule(`
.arduino-boards-dropdown-item:hover {
background: ${dropdownBackground};
}
`);
}
if (warningForeground && warningBackground) {
// <input> widget with inverted foreground and background colors
collector.addRule(`
.theia-input.warning:focus,
.theia-input.warning::placeholder,
.theia-input.warning {
color: ${warningBackground};
background-color: ${warningForeground};
}
`);
}
if (buttonBorder) {
collector.addRule(`
button.theia-button,
button.theia-button.secondary,
.component-list-item .theia-button.secondary.no-border,
.component-list-item .theia-button.secondary.no-border:hover {
border: 1px solid ${buttonBorder};
}
`);
collector.addRule(`
.component-list-item .header .installed-version:before {
color: ${buttonBackground};
border: 1px solid ${buttonBorder};
}
`);
}
registerToolbarItems(registry: TabBarToolbarRegistry): void {
registry.registerItem({
id: BoardsToolBarItem.TOOLBAR_ID,
render: () => <BoardsToolBarItem
key='boardsToolbarItem'
commands={this.commandRegistry}
boardsServiceClient={this.boardsServiceClientImpl} />,
isVisible: widget => ArduinoToolbar.is(widget) && widget.side === 'left',
priority: 7
});
registry.registerItem({
id: 'toggle-serial-monitor',
command: MonitorViewContribution.TOGGLE_SERIAL_MONITOR_TOOLBAR,
tooltip: 'Serial Monitor'
});
registry.registerItem({
id: ArduinoCommands.TOGGLE_ADVANCED_MODE.id,
command: ArduinoCommands.TOGGLE_ADVANCED_MODE_TOOLBAR.id,
tooltip: this.editorMode.proMode ? 'Switch to Classic Mode' : 'Switch to Advanced Mode',
text: this.editorMode.proMode ? '$(toggle-on)' : '$(toggle-off)'
});
}
}
registerCommands(registry: CommandRegistry): void {
registry.registerCommand(ArduinoCommands.TOGGLE_COMPILE_FOR_DEBUG, {
execute: () => this.editorMode.toggleCompileForDebug(),
isToggled: () => this.editorMode.compileForDebug
});
registry.registerCommand(ArduinoCommands.OPEN_SKETCH_FILES, {
execute: async (uri: string) => {
this.openSketchFiles(uri);
}
});
registry.registerCommand(ArduinoCommands.OPEN_BOARDS_DIALOG, {
execute: async () => {
const boardsConfig = await this.boardsConfigDialog.open();
if (boardsConfig) {
this.boardsServiceClientImpl.boardsConfig = boardsConfig;
}
}
});
registry.registerCommand(ArduinoCommands.TOGGLE_ADVANCED_MODE, {
isToggled: () => this.editorMode.proMode,
execute: () => this.editorMode.toggleProMode()
});
registry.registerCommand(ArduinoCommands.TOGGLE_ADVANCED_MODE_TOOLBAR, {
isVisible: widget => ArduinoToolbar.is(widget) && widget.side === 'right',
isToggled: () => this.editorMode.proMode,
execute: () => this.editorMode.toggleProMode()
});
}
registerMenus(registry: MenuModelRegistry) {
if (!this.editorMode.proMode) {
const menuId = (menuPath: string[]): string => {
const index = menuPath.length - 1;
const menuId = menuPath[index];
return menuId;
}
registry.getMenu(MAIN_MENU_BAR).removeNode(menuId(MonacoMenus.SELECTION));
registry.getMenu(MAIN_MENU_BAR).removeNode(menuId(EditorMainMenu.GO));
registry.getMenu(MAIN_MENU_BAR).removeNode(menuId(TerminalMenus.TERMINAL));
registry.getMenu(MAIN_MENU_BAR).removeNode(menuId(CommonMenus.VIEW));
}
registry.registerSubmenu(ArduinoMenus.SKETCH, 'Sketch');
registry.registerSubmenu(ArduinoMenus.TOOLS, 'Tools');
registry.registerMenuAction(ArduinoMenus.SKETCH, {
commandId: ArduinoCommands.TOGGLE_COMPILE_FOR_DEBUG.id,
label: 'Optimize for Debugging',
order: '1'
});
registry.registerMenuAction(CommonMenus.HELP, {
commandId: ArduinoCommands.TOGGLE_ADVANCED_MODE.id,
label: 'Advanced Mode'
});
}
protected async openSketchFiles(uri: string): Promise<void> {
try {
const sketch = await this.sketchService.loadSketch(uri);
const { mainFileUri, otherSketchFileUris, additionalFileUris } = sketch;
for (const uri of [mainFileUri, ...otherSketchFileUris, ...additionalFileUris]) {
await this.ensureOpened(uri);
}
await this.ensureOpened(mainFileUri, true);
} catch (e) {
console.error(e);
const message = e instanceof Error ? e.message : JSON.stringify(e);
this.messageService.error(message);
}
}
protected async ensureOpened(uri: string, forceOpen: boolean = false): Promise<any> {
const widget = this.editorManager.all.find(widget => widget.editor.uri.toString() === uri);
if (!widget || forceOpen) {
return this.editorManager.open(new URI(uri));
}
}
registerColors(colors: ColorRegistry): void {
colors.register(
{
id: 'arduino.branding.primary',
defaults: {
dark: 'statusBar.background',
light: 'statusBar.background'
},
description: 'The primary branding color, such as dialog titles, library, and board manager list labels.'
},
{
id: 'arduino.branding.secondary',
defaults: {
dark: 'statusBar.background',
light: 'statusBar.background'
},
description: 'Secondary branding color for list selections, dropdowns, and widget borders.'
},
{
id: 'arduino.foreground',
defaults: {
dark: 'editorWidget.background',
light: 'editorWidget.background',
hc: 'editorWidget.background'
},
description: 'Color of the Arduino Pro IDE foreground which is used for dialogs, such as the Select Board dialog.'
},
{
id: 'arduino.toolbar.background',
defaults: {
dark: 'button.background',
light: 'button.background',
hc: 'activityBar.inactiveForeground'
},
description: 'Background color of the toolbar items. Such as Upload, Verify, etc.'
},
{
id: 'arduino.toolbar.hoverBackground',
defaults: {
dark: 'button.hoverBackground',
light: 'button.hoverBackground',
hc: 'activityBar.inactiveForeground'
},
description: 'Background color of the toolbar items when hovering over them. Such as Upload, Verify, etc.'
},
{
id: 'arduino.output.foreground',
defaults: {
dark: 'editor.foreground',
light: 'editor.foreground',
hc: 'editor.foreground'
},
description: 'Color of the text in the Output view.'
},
{
id: 'arduino.output.background',
defaults: {
dark: 'editor.background',
light: 'editor.background',
hc: 'editor.background'
},
description: 'Background color of the Output view.'
}
);
}
}

View File

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

View File

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

View File

@ -1,99 +0,0 @@
import { inject, injectable } from '@theia/core/shared/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-contribution';
import {
CommandRegistry,
CommandContribution,
} from '@theia/core/lib/common/command';
import {
AuthOptions,
AuthenticationService,
AuthenticationServiceClient,
AuthenticationSession,
authServerPort,
} from '../../common/protocol/authentication-service';
import { CloudUserCommands } from './cloud-user-commands';
import { 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;
async onStart(): Promise<void> {
this.toDispose.push(this.onSessionDidChangeEmitter);
this.service.setClient(this);
this.service
.session()
.then((session) => this.notifySessionDidChange(session));
this.setOptions().then(() => this.service.initAuthSession());
this.arduinoPreferences.onPreferenceChanged((event) => {
if (event.preferenceName.startsWith('arduino.auth.')) {
this.setOptions();
}
});
}
setOptions(): Promise<void> {
return this.service.setOptions({
redirectUri: `http://localhost:${authServerPort}/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(),
isEnabled: () => !this._session,
isVisible: () => !this._session,
});
registry.registerCommand(CloudUserCommands.LOGOUT, {
execute: () => this.service.logout(),
isEnabled: () => !!this._session,
isVisible: () => !!this._session,
});
}
notifySessionDidChange(session: AuthenticationSession | undefined): void {
this.updateSession(session);
}
}

View File

@ -1,22 +0,0 @@
import { Command } from '@theia/core/lib/common/command';
export const LEARN_MORE_URL =
'https://docs.arduino.cc/software/ide-v2/tutorials/ide-v2-cloud-sketch-sync';
export namespace CloudUserCommands {
export const LOGIN = Command.toLocalizedCommand(
{
id: 'arduino-cloud--login',
label: 'Sign in',
},
'arduino/cloud/signIn'
);
export const LOGOUT = Command.toLocalizedCommand(
{
id: 'arduino-cloud--logout',
label: 'Sign Out',
},
'arduino/cloud/signOut'
);
}

View File

@ -1,229 +1,62 @@
import { FrontendApplicationContribution } from '@theia/core/lib/browser/frontend-application-contribution';
import { DisposableCollection } from '@theia/core/lib/common/disposable';
import { injectable, inject } from 'inversify';
import { MessageService } from '@theia/core/lib/common/message-service';
import { MessageType } from '@theia/core/lib/common/message-service-protocol';
import { nls } from '@theia/core/lib/common/nls';
import { notEmpty } from '@theia/core/lib/common/objects';
import { inject, injectable } from '@theia/core/shared/inversify';
import { NotificationManager } from '@theia/messages/lib/browser/notifications-manager';
import { InstallManually } from '../../common/nls';
import { Installable, ResponseServiceClient } from '../../common/protocol';
import {
BoardIdentifier,
BoardsPackage,
BoardsService,
createPlatformIdentifier,
isBoardIdentifierChangeEvent,
PlatformIdentifier,
platformIdentifierEquals,
serializePlatformIdentifier,
} from '../../common/protocol/boards-service';
import { NotificationCenter } from '../notification-center';
import { BoardsServiceProvider } from './boards-service-provider';
import { FrontendApplicationContribution } from '@theia/core/lib/browser/frontend-application';
import { BoardsService, Board } from '../../common/protocol/boards-service';
import { BoardsServiceClientImpl } from './boards-service-client-impl';
import { BoardsListWidgetFrontendContribution } from './boards-widget-frontend-contribution';
import { InstallationProgressDialog } from '../widgets/progress-dialog';
import { BoardsConfig } from './boards-config';
/**
* Listens on `BoardsConfigChangeEvent`s, if a board is selected which does not
* Listens on `BoardsConfig.Config` changes, if a board is selected which does not
* have the corresponding core installed, it proposes the user to install the core.
*/
@injectable()
export class BoardsAutoInstaller implements FrontendApplicationContribution {
@inject(NotificationCenter)
private readonly notificationCenter: NotificationCenter;
@inject(MessageService)
private readonly messageService: MessageService;
@inject(NotificationManager)
private readonly notificationManager: NotificationManager;
@inject(BoardsService)
private readonly boardsService: BoardsService;
@inject(BoardsServiceProvider)
private readonly boardsServiceProvider: BoardsServiceProvider;
@inject(ResponseServiceClient)
private readonly responseService: ResponseServiceClient;
@inject(BoardsListWidgetFrontendContribution)
private readonly boardsManagerWidgetContribution: BoardsListWidgetFrontendContribution;
// Workaround for https://github.com/eclipse-theia/theia/issues/9349
private readonly installNotificationInfos: Readonly<{
boardName: string;
platformId: string;
notificationId: string;
}>[] = [];
private readonly toDispose = new DisposableCollection();
@inject(MessageService)
protected readonly messageService: MessageService;
onStart(): void {
this.toDispose.pushAll([
this.boardsServiceProvider.onBoardsConfigDidChange((event) => {
if (isBoardIdentifierChangeEvent(event)) {
this.ensureCoreExists(event.selectedBoard);
}
}),
this.notificationCenter.onPlatformDidInstall((event) =>
this.clearAllNotificationForPlatform(event.item.id)
),
]);
this.boardsServiceProvider.ready.then(() => {
const { selectedBoard } = this.boardsServiceProvider.boardsConfig;
this.ensureCoreExists(selectedBoard);
});
}
@inject(BoardsService)
protected readonly boardsService: BoardsService;
private async findPlatformToInstall(
selectedBoard: BoardIdentifier
): Promise<BoardsPackage | undefined> {
const platformId = await this.findPlatformIdToInstall(selectedBoard);
if (!platformId) {
return undefined;
}
const id = serializePlatformIdentifier(platformId);
const platform = await this.boardsService.getBoardPackage({ id });
if (!platform) {
console.warn(`Could not resolve platform for ID: ${id}`);
return undefined;
}
if (platform.installedVersion) {
return undefined;
}
return platform;
}
@inject(BoardsServiceClientImpl)
protected readonly boardsServiceClient: BoardsServiceClientImpl;
private async findPlatformIdToInstall(
selectedBoard: BoardIdentifier
): Promise<PlatformIdentifier | undefined> {
const selectedBoardPlatformId = createPlatformIdentifier(selectedBoard);
// The board is installed or the FQBN is available from the `board list watch` for Arduino boards. The latter might change!
if (selectedBoardPlatformId) {
const installedPlatforms =
await this.boardsService.getInstalledPlatforms();
const installedPlatformIds = installedPlatforms
.map((platform) => createPlatformIdentifier(platform.id))
.filter(notEmpty);
if (
installedPlatformIds.every(
(installedPlatformId) =>
!platformIdentifierEquals(
installedPlatformId,
selectedBoardPlatformId
)
)
) {
return selectedBoardPlatformId;
}
} else {
// IDE2 knows that selected board is not installed. Look for board `name` match in not yet installed platforms.
// The order should be correct when there is a board name collision (e.g. Arduino Nano RP2040 from Arduino Mbed OS Nano Boards, [DEPRECATED] Arduino Mbed OS Nano Boards). The CLI boosts the platforms, so picking the first name match should be fine.
const platforms = await this.boardsService.search({});
for (const platform of platforms) {
// Ignore installed platforms
if (platform.installedVersion) {
continue;
}
if (
platform.boards.some((board) => board.name === selectedBoard.name)
) {
const platformId = createPlatformIdentifier(platform.id);
if (platformId) {
return platformId;
}
}
}
}
return undefined;
}
@inject(BoardsListWidgetFrontendContribution)
protected readonly boardsManagerFrontendContribution: BoardsListWidgetFrontendContribution;
private async ensureCoreExists(
selectedBoard: BoardIdentifier | undefined
): Promise<void> {
if (!selectedBoard) {
return;
onStart(): void {
this.boardsServiceClient.onBoardsConfigChanged(this.ensureCoreExists.bind(this));
this.ensureCoreExists(this.boardsServiceClient.boardsConfig);
}
const candidate = await this.findPlatformToInstall(selectedBoard);
if (!candidate) {
return;
}
const platformIdToInstall = candidate.id;
const selectedBoardName = selectedBoard.name;
if (
this.installNotificationInfos.some(
({ boardName, platformId }) =>
platformIdToInstall === platformId && selectedBoardName === boardName
)
) {
// Already has a notification for the board with the same platform. Nothing to do.
return;
}
this.clearAllNotificationForPlatform(platformIdToInstall);
const version = candidate.availableVersions[0]
? `[v ${candidate.availableVersions[0]}]`
: '';
const yes = nls.localize('vscode/extensionsUtils/yes', 'Yes');
const message = nls.localize(
'arduino/board/installNow',
'The "{0} {1}" core has to be installed for the currently selected "{2}" board. Do you want to install it now?',
candidate.name,
version,
selectedBoard.name
);
const notificationId = this.notificationId(message, InstallManually, yes);
this.installNotificationInfos.push({
boardName: selectedBoardName,
platformId: platformIdToInstall,
notificationId,
});
const answer = await this.messageService.info(
message,
InstallManually,
yes
);
if (answer) {
const index = this.installNotificationInfos.findIndex(
({ boardName, platformId }) =>
platformIdToInstall === platformId && selectedBoardName === boardName
);
if (index !== -1) {
this.installNotificationInfos.splice(index, 1);
}
if (answer === yes) {
await Installable.installWithProgress({
installable: this.boardsService,
item: candidate,
messageService: this.messageService,
responseService: this.responseService,
version: candidate.availableVersions[0],
});
return;
}
if (answer === InstallManually) {
this.boardsManagerWidgetContribution
.openView({ reveal: true })
.then((widget) =>
widget.refresh({
query: candidate.name.toLocaleLowerCase(),
type: 'All',
protected ensureCoreExists(config: BoardsConfig.Config): void {
const { selectedBoard } = config;
if (selectedBoard) {
this.boardsService.search({}).then(packages => {
const candidates = packages
.filter(pkg => pkg.boards.some(board => Board.sameAs(board, selectedBoard)))
.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()));
}
});
}
})
);
}
}
}
}
private clearAllNotificationForPlatform(predicatePlatformId: string): void {
// Discard all install notifications for the same platform.
const notificationsLength = this.installNotificationInfos.length;
for (let i = notificationsLength - 1; i >= 0; i--) {
const { notificationId, platformId } = this.installNotificationInfos[i];
if (platformId === predicatePlatformId) {
this.installNotificationInfos.splice(i, 1);
this.notificationManager.clear(notificationId);
}
}
}
private notificationId(message: string, ...actions: string[]): string {
return this.notificationManager['getMessageId']({
text: message,
actions,
type: MessageType.Info,
});
}
}

View File

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

View File

@ -0,0 +1,64 @@
import * as React from 'react';
import { injectable, inject } from 'inversify';
import { Emitter } from '@theia/core/lib/common/event';
import { ReactWidget, Message } from '@theia/core/lib/browser';
import { BoardsService } from '../../common/protocol/boards-service';
import { BoardsConfig } from './boards-config';
import { BoardsServiceClientImpl } from './boards-service-client-impl';
import { CoreServiceClientImpl } from '../core-service-client-impl';
import { ArduinoDaemonClientImpl } from '../arduino-daemon-client-impl';
@injectable()
export class BoardsConfigDialogWidget extends ReactWidget {
@inject(BoardsService)
protected readonly boardsService: BoardsService;
@inject(BoardsServiceClientImpl)
protected readonly boardsServiceClient: BoardsServiceClientImpl;
@inject(CoreServiceClientImpl)
protected readonly coreServiceClient: CoreServiceClientImpl;
@inject(ArduinoDaemonClientImpl)
protected readonly daemonClient: ArduinoDaemonClientImpl;
protected readonly onBoardConfigChangedEmitter = new Emitter<BoardsConfig.Config>();
readonly onBoardConfigChanged = this.onBoardConfigChangedEmitter.event;
protected focusNode: HTMLElement | undefined;
constructor() {
super();
this.id = 'select-board-dialog';
}
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
boardsService={this.boardsService}
boardsServiceClient={this.boardsServiceClient}
coreServiceClient={this.coreServiceClient}
daemonClient={this.daemonClient}
onConfigChange={this.fireConfigChanged}
onFocusNodeSet={this.setFocusNode} />
</div>;
}
protected onActivateRequest(msg: Message): void {
super.onActivateRequest(msg);
if (this.focusNode instanceof HTMLInputElement) {
this.focusNode.select();
}
(this.focusNode || this.node).focus();
}
}

View File

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

View File

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

View File

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

View File

@ -0,0 +1,117 @@
import * as PQueue from 'p-queue';
import { inject, injectable } from 'inversify';
import { CommandRegistry } from '@theia/core/lib/common/command';
import { MenuModelRegistry, MenuNode } from '@theia/core/lib/common/menu';
import { Disposable, DisposableCollection } from '@theia/core/lib/common/disposable';
import { BoardsServiceClientImpl } from './boards-service-client-impl';
import { Board, ConfigOption, Programmer } from '../../common/protocol';
import { FrontendApplicationContribution } from '@theia/core/lib/browser';
import { BoardsDataStore } from './boards-data-store';
import { MainMenuManager } from '../../common/main-menu-manager';
import { ArduinoMenus } from '../menu/arduino-menus';
@injectable()
export class BoardsDataMenuUpdater implements FrontendApplicationContribution {
@inject(CommandRegistry)
protected readonly commandRegistry: CommandRegistry;
@inject(MenuModelRegistry)
protected readonly menuRegistry: MenuModelRegistry;
@inject(MainMenuManager)
protected readonly mainMenuManager: MainMenuManager;
@inject(BoardsDataStore)
protected readonly boardsDataStore: BoardsDataStore;
@inject(BoardsServiceClientImpl)
protected readonly boardsServiceClient: BoardsServiceClientImpl;
protected readonly queue = new PQueue({ autoStart: true, concurrency: 1 });
protected readonly toDisposeOnBoardChange = new DisposableCollection();
async onStart(): Promise<void> {
this.updateMenuActions(this.boardsServiceClient.boardsConfig.selectedBoard);
this.boardsDataStore.onChanged(() => this.updateMenuActions(this.boardsServiceClient.boardsConfig.selectedBoard));
this.boardsServiceClient.onBoardsConfigChanged(({ selectedBoard }) => this.updateMenuActions(selectedBoard));
}
protected async updateMenuActions(selectedBoard: Board | undefined): Promise<void> {
return this.queue.add(async () => {
this.toDisposeOnBoardChange.dispose();
this.mainMenuManager.update();
if (selectedBoard) {
const { fqbn } = selectedBoard;
if (fqbn) {
const { configOptions, programmers, selectedProgrammer } = await this.boardsDataStore.getData(fqbn);
if (configOptions.length) {
const boardsConfigMenuPath = [...ArduinoMenus.TOOLS__BOARD_SETTINGS_GROUP, 'z01_boardsConfig']; // `z_` is for ordering.
for (const { label, option, values } of configOptions.sort(ConfigOption.LABEL_COMPARATOR)) {
const menuPath = [...boardsConfigMenuPath, `${option}`];
const commands = new Map<string, Disposable & { label: string }>()
for (const value of values) {
const id = `${fqbn}-${option}--${value.value}`;
const command = { id };
const selectedValue = value.value;
const handler = {
execute: () => this.boardsDataStore.selectConfigOption({ fqbn, option, selectedValue }),
isToggled: () => value.selected
};
commands.set(id, Object.assign(this.commandRegistry.registerCommand(command, handler), { label: value.label }));
}
this.menuRegistry.registerSubmenu(menuPath, label);
this.toDisposeOnBoardChange.pushAll([
...commands.values(),
Disposable.create(() => this.unregisterSubmenu(menuPath)), // We cannot dispose submenu entries: https://github.com/eclipse-theia/theia/issues/7299
...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(() => this.unregisterSubmenu(programmersMenuPath)));
for (const programmer of programmers) {
const { id, name } = programmer;
const command = { id: `${fqbn}-programmer--${id}` };
const handler = {
execute: () => this.boardsDataStore.selectProgrammer({ fqbn, selectedProgrammer: programmer }),
isToggled: () => Programmer.equals(programmer, selectedProgrammer)
};
this.menuRegistry.registerMenuAction(programmersMenuPath, { commandId: command.id, label: name });
this.commandRegistry.registerCommand(command, handler);
this.toDisposeOnBoardChange.pushAll([
Disposable.create(() => this.commandRegistry.unregisterCommand(command)),
Disposable.create(() => this.menuRegistry.unregisterMenuAction(command.id))
]);
}
}
this.mainMenuManager.update();
}
}
});
}
protected unregisterSubmenu(menuPath: string[]): void {
if (menuPath.length < 2) {
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);
// This is unsafe. Calling `getMenu` with a non-existing menu-path will result in a new menu creation.
// https://github.com/eclipse-theia/theia/issues/7300
const parent = this.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)}.`);
}
(parent.children as Array<MenuNode>).splice(index, 1);
}
}

View File

@ -1,437 +1,200 @@
import { FrontendApplicationContribution } from '@theia/core/lib/browser/frontend-application-contribution';
import { FrontendApplicationStateService } from '@theia/core/lib/browser/frontend-application-state';
import { StorageService } from '@theia/core/lib/browser/storage-service';
import type {
Command,
CommandContribution,
CommandRegistry,
} from '@theia/core/lib/common/command';
import { DisposableCollection } from '@theia/core/lib/common/disposable';
import { Emitter, Event } from '@theia/core/lib/common/event';
import { injectable, inject, named } from 'inversify';
import { ILogger } from '@theia/core/lib/common/logger';
import { deepClone, deepFreeze } from '@theia/core/lib/common/objects';
import type { Mutable } from '@theia/core/lib/common/types';
import { inject, injectable, named } from '@theia/core/shared/inversify';
import { FQBN } from 'fqbn';
import {
BoardDetails,
BoardsService,
ConfigOption,
ConfigValue,
Programmer,
isBoardIdentifierChangeEvent,
isProgrammer,
sanitizeFqbn,
} from '../../common/protocol';
import { deepClone } from '@theia/core/lib/common/objects';
import { MaybePromise } from '@theia/core/lib/common/types';
import { Event, Emitter } from '@theia/core/lib/common/event';
import { FrontendApplicationContribution, LocalStorageService } from '@theia/core/lib/browser';
import { notEmpty } from '../../common/utils';
import type {
StartupTask,
StartupTaskProvider,
} from '../../electron-common/startup-task';
import { NotificationCenter } from '../notification-center';
import { BoardsServiceProvider } from './boards-service-provider';
export interface SelectConfigOptionParams {
readonly fqbn: string;
readonly optionsToUpdate: readonly Readonly<{
option: string;
selectedValue: string;
}>[];
}
import { BoardsServiceClientImpl } from './boards-service-client-impl';
import { BoardsService, ConfigOption, Installable, BoardDetails, Programmer } from '../../common/protocol';
@injectable()
export class BoardsDataStore
implements
FrontendApplicationContribution,
StartupTaskProvider,
CommandContribution
{
@inject(ILogger)
@named('store')
private readonly logger: ILogger;
@inject(BoardsService)
private readonly boardsService: BoardsService;
@inject(NotificationCenter)
private readonly notificationCenter: NotificationCenter;
// When `@theia/workspace` is part of the application, the workspace-scoped storage service is the default implementation, and the `StorageService` symbol must be used for the injection.
// https://github.com/eclipse-theia/theia/blob/ba3722b04ff91eb6a4af6a571c9e263c77cdd8b5/packages/workspace/src/browser/workspace-frontend-module.ts#L97-L98
// In other words, store the data (such as the board configs) per sketch, not per IDE2 installation. https://github.com/arduino/arduino-ide/issues/2240
@inject(StorageService)
private readonly storageService: StorageService;
@inject(BoardsServiceProvider)
private readonly boardsServiceProvider: BoardsServiceProvider;
@inject(FrontendApplicationStateService)
private readonly appStateService: FrontendApplicationStateService;
export class BoardsDataStore implements FrontendApplicationContribution {
private readonly onDidChangeEmitter =
new Emitter<BoardsDataStoreChangeEvent>();
private readonly toDispose = new DisposableCollection(
this.onDidChangeEmitter
);
private _selectedBoardData: BoardsDataStoreChange | undefined;
@inject(ILogger)
@named('store')
protected readonly logger: ILogger;
onStart(): void {
this.toDispose.pushAll([
this.boardsServiceProvider.onBoardsConfigDidChange((event) => {
if (isBoardIdentifierChangeEvent(event)) {
this.updateSelectedBoardData(
event.selectedBoard?.fqbn,
// If the change event comes from toolbar and the FQBN contains custom board options, change the currently selected options
// https://github.com/arduino/arduino-ide/issues/1588
event.reason === 'toolbar'
);
@inject(BoardsService)
protected readonly boardsService: BoardsService;
@inject(BoardsServiceClientImpl)
protected readonly boardsServiceClient: BoardsServiceClientImpl;
@inject(LocalStorageService)
protected readonly storageService: LocalStorageService;
protected readonly onChangedEmitter = new Emitter<void>();
onStart(): void {
this.boardsServiceClient.onBoardsPackageInstalled(async ({ pkg }) => {
const { installedVersion: version } = pkg;
if (!version) {
return;
}
let shouldFireChanged = false;
for (const fqbn of pkg.boards.map(({ fqbn }) => fqbn).filter(notEmpty).filter(fqbn => !!fqbn)) {
const key = this.getStorageKey(fqbn, version);
let data = await this.storageService.getData<ConfigOption[] | undefined>(key);
if (!data || !data.length) {
const details = await this.getBoardDetailsSafe(fqbn);
if (details) {
data = details.configOptions;
if (data.length) {
await this.storageService.setData(key, data);
shouldFireChanged = true;
}
}
}
}
if (shouldFireChanged) {
this.fireChanged();
}
});
}
get onChanged(): Event<void> {
return this.onChangedEmitter.event;
}
async appendConfigToFqbn(
fqbn: string,
boardsPackageVersion: MaybePromise<Installable.Version | undefined> = this.getBoardsPackageVersion(fqbn)): Promise<string> {
const { configOptions } = await this.getData(fqbn, boardsPackageVersion);
return ConfigOption.decorate(fqbn, configOptions);
}
async getData(
fqbn: string,
boardsPackageVersion: MaybePromise<Installable.Version | undefined> = this.getBoardsPackageVersion(fqbn)): Promise<BoardsDataStore.Data> {
const version = await boardsPackageVersion;
if (!version) {
return BoardsDataStore.Data.EMPTY;
}
}),
this.notificationCenter.onPlatformDidInstall(async ({ item }) => {
const boardsWithFqbn = item.boards
.map(({ fqbn }) => fqbn)
.filter(notEmpty);
const changes: BoardsDataStoreChange[] = [];
for (const fqbn of boardsWithFqbn) {
const key = this.getStorageKey(fqbn);
const storedData =
await this.storageService.getData<BoardsDataStore.Data>(key);
if (!storedData) {
// if no previously value is available for the board, do not update the cache
continue;
}
const details = await this.loadBoardDetails(fqbn);
if (details) {
const data = createDataStoreEntry(details);
await this.storageService.setData(key, data);
changes.push({ fqbn, data });
}
const key = this.getStorageKey(fqbn, version);
let data = await this.storageService.getData<BoardsDataStore.Data | undefined>(key, undefined);
if (data) {
if (data.programmers !== undefined) { // to be backward compatible. We did not save the `programmers` into the `localStorage`.
return data;
}
}
if (changes.length) {
this.fireChanged(...changes);
const boardDetails = await this.getBoardDetailsSafe(fqbn);
if (!boardDetails) {
return BoardsDataStore.Data.EMPTY;
}
}),
this.onDidChange((event) => {
const selectedFqbn =
this.boardsServiceProvider.boardsConfig.selectedBoard?.fqbn;
if (event.changes.find((change) => change.fqbn === selectedFqbn)) {
this.updateSelectedBoardData(selectedFqbn);
data = { configOptions: boardDetails.configOptions, programmers: boardDetails.programmers };
await this.storageService.setData(key, data);
return data;
}
async selectProgrammer(
{ fqbn, selectedProgrammer }: { fqbn: string, selectedProgrammer: Programmer },
boardsPackageVersion: MaybePromise<Installable.Version | undefined> = this.getBoardsPackageVersion(fqbn)): Promise<boolean> {
const data = deepClone(await this.getData(fqbn, boardsPackageVersion));
const { programmers } = data;
if (!programmers.find(p => Programmer.equals(selectedProgrammer, p))) {
return false;
}
}),
]);
Promise.all([
this.boardsServiceProvider.ready,
this.appStateService.reachedState('ready'),
]).then(() =>
this.updateSelectedBoardData(
this.boardsServiceProvider.boardsConfig.selectedBoard?.fqbn
)
);
}
private async getSelectedBoardData(
fqbn: string | undefined
): Promise<BoardsDataStoreChange | undefined> {
if (!fqbn) {
return undefined;
} else {
const data = await this.getData(sanitizeFqbn(fqbn));
if (data === BoardsDataStore.Data.EMPTY) {
return undefined;
}
return { fqbn, data };
}
}
private async updateSelectedBoardData(
fqbn: string | undefined,
updateConfigOptions = false
): Promise<void> {
this._selectedBoardData = await this.getSelectedBoardData(fqbn);
if (fqbn && updateConfigOptions) {
const { options } = new FQBN(fqbn);
if (options) {
const optionsToUpdate = Object.entries(options).map(([key, value]) => ({
option: key,
selectedValue: value,
}));
const params = { fqbn, optionsToUpdate };
await this.selectConfigOption(params);
this._selectedBoardData = await this.getSelectedBoardData(fqbn); // reload the updated data
}
}
}
onStop(): void {
this.toDispose.dispose();
}
registerCommands(registry: CommandRegistry): void {
registry.registerCommand(USE_INHERITED_DATA, {
execute: async (arg: unknown) => {
if (isBoardsDataStoreChange(arg)) {
await this.setData(arg);
this.fireChanged(arg);
const version = await boardsPackageVersion;
if (!version) {
return false;
}
},
});
}
tasks(): StartupTask[] {
if (!this._selectedBoardData) {
return [];
}
return [
{
command: USE_INHERITED_DATA.id,
args: [this._selectedBoardData],
},
];
}
get onDidChange(): Event<BoardsDataStoreChangeEvent> {
return this.onDidChangeEmitter.event;
}
async appendConfigToFqbn(
fqbn: string | undefined
): Promise<string | undefined> {
if (!fqbn) {
return undefined;
}
const { configOptions } = await this.getData(fqbn);
return new FQBN(fqbn).withConfigOptions(...configOptions).toString();
}
async getData(fqbn: string | undefined): Promise<BoardsDataStore.Data> {
if (!fqbn) {
return BoardsDataStore.Data.EMPTY;
await this.setData({ fqbn, data: { ...data, selectedProgrammer }, version });
this.fireChanged();
return true;
}
const key = this.getStorageKey(fqbn);
const storedData = await this.storageService.getData<
BoardsDataStore.Data | undefined
>(key, undefined);
if (BoardsDataStore.Data.is(storedData)) {
return storedData;
}
async selectConfigOption(
{ fqbn, option, selectedValue }: { fqbn: string, option: string, selectedValue: string },
boardsPackageVersion: MaybePromise<Installable.Version | undefined> = this.getBoardsPackageVersion(fqbn)): Promise<boolean> {
const boardDetails = await this.loadBoardDetails(fqbn);
if (!boardDetails) {
return BoardsDataStore.Data.EMPTY;
}
const data = createDataStoreEntry(boardDetails);
await this.storageService.setData(key, data);
return data;
}
async reloadBoardData(fqbn: string | undefined): Promise<void> {
if (!fqbn) {
return;
}
const key = this.getStorageKey(fqbn);
const details = await this.loadBoardDetails(fqbn, true);
if (!details) {
return;
}
const data = createDataStoreEntry(details);
await this.storageService.setData(key, data);
this.fireChanged({ fqbn, data });
}
async selectProgrammer({
fqbn,
selectedProgrammer,
}: {
fqbn: string;
selectedProgrammer: Programmer;
}): Promise<boolean> {
const sanitizedFQBN = sanitizeFqbn(fqbn);
const storedData = deepClone(await this.getData(sanitizedFQBN));
const { programmers } = storedData;
if (!programmers.find((p) => Programmer.equals(selectedProgrammer, p))) {
return false;
}
const change: BoardsDataStoreChange = {
fqbn: sanitizedFQBN,
data: { ...storedData, selectedProgrammer },
};
await this.setData(change);
this.fireChanged(change);
return true;
}
async selectConfigOption(params: SelectConfigOptionParams): Promise<boolean> {
const { fqbn, optionsToUpdate } = params;
if (!optionsToUpdate.length) {
return false;
}
const sanitizedFQBN = sanitizeFqbn(fqbn);
const mutableData = deepClone(await this.getData(sanitizedFQBN));
let didChange = false;
for (const { option, selectedValue } of optionsToUpdate) {
const { configOptions } = mutableData;
const configOption = configOptions.find((c) => c.option === option);
if (configOption) {
const configOptionValueIndex = configOption.values.findIndex(
(configOptionValue) => configOptionValue.value === selectedValue
);
if (configOptionValueIndex >= 0) {
// unselect all
configOption.values
.map((value) => value as Mutable<ConfigValue>)
.forEach((value) => (value.selected = false));
const mutableConfigValue: Mutable<ConfigValue> =
configOption.values[configOptionValueIndex];
// make the new value `selected`
mutableConfigValue.selected = true;
didChange = true;
const data = deepClone(await this.getData(fqbn, boardsPackageVersion));
const { configOptions } = data;
const configOption = configOptions.find(c => c.option === option);
if (!configOption) {
return false;
}
}
let updated = false;
for (const value of configOption.values) {
if (value.value === selectedValue) {
(value as any).selected = true;
updated = true;
} else {
(value as any).selected = false;
}
}
if (!updated) {
return false;
}
const version = await boardsPackageVersion;
if (!version) {
return false;
}
await this.setData({ fqbn, data, version });
this.fireChanged();
return true;
}
if (!didChange) {
return false;
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);
}
const change: BoardsDataStoreChange = {
fqbn: sanitizedFQBN,
data: mutableData,
};
await this.setData(change);
this.fireChanged(change);
return true;
}
protected async setData(change: BoardsDataStoreChange): Promise<void> {
const { fqbn, data } = change;
const key = this.getStorageKey(fqbn);
return this.storageService.setData(key, data);
}
protected getStorageKey(fqbn: string): string {
return `.arduinoIDE-configOptions-${fqbn}`;
}
async loadBoardDetails(
fqbn: string,
forceRefresh = false
): Promise<BoardDetails | undefined> {
try {
const details = await this.boardsService.getBoardDetails({
fqbn,
forceRefresh,
});
return details;
} catch (err) {
if (
err instanceof Error &&
err.message.includes('loading board data') &&
err.message.includes('is not installed')
) {
this.logger.warn(
`The boards package is not installed for board with FQBN: ${fqbn}`
);
} else {
this.logger.error(
`An unexpected error occurred while retrieving the board details for ${fqbn}.`,
err
);
}
return undefined;
protected getStorageKey(fqbn: string, version: Installable.Version): string {
return `.arduinoProIDE-configOptions-${version}-${fqbn}`;
}
protected async getBoardDetailsSafe(fqbn: string): Promise<BoardDetails | undefined> {
try {
const details = this.boardsService.getBoardDetails({ fqbn });
return details;
} catch (err) {
if (err instanceof Error && err.message.includes('loading board data') && err.message.includes('is not installed')) {
this.logger.warn(`The boards package is not installed for board with FQBN: ${fqbn}`);
} else {
this.logger.error(`An unexpected error occurred while retrieving the board details for ${fqbn}.`, err);
}
return undefined;
}
}
protected fireChanged(): void {
this.onChangedEmitter.fire();
}
protected async getBoardsPackageVersion(fqbn: string): Promise<Installable.Version | undefined> {
if (!fqbn) {
return undefined;
}
const boardsPackage = await this.boardsService.getContainerBoardPackage({ fqbn });
if (!boardsPackage) {
return undefined;
}
return boardsPackage.installedVersion;
}
}
protected fireChanged(...changes: BoardsDataStoreChange[]): void {
this.onDidChangeEmitter.fire({ changes });
}
}
export namespace BoardsDataStore {
export interface Data {
readonly configOptions: ConfigOption[];
readonly programmers: Programmer[];
readonly selectedProgrammer?: Programmer;
readonly defaultProgrammerId?: string;
}
export namespace Data {
export const EMPTY: Data = deepFreeze({
configOptions: [],
programmers: [],
});
export function is(arg: unknown): arg is Data {
return (
typeof arg === 'object' &&
arg !== null &&
Array.isArray((<Data>arg).configOptions) &&
Array.isArray((<Data>arg).programmers) &&
((<Data>arg).selectedProgrammer === undefined ||
isProgrammer((<Data>arg).selectedProgrammer)) &&
((<Data>arg).defaultProgrammerId === undefined ||
typeof (<Data>arg).defaultProgrammerId === 'string')
);
export interface Data {
readonly configOptions: ConfigOption[];
readonly programmers: Programmer[];
readonly selectedProgrammer?: Programmer;
}
export namespace Data {
export const EMPTY: Data = {
configOptions: [],
programmers: []
};
}
}
}
export function isEmptyData(data: BoardsDataStore.Data): boolean {
return (
Boolean(!data.configOptions.length) &&
Boolean(!data.programmers.length) &&
Boolean(!data.selectedProgrammer) &&
Boolean(!data.defaultProgrammerId)
);
}
export function findDefaultProgrammer(
programmers: readonly Programmer[],
defaultProgrammerId: string | undefined | BoardsDataStore.Data
): Programmer | undefined {
if (!defaultProgrammerId) {
return undefined;
}
const id =
typeof defaultProgrammerId === 'string'
? defaultProgrammerId
: defaultProgrammerId.defaultProgrammerId;
return programmers.find((p) => p.id === id);
}
function createDataStoreEntry(details: BoardDetails): BoardsDataStore.Data {
const configOptions = details.configOptions.slice();
const programmers = details.programmers.slice();
const { defaultProgrammerId } = details;
const selectedProgrammer = findDefaultProgrammer(
programmers,
defaultProgrammerId
);
const data = {
configOptions,
programmers,
...(selectedProgrammer ? { selectedProgrammer } : {}),
...(defaultProgrammerId ? { defaultProgrammerId } : {}),
};
return data;
}
export interface BoardsDataStoreChange {
readonly fqbn: string;
readonly data: BoardsDataStore.Data;
}
function isBoardsDataStoreChange(arg: unknown): arg is BoardsDataStoreChange {
return (
typeof arg === 'object' &&
arg !== null &&
typeof (<BoardsDataStoreChange>arg).fqbn === 'string' &&
BoardsDataStore.Data.is((<BoardsDataStoreChange>arg).data)
);
}
export interface BoardsDataStoreChangeEvent {
readonly changes: readonly BoardsDataStoreChange[];
}
const USE_INHERITED_DATA: Command = {
id: 'arduino-use-inherited-boards-data',
};

View File

@ -1,91 +1,27 @@
import {
inject,
injectable,
postConstruct,
} from '@theia/core/shared/inversify';
import {
BoardSearch,
BoardsPackage,
BoardsService,
} from '../../common/protocol/boards-service';
import { inject, injectable } from 'inversify';
import { BoardsPackage, BoardsService } from '../../common/protocol/boards-service';
import { ListWidget } from '../widgets/component-list/list-widget';
import { ListItemRenderer } from '../widgets/component-list/list-item-renderer';
import { nls } from '@theia/core/lib/common';
import { BoardsFilterRenderer } from '../widgets/component-list/filter-renderer';
@injectable()
export class BoardsListWidget extends ListWidget<BoardsPackage, BoardSearch> {
static WIDGET_ID = 'boards-list-widget';
static WIDGET_LABEL = nls.localize('arduino/boardsManager', 'Boards Manager');
export class BoardsListWidget extends ListWidget<BoardsPackage> {
constructor(
@inject(BoardsService) service: BoardsService,
@inject(ListItemRenderer) itemRenderer: ListItemRenderer<BoardsPackage>,
@inject(BoardsFilterRenderer) filterRenderer: BoardsFilterRenderer
) {
super({
id: BoardsListWidget.WIDGET_ID,
label: BoardsListWidget.WIDGET_LABEL,
iconClass: 'fa fa-arduino-boards',
searchable: service,
installable: service,
itemLabel: (item: BoardsPackage) => item.name,
itemRenderer,
filterRenderer,
defaultSearchOptions: { query: '', type: 'All' },
});
}
static WIDGET_ID = 'boards-list-widget';
static WIDGET_LABEL = 'Boards Manager';
@postConstruct()
protected override init(): void {
super.init();
this.toDispose.pushAll([
this.notificationCenter.onPlatformDidInstall(() =>
this.refresh(undefined)
),
this.notificationCenter.onPlatformDidUninstall(() =>
this.refresh(undefined)
),
]);
}
constructor(
@inject(BoardsService) protected service: BoardsService,
@inject(ListItemRenderer) protected itemRenderer: ListItemRenderer<BoardsPackage>) {
protected override async install({
item,
progressId,
version,
}: {
item: BoardsPackage;
progressId: string;
version: string;
}): Promise<void> {
await super.install({ item, progressId, version });
this.messageService.info(
nls.localize(
'arduino/board/succesfullyInstalledPlatform',
'Successfully installed platform {0}:{1}',
item.name,
version
),
{ timeout: 3000 }
);
}
super({
id: BoardsListWidget.WIDGET_ID,
label: BoardsListWidget.WIDGET_LABEL,
iconClass: 'fa fa-microchip',
searchable: service,
installable: service,
itemLabel: (item: BoardsPackage) => item.name,
itemRenderer
});
}
protected override async uninstall({
item,
progressId,
}: {
item: BoardsPackage;
progressId: string;
}): Promise<void> {
await super.uninstall({ item, progressId });
this.messageService.info(
nls.localize(
'arduino/board/succesfullyUninstalledPlatform',
'Successfully uninstalled platform {0}:{1}',
item.name,
item.installedVersion!
),
{ timeout: 3000 }
);
}
}

View File

@ -0,0 +1,430 @@
import { injectable, inject, optional } from 'inversify';
import { Emitter } from '@theia/core/lib/common/event';
import { ILogger } from '@theia/core/lib/common/logger';
import { MessageService } from '@theia/core/lib/common/message-service';
import { StorageService } from '@theia/core/lib/browser/storage-service';
import { FrontendApplicationContribution } from '@theia/core/lib/browser/frontend-application';
import { RecursiveRequired } from '../../common/types';
import { BoardsServiceClient, AttachedBoardsChangeEvent, BoardInstalledEvent, Board, Port, BoardUninstalledEvent, BoardsService } from '../../common/protocol';
import { BoardsConfig } from './boards-config';
import { naturalCompare } from '../../common/utils';
import { compareAnything } from '../theia/monaco/comparers';
interface BoardMatch {
readonly board: Board & Readonly<{ packageName: string }>;
readonly matches: monaco.filters.IMatch[] | undefined;
}
@injectable()
export class BoardsServiceClientImpl implements BoardsServiceClient, FrontendApplicationContribution {
@inject(ILogger)
protected logger: ILogger;
@optional()
@inject(MessageService)
protected messageService: MessageService;
@inject(StorageService)
protected storageService: StorageService;
protected readonly onBoardsPackageInstalledEmitter = new Emitter<BoardInstalledEvent>();
protected readonly onBoardsPackageUninstalledEmitter = new Emitter<BoardUninstalledEvent>();
protected readonly onAttachedBoardsChangedEmitter = new Emitter<AttachedBoardsChangeEvent>();
protected readonly onBoardsConfigChangedEmitter = new Emitter<BoardsConfig.Config>();
protected readonly onAvailableBoardsChangedEmitter = new Emitter<AvailableBoard[]>();
/**
* Used for the auto-reconnecting. Sometimes, the attached board gets disconnected after uploading something to it.
* It happens with certain boards on Windows. For example, the `MKR1000` boards is selected on post `COM5` on Windows,
* perform an upload, the board automatically disconnects and reconnects, but on another port, `COM10`.
* We have to listen on such changes and auto-reconnect the same board on another port.
* See: https://arduino.slack.com/archives/CJJHJCJSJ/p1568645417013000?thread_ts=1568640504.009400&cid=CJJHJCJSJ
*/
protected latestValidBoardsConfig: RecursiveRequired<BoardsConfig.Config> | undefined = undefined;
protected _boardsConfig: BoardsConfig.Config = {};
protected _attachedBoards: Board[] = []; // This does not contain the `Unknown` boards. They're visible from the available ports only.
protected _availablePorts: Port[] = [];
protected _availableBoards: AvailableBoard[] = [];
protected boardsService: BoardsService;
/**
* Event when the state of the attached/detached boards has changed. For instance, the user have detached a physical board.
*/
readonly onAttachedBoardsChanged = this.onAttachedBoardsChangedEmitter.event;
readonly onBoardsPackageInstalled = this.onBoardsPackageInstalledEmitter.event;
readonly onBoardsPackageUninstalled = this.onBoardsPackageUninstalledEmitter.event;
/**
* Unlike `onAttachedBoardsChanged` this even fires when the user modifies the selected board in the IDE.\
* This even also fires, when the boards package was not available for the currently selected board,
* and the user installs the board package. Note: installing a board package will set the `fqbn` of the
* currently selected board.\
* This even also emitted when the board package for the currently selected board was uninstalled.
*/
readonly onBoardsConfigChanged = this.onBoardsConfigChangedEmitter.event;
readonly onAvailableBoardsChanged = this.onAvailableBoardsChangedEmitter.event;
async onStart(): Promise<void> {
return this.loadState();
}
/**
* When the FE connects to the BE, the BE stets the known boards and ports.\
* This is a DI workaround for not being able to inject the service into the client.
*/
async init(boardsService: BoardsService): Promise<void> {
this.boardsService = boardsService;
const [attachedBoards, availablePorts] = await Promise.all([
this.boardsService.getAttachedBoards(),
this.boardsService.getAvailablePorts()
]);
this._attachedBoards = attachedBoards;
this._availablePorts = availablePorts;
this.reconcileAvailableBoards().then(() => this.tryReconnect());
}
notifyAttachedBoardsChanged(event: AttachedBoardsChangeEvent): void {
this.logger.info('Attached boards and available ports changed: ', JSON.stringify(event));
this._attachedBoards = event.newState.boards;
this.onAttachedBoardsChangedEmitter.fire(event);
this._availablePorts = event.newState.ports;
this.reconcileAvailableBoards().then(() => this.tryReconnect());
}
protected async tryReconnect(): Promise<boolean> {
if (this.latestValidBoardsConfig && !this.canUploadTo(this.boardsConfig)) {
for (const board of this.availableBoards.filter(({ state }) => state !== AvailableBoard.State.incomplete)) {
if (this.latestValidBoardsConfig.selectedBoard.fqbn === board.fqbn
&& this.latestValidBoardsConfig.selectedBoard.name === board.name
&& Port.sameAs(this.latestValidBoardsConfig.selectedPort, board.port)) {
this.boardsConfig = this.latestValidBoardsConfig;
return true;
}
}
// If we could not find an exact match, we compare the board FQBN-name pairs and ignore the port, as it might have changed.
// See documentation on `latestValidBoardsConfig`.
for (const board of this.availableBoards.filter(({ state }) => state !== AvailableBoard.State.incomplete)) {
if (this.latestValidBoardsConfig.selectedBoard.fqbn === board.fqbn
&& this.latestValidBoardsConfig.selectedBoard.name === board.name) {
this.boardsConfig = {
...this.latestValidBoardsConfig,
selectedPort: board.port
};
return true;
}
}
}
return false;
}
notifyBoardInstalled(event: BoardInstalledEvent): void {
this.logger.info('Board installed: ', JSON.stringify(event));
this.onBoardsPackageInstalledEmitter.fire(event);
const { selectedBoard } = this.boardsConfig;
const { installedVersion, id } = event.pkg;
if (selectedBoard) {
const installedBoard = event.pkg.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
};
}
}
}
notifyBoardUninstalled(event: BoardUninstalledEvent): void {
this.logger.info('Board uninstalled: ', JSON.stringify(event));
this.onBoardsPackageUninstalledEmitter.fire(event);
const { selectedBoard } = this.boardsConfig;
if (selectedBoard && selectedBoard.fqbn) {
const uninstalledBoard = event.pkg.boards.find(({ name }) => name === selectedBoard.name);
if (uninstalledBoard && uninstalledBoard.fqbn === selectedBoard.fqbn) {
this.logger.info(`Board package ${event.pkg.id} was uninstalled. Discarding the FQBN of the currently selected ${selectedBoard.name} board.`);
const selectedBoardWithoutFqbn = {
name: selectedBoard.name
// No FQBN
};
this.boardsConfig = {
...this.boardsConfig,
selectedBoard: selectedBoardWithoutFqbn
};
}
}
}
set boardsConfig(config: BoardsConfig.Config) {
this.doSetBoardsConfig(config);
this.saveState().finally(() => this.reconcileAvailableBoards().finally(() => this.onBoardsConfigChangedEmitter.fire(this._boardsConfig)));
}
protected doSetBoardsConfig(config: BoardsConfig.Config): void {
this.logger.info('Board config changed: ', JSON.stringify(config));
this._boardsConfig = config;
if (this.canUploadTo(this._boardsConfig)) {
this.latestValidBoardsConfig = this._boardsConfig;
}
}
async searchBoards({ query, cores }: { query?: string, cores?: string[] }): Promise<Array<Board & { packageName: string }>> {
const boards = await this.boardsService.allBoards({});
const coresFilter = !!cores && cores.length
? ((toFilter: { packageName: string }) => cores.some(core => core === toFilter.packageName))
: () => true;
if (!query) {
return boards.filter(coresFilter).sort(Board.compare);
}
const toMatch = ((toFilter: Board & { packageName: string }) => (({ board: toFilter, matches: monaco.filters.matchesFuzzy(query, toFilter.name, true) })));
const compareEntries = (left: BoardMatch, right: BoardMatch, lookFor: string) => {
const leftMatches = left.matches || [];
const rightMatches = right.matches || [];
if (leftMatches.length && !rightMatches.length) {
return -1;
}
if (!leftMatches.length && rightMatches.length) {
return 1;
}
if (leftMatches.length === 0 && rightMatches.length === 0) {
return 0;
}
const leftLabel = left.board.name.replace(/\r?\n/g, ' ');
const rightLabel = right.board.name.replace(/\r?\n/g, ' ');
return compareAnything(leftLabel, rightLabel, lookFor);
}
const normalizedQuery = query.toLowerCase();
return boards
.filter(coresFilter)
.map(toMatch)
.filter(({ matches }) => !!matches)
.sort((left, right) => compareEntries(left, right, normalizedQuery))
.map(({ board }) => board);
}
get boardsConfig(): BoardsConfig.Config {
return this._boardsConfig;
}
/**
* `true` if the `config.selectedBoard` is defined; hence can compile against the board. Otherwise, `false`.
*/
canVerify(
config: BoardsConfig.Config | undefined = this.boardsConfig,
options: { silent: boolean } = { silent: true }): config is BoardsConfig.Config & { selectedBoard: Board } {
if (!config) {
return false;
}
if (!config.selectedBoard) {
if (!options.silent && this.messageService) {
this.messageService.warn('No boards selected.', { timeout: 3000 });
}
return false;
}
return true;
}
/**
* `true` if `canVerify`, the board has an FQBN and the `config.selectedPort` is also set, hence can upload to board. Otherwise, `false`.
*/
canUploadTo(
config: BoardsConfig.Config | undefined = this.boardsConfig,
options: { silent: boolean } = { silent: true }): config is RecursiveRequired<BoardsConfig.Config> {
if (!this.canVerify(config, options)) {
return false;
}
const { name } = config.selectedBoard;
if (!config.selectedPort) {
if (!options.silent && this.messageService) {
this.messageService.warn(`No ports selected for board: '${name}'.`, { timeout: 3000 });
}
return false;
}
if (!config.selectedBoard.fqbn) {
if (!options.silent && this.messageService) {
this.messageService.warn(`The FQBN is not available for the selected board ${name}. Do you have the corresponding core installed?`, { timeout: 3000 });
}
return false;
}
return true;
}
get availableBoards(): AvailableBoard[] {
return this._availableBoards;
}
protected async reconcileAvailableBoards(): Promise<void> {
const attachedBoards = this._attachedBoards;
const availablePorts = this._availablePorts;
// Unset the port on the user's config, if it is not available anymore.
if (this.boardsConfig.selectedPort && !availablePorts.some(port => Port.sameAs(port, this.boardsConfig.selectedPort))) {
this.doSetBoardsConfig({ selectedBoard: this.boardsConfig.selectedBoard, selectedPort: undefined });
this.onBoardsConfigChangedEmitter.fire(this._boardsConfig);
}
const boardsConfig = this.boardsConfig;
const currentAvailableBoards = this._availableBoards;
const availableBoards: AvailableBoard[] = [];
const availableBoardPorts = availablePorts.filter(Port.isBoardPort);
const attachedSerialBoards = attachedBoards.filter(({ port }) => !!port);
for (const boardPort of availableBoardPorts) {
let state = AvailableBoard.State.incomplete; // Initial pessimism.
let board = attachedSerialBoards.find(({ port }) => Port.sameAs(boardPort, port));
if (board) {
state = AvailableBoard.State.recognized;
} else {
// If the selected board is not recognized because it is a 3rd party board: https://github.com/arduino/arduino-cli/issues/623
// We still want to show it without the red X in the boards toolbar: https://github.com/arduino/arduino-pro-ide/issues/198#issuecomment-599355836
const lastSelectedBoard = await this.getLastSelectedBoardOnPort(boardPort);
if (lastSelectedBoard) {
board = {
...lastSelectedBoard,
port: boardPort
};
state = AvailableBoard.State.guessed;
}
}
if (!board) {
availableBoards.push({ name: 'Unknown', port: boardPort, state });
} else {
const selected = BoardsConfig.Config.sameAs(boardsConfig, board);
availableBoards.push({ ...board, state, selected, port: boardPort });
}
}
if (boardsConfig.selectedBoard && !availableBoards.some(({ selected }) => selected)) {
availableBoards.push({
...boardsConfig.selectedBoard,
port: boardsConfig.selectedPort,
selected: true,
state: AvailableBoard.State.incomplete
});
}
const sortedAvailableBoards = availableBoards.sort(AvailableBoard.compare);
let hasChanged = sortedAvailableBoards.length !== currentAvailableBoards.length;
for (let i = 0; !hasChanged && i < sortedAvailableBoards.length; i++) {
hasChanged = AvailableBoard.compare(sortedAvailableBoards[i], currentAvailableBoards[i]) !== 0;
}
if (hasChanged) {
this._availableBoards = sortedAvailableBoards;
this.onAvailableBoardsChangedEmitter.fire(this._availableBoards);
}
}
protected async getLastSelectedBoardOnPort(port: Port | string | undefined): Promise<Board | undefined> {
if (!port) {
return undefined;
}
const key = this.getLastSelectedBoardOnPortKey(port);
return this.storageService.getData<Board>(key);
}
protected async saveState(): Promise<void> {
// We save the port with the selected board name/FQBN, to be able to guess a better board name.
// Required when the attached board belongs to a 3rd party boards package, and neither the name, nor
// the FQBN can be retrieved with a `board list` command.
// https://github.com/arduino/arduino-cli/issues/623
const { selectedBoard, selectedPort } = this.boardsConfig;
if (selectedBoard && selectedPort) {
const key = this.getLastSelectedBoardOnPortKey(selectedPort);
await this.storageService.setData(key, selectedBoard);
}
await this.storageService.setData('latest-valid-boards-config', this.latestValidBoardsConfig);
}
protected getLastSelectedBoardOnPortKey(port: Port | string): string {
// TODO: we lose the port's `protocol` info (`serial`, `network`, etc.) here if the `port` is a `string`.
return `last-selected-board-on-port:${typeof port === 'string' ? port : Port.toString(port)}`;
}
protected async loadState(): Promise<void> {
const storedValidBoardsConfig = await this.storageService.getData<RecursiveRequired<BoardsConfig.Config>>('latest-valid-boards-config');
if (storedValidBoardsConfig) {
this.latestValidBoardsConfig = storedValidBoardsConfig;
if (this.canUploadTo(this.latestValidBoardsConfig)) {
this.boardsConfig = this.latestValidBoardsConfig;
}
}
}
}
/**
* Representation of a ready-to-use board, either the user has configured it or was automatically recognized by the CLI.
* An available board was not necessarily recognized by the CLI (e.g.: it is a 3rd party board) or correctly configured but ready for `verify`.
* If it has the selected board and a associated port, it can be used for `upload`. We render an available board for the user
* when it has the `port` set.
*/
export interface AvailableBoard extends Board {
readonly state: AvailableBoard.State;
readonly selected?: boolean;
readonly port?: Port;
}
export namespace AvailableBoard {
export enum State {
/**
* Retrieved from the CLI via the `board list` command.
*/
'recognized',
/**
* Guessed the name/FQBN of the board from the available board ports (3rd party).
*/
'guessed',
/**
* We do not know anything about this board, probably a 3rd party. The user has not selected a board for this port yet.
*/
'incomplete'
}
export function is(board: any): board is AvailableBoard {
return Board.is(board) && 'state' in board;
}
export function hasPort(board: AvailableBoard): board is AvailableBoard & { port: Port } {
return !!board.port;
}
export const compare = (left: AvailableBoard, right: AvailableBoard) => {
if (left.selected && !right.selected) {
return -1;
}
if (right.selected && !left.selected) {
return 1;
}
let result = naturalCompare(left.name, right.name);
if (result !== 0) {
return result;
}
if (left.fqbn && right.fqbn) {
result = naturalCompare(left.fqbn, right.fqbn);
if (result !== 0) {
return result;
}
}
if (left.port && right.port) {
result = Port.compare(left.port, right.port);
if (result !== 0) {
return result;
}
}
if (!!left.selected && !right.selected) {
return -1;
}
if (!!right.selected && !left.selected) {
return 1;
}
return left.state - right.state;
}
}

View File

@ -1,696 +0,0 @@
import { FrontendApplicationContribution } from '@theia/core/lib/browser/frontend-application-contribution';
import { FrontendApplicationStateService } from '@theia/core/lib/browser/frontend-application-state';
import { StorageService } from '@theia/core/lib/browser/storage-service';
import {
Command,
CommandContribution,
CommandRegistry,
CommandService,
} from '@theia/core/lib/common/command';
import type { Disposable } from '@theia/core/lib/common/disposable';
import { Emitter } from '@theia/core/lib/common/event';
import { ILogger } from '@theia/core/lib/common/logger';
import { MessageService } from '@theia/core/lib/common/message-service';
import { nls } from '@theia/core/lib/common/nls';
import { deepClone } from '@theia/core/lib/common/objects';
import { Deferred } from '@theia/core/lib/common/promise-util';
import type { Mutable } from '@theia/core/lib/common/types';
import { inject, injectable, optional } from '@theia/core/shared/inversify';
import {
OutputChannel,
OutputChannelManager,
} from '@theia/output/lib/browser/output-channel';
import {
BoardIdentifier,
BoardUserField,
BoardWithPackage,
BoardsConfig,
BoardsConfigChangeEvent,
BoardsPackage,
BoardsService,
DetectedPorts,
Port,
PortIdentifier,
boardIdentifierEquals,
emptyBoardsConfig,
isBoardIdentifier,
isBoardIdentifierChangeEvent,
isPortIdentifier,
isPortIdentifierChangeEvent,
portIdentifierEquals,
sanitizeFqbn,
serializePlatformIdentifier,
} from '../../common/protocol';
import {
BoardList,
BoardListHistory,
EditBoardsConfigActionParams,
SelectBoardsConfigActionParams,
createBoardList,
isBoardListHistory,
} from '../../common/protocol/board-list';
import type { Defined } from '../../common/types';
import type {
StartupTask,
StartupTaskProvider,
} from '../../electron-common/startup-task';
import { NotificationCenter } from '../notification-center';
const boardListHistoryStorageKey = 'arduino-ide:boardListHistory';
const selectedPortStorageKey = 'arduino-ide:selectedPort';
const selectedBoardStorageKey = 'arduino-ide:selectedBoard';
type UpdateBoardsConfigReason =
/**
* Restore previous state at IDE startup.
*/
| 'restore'
/**
* The board and the optional port were changed from the dialog.
*/
| 'dialog'
/**
* The board and the port were updated from the board select toolbar.
*/
| 'toolbar'
/**
* The board and port configuration was inherited from another window.
*/
| 'inherit';
interface RefreshBoardListParams {
detectedPorts?: DetectedPorts;
boardsConfig?: BoardsConfig;
boardListHistory?: BoardListHistory;
}
export type UpdateBoardsConfigParams =
| BoardIdentifier
/**
* `'unset-board'` is special case when a non installed board is selected (no FQBN), the platform is installed,
* but there is no way to determine the FQBN from the previous partial data, and IDE2 unsets the board.
*/
| 'unset-board'
| PortIdentifier
| (Readonly<Defined<BoardsConfig>> &
Readonly<{ reason?: UpdateBoardsConfigReason }>);
type HistoryDidNotChange = undefined;
type HistoryDidDelete = Readonly<{ [portKey: string]: undefined }>;
type HistoryDidUpdate = Readonly<{ [portKey: string]: BoardIdentifier }>;
type BoardListHistoryUpdateResult =
| HistoryDidNotChange
| HistoryDidDelete
| HistoryDidUpdate;
type BoardToSelect = BoardIdentifier | undefined | 'ignore-board';
type PortToSelect = PortIdentifier | undefined | 'ignore-port';
function sanitizeBoardToSelectFQBN(board: BoardToSelect): BoardToSelect {
if (isBoardIdentifier(board)) {
return sanitizeBoardIdentifierFQBN(board);
}
return board;
}
function sanitizeBoardIdentifierFQBN(board: BoardIdentifier): BoardIdentifier {
if (board.fqbn) {
const copy: Mutable<BoardIdentifier> = deepClone(board);
copy.fqbn = sanitizeFqbn(board.fqbn);
return copy;
}
return board;
}
interface UpdateBoardListHistoryParams {
readonly portToSelect: PortToSelect;
readonly boardToSelect: BoardToSelect;
}
interface UpdateBoardsDataParams {
readonly boardToSelect: BoardToSelect;
readonly reason?: UpdateBoardsConfigReason;
}
export interface SelectBoardsConfigAction {
(params: SelectBoardsConfigActionParams): void;
}
export interface EditBoardsConfigAction {
(params?: EditBoardsConfigActionParams): void;
}
export interface BoardListUIActions {
/**
* Sets the frontend's port and board configuration according to the params.
*/
readonly select: SelectBoardsConfigAction;
/**
* Opens up the boards config dialog with the port and (optional) board to select in the dialog.
* Calling this function does not immediately change the frontend's port and board config, but
* preselects items in the dialog.
*/
readonly edit: EditBoardsConfigAction;
}
export type BoardListUI = BoardList & BoardListUIActions;
export type BoardsConfigChangeEventUI = BoardsConfigChangeEvent &
Readonly<{ reason?: UpdateBoardsConfigReason }>;
@injectable()
export class BoardListDumper implements Disposable {
@inject(OutputChannelManager)
private readonly outputChannelManager: OutputChannelManager;
private outputChannel: OutputChannel | undefined;
dump(boardList: BoardList): void {
if (!this.outputChannel) {
this.outputChannel = this.outputChannelManager.getChannel(
'Developer (Arduino)'
);
}
this.outputChannel.show({ preserveFocus: true });
this.outputChannel.append(boardList.toString() + '\n');
}
dispose(): void {
this.outputChannel?.dispose();
}
}
@injectable()
export class BoardsServiceProvider
implements
FrontendApplicationContribution,
StartupTaskProvider,
CommandContribution
{
@inject(ILogger)
private readonly logger: ILogger;
@inject(MessageService)
private readonly messageService: MessageService;
@inject(BoardsService)
private readonly boardsService: BoardsService;
@inject(CommandService)
private readonly commandService: CommandService;
@inject(StorageService)
private readonly storageService: StorageService;
@inject(NotificationCenter)
private readonly notificationCenter: NotificationCenter;
@inject(FrontendApplicationStateService)
private readonly appStateService: FrontendApplicationStateService;
@optional()
@inject(BoardListDumper)
private readonly boardListDumper?: BoardListDumper;
private _boardsConfig = emptyBoardsConfig();
private _detectedPorts: DetectedPorts = {};
private _boardList = this.createBoardListUI(createBoardList({}));
private _boardListHistory: Mutable<BoardListHistory> = {};
private _ready = new Deferred<void>();
private readonly boardsConfigDidChangeEmitter =
new Emitter<BoardsConfigChangeEventUI>();
readonly onBoardsConfigDidChange = this.boardsConfigDidChangeEmitter.event;
private readonly boardListDidChangeEmitter = new Emitter<BoardListUI>();
/**
* Emits an event on board config (port or board) change, and when the discovery (`board list --watch`) detected any changes.
*/
readonly onBoardListDidChange = this.boardListDidChangeEmitter.event;
onStart(): void {
this.notificationCenter.onDetectedPortsDidChange(({ detectedPorts }) =>
this.refreshBoardList({ detectedPorts })
);
this.notificationCenter.onPlatformDidInstall((event) =>
this.maybeUpdateSelectedBoard(event)
);
this.appStateService
.reachedState('ready')
.then(async () => {
const [detectedPorts, storedState] = await Promise.all([
this.boardsService.getDetectedPorts(),
this.restoreState(),
]);
const { selectedBoard, selectedPort, boardListHistory } = storedState;
const options: RefreshBoardListParams = {
boardListHistory,
detectedPorts,
};
// If either the port or the board is set, restore it. Otherwise, do not restore nothing.
// It might override the inherited boards config from the other window on File > New Sketch
if (selectedBoard || selectedPort) {
options.boardsConfig = { selectedBoard, selectedPort };
}
this.refreshBoardList(options);
this._ready.resolve();
})
.finally(() => this._ready.resolve());
}
onStop(): void {
this.boardListDumper?.dispose();
}
registerCommands(registry: CommandRegistry): void {
registry.registerCommand(USE_INHERITED_CONFIG, {
execute: (
boardsConfig: BoardsConfig,
boardListHistory: BoardListHistory
) => {
if (boardListHistory) {
this._boardListHistory = boardListHistory;
}
this.update({ boardsConfig }, 'inherit');
},
});
if (this.boardListDumper) {
registry.registerCommand(DUMP_BOARD_LIST, {
execute: () => this.boardListDumper?.dump(this._boardList),
});
}
registry.registerCommand(CLEAR_BOARD_LIST_HISTORY, {
execute: () => {
this.refreshBoardList({ boardListHistory: {} });
this.setData(boardListHistoryStorageKey, undefined);
},
});
registry.registerCommand(CLEAR_BOARDS_CONFIG, {
execute: () => {
this.refreshBoardList({ boardsConfig: emptyBoardsConfig() });
Promise.all([
this.setData(selectedPortStorageKey, undefined),
this.setData(selectedBoardStorageKey, undefined),
]);
},
});
}
tasks(): StartupTask[] {
return [
{
command: USE_INHERITED_CONFIG.id,
args: [this._boardsConfig, this._boardListHistory],
},
];
}
private refreshBoardList(params?: RefreshBoardListParams): void {
if (params?.detectedPorts) {
this._detectedPorts = params.detectedPorts;
}
if (params?.boardsConfig) {
this._boardsConfig = params.boardsConfig;
}
if (params?.boardListHistory) {
this._boardListHistory = params.boardListHistory;
}
const boardList = createBoardList(
this._detectedPorts,
this._boardsConfig,
this._boardListHistory
);
this._boardList = this.createBoardListUI(boardList);
this.boardListDidChangeEmitter.fire(this._boardList);
}
private createBoardListUI(boardList: BoardList): BoardListUI {
return Object.assign(boardList, {
select: this.onBoardsConfigSelect.bind(this),
edit: this.onBoardsConfigEdit.bind(this),
});
}
private onBoardsConfigSelect(params: SelectBoardsConfigActionParams): void {
this.updateConfig({ ...params, reason: 'toolbar' });
}
private async onBoardsConfigEdit(
params?: EditBoardsConfigActionParams
): Promise<void> {
const boardsConfig = await this.commandService.executeCommand<
BoardsConfig | undefined
>('arduino-open-boards-dialog', params);
if (boardsConfig) {
this.update({ boardsConfig }, 'dialog');
}
}
private update(
params: RefreshBoardListParams,
reason?: UpdateBoardsConfigReason
): void {
const { boardsConfig } = params;
if (!boardsConfig) {
return;
}
const { selectedBoard, selectedPort } = boardsConfig;
if (selectedBoard && selectedPort) {
this.updateConfig({
selectedBoard,
selectedPort,
reason,
});
} else if (selectedBoard) {
this.updateConfig(selectedBoard);
} else if (selectedPort) {
this.updateConfig(selectedPort);
}
}
updateConfig(params: UpdateBoardsConfigParams): boolean {
const previousSelectedBoard = this._boardsConfig.selectedBoard;
const previousSelectedPort = this._boardsConfig.selectedPort;
const boardToSelect = this.getBoardToSelect(params);
const portToSelect = this.getPortToSelect(params);
const reason = this.getUpdateReason(params);
const boardDidChange =
boardToSelect !== 'ignore-board' &&
!boardIdentifierEquals(boardToSelect, previousSelectedBoard);
const portDidChange =
portToSelect !== 'ignore-port' &&
!portIdentifierEquals(portToSelect, previousSelectedPort);
const boardDidChangeEvent = boardDidChange
? // The change event must always contain any custom board options. Hence the board to select is not sanitized.
{ selectedBoard: boardToSelect, previousSelectedBoard }
: undefined;
const portDidChangeEvent = portDidChange
? { selectedPort: portToSelect, previousSelectedPort }
: undefined;
let event: BoardsConfigChangeEvent | undefined = boardDidChangeEvent;
if (portDidChangeEvent) {
if (event) {
event = {
...event,
...portDidChangeEvent,
};
} else {
event = portDidChangeEvent;
}
}
if (!event) {
return false;
}
// unlike for the board change event, every persistent state must not contain custom board config options in the FQBN
const sanitizedBoardToSelect = sanitizeBoardToSelectFQBN(boardToSelect);
this.maybeUpdateBoardListHistory({
portToSelect,
boardToSelect: sanitizedBoardToSelect,
});
this.maybeUpdateBoardsData({
boardToSelect: sanitizedBoardToSelect,
reason,
});
if (isBoardIdentifierChangeEvent(event)) {
this._boardsConfig.selectedBoard = event.selectedBoard
? sanitizeBoardIdentifierFQBN(event.selectedBoard)
: event.selectedBoard;
}
if (isPortIdentifierChangeEvent(event)) {
this._boardsConfig.selectedPort = event.selectedPort;
}
if (reason) {
event = Object.assign(event, { reason });
}
this.boardsConfigDidChangeEmitter.fire(event);
this.refreshBoardList();
this.saveState();
return true;
}
private getBoardToSelect(params: UpdateBoardsConfigParams): BoardToSelect {
if (isPortIdentifier(params)) {
return 'ignore-board';
}
if (params === 'unset-board') {
return undefined;
}
return isBoardIdentifier(params) ? params : params.selectedBoard;
}
private getPortToSelect(
params: UpdateBoardsConfigParams
): Exclude<PortToSelect, undefined> {
if (isBoardIdentifier(params) || params === 'unset-board') {
return 'ignore-port';
}
return isPortIdentifier(params) ? params : params.selectedPort;
}
private getUpdateReason(
params: UpdateBoardsConfigParams
): UpdateBoardsConfigReason | undefined {
if (
isBoardIdentifier(params) ||
isPortIdentifier(params) ||
params === 'unset-board'
) {
return undefined;
}
return params.reason;
}
get ready(): Promise<void> {
return this._ready.promise;
}
get boardsConfig(): BoardsConfig {
return this._boardsConfig;
}
get boardList(): BoardListUI {
return this._boardList;
}
get detectedPorts(): DetectedPorts {
return this._detectedPorts;
}
async searchBoards({
query,
}: {
query?: string;
cores?: string[];
}): Promise<BoardWithPackage[]> {
const boards = await this.boardsService.searchBoards({ query });
return boards;
}
async selectedBoardUserFields(): Promise<BoardUserField[]> {
if (!this._boardsConfig.selectedBoard) {
return [];
}
const fqbn = this._boardsConfig.selectedBoard.fqbn;
if (!fqbn) {
return [];
}
// Protocol must be set to `default` when uploading without a port selected:
// https://arduino.github.io/arduino-cli/dev/platform-specification/#sketch-upload-configuration
const protocol = this._boardsConfig.selectedPort?.protocol || 'default';
return await this.boardsService.getBoardUserFields({ fqbn, protocol });
}
private async maybeUpdateSelectedBoard(platformDidInstallEvent: {
item: BoardsPackage;
}): Promise<void> {
const { selectedBoard } = this._boardsConfig;
if (
selectedBoard &&
!selectedBoard.fqbn &&
BoardWithPackage.is(selectedBoard)
) {
const selectedBoardPlatformId = serializePlatformIdentifier(
selectedBoard.packageId
);
if (selectedBoardPlatformId === platformDidInstallEvent.item.id) {
const installedSelectedBoard = platformDidInstallEvent.item.boards.find(
(board) => board.name === selectedBoard.name
);
// if the board can be found by its name after the install event select it. otherwise unselect it
// historical hint: https://github.com/arduino/arduino-ide/blob/144df893d0dafec64a26565cf912a98f32572da9/arduino-ide-extension/src/browser/boards/boards-service-provider.ts#L289-L320
this.updateConfig(
installedSelectedBoard ? installedSelectedBoard : 'unset-board'
);
if (!installedSelectedBoard) {
const yes = nls.localize('vscode/extensionsUtils/yes', 'Yes');
const answer = await this.messageService.warn(
nls.localize(
'arduino/board/couldNotFindPreviouslySelected',
"Could not find previously selected board '{0}' in installed platform '{1}'. Please manually reselect the board you want to use. Do you want to reselect it now?",
selectedBoard.name,
platformDidInstallEvent.item.name
),
nls.localize('arduino/board/reselectLater', 'Reselect later'),
yes
);
if (answer === yes) {
this.onBoardsConfigEdit({
query: selectedBoard.name,
portToSelect: this._boardsConfig.selectedPort,
});
}
}
}
}
}
private maybeUpdateBoardListHistory(
params: UpdateBoardListHistoryParams
): BoardListHistoryUpdateResult {
const { portToSelect, boardToSelect } = params;
const selectedPort = isPortIdentifier(portToSelect)
? portToSelect
: portToSelect === 'ignore-port'
? this._boardsConfig.selectedPort
: undefined;
const selectedBoard = isBoardIdentifier(boardToSelect)
? boardToSelect
: boardToSelect === 'ignore-board'
? this._boardsConfig.selectedBoard
: undefined;
if (selectedBoard && selectedPort) {
const match = this.boardList.items.find(
(item) =>
portIdentifierEquals(item.port, selectedPort) &&
item.board &&
boardIdentifierEquals(item.board, selectedBoard)
);
const portKey = Port.keyOf(selectedPort);
if (match) {
// When board `B` is detected on port `P` and saving `B` on `P`, remove the entry instead!
delete this._boardListHistory[portKey];
} else {
this._boardListHistory[portKey] = selectedBoard;
}
if (match) {
return { [portKey]: undefined };
}
return { [portKey]: selectedBoard };
}
return undefined;
}
private maybeUpdateBoardsData(params: UpdateBoardsDataParams): void {
const { boardToSelect, reason } = params;
if (
boardToSelect &&
boardToSelect !== 'ignore-board' &&
boardToSelect.fqbn &&
(reason === 'toolbar' || reason === 'inherit')
) {
const [, , , ...rest] = boardToSelect.fqbn.split(':');
if (rest.length) {
// https://github.com/arduino/arduino-ide/pull/2113
// TODO: save update data store if reason is toolbar and the FQBN has options
}
}
}
private async saveState(): Promise<void> {
const { selectedBoard, selectedPort } = this.boardsConfig;
await Promise.all([
this.setData(
selectedBoardStorageKey,
selectedBoard ? JSON.stringify(selectedBoard) : undefined
),
this.setData(
selectedPortStorageKey,
selectedPort ? JSON.stringify(selectedPort) : undefined
),
this.setData(
boardListHistoryStorageKey,
JSON.stringify(this._boardListHistory)
),
]);
}
private async restoreState(): Promise<
Readonly<BoardsConfig> & { boardListHistory: BoardListHistory | undefined }
> {
const [maybeSelectedBoard, maybeSelectedPort, maybeBoardHistory] =
await Promise.all([
this.getData<string>(selectedBoardStorageKey),
this.getData<string>(selectedPortStorageKey),
this.getData<string>(boardListHistoryStorageKey),
]);
const selectedBoard = this.tryParse(maybeSelectedBoard, isBoardIdentifier);
const selectedPort = this.tryParse(maybeSelectedPort, isPortIdentifier);
const boardListHistory = this.tryParse(
maybeBoardHistory,
isBoardListHistory
);
return { selectedBoard, selectedPort, boardListHistory };
}
private tryParse<T>(
raw: string | undefined,
typeGuard: (object: unknown) => object is T
): T | undefined {
if (!raw) {
return undefined;
}
try {
const object = JSON.parse(raw);
if (typeGuard(object)) {
return object;
}
} catch {
this.logger.error(`Failed to parse raw: '${raw}'`);
}
return undefined;
}
private setData<T>(key: string, value: T): Promise<void> {
return this.storageService.setData(key, value);
}
private getData<T>(key: string): Promise<T | undefined> {
return this.storageService.getData(key);
}
}
/**
* It should be neither visible nor called from outside.
*
* This service creates a startup task with the current board config and
* passes the task to the electron-main process so that the new window
* can inherit the boards config state of this service.
*
* Note that the state is always set, but new windows might ignore it.
* For example, the new window already has a valid boards config persisted to the local storage.
*/
const USE_INHERITED_CONFIG: Command = {
id: 'arduino-use-inherited-boards-config',
};
const DUMP_BOARD_LIST: Command = {
id: 'arduino-dump-board-list',
label: nls.localize('arduino/developer/dumpBoardList', 'Dump the Board List'),
category: 'Developer (Arduino)',
};
const CLEAR_BOARD_LIST_HISTORY: Command = {
id: 'arduino-clear-board-list-history',
label: nls.localize(
'arduino/developer/clearBoardList',
'Clear the Board List History'
),
category: 'Developer (Arduino)',
};
const CLEAR_BOARDS_CONFIG: Command = {
id: 'arduino-clear-boards-config',
label: nls.localize(
'arduino/developer/clearBoardsConfig',
'Clear the Board and Port Selection'
),
category: 'Developer (Arduino)',
};

View File

@ -1,352 +1,193 @@
import { TabBarToolbar } from '@theia/core/lib/browser/shell/tab-bar-toolbar/tab-bar-toolbar';
import { codicon } from '@theia/core/lib/browser/widgets/widget';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { CommandRegistry } from '@theia/core/lib/common/command';
import {
Disposable,
DisposableCollection,
} from '@theia/core/lib/common/disposable';
import { nls } from '@theia/core/lib/common/nls';
import React from '@theia/core/shared/react';
import ReactDOM from '@theia/core/shared/react-dom';
import classNames from 'classnames';
import { boardIdentifierLabel, Port } from '../../common/protocol';
import { BoardListItemUI } from '../../common/protocol/board-list';
import { assertUnreachable } from '../../common/utils';
import type {
BoardListUI,
BoardsServiceProvider,
} from './boards-service-provider';
import { DisposableCollection } from '@theia/core/lib/common/disposable';
import { Port } from '../../common/protocol';
import { BoardsConfig } from './boards-config';
import { ArduinoCommands } from '../arduino-commands';
import { BoardsServiceClientImpl, AvailableBoard } from './boards-service-client-impl';
export interface BoardsDropDownListCoords {
readonly top: number;
readonly left: number;
readonly width: number;
readonly paddingTop: number;
readonly top: number;
readonly left: number;
readonly width: number;
readonly paddingTop: number;
}
export namespace BoardsDropDown {
export interface Props {
readonly coords: BoardsDropDownListCoords | 'hidden';
readonly boardList: BoardListUI;
readonly openBoardsConfig: () => void;
readonly hide: () => void;
}
export interface Props {
readonly coords: BoardsDropDownListCoords | 'hidden';
readonly items: Array<AvailableBoard & { onClick: () => void, port: Port }>;
readonly openBoardsConfig: () => void;
}
}
export class BoardListDropDown extends React.Component<BoardsDropDown.Props> {
private dropdownElement: HTMLElement;
private listRef: React.RefObject<HTMLDivElement>;
export class BoardsDropDown extends React.Component<BoardsDropDown.Props> {
constructor(props: BoardsDropDown.Props) {
super(props);
this.listRef = React.createRef();
let list = document.getElementById('boards-dropdown-container');
if (!list) {
list = document.createElement('div');
list.id = 'boards-dropdown-container';
document.body.appendChild(list);
this.dropdownElement = list;
protected dropdownElement: HTMLElement;
constructor(props: BoardsDropDown.Props) {
super(props);
let list = document.getElementById('boards-dropdown-container');
if (!list) {
list = document.createElement('div');
list.id = 'boards-dropdown-container';
document.body.appendChild(list);
this.dropdownElement = list;
}
}
}
override componentDidUpdate(prevProps: BoardsDropDown.Props): void {
if (prevProps.coords === 'hidden' && this.listRef.current) {
this.listRef.current.focus();
render(): React.ReactNode {
return ReactDOM.createPortal(this.renderNode(), this.dropdownElement);
}
}
override render(): React.ReactNode {
return ReactDOM.createPortal(
this.renderBoardListItems(),
this.dropdownElement
);
}
private renderBoardListItems(): React.ReactNode {
const { coords, boardList } = this.props;
if (coords === 'hidden') {
return '';
}
const footerLabel = nls.localize(
'arduino/board/openBoardsConfig',
'Select other board and port…'
);
return (
<div
className="arduino-boards-dropdown-list"
style={{
position: 'absolute',
...coords,
}}
ref={this.listRef}
tabIndex={0}
>
<div className="arduino-boards-dropdown-list--items-container">
{boardList.items.map((item, index) =>
this.renderBoardListItem({
item,
selected: index === boardList.selectedIndex,
})
)}
protected renderNode(): React.ReactNode {
const { coords, items } = this.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>
<div
key={footerLabel}
tabIndex={0}
className="arduino-boards-dropdown-item arduino-board-dropdown-footer"
onClick={() => this.props.openBoardsConfig()}
>
<div>{footerLabel}</div>
</div>
</div>
);
}
private readonly onDefaultAction = (item: BoardListItemUI): unknown => {
const { boardList, hide } = this.props;
const { type, params } = item.defaultAction;
hide();
switch (type) {
case 'select-boards-config': {
return boardList.select(params);
}
case 'edit-boards-config': {
return boardList.edit(params);
}
default:
return assertUnreachable(type);
}
};
private renderBoardListItem({
item,
selected,
}: {
item: BoardListItemUI;
selected: boolean;
}): React.ReactNode {
const { boardLabel, portLabel, portProtocol, tooltip } = item.labels;
const port = item.port;
const onKeyUp = (e: React.KeyboardEvent) => {
if (e.key === 'Enter') {
this.onDefaultAction(item);
}
};
return (
<div
key={`board-item--${Port.keyOf(port)}`}
className={classNames('arduino-boards-dropdown-item', {
'arduino-boards-dropdown-item--selected': selected,
})}
onClick={() => this.onDefaultAction(item)}
onKeyUp={onKeyUp}
tabIndex={0}
>
<div
className={classNames(
'arduino-boards-dropdown-item--protocol',
'fa',
iconNameFromProtocol(portProtocol)
)}
/>
<div className="arduino-boards-dropdown-item--label" title={tooltip}>
<div className="arduino-boards-dropdown-item--board-header">
<div className="arduino-boards-dropdown-item--board-label noWrapInfo noselect">
{boardLabel}
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>
</div>
<div className="arduino-boards-dropdown-item--port-label noWrapInfo noselect">
{portLabel}
</div>
{selected ? <span className='fa fa-check' /> : ''}
</div>
{this.renderActions(item)}
</div>
);
}
private renderActions(item: BoardListItemUI): React.ReactNode {
const { boardList, hide } = this.props;
const { revert, edit } = item.otherActions;
if (!edit && !revert) {
return undefined;
}
const handleOnClick = (
event: React.MouseEvent<HTMLElement, MouseEvent>,
callback: () => void
) => {
event.preventDefault();
event.stopPropagation();
hide();
callback();
};
return (
<div className={TabBarToolbar.Styles.TAB_BAR_TOOLBAR}>
{edit && (
<div
className={`${TabBarToolbar.Styles.TAB_BAR_TOOLBAR_ITEM} enabled`}
>
{
<div
id="edit"
className={codicon('pencil', true)}
title={nls.localize(
'arduino/board/editBoardsConfig',
'Edit Board and Port...'
)}
onClick={(event) =>
handleOnClick(event, () => boardList.edit(edit.params))
}
/>
}
</div>
)}
{revert && (
<div
className={`${TabBarToolbar.Styles.TAB_BAR_TOOLBAR_ITEM} enabled`}
>
{
<div
id="revert"
className={codicon('discard', true)}
title={nls.localize(
'arduino/board/revertBoardsConfig',
"Use '{0}' discovered on '{1}'",
boardIdentifierLabel(revert.params.selectedBoard),
item.labels.portLabel
)}
onClick={(event) =>
handleOnClick(event, () => boardList.select(revert.params))
}
/>
}
</div>
)}
</div>
);
}
}
export class BoardsToolBarItem extends React.Component<
BoardsToolBarItem.Props,
BoardsToolBarItem.State
> {
static TOOLBAR_ID: 'boards-toolbar';
export class BoardsToolBarItem extends React.Component<BoardsToolBarItem.Props, BoardsToolBarItem.State> {
private readonly toDispose: DisposableCollection;
static TOOLBAR_ID: 'boards-toolbar';
constructor(props: BoardsToolBarItem.Props) {
super(props);
const { boardList } = props.boardsServiceProvider;
this.state = {
boardList,
coords: 'hidden',
};
const listener = () => this.setState({ coords: 'hidden' });
document.addEventListener('click', listener);
this.toDispose = new DisposableCollection(
Disposable.create(() => document.removeEventListener('click', listener))
);
}
protected readonly toDispose: DisposableCollection = new DisposableCollection();
override componentDidMount(): void {
this.toDispose.push(
this.props.boardsServiceProvider.onBoardListDidChange((boardList) =>
this.setState({ boardList })
)
);
}
constructor(props: BoardsToolBarItem.Props) {
super(props);
override componentWillUnmount(): void {
this.toDispose.dispose();
}
const { availableBoards } = props.boardsServiceClient;
this.state = {
availableBoards,
coords: 'hidden'
};
private readonly show = (event: React.MouseEvent<HTMLElement>): void => {
const { currentTarget: element } = event;
if (element instanceof HTMLElement) {
if (this.state.coords === 'hidden') {
const rect = element.getBoundingClientRect();
this.setState({
coords: {
top: rect.top,
left: rect.left,
width: rect.width,
paddingTop: rect.height,
},
document.addEventListener('click', () => {
this.setState({ coords: 'hidden' });
});
} else {
this.setState({ coords: 'hidden' });
}
}
event.stopPropagation();
event.nativeEvent.stopImmediatePropagation();
};
private readonly hide = () => {
this.setState({ coords: 'hidden' });
};
componentDidMount() {
this.props.boardsServiceClient.onAvailableBoardsChanged(availableBoards => this.setState({ availableBoards }));
}
componentWillUnmount(): void {
this.toDispose.dispose();
}
protected readonly show = (event: React.MouseEvent<HTMLElement>) => {
const { currentTarget: element } = event;
if (element instanceof HTMLElement) {
if (this.state.coords === 'hidden') {
const rect = element.getBoundingClientRect();
this.setState({
coords: {
top: rect.top,
left: rect.left,
width: rect.width,
paddingTop: rect.height
}
});
} else {
this.setState({ coords: 'hidden' });
}
}
event.stopPropagation();
event.nativeEvent.stopImmediatePropagation();
};
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 decorator = (() => {
const selectedBoard = availableBoards.find(({ selected }) => selected);
if (!selectedBoard || !selectedBoard.port) {
return 'fa fa-times notAttached'
}
if (selectedBoard.state === AvailableBoard.State.guessed) {
return 'fa fa-exclamation-triangle guessed'
}
return ''
})();
return <React.Fragment>
<div className='arduino-boards-toolbar-item-container'>
<div className='arduino-boards-toolbar-item' title={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>
</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>;
}
protected openDialog = () => {
this.props.commands.executeCommand(ArduinoCommands.OPEN_BOARDS_DIALOG.id);
this.setState({ coords: 'hidden' });
};
override render(): React.ReactNode {
const { coords, boardList } = this.state;
const { boardLabel, selected, portProtocol, tooltip } = boardList.labels;
const protocolIcon = portProtocol
? iconNameFromProtocol(portProtocol)
: null;
const protocolIconClassNames = classNames(
'arduino-boards-toolbar-item--protocol',
'fa',
protocolIcon
);
return (
<React.Fragment>
<div
className="arduino-boards-toolbar-item-container"
title={tooltip}
onClick={this.show}
>
{protocolIcon && <div className={protocolIconClassNames} />}
<div
className={classNames(
'arduino-boards-toolbar-item--label',
'noWrapInfo',
'noselect',
{ 'arduino-boards-toolbar-item--label-connected': selected }
)}
>
{boardLabel}
</div>
<div className="fa fa-caret-down caret" />
</div>
<BoardListDropDown
coords={coords}
boardList={boardList}
openBoardsConfig={() => boardList.edit({ query: '' })}
hide={this.hide}
/>
</React.Fragment>
);
}
}
export namespace BoardsToolBarItem {
export interface Props {
readonly boardsServiceProvider: BoardsServiceProvider;
readonly commands: CommandRegistry;
}
export interface State {
boardList: BoardListUI;
coords: BoardsDropDownListCoords | 'hidden';
}
}
export interface Props {
readonly boardsServiceClient: BoardsServiceClientImpl;
readonly commands: CommandRegistry;
}
export interface State {
availableBoards: AvailableBoard[];
coords: BoardsDropDownListCoords | 'hidden';
}
function iconNameFromProtocol(protocol: string): string {
switch (protocol) {
case 'serial':
return 'fa-arduino-technology-usb';
case 'network':
return 'fa-arduino-technology-connection';
// it is fine to assign dedicated icons to the protocols used by the official boards,
// but other than that it is best to avoid implementing any special handling
// for specific protocols in the IDE codebase.
default:
return 'fa-arduino-technology-3dimensionscube';
}
}

View File

@ -1,40 +1,40 @@
import { injectable } from '@theia/core/shared/inversify';
import {
BoardSearch,
BoardsPackage,
} from '../../common/protocol/boards-service';
import { URI } from '../contributions/contribution';
import { ListWidgetFrontendContribution } from '../widgets/component-list/list-widget-frontend-contribution';
import { injectable } from 'inversify';
import { MenuModelRegistry } from '@theia/core';
import { BoardsListWidget } from './boards-list-widget';
import { BoardsPackage } from '../../common/protocol/boards-service';
import { ListWidgetFrontendContribution } from '../widgets/component-list/list-widget-frontend-contribution';
import { ArduinoMenus } from '../menu/arduino-menus';
@injectable()
export class BoardsListWidgetFrontendContribution extends ListWidgetFrontendContribution<
BoardsPackage,
BoardSearch
> {
constructor() {
super({
widgetId: BoardsListWidget.WIDGET_ID,
widgetName: BoardsListWidget.WIDGET_LABEL,
defaultWidgetOptions: {
area: 'left',
rank: 2,
},
toggleCommandId: `${BoardsListWidget.WIDGET_ID}:toggle`,
toggleKeybinding: 'CtrlCmd+Shift+B',
});
}
export class BoardsListWidgetFrontendContribution extends ListWidgetFrontendContribution<BoardsPackage> {
protected canParse(uri: URI): boolean {
try {
BoardSearch.UriParser.parse(uri);
return true;
} catch {
return false;
static readonly OPEN_MANAGER = `${BoardsListWidget.WIDGET_ID}:toggle`;
constructor() {
super({
widgetId: BoardsListWidget.WIDGET_ID,
widgetName: BoardsListWidget.WIDGET_LABEL,
defaultWidgetOptions: {
area: 'left',
rank: 600
},
toggleCommandId: BoardsListWidgetFrontendContribution.OPEN_MANAGER,
toggleKeybinding: 'CtrlCmd+Shift+B'
});
}
async initializeLayout(): Promise<void> {
this.openView();
}
registerMenus(menus: MenuModelRegistry): void {
if (this.toggleCommand) {
menus.registerMenuAction(ArduinoMenus.TOOLS__MAIN_GROUP, {
commandId: this.toggleCommand.id,
label: 'Boards Manager...',
order: '4'
});
}
}
}
protected parse(uri: URI): BoardSearch | undefined {
return BoardSearch.UriParser.parse(uri);
}
}

View File

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

View File

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

View File

@ -1,28 +0,0 @@
import React from '@theia/core/shared/react';
export type ProgressBarProps = {
percent?: number;
showPercentage?: boolean;
};
export default function ProgressBar({
percent = 0,
showPercentage = false,
}: ProgressBarProps): React.ReactElement {
const roundedPercent = Math.round(percent);
return (
<div className="progress-bar">
<div className="progress-bar--outer">
<div
className="progress-bar--inner"
style={{ width: `${roundedPercent}%` }}
/>
</div>
{showPercentage && (
<div className="progress-bar--percentage">
<div className="progress-bar--percentage-text">{roundedPercent}%</div>
</div>
)}
</div>
);
}

View File

@ -0,0 +1,52 @@
import { injectable, inject } from 'inversify';
import { ILogger } from '@theia/core/lib/common/logger';
import { Event, Emitter } from '@theia/core/lib/common/event';
import { CommandService } from '@theia/core/lib/common/command';
import { MessageService } from '@theia/core/lib/common/message-service';
import { ConfigServiceClient, Config } from '../common/protocol';
import { Settings } from './contributions/settings';
@injectable()
export class ConfigServiceClientImpl implements ConfigServiceClient {
@inject(CommandService)
protected readonly commandService: CommandService;
@inject(ILogger)
protected readonly logger: ILogger;
@inject(MessageService)
protected readonly messageService: MessageService;
protected readonly onConfigChangedEmitter = new Emitter<Config>();
protected invalidConfigPopup: Promise<void | 'No' | 'Yes' | undefined> | undefined;
notifyConfigChanged(config: Config): void {
this.invalidConfigPopup = undefined;
this.info(`The CLI configuration has been successfully reloaded.`);
this.onConfigChangedEmitter.fire(config);
}
notifyInvalidConfig(): void {
if (!this.invalidConfigPopup) {
this.invalidConfigPopup = this.messageService.error(`Your CLI configuration is invalid. Do you want to correct it now?`, 'No', 'Yes')
.then(answer => {
if (answer === 'Yes') {
this.commandService.executeCommand(Settings.Commands.OPEN_CLI_CONFIG.id)
}
this.invalidConfigPopup = undefined;
})
}
}
get onConfigChanged(): Event<Config> {
return this.onConfigChangedEmitter.event;
}
protected info(message: string): void {
this.messageService.info(message, { timeout: 3000 });
this.logger.info(message);
}
}

View File

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

View File

@ -1,176 +0,0 @@
import { ClipboardService } from '@theia/core/lib/browser/clipboard-service';
import { FrontendApplicationConfigProvider } from '@theia/core/lib/browser/frontend-application-config-provider';
import { nls } from '@theia/core/lib/common/nls';
import { isOSX, isWindows } from '@theia/core/lib/common/os';
import { inject, injectable } from '@theia/core/shared/inversify';
import moment from 'moment';
import { AppService } from '../app-service';
import { ArduinoMenus } from '../menu/arduino-menus';
import {
Command,
CommandRegistry,
Contribution,
MenuModelRegistry,
} from './contribution';
@injectable()
export class About extends Contribution {
@inject(ClipboardService)
private readonly clipboardService: ClipboardService;
@inject(AppService)
private readonly appService: AppService;
override registerCommands(registry: CommandRegistry): void {
registry.registerCommand(About.Commands.ABOUT_APP, {
execute: () => this.showAbout(),
});
}
override registerMenus(registry: MenuModelRegistry): void {
registry.registerMenuAction(ArduinoMenus.HELP__ABOUT_GROUP, {
commandId: About.Commands.ABOUT_APP.id,
label: nls.localize(
'arduino/about/label',
'About {0}',
this.applicationName
),
order: '0',
});
}
private async showAbout(): Promise<void> {
const appInfo = await this.appService.info();
const { appVersion, cliVersion, buildDate } = appInfo;
const detail = (showAll: boolean) =>
nls.localize(
'arduino/about/detail',
'Version: {0}\nDate: {1}{2}\nCLI Version: {3}\n\n{4}',
appVersion,
buildDate ? buildDate : nls.localize('', 'dev build'),
buildDate && showAll ? ` (${this.ago(buildDate)})` : '',
cliVersion,
nls.localize(
'arduino/about/copyright',
'Copyright © {0} Arduino SA',
new Date().getFullYear().toString()
)
);
const ok = nls.localize('vscode/issueMainService/ok', 'OK');
const copy = nls.localize('vscode/textInputActions/copy', 'Copy');
const buttons = !isWindows && !isOSX ? [copy, ok] : [ok, copy];
const { response } = await this.dialogService.showMessageBox({
message: `${this.applicationName}`,
title: `${this.applicationName}`,
type: 'info',
detail: detail(true),
buttons,
noLink: true,
defaultId: buttons.indexOf(ok),
cancelId: buttons.indexOf(ok),
});
if (buttons[response] === copy) {
await this.clipboardService.writeText(detail(false).trim());
}
}
private get applicationName(): string {
return FrontendApplicationConfigProvider.get().applicationName;
}
private ago(isoTime: string): string {
const now = moment(Date.now());
const other = moment(isoTime);
let result = now.diff(other, 'minute');
if (result < 60) {
return result === 1
? nls.localize(
'vscode/date/date.fromNow.minutes.singular.ago',
'{0} minute ago',
result.toString()
)
: nls.localize(
'vscode/date/date.fromNow.minutes.plural.ago',
'{0} minutes ago',
result.toString()
);
}
result = now.diff(other, 'hour');
if (result < 25) {
return result === 1
? nls.localize(
'vscode/date/date.fromNow.hours.singular.ago',
'{0} hour ago',
result.toString()
)
: nls.localize(
'vscode/date/date.fromNow.hours.plural.ago',
'{0} hours ago',
result.toString()
);
}
result = now.diff(other, 'day');
if (result < 8) {
return result === 1
? nls.localize(
'vscode/date/date.fromNow.days.singular.ago',
'{0} day ago',
result.toString()
)
: nls.localize(
'vscode/date/date.fromNow.days.plural.ago',
'{0} days ago',
result.toString()
);
}
result = now.diff(other, 'week');
if (result < 5) {
return result === 1
? nls.localize(
'vscode/date/date.fromNow.weeks.singular.ago',
'{0} week ago',
result.toString()
)
: nls.localize(
'vscode/date/date.fromNow.weeks.plural.ago',
'{0} weeks ago',
result.toString()
);
}
result = now.diff(other, 'month');
if (result < 13) {
return result === 1
? nls.localize(
'vscode/date/date.fromNow.months.singular.ago',
'{0} month ago',
result.toString()
)
: nls.localize(
'vscode/date/date.fromNow.months.plural.ago',
'{0} months ago',
result.toString()
);
}
result = now.diff(other, 'year');
return result === 1
? nls.localize(
'vscode/date/date.fromNow.years.singular.ago',
'{0} year ago',
result.toString()
)
: nls.localize(
'vscode/date/date.fromNow.years.plural.ago',
'{0} years ago',
result.toString()
);
}
}
export namespace About {
export namespace Commands {
export const ABOUT_APP: Command = {
id: 'arduino-about',
};
}
}

View File

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

View File

@ -1,105 +0,0 @@
import { nls } from '@theia/core/lib/common/nls';
import { inject, injectable } from '@theia/core/shared/inversify';
import { FileDialogService } from '@theia/filesystem/lib/browser';
import { ArduinoMenus } from '../menu/arduino-menus';
import { CurrentSketch } from '../sketches-service-client-impl';
import {
Command,
CommandRegistry,
MenuModelRegistry,
Sketch,
SketchContribution,
URI,
} from './contribution';
@injectable()
export class AddFile extends SketchContribution {
@inject(FileDialogService)
private readonly fileDialogService: FileDialogService; // TODO: use dialogService
override registerCommands(registry: CommandRegistry): void {
registry.registerCommand(AddFile.Commands.ADD_FILE, {
execute: () => this.addFile(),
});
}
override registerMenus(registry: MenuModelRegistry): void {
registry.registerMenuAction(ArduinoMenus.SKETCH__UTILS_GROUP, {
commandId: AddFile.Commands.ADD_FILE.id,
label: nls.localize('arduino/contributions/addFile', 'Add File') + '...',
order: '2',
});
}
private async addFile(): Promise<void> {
const sketch = await this.sketchServiceClient.currentSketch();
if (!CurrentSketch.isValid(sketch)) {
return;
}
const toAddUri = await this.fileDialogService.showOpenDialog({
title: nls.localize('arduino/contributions/addFile', 'Add File'),
canSelectFiles: true,
canSelectFolders: false,
canSelectMany: false,
modal: true,
});
if (!toAddUri) {
return;
}
const { uri: targetUri, filename } = this.resolveTarget(sketch, toAddUri);
const exists = await this.fileService.exists(targetUri);
if (exists) {
const { response } = await this.dialogService.showMessageBox({
type: 'question',
title: nls.localize('arduino/contributions/replaceTitle', 'Replace'),
buttons: [
nls.localize('vscode/issueMainService/cancel', 'Cancel'),
nls.localize('vscode/issueMainService/ok', 'OK'),
],
message: nls.localize(
'arduino/replaceMsg',
'Replace the existing version of {0}?',
filename
),
});
if (response === 0) {
// Cancel
return;
}
}
await this.fileService.copy(toAddUri, targetUri, { overwrite: true });
this.messageService.info(
nls.localize(
'arduino/contributions/fileAdded',
'One file added to the sketch.'
),
{
timeout: 2000,
}
);
}
// https://github.com/arduino/arduino-ide/issues/284#issuecomment-1364533662
// File the file to add has one of the following extension, it goes to the sketch folder root: .ino, .h, .cpp, .c, .S
// Otherwise, the files goes to the `data` folder inside the sketch folder root.
private resolveTarget(
sketch: Sketch,
toAddUri: URI
): { uri: URI; filename: string } {
const path = toAddUri.path;
const filename = path.base;
let root = new URI(sketch.uri);
if (!Sketch.Extensions.CODE_FILES.includes(path.ext)) {
root = root.resolve('data');
}
return { uri: root.resolve(filename), filename: filename };
}
}
export namespace AddFile {
export namespace Commands {
export const ADD_FILE: Command = {
id: 'arduino-add-file',
};
}
}

View File

@ -1,142 +0,0 @@
import { inject, injectable } from '@theia/core/shared/inversify';
import URI from '@theia/core/lib/common/uri';
import { ConfirmDialog } from '@theia/core/lib/browser/dialogs';
import { ArduinoMenus } from '../menu/arduino-menus';
import { LibraryService, ResponseServiceClient } from '../../common/protocol';
import { ExecuteWithProgress } from '../../common/protocol/progressible';
import {
SketchContribution,
Command,
CommandRegistry,
MenuModelRegistry,
} from './contribution';
import { nls } from '@theia/core/lib/common';
@injectable()
export class AddZipLibrary extends SketchContribution {
@inject(ResponseServiceClient)
private readonly responseService: ResponseServiceClient;
@inject(LibraryService)
private readonly libraryService: LibraryService;
override registerCommands(registry: CommandRegistry): void {
registry.registerCommand(AddZipLibrary.Commands.ADD_ZIP_LIBRARY, {
execute: () => this.addZipLibrary(),
});
}
override registerMenus(registry: MenuModelRegistry): void {
const includeLibMenuPath = [
...ArduinoMenus.SKETCH__UTILS_GROUP,
'0_include',
];
registry.registerMenuAction([...includeLibMenuPath, '1_install'], {
commandId: AddZipLibrary.Commands.ADD_ZIP_LIBRARY.id,
label: nls.localize('arduino/library/addZip', 'Add .ZIP Library...'),
order: '1',
});
}
private async addZipLibrary(): Promise<void> {
const homeUri = await this.envVariableServer.getHomeDirUri();
const defaultPath = await this.fileService.fsPath(new URI(homeUri));
const { canceled, filePaths } = await this.dialogService.showOpenDialog({
title: nls.localize(
'arduino/selectZip',
"Select a zip file containing the library you'd like to add"
),
defaultPath,
properties: ['openFile'],
filters: [
{
name: nls.localize('arduino/library/zipLibrary', 'Library'),
extensions: ['zip'],
},
],
});
if (!canceled && filePaths.length) {
const zipUri = await this.fileSystemExt.getUri(filePaths[0]);
try {
await this.doInstall(zipUri);
} catch (error) {
if (error instanceof AlreadyInstalledError) {
const result = await new ConfirmDialog({
msg: error.message,
title: nls.localize(
'arduino/library/overwriteExistingLibrary',
'Do you want to overwrite the existing library?'
),
ok: nls.localize('vscode/extensionsUtils/yes', 'Yes'),
cancel: nls.localize('vscode/extensionsUtils/no', 'No'),
}).open();
if (result) {
await this.doInstall(zipUri, true);
}
}
}
}
}
private async doInstall(zipUri: string, overwrite?: boolean): Promise<void> {
try {
await ExecuteWithProgress.doWithProgress({
messageService: this.messageService,
progressText:
nls.localize('arduino/common/processing', 'Processing') +
` ${new URI(zipUri).path.base}`,
responseService: this.responseService,
run: () => this.libraryService.installZip({ zipUri, overwrite }),
});
this.messageService.info(
nls.localize(
'arduino/library/successfullyInstalledZipLibrary',
'Successfully installed library from {0} archive',
new URI(zipUri).path.base
),
{ timeout: 3000 }
);
} catch (error) {
if (error instanceof Error) {
const match = error.message.match(/library (.*?) already installed/);
if (match && match.length >= 2) {
const name = match[1].trim();
if (name) {
throw new AlreadyInstalledError(
nls.localize(
'arduino/library/namedLibraryAlreadyExists',
'A library folder named {0} already exists. Do you want to overwrite it?',
name
),
name
);
} else {
throw new AlreadyInstalledError(
nls.localize(
'arduino/library/libraryAlreadyExists',
'A library already exists. Do you want to overwrite it?'
)
);
}
}
}
this.messageService.error(error.toString());
throw error;
}
}
}
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',
};
}
}

View File

@ -1,75 +0,0 @@
import { injectable } from '@theia/core/shared/inversify';
import dateFormat from 'dateformat';
import { ArduinoMenus } from '../menu/arduino-menus';
import {
SketchContribution,
Command,
CommandRegistry,
MenuModelRegistry,
} from './contribution';
import { nls } from '@theia/core/lib/common';
import { CurrentSketch } from '../sketches-service-client-impl';
@injectable()
export class ArchiveSketch extends SketchContribution {
override registerCommands(registry: CommandRegistry): void {
registry.registerCommand(ArchiveSketch.Commands.ARCHIVE_SKETCH, {
execute: () => this.archiveSketch(),
});
}
override registerMenus(registry: MenuModelRegistry): void {
registry.registerMenuAction(ArduinoMenus.TOOLS__MAIN_GROUP, {
commandId: ArchiveSketch.Commands.ARCHIVE_SKETCH.id,
label: nls.localize('arduino/sketch/archiveSketch', 'Archive Sketch'),
order: '1',
});
}
private async archiveSketch(): Promise<void> {
const sketch = await this.sketchServiceClient.currentSketch();
if (!CurrentSketch.isValid(sketch)) {
return;
}
const archiveBasename = `${sketch.name}-${dateFormat(
new Date(),
'yymmdd'
)}a.zip`;
const defaultContainerUri = await this.defaultUri();
const defaultUri = defaultContainerUri.resolve(archiveBasename);
const defaultPath = await this.fileService.fsPath(defaultUri);
const { filePath, canceled } = await this.dialogService.showSaveDialog({
title: nls.localize(
'arduino/sketch/saveSketchAs',
'Save sketch folder as...'
),
defaultPath,
});
if (!filePath || canceled) {
return;
}
const destinationUri = await this.fileSystemExt.getUri(filePath);
if (!destinationUri) {
return;
}
await this.sketchesService.archive(sketch, destinationUri.toString());
this.messageService.info(
nls.localize(
'arduino/sketch/createdArchive',
"Created archive '{0}'.",
archiveBasename
),
{
timeout: 2000,
}
);
}
}
export namespace ArchiveSketch {
export namespace Commands {
export const ARCHIVE_SKETCH: Command = {
id: 'arduino-archive-sketch',
};
}
}

View File

@ -1,123 +0,0 @@
import type { MaybePromise } from '@theia/core/lib/common/types';
import { inject, injectable } from '@theia/core/shared/inversify';
import {
BoardDetails,
Programmer,
isBoardIdentifierChangeEvent,
} from '../../common/protocol';
import {
BoardsDataStore,
findDefaultProgrammer,
isEmptyData,
} from '../boards/boards-data-store';
import { BoardsServiceProvider } from '../boards/boards-service-provider';
import { Contribution } from './contribution';
/**
* Before CLI 0.35.0-rc.3, there was no `programmer#default` property in the `board details` response.
* This method does the programmer migration in the data store. If there is a programmer selected, it's a noop.
* If no programmer is selected, it forcefully reloads the details from the CLI and updates it in the local storage.
*/
@injectable()
export class AutoSelectProgrammer extends Contribution {
@inject(BoardsServiceProvider)
private readonly boardsServiceProvider: BoardsServiceProvider;
@inject(BoardsDataStore)
private readonly boardsDataStore: BoardsDataStore;
override onStart(): void {
this.boardsServiceProvider.onBoardsConfigDidChange((event) => {
if (isBoardIdentifierChangeEvent(event)) {
this.ensureProgrammerIsSelected();
}
});
}
override onReady(): void {
this.boardsServiceProvider.ready.then(() =>
this.ensureProgrammerIsSelected()
);
}
private async ensureProgrammerIsSelected(): Promise<boolean> {
return ensureProgrammerIsSelected({
fqbn: this.boardsServiceProvider.boardsConfig.selectedBoard?.fqbn,
getData: (fqbn) => this.boardsDataStore.getData(fqbn),
loadBoardDetails: (fqbn) => this.boardsDataStore.loadBoardDetails(fqbn),
selectProgrammer: (arg) => this.boardsDataStore.selectProgrammer(arg),
});
}
}
interface EnsureProgrammerIsSelectedParams {
fqbn: string | undefined;
getData: (fqbn: string | undefined) => MaybePromise<BoardsDataStore.Data>;
loadBoardDetails: (fqbn: string) => MaybePromise<BoardDetails | undefined>;
selectProgrammer(options: {
fqbn: string;
selectedProgrammer: Programmer;
}): MaybePromise<boolean>;
}
export async function ensureProgrammerIsSelected(
params: EnsureProgrammerIsSelectedParams
): Promise<boolean> {
const { fqbn, getData, loadBoardDetails, selectProgrammer } = params;
if (!fqbn) {
return false;
}
console.debug(`Ensuring a programmer is selected for ${fqbn}...`);
const data = await getData(fqbn);
if (isEmptyData(data)) {
// For example, the platform is not installed.
console.debug(`Skipping. No boards data is available for ${fqbn}.`);
return false;
}
if (data.selectedProgrammer) {
console.debug(
`A programmer is already selected for ${fqbn}: '${data.selectedProgrammer.id}'.`
);
return true;
}
let programmer = findDefaultProgrammer(data.programmers, data);
if (programmer) {
// select the programmer if the default info is available
const result = await selectProgrammer({
fqbn,
selectedProgrammer: programmer,
});
if (result) {
console.debug(`Selected '${programmer.id}' programmer for ${fqbn}.`);
return result;
}
}
console.debug(`Reloading board details for ${fqbn}...`);
const reloadedData = await loadBoardDetails(fqbn);
if (!reloadedData) {
console.debug(`Skipping. No board details found for ${fqbn}.`);
return false;
}
if (!reloadedData.programmers.length) {
console.debug(`Skipping. ${fqbn} does not have programmers.`);
return false;
}
programmer = findDefaultProgrammer(reloadedData.programmers, reloadedData);
if (!programmer) {
console.debug(
`Skipping. Could not find a default programmer for ${fqbn}. Programmers were: `
);
return false;
}
const result = await selectProgrammer({
fqbn,
selectedProgrammer: programmer,
});
if (result) {
console.debug(`Selected '${programmer.id}' programmer for ${fqbn}.`);
} else {
console.debug(
`Could not select '${programmer.id}' programmer for ${fqbn}.`
);
}
return result;
}

View File

@ -1,409 +0,0 @@
import {
Disposable,
DisposableCollection,
} from '@theia/core/lib/common/disposable';
import { MenuModelRegistry } from '@theia/core/lib/common/menu/menu-model-registry';
import type { MenuPath } from '@theia/core/lib/common/menu/menu-types';
import { nls } from '@theia/core/lib/common/nls';
import { Deferred } from '@theia/core/lib/common/promise-util';
import { inject, injectable } from '@theia/core/shared/inversify';
import { MainMenuManager } from '../../common/main-menu-manager';
import {
BoardsService,
BoardWithPackage,
createPlatformIdentifier,
getBoardInfo,
InstalledBoardWithPackage,
platformIdentifierEquals,
Port,
serializePlatformIdentifier,
} from '../../common/protocol';
import type { BoardList } from '../../common/protocol/board-list';
import { BoardsListWidget } from '../boards/boards-list-widget';
import { BoardsDataStore } from '../boards/boards-data-store';
import { BoardsServiceProvider } from '../boards/boards-service-provider';
import {
ArduinoMenus,
PlaceholderMenuNode,
unregisterSubmenu,
} from '../menu/arduino-menus';
import { NotificationCenter } from '../notification-center';
import { Command, CommandRegistry, SketchContribution } from './contribution';
@injectable()
export class BoardSelection extends SketchContribution {
@inject(CommandRegistry)
private readonly commandRegistry: CommandRegistry;
@inject(MainMenuManager)
private readonly mainMenuManager: MainMenuManager;
@inject(MenuModelRegistry)
private readonly menuModelRegistry: MenuModelRegistry;
@inject(NotificationCenter)
private readonly notificationCenter: NotificationCenter;
@inject(BoardsDataStore)
private readonly boardsDataStore: BoardsDataStore;
@inject(BoardsService)
private readonly boardsService: BoardsService;
@inject(BoardsServiceProvider)
private readonly boardsServiceProvider: BoardsServiceProvider;
private readonly toDisposeBeforeMenuRebuild = new DisposableCollection();
// do not query installed platforms on every change
private _installedBoards: Deferred<InstalledBoardWithPackage[]> | undefined;
override registerCommands(registry: CommandRegistry): void {
registry.registerCommand(BoardSelection.Commands.GET_BOARD_INFO, {
execute: async () => {
const boardInfo = await getBoardInfo(
this.boardsServiceProvider.boardList
);
if (typeof boardInfo === 'string') {
this.messageService.info(boardInfo);
return;
}
const { BN, VID, PID, SN } = boardInfo;
const detail = `
BN: ${BN}
VID: ${VID}
PID: ${PID}
SN: ${SN}
`.trim();
await this.dialogService.showMessageBox({
message: nls.localize('arduino/board/boardInfo', 'Board Info'),
title: nls.localize('arduino/board/boardInfo', 'Board Info'),
type: 'info',
detail,
buttons: [nls.localize('vscode/issueMainService/ok', 'OK')],
});
},
});
registry.registerCommand(BoardSelection.Commands.RELOAD_BOARD_DATA, {
execute: async () => {
const selectedFqbn =
this.boardsServiceProvider.boardList.boardsConfig.selectedBoard?.fqbn;
let message: string;
if (selectedFqbn) {
await this.boardsDataStore.reloadBoardData(selectedFqbn);
message = nls.localize(
'arduino/board/boardDataReloaded',
'Board data reloaded.'
);
} else {
message = nls.localize(
'arduino/board/selectBoardToReload',
'Please select a board first.'
);
}
this.messageService.info(message, { timeout: 2000 });
},
});
}
override onStart(): void {
this.notificationCenter.onPlatformDidInstall(() => this.updateMenus(true));
this.notificationCenter.onPlatformDidUninstall(() =>
this.updateMenus(true)
);
this.boardsServiceProvider.onBoardListDidChange(() => this.updateMenus());
}
override async onReady(): Promise<void> {
this.updateMenus();
}
private async updateMenus(discardCache = false): Promise<void> {
if (discardCache) {
this._installedBoards?.reject();
this._installedBoards = undefined;
}
if (!this._installedBoards) {
this._installedBoards = new Deferred();
this.installedBoards().then((installedBoards) =>
this._installedBoards?.resolve(installedBoards)
);
}
const installedBoards = await this._installedBoards.promise;
this.rebuildMenus(installedBoards, this.boardsServiceProvider.boardList);
}
private rebuildMenus(
installedBoards: InstalledBoardWithPackage[],
boardList: BoardList
): void {
this.toDisposeBeforeMenuRebuild.dispose();
// Boards submenu
const boardsSubmenuPath = [
...ArduinoMenus.TOOLS__BOARD_SELECTION_GROUP,
'1_boards',
];
const { selectedBoard, selectedPort } = boardList.boardsConfig;
const boardsSubmenuLabel = selectedBoard?.name;
// Note: The submenu order starts from `100` because `Auto Format`, `Serial Monitor`, etc starts from `0` index.
// The board specific items, and the rest, have order with `z`. We needed something between `0` and `z` with natural-order.
this.menuModelRegistry.registerSubmenu(
boardsSubmenuPath,
nls.localize(
'arduino/board/board',
'Board{0}',
!!boardsSubmenuLabel ? `: "${boardsSubmenuLabel}"` : ''
),
{ order: '100' }
);
this.toDisposeBeforeMenuRebuild.push(
Disposable.create(() =>
unregisterSubmenu(boardsSubmenuPath, this.menuModelRegistry)
)
);
// Ports submenu
const portsSubmenuPath = ArduinoMenus.TOOLS__PORTS_SUBMENU;
const portsSubmenuLabel = selectedPort?.address;
this.menuModelRegistry.registerSubmenu(
portsSubmenuPath,
nls.localize(
'arduino/board/port',
'Port{0}',
portsSubmenuLabel ? `: "${portsSubmenuLabel}"` : ''
),
{ order: '101' }
);
this.toDisposeBeforeMenuRebuild.push(
Disposable.create(() =>
unregisterSubmenu(portsSubmenuPath, this.menuModelRegistry)
)
);
const reloadBoardData = {
commandId: BoardSelection.Commands.RELOAD_BOARD_DATA.id,
label: nls.localize('arduino/board/reloadBoardData', 'Reload Board Data'),
order: '102',
};
this.menuModelRegistry.registerMenuAction(
ArduinoMenus.TOOLS__BOARD_SELECTION_GROUP,
reloadBoardData
);
this.toDisposeBeforeMenuRebuild.push(
Disposable.create(() =>
this.menuModelRegistry.unregisterMenuAction(reloadBoardData)
)
);
const getBoardInfo = {
commandId: BoardSelection.Commands.GET_BOARD_INFO.id,
label: nls.localize('arduino/board/getBoardInfo', '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: `${BoardsListWidget.WIDGET_LABEL}...`,
});
const selectedBoardPlatformId = selectedBoard
? createPlatformIdentifier(selectedBoard)
: undefined;
// Keys are the vendor IDs
type BoardsPerVendor = Record<string, BoardWithPackage[]>;
// Group boards by their platform names. The keys are the platform names as menu labels.
// If there is a platform name (menu label) collision, refine the menu label with the vendor ID.
const groupedBoards = new Map<string, BoardsPerVendor>();
for (const board of installedBoards) {
const { packageId, packageName } = board;
const { vendorId } = packageId;
let boardsPerPackageName = groupedBoards.get(packageName);
if (!boardsPerPackageName) {
boardsPerPackageName = {} as BoardsPerVendor;
groupedBoards.set(packageName, boardsPerPackageName);
}
let boardPerVendor: BoardWithPackage[] | undefined =
boardsPerPackageName[vendorId];
if (!boardPerVendor) {
boardPerVendor = [];
boardsPerPackageName[vendorId] = boardPerVendor;
}
boardPerVendor.push(board);
}
// Installed boards
Array.from(groupedBoards.entries()).forEach(
([packageName, boardsPerPackage]) => {
const useVendorSuffix = Object.keys(boardsPerPackage).length > 1;
Object.entries(boardsPerPackage).forEach(([vendorId, boards]) => {
let platformMenuPath: MenuPath | undefined = undefined;
boards.forEach((board, index) => {
const { packageId, fqbn, name, manuallyInstalled } = board;
// create the platform submenu once.
// creating and registering the same submenu twice in Theia is a noop, though.
if (!platformMenuPath) {
let packageLabel =
packageName +
`${
manuallyInstalled
? nls.localize(
'arduino/board/inSketchbook',
' (in Sketchbook)'
)
: ''
}`;
if (
selectedBoardPlatformId &&
platformIdentifierEquals(packageId, selectedBoardPlatformId)
) {
packageLabel = `${packageLabel}`;
}
if (useVendorSuffix) {
packageLabel += ` (${vendorId})`;
}
// Platform submenu
platformMenuPath = [
...boardsPackagesGroup,
serializePlatformIdentifier(packageId),
];
this.menuModelRegistry.registerSubmenu(
platformMenuPath,
packageLabel,
{
order: packageName.toLowerCase(),
}
);
}
const id = `arduino-select-board--${fqbn}`;
const command = { id };
const handler = {
execute: () =>
this.boardsServiceProvider.updateConfig({
name: name,
fqbn: fqbn,
}),
isToggled: () => fqbn === selectedBoard?.fqbn,
};
// Board menu
const menuAction = {
commandId: id,
label: name,
order: String(index).padStart(4), // pads with leading zeros for alphanumeric sort where order is 1, 2, 11, and NOT 1, 11, 2
};
this.commandRegistry.registerCommand(command, handler);
this.toDisposeBeforeMenuRebuild.push(
Disposable.create(() =>
this.commandRegistry.unregisterCommand(command)
)
);
this.menuModelRegistry.registerMenuAction(
platformMenuPath,
menuAction
);
// Note: we do not dispose the menu actions individually. Calling `unregisterSubmenu` on the parent will wipe the children menu nodes recursively.
});
});
}
);
// Detected ports
const registerPorts = (
protocol: string,
ports: ReturnType<BoardList['ports']>,
protocolOrder: number
) => {
if (!ports.length) {
return;
}
// Register placeholder for protocol
const menuPath = [
...portsSubmenuPath,
`${protocolOrder.toString()}_${protocol}`,
];
const placeholder = new PlaceholderMenuNode(
menuPath,
nls.localize(
'arduino/board/typeOfPorts',
'{0} ports',
Port.Protocols.protocolLabel(protocol)
),
{ order: protocolOrder.toString().padStart(4) }
);
this.menuModelRegistry.registerMenuNode(menuPath, placeholder);
this.toDisposeBeforeMenuRebuild.push(
Disposable.create(() =>
this.menuModelRegistry.unregisterMenuNode(placeholder.id)
)
);
for (let i = 0; i < ports.length; i++) {
const { port, boards } = ports[i];
const portKey = Port.keyOf(port);
let label = `${port.addressLabel}`;
if (boards?.length) {
const boardsList = boards.map((board) => board.name).join(', ');
label = `${label} (${boardsList})`;
}
const id = `arduino-select-port--${portKey}`;
const command = { id };
const handler = {
execute: () => {
this.boardsServiceProvider.updateConfig({
protocol: port.protocol,
address: port.address,
});
},
isToggled: () => {
return i === ports.matchingIndex;
},
};
const menuAction = {
commandId: id,
label,
order: String(protocolOrder + i + 1).padStart(4),
};
this.commandRegistry.registerCommand(command, handler);
this.toDisposeBeforeMenuRebuild.push(
Disposable.create(() =>
this.commandRegistry.unregisterCommand(command)
)
);
this.menuModelRegistry.registerMenuAction(menuPath, menuAction);
}
};
const groupedPorts = boardList.portsGroupedByProtocol();
let protocolOrder = 100;
Object.entries(groupedPorts).forEach(([protocol, ports]) => {
registerPorts(protocol, ports, protocolOrder);
protocolOrder += 100;
});
this.mainMenuManager.update();
}
protected async installedBoards(): Promise<InstalledBoardWithPackage[]> {
const allBoards = await this.boardsService.getInstalledBoards();
return allBoards.filter(InstalledBoardWithPackage.is);
}
}
export namespace BoardSelection {
export namespace Commands {
export const GET_BOARD_INFO: Command = { id: 'arduino-get-board-info' };
export const RELOAD_BOARD_DATA: Command = {
id: 'arduino-reload-board-data',
};
}
}

View File

@ -1,178 +0,0 @@
import {
Disposable,
DisposableCollection,
} from '@theia/core/lib/common/disposable';
import { nls } from '@theia/core/lib/common/nls';
import { inject, injectable } from '@theia/core/shared/inversify';
import PQueue from 'p-queue';
import {
BoardIdentifier,
ConfigOption,
isBoardIdentifierChangeEvent,
Programmer,
} from '../../common/protocol';
import { BoardsDataStore } from '../boards/boards-data-store';
import { BoardsServiceProvider } from '../boards/boards-service-provider';
import { ArduinoMenus, unregisterSubmenu } from '../menu/arduino-menus';
import {
CommandRegistry,
Contribution,
MenuModelRegistry,
} from './contribution';
@injectable()
export class BoardsDataMenuUpdater extends Contribution {
@inject(CommandRegistry)
private readonly commandRegistry: CommandRegistry;
@inject(MenuModelRegistry)
private readonly menuRegistry: MenuModelRegistry;
@inject(BoardsDataStore)
private readonly boardsDataStore: BoardsDataStore;
@inject(BoardsServiceProvider)
private readonly boardsServiceProvider: BoardsServiceProvider;
private readonly queue = new PQueue({ autoStart: true, concurrency: 1 });
private readonly toDisposeOnBoardChange = new DisposableCollection();
override onStart(): void {
this.boardsDataStore.onDidChange(() =>
this.updateMenuActions(
this.boardsServiceProvider.boardsConfig.selectedBoard
)
);
this.boardsServiceProvider.onBoardsConfigDidChange((event) => {
if (isBoardIdentifierChangeEvent(event)) {
this.updateMenuActions(event.selectedBoard);
}
});
}
override onReady(): void {
this.boardsServiceProvider.ready.then(() =>
this.updateMenuActions(
this.boardsServiceProvider.boardsConfig.selectedBoard
)
);
}
private async updateMenuActions(
selectedBoard: BoardIdentifier | undefined
): Promise<void> {
return this.queue.add(async () => {
this.toDisposeOnBoardChange.dispose();
this.menuManager.update();
if (selectedBoard) {
const { fqbn } = selectedBoard;
if (fqbn) {
const { configOptions, programmers, selectedProgrammer } =
await this.boardsDataStore.getData(fqbn);
if (configOptions.length) {
const boardsConfigMenuPath = [
...ArduinoMenus.TOOLS__BOARD_SETTINGS_GROUP,
'z01_boardsConfig',
]; // `z_` is for ordering.
for (const { label, option, values } of configOptions.sort(
ConfigOption.LABEL_COMPARATOR
)) {
const menuPath = [...boardsConfigMenuPath, `${option}`];
const commands = new Map<
string,
Disposable & { label: string }
>();
let selectedValue = '';
for (const value of values) {
const id = `${fqbn}-${option}--${value.value}`;
const command = { id };
const handler = {
execute: () =>
this.boardsDataStore.selectConfigOption({
fqbn,
optionsToUpdate: [{ option, selectedValue: value.value }],
}),
isToggled: () => value.selected,
};
commands.set(
id,
Object.assign(
this.commandRegistry.registerCommand(command, handler),
{ label: value.label }
)
);
if (value.selected) {
selectedValue = value.label;
}
}
this.menuRegistry.registerSubmenu(
menuPath,
`${label}${selectedValue ? `: "${selectedValue}"` : ''}`
);
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: String(i).padStart(4),
label,
});
return Disposable.create(() =>
this.menuRegistry.unregisterMenuAction(commandId)
);
}),
]);
}
}
if (programmers.length) {
const programmersMenuPath = [
...ArduinoMenus.TOOLS__BOARD_SETTINGS_GROUP,
'z02_programmers',
];
const programmerNls = nls.localize(
'arduino/board/programmer',
'Programmer'
);
const label = selectedProgrammer
? `${programmerNls}: "${selectedProgrammer.name}"`
: programmerNls;
this.menuRegistry.registerSubmenu(programmersMenuPath, label);
this.toDisposeOnBoardChange.push(
Disposable.create(() =>
unregisterSubmenu(programmersMenuPath, this.menuRegistry)
)
);
for (const programmer of programmers) {
const { id, name } = programmer;
const command = { id: `${fqbn}-programmer--${id}` };
const handler = {
execute: () =>
this.boardsDataStore.selectProgrammer({
fqbn,
selectedProgrammer: programmer,
}),
isToggled: () =>
Programmer.equals(programmer, selectedProgrammer),
};
this.menuRegistry.registerMenuAction(programmersMenuPath, {
commandId: command.id,
label: name,
});
this.commandRegistry.registerCommand(command, handler);
this.toDisposeOnBoardChange.pushAll([
Disposable.create(() =>
this.commandRegistry.unregisterCommand(command)
),
Disposable.create(() =>
this.menuRegistry.unregisterMenuAction(command.id)
),
]);
}
}
this.menuManager.update();
}
}
});
}
}

View File

@ -1,92 +0,0 @@
import { nls } from '@theia/core/lib/common';
import { injectable } from '@theia/core/shared/inversify';
import { CoreService } from '../../common/protocol';
import { ArduinoMenus } from '../menu/arduino-menus';
import {
Command,
CommandRegistry,
CoreServiceContribution,
MenuModelRegistry,
} from './contribution';
@injectable()
export class BurnBootloader extends CoreServiceContribution {
override registerCommands(registry: CommandRegistry): void {
registry.registerCommand(BurnBootloader.Commands.BURN_BOOTLOADER, {
execute: () => this.burnBootloader(),
});
}
override registerMenus(registry: MenuModelRegistry): void {
registry.registerMenuAction(ArduinoMenus.TOOLS__BOARD_SETTINGS_GROUP, {
commandId: BurnBootloader.Commands.BURN_BOOTLOADER.id,
label: nls.localize(
'arduino/bootloader/burnBootloader',
'Burn Bootloader'
),
order: 'z99',
});
}
private async burnBootloader(): Promise<void> {
this.clearVisibleNotification();
const options = await this.options();
try {
await this.doWithProgress({
progressText: nls.localize(
'arduino/bootloader/burningBootloader',
'Burning bootloader...'
),
task: (progressId, coreService, token) =>
coreService.burnBootloader(
{
...options,
progressId,
},
token
),
cancelable: true,
});
this.messageService.info(
nls.localize(
'arduino/bootloader/doneBurningBootloader',
'Done burning bootloader.'
),
{
timeout: 3000,
}
);
} catch (e) {
this.handleError(e);
}
}
private async options(): Promise<CoreService.Options.Bootloader> {
const { boardsConfig } = this.boardsServiceProvider;
const port = boardsConfig.selectedPort;
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'),
]);
return {
fqbn,
programmer,
port,
verify,
verbose,
};
}
}
export namespace BurnBootloader {
export namespace Commands {
export const BURN_BOOTLOADER: Command = {
id: 'arduino-burn-bootloader',
};
}
}

View File

@ -1,123 +0,0 @@
import { nls } from '@theia/core/lib/common/nls';
import { LocalStorageService } from '@theia/core/lib/browser/storage-service';
import { inject, injectable } from '@theia/core/shared/inversify';
import {
IDEUpdater,
LAST_USED_IDE_VERSION,
SKIP_IDE_VERSION,
} from '../../common/protocol/ide-updater';
import { IDEUpdaterDialog } from '../dialogs/ide-updater/ide-updater-dialog';
import { Contribution } from './contribution';
import { VersionWelcomeDialog } from '../dialogs/version-welcome-dialog';
import { AppService } from '../app-service';
import { SemVer } from 'semver';
@injectable()
export class CheckForIDEUpdates extends Contribution {
@inject(IDEUpdater)
private readonly updater: IDEUpdater;
@inject(IDEUpdaterDialog)
private readonly updaterDialog: IDEUpdaterDialog;
@inject(VersionWelcomeDialog)
private readonly versionWelcomeDialog: VersionWelcomeDialog;
@inject(LocalStorageService)
private readonly localStorage: LocalStorageService;
@inject(AppService)
private readonly appService: AppService;
override onStart(): void {
this.preferences.onPreferenceChanged(
({ preferenceName, newValue, oldValue }) => {
if (newValue !== oldValue) {
switch (preferenceName) {
case 'arduino.ide.updateChannel':
case 'arduino.ide.updateBaseUrl':
this.updater.init(
this.preferences.get('arduino.ide.updateChannel'),
this.preferences.get('arduino.ide.updateBaseUrl')
);
}
}
}
);
}
override async onReady(): Promise<void> {
this.updater
.init(
this.preferences.get('arduino.ide.updateChannel'),
this.preferences.get('arduino.ide.updateBaseUrl')
)
.then(() => {
if (!this.preferences['arduino.checkForUpdates']) {
return;
}
return this.updater.checkForUpdates(true);
})
.then(async (updateInfo) => {
if (!updateInfo) {
const isNewVersion = await this.isNewStableVersion();
if (isNewVersion) {
this.versionWelcomeDialog.open();
}
return;
}
const versionToSkip = await this.localStorage.getData<string>(
SKIP_IDE_VERSION
);
if (versionToSkip === updateInfo.version) return;
this.updaterDialog.open(true, updateInfo);
})
.catch((e) => {
this.messageService.error(
nls.localize(
'arduino/ide-updater/errorCheckingForUpdates',
'Error while checking for Arduino IDE updates.\n{0}',
e.message
)
);
})
.finally(() => {
this.setCurrentIDEVersion();
});
}
private async setCurrentIDEVersion(): Promise<void> {
try {
const { appVersion } = await this.appService.info();
const currSemVer = new SemVer(appVersion ?? '');
this.localStorage.setData(LAST_USED_IDE_VERSION, currSemVer.format());
} catch {
// ignore invalid versions
}
}
/**
* Check if user is running a new IDE version for the first time.
* @returns true if the current IDE version is greater than the last used version
* and both are non-prerelease versions.
*/
private async isNewStableVersion(): Promise<boolean> {
try {
const { appVersion } = await this.appService.info();
const prevVersion = await this.localStorage.getData<string>(
LAST_USED_IDE_VERSION
);
const prevSemVer = new SemVer(prevVersion ?? '');
const currSemVer = new SemVer(appVersion ?? '');
if (prevSemVer.prerelease.length || currSemVer.prerelease.length) {
return false;
}
return currSemVer.compare(prevSemVer) === 1;
} catch (e) {
return false;
}
}
}

View File

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

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