mirror of
https://github.com/arduino/arduino-ide.git
synced 2025-10-25 02:58:33 +00:00
Compare commits
211 Commits
2.0.0-beta
...
2.0.0-rc4
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
96b5edf427 | ||
|
|
a5a6a0b611 | ||
|
|
2a27a14a68 | ||
|
|
f2d492b5dc | ||
|
|
5979e5aad2 | ||
|
|
baa9b5f7ab | ||
|
|
481497e384 | ||
|
|
0207778373 | ||
|
|
d79f32efd7 | ||
|
|
3ab03dd62f | ||
|
|
bc3cb0c230 | ||
|
|
473cb11053 | ||
|
|
0a87fd00f3 | ||
|
|
9b1f15def8 | ||
|
|
77b430675d | ||
|
|
f660058c75 | ||
|
|
9ecff86bbe | ||
|
|
5ab3a747a6 | ||
|
|
877c1a1559 | ||
|
|
2f9bf86d75 | ||
|
|
112153fb96 | ||
|
|
69ac1f4779 | ||
|
|
a20899ff43 | ||
|
|
ef2be1c086 | ||
|
|
af33dce0f6 | ||
|
|
b3b22795f8 | ||
|
|
8a0454db51 | ||
|
|
f1a5d87ab2 | ||
|
|
cf0a2161af | ||
|
|
dcebd863cc | ||
|
|
e8477b14f3 | ||
|
|
0230071b5f | ||
|
|
1d88263c85 | ||
|
|
a71ac4c44d | ||
|
|
66fc27e58c | ||
|
|
bc365f4a8d | ||
|
|
a5891f9884 | ||
|
|
fcdf16a937 | ||
|
|
e0b6dbbf2a | ||
|
|
9529e78647 | ||
|
|
51da3c0668 | ||
|
|
c00d3d33dd | ||
|
|
cfa9b8aea6 | ||
|
|
6106e9ff1a | ||
|
|
b1d9f65a0d | ||
|
|
f4008100e1 | ||
|
|
11a6959a24 | ||
|
|
3c6e11832b | ||
|
|
c064673ce1 | ||
|
|
cc5764e536 | ||
|
|
9131f2d09e | ||
|
|
0b6fc0b973 | ||
|
|
c91fe2d775 | ||
|
|
bbded57ae4 | ||
|
|
a8ae0bb4e0 | ||
|
|
49d12d99ff | ||
|
|
767b09d2f1 | ||
|
|
88397931c5 | ||
|
|
5ddab1ded7 | ||
|
|
f0d9894a16 | ||
|
|
59e4c57ecd | ||
|
|
dd76f9180c | ||
|
|
6e34a27b7e | ||
|
|
a090dfe99c | ||
|
|
74bfdc4c56 | ||
|
|
20f7712129 | ||
|
|
9863dc2f90 | ||
|
|
13734a642c | ||
|
|
7ac7ae9063 | ||
|
|
437caeb348 | ||
|
|
3b04d8df26 | ||
|
|
99d65531c4 | ||
|
|
4f4ccb8c66 | ||
|
|
7bc83eba1d | ||
|
|
72750f0be3 | ||
|
|
8cbf7f419c | ||
|
|
ea2aeec69b | ||
|
|
b83702fde3 | ||
|
|
5be3e9de2d | ||
|
|
e8bc7d7179 | ||
|
|
acbb164c3c | ||
|
|
99099b06aa | ||
|
|
5c958bc6c7 | ||
|
|
11b75bd610 | ||
|
|
61262c23ac | ||
|
|
7503739a9f | ||
|
|
060ab5bccb | ||
|
|
1c42b8cefc | ||
|
|
825f0b0f2a | ||
|
|
846c22cb03 | ||
|
|
fc0f67493b | ||
|
|
54a67fc67c | ||
|
|
7f8b227c39 | ||
|
|
ba177be41d | ||
|
|
0eb2d25570 | ||
|
|
e9db1c0482 | ||
|
|
79b075c961 | ||
|
|
a46f36acd1 | ||
|
|
bfb90a8b4f | ||
|
|
658c19f55b | ||
|
|
3f8a07654d | ||
|
|
a8ec7c2640 | ||
|
|
a7a1f95ced | ||
|
|
835e9913ae | ||
|
|
d3d6ba8176 | ||
|
|
0f82e91380 | ||
|
|
7d5381bbde | ||
|
|
302fb7b6af | ||
|
|
6233e1fa98 | ||
|
|
2cb9889fe4 | ||
|
|
bed6e0b741 | ||
|
|
302f0109dd | ||
|
|
735d3733e2 | ||
|
|
4b36852f57 | ||
|
|
b84b6c921d | ||
|
|
289f07f187 | ||
|
|
b9c777a5c3 | ||
|
|
92af4bef26 | ||
|
|
167f059163 | ||
|
|
93515fc906 | ||
|
|
20c2e1c67e | ||
|
|
65152731f9 | ||
|
|
57b9eb95bb | ||
|
|
64dc124a53 | ||
|
|
38d372e2d5 | ||
|
|
5897f379a4 | ||
|
|
d790266cc8 | ||
|
|
4da5d573e4 | ||
|
|
4e6f9ae75d | ||
|
|
e10f0f1683 | ||
|
|
40a73af82b | ||
|
|
461ca06445 | ||
|
|
773675e3c5 | ||
|
|
4c536ec8fc | ||
|
|
e6cbefb880 | ||
|
|
0592199858 | ||
|
|
2a3873a923 | ||
|
|
05c0505228 | ||
|
|
8c4e66f536 | ||
|
|
cd0f1b3163 | ||
|
|
4fa2024266 | ||
|
|
852bf9b73e | ||
|
|
db48ed616b | ||
|
|
0dd1e45233 | ||
|
|
2a55ddd757 | ||
|
|
3240bf7f3d | ||
|
|
0d0ad9efae | ||
|
|
9aff90b0af | ||
|
|
8071298598 | ||
|
|
c86d82d273 | ||
|
|
fa9334eb7a | ||
|
|
c50d45c663 | ||
|
|
c20f832ddf | ||
|
|
cb2ef78c0a | ||
|
|
68af4c38fe | ||
|
|
a8df2444a9 | ||
|
|
d45dd6beef | ||
|
|
1ab5634789 | ||
|
|
80bddc238d | ||
|
|
8a692d0ce5 | ||
|
|
98671225ac | ||
|
|
f106c97f1e | ||
|
|
369a8f4307 | ||
|
|
4e7f8291e8 | ||
|
|
26a1db3cf8 | ||
|
|
a3f7b795a0 | ||
|
|
b422fc5298 | ||
|
|
ab320eb0b0 | ||
|
|
b17b7a6de7 | ||
|
|
562b77aec3 | ||
|
|
cdd5cfdfc1 | ||
|
|
f712ec986f | ||
|
|
c75b954041 | ||
|
|
3fb087f1ad | ||
|
|
27292774d7 | ||
|
|
da424f34cc | ||
|
|
f6e623ca9c | ||
|
|
1e0f52bbdd | ||
|
|
6dadd1775a | ||
|
|
067cc8766a | ||
|
|
15b0564212 | ||
|
|
e90fa27ebf | ||
|
|
ef03d3f583 | ||
|
|
5c8669d699 | ||
|
|
9cd91464e3 | ||
|
|
5a262d42c1 | ||
|
|
eadc993854 | ||
|
|
c64ac48fe3 | ||
|
|
ac502053d7 | ||
|
|
1d8eb0d544 | ||
|
|
e94702349b | ||
|
|
d648159f43 | ||
|
|
acbd98d0f8 | ||
|
|
22e02e19b8 | ||
|
|
7ee6d5ad8f | ||
|
|
19aa3dd8a5 | ||
|
|
de4ae232fa | ||
|
|
5a57576320 | ||
|
|
8e1feb36ff | ||
|
|
cdadda85e5 | ||
|
|
596d54a102 | ||
|
|
e1b36c6c56 | ||
|
|
86be874bb0 | ||
|
|
057904d38d | ||
|
|
0aef4b328f | ||
|
|
79b1a306a1 | ||
|
|
709baaca98 | ||
|
|
a06a69dff9 | ||
|
|
561d5fbbd3 | ||
|
|
df0aafd928 | ||
|
|
ad2cfc8894 |
65
.eslintrc.js
Normal file
65
.eslintrc.js
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
module.exports = {
|
||||||
|
parser: '@typescript-eslint/parser', // Specifies the ESLint parser
|
||||||
|
parserOptions: {
|
||||||
|
ecmaVersion: 2020, // Allows for the parsing of modern ECMAScript features
|
||||||
|
sourceType: 'module', // Allows for the use of imports
|
||||||
|
ecmaFeatures: {
|
||||||
|
jsx: true, // Allows for the parsing of JSX
|
||||||
|
},
|
||||||
|
},
|
||||||
|
ignorePatterns: [
|
||||||
|
'node_modules/*',
|
||||||
|
'**/node_modules/*',
|
||||||
|
'.node_modules/*',
|
||||||
|
'.github/*',
|
||||||
|
'.browser_modules/*',
|
||||||
|
'docs/*',
|
||||||
|
'scripts/*',
|
||||||
|
'electron/*',
|
||||||
|
'electron-app/*',
|
||||||
|
'browser-app/*',
|
||||||
|
'plugins/*',
|
||||||
|
'arduino-ide-extension/src/node/cli-protocol',
|
||||||
|
],
|
||||||
|
settings: {
|
||||||
|
react: {
|
||||||
|
version: 'detect', // Tells eslint-plugin-react to automatically detect the version of React to use
|
||||||
|
},
|
||||||
|
},
|
||||||
|
extends: [
|
||||||
|
'plugin:@typescript-eslint/recommended', // Uses the recommended rules from the @typescript-eslint/eslint-plugin
|
||||||
|
'plugin:react/recommended', // Uses the recommended rules from @eslint-plugin-react
|
||||||
|
'plugin:react-hooks/recommended', // Uses recommended rules from react hooks
|
||||||
|
'plugin:prettier/recommended',
|
||||||
|
'prettier', // Uses eslint-config-prettier to disable ESLint rules from @typescript-eslint/eslint-plugin that would conflict with prettier
|
||||||
|
],
|
||||||
|
plugins: ['prettier', 'unused-imports'],
|
||||||
|
rules: {
|
||||||
|
'@typescript-eslint/no-unused-expressions': 'off',
|
||||||
|
'@typescript-eslint/no-namespace': 'off',
|
||||||
|
'@typescript-eslint/no-var-requires': 'off',
|
||||||
|
'@typescript-eslint/no-empty-function': 'warn',
|
||||||
|
'@typescript-eslint/no-empty-interface': 'warn',
|
||||||
|
'no-unused-vars': 'off',
|
||||||
|
'unused-imports/no-unused-imports': 'error',
|
||||||
|
'unused-imports/no-unused-vars': [
|
||||||
|
'warn',
|
||||||
|
{
|
||||||
|
vars: 'all',
|
||||||
|
varsIgnorePattern: '^_',
|
||||||
|
args: 'after-used',
|
||||||
|
argsIgnorePattern: '^_',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
'react/display-name': 'warn',
|
||||||
|
eqeqeq: ['error', 'smart'],
|
||||||
|
'guard-for-in': 'off',
|
||||||
|
'id-blacklist': 'off',
|
||||||
|
'id-match': 'off',
|
||||||
|
'no-underscore-dangle': 'off',
|
||||||
|
'no-unused-expressions': 'off',
|
||||||
|
'no-var': 'error',
|
||||||
|
radix: 'error',
|
||||||
|
'prettier/prettier': 'warn',
|
||||||
|
},
|
||||||
|
};
|
||||||
2
.github/ISSUE_TEMPLATE/bug_report.md
vendored
2
.github/ISSUE_TEMPLATE/bug_report.md
vendored
@@ -2,7 +2,7 @@
|
|||||||
name: Bug report
|
name: Bug report
|
||||||
about: Create a report to help us improve
|
about: Create a report to help us improve
|
||||||
title: ''
|
title: ''
|
||||||
labels: bug
|
labels: 'type: imperfection'
|
||||||
assignees: ''
|
assignees: ''
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
2
.github/ISSUE_TEMPLATE/feature_request.md
vendored
2
.github/ISSUE_TEMPLATE/feature_request.md
vendored
@@ -2,7 +2,7 @@
|
|||||||
name: Feature request
|
name: Feature request
|
||||||
about: Suggest an idea for this project
|
about: Suggest an idea for this project
|
||||||
title: ''
|
title: ''
|
||||||
labels: enhancement
|
labels: 'type: enhancement'
|
||||||
assignees: ''
|
assignees: ''
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
24
.github/label-configuration-files/labels.yml
vendored
Normal file
24
.github/label-configuration-files/labels.yml
vendored
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
# 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: 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
|
||||||
131
.github/tools/fetch_athena_stats.py
vendored
Normal file
131
.github/tools/fetch_athena_stats.py
vendored
Normal file
@@ -0,0 +1,131 @@
|
|||||||
|
import boto3
|
||||||
|
import semver
|
||||||
|
import os
|
||||||
|
import logging
|
||||||
|
import uuid
|
||||||
|
import time
|
||||||
|
|
||||||
|
|
||||||
|
# logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
|
||||||
|
log = logging.getLogger()
|
||||||
|
logging.getLogger("boto3").setLevel(logging.CRITICAL)
|
||||||
|
logging.getLogger("botocore").setLevel(logging.CRITICAL)
|
||||||
|
logging.getLogger("urllib3").setLevel(logging.CRITICAL)
|
||||||
|
|
||||||
|
|
||||||
|
def execute(client, statement, dest_s3_output_location):
|
||||||
|
log.info("execute query: {} dumping in {}".format(statement, dest_s3_output_location))
|
||||||
|
result = client.start_query_execution(
|
||||||
|
QueryString=statement,
|
||||||
|
ClientRequestToken=str(uuid.uuid4()),
|
||||||
|
ResultConfiguration={
|
||||||
|
"OutputLocation": dest_s3_output_location,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
execution_id = result["QueryExecutionId"]
|
||||||
|
log.info("wait for query {} completion".format(execution_id))
|
||||||
|
wait_for_query_execution_completion(client, execution_id)
|
||||||
|
log.info("operation successful")
|
||||||
|
return execution_id
|
||||||
|
|
||||||
|
|
||||||
|
def wait_for_query_execution_completion(client, query_execution_id):
|
||||||
|
query_ended = False
|
||||||
|
while not query_ended:
|
||||||
|
query_execution = client.get_query_execution(QueryExecutionId=query_execution_id)
|
||||||
|
state = query_execution["QueryExecution"]["Status"]["State"]
|
||||||
|
if state == "SUCCEEDED":
|
||||||
|
query_ended = True
|
||||||
|
elif state in ["FAILED", "CANCELLED"]:
|
||||||
|
raise BaseException(
|
||||||
|
"query failed or canceled: {}".format(query_execution["QueryExecution"]["Status"]["StateChangeReason"])
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
time.sleep(1)
|
||||||
|
|
||||||
|
|
||||||
|
def valid(key):
|
||||||
|
split = key.split("_")
|
||||||
|
if len(split) < 1:
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
semver.parse(split[0])
|
||||||
|
except ValueError:
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def get_results(client, execution_id):
|
||||||
|
results_paginator = client.get_paginator("get_query_results")
|
||||||
|
results_iter = results_paginator.paginate(QueryExecutionId=execution_id, PaginationConfig={"PageSize": 1000})
|
||||||
|
res = {}
|
||||||
|
for results_page in results_iter:
|
||||||
|
for row in results_page["ResultSet"]["Rows"][1:]:
|
||||||
|
# Loop through the JSON objects
|
||||||
|
key = row["Data"][0]["VarCharValue"]
|
||||||
|
if valid(key):
|
||||||
|
res[key] = row["Data"][1]["VarCharValue"]
|
||||||
|
|
||||||
|
return res
|
||||||
|
|
||||||
|
|
||||||
|
def convert_data(data):
|
||||||
|
result = []
|
||||||
|
for key, value in data.items():
|
||||||
|
# 0.18.0_macOS_64bit.tar.gz
|
||||||
|
split_key = key.split("_")
|
||||||
|
if len(split_key) != 3:
|
||||||
|
continue
|
||||||
|
(version, os_version, arch) = split_key
|
||||||
|
arch_split = arch.split(".")
|
||||||
|
if len(arch_split) < 1:
|
||||||
|
continue
|
||||||
|
arch = arch_split[0]
|
||||||
|
if len(arch) > 10:
|
||||||
|
# This can't be an architecture really.
|
||||||
|
# It's an ugly solution but works for now so deal with it.
|
||||||
|
continue
|
||||||
|
repo = os.environ["GITHUB_REPOSITORY"].split("/")[1]
|
||||||
|
result.append(
|
||||||
|
{
|
||||||
|
"type": "gauge",
|
||||||
|
"name": "arduino.downloads.total",
|
||||||
|
"value": value,
|
||||||
|
"host": os.environ["GITHUB_REPOSITORY"],
|
||||||
|
"tags": [
|
||||||
|
f"version:{version}",
|
||||||
|
f"os:{os_version}",
|
||||||
|
f"arch:{arch}",
|
||||||
|
"cdn:downloads.arduino.cc",
|
||||||
|
f"project:{repo}",
|
||||||
|
],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
DEST_S3_OUTPUT = os.environ["AWS_ATHENA_OUTPUT_LOCATION"]
|
||||||
|
AWS_ATHENA_SOURCE_TABLE = os.environ["AWS_ATHENA_SOURCE_TABLE"]
|
||||||
|
|
||||||
|
session = boto3.session.Session(region_name="us-east-1")
|
||||||
|
athena_client = session.client("athena")
|
||||||
|
|
||||||
|
# Load all partitions before querying downloads
|
||||||
|
execute(athena_client, f"MSCK REPAIR TABLE {AWS_ATHENA_SOURCE_TABLE};", DEST_S3_OUTPUT)
|
||||||
|
|
||||||
|
query = f"""SELECT replace(json_extract_scalar(url_decode(url_decode(querystring)),
|
||||||
|
'$.data.url'), 'https://downloads.arduino.cc/arduino-ide/arduino-ide_', '')
|
||||||
|
AS flavor, count(json_extract(url_decode(url_decode(querystring)),'$')) AS gauge
|
||||||
|
FROM {AWS_ATHENA_SOURCE_TABLE}
|
||||||
|
WHERE json_extract_scalar(url_decode(url_decode(querystring)),'$.data.url')
|
||||||
|
LIKE 'https://downloads.arduino.cc/arduino-ide/arduino-ide_%'
|
||||||
|
AND json_extract_scalar(url_decode(url_decode(querystring)),'$.data.url')
|
||||||
|
NOT LIKE '%latest%' -- exclude latest redirect
|
||||||
|
group by 1 ;"""
|
||||||
|
exec_id = execute(athena_client, query, DEST_S3_OUTPUT)
|
||||||
|
results = get_results(athena_client, exec_id)
|
||||||
|
result_json = convert_data(results)
|
||||||
|
|
||||||
|
print(f"::set-output name=result::{result_json}")
|
||||||
57
.github/workflows/arduino-stats.yaml
vendored
Normal file
57
.github/workflows/arduino-stats.yaml
vendored
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
name: arduino-stats
|
||||||
|
|
||||||
|
on:
|
||||||
|
schedule:
|
||||||
|
# run every day at 07:00 AM, 03:00 PM and 11:00 PM
|
||||||
|
- cron: "0 7,15,23 * * *"
|
||||||
|
workflow_dispatch:
|
||||||
|
repository_dispatch:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
push-stats:
|
||||||
|
# This workflow is only of value to the arduino/arduino-ide repository and
|
||||||
|
# would always fail in forks
|
||||||
|
if: github.repository == 'arduino/arduino-ide'
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v2
|
||||||
|
|
||||||
|
- uses: actions/setup-python@v2
|
||||||
|
with:
|
||||||
|
python-version: '3.x'
|
||||||
|
|
||||||
|
- name: Fetch downloads count form Arduino CDN using AWS Athena
|
||||||
|
id: fetch
|
||||||
|
env:
|
||||||
|
AWS_ACCESS_KEY_ID: ${{ secrets.STATS_AWS_ACCESS_KEY_ID }}
|
||||||
|
AWS_SECRET_ACCESS_KEY: ${{ secrets.STATS_AWS_SECRET_ACCESS_KEY }}
|
||||||
|
AWS_ATHENA_SOURCE_TABLE: ${{ secrets.STATS_AWS_ATHENA_SOURCE_TABLE }}
|
||||||
|
AWS_ATHENA_OUTPUT_LOCATION: ${{ secrets.STATS_AWS_ATHENA_OUTPUT_LOCATION }}
|
||||||
|
GITHUB_REPOSITORY: ${{ github.repository }}
|
||||||
|
run: |
|
||||||
|
pip install boto3 semver
|
||||||
|
python .github/tools/fetch_athena_stats.py
|
||||||
|
|
||||||
|
- name: Send metrics
|
||||||
|
uses: masci/datadog@v1
|
||||||
|
with:
|
||||||
|
api-key: ${{ secrets.DD_API_KEY }}
|
||||||
|
# Metrics input expects YAML but JSON will work just right.
|
||||||
|
metrics: ${{steps.fetch.outputs.result}}
|
||||||
|
|
||||||
|
- name: Report failure
|
||||||
|
if: failure()
|
||||||
|
uses: masci/datadog@v1
|
||||||
|
with:
|
||||||
|
api-key: ${{ secrets.DD_API_KEY }}
|
||||||
|
events: |
|
||||||
|
- title: "Arduino IDE stats failing"
|
||||||
|
text: "Stats collection failed"
|
||||||
|
alert_type: "error"
|
||||||
|
host: ${{ github.repository }}
|
||||||
|
tags:
|
||||||
|
- "project:arduino-ide"
|
||||||
|
- "cdn:downloads.arduino.cc"
|
||||||
|
- "workflow:${{ github.workflow }}"
|
||||||
108
.github/workflows/build.yml
vendored
108
.github/workflows/build.yml
vendored
@@ -13,14 +13,18 @@ on:
|
|||||||
schedule:
|
schedule:
|
||||||
- cron: '0 3 * * *' # run every day at 3AM (https://docs.github.com/en/actions/reference/events-that-trigger-workflows#scheduled-events-schedule)
|
- cron: '0 3 * * *' # run every day at 3AM (https://docs.github.com/en/actions/reference/events-that-trigger-workflows#scheduled-events-schedule)
|
||||||
|
|
||||||
jobs:
|
env:
|
||||||
|
JOB_TRANSFER_ARTIFACT: build-artifacts
|
||||||
|
CHANGELOG_ARTIFACTS: changelog
|
||||||
|
|
||||||
|
jobs:
|
||||||
build:
|
build:
|
||||||
|
if: github.repository == 'arduino/arduino-ide'
|
||||||
strategy:
|
strategy:
|
||||||
matrix:
|
matrix:
|
||||||
config:
|
config:
|
||||||
- os: windows-latest
|
- os: windows-2019
|
||||||
- os: ubuntu-latest
|
- os: ubuntu-18.04 # https://github.com/arduino/arduino-ide/issues/259
|
||||||
- os: macos-latest
|
- os: macos-latest
|
||||||
runs-on: ${{ matrix.config.os }}
|
runs-on: ${{ matrix.config.os }}
|
||||||
timeout-minutes: 90
|
timeout-minutes: 90
|
||||||
@@ -29,16 +33,16 @@ jobs:
|
|||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v2
|
||||||
|
|
||||||
- name: Install Node.js 12.x
|
- name: Install Node.js 14.x
|
||||||
uses: actions/setup-node@v1
|
uses: actions/setup-node@v1
|
||||||
with:
|
with:
|
||||||
node-version: '12.14.1'
|
node-version: '14.x'
|
||||||
registry-url: 'https://registry.npmjs.org'
|
registry-url: 'https://registry.npmjs.org'
|
||||||
|
|
||||||
- name: Install Python 2.7
|
- name: Install Python 3.x
|
||||||
uses: actions/setup-python@v2
|
uses: actions/setup-python@v2
|
||||||
with:
|
with:
|
||||||
python-version: '2.7'
|
python-version: '3.x'
|
||||||
|
|
||||||
- name: Package
|
- name: Package
|
||||||
shell: bash
|
shell: bash
|
||||||
@@ -46,12 +50,17 @@ jobs:
|
|||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
AC_USERNAME: ${{ secrets.AC_USERNAME }}
|
AC_USERNAME: ${{ secrets.AC_USERNAME }}
|
||||||
AC_PASSWORD: ${{ secrets.AC_PASSWORD }}
|
AC_PASSWORD: ${{ secrets.AC_PASSWORD }}
|
||||||
|
AC_TEAM_ID: ${{ secrets.AC_TEAM_ID }}
|
||||||
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
|
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
|
||||||
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
|
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
|
||||||
IS_NIGHTLY: ${{ github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main') }}
|
IS_NIGHTLY: ${{ github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main') }}
|
||||||
IS_RELEASE: ${{ startsWith(github.ref, 'refs/tags/') }}
|
IS_RELEASE: ${{ startsWith(github.ref, 'refs/tags/') }}
|
||||||
|
IS_FORK: ${{ github.event.pull_request.head.repo.fork == true }}
|
||||||
run: |
|
run: |
|
||||||
# See: https://www.electron.build/code-signing
|
# See: https://www.electron.build/code-signing
|
||||||
|
if [ $IS_FORK = true ]; then
|
||||||
|
echo "Skipping the app signing: building from a fork."
|
||||||
|
else
|
||||||
if [ "${{ runner.OS }}" = "macOS" ]; then
|
if [ "${{ runner.OS }}" = "macOS" ]; then
|
||||||
export CSC_LINK="${{ runner.temp }}/signing_certificate.p12"
|
export CSC_LINK="${{ runner.temp }}/signing_certificate.p12"
|
||||||
# APPLE_SIGNING_CERTIFICATE_P12 secret was produced by following the procedure from:
|
# APPLE_SIGNING_CERTIFICATE_P12 secret was produced by following the procedure from:
|
||||||
@@ -62,10 +71,12 @@ jobs:
|
|||||||
|
|
||||||
elif [ "${{ runner.OS }}" = "Windows" ]; then
|
elif [ "${{ runner.OS }}" = "Windows" ]; then
|
||||||
export CSC_LINK="${{ runner.temp }}/signing_certificate.pfx"
|
export CSC_LINK="${{ runner.temp }}/signing_certificate.pfx"
|
||||||
|
npm config set msvs_version 2017 --global
|
||||||
echo "${{ secrets.WINDOWS_SIGNING_CERTIFICATE_PFX }}" | base64 --decode > "$CSC_LINK"
|
echo "${{ secrets.WINDOWS_SIGNING_CERTIFICATE_PFX }}" | base64 --decode > "$CSC_LINK"
|
||||||
|
|
||||||
export CSC_KEY_PASSWORD="${{ secrets.WINDOWS_SIGNING_CERTIFICATE_PASSWORD }}"
|
export CSC_KEY_PASSWORD="${{ secrets.WINDOWS_SIGNING_CERTIFICATE_PASSWORD }}"
|
||||||
fi
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
yarn --cwd ./electron/packager/
|
yarn --cwd ./electron/packager/
|
||||||
yarn --cwd ./electron/packager/ package
|
yarn --cwd ./electron/packager/ package
|
||||||
@@ -73,9 +84,46 @@ jobs:
|
|||||||
- name: Upload [GitHub Actions]
|
- name: Upload [GitHub Actions]
|
||||||
uses: actions/upload-artifact@v2
|
uses: actions/upload-artifact@v2
|
||||||
with:
|
with:
|
||||||
name: build-artifacts
|
name: ${{ env.JOB_TRANSFER_ARTIFACT }}
|
||||||
path: electron/build/dist/build-artifacts/
|
path: electron/build/dist/build-artifacts/
|
||||||
|
|
||||||
|
artifacts:
|
||||||
|
name: ${{ matrix.artifact.name }} artifact
|
||||||
|
needs: build
|
||||||
|
if: always() && needs.build.result != 'skipped'
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
artifact:
|
||||||
|
- path: '*Linux_64bit.zip'
|
||||||
|
name: Linux_X86-64_zip
|
||||||
|
- path: '*Linux_64bit.AppImage'
|
||||||
|
name: Linux_X86-64_app_image
|
||||||
|
- path: '*macOS_64bit.dmg'
|
||||||
|
name: macOS_dmg
|
||||||
|
- path: '*macOS_64bit.zip'
|
||||||
|
name: macOS_zip
|
||||||
|
- path: '*Windows_64bit.exe'
|
||||||
|
name: Windows_X86-64_interactive_installer
|
||||||
|
- path: '*Windows_64bit.msi'
|
||||||
|
name: Windows_X86-64_MSI
|
||||||
|
- path: '*Windows_64bit.zip'
|
||||||
|
name: Windows_X86-64_zip
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Download job transfer artifact
|
||||||
|
uses: actions/download-artifact@v2
|
||||||
|
with:
|
||||||
|
name: ${{ env.JOB_TRANSFER_ARTIFACT }}
|
||||||
|
path: ${{ env.JOB_TRANSFER_ARTIFACT }}
|
||||||
|
|
||||||
|
- name: Upload tester build artifact
|
||||||
|
uses: actions/upload-artifact@v2
|
||||||
|
with:
|
||||||
|
name: ${{ matrix.artifact.name }}
|
||||||
|
path: ${{ env.JOB_TRANSFER_ARTIFACT }}/${{ matrix.artifact.path }}
|
||||||
|
|
||||||
changelog:
|
changelog:
|
||||||
needs: build
|
needs: build
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
@@ -115,40 +163,40 @@ jobs:
|
|||||||
if: github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main')
|
if: github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main')
|
||||||
uses: actions/upload-artifact@v2
|
uses: actions/upload-artifact@v2
|
||||||
with:
|
with:
|
||||||
name: build-artifacts
|
name: ${{ env.JOB_TRANSFER_ARTIFACT }}
|
||||||
path: CHANGELOG.txt
|
path: CHANGELOG.txt
|
||||||
|
|
||||||
publish:
|
publish:
|
||||||
needs: changelog
|
needs: changelog
|
||||||
if: github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main')
|
if: github.repository == 'arduino/arduino-ide' && (github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main'))
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Download [GitHub Actions]
|
- name: Download [GitHub Actions]
|
||||||
uses: actions/download-artifact@v2
|
uses: actions/download-artifact@v2
|
||||||
with:
|
with:
|
||||||
name: build-artifacts
|
name: ${{ env.JOB_TRANSFER_ARTIFACT }}
|
||||||
path: build-artifacts
|
path: ${{ env.JOB_TRANSFER_ARTIFACT }}
|
||||||
|
|
||||||
- name: Publish Nightly [S3]
|
- name: Publish Nightly [S3]
|
||||||
uses: docker://plugins/s3
|
uses: docker://plugins/s3
|
||||||
env:
|
env:
|
||||||
PLUGIN_SOURCE: "build-artifacts/*"
|
PLUGIN_SOURCE: '${{ env.JOB_TRANSFER_ARTIFACT }}/*'
|
||||||
PLUGIN_STRIP_PREFIX: "build-artifacts/"
|
PLUGIN_STRIP_PREFIX: '${{ env.JOB_TRANSFER_ARTIFACT }}/'
|
||||||
PLUGIN_TARGET: "/arduino-ide/nightly"
|
PLUGIN_TARGET: '/arduino-ide/nightly'
|
||||||
PLUGIN_BUCKET: ${{ secrets.DOWNLOADS_BUCKET }}
|
PLUGIN_BUCKET: ${{ secrets.DOWNLOADS_BUCKET }}
|
||||||
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
|
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
|
||||||
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
|
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
|
||||||
|
|
||||||
release:
|
release:
|
||||||
needs: changelog
|
needs: changelog
|
||||||
if: startsWith(github.ref, 'refs/tags/')
|
if: github.repository == 'arduino/arduino-ide' && startsWith(github.ref, 'refs/tags/')
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Download [GitHub Actions]
|
- name: Download [GitHub Actions]
|
||||||
uses: actions/download-artifact@v2
|
uses: actions/download-artifact@v2
|
||||||
with:
|
with:
|
||||||
name: build-artifacts
|
name: ${{ env.JOB_TRANSFER_ARTIFACT }}
|
||||||
path: build-artifacts
|
path: ${{ env.JOB_TRANSFER_ARTIFACT }}
|
||||||
|
|
||||||
- name: Get Tag
|
- name: Get Tag
|
||||||
id: tag_name
|
id: tag_name
|
||||||
@@ -160,7 +208,7 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
repo_token: ${{ secrets.GITHUB_TOKEN }}
|
repo_token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
release_name: ${{ steps.tag_name.outputs.TAG_NAME }}
|
release_name: ${{ steps.tag_name.outputs.TAG_NAME }}
|
||||||
file: build-artifacts/*
|
file: ${{ env.JOB_TRANSFER_ARTIFACT }}/*
|
||||||
tag: ${{ github.ref }}
|
tag: ${{ github.ref }}
|
||||||
file_glob: true
|
file_glob: true
|
||||||
body: ${{ needs.changelog.outputs.BODY }}
|
body: ${{ needs.changelog.outputs.BODY }}
|
||||||
@@ -168,9 +216,25 @@ jobs:
|
|||||||
- name: Publish Release [S3]
|
- name: Publish Release [S3]
|
||||||
uses: docker://plugins/s3
|
uses: docker://plugins/s3
|
||||||
env:
|
env:
|
||||||
PLUGIN_SOURCE: "build-artifacts/*"
|
PLUGIN_SOURCE: '${{ env.JOB_TRANSFER_ARTIFACT }}/*'
|
||||||
PLUGIN_STRIP_PREFIX: "build-artifacts/"
|
PLUGIN_STRIP_PREFIX: '${{ env.JOB_TRANSFER_ARTIFACT }}/'
|
||||||
PLUGIN_TARGET: "/arduino-ide"
|
PLUGIN_TARGET: '/arduino-ide'
|
||||||
PLUGIN_BUCKET: ${{ secrets.DOWNLOADS_BUCKET }}
|
PLUGIN_BUCKET: ${{ secrets.DOWNLOADS_BUCKET }}
|
||||||
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
|
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
|
||||||
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
|
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
|
||||||
|
|
||||||
|
clean:
|
||||||
|
# This job must run after all jobs that use the transfer artifact.
|
||||||
|
needs:
|
||||||
|
- build
|
||||||
|
- publish
|
||||||
|
- release
|
||||||
|
- artifacts
|
||||||
|
if: always() && needs.build.result != 'skipped'
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Remove unneeded job transfer artifact
|
||||||
|
uses: geekyeggo/delete-artifact@v1
|
||||||
|
with:
|
||||||
|
name: ${{ env.JOB_TRANSFER_ARTIFACT }}
|
||||||
|
|||||||
48
.github/workflows/check-certificates.yml
vendored
48
.github/workflows/check-certificates.yml
vendored
@@ -1,30 +1,41 @@
|
|||||||
name: Check for issues with signing certificates
|
# 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:
|
on:
|
||||||
|
push:
|
||||||
|
paths:
|
||||||
|
- '.github/workflows/check-certificates.ya?ml'
|
||||||
|
pull_request:
|
||||||
|
paths:
|
||||||
|
- '.github/workflows/check-certificates.ya?ml'
|
||||||
schedule:
|
schedule:
|
||||||
# run every 10 hours
|
# Run every 10 hours.
|
||||||
- cron: "0 */10 * * *"
|
- cron: '0 */10 * * *'
|
||||||
# workflow_dispatch event allows the workflow to be triggered manually.
|
|
||||||
# This could be used to run an immediate check after updating certificate secrets.
|
|
||||||
# See: https://docs.github.com/en/actions/reference/events-that-trigger-workflows#workflow_dispatch
|
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
repository_dispatch:
|
||||||
|
|
||||||
env:
|
env:
|
||||||
# Begin notifications when there are less than this many days remaining before expiration
|
# Begin notifications when there are less than this many days remaining before expiration.
|
||||||
EXPIRATION_WARNING_PERIOD: 30
|
EXPIRATION_WARNING_PERIOD: 30
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
check-certificates:
|
check-certificates:
|
||||||
|
name: ${{ matrix.certificate.identifier }}
|
||||||
|
# Only run when the workflow will have access to the certificate secrets.
|
||||||
|
if: >
|
||||||
|
(github.event_name != 'pull_request' && github.repository == 'arduino/arduino-ide') ||
|
||||||
|
(github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == 'arduino/arduino-ide')
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
|
|
||||||
matrix:
|
matrix:
|
||||||
certificate:
|
certificate:
|
||||||
- identifier: macOS signing certificate # Text used to identify the certificate in notifications
|
# Additional certificate definitions can be added to this list.
|
||||||
certificate-secret: APPLE_SIGNING_CERTIFICATE_P12 # The name of the secret that contains the certificate
|
- identifier: macOS signing certificate # Text used to identify certificate in notifications.
|
||||||
password-secret: KEYCHAIN_PASSWORD # The name of the secret that contains the certificate password
|
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.
|
||||||
- identifier: Windows signing certificate
|
- identifier: Windows signing certificate
|
||||||
certificate-secret: WINDOWS_SIGNING_CERTIFICATE_PFX
|
certificate-secret: WINDOWS_SIGNING_CERTIFICATE_PFX
|
||||||
password-secret: WINDOWS_SIGNING_CERTIFICATE_PASSWORD
|
password-secret: WINDOWS_SIGNING_CERTIFICATE_PASSWORD
|
||||||
@@ -32,7 +43,7 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Set certificate path environment variable
|
- name: Set certificate path environment variable
|
||||||
run: |
|
run: |
|
||||||
# See: https://docs.github.com/en/free-pro-team@latest/actions/reference/workflow-commands-for-github-actions#setting-an-environment-variable
|
# 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"
|
echo "CERTIFICATE_PATH=${{ runner.temp }}/certificate.p12" >> "$GITHUB_ENV"
|
||||||
|
|
||||||
- name: Decode certificate
|
- name: Decode certificate
|
||||||
@@ -54,18 +65,17 @@ jobs:
|
|||||||
exit 1
|
exit 1
|
||||||
)
|
)
|
||||||
|
|
||||||
# See: https://github.com/rtCamp/action-slack-notify
|
|
||||||
- name: Slack notification of certificate verification failure
|
- name: Slack notification of certificate verification failure
|
||||||
if: failure()
|
if: failure()
|
||||||
uses: rtCamp/action-slack-notify@v2.1.0
|
|
||||||
env:
|
env:
|
||||||
SLACK_WEBHOOK: ${{ secrets.TEAM_TOOLING_CHANNEL_SLACK_WEBHOOK }}
|
SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK }}
|
||||||
SLACK_MESSAGE: |
|
SLACK_MESSAGE: |
|
||||||
:warning::warning::warning::warning:
|
:warning::warning::warning::warning:
|
||||||
WARNING: ${{ github.repository }} ${{ matrix.certificate.identifier }} verification failed!!!
|
WARNING: ${{ github.repository }} ${{ matrix.certificate.identifier }} verification failed!!!
|
||||||
:warning::warning::warning::warning:
|
:warning::warning::warning::warning:
|
||||||
SLACK_COLOR: danger
|
SLACK_COLOR: danger
|
||||||
MSG_MINIMAL: true
|
MSG_MINIMAL: true
|
||||||
|
uses: rtCamp/action-slack-notify@v2
|
||||||
|
|
||||||
- name: Get days remaining before certificate expiration date
|
- name: Get days remaining before certificate expiration date
|
||||||
env:
|
env:
|
||||||
@@ -94,7 +104,7 @@ jobs:
|
|||||||
|
|
||||||
DAYS_BEFORE_EXPIRATION="$((($(date --utc --date="$EXPIRATION_DATE" +%s) - $(date --utc +%s)) / 60 / 60 / 24))"
|
DAYS_BEFORE_EXPIRATION="$((($(date --utc --date="$EXPIRATION_DATE" +%s) - $(date --utc +%s)) / 60 / 60 / 24))"
|
||||||
|
|
||||||
# Display the expiration information in the log
|
# Display the expiration information in the log.
|
||||||
echo "Certificate expiration date: $EXPIRATION_DATE"
|
echo "Certificate expiration date: $EXPIRATION_DATE"
|
||||||
echo "Days remaining before expiration: $DAYS_BEFORE_EXPIRATION"
|
echo "Days remaining before expiration: $DAYS_BEFORE_EXPIRATION"
|
||||||
|
|
||||||
@@ -109,14 +119,14 @@ jobs:
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
- name: Slack notification of pending certificate expiration
|
- name: Slack notification of pending certificate expiration
|
||||||
# Don't send spurious expiration notification if verification fails
|
# Don't send spurious expiration notification if verification fails.
|
||||||
if: failure() && steps.check-expiration.outcome == 'failure'
|
if: failure() && steps.check-expiration.outcome == 'failure'
|
||||||
uses: rtCamp/action-slack-notify@v2.1.0
|
|
||||||
env:
|
env:
|
||||||
SLACK_WEBHOOK: ${{ secrets.TEAM_TOOLING_CHANNEL_SLACK_WEBHOOK }}
|
SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK }}
|
||||||
SLACK_MESSAGE: |
|
SLACK_MESSAGE: |
|
||||||
:warning::warning::warning::warning:
|
:warning::warning::warning::warning:
|
||||||
WARNING: ${{ github.repository }} ${{ matrix.certificate.identifier }} will expire in ${{ steps.get-days-before-expiration.outputs.days }} days!!!
|
WARNING: ${{ github.repository }} ${{ matrix.certificate.identifier }} will expire in ${{ steps.get-days-before-expiration.outputs.days }} days!!!
|
||||||
:warning::warning::warning::warning:
|
:warning::warning::warning::warning:
|
||||||
SLACK_COLOR: danger
|
SLACK_COLOR: danger
|
||||||
MSG_MINIMAL: true
|
MSG_MINIMAL: true
|
||||||
|
uses: rtCamp/action-slack-notify@v2
|
||||||
|
|||||||
38
.github/workflows/check-i18n-task.yml
vendored
Normal file
38
.github/workflows/check-i18n-task.yml
vendored
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
name: Check Internationalization
|
||||||
|
|
||||||
|
# See: https://docs.github.com/en/actions/reference/events-that-trigger-workflows
|
||||||
|
on:
|
||||||
|
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:
|
||||||
|
check:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v2
|
||||||
|
|
||||||
|
- name: Install Node.js 14.x
|
||||||
|
uses: actions/setup-node@v2
|
||||||
|
with:
|
||||||
|
node-version: '14.x'
|
||||||
|
registry-url: 'https://registry.npmjs.org'
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: yarn
|
||||||
|
|
||||||
|
- name: Check for errors
|
||||||
|
run: yarn i18n:check
|
||||||
45
.github/workflows/compose-full-changelog.yaml
vendored
Normal file
45
.github/workflows/compose-full-changelog.yaml
vendored
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
name: Compose full changelog
|
||||||
|
|
||||||
|
on:
|
||||||
|
release:
|
||||||
|
types: [created, edited]
|
||||||
|
|
||||||
|
env:
|
||||||
|
CHANGELOG_ARTIFACTS: changelog
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
create-changelog:
|
||||||
|
if: github.repository == 'arduino/arduino-ide'
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v2
|
||||||
|
|
||||||
|
- name: Get Tag
|
||||||
|
id: tag_name
|
||||||
|
run: |
|
||||||
|
echo ::set-output name=TAG_NAME::${GITHUB_REF#refs/tags/}
|
||||||
|
|
||||||
|
- name: Create full changelog
|
||||||
|
id: full-changelog
|
||||||
|
run: |
|
||||||
|
mkdir "${{ github.workspace }}/${{ env.CHANGELOG_ARTIFACTS }}"
|
||||||
|
|
||||||
|
# Get the changelog file name to build
|
||||||
|
CHANGELOG_FILE_NAME="${{ steps.tag_name.outputs.TAG_NAME }}-$(date --iso-8601=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: Publish Changelog [S3]
|
||||||
|
uses: docker://plugins/s3
|
||||||
|
env:
|
||||||
|
PLUGIN_SOURCE: '${{ env.CHANGELOG_ARTIFACTS }}/*'
|
||||||
|
PLUGIN_STRIP_PREFIX: '${{ env.CHANGELOG_ARTIFACTS }}/'
|
||||||
|
PLUGIN_TARGET: '/arduino-ide/changelog'
|
||||||
|
PLUGIN_BUCKET: ${{ secrets.DOWNLOADS_BUCKET }}
|
||||||
|
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
|
||||||
|
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
|
||||||
96
.github/workflows/github-stats.yaml
vendored
Normal file
96
.github/workflows/github-stats.yaml
vendored
Normal file
@@ -0,0 +1,96 @@
|
|||||||
|
name: github-stats
|
||||||
|
|
||||||
|
on:
|
||||||
|
schedule:
|
||||||
|
# run every 30 minutes
|
||||||
|
- cron: "*/30 * * * *"
|
||||||
|
workflow_dispatch:
|
||||||
|
repository_dispatch:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
push-stats:
|
||||||
|
# This workflow is only of value to the arduino/arduino-ide repository and
|
||||||
|
# would always fail in forks
|
||||||
|
if: github.repository == 'arduino/arduino-ide'
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Fetch downloads count
|
||||||
|
id: fetch
|
||||||
|
uses: actions/github-script@v4
|
||||||
|
with:
|
||||||
|
github-token: ${{github.token}}
|
||||||
|
script: |
|
||||||
|
let metrics = []
|
||||||
|
|
||||||
|
// Get a list of releases
|
||||||
|
const opts = github.repos.listReleases.endpoint.merge({
|
||||||
|
...context.repo
|
||||||
|
})
|
||||||
|
const releases = await github.paginate(opts)
|
||||||
|
|
||||||
|
// Get download stats for every release
|
||||||
|
for (const rel of releases) {
|
||||||
|
// Names for assets are like `arduino-ide_2.0.0-beta.12_Linux_64bit.zip`,
|
||||||
|
// we'll use this later to split the asset file name more easily
|
||||||
|
const baseName = `arduino-ide_${rel.name}_`
|
||||||
|
|
||||||
|
// Get a list of assets for this release
|
||||||
|
const opts = github.repos.listReleaseAssets.endpoint.merge({
|
||||||
|
...context.repo,
|
||||||
|
release_id: rel.id
|
||||||
|
})
|
||||||
|
const assets = await github.paginate(opts)
|
||||||
|
|
||||||
|
for (const asset of assets) {
|
||||||
|
// Ignore files that are not arduino-ide packages
|
||||||
|
if (!asset.name.startsWith(baseName)) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Strip the base and remove file extension to get `Linux_32bit`
|
||||||
|
systemArch = asset.name.replace(baseName, "").split(".")[0].split("_")
|
||||||
|
|
||||||
|
// Add a metric object to the list of gathered metrics
|
||||||
|
metrics.push({
|
||||||
|
"type": "gauge",
|
||||||
|
"name": "arduino.downloads.total",
|
||||||
|
"value": asset.download_count,
|
||||||
|
"host": "${{ github.repository }}",
|
||||||
|
"tags": [
|
||||||
|
`version:${rel.name}`,
|
||||||
|
`os:${systemArch[0]}`,
|
||||||
|
`arch:${systemArch[1]}`,
|
||||||
|
"cdn:github.com",
|
||||||
|
"project:arduino-ide"
|
||||||
|
]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The action will put whatever we return from this function in
|
||||||
|
// `outputs.result`, JSON encoded. So we just return the array
|
||||||
|
// of objects and GitHub will do the rest.
|
||||||
|
return metrics
|
||||||
|
|
||||||
|
- name: Send metrics
|
||||||
|
uses: masci/datadog@v1
|
||||||
|
with:
|
||||||
|
api-key: ${{ secrets.DD_API_KEY }}
|
||||||
|
# Metrics input expects YAML but JSON will work just right.
|
||||||
|
metrics: ${{steps.fetch.outputs.result}}
|
||||||
|
|
||||||
|
- name: Report failure
|
||||||
|
if: failure()
|
||||||
|
uses: masci/datadog@v1
|
||||||
|
with:
|
||||||
|
api-key: ${{ secrets.DD_API_KEY }}
|
||||||
|
events: |
|
||||||
|
- title: "Arduino IDE stats failing"
|
||||||
|
text: "Stats collection failed"
|
||||||
|
alert_type: "error"
|
||||||
|
host: ${{ github.repository }}
|
||||||
|
tags:
|
||||||
|
- "project:arduino-ide"
|
||||||
|
- "cdn:github.com"
|
||||||
|
- "workflow:${{ github.workflow }}"
|
||||||
30
.github/workflows/i18n-nightly-push.yml
vendored
Normal file
30
.github/workflows/i18n-nightly-push.yml
vendored
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
name: i18n-nightly-push
|
||||||
|
|
||||||
|
on:
|
||||||
|
schedule:
|
||||||
|
# run every day at 1AM
|
||||||
|
- cron: '0 1 * * *'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
push-to-transifex:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v2
|
||||||
|
|
||||||
|
- name: Install Node.js 14.x
|
||||||
|
uses: actions/setup-node@v2
|
||||||
|
with:
|
||||||
|
node-version: '14.x'
|
||||||
|
registry-url: 'https://registry.npmjs.org'
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: yarn
|
||||||
|
|
||||||
|
- 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 }}
|
||||||
38
.github/workflows/i18n-weekly-pull.yml
vendored
Normal file
38
.github/workflows/i18n-weekly-pull.yml
vendored
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
name: i18n-weekly-pull
|
||||||
|
|
||||||
|
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@v2
|
||||||
|
|
||||||
|
- name: Install Node.js 14.x
|
||||||
|
uses: actions/setup-node@v2
|
||||||
|
with:
|
||||||
|
node-version: '14.x'
|
||||||
|
registry-url: 'https://registry.npmjs.org'
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: yarn
|
||||||
|
|
||||||
|
- 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@v3
|
||||||
|
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>
|
||||||
139
.github/workflows/sync-labels.yml
vendored
Normal file
139
.github/workflows/sync-labels.yml
vendored
Normal file
@@ -0,0 +1,139 @@
|
|||||||
|
# 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: label-configuration-files
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
check:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v2
|
||||||
|
|
||||||
|
- name: Download JSON schema for labels configuration file
|
||||||
|
id: download-schema
|
||||||
|
uses: carlosperate/download-file-action@v1
|
||||||
|
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@v1
|
||||||
|
with:
|
||||||
|
file-url: https://raw.githubusercontent.com/arduino/tooling-project-assets/main/workflow-templates/assets/sync-labels/${{ matrix.filename }}
|
||||||
|
|
||||||
|
- name: Pass configuration files to next job via workflow artifact
|
||||||
|
uses: actions/upload-artifact@v2
|
||||||
|
with:
|
||||||
|
path: |
|
||||||
|
*.yaml
|
||||||
|
*.yml
|
||||||
|
if-no-files-found: error
|
||||||
|
name: ${{ env.CONFIGURATIONS_ARTIFACT }}
|
||||||
|
|
||||||
|
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 "::set-output name=flag::--dry-run"
|
||||||
|
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v2
|
||||||
|
|
||||||
|
- name: Download configuration files artifact
|
||||||
|
uses: actions/download-artifact@v2
|
||||||
|
with:
|
||||||
|
name: ${{ env.CONFIGURATIONS_ARTIFACT }}
|
||||||
|
path: ${{ env.CONFIGURATIONS_FOLDER }}
|
||||||
|
|
||||||
|
- name: Remove unneeded artifact
|
||||||
|
uses: geekyeggo/delete-artifact@v1
|
||||||
|
with:
|
||||||
|
name: ${{ env.CONFIGURATIONS_ARTIFACT }}
|
||||||
|
|
||||||
|
- 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 }}
|
||||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -7,7 +7,8 @@ build/
|
|||||||
Examples/
|
Examples/
|
||||||
!electron/build/
|
!electron/build/
|
||||||
src-gen/
|
src-gen/
|
||||||
*webpack.config.js
|
!webpack.config.js
|
||||||
|
gen-webpack.config.js
|
||||||
.DS_Store
|
.DS_Store
|
||||||
# switching from `electron` to `browser` in dev mode.
|
# switching from `electron` to `browser` in dev mode.
|
||||||
.browser_modules
|
.browser_modules
|
||||||
|
|||||||
6
.prettierrc
Normal file
6
.prettierrc
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"singleQuote": true,
|
||||||
|
"tabWidth": 2,
|
||||||
|
"useTabs": false,
|
||||||
|
"printWidth": 80
|
||||||
|
}
|
||||||
61
.vscode/launch.json
vendored
61
.vscode/launch.json
vendored
@@ -1,22 +1,6 @@
|
|||||||
{
|
{
|
||||||
// Use IntelliSense to learn about possible attributes.
|
|
||||||
// Hover to view descriptions of existing attributes.
|
|
||||||
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
|
|
||||||
"version": "0.2.0",
|
"version": "0.2.0",
|
||||||
"configurations": [
|
"configurations": [
|
||||||
{
|
|
||||||
"type": "node",
|
|
||||||
"request": "attach",
|
|
||||||
"name": "Attach by Process ID",
|
|
||||||
"processId": "${command:PickProcess}"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "node",
|
|
||||||
"request": "launch",
|
|
||||||
"name": "Electron Packager",
|
|
||||||
"program": "${workspaceRoot}/electron/packager/index.js",
|
|
||||||
"cwd": "${workspaceFolder}/electron/packager"
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"type": "node",
|
"type": "node",
|
||||||
"request": "launch",
|
"request": "launch",
|
||||||
@@ -24,20 +8,19 @@
|
|||||||
"runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron",
|
"runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron",
|
||||||
"windows": {
|
"windows": {
|
||||||
"runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron.cmd",
|
"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",
|
"cwd": "${workspaceFolder}/electron-app",
|
||||||
"protocol": "inspector",
|
"protocol": "inspector",
|
||||||
"args": [
|
"args": [
|
||||||
|
".",
|
||||||
"--log-level=debug",
|
"--log-level=debug",
|
||||||
"--hostname=localhost",
|
"--hostname=localhost",
|
||||||
"--no-cluster",
|
"--no-cluster",
|
||||||
|
"--app-project-path=${workspaceRoot}/electron-app",
|
||||||
"--remote-debugging-port=9222",
|
"--remote-debugging-port=9222",
|
||||||
"--no-app-auto-install",
|
"--no-app-auto-install",
|
||||||
"--plugins=local-dir:plugins"
|
"--plugins=local-dir:../plugins",
|
||||||
|
"--hosted-plugin-inspect=9339"
|
||||||
],
|
],
|
||||||
"env": {
|
"env": {
|
||||||
"NODE_ENV": "development"
|
"NODE_ENV": "development"
|
||||||
@@ -47,12 +30,20 @@
|
|||||||
"${workspaceRoot}/electron-app/src-gen/backend/*.js",
|
"${workspaceRoot}/electron-app/src-gen/backend/*.js",
|
||||||
"${workspaceRoot}/electron-app/src-gen/frontend/*.js",
|
"${workspaceRoot}/electron-app/src-gen/frontend/*.js",
|
||||||
"${workspaceRoot}/electron-app/lib/**/*.js",
|
"${workspaceRoot}/electron-app/lib/**/*.js",
|
||||||
"${workspaceRoot}/arduino-ide-extension/lib/**/*.js"
|
"${workspaceRoot}/arduino-ide-extension/lib/**/*.js",
|
||||||
|
"${workspaceRoot}/node_modules/@theia/**/*.js"
|
||||||
],
|
],
|
||||||
"smartStep": true,
|
"smartStep": true,
|
||||||
"internalConsoleOptions": "openOnSessionStart",
|
"internalConsoleOptions": "openOnSessionStart",
|
||||||
"outputCapture": "std"
|
"outputCapture": "std"
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"type": "chrome",
|
||||||
|
"request": "attach",
|
||||||
|
"name": "Attach to Electron Frontend",
|
||||||
|
"port": 9222,
|
||||||
|
"webRoot": "${workspaceFolder}/electron-app"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"type": "node",
|
"type": "node",
|
||||||
"request": "launch",
|
"request": "launch",
|
||||||
@@ -93,6 +84,8 @@
|
|||||||
"args": [
|
"args": [
|
||||||
"--require",
|
"--require",
|
||||||
"reflect-metadata/Reflect",
|
"reflect-metadata/Reflect",
|
||||||
|
"--require",
|
||||||
|
"ignore-styles",
|
||||||
"--no-timeouts",
|
"--no-timeouts",
|
||||||
"--colors",
|
"--colors",
|
||||||
"**/${fileBasenameNoExtension}.js"
|
"**/${fileBasenameNoExtension}.js"
|
||||||
@@ -104,6 +97,28 @@
|
|||||||
"smartStep": true,
|
"smartStep": true,
|
||||||
"internalConsoleOptions": "openOnSessionStart",
|
"internalConsoleOptions": "openOnSessionStart",
|
||||||
"outputCapture": "std"
|
"outputCapture": "std"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "node",
|
||||||
|
"request": "attach",
|
||||||
|
"name": "Attach by Process ID",
|
||||||
|
"processId": "${command:PickProcess}"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "node",
|
||||||
|
"request": "launch",
|
||||||
|
"name": "Electron Packager",
|
||||||
|
"program": "${workspaceRoot}/electron/packager/index.js",
|
||||||
|
"cwd": "${workspaceFolder}/electron/packager"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"compounds": [
|
||||||
|
{
|
||||||
|
"name": "Launch Electron Backend & Frontend",
|
||||||
|
"configurations": [
|
||||||
|
"App (Electron)",
|
||||||
|
"Attach to Electron Frontend"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
18
.vscode/settings.json
vendored
18
.vscode/settings.json
vendored
@@ -1,21 +1,9 @@
|
|||||||
{
|
{
|
||||||
"tslint.enable": true,
|
|
||||||
"tslint.configFile": "./tslint.json",
|
|
||||||
"editor.formatOnSave": true,
|
|
||||||
"files.exclude": {
|
"files.exclude": {
|
||||||
"**/lib": false
|
"**/lib": false
|
||||||
},
|
},
|
||||||
"editor.insertSpaces": true,
|
"typescript.tsdk": "node_modules/typescript/lib",
|
||||||
"editor.detectIndentation": false,
|
"editor.codeActionsOnSave": {
|
||||||
"[typescript]": {
|
"source.fixAll.eslint": true
|
||||||
"editor.tabSize": 4
|
|
||||||
},
|
},
|
||||||
"[json]": {
|
|
||||||
"editor.tabSize": 2
|
|
||||||
},
|
|
||||||
"[jsonc]": {
|
|
||||||
"editor.tabSize": 2
|
|
||||||
},
|
|
||||||
"files.insertFinalNewline": true,
|
|
||||||
"typescript.tsdk": "node_modules/typescript/lib"
|
|
||||||
}
|
}
|
||||||
|
|||||||
4
.vscode/tasks.json
vendored
4
.vscode/tasks.json
vendored
@@ -1,6 +1,4 @@
|
|||||||
{
|
{
|
||||||
// See https://go.microsoft.com/fwlink/?LinkId=733558
|
|
||||||
// for the documentation about the tasks.json format
|
|
||||||
"version": "2.0.0",
|
"version": "2.0.0",
|
||||||
"tasks": [
|
"tasks": [
|
||||||
{
|
{
|
||||||
@@ -35,7 +33,7 @@
|
|||||||
"panel": "new",
|
"panel": "new",
|
||||||
"clear": false
|
"clear": false
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
{
|
{
|
||||||
"label": "Arduino IDE - Watch Browser App",
|
"label": "Arduino IDE - Watch Browser App",
|
||||||
"type": "shell",
|
"type": "shell",
|
||||||
|
|||||||
145
BUILDING.md
Normal file
145
BUILDING.md
Normal file
@@ -0,0 +1,145 @@
|
|||||||
|
# Development
|
||||||
|
|
||||||
|
This page includes technical documentation for developers who want to build the IDE locally and contribute to the project.
|
||||||
|
|
||||||
|
## Architecture overview
|
||||||
|
|
||||||
|
The IDE consists of three major parts:
|
||||||
|
- the _Electron main_ process,
|
||||||
|
- the _backend_, and
|
||||||
|
- the _frontend_.
|
||||||
|
|
||||||
|
The _Electron main_ process is responsible for:
|
||||||
|
- creating the application,
|
||||||
|
- managing the application lifecycle via listeners, and
|
||||||
|
- creating and managing the web pages for the app.
|
||||||
|
|
||||||
|
In Electron, the process that runs the main entry JavaScript file is called the main process. The _Electron main_ process can display a GUI by creating web pages. An Electron app always has exactly one main process.
|
||||||
|
|
||||||
|
By default, whenever the _Electron main_ process creates a web page, it will instantiate a new `BrowserWindow` instance. Since Electron uses Chromium for displaying web pages, Chromium's multi-process architecture is also used. Each web page in Electron runs in its own process, which is called the renderer process. Each `BrowserWindow` instance runs the web page in its own renderer process. When a `BrowserWindow` instance is destroyed, the corresponding renderer process is also terminated. The main process manages all web pages and their corresponding renderer processes. Each renderer process is isolated and only cares about the web page running in it.<sup>[[1]]</sup>
|
||||||
|
|
||||||
|
In normal browsers, web pages usually run in a sandboxed environment, and accessing native resources are disallowed. However, Electron has the power to use Node.js APIs in the web pages allowing lower-level OS interactions. Due to security reasons, accessing native resources is an undesired behavior in the IDE. So by convention, we do not use Node.js APIs. (Note: the Node.js integration is [not yet disabled](https://github.com/eclipse-theia/theia/issues/2018) although it is not used). In the IDE, only the _backend_ allows OS interaction.
|
||||||
|
|
||||||
|
The _backend_ process is responsible for:
|
||||||
|
- providing access to the filesystem,
|
||||||
|
- communicating with the [Arduino CLI](https://github.com/arduino/arduino-cli) via gRPC,
|
||||||
|
- running your terminal,
|
||||||
|
- exposing additional RESTful APIs,
|
||||||
|
- performing the Git commands in the local repositories,
|
||||||
|
- hosting and running any VS Code extensions, or
|
||||||
|
- executing VS Code tasks<sup>[[2]]</sup>.
|
||||||
|
|
||||||
|
The _Electron main_ process spawns the _backend_ process. There is always exactly one _backend_ process. However, due to performance considerations, the _backend_ spawns several sub-processes for the filesystem watching, Git repository discovery, etc. The communication between the _backend_ process and its sub-processes is established via IPC. Besides spawning sub-processes, the _backend_ will start an HTTP server on a random available port, and serves the web application as static content. When the sub-processes are up and running, and the HTTP server is also listening, the _backend_ process sends the HTTP server port to the _Electron main_ process via IPC. The _Electron main_ process will load the _backend_'s endpoint in the `BrowserWindow`.
|
||||||
|
|
||||||
|
The _frontend_ is running as an Electron renderer process and can invoke services implemented on the _backend_. The communication between the _backend_ and the _frontend_ is done via JSON-RPC over a websocket connection. This means, the services running in the _frontend_ are all proxies, and will ask the corresponding service implementation on the _backend_.
|
||||||
|
|
||||||
|
[1]: https://www.electronjs.org/docs/tutorial/application-architecture#differences-between-main-process-and-renderer-process
|
||||||
|
[2]: https://code.visualstudio.com/Docs/editor/tasks
|
||||||
|
|
||||||
|
|
||||||
|
## Build from source
|
||||||
|
|
||||||
|
If you’re familiar with TypeScript, the [Theia IDE](https://theia-ide.org/), and if you want to contribute to the
|
||||||
|
project, you should be able to build the Arduino IDE locally.
|
||||||
|
Please refer to the [Theia IDE prerequisites](https://github.com/theia-ide/theia/blob/master/doc/) documentation for the setup instructions.
|
||||||
|
> **Note**: Node.js 14 must be used instead of the version 12 recommended at the link above.
|
||||||
|
|
||||||
|
Once you have all the tools installed, you can build the editor following these steps
|
||||||
|
|
||||||
|
1. Install the dependencies and build
|
||||||
|
```sh
|
||||||
|
yarn
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Rebuild the dependencies
|
||||||
|
```sh
|
||||||
|
yarn rebuild:browser
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Rebuild the electron dependencies
|
||||||
|
```sh
|
||||||
|
yarn rebuild:electron
|
||||||
|
```
|
||||||
|
|
||||||
|
4. Start the application
|
||||||
|
```sh
|
||||||
|
yarn start
|
||||||
|
```
|
||||||
|
|
||||||
|
### CI
|
||||||
|
|
||||||
|
This project is built on [GitHub Actions](https://github.com/arduino/arduino-ide/actions).
|
||||||
|
|
||||||
|
- _Snapshot_ builds run when changes are pushed to the `main` branch, or when a PR is created against the `main` branch. For the sake of the review and verification process, the build artifacts for each operating system can be downloaded from the GitHub Actions page.
|
||||||
|
- _Nightly_ builds run every day at 03:00 GMT from the `main` branch.
|
||||||
|
- _Release_ builds run when a new tag is pushed to the remote. The tag must follow the [semver](https://semver.org/). For instance, `1.2.3` is a correct tag, but `v2.3.4` won't work. Steps to trigger a new release build:
|
||||||
|
- Create a local tag:
|
||||||
|
```sh
|
||||||
|
git tag -a 1.2.3 -m "Creating a new tag for the `1.2.3` release."
|
||||||
|
```
|
||||||
|
- Push it to the remote:
|
||||||
|
```sh
|
||||||
|
git push origin 1.2.3
|
||||||
|
```
|
||||||
|
|
||||||
|
## Notes for macOS contributors
|
||||||
|
Beginning in macOS 10.14.5, the software [must be notarized to run](https://developer.apple.com/documentation/xcode/notarizing_macos_software_before_distribution). The signing and notarization processes for the Arduino IDE are managed by our Continuous Integration (CI) workflows, implemented with GitHub Actions. On every push and pull request, the Arduino IDE is built and saved to a workflow artifact. These artifacts can be used by contributors and beta testers who don't want to set up a build system locally.
|
||||||
|
For security reasons, signing and notarization are disabled for workflow runs for pull requests from forks of this repository. This means that macOS will block you from running those artifacts.
|
||||||
|
Due to this limitation, Mac users have two options for testing contributions from forks:
|
||||||
|
|
||||||
|
### The Safe approach (recommended)
|
||||||
|
|
||||||
|
Follow [the instructions above](#build-from-source) to create the build environment locally, then build the code you want to test.
|
||||||
|
|
||||||
|
### The Risky approach
|
||||||
|
|
||||||
|
*Please note that this approach is risky as you are lowering the security on your system, therefore we strongly discourage you from following it.*
|
||||||
|
1. Use [this guide](https://help.apple.com/xcode/mac/10.2/index.html?localePath=en.lproj#/dev9b7736b0e), in order to disable Gatekeeper (at your own risk!).
|
||||||
|
1. Download the unsigned artifact provided by the CI workflow run related to the Pull Request at each push.
|
||||||
|
1. Re-enable Gatekeeper after tests are done, following the guide linked above.
|
||||||
|
|
||||||
|
### Creating a release
|
||||||
|
|
||||||
|
You will not need to create a new release yourself as the Arduino team takes care of this on a regular basis, but we are documenting the process here. Let's assume the current version is `0.1.3` and you want to release `0.2.0`.
|
||||||
|
|
||||||
|
- Make sure the `main` state represents what you want to release and you're on `main`.
|
||||||
|
- Prepare a release-candidate build on a branch:
|
||||||
|
```bash
|
||||||
|
git branch 0.2.0-rc \
|
||||||
|
&& git checkout 0.2.0-rc
|
||||||
|
```
|
||||||
|
- Bump up the version number. It must be a valid [semver](https://semver.org/) and must be greater than the current one:
|
||||||
|
```bash
|
||||||
|
yarn update:version 0.2.0
|
||||||
|
```
|
||||||
|
- This should generate multiple outgoing changes with the version update.
|
||||||
|
- Commit your changes and push to the remote:
|
||||||
|
```bash
|
||||||
|
git add . \
|
||||||
|
&& git commit -s -m "Updated versions to 0.2.0" \
|
||||||
|
&& git push
|
||||||
|
```
|
||||||
|
- Create the GH PR the workflow starts automatically.
|
||||||
|
- Once you're happy with the RC, merge the changes to the `main`.
|
||||||
|
- Create a tag and push it:
|
||||||
|
```bash
|
||||||
|
git tag -a 0.2.0 -m "0.2.0" \
|
||||||
|
&& git push origin 0.2.0
|
||||||
|
```
|
||||||
|
- The release build starts automatically and uploads the artifacts with the changelog to the [release page](https://github.com/arduino/arduino-ide/releases).
|
||||||
|
- If you do not want to release the `EXE` and `MSI` installers, wipe them manually.
|
||||||
|
- If you do not like the generated changelog, modify it and update the GH release.
|
||||||
|
|
||||||
|
## FAQ
|
||||||
|
|
||||||
|
* *Can I manually change the version of the [`arduino-cli`](https://github.com/arduino/arduino-cli/) used by the IDE?*
|
||||||
|
|
||||||
|
Yes. It is possible but not recommended. The CLI exposes a set of functionality via [gRPC](https://github.com/arduino/arduino-cli/tree/master/rpc) and the IDE uses this API to communicate with the CLI. Before we build a new version of IDE, we pin a specific version of CLI and use the corresponding `proto` files to generate TypeScript modules for gRPC. This means, a particular version of IDE is compliant only with the pinned version of CLI. Mismatching IDE and CLI versions might not be able to communicate with each other. This could cause unpredictable IDE behavior.
|
||||||
|
|
||||||
|
* *I have understood that not all versions of the CLI are compatible with my version of IDE but how can I manually update the `arduino-cli` inside the IDE?*
|
||||||
|
|
||||||
|
[Get](https://arduino.github.io/arduino-cli/installation) the desired version of `arduino-cli` for your platform and manually replace the one inside the IDE. The CLI can be found inside the IDE at:
|
||||||
|
- Windows: `C:\path\to\Arduino IDE\resources\app\node_modules\arduino-ide-extension\build\arduino-cli.exe`,
|
||||||
|
- macOS: `/path/to/Arduino IDE.app/Contents/Resources/app/node_modules/arduino-ide-extension/build/arduino-cli`, and
|
||||||
|
- Linux: `/path/to/Arduino IDE/resources/app/node_modules/arduino-ide-extension/build/arduino-cli`.
|
||||||
|
|
||||||
19
Dockerfile
19
Dockerfile
@@ -1,19 +0,0 @@
|
|||||||
FROM gitpod/workspace-full-vnc
|
|
||||||
|
|
||||||
USER root
|
|
||||||
RUN apt-get update -q --fix-missing && \
|
|
||||||
apt-get install -y -q software-properties-common && \
|
|
||||||
apt-get install -y -q --no-install-recommends \
|
|
||||||
build-essential \
|
|
||||||
libssl-dev \
|
|
||||||
golang-go \
|
|
||||||
libxkbfile-dev \
|
|
||||||
libnss3-dev
|
|
||||||
|
|
||||||
RUN set -ex && \
|
|
||||||
tmpdir=$(mktemp -d) && \
|
|
||||||
curl -L -o $tmpdir/protoc.zip https://github.com/protocolbuffers/protobuf/releases/download/v3.6.1/protoc-3.6.1-linux-x86_64.zip && \
|
|
||||||
mkdir -p /usr/lib/protoc && cd /usr/lib/protoc && unzip $tmpdir/protoc.zip && \
|
|
||||||
chmod -R 755 /usr/lib/protoc/include/google && \
|
|
||||||
ln -s /usr/lib/protoc/bin/* /usr/bin && \
|
|
||||||
rm $tmpdir/protoc.zip
|
|
||||||
661
LICENSE.txt
Normal file
661
LICENSE.txt
Normal file
@@ -0,0 +1,661 @@
|
|||||||
|
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/>.
|
||||||
180
README.md
180
README.md
@@ -1,165 +1,81 @@
|
|||||||
# Arduino IDE
|
<img src="https://content.arduino.cc/website/Arduino_logo_teal.svg" height="100" align="right" />
|
||||||
|
|
||||||
|
# Arduino IDE 2.x (beta)
|
||||||
|
|
||||||
[](https://github.com/arduino/arduino-ide/actions?query=workflow%3A%22Arduino+IDE%22)
|
[](https://github.com/arduino/arduino-ide/actions?query=workflow%3A%22Arduino+IDE%22)
|
||||||
|
|
||||||
### Download
|
This repository contains the source code of the Arduino IDE 2.x, which is currently in beta stage. If you're looking for the stable IDE, go to the repository of the 1.x version at https://github.com/arduino/Arduino.
|
||||||
|
|
||||||
You can download the latest version of the Arduino IDE application for the supported platforms from the [GitHub release page](https://github.com/arduino/arduino-ide/releases) or following the links in the following table.
|
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
|
> ⚠️ This is **beta** software. Help us test it!
|
||||||
|
|
||||||
Platform | 32 bit | 64 bit |
|

|
||||||
--------- | ------------------------ | ------------------------------------------------------------------------------ |
|
|
||||||
Linux | | [Linux 64 bit] |
|
|
||||||
Linux ARM | [🚧 Work in progress...] | [🚧 Work in progress...] |
|
|
||||||
Windows | | [Windows 64 bit installer]<br />[Windows 64 bit MSI]<br />[Windows 64 bit ZIP] |
|
|
||||||
macOS | | [macOS 64 bit] |
|
|
||||||
|
|
||||||
[🚧 Work in progress...]: https://github.com/arduino/arduino-ide/issues/287
|
## Download
|
||||||
[Linux 64 bit]: https://downloads.arduino.cc/arduino-ide/arduino-ide_latest_Linux_64bit.zip
|
|
||||||
[Windows 64 bit installer]: https://downloads.arduino.cc/arduino-ide/arduino-ide_latest_Windows_64bit.exe
|
|
||||||
[Windows 64 bit MSI]: https://downloads.arduino.cc/arduino-ide/arduino-ide_latest_Windows_64bit.msi
|
|
||||||
[Windows 64 bit ZIP]: https://downloads.arduino.cc/arduino-ide/arduino-ide_latest_Windows_64bit.zip
|
|
||||||
[macOS 64 bit]: https://downloads.arduino.cc/arduino-ide/arduino-ide_latest_macOS_64bit.dmg
|
|
||||||
|
|
||||||
#### Previous versions
|
You can download the latest version from the [software download page on the Arduino website](https://www.arduino.cc/en/software#experimental-software).
|
||||||
|
|
||||||
These are available from the [GitHub releases page](https://github.com/arduino/arduino-ide/releases).
|
### Nightly builds
|
||||||
|
|
||||||
#### Nightly builds
|
|
||||||
|
|
||||||
These builds are generated every day at 03:00 GMT from the `main` branch and
|
These builds are generated every day at 03:00 GMT from the `main` branch and
|
||||||
should be considered unstable. In order to get the latest nightly build
|
should be considered unstable:
|
||||||
available for the supported platform, use the following links:
|
|
||||||
|
|
||||||
Platform | 32 bit | 64 bit |
|
| Platform | 32 bit | 64 bit |
|
||||||
--------- | ------------------------ | ------------------------------------------------------------------------------------------------------ |
|
| --------- | ------------------------ | ------------------------------------------------------------------------------------------------------ |
|
||||||
Linux | | [Nightly Linux 64 bit] |
|
| Linux | | [Nightly Linux 64 bit] |
|
||||||
Linux ARM | [🚧 Work in progress...] | [🚧 Work in progress...] |
|
| Linux ARM | [🚧 Work in progress...] | [🚧 Work in progress...] |
|
||||||
Windows | | [Nightly Windows 64 bit installer]<br />[Nightly Windows 64 bit MSI]<br />[Nightly Windows 64 bit ZIP] |
|
| Windows | | [Nightly Windows 64 bit installer]<br />[Nightly Windows 64 bit MSI]<br />[Nightly Windows 64 bit ZIP] |
|
||||||
macOS | | [Nightly macOS 64 bit] |
|
| macOS | | [Nightly macOS 64 bit] |
|
||||||
|
|
||||||
[🚧 Work in progress...]: https://github.com/arduino/arduino-ide/issues/287
|
[🚧 work in progress...]: https://github.com/arduino/arduino-ide/issues/107
|
||||||
[Nightly Linux 64 bit]: https://downloads.arduino.cc/arduino-ide/nightly/arduino-ide_nightly-latest_Linux_64bit.zip
|
[nightly linux 64 bit]: https://downloads.arduino.cc/arduino-ide/nightly/arduino-ide_nightly-latest_Linux_64bit.zip
|
||||||
[Nightly Windows 64 bit installer]: https://downloads.arduino.cc/arduino-ide/nightly/arduino-ide_nightly-latest_Windows_64bit.exe
|
[nightly windows 64 bit installer]: https://downloads.arduino.cc/arduino-ide/nightly/arduino-ide_nightly-latest_Windows_64bit.exe
|
||||||
[Nightly Windows 64 bit MSI]: https://downloads.arduino.cc/arduino-ide/nightly/arduino-ide_nightly-latest_Windows_64bit.msi
|
[nightly windows 64 bit msi]: https://downloads.arduino.cc/arduino-ide/nightly/arduino-ide_nightly-latest_Windows_64bit.msi
|
||||||
[Nightly Windows 64 bit ZIP]: https://downloads.arduino.cc/arduino-ide/nightly/arduino-ide_nightly-latest_Windows_64bit.zip
|
[nightly windows 64 bit zip]: https://downloads.arduino.cc/arduino-ide/nightly/arduino-ide_nightly-latest_Windows_64bit.zip
|
||||||
[Nightly macOS 64 bit]: https://downloads.arduino.cc/arduino-ide/nightly/arduino-ide_nightly-latest_macOS_64bit.dmg
|
[nightly macos 64 bit]: https://downloads.arduino.cc/arduino-ide/nightly/arduino-ide_nightly-latest_macOS_64bit.dmg
|
||||||
|
|
||||||
> These links return an HTTP `302: Found` response, redirecting to latest
|
> These links return an HTTP `302: Found` response, redirecting to latest
|
||||||
generated builds by replacing `latest` with the latest available build
|
> generated builds by replacing `latest` with the latest available build
|
||||||
date, using the format YYYYMMDD (i.e for 2019/Aug/06 `latest` is
|
> date, using the format YYYYMMDD (i.e for 2019/Aug/06 `latest` is
|
||||||
replaced with `20190806` )
|
> replaced with `20190806`)
|
||||||
|
|
||||||
### Build from source
|
## Support
|
||||||
|
|
||||||
If you’re familiar with TypeScript, the [Theia IDE](https://theia-ide.org/), and if you want to contribute to the
|
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).
|
||||||
project, you should be able to build the Arduino IDE locally. Please refer to the [Theia IDE prerequisites](https://github.com/theia-ide/theia/blob/master/doc/) documentation for the setup instructions.
|
|
||||||
|
|
||||||
### Build
|
## Bugs & Issues
|
||||||
```sh
|
|
||||||
yarn
|
|
||||||
```
|
|
||||||
|
|
||||||
### Rebuild the native dependencies
|
If you want to report an issue, you can submit it to the [issue tracker](https://github.com/arduino/arduino-ide/issues) of this repository. A few rules apply:
|
||||||
```sh
|
|
||||||
yarn rebuild:electron
|
|
||||||
```
|
|
||||||
|
|
||||||
### Start
|
- Before posting, please check if the same problem has been already reported by someone else to avoid duplicates.
|
||||||
```sh
|
- Remember to include as much detail as you can about your hardware set-up, code and steps for reproducing the issue. Make sure you're using an original Arduino board.
|
||||||
yarn start
|
|
||||||
```
|
|
||||||
|
|
||||||
### CI
|
### Security
|
||||||
|
|
||||||
This project is built on [GitHub Actions](https://github.com/bcmi-labs/arduino-editor/actions?query=workflow%3A%22Arduino+Pro+IDE%22).
|
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!
|
||||||
|
|
||||||
- _Snapshot_ builds run when changes are pushed to the `main` branch, or when a PR is created against the `main` branch. For the sake of the review and verification process, the build artifacts can be downloaded from the GitHub Actions page. Note: [due to a limitation](https://github.com/actions/upload-artifact/issues/80#issuecomment-630030144) with the GH Actions UI, you cannot download a particular build, but you have to get all together inside the `build-artifacts.zip`.
|
e-mail contact: security@arduino.cc
|
||||||
- _Nightly_ builds run every day at 03:00 GMT from the `main` branch.
|
|
||||||
- _Release_ builds run when a new tag is pushed to the remote. The tag must follow the [semver](https://semver.org/). For instance, `1.2.3` is a correct tag, but `v2.3.4` won't work. Steps to trigger a new release build:
|
|
||||||
- Create a local tag:
|
|
||||||
```sh
|
|
||||||
git tag -a 1.2.3 -m "Creating a new tag for the `1.2.3` release."
|
|
||||||
```
|
|
||||||
- Push it to the remote:
|
|
||||||
```sh
|
|
||||||
git push origin 1.2.3
|
|
||||||
```
|
|
||||||
|
|
||||||
### Creating a GH release
|
## Contributions and development
|
||||||
This section guides you through how to create a new release. Let's assume the current version is `0.1.3` and you want to release `0.2.0`.
|
|
||||||
|
|
||||||
- Make sure the `main` state represents what you want to release and you're on `main`.
|
Contributions are very welcome! You can browse the list of open issues to see what's needed and then you can submit your code using a Pull Request. Please provide detailed descriptions. We also appreciate any help in testing issues and patches contributed by other users.
|
||||||
- Prepare a release-candidate build on a branch:
|
|
||||||
```bash
|
|
||||||
git branch 0.2.0-rc \
|
|
||||||
&& git checkout 0.2.0-rc
|
|
||||||
```
|
|
||||||
- Bump up the version number. It must be a valid [semver](https://semver.org/) and must be greater than the current one:
|
|
||||||
```bash
|
|
||||||
yarn update:version 0.2.0
|
|
||||||
```
|
|
||||||
- This should generate multiple outgoing changes with the version update.
|
|
||||||
- Commit your changes and push to the remote:
|
|
||||||
```bash
|
|
||||||
git add . \
|
|
||||||
&& git commit -s -m "Updated versions to 0.2.0" \
|
|
||||||
&& git push
|
|
||||||
```
|
|
||||||
- Create the GH PR the workflow starts automatically.
|
|
||||||
- Once you're happy with the RC, merge the changes to the `main`.
|
|
||||||
- Create a tag and push it:
|
|
||||||
```bash
|
|
||||||
git tag -a 0.2.0 -m "0.2.0" \
|
|
||||||
&& git push origin 0.2.0
|
|
||||||
```
|
|
||||||
- The release build starts automatically and uploads the artifacts with the changelog to the Pro IDE [release page](https://github.com/arduino/arduino-ide/releases).
|
|
||||||
- If you do not want to release the `EXE` and `MSI` installers, wipe them manually.
|
|
||||||
- If you do not like the generated changelog, modify it and update the GH release.
|
|
||||||
|
|
||||||
|
This repository contains the main code, but two more repositories are included during the build process:
|
||||||
|
|
||||||
### FAQ
|
- [vscode-arduino-tools](https://github.com/arduino/vscode-arduino-tools): provides support for the language server and the debugger
|
||||||
|
- [arduino-language-server](https://github.com/arduino/arduino-language-server): provides the language server that parses Arduino code
|
||||||
|
|
||||||
- Q: Can I manually change the version of the [`arduino-cli`](https://github.com/arduino/arduino-cli/) used by the IDE?
|
See the [BUILDING.md](BUILDING.md) for a technical overview of the application and instructions for building the code.
|
||||||
- A: Yes. It is possible but not recommended. The CLI exposes a set of functionality via [gRPC](https://github.com/arduino/arduino-cli/tree/master/rpc) and the IDE uses this API to communicate with the CLI. Before we build a new version of IDE, we pin a specific version of CLI and use the corresponding `proto` files to generate TypeScript modules for gRPC. This means, a particular version of IDE is compliant only with the pinned version of CLI. Mismatching IDE and CLI versions might not be able to communicate with each other. This could cause unpredictable IDE behavior.
|
|
||||||
|
|
||||||
- Q: I have understood that not all versions of the CLI is compatible with my version of IDE but how can I manually update the `arduino-cli` inside the IDE?
|
You can help with the translation of the Arduino IDE to your language here: [Arduino IDE on Transifex](https://www.transifex.com/arduino-1/ide2/dashboard/).
|
||||||
- A: [Get](https://arduino.github.io/arduino-cli/installation) the desired version of `arduino-cli` for your platform and manually replace the one inside the IDE. The CLI can be found inside the IDE at:
|
|
||||||
- Windows: `C:\path\to\Arduino IDE\resources\app\node_modules\arduino-ide-extension\build\arduino-cli.exe`,
|
|
||||||
- macOS: `/path/to/Arduino IDE.app/Contents/Resources/app/node_modules/arduino-ide-extension/build/arduino-cli`, and
|
|
||||||
- Linux: `/path/to/Arduino IDE/resources/app/node_modules/arduino-ide-extension/build/arduino-cli`.
|
|
||||||
|
|
||||||
### Architecture overview
|
## Donations
|
||||||
|
|
||||||
The Pro IDE consists of three major parts:
|
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.
|
||||||
- the _Electron main_ process,
|
|
||||||
- the _backend_, and
|
|
||||||
- the _frontend_.
|
|
||||||
|
|
||||||
The _Electron main_ process is responsible for:
|
## License
|
||||||
- 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.
|
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).
|
||||||
|
|
||||||
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
|
|
||||||
|
|||||||
@@ -30,17 +30,20 @@ The Core Service is responsible for building your sketches and uploading them to
|
|||||||
- compiling a sketch for a selected board type
|
- compiling a sketch for a selected board type
|
||||||
- uploading a sketch to a connected board
|
- uploading a sketch to a connected board
|
||||||
|
|
||||||
#### Monitor Service
|
#### Serial Service
|
||||||
|
|
||||||
The Monitor Service allows getting information back from sketches running on your Arduino boards.
|
The Serial Service allows getting information back from sketches running on your Arduino boards.
|
||||||
|
|
||||||
- [src/common/protocol/monitor-service.ts](./src/common/protocol/monitor-service.ts) implements the common classes and interfaces
|
- [src/common/protocol/serial-service.ts](./src/common/protocol/serial-service.ts) implements the common classes and interfaces
|
||||||
- [src/node/monitor-service-impl.ts](./src/node/monitor-service-impl.ts) implements the service backend:
|
- [src/node/serial/serial-service-impl.ts](./src/node/serial/serial-service-impl.ts) implements the service backend:
|
||||||
- connecting to / disconnecting from a board
|
- connecting to / disconnecting from a board
|
||||||
- receiving and sending data
|
- receiving and sending data
|
||||||
- [src/browser/monitor/monitor-widget.tsx](./src/browser/monitor/monitor-widget.tsx) implements the serial monitor front-end:
|
- [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:
|
||||||
- viewing the output from a connected board
|
- viewing the output from a connected board
|
||||||
- entering data to send to the 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
|
#### Config Service
|
||||||
|
|
||||||
@@ -54,3 +57,17 @@ The Config Service knows about your system, like for example the default sketch
|
|||||||
### `"arduino"` configuration in the `package.json`:
|
### `"arduino"` configuration in the `package.json`:
|
||||||
- `"cli"`:
|
- `"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.
|
- `"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`
|
||||||
|
|
||||||
|
### 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
|
||||||
|
|||||||
1
arduino-ide-extension/arduino-icons.json
Normal file
1
arduino-ide-extension/arduino-icons.json
Normal file
File diff suppressed because one or more lines are too long
@@ -1,76 +1,108 @@
|
|||||||
{
|
{
|
||||||
"name": "arduino-ide-extension",
|
"name": "arduino-ide-extension",
|
||||||
"version": "2.0.0-beta.2",
|
"version": "2.0.0-rc4",
|
||||||
"description": "An extension for Theia building the Arduino IDE",
|
"description": "An extension for Theia building the Arduino IDE",
|
||||||
"license": "MIT",
|
"license": "AGPL-3.0-or-later",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"prepare": "yarn download-cli && yarn download-ls && yarn clean && yarn download-examples && yarn build",
|
"prepare": "yarn download-cli && yarn download-fwuploader && yarn download-ls && yarn copy-serial-plotter && yarn clean && yarn download-examples && yarn build && yarn test",
|
||||||
"clean": "rimraf lib",
|
"clean": "rimraf lib",
|
||||||
|
"compose-changelog": "node ./scripts/compose-changelog.js",
|
||||||
"download-cli": "node ./scripts/download-cli.js",
|
"download-cli": "node ./scripts/download-cli.js",
|
||||||
|
"download-fwuploader": "node ./scripts/download-fwuploader.js",
|
||||||
|
"copy-serial-plotter": "npx ncp ../node_modules/arduino-serial-plotter-webapp ./build/arduino-serial-plotter-webapp",
|
||||||
"download-ls": "node ./scripts/download-ls.js",
|
"download-ls": "node ./scripts/download-ls.js",
|
||||||
"download-examples": "node ./scripts/download-examples.js",
|
"download-examples": "node ./scripts/download-examples.js",
|
||||||
"generate-protocol": "node ./scripts/generate-protocol.js",
|
"generate-protocol": "node ./scripts/generate-protocol.js",
|
||||||
"lint": "tslint -c ./tslint.json --project ./tsconfig.json",
|
"lint": "eslint",
|
||||||
"build": "tsc && ncp ./src/node/cli-protocol/ ./lib/node/cli-protocol/ && yarn lint",
|
"build": "tsc && ncp ./src/node/cli-protocol/ ./lib/node/cli-protocol/ && yarn lint",
|
||||||
"watch": "tsc -w",
|
"watch": "tsc -w",
|
||||||
"test": "mocha \"./lib/test/**/*.test.js\"",
|
"test": "mocha \"./lib/test/**/*.test.js\"",
|
||||||
"test:watch": "mocha --watch --watch-files lib \"./lib/test/**/*.test.js\""
|
"test:watch": "mocha --watch --watch-files lib \"./lib/test/**/*.test.js\""
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@grpc/grpc-js": "^1.1.1",
|
"@grpc/grpc-js": "^1.3.7",
|
||||||
"@theia/application-package": "next",
|
"@theia/application-package": "1.22.1",
|
||||||
"@theia/core": "next",
|
"@theia/core": "1.22.1",
|
||||||
"@theia/editor": "next",
|
"@theia/editor": "1.22.1",
|
||||||
"@theia/filesystem": "next",
|
"@theia/editor-preview": "1.22.1",
|
||||||
"@theia/git": "next",
|
"@theia/electron": "1.22.1",
|
||||||
"@theia/markers": "next",
|
"@theia/filesystem": "1.22.1",
|
||||||
"@theia/monaco": "next",
|
"@theia/git": "1.22.1",
|
||||||
"@theia/navigator": "next",
|
"@theia/keymaps": "1.22.1",
|
||||||
"@theia/outline-view": "next",
|
"@theia/markers": "1.22.1",
|
||||||
"@theia/preferences": "next",
|
"@theia/monaco": "1.22.1",
|
||||||
"@theia/output": "next",
|
"@theia/navigator": "1.22.1",
|
||||||
"@theia/search-in-workspace": "next",
|
"@theia/outline-view": "1.22.1",
|
||||||
"@theia/terminal": "next",
|
"@theia/output": "1.22.1",
|
||||||
"@theia/workspace": "next",
|
"@theia/preferences": "1.22.1",
|
||||||
|
"@theia/search-in-workspace": "1.22.1",
|
||||||
|
"@theia/terminal": "1.22.1",
|
||||||
|
"@theia/workspace": "1.22.1",
|
||||||
|
"@tippyjs/react": "^4.2.5",
|
||||||
|
"@types/atob": "^2.1.2",
|
||||||
|
"@types/auth0-js": "^9.14.0",
|
||||||
|
"@types/btoa": "^1.2.3",
|
||||||
"@types/dateformat": "^3.0.1",
|
"@types/dateformat": "^3.0.1",
|
||||||
"@types/deepmerge": "^2.2.0",
|
"@types/deepmerge": "^2.2.0",
|
||||||
"@types/glob": "^5.0.35",
|
"@types/glob": "^5.0.35",
|
||||||
"@types/google-protobuf": "^3.7.2",
|
"@types/google-protobuf": "^3.7.2",
|
||||||
"@types/js-yaml": "^3.12.2",
|
"@types/js-yaml": "^3.12.2",
|
||||||
|
"@types/keytar": "^4.4.0",
|
||||||
"@types/lodash.debounce": "^4.0.6",
|
"@types/lodash.debounce": "^4.0.6",
|
||||||
"@types/ncp": "^2.0.4",
|
"@types/ncp": "^2.0.4",
|
||||||
|
"@types/node-fetch": "^2.5.7",
|
||||||
"@types/ps-tree": "^1.1.0",
|
"@types/ps-tree": "^1.1.0",
|
||||||
"@types/react-select": "^3.0.0",
|
"@types/react-select": "^3.0.0",
|
||||||
"@types/react-tabs": "^2.3.2",
|
"@types/react-tabs": "^2.3.2",
|
||||||
"@types/sinon": "^7.5.2",
|
|
||||||
"@types/temp": "^0.8.34",
|
"@types/temp": "^0.8.34",
|
||||||
"@types/which": "^1.3.1",
|
"@types/which": "^1.3.1",
|
||||||
"ajv": "^6.5.3",
|
"ajv": "^6.5.3",
|
||||||
|
"arduino-serial-plotter-webapp": "0.0.17",
|
||||||
|
"async-mutex": "^0.3.0",
|
||||||
|
"atob": "^2.1.2",
|
||||||
|
"auth0-js": "^9.14.0",
|
||||||
|
"btoa": "^1.2.1",
|
||||||
"css-element-queries": "^1.2.0",
|
"css-element-queries": "^1.2.0",
|
||||||
"dateformat": "^3.0.3",
|
"dateformat": "^3.0.3",
|
||||||
"deepmerge": "^4.2.2",
|
"deepmerge": "2.0.1",
|
||||||
|
"electron-updater": "^4.6.5",
|
||||||
"fuzzy": "^0.1.3",
|
"fuzzy": "^0.1.3",
|
||||||
"glob": "^7.1.6",
|
"glob": "^7.1.6",
|
||||||
"google-protobuf": "^3.11.4",
|
"google-protobuf": "^3.11.4",
|
||||||
"lodash.debounce": "^4.0.8",
|
"grpc": "^1.24.11",
|
||||||
|
"hash.js": "^1.1.7",
|
||||||
|
"is-valid-path": "^0.1.1",
|
||||||
"js-yaml": "^3.13.1",
|
"js-yaml": "^3.13.1",
|
||||||
|
"jwt-decode": "^3.1.2",
|
||||||
|
"keytar": "7.2.0",
|
||||||
|
"lodash.debounce": "^4.0.8",
|
||||||
"ncp": "^2.0.0",
|
"ncp": "^2.0.0",
|
||||||
|
"node-fetch": "^2.6.1",
|
||||||
|
"open": "^8.0.6",
|
||||||
"p-queue": "^5.0.0",
|
"p-queue": "^5.0.0",
|
||||||
"ps-tree": "^1.2.0",
|
"ps-tree": "^1.2.0",
|
||||||
|
"query-string": "^7.0.1",
|
||||||
"react-disable": "^0.1.0",
|
"react-disable": "^0.1.0",
|
||||||
|
"react-markdown": "^8.0.0",
|
||||||
"react-select": "^3.0.4",
|
"react-select": "^3.0.4",
|
||||||
"react-tabs": "^3.1.2",
|
"react-tabs": "^3.1.2",
|
||||||
|
"react-window": "^1.8.6",
|
||||||
"semver": "^7.3.2",
|
"semver": "^7.3.2",
|
||||||
"string-natural-compare": "^2.0.3",
|
"string-natural-compare": "^2.0.3",
|
||||||
"temp": "^0.9.1",
|
"temp": "^0.9.1",
|
||||||
"tree-kill": "^1.2.1",
|
"tree-kill": "^1.2.1",
|
||||||
"upath": "^1.1.2",
|
"upath": "^1.1.2",
|
||||||
|
"url": "^0.11.0",
|
||||||
"which": "^1.3.1"
|
"which": "^1.3.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@octokit/rest": "^18.12.0",
|
||||||
"@types/chai": "^4.2.7",
|
"@types/chai": "^4.2.7",
|
||||||
"@types/chai-string": "^1.4.2",
|
"@types/chai-string": "^1.4.2",
|
||||||
"@types/mocha": "^5.2.7",
|
"@types/mocha": "^5.2.7",
|
||||||
|
"@types/react-window": "^1.8.5",
|
||||||
|
"@types/sinon": "^10.0.6",
|
||||||
|
"@types/sinon-chai": "^3.2.6",
|
||||||
"chai": "^4.2.0",
|
"chai": "^4.2.0",
|
||||||
"chai-string": "^1.5.0",
|
"chai-string": "^1.5.0",
|
||||||
"decompress": "^4.2.0",
|
"decompress": "^4.2.0",
|
||||||
@@ -79,10 +111,13 @@
|
|||||||
"download": "^7.1.0",
|
"download": "^7.1.0",
|
||||||
"grpc_tools_node_protoc_ts": "^4.1.0",
|
"grpc_tools_node_protoc_ts": "^4.1.0",
|
||||||
"mocha": "^7.0.0",
|
"mocha": "^7.0.0",
|
||||||
|
"mockdate": "^3.0.5",
|
||||||
"moment": "^2.24.0",
|
"moment": "^2.24.0",
|
||||||
"protoc": "^1.0.4",
|
"protoc": "^1.0.4",
|
||||||
"shelljs": "^0.8.3",
|
"shelljs": "^0.8.3",
|
||||||
"sinon": "^9.0.1",
|
"sinon": "^12.0.1",
|
||||||
|
"sinon-chai": "^3.7.0",
|
||||||
|
"typemoq": "^2.1.0",
|
||||||
"uuid": "^3.2.1",
|
"uuid": "^3.2.1",
|
||||||
"yargs": "^11.1.0"
|
"yargs": "^11.1.0"
|
||||||
},
|
},
|
||||||
@@ -91,7 +126,8 @@
|
|||||||
},
|
},
|
||||||
"mocha": {
|
"mocha": {
|
||||||
"require": [
|
"require": [
|
||||||
"reflect-metadata/Reflect"
|
"reflect-metadata/Reflect",
|
||||||
|
"ignore-styles"
|
||||||
],
|
],
|
||||||
"reporter": "spec",
|
"reporter": "spec",
|
||||||
"colors": true,
|
"colors": true,
|
||||||
@@ -114,16 +150,22 @@
|
|||||||
"frontend": "lib/browser/theia/core/browser-menu-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-menu-module"
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"frontend": "lib/browser/boards/quick-open/boards-quick-open-module"
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"electronMain": "lib/electron-main/arduino-electron-main-module"
|
"electronMain": "lib/electron-main/arduino-electron-main-module"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"arduino": {
|
"arduino": {
|
||||||
"cli": {
|
"cli": {
|
||||||
"version": "0.16.0"
|
"version": "0.21.0"
|
||||||
|
},
|
||||||
|
"fwuploader": {
|
||||||
|
"version": "2.0.0"
|
||||||
|
},
|
||||||
|
"clangd": {
|
||||||
|
"version": "13.0.0"
|
||||||
|
},
|
||||||
|
"languageServer": {
|
||||||
|
"version": "0.6.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
116
arduino-ide-extension/scripts/compose-changelog.js
Executable file
116
arduino-ide-extension/scripts/compose-changelog.js
Executable file
@@ -0,0 +1,116 @@
|
|||||||
|
// @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;
|
||||||
|
};
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
// @ts-check
|
// @ts-check
|
||||||
|
|
||||||
// The version to use.
|
// The version to use.
|
||||||
const version = '1.9.0';
|
const version = '1.9.1';
|
||||||
|
|
||||||
(async () => {
|
(async () => {
|
||||||
|
|
||||||
|
|||||||
166
arduino-ide-extension/scripts/download-fwuploader.js
Executable file
166
arduino-ide-extension/scripts/download-fwuploader.js
Executable file
@@ -0,0 +1,166 @@
|
|||||||
|
// @ts-check
|
||||||
|
|
||||||
|
(async () => {
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
const temp = require('temp');
|
||||||
|
const shell = require('shelljs');
|
||||||
|
const semver = require('semver');
|
||||||
|
const downloader = require('./downloader');
|
||||||
|
|
||||||
|
const version = (() => {
|
||||||
|
const pkg = require(path.join(__dirname, '..', 'package.json'));
|
||||||
|
if (!pkg) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { arduino } = pkg;
|
||||||
|
if (!arduino) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { fwuploader } = arduino;
|
||||||
|
if (!fwuploader) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { version } = fwuploader;
|
||||||
|
return version;
|
||||||
|
})();
|
||||||
|
|
||||||
|
if (!version) {
|
||||||
|
shell.echo(
|
||||||
|
`Could not retrieve Firmware Uploader version info from the 'package.json'.`
|
||||||
|
);
|
||||||
|
shell.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { platform, arch } = process;
|
||||||
|
const buildFolder = path.join(__dirname, '..', 'build');
|
||||||
|
const fwuploderName = `arduino-fwuploader${
|
||||||
|
platform === 'win32' ? '.exe' : ''
|
||||||
|
}`;
|
||||||
|
const destinationPath = path.join(buildFolder, fwuploderName);
|
||||||
|
|
||||||
|
if (typeof version === 'string') {
|
||||||
|
const suffix = (() => {
|
||||||
|
switch (platform) {
|
||||||
|
case 'darwin':
|
||||||
|
return 'macOS_64bit.tar.gz';
|
||||||
|
case 'win32':
|
||||||
|
return 'Windows_64bit.zip';
|
||||||
|
case 'linux': {
|
||||||
|
switch (arch) {
|
||||||
|
case 'arm':
|
||||||
|
return 'Linux_ARMv7.tar.gz';
|
||||||
|
case 'arm64':
|
||||||
|
return 'Linux_ARM64.tar.gz';
|
||||||
|
case 'x64':
|
||||||
|
return 'Linux_64bit.tar.gz';
|
||||||
|
default:
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
if (!suffix) {
|
||||||
|
shell.echo(
|
||||||
|
`The Firmware Uploader is not available for ${platform} ${arch}.`
|
||||||
|
);
|
||||||
|
shell.exit(1);
|
||||||
|
}
|
||||||
|
if (semver.valid(version)) {
|
||||||
|
const url = `https://downloads.arduino.cc/arduino-fwuploader/arduino-fwuploader_${version}_${suffix}`;
|
||||||
|
shell.echo(
|
||||||
|
`📦 Identified released version of the Firmware Uploader. Downloading version ${version} from '${url}'`
|
||||||
|
);
|
||||||
|
await downloader.downloadUnzipFile(
|
||||||
|
url,
|
||||||
|
destinationPath,
|
||||||
|
'arduino-fwuploader'
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
shell.echo(`🔥 Could not interpret 'version': ${version}`);
|
||||||
|
shell.exit(1);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// We assume an object with `owner`, `repo`, commitish?` properties.
|
||||||
|
const { owner, repo, commitish } = version;
|
||||||
|
if (!owner) {
|
||||||
|
shell.echo(`Could not retrieve 'owner' from ${JSON.stringify(version)}`);
|
||||||
|
shell.exit(1);
|
||||||
|
}
|
||||||
|
if (!repo) {
|
||||||
|
shell.echo(`Could not retrieve 'repo' from ${JSON.stringify(version)}`);
|
||||||
|
shell.exit(1);
|
||||||
|
}
|
||||||
|
const url = `https://github.com/${owner}/${repo}.git`;
|
||||||
|
shell.echo(
|
||||||
|
`Building Firmware Uploader from ${url}. Commitish: ${
|
||||||
|
commitish ? commitish : 'HEAD'
|
||||||
|
}`
|
||||||
|
);
|
||||||
|
|
||||||
|
if (fs.existsSync(destinationPath)) {
|
||||||
|
shell.echo(
|
||||||
|
`Skipping the Firmware Uploader build because it already exists: ${destinationPath}`
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (shell.mkdir('-p', buildFolder).code !== 0) {
|
||||||
|
shell.echo('Could not create build folder.');
|
||||||
|
shell.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const tempRepoPath = temp.mkdirSync();
|
||||||
|
shell.echo(`>>> Cloning Firmware Uploader source to ${tempRepoPath}...`);
|
||||||
|
if (shell.exec(`git clone ${url} ${tempRepoPath}`).code !== 0) {
|
||||||
|
shell.exit(1);
|
||||||
|
}
|
||||||
|
shell.echo('<<< Cloned Firmware Uploader repo.');
|
||||||
|
|
||||||
|
if (commitish) {
|
||||||
|
shell.echo(`>>> Checking out ${commitish}...`);
|
||||||
|
if (
|
||||||
|
shell.exec(`git -C ${tempRepoPath} checkout ${commitish}`).code !== 0
|
||||||
|
) {
|
||||||
|
shell.exit(1);
|
||||||
|
}
|
||||||
|
shell.echo(`<<< Checked out ${commitish}.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
shell.echo(`>>> Building the Firmware Uploader...`);
|
||||||
|
if (shell.exec('go build', { cwd: tempRepoPath }).code !== 0) {
|
||||||
|
shell.exit(1);
|
||||||
|
}
|
||||||
|
shell.echo('<<< Firmware Uploader build done.');
|
||||||
|
|
||||||
|
if (!fs.existsSync(path.join(tempRepoPath, fwuploderName))) {
|
||||||
|
shell.echo(
|
||||||
|
`Could not find the Firmware Uploader at ${path.join(
|
||||||
|
tempRepoPath,
|
||||||
|
fwuploderName
|
||||||
|
)}.`
|
||||||
|
);
|
||||||
|
shell.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const builtFwUploaderPath = path.join(tempRepoPath, fwuploderName);
|
||||||
|
shell.echo(
|
||||||
|
`>>> Copying Firmware Uploader from ${builtFwUploaderPath} to ${destinationPath}...`
|
||||||
|
);
|
||||||
|
if (shell.cp(builtFwUploaderPath, destinationPath).code !== 0) {
|
||||||
|
shell.exit(1);
|
||||||
|
}
|
||||||
|
shell.echo(`<<< Copied the Firmware Uploader.`);
|
||||||
|
|
||||||
|
shell.echo('<<< Verifying Firmware Uploader...');
|
||||||
|
if (!fs.existsSync(destinationPath)) {
|
||||||
|
shell.exit(1);
|
||||||
|
}
|
||||||
|
shell.echo('>>> Verified Firmware Uploader.');
|
||||||
|
}
|
||||||
|
})();
|
||||||
@@ -4,69 +4,103 @@
|
|||||||
// - https://downloads.arduino.cc/arduino-language-server/clangd/clangd_${VERSION}_${SUFFIX}
|
// - https://downloads.arduino.cc/arduino-language-server/clangd/clangd_${VERSION}_${SUFFIX}
|
||||||
|
|
||||||
(() => {
|
(() => {
|
||||||
|
|
||||||
const DEFAULT_ALS_VERSION = 'nightly';
|
|
||||||
const DEFAULT_CLANGD_VERSION = 'snapshot_20210124';
|
|
||||||
|
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
const shell = require('shelljs');
|
const shell = require('shelljs');
|
||||||
const downloader = require('./downloader');
|
const downloader = require('./downloader');
|
||||||
|
|
||||||
|
const [DEFAULT_ALS_VERSION, DEFAULT_CLANGD_VERSION] = (() => {
|
||||||
|
const pkg = require(path.join(__dirname, '..', 'package.json'));
|
||||||
|
if (!pkg) return undefined;
|
||||||
|
|
||||||
|
const { arduino } = pkg;
|
||||||
|
if (!arduino) return undefined;
|
||||||
|
|
||||||
|
const { languageServer, clangd } = arduino;
|
||||||
|
if (!languageServer) return undefined;
|
||||||
|
if (!clangd) return undefined;
|
||||||
|
|
||||||
|
return [languageServer.version, clangd.version];
|
||||||
|
})();
|
||||||
|
|
||||||
|
if (!DEFAULT_ALS_VERSION) {
|
||||||
|
shell.echo(
|
||||||
|
`Could not retrieve Arduino Language Server version info from the 'package.json'.`
|
||||||
|
);
|
||||||
|
shell.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!DEFAULT_CLANGD_VERSION) {
|
||||||
|
shell.echo(
|
||||||
|
`Could not retrieve clangd version info from the 'package.json'.`
|
||||||
|
);
|
||||||
|
shell.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
const yargs = require('yargs')
|
const yargs = require('yargs')
|
||||||
.option('ls-version', {
|
.option('ls-version', {
|
||||||
alias: 'lv',
|
alias: 'lv',
|
||||||
default: DEFAULT_ALS_VERSION,
|
default: DEFAULT_ALS_VERSION,
|
||||||
choices: ['nightly'],
|
describe: `The version of the 'arduino-language-server' to download. Defaults to ${DEFAULT_ALS_VERSION}.`,
|
||||||
describe: `The version of the 'arduino-language-server' to download. Defaults to ${DEFAULT_ALS_VERSION}.`
|
|
||||||
})
|
})
|
||||||
.option('clangd-version', {
|
.option('clangd-version', {
|
||||||
alias: 'cv',
|
alias: 'cv',
|
||||||
default: DEFAULT_CLANGD_VERSION,
|
default: DEFAULT_CLANGD_VERSION,
|
||||||
choices: ['snapshot_20210124'],
|
choices: [DEFAULT_CLANGD_VERSION, 'snapshot_20210124'],
|
||||||
describe: `The version of 'clangd' to download. Defaults to ${DEFAULT_CLANGD_VERSION}.`
|
describe: `The version of 'clangd' to download. Defaults to ${DEFAULT_CLANGD_VERSION}.`,
|
||||||
})
|
})
|
||||||
.option('force-download', {
|
.option('force-download', {
|
||||||
alias: 'fd',
|
alias: 'fd',
|
||||||
default: false,
|
default: false,
|
||||||
describe: `If set, this script force downloads the 'arduino-language-server' even if it already exists on the file system.`
|
describe: `If set, this script force downloads the 'arduino-language-server' even if it already exists on the file system.`,
|
||||||
})
|
})
|
||||||
.version(false).parse();
|
.version(false)
|
||||||
|
.parse();
|
||||||
|
|
||||||
const alsVersion = yargs['ls-version'];
|
const alsVersion = yargs['ls-version'];
|
||||||
const clangdVersion = yargs['clangd-version']
|
const clangdVersion = yargs['clangd-version'];
|
||||||
const force = yargs['force-download'];
|
const force = yargs['force-download'];
|
||||||
const { platform, arch } = process;
|
const { platform, arch } = process;
|
||||||
|
const platformArch = platform + '-' + arch;
|
||||||
const build = path.join(__dirname, '..', 'build');
|
const build = path.join(__dirname, '..', 'build');
|
||||||
const lsExecutablePath = path.join(build, `arduino-language-server${platform === 'win32' ? '.exe' : ''}`);
|
const lsExecutablePath = path.join(
|
||||||
|
build,
|
||||||
|
`arduino-language-server${platform === 'win32' ? '.exe' : ''}`
|
||||||
|
);
|
||||||
|
let clangdExecutablePath, lsSuffix, clangdSuffix;
|
||||||
|
|
||||||
let clangdExecutablePath, lsSuffix, clangdPrefix;
|
switch (platformArch) {
|
||||||
switch (platform) {
|
case 'darwin-x64':
|
||||||
case 'darwin':
|
clangdExecutablePath = path.join(build, 'clangd');
|
||||||
clangdExecutablePath = path.join(build, 'bin', 'clangd')
|
lsSuffix = 'macOS_64bit.tar.gz';
|
||||||
lsSuffix = 'macOS_amd64.zip';
|
clangdSuffix = 'macOS_64bit';
|
||||||
clangdPrefix = 'mac';
|
|
||||||
break;
|
break;
|
||||||
case 'linux':
|
case 'linux-x64':
|
||||||
clangdExecutablePath = path.join(build, 'bin', 'clangd')
|
clangdExecutablePath = path.join(build, 'clangd');
|
||||||
lsSuffix = 'Linux_amd64.zip';
|
lsSuffix = 'Linux_64bit.tar.gz';
|
||||||
clangdPrefix = 'linux'
|
clangdSuffix = 'Linux_64bit';
|
||||||
break;
|
break;
|
||||||
case 'win32':
|
case 'win32-x64':
|
||||||
clangdExecutablePath = path.join(build, 'bin', 'clangd.exe')
|
clangdExecutablePath = path.join(build, 'clangd.exe');
|
||||||
lsSuffix = 'Windows_amd64.zip';
|
lsSuffix = 'Windows_64bit.zip';
|
||||||
clangdPrefix = 'windows';
|
clangdSuffix = 'Windows_64bit';
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
if (!lsSuffix) {
|
if (!lsSuffix || !clangdSuffix) {
|
||||||
shell.echo(`The arduino-language-server is not available for ${platform} ${arch}.`);
|
shell.echo(
|
||||||
|
`The arduino-language-server is not available for ${platform} ${arch}.`
|
||||||
|
);
|
||||||
shell.exit(1);
|
shell.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
const alsUrl = `https://downloads.arduino.cc/arduino-language-server/${alsVersion === 'nightly' ? 'nightly/arduino-language-server' : 'arduino-language-server_' + alsVersion}_${lsSuffix}`;
|
const alsUrl = `https://downloads.arduino.cc/arduino-language-server/${
|
||||||
|
alsVersion === 'nightly'
|
||||||
|
? 'nightly/arduino-language-server'
|
||||||
|
: 'arduino-language-server_' + alsVersion
|
||||||
|
}_${lsSuffix}`;
|
||||||
downloader.downloadUnzipAll(alsUrl, build, lsExecutablePath, force);
|
downloader.downloadUnzipAll(alsUrl, build, lsExecutablePath, force);
|
||||||
|
|
||||||
const clangdUrl = `https://downloads.arduino.cc/arduino-language-server/clangd/clangd-${clangdPrefix}-${clangdVersion}.zip`;
|
const clangdUrl = `https://downloads.arduino.cc/tools/clangd_${clangdVersion}_${clangdSuffix}.tar.bz2`;
|
||||||
downloader.downloadUnzipAll(clangdUrl, build, clangdExecutablePath, force, { strip: 1 }); // `strip`: the new clangd (12.x) is zipped into a folder, so we have to strip the outmost folder.
|
downloader.downloadUnzipAll(clangdUrl, build, clangdExecutablePath, force, {
|
||||||
|
strip: 1,
|
||||||
|
}); // `strip`: the new clangd (12.x) is zipped into a folder, so we have to strip the outmost folder.
|
||||||
})();
|
})();
|
||||||
|
|||||||
@@ -5,13 +5,14 @@ const download = require('download');
|
|||||||
const decompress = require('decompress');
|
const decompress = require('decompress');
|
||||||
const unzip = require('decompress-unzip');
|
const unzip = require('decompress-unzip');
|
||||||
const untargz = require('decompress-targz');
|
const untargz = require('decompress-targz');
|
||||||
|
const untarbz2 = require('decompress-tarbz2');
|
||||||
|
|
||||||
process.on('unhandledRejection', (reason, _) => {
|
process.on('unhandledRejection', (reason, _) => {
|
||||||
shell.echo(String(reason));
|
shell.echo(String(reason));
|
||||||
shell.exit(1);
|
shell.exit(1);
|
||||||
throw reason;
|
throw reason;
|
||||||
});
|
});
|
||||||
process.on('uncaughtException', error => {
|
process.on('uncaughtException', (error) => {
|
||||||
shell.echo(String(error));
|
shell.echo(String(error));
|
||||||
shell.exit(1);
|
shell.exit(1);
|
||||||
throw error;
|
throw error;
|
||||||
@@ -23,7 +24,12 @@ process.on('uncaughtException', error => {
|
|||||||
* @param filePrefix {string} Prefix of the file name found in the 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. `false` by default.
|
||||||
*/
|
*/
|
||||||
exports.downloadUnzipFile = async (url, targetFile, filePrefix, force = false) => {
|
exports.downloadUnzipFile = async (
|
||||||
|
url,
|
||||||
|
targetFile,
|
||||||
|
filePrefix,
|
||||||
|
force = false
|
||||||
|
) => {
|
||||||
if (fs.existsSync(targetFile) && !force) {
|
if (fs.existsSync(targetFile) && !force) {
|
||||||
shell.echo(`Skipping download because file already exists: ${targetFile}`);
|
shell.echo(`Skipping download because file already exists: ${targetFile}`);
|
||||||
return;
|
return;
|
||||||
@@ -46,23 +52,25 @@ exports.downloadUnzipFile = async (url, targetFile, filePrefix, force = false) =
|
|||||||
|
|
||||||
shell.echo('>>> Decompressing...');
|
shell.echo('>>> Decompressing...');
|
||||||
const files = await decompress(data, downloads, {
|
const files = await decompress(data, downloads, {
|
||||||
plugins: [
|
plugins: [unzip(), untargz(), untarbz2()],
|
||||||
unzip(),
|
|
||||||
untargz()
|
|
||||||
]
|
|
||||||
});
|
});
|
||||||
if (files.length === 0) {
|
if (files.length === 0) {
|
||||||
shell.echo('Error ocurred while decompressing the archive.');
|
shell.echo('Error ocurred while decompressing the archive.');
|
||||||
shell.exit(1);
|
shell.exit(1);
|
||||||
}
|
}
|
||||||
const fileIndex = files.findIndex(f => f.path.startsWith(filePrefix));
|
const fileIndex = files.findIndex((f) => f.path.startsWith(filePrefix));
|
||||||
if (fileIndex === -1) {
|
if (fileIndex === -1) {
|
||||||
shell.echo(`The downloaded artifact does not contain any file with prefix ${filePrefix}.`);
|
shell.echo(
|
||||||
|
`The downloaded artifact does not contain any file with prefix ${filePrefix}.`
|
||||||
|
);
|
||||||
shell.exit(1);
|
shell.exit(1);
|
||||||
}
|
}
|
||||||
shell.echo('<<< Decompressing succeeded.');
|
shell.echo('<<< Decompressing succeeded.');
|
||||||
|
|
||||||
if (shell.mv('-f', path.join(downloads, files[fileIndex].path), targetFile).code !== 0) {
|
if (
|
||||||
|
shell.mv('-f', path.join(downloads, files[fileIndex].path), targetFile)
|
||||||
|
.code !== 0
|
||||||
|
) {
|
||||||
shell.echo(`Could not move file to target path: ${targetFile}`);
|
shell.echo(`Could not move file to target path: ${targetFile}`);
|
||||||
shell.exit(1);
|
shell.exit(1);
|
||||||
}
|
}
|
||||||
@@ -71,7 +79,7 @@ exports.downloadUnzipFile = async (url, targetFile, filePrefix, force = false) =
|
|||||||
shell.exit(1);
|
shell.exit(1);
|
||||||
}
|
}
|
||||||
shell.echo(`Done: ${targetFile}`);
|
shell.echo(`Done: ${targetFile}`);
|
||||||
}
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param url {string} Download URL
|
* @param url {string} Download URL
|
||||||
@@ -79,7 +87,13 @@ exports.downloadUnzipFile = async (url, targetFile, filePrefix, force = false) =
|
|||||||
* @param targetFile {string} Path to the main file expected after decompressing
|
* @param targetFile {string} Path to the main file expected after decompressing
|
||||||
* @param force {boolean} Whether to download even if the target file exists
|
* @param force {boolean} Whether to download even if the target file exists
|
||||||
*/
|
*/
|
||||||
exports.downloadUnzipAll = async (url, targetDir, targetFile, force, decompressOptions = undefined) => {
|
exports.downloadUnzipAll = async (
|
||||||
|
url,
|
||||||
|
targetDir,
|
||||||
|
targetFile,
|
||||||
|
force,
|
||||||
|
decompressOptions = undefined
|
||||||
|
) => {
|
||||||
if (fs.existsSync(targetFile) && !force) {
|
if (fs.existsSync(targetFile) && !force) {
|
||||||
shell.echo(`Skipping download because file already exists: ${targetFile}`);
|
shell.echo(`Skipping download because file already exists: ${targetFile}`);
|
||||||
return;
|
return;
|
||||||
@@ -97,13 +111,10 @@ exports.downloadUnzipAll = async (url, targetDir, targetFile, force, decompressO
|
|||||||
|
|
||||||
shell.echo('>>> Decompressing...');
|
shell.echo('>>> Decompressing...');
|
||||||
let options = {
|
let options = {
|
||||||
plugins: [
|
plugins: [unzip(), untargz(), untarbz2()],
|
||||||
unzip(),
|
|
||||||
untargz()
|
|
||||||
]
|
|
||||||
};
|
};
|
||||||
if (decompressOptions) {
|
if (decompressOptions) {
|
||||||
options = Object.assign(options, decompressOptions)
|
options = Object.assign(options, decompressOptions);
|
||||||
}
|
}
|
||||||
const files = await decompress(data, targetDir, options);
|
const files = await decompress(data, targetDir, options);
|
||||||
if (files.length === 0) {
|
if (files.length === 0) {
|
||||||
@@ -117,4 +128,4 @@ exports.downloadUnzipAll = async (url, targetDir, targetFile, force, decompressO
|
|||||||
shell.exit(1);
|
shell.exit(1);
|
||||||
}
|
}
|
||||||
shell.echo(`Done: ${targetFile}`);
|
shell.echo(`Done: ${targetFile}`);
|
||||||
}
|
};
|
||||||
|
|||||||
@@ -4,20 +4,18 @@ import { Command } from '@theia/core/lib/common/command';
|
|||||||
* @deprecated all these commands should go under contributions and have their command, menu, keybinding, and toolbar contributions.
|
* @deprecated all these commands should go under contributions and have their command, menu, keybinding, and toolbar contributions.
|
||||||
*/
|
*/
|
||||||
export namespace ArduinoCommands {
|
export namespace ArduinoCommands {
|
||||||
|
|
||||||
export const TOGGLE_COMPILE_FOR_DEBUG: Command = {
|
export const TOGGLE_COMPILE_FOR_DEBUG: Command = {
|
||||||
id: 'arduino-toggle-compile-for-debug'
|
id: 'arduino-toggle-compile-for-debug',
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Unlike `OPEN_SKETCH`, it opens all files from a sketch folder. (ino, cpp, etc...)
|
* Unlike `OPEN_SKETCH`, it opens all files from a sketch folder. (ino, cpp, etc...)
|
||||||
*/
|
*/
|
||||||
export const OPEN_SKETCH_FILES: Command = {
|
export const OPEN_SKETCH_FILES: Command = {
|
||||||
id: 'arduino-open-sketch-files'
|
id: 'arduino-open-sketch-files',
|
||||||
};
|
};
|
||||||
|
|
||||||
export const OPEN_BOARDS_DIALOG: Command = {
|
export const OPEN_BOARDS_DIALOG: Command = {
|
||||||
id: 'arduino-open-boards-dialog'
|
id: 'arduino-open-boards-dialog',
|
||||||
};
|
};
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,19 +1,47 @@
|
|||||||
const debounce = require('lodash.debounce');
|
import { inject, injectable, postConstruct } from 'inversify';
|
||||||
import { MAIN_MENU_BAR, MenuContribution, MenuModelRegistry, SelectionService, ILogger } from '@theia/core';
|
import * as React from 'react';
|
||||||
|
import * as remote from '@theia/core/electron-shared/@electron/remote';
|
||||||
import {
|
import {
|
||||||
ContextMenuRenderer,
|
BoardsService,
|
||||||
FrontendApplication, FrontendApplicationContribution,
|
SketchesService,
|
||||||
OpenerService, StatusBar, StatusBarAlignment
|
ExecutableService,
|
||||||
|
Sketch,
|
||||||
|
LibraryService,
|
||||||
|
} from '../common/protocol';
|
||||||
|
import { Mutex } from 'async-mutex';
|
||||||
|
import {
|
||||||
|
MAIN_MENU_BAR,
|
||||||
|
MenuContribution,
|
||||||
|
MenuModelRegistry,
|
||||||
|
ILogger,
|
||||||
|
DisposableCollection,
|
||||||
|
} from '@theia/core';
|
||||||
|
import {
|
||||||
|
FrontendApplication,
|
||||||
|
FrontendApplicationContribution,
|
||||||
|
LocalStorageService,
|
||||||
|
StatusBar,
|
||||||
|
StatusBarAlignment,
|
||||||
} from '@theia/core/lib/browser';
|
} from '@theia/core/lib/browser';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
import { ColorContribution } from '@theia/core/lib/browser/color-application-contribution';
|
import { ColorContribution } from '@theia/core/lib/browser/color-application-contribution';
|
||||||
import { ColorRegistry } from '@theia/core/lib/browser/color-registry';
|
import { ColorRegistry } from '@theia/core/lib/browser/color-registry';
|
||||||
import { CommonMenus } from '@theia/core/lib/browser/common-frontend-contribution';
|
import { CommonMenus } from '@theia/core/lib/browser/common-frontend-contribution';
|
||||||
import { TabBarToolbarContribution, TabBarToolbarRegistry } from '@theia/core/lib/browser/shell/tab-bar-toolbar';
|
import {
|
||||||
import { CommandContribution, CommandRegistry } from '@theia/core/lib/common/command';
|
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 { MessageService } from '@theia/core/lib/common/message-service';
|
||||||
import URI from '@theia/core/lib/common/uri';
|
import URI from '@theia/core/lib/common/uri';
|
||||||
import { EditorMainMenu, EditorManager } from '@theia/editor/lib/browser';
|
import {
|
||||||
import { FileDialogService } from '@theia/filesystem/lib/browser/file-dialog';
|
EditorMainMenu,
|
||||||
|
EditorManager,
|
||||||
|
EditorOpenerOptions,
|
||||||
|
} from '@theia/editor/lib/browser';
|
||||||
import { ProblemContribution } from '@theia/markers/lib/browser/problem/problem-contribution';
|
import { ProblemContribution } from '@theia/markers/lib/browser/problem/problem-contribution';
|
||||||
import { MonacoMenus } from '@theia/monaco/lib/browser/monaco-menu';
|
import { MonacoMenus } from '@theia/monaco/lib/browser/monaco-menu';
|
||||||
import { FileNavigatorContribution } from '@theia/navigator/lib/browser/navigator-contribution';
|
import { FileNavigatorContribution } from '@theia/navigator/lib/browser/navigator-contribution';
|
||||||
@@ -22,37 +50,38 @@ import { OutputContribution } from '@theia/output/lib/browser/output-contributio
|
|||||||
import { ScmContribution } from '@theia/scm/lib/browser/scm-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 { SearchInWorkspaceFrontendContribution } from '@theia/search-in-workspace/lib/browser/search-in-workspace-frontend-contribution';
|
||||||
import { TerminalMenus } from '@theia/terminal/lib/browser/terminal-frontend-contribution';
|
import { TerminalMenus } from '@theia/terminal/lib/browser/terminal-frontend-contribution';
|
||||||
import { inject, injectable, postConstruct } from 'inversify';
|
import { HostedPluginSupport } from '@theia/plugin-ext/lib/hosted/browser/hosted-plugin';
|
||||||
import * as React from 'react';
|
import { FileService } from '@theia/filesystem/lib/browser/file-service';
|
||||||
import { remote } from 'electron';
|
import { FileChangeType } from '@theia/filesystem/lib/browser';
|
||||||
import { MainMenuManager } from '../common/main-menu-manager';
|
import { FrontendApplicationStateService } from '@theia/core/lib/browser/frontend-application-state';
|
||||||
import { BoardsService, CoreService, Port, SketchesService, ExecutableService } from '../common/protocol';
|
|
||||||
import { ArduinoDaemon } from '../common/protocol/arduino-daemon';
|
|
||||||
import { ConfigService } from '../common/protocol/config-service';
|
import { ConfigService } from '../common/protocol/config-service';
|
||||||
import { FileSystemExt } from '../common/protocol/filesystem-ext';
|
|
||||||
import { ArduinoCommands } from './arduino-commands';
|
import { ArduinoCommands } from './arduino-commands';
|
||||||
import { BoardsConfig } from './boards/boards-config';
|
import { BoardsConfig } from './boards/boards-config';
|
||||||
import { BoardsConfigDialog } from './boards/boards-config-dialog';
|
import { BoardsConfigDialog } from './boards/boards-config-dialog';
|
||||||
import { BoardsDataStore } from './boards/boards-data-store';
|
|
||||||
import { BoardsServiceProvider } from './boards/boards-service-provider';
|
import { BoardsServiceProvider } from './boards/boards-service-provider';
|
||||||
import { BoardsToolBarItem } from './boards/boards-toolbar-item';
|
import { BoardsToolBarItem } from './boards/boards-toolbar-item';
|
||||||
import { EditorMode } from './editor-mode';
|
import { EditorMode } from './editor-mode';
|
||||||
import { ArduinoMenus } from './menu/arduino-menus';
|
import { ArduinoMenus } from './menu/arduino-menus';
|
||||||
import { MonitorConnection } from './monitor/monitor-connection';
|
import { MonitorViewContribution } from './serial/monitor/monitor-view-contribution';
|
||||||
import { MonitorViewContribution } from './monitor/monitor-view-contribution';
|
|
||||||
import { WorkspaceService } from './theia/workspace/workspace-service';
|
|
||||||
import { ArduinoToolbar } from './toolbar/arduino-toolbar';
|
import { ArduinoToolbar } from './toolbar/arduino-toolbar';
|
||||||
import { HostedPluginSupport } from '@theia/plugin-ext/lib/hosted/browser/hosted-plugin';
|
|
||||||
import { FileService } from '@theia/filesystem/lib/browser/file-service';
|
|
||||||
import { OutputService } from '../common/protocol/output-service';
|
|
||||||
import { ArduinoPreferences } from './arduino-preferences';
|
import { ArduinoPreferences } from './arduino-preferences';
|
||||||
import { SketchesServiceClientImpl } from '../common/protocol/sketches-service-client-impl';
|
import { SketchesServiceClientImpl } from '../common/protocol/sketches-service-client-impl';
|
||||||
import { SaveAsSketch } from './contributions/save-as-sketch';
|
import { SaveAsSketch } from './contributions/save-as-sketch';
|
||||||
|
import { SketchbookWidgetContribution } from './widgets/sketchbook/sketchbook-widget-contribution';
|
||||||
|
import { IDEUpdaterDialog } from './dialogs/ide-updater/ide-updater-dialog';
|
||||||
|
import { IDEUpdater } from '../common/protocol/ide-updater';
|
||||||
|
|
||||||
|
const INIT_LIBS_AND_PACKAGES = 'initializedLibsAndPackages';
|
||||||
|
export const SKIP_IDE_VERSION = 'skipIDEVersion';
|
||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export class ArduinoFrontendContribution implements FrontendApplicationContribution,
|
export class ArduinoFrontendContribution
|
||||||
TabBarToolbarContribution, CommandContribution, MenuContribution, ColorContribution {
|
implements
|
||||||
|
FrontendApplicationContribution,
|
||||||
|
TabBarToolbarContribution,
|
||||||
|
CommandContribution,
|
||||||
|
MenuContribution,
|
||||||
|
ColorContribution {
|
||||||
@inject(ILogger)
|
@inject(ILogger)
|
||||||
protected logger: ILogger;
|
protected logger: ILogger;
|
||||||
|
|
||||||
@@ -62,26 +91,17 @@ export class ArduinoFrontendContribution implements FrontendApplicationContribut
|
|||||||
@inject(BoardsService)
|
@inject(BoardsService)
|
||||||
protected readonly boardsService: BoardsService;
|
protected readonly boardsService: BoardsService;
|
||||||
|
|
||||||
@inject(CoreService)
|
@inject(LibraryService)
|
||||||
protected readonly coreService: CoreService;
|
protected readonly libraryService: LibraryService;
|
||||||
|
|
||||||
@inject(BoardsServiceProvider)
|
@inject(BoardsServiceProvider)
|
||||||
protected readonly boardsServiceClientImpl: BoardsServiceProvider;
|
protected readonly boardsServiceClientImpl: BoardsServiceProvider;
|
||||||
|
|
||||||
@inject(SelectionService)
|
|
||||||
protected readonly selectionService: SelectionService;
|
|
||||||
|
|
||||||
@inject(EditorManager)
|
@inject(EditorManager)
|
||||||
protected readonly editorManager: EditorManager;
|
protected readonly editorManager: EditorManager;
|
||||||
|
|
||||||
@inject(ContextMenuRenderer)
|
|
||||||
protected readonly contextMenuRenderer: ContextMenuRenderer;
|
|
||||||
|
|
||||||
@inject(FileDialogService)
|
|
||||||
protected readonly fileDialogService: FileDialogService;
|
|
||||||
|
|
||||||
@inject(FileService)
|
@inject(FileService)
|
||||||
protected readonly fileSystem: FileService;
|
protected readonly fileService: FileService;
|
||||||
|
|
||||||
@inject(SketchesService)
|
@inject(SketchesService)
|
||||||
protected readonly sketchService: SketchesService;
|
protected readonly sketchService: SketchesService;
|
||||||
@@ -89,21 +109,12 @@ export class ArduinoFrontendContribution implements FrontendApplicationContribut
|
|||||||
@inject(BoardsConfigDialog)
|
@inject(BoardsConfigDialog)
|
||||||
protected readonly boardsConfigDialog: BoardsConfigDialog;
|
protected readonly boardsConfigDialog: BoardsConfigDialog;
|
||||||
|
|
||||||
@inject(MenuModelRegistry)
|
|
||||||
protected readonly menuRegistry: MenuModelRegistry;
|
|
||||||
|
|
||||||
@inject(CommandRegistry)
|
@inject(CommandRegistry)
|
||||||
protected readonly commandRegistry: CommandRegistry;
|
protected readonly commandRegistry: CommandRegistry;
|
||||||
|
|
||||||
@inject(StatusBar)
|
@inject(StatusBar)
|
||||||
protected readonly statusBar: StatusBar;
|
protected readonly statusBar: StatusBar;
|
||||||
|
|
||||||
@inject(WorkspaceService)
|
|
||||||
protected readonly workspaceService: WorkspaceService;
|
|
||||||
|
|
||||||
@inject(MonitorConnection)
|
|
||||||
protected readonly monitorConnection: MonitorConnection;
|
|
||||||
|
|
||||||
@inject(FileNavigatorContribution)
|
@inject(FileNavigatorContribution)
|
||||||
protected readonly fileNavigatorContributions: FileNavigatorContribution;
|
protected readonly fileNavigatorContributions: FileNavigatorContribution;
|
||||||
|
|
||||||
@@ -122,69 +133,133 @@ export class ArduinoFrontendContribution implements FrontendApplicationContribut
|
|||||||
@inject(SearchInWorkspaceFrontendContribution)
|
@inject(SearchInWorkspaceFrontendContribution)
|
||||||
protected readonly siwContribution: SearchInWorkspaceFrontendContribution;
|
protected readonly siwContribution: SearchInWorkspaceFrontendContribution;
|
||||||
|
|
||||||
|
@inject(SketchbookWidgetContribution)
|
||||||
|
protected readonly sketchbookWidgetContribution: SketchbookWidgetContribution;
|
||||||
|
|
||||||
@inject(EditorMode)
|
@inject(EditorMode)
|
||||||
protected readonly editorMode: EditorMode;
|
protected readonly editorMode: EditorMode;
|
||||||
|
|
||||||
@inject(ArduinoDaemon)
|
|
||||||
protected readonly daemon: ArduinoDaemon;
|
|
||||||
|
|
||||||
@inject(OpenerService)
|
|
||||||
protected readonly openerService: OpenerService;
|
|
||||||
|
|
||||||
@inject(ConfigService)
|
@inject(ConfigService)
|
||||||
protected readonly configService: ConfigService;
|
protected readonly configService: ConfigService;
|
||||||
|
|
||||||
@inject(BoardsDataStore)
|
|
||||||
protected readonly boardsDataStore: BoardsDataStore;
|
|
||||||
|
|
||||||
@inject(MainMenuManager)
|
|
||||||
protected readonly mainMenuManager: MainMenuManager;
|
|
||||||
|
|
||||||
@inject(FileSystemExt)
|
|
||||||
protected readonly fileSystemExt: FileSystemExt;
|
|
||||||
|
|
||||||
@inject(HostedPluginSupport)
|
@inject(HostedPluginSupport)
|
||||||
protected hostedPluginSupport: HostedPluginSupport;
|
protected hostedPluginSupport: HostedPluginSupport;
|
||||||
|
|
||||||
@inject(ExecutableService)
|
@inject(ExecutableService)
|
||||||
protected executableService: ExecutableService;
|
protected executableService: ExecutableService;
|
||||||
|
|
||||||
@inject(OutputService)
|
|
||||||
protected readonly outputService: OutputService;
|
|
||||||
|
|
||||||
@inject(ArduinoPreferences)
|
@inject(ArduinoPreferences)
|
||||||
protected readonly arduinoPreferences: ArduinoPreferences;
|
protected readonly arduinoPreferences: ArduinoPreferences;
|
||||||
|
|
||||||
@inject(SketchesServiceClientImpl)
|
@inject(SketchesServiceClientImpl)
|
||||||
protected readonly sketchServiceClient: SketchesServiceClientImpl;
|
protected readonly sketchServiceClient: SketchesServiceClientImpl;
|
||||||
|
|
||||||
protected invalidConfigPopup: Promise<void | 'No' | 'Yes' | undefined> | undefined;
|
protected readonly appStateService: FrontendApplicationStateService;
|
||||||
|
|
||||||
|
@inject(LocalStorageService)
|
||||||
|
protected readonly localStorageService: LocalStorageService;
|
||||||
|
|
||||||
|
@inject(IDEUpdater)
|
||||||
|
protected readonly updater: IDEUpdater;
|
||||||
|
|
||||||
|
@inject(IDEUpdaterDialog)
|
||||||
|
protected readonly updaterDialog: IDEUpdaterDialog;
|
||||||
|
|
||||||
|
protected invalidConfigPopup:
|
||||||
|
| Promise<void | 'No' | 'Yes' | undefined>
|
||||||
|
| undefined;
|
||||||
|
protected toDisposeOnStop = new DisposableCollection();
|
||||||
|
|
||||||
@postConstruct()
|
@postConstruct()
|
||||||
protected async init(): Promise<void> {
|
protected async init(): Promise<void> {
|
||||||
|
const isFirstStartup = !(await this.localStorageService.getData(
|
||||||
|
INIT_LIBS_AND_PACKAGES
|
||||||
|
));
|
||||||
|
if (isFirstStartup) {
|
||||||
|
await this.localStorageService.setData(INIT_LIBS_AND_PACKAGES, true);
|
||||||
|
const avrPackage = await this.boardsService.getBoardPackage({
|
||||||
|
id: 'arduino:avr',
|
||||||
|
});
|
||||||
|
const builtInLibrary = (
|
||||||
|
await this.libraryService.search({
|
||||||
|
query: 'Arduino_BuiltIn',
|
||||||
|
})
|
||||||
|
)[0];
|
||||||
|
|
||||||
|
!!avrPackage && (await this.boardsService.install({ item: avrPackage }));
|
||||||
|
!!builtInLibrary &&
|
||||||
|
(await this.libraryService.install({
|
||||||
|
item: builtInLibrary,
|
||||||
|
installDependencies: true,
|
||||||
|
}));
|
||||||
|
}
|
||||||
if (!window.navigator.onLine) {
|
if (!window.navigator.onLine) {
|
||||||
// tslint:disable-next-line:max-line-length
|
// 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.');
|
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.'
|
||||||
|
)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
const updateStatusBar = ({ selectedBoard, selectedPort }: BoardsConfig.Config) => {
|
const updateStatusBar = ({
|
||||||
|
selectedBoard,
|
||||||
|
selectedPort,
|
||||||
|
}: BoardsConfig.Config) => {
|
||||||
this.statusBar.setElement('arduino-selected-board', {
|
this.statusBar.setElement('arduino-selected-board', {
|
||||||
alignment: StatusBarAlignment.RIGHT,
|
alignment: StatusBarAlignment.RIGHT,
|
||||||
text: selectedBoard ? `$(microchip) ${selectedBoard.name}` : '$(close) no board selected',
|
text: selectedBoard
|
||||||
className: 'arduino-selected-board'
|
? `$(microchip) ${selectedBoard.name}`
|
||||||
|
: `$(close) ${nls.localize(
|
||||||
|
'arduino/common/noBoardSelected',
|
||||||
|
'No board selected'
|
||||||
|
)}`,
|
||||||
|
className: 'arduino-selected-board',
|
||||||
});
|
});
|
||||||
if (selectedBoard) {
|
if (selectedBoard) {
|
||||||
this.statusBar.setElement('arduino-selected-port', {
|
this.statusBar.setElement('arduino-selected-port', {
|
||||||
alignment: StatusBarAlignment.RIGHT,
|
alignment: StatusBarAlignment.RIGHT,
|
||||||
text: selectedPort ? `on ${Port.toString(selectedPort)}` : '[not connected]',
|
text: selectedPort
|
||||||
className: 'arduino-selected-port'
|
? nls.localize(
|
||||||
|
'arduino/common/selectedOn',
|
||||||
|
'on {0}',
|
||||||
|
selectedPort.address
|
||||||
|
)
|
||||||
|
: nls.localize('arduino/common/notConnected', '[not connected]'),
|
||||||
|
className: 'arduino-selected-port',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
this.boardsServiceClientImpl.onBoardsConfigChanged(updateStatusBar);
|
||||||
|
updateStatusBar(this.boardsServiceClientImpl.boardsConfig);
|
||||||
|
this.appStateService.reachedState('ready').then(async () => {
|
||||||
|
const sketch = await this.sketchServiceClient.currentSketch();
|
||||||
|
if (sketch && !(await this.sketchService.isTemp(sketch))) {
|
||||||
|
this.toDisposeOnStop.push(this.fileService.watch(new URI(sketch.uri)));
|
||||||
|
this.toDisposeOnStop.push(
|
||||||
|
this.fileService.onDidFilesChange(async (event) => {
|
||||||
|
for (const { type, resource } of event.changes) {
|
||||||
|
if (
|
||||||
|
type === FileChangeType.ADDED &&
|
||||||
|
resource.parent.toString() === sketch.uri
|
||||||
|
) {
|
||||||
|
const reloadedSketch = await this.sketchService.loadSketch(
|
||||||
|
sketch.uri
|
||||||
|
);
|
||||||
|
if (Sketch.isInSketch(resource, reloadedSketch)) {
|
||||||
|
this.ensureOpened(resource.toString(), true, {
|
||||||
|
mode: 'open',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
this.boardsServiceClientImpl.onBoardsConfigChanged(updateStatusBar);
|
}
|
||||||
updateStatusBar(this.boardsServiceClientImpl.boardsConfig);
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
onStart(app: FrontendApplication): void {
|
async onStart(app: FrontendApplication): Promise<void> {
|
||||||
// Initialize all `pro-mode` widgets. This is a NOOP if in normal mode.
|
// Initialize all `pro-mode` widgets. This is a NOOP if in normal mode.
|
||||||
for (const viewContribution of [
|
for (const viewContribution of [
|
||||||
this.fileNavigatorContributions,
|
this.fileNavigatorContributions,
|
||||||
@@ -192,24 +267,67 @@ export class ArduinoFrontendContribution implements FrontendApplicationContribut
|
|||||||
this.outlineContribution,
|
this.outlineContribution,
|
||||||
this.problemContribution,
|
this.problemContribution,
|
||||||
this.scmContribution,
|
this.scmContribution,
|
||||||
this.siwContribution] as Array<FrontendApplicationContribution>) {
|
this.siwContribution,
|
||||||
|
this.sketchbookWidgetContribution,
|
||||||
|
] as Array<FrontendApplicationContribution>) {
|
||||||
if (viewContribution.initializeLayout) {
|
if (viewContribution.initializeLayout) {
|
||||||
viewContribution.initializeLayout(app);
|
viewContribution.initializeLayout(app);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
this.updater
|
||||||
|
.init(
|
||||||
|
this.arduinoPreferences.get('arduino.ide.updateChannel'),
|
||||||
|
this.arduinoPreferences.get('arduino.ide.updateBaseUrl')
|
||||||
|
)
|
||||||
|
.then(() => this.updater.checkForUpdates(true))
|
||||||
|
.then(async (updateInfo) => {
|
||||||
|
if (!updateInfo) return;
|
||||||
|
const versionToSkip = await this.localStorageService.getData<string>(
|
||||||
|
SKIP_IDE_VERSION
|
||||||
|
);
|
||||||
|
if (versionToSkip === updateInfo.version) return;
|
||||||
|
this.updaterDialog.open(updateInfo);
|
||||||
|
})
|
||||||
|
.catch((e) => {
|
||||||
|
this.messageService.error(
|
||||||
|
nls.localize(
|
||||||
|
'arduino/ide-updater/errorCheckingForUpdates',
|
||||||
|
'Error while checking for Arduino IDE updates.\n{0}',
|
||||||
|
e.message
|
||||||
|
)
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
const start = async ({ selectedBoard }: BoardsConfig.Config) => {
|
const start = async ({ selectedBoard }: BoardsConfig.Config) => {
|
||||||
if (selectedBoard) {
|
if (selectedBoard) {
|
||||||
const { name, fqbn } = selectedBoard;
|
const { name, fqbn } = selectedBoard;
|
||||||
if (fqbn) {
|
if (fqbn) {
|
||||||
await this.hostedPluginSupport.didStart;
|
|
||||||
this.startLanguageServer(fqbn, name);
|
this.startLanguageServer(fqbn, name);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
this.boardsServiceClientImpl.onBoardsConfigChanged(start);
|
this.boardsServiceClientImpl.onBoardsConfigChanged(start);
|
||||||
this.arduinoPreferences.onPreferenceChanged(event => {
|
this.arduinoPreferences.onPreferenceChanged((event) => {
|
||||||
if (event.preferenceName === 'arduino.language.log' && event.newValue !== event.oldValue) {
|
if (event.newValue !== event.oldValue) {
|
||||||
|
switch (event.preferenceName) {
|
||||||
|
case 'arduino.language.log':
|
||||||
start(this.boardsServiceClientImpl.boardsConfig);
|
start(this.boardsServiceClientImpl.boardsConfig);
|
||||||
|
break;
|
||||||
|
case 'arduino.window.zoomLevel':
|
||||||
|
if (typeof event.newValue === 'number') {
|
||||||
|
const webContents = remote.getCurrentWebContents();
|
||||||
|
webContents.setZoomLevel(event.newValue || 0);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case 'arduino.ide.updateChannel':
|
||||||
|
case 'arduino.ide.updateBaseUrl':
|
||||||
|
this.updater.init(
|
||||||
|
this.arduinoPreferences.get('arduino.ide.updateChannel'),
|
||||||
|
this.arduinoPreferences.get('arduino.ide.updateBaseUrl')
|
||||||
|
);
|
||||||
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
this.arduinoPreferences.ready.then(() => {
|
this.arduinoPreferences.ready.then(() => {
|
||||||
@@ -217,69 +335,131 @@ export class ArduinoFrontendContribution implements FrontendApplicationContribut
|
|||||||
const zoomLevel = this.arduinoPreferences.get('arduino.window.zoomLevel');
|
const zoomLevel = this.arduinoPreferences.get('arduino.window.zoomLevel');
|
||||||
webContents.setZoomLevel(zoomLevel);
|
webContents.setZoomLevel(zoomLevel);
|
||||||
});
|
});
|
||||||
this.arduinoPreferences.onPreferenceChanged(event => {
|
|
||||||
if (event.preferenceName === 'arduino.window.zoomLevel' && typeof event.newValue === 'number' && event.newValue !== event.oldValue) {
|
app.shell.leftPanelHandler.removeBottomMenu('settings-menu');
|
||||||
const webContents = remote.getCurrentWebContents();
|
|
||||||
webContents.setZoomLevel(event.newValue || 0);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected startLanguageServer = debounce((fqbn: string, name: string | undefined) => this.doStartLanguageServer(fqbn, name));
|
onStop(): void {
|
||||||
protected async doStartLanguageServer(fqbn: string, name: string | undefined): Promise<void> {
|
this.toDisposeOnStop.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected languageServerFqbn?: string;
|
||||||
|
protected languageServerStartMutex = new Mutex();
|
||||||
|
protected async startLanguageServer(
|
||||||
|
fqbn: string,
|
||||||
|
name: string | undefined
|
||||||
|
): Promise<void> {
|
||||||
|
const release = await this.languageServerStartMutex.acquire();
|
||||||
|
try {
|
||||||
|
await this.hostedPluginSupport.didStart;
|
||||||
|
const details = await this.boardsService.getBoardDetails({ fqbn });
|
||||||
|
if (!details) {
|
||||||
|
// Core is not installed for the selected board.
|
||||||
|
console.info(
|
||||||
|
`Could not start language server for ${fqbn}. The core is not installed for the board.`
|
||||||
|
);
|
||||||
|
if (this.languageServerFqbn) {
|
||||||
|
try {
|
||||||
|
await this.commandRegistry.executeCommand(
|
||||||
|
'arduino.languageserver.stop'
|
||||||
|
);
|
||||||
|
console.info(
|
||||||
|
`Stopped language server process for ${this.languageServerFqbn}.`
|
||||||
|
);
|
||||||
|
this.languageServerFqbn = undefined;
|
||||||
|
} catch (e) {
|
||||||
|
console.error(
|
||||||
|
`Failed to start language server process for ${this.languageServerFqbn}`,
|
||||||
|
e
|
||||||
|
);
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (fqbn === this.languageServerFqbn) {
|
||||||
|
// NOOP
|
||||||
|
return;
|
||||||
|
}
|
||||||
this.logger.info(`Starting language server: ${fqbn}`);
|
this.logger.info(`Starting language server: ${fqbn}`);
|
||||||
const log = this.arduinoPreferences.get('arduino.language.log');
|
const log = this.arduinoPreferences.get('arduino.language.log');
|
||||||
let currentSketchPath: string | undefined = undefined;
|
let currentSketchPath: string | undefined = undefined;
|
||||||
if (log) {
|
if (log) {
|
||||||
const currentSketch = await this.sketchServiceClient.currentSketch();
|
const currentSketch = await this.sketchServiceClient.currentSketch();
|
||||||
if (currentSketch) {
|
if (currentSketch) {
|
||||||
currentSketchPath = await this.fileSystem.fsPath(new URI(currentSketch.uri));
|
currentSketchPath = await this.fileService.fsPath(
|
||||||
|
new URI(currentSketch.uri)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const { clangdUri, cliUri, lsUri } = await this.executableService.list();
|
const { clangdUri, lsUri } = await this.executableService.list();
|
||||||
const [clangdPath, cliPath, lsPath] = await Promise.all([
|
const [clangdPath, lsPath] = await Promise.all([
|
||||||
this.fileSystem.fsPath(new URI(clangdUri)),
|
this.fileService.fsPath(new URI(clangdUri)),
|
||||||
this.fileSystem.fsPath(new URI(cliUri)),
|
this.fileService.fsPath(new URI(lsUri)),
|
||||||
this.fileSystem.fsPath(new URI(lsUri)),
|
|
||||||
]);
|
]);
|
||||||
this.commandRegistry.executeCommand('arduino.languageserver.start', {
|
|
||||||
|
const config = await this.configService.getConfiguration();
|
||||||
|
|
||||||
|
this.languageServerFqbn = await Promise.race([
|
||||||
|
new Promise<undefined>((_, reject) =>
|
||||||
|
setTimeout(
|
||||||
|
() => reject(new Error(`Timeout after ${20_000} ms.`)),
|
||||||
|
20_000
|
||||||
|
)
|
||||||
|
),
|
||||||
|
this.commandRegistry.executeCommand<string>(
|
||||||
|
'arduino.languageserver.start',
|
||||||
|
{
|
||||||
lsPath,
|
lsPath,
|
||||||
cliPath,
|
cliDaemonAddr: `localhost:${config.daemon.port}`, // TODO: verify if this port is coming from the BE
|
||||||
clangdPath,
|
clangdPath,
|
||||||
log: currentSketchPath ? currentSketchPath : log,
|
log: currentSketchPath ? currentSketchPath : log,
|
||||||
|
cliDaemonInstance: '1',
|
||||||
board: {
|
board: {
|
||||||
fqbn,
|
fqbn,
|
||||||
name: name ? `"${name}"` : undefined
|
name: name ? `"${name}"` : undefined,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
),
|
||||||
|
]);
|
||||||
|
} catch (e) {
|
||||||
|
console.log(`Failed to start language server for ${fqbn}`, e);
|
||||||
|
this.languageServerFqbn = undefined;
|
||||||
|
} finally {
|
||||||
|
release();
|
||||||
}
|
}
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
registerToolbarItems(registry: TabBarToolbarRegistry): void {
|
registerToolbarItems(registry: TabBarToolbarRegistry): void {
|
||||||
registry.registerItem({
|
registry.registerItem({
|
||||||
id: BoardsToolBarItem.TOOLBAR_ID,
|
id: BoardsToolBarItem.TOOLBAR_ID,
|
||||||
render: () => <BoardsToolBarItem
|
render: () => (
|
||||||
key='boardsToolbarItem'
|
<BoardsToolBarItem
|
||||||
|
key="boardsToolbarItem"
|
||||||
commands={this.commandRegistry}
|
commands={this.commandRegistry}
|
||||||
boardsServiceClient={this.boardsServiceClientImpl} />,
|
boardsServiceClient={this.boardsServiceClientImpl}
|
||||||
isVisible: widget => ArduinoToolbar.is(widget) && widget.side === 'left',
|
/>
|
||||||
priority: 7
|
),
|
||||||
|
isVisible: (widget) =>
|
||||||
|
ArduinoToolbar.is(widget) && widget.side === 'left',
|
||||||
|
priority: 7,
|
||||||
});
|
});
|
||||||
registry.registerItem({
|
registry.registerItem({
|
||||||
id: 'toggle-serial-monitor',
|
id: 'toggle-serial-monitor',
|
||||||
command: MonitorViewContribution.TOGGLE_SERIAL_MONITOR_TOOLBAR,
|
command: MonitorViewContribution.TOGGLE_SERIAL_MONITOR_TOOLBAR,
|
||||||
tooltip: 'Serial Monitor'
|
tooltip: nls.localize('arduino/common/serialMonitor', 'Serial Monitor'),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
registerCommands(registry: CommandRegistry): void {
|
registerCommands(registry: CommandRegistry): void {
|
||||||
registry.registerCommand(ArduinoCommands.TOGGLE_COMPILE_FOR_DEBUG, {
|
registry.registerCommand(ArduinoCommands.TOGGLE_COMPILE_FOR_DEBUG, {
|
||||||
execute: () => this.editorMode.toggleCompileForDebug(),
|
execute: () => this.editorMode.toggleCompileForDebug(),
|
||||||
isToggled: () => this.editorMode.compileForDebug
|
isToggled: () => this.editorMode.compileForDebug,
|
||||||
});
|
});
|
||||||
registry.registerCommand(ArduinoCommands.OPEN_SKETCH_FILES, {
|
registry.registerCommand(ArduinoCommands.OPEN_SKETCH_FILES, {
|
||||||
execute: async (uri: URI) => {
|
execute: async (uri: URI) => {
|
||||||
this.openSketchFiles(uri);
|
this.openSketchFiles(uri);
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
registry.registerCommand(ArduinoCommands.OPEN_BOARDS_DIALOG, {
|
registry.registerCommand(ArduinoCommands.OPEN_BOARDS_DIALOG, {
|
||||||
execute: async (query?: string | undefined) => {
|
execute: async (query?: string | undefined) => {
|
||||||
@@ -287,7 +467,7 @@ export class ArduinoFrontendContribution implements FrontendApplicationContribut
|
|||||||
if (boardsConfig) {
|
if (boardsConfig) {
|
||||||
this.boardsServiceClientImpl.boardsConfig = boardsConfig;
|
this.boardsServiceClientImpl.boardsConfig = boardsConfig;
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -296,18 +476,27 @@ export class ArduinoFrontendContribution implements FrontendApplicationContribut
|
|||||||
const index = menuPath.length - 1;
|
const index = menuPath.length - 1;
|
||||||
const menuId = menuPath[index];
|
const menuId = menuPath[index];
|
||||||
return menuId;
|
return menuId;
|
||||||
}
|
};
|
||||||
registry.getMenu(MAIN_MENU_BAR).removeNode(menuId(MonacoMenus.SELECTION));
|
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(EditorMainMenu.GO));
|
||||||
registry.getMenu(MAIN_MENU_BAR).removeNode(menuId(TerminalMenus.TERMINAL));
|
registry.getMenu(MAIN_MENU_BAR).removeNode(menuId(TerminalMenus.TERMINAL));
|
||||||
registry.getMenu(MAIN_MENU_BAR).removeNode(menuId(CommonMenus.VIEW));
|
registry.getMenu(MAIN_MENU_BAR).removeNode(menuId(CommonMenus.VIEW));
|
||||||
|
|
||||||
registry.registerSubmenu(ArduinoMenus.SKETCH, 'Sketch');
|
registry.registerSubmenu(
|
||||||
registry.registerSubmenu(ArduinoMenus.TOOLS, 'Tools');
|
ArduinoMenus.SKETCH,
|
||||||
|
nls.localize('arduino/menu/sketch', 'Sketch')
|
||||||
|
);
|
||||||
|
registry.registerSubmenu(
|
||||||
|
ArduinoMenus.TOOLS,
|
||||||
|
nls.localize('arduino/menu/tools', 'Tools')
|
||||||
|
);
|
||||||
registry.registerMenuAction(ArduinoMenus.SKETCH__MAIN_GROUP, {
|
registry.registerMenuAction(ArduinoMenus.SKETCH__MAIN_GROUP, {
|
||||||
commandId: ArduinoCommands.TOGGLE_COMPILE_FOR_DEBUG.id,
|
commandId: ArduinoCommands.TOGGLE_COMPILE_FOR_DEBUG.id,
|
||||||
label: 'Optimize for Debugging',
|
label: nls.localize(
|
||||||
order: '4'
|
'arduino/debug/optimizeForDebugging',
|
||||||
|
'Optimize for Debugging'
|
||||||
|
),
|
||||||
|
order: '5',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -318,12 +507,25 @@ export class ArduinoFrontendContribution implements FrontendApplicationContribut
|
|||||||
for (const uri of [mainFileUri, ...rootFolderFileUris]) {
|
for (const uri of [mainFileUri, ...rootFolderFileUris]) {
|
||||||
await this.ensureOpened(uri);
|
await this.ensureOpened(uri);
|
||||||
}
|
}
|
||||||
await this.ensureOpened(mainFileUri, true);
|
|
||||||
if (mainFileUri.endsWith('.pde')) {
|
if (mainFileUri.endsWith('.pde')) {
|
||||||
const message = `The '${sketch.name}' still uses the old \`.pde\` format. Do you want to switch to the new \`.ino\` extension?`;
|
const message = nls.localize(
|
||||||
this.messageService.info(message, 'Later', 'Yes').then(async answer => {
|
'arduino/common/oldFormat',
|
||||||
if (answer === 'Yes') {
|
"The '{0}' still uses the old `.pde` format. Do you want to switch to the new `.ino` extension?",
|
||||||
this.commandRegistry.executeCommand(SaveAsSketch.Commands.SAVE_AS_SKETCH.id, { execOnlyIfTemp: false, openAfterMove: true, wipeOriginal: false });
|
sketch.name
|
||||||
|
);
|
||||||
|
const yes = nls.localize('vscode/extensionsUtils/yes', 'Yes');
|
||||||
|
this.messageService
|
||||||
|
.info(message, nls.localize('arduino/common/later', 'Later'), yes)
|
||||||
|
.then(async (answer) => {
|
||||||
|
if (answer === yes) {
|
||||||
|
this.commandRegistry.executeCommand(
|
||||||
|
SaveAsSketch.Commands.SAVE_AS_SKETCH.id,
|
||||||
|
{
|
||||||
|
execOnlyIfTemp: false,
|
||||||
|
openAfterMove: true,
|
||||||
|
wipeOriginal: false,
|
||||||
|
}
|
||||||
|
);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -334,10 +536,16 @@ export class ArduinoFrontendContribution implements FrontendApplicationContribut
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected async ensureOpened(uri: string, forceOpen: boolean = false): Promise<any> {
|
protected async ensureOpened(
|
||||||
const widget = this.editorManager.all.find(widget => widget.editor.uri.toString() === uri);
|
uri: string,
|
||||||
|
forceOpen = false,
|
||||||
|
options?: EditorOpenerOptions | undefined
|
||||||
|
): Promise<any> {
|
||||||
|
const widget = this.editorManager.all.find(
|
||||||
|
(widget) => widget.editor.uri.toString() === uri
|
||||||
|
);
|
||||||
if (!widget || forceOpen) {
|
if (!widget || forceOpen) {
|
||||||
return this.editorManager.open(new URI(uri));
|
return this.editorManager.open(new URI(uri), options);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -347,64 +555,78 @@ export class ArduinoFrontendContribution implements FrontendApplicationContribut
|
|||||||
id: 'arduino.branding.primary',
|
id: 'arduino.branding.primary',
|
||||||
defaults: {
|
defaults: {
|
||||||
dark: 'statusBar.background',
|
dark: 'statusBar.background',
|
||||||
light: 'statusBar.background'
|
light: 'statusBar.background',
|
||||||
},
|
},
|
||||||
description: 'The primary branding color, such as dialog titles, library, and board manager list labels.'
|
description:
|
||||||
|
'The primary branding color, such as dialog titles, library, and board manager list labels.',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 'arduino.branding.secondary',
|
id: 'arduino.branding.secondary',
|
||||||
defaults: {
|
defaults: {
|
||||||
dark: 'statusBar.background',
|
dark: 'statusBar.background',
|
||||||
light: 'statusBar.background'
|
light: 'statusBar.background',
|
||||||
},
|
},
|
||||||
description: 'Secondary branding color for list selections, dropdowns, and widget borders.'
|
description:
|
||||||
|
'Secondary branding color for list selections, dropdowns, and widget borders.',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 'arduino.foreground',
|
id: 'arduino.foreground',
|
||||||
defaults: {
|
defaults: {
|
||||||
dark: 'editorWidget.background',
|
dark: 'editorWidget.background',
|
||||||
light: 'editorWidget.background',
|
light: 'editorWidget.background',
|
||||||
hc: 'editorWidget.background'
|
hc: 'editorWidget.background',
|
||||||
},
|
},
|
||||||
description: 'Color of the Arduino IDE foreground which is used for dialogs, such as the Select Board dialog.'
|
description:
|
||||||
|
'Color of the Arduino IDE foreground which is used for dialogs, such as the Select Board dialog.',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 'arduino.toolbar.background',
|
id: 'arduino.toolbar.background',
|
||||||
defaults: {
|
defaults: {
|
||||||
dark: 'button.background',
|
dark: 'button.background',
|
||||||
light: 'button.background',
|
light: 'button.background',
|
||||||
hc: 'activityBar.inactiveForeground'
|
hc: 'activityBar.inactiveForeground',
|
||||||
},
|
},
|
||||||
description: 'Background color of the toolbar items. Such as Upload, Verify, etc.'
|
description:
|
||||||
|
'Background color of the toolbar items. Such as Upload, Verify, etc.',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 'arduino.toolbar.hoverBackground',
|
id: 'arduino.toolbar.hoverBackground',
|
||||||
defaults: {
|
defaults: {
|
||||||
dark: 'button.hoverBackground',
|
dark: 'button.hoverBackground',
|
||||||
light: 'button.hoverBackground',
|
light: 'button.foreground',
|
||||||
hc: 'activityBar.inactiveForeground'
|
hc: 'textLink.foreground',
|
||||||
},
|
},
|
||||||
description: 'Background color of the toolbar items when hovering over them. Such as Upload, Verify, etc.'
|
description:
|
||||||
|
'Background color of the toolbar items when hovering over them. Such as Upload, Verify, etc.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'arduino.toolbar.toggleBackground',
|
||||||
|
defaults: {
|
||||||
|
dark: 'editor.selectionBackground',
|
||||||
|
light: 'editor.selectionBackground',
|
||||||
|
hc: 'textPreformat.foreground',
|
||||||
|
},
|
||||||
|
description:
|
||||||
|
'Toggle color of the toolbar items when they are currently toggled (the command is in progress)',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 'arduino.output.foreground',
|
id: 'arduino.output.foreground',
|
||||||
defaults: {
|
defaults: {
|
||||||
dark: 'editor.foreground',
|
dark: 'editor.foreground',
|
||||||
light: 'editor.foreground',
|
light: 'editor.foreground',
|
||||||
hc: 'editor.foreground'
|
hc: 'editor.foreground',
|
||||||
},
|
},
|
||||||
description: 'Color of the text in the Output view.'
|
description: 'Color of the text in the Output view.',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 'arduino.output.background',
|
id: 'arduino.output.background',
|
||||||
defaults: {
|
defaults: {
|
||||||
dark: 'editor.background',
|
dark: 'editor.background',
|
||||||
light: 'editor.background',
|
light: 'editor.background',
|
||||||
hc: 'editor.background'
|
hc: 'editor.background',
|
||||||
},
|
},
|
||||||
description: 'Background color of the Output view.'
|
description: 'Background color of the Output view.',
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,14 +3,29 @@ import { ContainerModule } from 'inversify';
|
|||||||
import { WidgetFactory } from '@theia/core/lib/browser/widget-manager';
|
import { WidgetFactory } from '@theia/core/lib/browser/widget-manager';
|
||||||
import { CommandContribution } from '@theia/core/lib/common/command';
|
import { CommandContribution } from '@theia/core/lib/common/command';
|
||||||
import { bindViewContribution } from '@theia/core/lib/browser/shell/view-contribution';
|
import { bindViewContribution } from '@theia/core/lib/browser/shell/view-contribution';
|
||||||
import { TabBarToolbarContribution, TabBarToolbarFactory } from '@theia/core/lib/browser/shell/tab-bar-toolbar';
|
import {
|
||||||
|
TabBarToolbarContribution,
|
||||||
|
TabBarToolbarFactory,
|
||||||
|
} from '@theia/core/lib/browser/shell/tab-bar-toolbar';
|
||||||
import { WebSocketConnectionProvider } from '@theia/core/lib/browser/messaging/ws-connection-provider';
|
import { WebSocketConnectionProvider } from '@theia/core/lib/browser/messaging/ws-connection-provider';
|
||||||
import { FrontendApplicationContribution, FrontendApplication as TheiaFrontendApplication } from '@theia/core/lib/browser/frontend-application'
|
import {
|
||||||
|
FrontendApplicationContribution,
|
||||||
|
FrontendApplication as TheiaFrontendApplication,
|
||||||
|
} from '@theia/core/lib/browser/frontend-application';
|
||||||
import { LibraryListWidget } from './library/library-list-widget';
|
import { LibraryListWidget } from './library/library-list-widget';
|
||||||
import { ArduinoFrontendContribution } from './arduino-frontend-contribution';
|
import { ArduinoFrontendContribution } from './arduino-frontend-contribution';
|
||||||
import { LibraryService, LibraryServicePath } from '../common/protocol/library-service';
|
import {
|
||||||
import { BoardsService, BoardsServicePath } from '../common/protocol/boards-service';
|
LibraryService,
|
||||||
import { SketchesService, SketchesServicePath } from '../common/protocol/sketches-service';
|
LibraryServicePath,
|
||||||
|
} from '../common/protocol/library-service';
|
||||||
|
import {
|
||||||
|
BoardsService,
|
||||||
|
BoardsServicePath,
|
||||||
|
} from '../common/protocol/boards-service';
|
||||||
|
import {
|
||||||
|
SketchesService,
|
||||||
|
SketchesServicePath,
|
||||||
|
} from '../common/protocol/sketches-service';
|
||||||
import { SketchesServiceClientImpl } from '../common/protocol/sketches-service-client-impl';
|
import { SketchesServiceClientImpl } from '../common/protocol/sketches-service-client-impl';
|
||||||
import { CoreService, CoreServicePath } from '../common/protocol/core-service';
|
import { CoreService, CoreServicePath } from '../common/protocol/core-service';
|
||||||
import { BoardsListWidget } from './boards/boards-list-widget';
|
import { BoardsListWidget } from './boards/boards-list-widget';
|
||||||
@@ -24,9 +39,11 @@ import { ProblemContribution as TheiaProblemContribution } from '@theia/markers/
|
|||||||
import { ProblemContribution } from './theia/markers/problem-contribution';
|
import { ProblemContribution } from './theia/markers/problem-contribution';
|
||||||
import { FileNavigatorContribution } from './theia/navigator/navigator-contribution';
|
import { FileNavigatorContribution } from './theia/navigator/navigator-contribution';
|
||||||
import { FileNavigatorContribution as TheiaFileNavigatorContribution } from '@theia/navigator/lib/browser/navigator-contribution';
|
import { FileNavigatorContribution as TheiaFileNavigatorContribution } from '@theia/navigator/lib/browser/navigator-contribution';
|
||||||
|
import { KeymapsFrontendContribution } from './theia/keymaps/keymaps-frontend-contribution';
|
||||||
|
import { KeymapsFrontendContribution as TheiaKeymapsFrontendContribution } from '@theia/keymaps/lib/browser/keymaps-frontend-contribution';
|
||||||
import { ArduinoToolbarContribution } from './toolbar/arduino-toolbar-contribution';
|
import { ArduinoToolbarContribution } from './toolbar/arduino-toolbar-contribution';
|
||||||
import { EditorContribution as TheiaEditorContribution } from '@theia/editor/lib/browser/editor-contribution';
|
import { EditorPreviewContribution as TheiaEditorPreviewContribution } from '@theia/editor-preview/lib/browser/editor-preview-contribution';
|
||||||
import { EditorContribution } from './theia/editor/editor-contribution';
|
import { EditorPreviewContribution } from './theia/editor/editor-contribution';
|
||||||
import { MonacoStatusBarContribution as TheiaMonacoStatusBarContribution } from '@theia/monaco/lib/browser/monaco-status-bar-contribution';
|
import { MonacoStatusBarContribution as TheiaMonacoStatusBarContribution } from '@theia/monaco/lib/browser/monaco-status-bar-contribution';
|
||||||
import { MonacoStatusBarContribution } from './theia/monaco/monaco-status-bar-contribution';
|
import { MonacoStatusBarContribution } from './theia/monaco/monaco-status-bar-contribution';
|
||||||
import {
|
import {
|
||||||
@@ -35,25 +52,37 @@ import {
|
|||||||
CommonFrontendContribution as TheiaCommonFrontendContribution,
|
CommonFrontendContribution as TheiaCommonFrontendContribution,
|
||||||
KeybindingRegistry as TheiaKeybindingRegistry,
|
KeybindingRegistry as TheiaKeybindingRegistry,
|
||||||
TabBarRendererFactory,
|
TabBarRendererFactory,
|
||||||
ContextMenuRenderer
|
ContextMenuRenderer,
|
||||||
|
createTreeContainer,
|
||||||
|
TreeWidget,
|
||||||
} from '@theia/core/lib/browser';
|
} from '@theia/core/lib/browser';
|
||||||
import { MenuContribution } from '@theia/core/lib/common/menu';
|
import { MenuContribution } from '@theia/core/lib/common/menu';
|
||||||
import { ApplicationShell } from './theia/core/application-shell';
|
import { ApplicationShell } from './theia/core/application-shell';
|
||||||
import { FrontendApplication } from './theia/core/frontend-application';
|
import { FrontendApplication } from './theia/core/frontend-application';
|
||||||
import { BoardsConfigDialog, BoardsConfigDialogProps } from './boards/boards-config-dialog';
|
import {
|
||||||
|
BoardsConfigDialog,
|
||||||
|
BoardsConfigDialogProps,
|
||||||
|
} from './boards/boards-config-dialog';
|
||||||
import { BoardsConfigDialogWidget } from './boards/boards-config-dialog-widget';
|
import { BoardsConfigDialogWidget } from './boards/boards-config-dialog-widget';
|
||||||
import { ScmContribution as TheiaScmContribution } from '@theia/scm/lib/browser/scm-contribution';
|
import { ScmContribution as TheiaScmContribution } from '@theia/scm/lib/browser/scm-contribution';
|
||||||
import { ScmContribution } from './theia/scm/scm-contribution';
|
import { ScmContribution } from './theia/scm/scm-contribution';
|
||||||
import { SearchInWorkspaceFrontendContribution as TheiaSearchInWorkspaceFrontendContribution } from '@theia/search-in-workspace/lib/browser/search-in-workspace-frontend-contribution';
|
import { SearchInWorkspaceFrontendContribution as TheiaSearchInWorkspaceFrontendContribution } from '@theia/search-in-workspace/lib/browser/search-in-workspace-frontend-contribution';
|
||||||
import { SearchInWorkspaceFrontendContribution } from './theia/search-in-workspace/search-in-workspace-frontend-contribution';
|
import { SearchInWorkspaceFrontendContribution } from './theia/search-in-workspace/search-in-workspace-frontend-contribution';
|
||||||
import { LibraryListWidgetFrontendContribution } from './library/library-widget-frontend-contribution';
|
import { LibraryListWidgetFrontendContribution } from './library/library-widget-frontend-contribution';
|
||||||
import { MonitorServiceClientImpl } from './monitor/monitor-service-client-impl';
|
import { SerialServiceClientImpl } from './serial/serial-service-client-impl';
|
||||||
import { MonitorServicePath, MonitorService, MonitorServiceClient } from '../common/protocol/monitor-service';
|
import {
|
||||||
import { ConfigService, ConfigServicePath } from '../common/protocol/config-service';
|
SerialServicePath,
|
||||||
import { MonitorWidget } from './monitor/monitor-widget';
|
SerialService,
|
||||||
import { MonitorViewContribution } from './monitor/monitor-view-contribution';
|
SerialServiceClient,
|
||||||
import { MonitorConnection } from './monitor/monitor-connection';
|
} from '../common/protocol/serial-service';
|
||||||
import { MonitorModel } from './monitor/monitor-model';
|
import {
|
||||||
|
ConfigService,
|
||||||
|
ConfigServicePath,
|
||||||
|
} from '../common/protocol/config-service';
|
||||||
|
import { MonitorWidget } from './serial/monitor/monitor-widget';
|
||||||
|
import { MonitorViewContribution } from './serial/monitor/monitor-view-contribution';
|
||||||
|
import { SerialConnectionManager } from './serial/serial-connection-manager';
|
||||||
|
import { SerialModel } from './serial/serial-model';
|
||||||
import { TabBarDecoratorService as TheiaTabBarDecoratorService } from '@theia/core/lib/browser/shell/tab-bar-decorator';
|
import { TabBarDecoratorService as TheiaTabBarDecoratorService } from '@theia/core/lib/browser/shell/tab-bar-decorator';
|
||||||
import { TabBarDecoratorService } from './theia/core/tab-bar-decorator';
|
import { TabBarDecoratorService } from './theia/core/tab-bar-decorator';
|
||||||
import { ProblemManager as TheiaProblemManager } from '@theia/markers/lib/browser';
|
import { ProblemManager as TheiaProblemManager } from '@theia/markers/lib/browser';
|
||||||
@@ -64,24 +93,35 @@ import { EditorMode } from './editor-mode';
|
|||||||
import { ListItemRenderer } from './widgets/component-list/list-item-renderer';
|
import { ListItemRenderer } from './widgets/component-list/list-item-renderer';
|
||||||
import { ColorContribution } from '@theia/core/lib/browser/color-application-contribution';
|
import { ColorContribution } from '@theia/core/lib/browser/color-application-contribution';
|
||||||
import { MonacoThemingService } from '@theia/monaco/lib/browser/monaco-theming-service';
|
import { MonacoThemingService } from '@theia/monaco/lib/browser/monaco-theming-service';
|
||||||
import { ArduinoDaemonPath, ArduinoDaemon } from '../common/protocol/arduino-daemon';
|
import {
|
||||||
import { EditorManager as TheiaEditorManager, EditorCommandContribution as TheiaEditorCommandContribution } from '@theia/editor/lib/browser';
|
ArduinoDaemonPath,
|
||||||
import { EditorManager } from './theia/editor/editor-manager';
|
ArduinoDaemon,
|
||||||
import { FrontendConnectionStatusService, ApplicationConnectionStatusContribution } from './theia/core/connection-status-service';
|
} from '../common/protocol/arduino-daemon';
|
||||||
|
import { EditorCommandContribution as TheiaEditorCommandContribution } from '@theia/editor/lib/browser';
|
||||||
|
import {
|
||||||
|
FrontendConnectionStatusService,
|
||||||
|
ApplicationConnectionStatusContribution,
|
||||||
|
} from './theia/core/connection-status-service';
|
||||||
import {
|
import {
|
||||||
FrontendConnectionStatusService as TheiaFrontendConnectionStatusService,
|
FrontendConnectionStatusService as TheiaFrontendConnectionStatusService,
|
||||||
ApplicationConnectionStatusContribution as TheiaApplicationConnectionStatusContribution
|
ApplicationConnectionStatusContribution as TheiaApplicationConnectionStatusContribution,
|
||||||
} from '@theia/core/lib/browser/connection-status-service';
|
} from '@theia/core/lib/browser/connection-status-service';
|
||||||
import { BoardsDataMenuUpdater } from './boards/boards-data-menu-updater';
|
import { BoardsDataMenuUpdater } from './boards/boards-data-menu-updater';
|
||||||
import { BoardsDataStore } from './boards/boards-data-store';
|
import { BoardsDataStore } from './boards/boards-data-store';
|
||||||
import { ILogger } from '@theia/core';
|
import { ILogger } from '@theia/core';
|
||||||
import { FileSystemExt, FileSystemExtPath } from '../common/protocol/filesystem-ext';
|
import {
|
||||||
|
FileSystemExt,
|
||||||
|
FileSystemExtPath,
|
||||||
|
} from '../common/protocol/filesystem-ext';
|
||||||
import {
|
import {
|
||||||
WorkspaceFrontendContribution as TheiaWorkspaceFrontendContribution,
|
WorkspaceFrontendContribution as TheiaWorkspaceFrontendContribution,
|
||||||
FileMenuContribution as TheiaFileMenuContribution,
|
FileMenuContribution as TheiaFileMenuContribution,
|
||||||
WorkspaceCommandContribution as TheiaWorkspaceCommandContribution
|
WorkspaceCommandContribution as TheiaWorkspaceCommandContribution,
|
||||||
} from '@theia/workspace/lib/browser';
|
} from '@theia/workspace/lib/browser';
|
||||||
import { WorkspaceFrontendContribution, ArduinoFileMenuContribution } from './theia/workspace/workspace-frontend-contribution';
|
import {
|
||||||
|
WorkspaceFrontendContribution,
|
||||||
|
ArduinoFileMenuContribution,
|
||||||
|
} from './theia/workspace/workspace-frontend-contribution';
|
||||||
import { Contribution } from './contributions/contribution';
|
import { Contribution } from './contributions/contribution';
|
||||||
import { NewSketch } from './contributions/new-sketch';
|
import { NewSketch } from './contributions/new-sketch';
|
||||||
import { OpenSketch } from './contributions/open-sketch';
|
import { OpenSketch } from './contributions/open-sketch';
|
||||||
@@ -108,19 +148,32 @@ import { EditorWidgetFactory } from './theia/editor/editor-widget-factory';
|
|||||||
import { OutputWidget as TheiaOutputWidget } from '@theia/output/lib/browser/output-widget';
|
import { OutputWidget as TheiaOutputWidget } from '@theia/output/lib/browser/output-widget';
|
||||||
import { OutputWidget } from './theia/output/output-widget';
|
import { OutputWidget } from './theia/output/output-widget';
|
||||||
import { BurnBootloader } from './contributions/burn-bootloader';
|
import { BurnBootloader } from './contributions/burn-bootloader';
|
||||||
import { ExamplesServicePath, ExamplesService } from '../common/protocol/examples-service';
|
import {
|
||||||
|
ExamplesServicePath,
|
||||||
|
ExamplesService,
|
||||||
|
} from '../common/protocol/examples-service';
|
||||||
import { BuiltInExamples, LibraryExamples } from './contributions/examples';
|
import { BuiltInExamples, LibraryExamples } from './contributions/examples';
|
||||||
import { IncludeLibrary } from './contributions/include-library';
|
import { IncludeLibrary } from './contributions/include-library';
|
||||||
import { OutputChannelManager as TheiaOutputChannelManager } from '@theia/output/lib/common/output-channel';
|
import { OutputChannelManager as TheiaOutputChannelManager } from '@theia/output/lib/browser/output-channel';
|
||||||
import { OutputChannelManager } from './theia/output/output-channel';
|
import { OutputChannelManager } from './theia/output/output-channel';
|
||||||
import { OutputChannelRegistryMainImpl as TheiaOutputChannelRegistryMainImpl, OutputChannelRegistryMainImpl } from './theia/plugin-ext/output-channel-registry-main';
|
import {
|
||||||
|
OutputChannelRegistryMainImpl as TheiaOutputChannelRegistryMainImpl,
|
||||||
|
OutputChannelRegistryMainImpl,
|
||||||
|
} from './theia/plugin-ext/output-channel-registry-main';
|
||||||
import { ExecutableService, ExecutableServicePath } from '../common/protocol';
|
import { ExecutableService, ExecutableServicePath } from '../common/protocol';
|
||||||
import { MonacoTextModelService as TheiaMonacoTextModelService } from '@theia/monaco/lib/browser/monaco-text-model-service';
|
import { MonacoTextModelService as TheiaMonacoTextModelService } from '@theia/monaco/lib/browser/monaco-text-model-service';
|
||||||
import { MonacoTextModelService } from './theia/monaco/monaco-text-model-service';
|
import { MonacoTextModelService } from './theia/monaco/monaco-text-model-service';
|
||||||
import { OutputServiceImpl } from './output-service-impl';
|
import { ResponseServiceImpl } from './response-service-impl';
|
||||||
import { OutputServicePath, OutputService } from '../common/protocol/output-service';
|
import {
|
||||||
|
ResponseService,
|
||||||
|
ResponseServiceArduino,
|
||||||
|
ResponseServicePath,
|
||||||
|
} from '../common/protocol/response-service';
|
||||||
import { NotificationCenter } from './notification-center';
|
import { NotificationCenter } from './notification-center';
|
||||||
import { NotificationServicePath, NotificationServiceServer } from '../common/protocol';
|
import {
|
||||||
|
NotificationServicePath,
|
||||||
|
NotificationServiceServer,
|
||||||
|
} from '../common/protocol';
|
||||||
import { About } from './contributions/about';
|
import { About } from './contributions/about';
|
||||||
import { IconThemeService } from '@theia/core/lib/browser/icon-theme-service';
|
import { IconThemeService } from '@theia/core/lib/browser/icon-theme-service';
|
||||||
import { TabBarRenderer } from './theia/core/tab-bars';
|
import { TabBarRenderer } from './theia/core/tab-bars';
|
||||||
@@ -136,12 +189,92 @@ import { DebugFrontendApplicationContribution as TheiaDebugFrontendApplicationCo
|
|||||||
import { BoardSelection } from './contributions/board-selection';
|
import { BoardSelection } from './contributions/board-selection';
|
||||||
import { OpenRecentSketch } from './contributions/open-recent-sketch';
|
import { OpenRecentSketch } from './contributions/open-recent-sketch';
|
||||||
import { Help } from './contributions/help';
|
import { Help } from './contributions/help';
|
||||||
import { bindArduinoPreferences } from './arduino-preferences'
|
import { bindArduinoPreferences } from './arduino-preferences';
|
||||||
import { SettingsService, SettingsDialog, SettingsWidget, SettingsDialogProps } from './settings';
|
import { SettingsService } from './dialogs/settings/settings';
|
||||||
|
import {
|
||||||
|
SettingsDialog,
|
||||||
|
SettingsWidget,
|
||||||
|
SettingsDialogProps,
|
||||||
|
} from './dialogs/settings/settings-dialog';
|
||||||
import { AddFile } from './contributions/add-file';
|
import { AddFile } from './contributions/add-file';
|
||||||
import { ArchiveSketch } from './contributions/archive-sketch';
|
import { ArchiveSketch } from './contributions/archive-sketch';
|
||||||
import { OutputToolbarContribution as TheiaOutputToolbarContribution } from '@theia/output/lib/browser/output-toolbar-contribution';
|
import { OutputToolbarContribution as TheiaOutputToolbarContribution } from '@theia/output/lib/browser/output-toolbar-contribution';
|
||||||
import { OutputToolbarContribution } from './theia/output/output-toolbar-contribution';
|
import { OutputToolbarContribution } from './theia/output/output-toolbar-contribution';
|
||||||
|
import { AddZipLibrary } from './contributions/add-zip-library';
|
||||||
|
import { WorkspaceVariableContribution as TheiaWorkspaceVariableContribution } from '@theia/workspace/lib/browser/workspace-variable-contribution';
|
||||||
|
import { WorkspaceVariableContribution } from './theia/workspace/workspace-variable-contribution';
|
||||||
|
import { DebugConfigurationManager } from './theia/debug/debug-configuration-manager';
|
||||||
|
import { DebugConfigurationManager as TheiaDebugConfigurationManager } from '@theia/debug/lib/browser/debug-configuration-manager';
|
||||||
|
import { SearchInWorkspaceWidget as TheiaSearchInWorkspaceWidget } from '@theia/search-in-workspace/lib/browser/search-in-workspace-widget';
|
||||||
|
import { SearchInWorkspaceWidget } from './theia/search-in-workspace/search-in-workspace-widget';
|
||||||
|
import { SearchInWorkspaceFactory as TheiaSearchInWorkspaceFactory } from '@theia/search-in-workspace/lib/browser/search-in-workspace-factory';
|
||||||
|
import { SearchInWorkspaceFactory } from './theia/search-in-workspace/search-in-workspace-factory';
|
||||||
|
import { SearchInWorkspaceResultTreeWidget as TheiaSearchInWorkspaceResultTreeWidget } from '@theia/search-in-workspace/lib/browser/search-in-workspace-result-tree-widget';
|
||||||
|
import { SearchInWorkspaceResultTreeWidget } from './theia/search-in-workspace/search-in-workspace-result-tree-widget';
|
||||||
|
import { MonacoEditorProvider } from './theia/monaco/monaco-editor-provider';
|
||||||
|
import { MonacoEditorProvider as TheiaMonacoEditorProvider } from '@theia/monaco/lib/browser/monaco-editor-provider';
|
||||||
|
import { StorageWrapper } from './storage-wrapper';
|
||||||
|
import { NotificationManager } from './theia/messages/notifications-manager';
|
||||||
|
import { NotificationManager as TheiaNotificationManager } from '@theia/messages/lib/browser/notifications-manager';
|
||||||
|
import { NotificationsRenderer as TheiaNotificationsRenderer } from '@theia/messages/lib/browser/notifications-renderer';
|
||||||
|
import { NotificationsRenderer } from './theia/messages/notifications-renderer';
|
||||||
|
import { SketchbookWidgetContribution } from './widgets/sketchbook/sketchbook-widget-contribution';
|
||||||
|
import { LocalCacheFsProvider } from './local-cache/local-cache-fs-provider';
|
||||||
|
import { CloudSketchbookWidget } from './widgets/cloud-sketchbook/cloud-sketchbook-widget';
|
||||||
|
import { CloudSketchbookTreeWidget } from './widgets/cloud-sketchbook/cloud-sketchbook-tree-widget';
|
||||||
|
import { createCloudSketchbookTreeWidget } from './widgets/cloud-sketchbook/cloud-sketchbook-tree-container';
|
||||||
|
import { CreateApi } from './create/create-api';
|
||||||
|
import { ShareSketchDialog } from './dialogs/cloud-share-sketch-dialog';
|
||||||
|
import { AuthenticationClientService } from './auth/authentication-client-service';
|
||||||
|
import {
|
||||||
|
AuthenticationService,
|
||||||
|
AuthenticationServicePath,
|
||||||
|
} from '../common/protocol/authentication-service';
|
||||||
|
import { CreateFsProvider } from './create/create-fs-provider';
|
||||||
|
import { FileServiceContribution } from '@theia/filesystem/lib/browser/file-service';
|
||||||
|
import { CloudSketchbookContribution } from './widgets/cloud-sketchbook/cloud-sketchbook-contributions';
|
||||||
|
import { CloudSketchbookCompositeWidget } from './widgets/cloud-sketchbook/cloud-sketchbook-composite-widget';
|
||||||
|
import { SketchbookWidget } from './widgets/sketchbook/sketchbook-widget';
|
||||||
|
import { SketchbookTreeWidget } from './widgets/sketchbook/sketchbook-tree-widget';
|
||||||
|
import { createSketchbookTreeWidget } from './widgets/sketchbook/sketchbook-tree-container';
|
||||||
|
import { SketchCache } from './widgets/cloud-sketchbook/cloud-sketch-cache';
|
||||||
|
import { UploadFirmware } from './contributions/upload-firmware';
|
||||||
|
import {
|
||||||
|
UploadFirmwareDialog,
|
||||||
|
UploadFirmwareDialogProps,
|
||||||
|
UploadFirmwareDialogWidget,
|
||||||
|
} from './dialogs/firmware-uploader/firmware-uploader-dialog';
|
||||||
|
|
||||||
|
import { UploadCertificate } from './contributions/upload-certificate';
|
||||||
|
import {
|
||||||
|
ArduinoFirmwareUploader,
|
||||||
|
ArduinoFirmwareUploaderPath,
|
||||||
|
} from '../common/protocol/arduino-firmware-uploader';
|
||||||
|
import {
|
||||||
|
UploadCertificateDialog,
|
||||||
|
UploadCertificateDialogProps,
|
||||||
|
UploadCertificateDialogWidget,
|
||||||
|
} from './dialogs/certificate-uploader/certificate-uploader-dialog';
|
||||||
|
import { PlotterFrontendContribution } from './serial/plotter/plotter-frontend-contribution';
|
||||||
|
import {
|
||||||
|
UserFieldsDialog,
|
||||||
|
UserFieldsDialogProps,
|
||||||
|
UserFieldsDialogWidget,
|
||||||
|
} from './dialogs/user-fields/user-fields-dialog';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
import { IDEUpdaterCommands } from './ide-updater/ide-updater-commands';
|
||||||
|
import {
|
||||||
|
IDEUpdater,
|
||||||
|
IDEUpdaterClient,
|
||||||
|
IDEUpdaterPath,
|
||||||
|
} from '../common/protocol/ide-updater';
|
||||||
|
import { IDEUpdaterClientImpl } from './ide-updater/ide-updater-client-impl';
|
||||||
|
import {
|
||||||
|
IDEUpdaterDialog,
|
||||||
|
IDEUpdaterDialogProps,
|
||||||
|
IDEUpdaterDialogWidget,
|
||||||
|
} from './dialogs/ide-updater/ide-updater-dialog';
|
||||||
|
import { ElectronIpcConnectionProvider } from '@theia/core/lib/electron-browser/messaging/electron-ipc-connection-provider';
|
||||||
|
|
||||||
const ElementQueries = require('css-element-queries/src/ElementQueries');
|
const ElementQueries = require('css-element-queries/src/ElementQueries');
|
||||||
|
|
||||||
@@ -149,7 +282,7 @@ MonacoThemingService.register({
|
|||||||
id: 'arduino-theme',
|
id: 'arduino-theme',
|
||||||
label: 'Light (Arduino)',
|
label: 'Light (Arduino)',
|
||||||
uiTheme: 'vs',
|
uiTheme: 'vs',
|
||||||
json: require('../../src/browser/data/arduino.color-theme.json')
|
json: require('../../src/browser/data/arduino.color-theme.json'),
|
||||||
});
|
});
|
||||||
|
|
||||||
export default new ContainerModule((bind, unbind, isBound, rebind) => {
|
export default new ContainerModule((bind, unbind, isBound, rebind) => {
|
||||||
@@ -171,40 +304,75 @@ export default new ContainerModule((bind, unbind, isBound, rebind) => {
|
|||||||
bind(ListItemRenderer).toSelf().inSingletonScope();
|
bind(ListItemRenderer).toSelf().inSingletonScope();
|
||||||
|
|
||||||
// Library service
|
// Library service
|
||||||
bind(LibraryService).toDynamicValue(context => WebSocketConnectionProvider.createProxy(context.container, LibraryServicePath)).inSingletonScope();
|
bind(LibraryService)
|
||||||
|
.toDynamicValue((context) =>
|
||||||
|
WebSocketConnectionProvider.createProxy(
|
||||||
|
context.container,
|
||||||
|
LibraryServicePath
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.inSingletonScope();
|
||||||
|
|
||||||
// Library list widget
|
// Library list widget
|
||||||
bind(LibraryListWidget).toSelf();
|
bind(LibraryListWidget).toSelf();
|
||||||
bindViewContribution(bind, LibraryListWidgetFrontendContribution);
|
bindViewContribution(bind, LibraryListWidgetFrontendContribution);
|
||||||
bind(WidgetFactory).toDynamicValue(context => ({
|
bind(WidgetFactory).toDynamicValue((context) => ({
|
||||||
id: LibraryListWidget.WIDGET_ID,
|
id: LibraryListWidget.WIDGET_ID,
|
||||||
createWidget: () => context.container.get(LibraryListWidget)
|
createWidget: () => context.container.get(LibraryListWidget),
|
||||||
}));
|
}));
|
||||||
bind(FrontendApplicationContribution).toService(LibraryListWidgetFrontendContribution);
|
bind(FrontendApplicationContribution).toService(
|
||||||
|
LibraryListWidgetFrontendContribution
|
||||||
|
);
|
||||||
|
|
||||||
// Sketch list service
|
// Sketch list service
|
||||||
bind(SketchesService).toDynamicValue(context => WebSocketConnectionProvider.createProxy(context.container, SketchesServicePath)).inSingletonScope();
|
bind(SketchesService)
|
||||||
|
.toDynamicValue((context) =>
|
||||||
|
WebSocketConnectionProvider.createProxy(
|
||||||
|
context.container,
|
||||||
|
SketchesServicePath
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.inSingletonScope();
|
||||||
bind(SketchesServiceClientImpl).toSelf().inSingletonScope();
|
bind(SketchesServiceClientImpl).toSelf().inSingletonScope();
|
||||||
bind(FrontendApplicationContribution).toService(SketchesServiceClientImpl);
|
bind(FrontendApplicationContribution).toService(SketchesServiceClientImpl);
|
||||||
|
|
||||||
// Config service
|
// Config service
|
||||||
bind(ConfigService).toDynamicValue(context => WebSocketConnectionProvider.createProxy(context.container, ConfigServicePath)).inSingletonScope();
|
bind(ConfigService)
|
||||||
|
.toDynamicValue((context) =>
|
||||||
|
WebSocketConnectionProvider.createProxy(
|
||||||
|
context.container,
|
||||||
|
ConfigServicePath
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.inSingletonScope();
|
||||||
|
|
||||||
// Boards service
|
// Boards service
|
||||||
bind(BoardsService).toDynamicValue(context => WebSocketConnectionProvider.createProxy(context.container, BoardsServicePath)).inSingletonScope();
|
bind(BoardsService)
|
||||||
|
.toDynamicValue((context) =>
|
||||||
|
WebSocketConnectionProvider.createProxy(
|
||||||
|
context.container,
|
||||||
|
BoardsServicePath
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.inSingletonScope();
|
||||||
// Boards service client to receive and delegate notifications from the backend.
|
// Boards service client to receive and delegate notifications from the backend.
|
||||||
bind(BoardsServiceProvider).toSelf().inSingletonScope();
|
bind(BoardsServiceProvider).toSelf().inSingletonScope();
|
||||||
bind(FrontendApplicationContribution).toService(BoardsServiceProvider);
|
bind(FrontendApplicationContribution).toService(BoardsServiceProvider);
|
||||||
|
|
||||||
// To be able to track, and update the menu based on the core settings (aka. board details) of the currently selected board.
|
// To be able to track, and update the menu based on the core settings (aka. board details) of the currently selected board.
|
||||||
bind(FrontendApplicationContribution).to(BoardsDataMenuUpdater).inSingletonScope();
|
bind(FrontendApplicationContribution)
|
||||||
|
.to(BoardsDataMenuUpdater)
|
||||||
|
.inSingletonScope();
|
||||||
bind(BoardsDataStore).toSelf().inSingletonScope();
|
bind(BoardsDataStore).toSelf().inSingletonScope();
|
||||||
bind(FrontendApplicationContribution).toService(BoardsDataStore);
|
bind(FrontendApplicationContribution).toService(BoardsDataStore);
|
||||||
// Logger for the Arduino daemon
|
// Logger for the Arduino daemon
|
||||||
bind(ILogger).toDynamicValue(ctx => {
|
bind(ILogger)
|
||||||
|
.toDynamicValue((ctx) => {
|
||||||
const parentLogger = ctx.container.get<ILogger>(ILogger);
|
const parentLogger = ctx.container.get<ILogger>(ILogger);
|
||||||
return parentLogger.child('store');
|
return parentLogger.child('store');
|
||||||
}).inSingletonScope().whenTargetNamed('store');
|
})
|
||||||
|
.inSingletonScope()
|
||||||
|
.whenTargetNamed('store');
|
||||||
|
|
||||||
// Boards auto-installer
|
// Boards auto-installer
|
||||||
bind(BoardsAutoInstaller).toSelf().inSingletonScope();
|
bind(BoardsAutoInstaller).toSelf().inSingletonScope();
|
||||||
@@ -213,95 +381,158 @@ export default new ContainerModule((bind, unbind, isBound, rebind) => {
|
|||||||
// Boards list widget
|
// Boards list widget
|
||||||
bind(BoardsListWidget).toSelf();
|
bind(BoardsListWidget).toSelf();
|
||||||
bindViewContribution(bind, BoardsListWidgetFrontendContribution);
|
bindViewContribution(bind, BoardsListWidgetFrontendContribution);
|
||||||
bind(WidgetFactory).toDynamicValue(context => ({
|
bind(WidgetFactory).toDynamicValue((context) => ({
|
||||||
id: BoardsListWidget.WIDGET_ID,
|
id: BoardsListWidget.WIDGET_ID,
|
||||||
createWidget: () => context.container.get(BoardsListWidget)
|
createWidget: () => context.container.get(BoardsListWidget),
|
||||||
}));
|
}));
|
||||||
bind(FrontendApplicationContribution).toService(BoardsListWidgetFrontendContribution);
|
bind(FrontendApplicationContribution).toService(
|
||||||
|
BoardsListWidgetFrontendContribution
|
||||||
|
);
|
||||||
|
|
||||||
// Board select dialog
|
// Board select dialog
|
||||||
bind(BoardsConfigDialogWidget).toSelf().inSingletonScope();
|
bind(BoardsConfigDialogWidget).toSelf().inSingletonScope();
|
||||||
bind(BoardsConfigDialog).toSelf().inSingletonScope();
|
bind(BoardsConfigDialog).toSelf().inSingletonScope();
|
||||||
bind(BoardsConfigDialogProps).toConstantValue({
|
bind(BoardsConfigDialogProps).toConstantValue({
|
||||||
title: 'Select Board'
|
title: nls.localize('arduino/common/selectBoard', 'Select Board'),
|
||||||
})
|
});
|
||||||
|
|
||||||
// Core service
|
// Core service
|
||||||
bind(CoreService).toDynamicValue(context => WebSocketConnectionProvider.createProxy(context.container, CoreServicePath)).inSingletonScope();
|
bind(CoreService)
|
||||||
|
.toDynamicValue((context) =>
|
||||||
|
WebSocketConnectionProvider.createProxy(
|
||||||
|
context.container,
|
||||||
|
CoreServicePath
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.inSingletonScope();
|
||||||
|
|
||||||
// Serial monitor
|
// Serial monitor
|
||||||
bind(MonitorModel).toSelf().inSingletonScope();
|
bind(SerialModel).toSelf().inSingletonScope();
|
||||||
bind(FrontendApplicationContribution).toService(MonitorModel);
|
bind(FrontendApplicationContribution).toService(SerialModel);
|
||||||
bind(MonitorWidget).toSelf();
|
bind(MonitorWidget).toSelf();
|
||||||
bindViewContribution(bind, MonitorViewContribution);
|
bindViewContribution(bind, MonitorViewContribution);
|
||||||
bind(TabBarToolbarContribution).toService(MonitorViewContribution);
|
bind(TabBarToolbarContribution).toService(MonitorViewContribution);
|
||||||
bind(WidgetFactory).toDynamicValue(context => ({
|
bind(WidgetFactory).toDynamicValue((context) => ({
|
||||||
id: MonitorWidget.ID,
|
id: MonitorWidget.ID,
|
||||||
createWidget: () => context.container.get(MonitorWidget)
|
createWidget: () => context.container.get(MonitorWidget),
|
||||||
}));
|
}));
|
||||||
// Frontend binding for the serial monitor service
|
// Frontend binding for the serial service
|
||||||
bind(MonitorService).toDynamicValue(context => {
|
bind(SerialService)
|
||||||
|
.toDynamicValue((context) => {
|
||||||
const connection = context.container.get(WebSocketConnectionProvider);
|
const connection = context.container.get(WebSocketConnectionProvider);
|
||||||
const client = context.container.get(MonitorServiceClientImpl);
|
const client = context.container.get<SerialServiceClient>(
|
||||||
return connection.createProxy(MonitorServicePath, client);
|
SerialServiceClient
|
||||||
}).inSingletonScope();
|
);
|
||||||
bind(MonitorConnection).toSelf().inSingletonScope();
|
return connection.createProxy(SerialServicePath, client);
|
||||||
// Serial monitor service client to receive and delegate notifications from the backend.
|
})
|
||||||
bind(MonitorServiceClientImpl).toSelf().inSingletonScope();
|
.inSingletonScope();
|
||||||
bind(MonitorServiceClient).toDynamicValue(context => {
|
bind(SerialConnectionManager).toSelf().inSingletonScope();
|
||||||
const client = context.container.get(MonitorServiceClientImpl);
|
|
||||||
WebSocketConnectionProvider.createProxy(context.container, MonitorServicePath, client);
|
// Serial service client to receive and delegate notifications from the backend.
|
||||||
return client;
|
bind(SerialServiceClient).to(SerialServiceClientImpl).inSingletonScope();
|
||||||
}).inSingletonScope();
|
|
||||||
|
|
||||||
bind(WorkspaceService).toSelf().inSingletonScope();
|
bind(WorkspaceService).toSelf().inSingletonScope();
|
||||||
rebind(TheiaWorkspaceService).toService(WorkspaceService);
|
rebind(TheiaWorkspaceService).toService(WorkspaceService);
|
||||||
|
bind(WorkspaceVariableContribution).toSelf().inSingletonScope();
|
||||||
|
rebind(TheiaWorkspaceVariableContribution).toService(
|
||||||
|
WorkspaceVariableContribution
|
||||||
|
);
|
||||||
|
|
||||||
// Customizing default Theia layout based on the editor mode: `pro-mode` or `classic`.
|
// Customizing default Theia layout based on the editor mode: `pro-mode` or `classic`.
|
||||||
bind(EditorMode).toSelf().inSingletonScope();
|
bind(EditorMode).toSelf().inSingletonScope();
|
||||||
bind(FrontendApplicationContribution).toService(EditorMode);
|
bind(FrontendApplicationContribution).toService(EditorMode);
|
||||||
|
|
||||||
// Layout and shell customizations.
|
// Layout and shell customizations.
|
||||||
rebind(TheiaOutlineViewContribution).to(OutlineViewContribution).inSingletonScope();
|
rebind(TheiaOutlineViewContribution)
|
||||||
|
.to(OutlineViewContribution)
|
||||||
|
.inSingletonScope();
|
||||||
rebind(TheiaProblemContribution).to(ProblemContribution).inSingletonScope();
|
rebind(TheiaProblemContribution).to(ProblemContribution).inSingletonScope();
|
||||||
rebind(TheiaFileNavigatorContribution).to(FileNavigatorContribution).inSingletonScope();
|
rebind(TheiaFileNavigatorContribution)
|
||||||
rebind(TheiaEditorContribution).to(EditorContribution).inSingletonScope();
|
.to(FileNavigatorContribution)
|
||||||
rebind(TheiaMonacoStatusBarContribution).to(MonacoStatusBarContribution).inSingletonScope();
|
.inSingletonScope();
|
||||||
|
rebind(TheiaKeymapsFrontendContribution)
|
||||||
|
.to(KeymapsFrontendContribution)
|
||||||
|
.inSingletonScope();
|
||||||
|
rebind(TheiaEditorPreviewContribution)
|
||||||
|
.to(EditorPreviewContribution)
|
||||||
|
.inSingletonScope();
|
||||||
|
rebind(TheiaMonacoStatusBarContribution)
|
||||||
|
.to(MonacoStatusBarContribution)
|
||||||
|
.inSingletonScope();
|
||||||
rebind(TheiaApplicationShell).to(ApplicationShell).inSingletonScope();
|
rebind(TheiaApplicationShell).to(ApplicationShell).inSingletonScope();
|
||||||
rebind(TheiaScmContribution).to(ScmContribution).inSingletonScope();
|
rebind(TheiaScmContribution).to(ScmContribution).inSingletonScope();
|
||||||
rebind(TheiaSearchInWorkspaceFrontendContribution).to(SearchInWorkspaceFrontendContribution).inSingletonScope();
|
rebind(TheiaSearchInWorkspaceFrontendContribution)
|
||||||
|
.to(SearchInWorkspaceFrontendContribution)
|
||||||
|
.inSingletonScope();
|
||||||
rebind(TheiaFrontendApplication).to(FrontendApplication).inSingletonScope();
|
rebind(TheiaFrontendApplication).to(FrontendApplication).inSingletonScope();
|
||||||
rebind(TheiaWorkspaceFrontendContribution).to(WorkspaceFrontendContribution).inSingletonScope();
|
rebind(TheiaWorkspaceFrontendContribution)
|
||||||
rebind(TheiaFileMenuContribution).to(ArduinoFileMenuContribution).inSingletonScope();
|
.to(WorkspaceFrontendContribution)
|
||||||
rebind(TheiaCommonFrontendContribution).to(CommonFrontendContribution).inSingletonScope();
|
.inSingletonScope();
|
||||||
rebind(TheiaPreferencesContribution).to(PreferencesContribution).inSingletonScope();
|
rebind(TheiaFileMenuContribution)
|
||||||
|
.to(ArduinoFileMenuContribution)
|
||||||
|
.inSingletonScope();
|
||||||
|
rebind(TheiaCommonFrontendContribution)
|
||||||
|
.to(CommonFrontendContribution)
|
||||||
|
.inSingletonScope();
|
||||||
|
rebind(TheiaPreferencesContribution)
|
||||||
|
.to(PreferencesContribution)
|
||||||
|
.inSingletonScope();
|
||||||
rebind(TheiaKeybindingRegistry).to(KeybindingRegistry).inSingletonScope();
|
rebind(TheiaKeybindingRegistry).to(KeybindingRegistry).inSingletonScope();
|
||||||
rebind(TheiaWorkspaceCommandContribution).to(WorkspaceCommandContribution).inSingletonScope();
|
rebind(TheiaWorkspaceCommandContribution)
|
||||||
rebind(TheiaWorkspaceDeleteHandler).to(WorkspaceDeleteHandler).inSingletonScope();
|
.to(WorkspaceCommandContribution)
|
||||||
|
.inSingletonScope();
|
||||||
|
rebind(TheiaWorkspaceDeleteHandler)
|
||||||
|
.to(WorkspaceDeleteHandler)
|
||||||
|
.inSingletonScope();
|
||||||
rebind(TheiaEditorWidgetFactory).to(EditorWidgetFactory).inSingletonScope();
|
rebind(TheiaEditorWidgetFactory).to(EditorWidgetFactory).inSingletonScope();
|
||||||
rebind(TabBarToolbarFactory).toFactory(({ container: parentContainer }) => () => {
|
rebind(TabBarToolbarFactory).toFactory(
|
||||||
|
({ container: parentContainer }) => () => {
|
||||||
const container = parentContainer.createChild();
|
const container = parentContainer.createChild();
|
||||||
container.bind(TabBarToolbar).toSelf().inSingletonScope();
|
container.bind(TabBarToolbar).toSelf().inSingletonScope();
|
||||||
return container.get(TabBarToolbar);
|
return container.get(TabBarToolbar);
|
||||||
});
|
}
|
||||||
|
);
|
||||||
bind(OutputWidget).toSelf().inSingletonScope();
|
bind(OutputWidget).toSelf().inSingletonScope();
|
||||||
rebind(TheiaOutputWidget).toService(OutputWidget);
|
rebind(TheiaOutputWidget).toService(OutputWidget);
|
||||||
bind(OutputChannelManager).toSelf().inSingletonScope();
|
bind(OutputChannelManager).toSelf().inSingletonScope();
|
||||||
rebind(TheiaOutputChannelManager).toService(OutputChannelManager);
|
rebind(TheiaOutputChannelManager).toService(OutputChannelManager);
|
||||||
bind(OutputChannelRegistryMainImpl).toSelf().inTransientScope();
|
bind(OutputChannelRegistryMainImpl).toSelf().inTransientScope();
|
||||||
rebind(TheiaOutputChannelRegistryMainImpl).toService(OutputChannelRegistryMainImpl);
|
rebind(TheiaOutputChannelRegistryMainImpl).toService(
|
||||||
|
OutputChannelRegistryMainImpl
|
||||||
|
);
|
||||||
bind(MonacoTextModelService).toSelf().inSingletonScope();
|
bind(MonacoTextModelService).toSelf().inSingletonScope();
|
||||||
rebind(TheiaMonacoTextModelService).toService(MonacoTextModelService);
|
rebind(TheiaMonacoTextModelService).toService(MonacoTextModelService);
|
||||||
|
bind(MonacoEditorProvider).toSelf().inSingletonScope();
|
||||||
|
rebind(TheiaMonacoEditorProvider).toService(MonacoEditorProvider);
|
||||||
|
|
||||||
|
bind(SearchInWorkspaceWidget).toSelf();
|
||||||
|
rebind(TheiaSearchInWorkspaceWidget).toService(SearchInWorkspaceWidget);
|
||||||
|
|
||||||
|
// replace search icon
|
||||||
|
rebind(TheiaSearchInWorkspaceFactory)
|
||||||
|
.to(SearchInWorkspaceFactory)
|
||||||
|
.inSingletonScope();
|
||||||
|
|
||||||
|
rebind(TheiaSearchInWorkspaceResultTreeWidget).toDynamicValue(
|
||||||
|
({ container }) => {
|
||||||
|
const childContainer = createTreeContainer(container);
|
||||||
|
childContainer.bind(SearchInWorkspaceResultTreeWidget).toSelf();
|
||||||
|
childContainer
|
||||||
|
.rebind(TreeWidget)
|
||||||
|
.toService(SearchInWorkspaceResultTreeWidget);
|
||||||
|
return childContainer.get(SearchInWorkspaceResultTreeWidget);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
// Show a disconnected status bar, when the daemon is not available
|
// Show a disconnected status bar, when the daemon is not available
|
||||||
bind(ApplicationConnectionStatusContribution).toSelf().inSingletonScope();
|
bind(ApplicationConnectionStatusContribution).toSelf().inSingletonScope();
|
||||||
rebind(TheiaApplicationConnectionStatusContribution).toService(ApplicationConnectionStatusContribution);
|
rebind(TheiaApplicationConnectionStatusContribution).toService(
|
||||||
|
ApplicationConnectionStatusContribution
|
||||||
|
);
|
||||||
bind(FrontendConnectionStatusService).toSelf().inSingletonScope();
|
bind(FrontendConnectionStatusService).toSelf().inSingletonScope();
|
||||||
rebind(TheiaFrontendConnectionStatusService).toService(FrontendConnectionStatusService);
|
rebind(TheiaFrontendConnectionStatusService).toService(
|
||||||
|
FrontendConnectionStatusService
|
||||||
// Editor customizations. Sets the editor to `readOnly` if under the data dir.
|
);
|
||||||
bind(EditorManager).toSelf().inSingletonScope();
|
|
||||||
rebind(TheiaEditorManager).toService(EditorManager);
|
|
||||||
|
|
||||||
// Decorator customizations
|
// Decorator customizations
|
||||||
bind(TabBarDecoratorService).toSelf().inSingletonScope();
|
bind(TabBarDecoratorService).toSelf().inSingletonScope();
|
||||||
@@ -319,16 +550,53 @@ export default new ContainerModule((bind, unbind, isBound, rebind) => {
|
|||||||
bind(OutputToolbarContribution).toSelf().inSingletonScope();
|
bind(OutputToolbarContribution).toSelf().inSingletonScope();
|
||||||
rebind(TheiaOutputToolbarContribution).toService(OutputToolbarContribution);
|
rebind(TheiaOutputToolbarContribution).toService(OutputToolbarContribution);
|
||||||
|
|
||||||
bind(ArduinoDaemon).toDynamicValue(context => WebSocketConnectionProvider.createProxy(context.container, ArduinoDaemonPath)).inSingletonScope();
|
bind(ArduinoDaemon)
|
||||||
|
.toDynamicValue((context) =>
|
||||||
|
WebSocketConnectionProvider.createProxy(
|
||||||
|
context.container,
|
||||||
|
ArduinoDaemonPath
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.inSingletonScope();
|
||||||
|
|
||||||
|
bind(ArduinoFirmwareUploader)
|
||||||
|
.toDynamicValue((context) =>
|
||||||
|
WebSocketConnectionProvider.createProxy(
|
||||||
|
context.container,
|
||||||
|
ArduinoFirmwareUploaderPath
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.inSingletonScope();
|
||||||
|
|
||||||
// File-system extension
|
// File-system extension
|
||||||
bind(FileSystemExt).toDynamicValue(context => WebSocketConnectionProvider.createProxy(context.container, FileSystemExtPath)).inSingletonScope();
|
bind(FileSystemExt)
|
||||||
|
.toDynamicValue((context) =>
|
||||||
|
WebSocketConnectionProvider.createProxy(
|
||||||
|
context.container,
|
||||||
|
FileSystemExtPath
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.inSingletonScope();
|
||||||
|
|
||||||
// Examples service@
|
// Examples service@
|
||||||
bind(ExamplesService).toDynamicValue(context => WebSocketConnectionProvider.createProxy(context.container, ExamplesServicePath)).inSingletonScope();
|
bind(ExamplesService)
|
||||||
|
.toDynamicValue((context) =>
|
||||||
|
WebSocketConnectionProvider.createProxy(
|
||||||
|
context.container,
|
||||||
|
ExamplesServicePath
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.inSingletonScope();
|
||||||
|
|
||||||
// Executable URIs known by the backend
|
// Executable URIs known by the backend
|
||||||
bind(ExecutableService).toDynamicValue(context => WebSocketConnectionProvider.createProxy(context.container, ExecutableServicePath)).inSingletonScope();
|
bind(ExecutableService)
|
||||||
|
.toDynamicValue((context) =>
|
||||||
|
WebSocketConnectionProvider.createProxy(
|
||||||
|
context.container,
|
||||||
|
ExecutableServicePath
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.inSingletonScope();
|
||||||
|
|
||||||
Contribution.configure(bind, NewSketch);
|
Contribution.configure(bind, NewSketch);
|
||||||
Contribution.configure(bind, OpenSketch);
|
Contribution.configure(bind, OpenSketch);
|
||||||
@@ -349,28 +617,58 @@ export default new ContainerModule((bind, unbind, isBound, rebind) => {
|
|||||||
Contribution.configure(bind, About);
|
Contribution.configure(bind, About);
|
||||||
Contribution.configure(bind, Debug);
|
Contribution.configure(bind, Debug);
|
||||||
Contribution.configure(bind, Sketchbook);
|
Contribution.configure(bind, Sketchbook);
|
||||||
|
Contribution.configure(bind, UploadFirmware);
|
||||||
|
Contribution.configure(bind, UploadCertificate);
|
||||||
Contribution.configure(bind, BoardSelection);
|
Contribution.configure(bind, BoardSelection);
|
||||||
Contribution.configure(bind, OpenRecentSketch);
|
Contribution.configure(bind, OpenRecentSketch);
|
||||||
Contribution.configure(bind, Help);
|
Contribution.configure(bind, Help);
|
||||||
Contribution.configure(bind, AddFile);
|
Contribution.configure(bind, AddFile);
|
||||||
Contribution.configure(bind, ArchiveSketch);
|
Contribution.configure(bind, ArchiveSketch);
|
||||||
|
Contribution.configure(bind, AddZipLibrary);
|
||||||
|
Contribution.configure(bind, PlotterFrontendContribution);
|
||||||
|
|
||||||
bind(OutputServiceImpl).toSelf().inSingletonScope().onActivation(({ container }, outputService) => {
|
bind(ResponseServiceImpl)
|
||||||
WebSocketConnectionProvider.createProxy(container, OutputServicePath, outputService);
|
.toSelf()
|
||||||
return outputService;
|
.inSingletonScope()
|
||||||
|
.onActivation(({ container }, responseService) => {
|
||||||
|
WebSocketConnectionProvider.createProxy(
|
||||||
|
container,
|
||||||
|
ResponseServicePath,
|
||||||
|
responseService
|
||||||
|
);
|
||||||
|
return responseService;
|
||||||
});
|
});
|
||||||
bind(OutputService).toService(OutputServiceImpl);
|
|
||||||
|
bind(ResponseService).toService(ResponseServiceImpl);
|
||||||
|
bind(ResponseServiceArduino).toService(ResponseServiceImpl);
|
||||||
|
|
||||||
bind(NotificationCenter).toSelf().inSingletonScope();
|
bind(NotificationCenter).toSelf().inSingletonScope();
|
||||||
bind(FrontendApplicationContribution).toService(NotificationCenter);
|
bind(FrontendApplicationContribution).toService(NotificationCenter);
|
||||||
bind(NotificationServiceServer).toDynamicValue(context => WebSocketConnectionProvider.createProxy(context.container, NotificationServicePath)).inSingletonScope();
|
bind(NotificationServiceServer)
|
||||||
|
.toDynamicValue((context) =>
|
||||||
|
WebSocketConnectionProvider.createProxy(
|
||||||
|
context.container,
|
||||||
|
NotificationServicePath
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.inSingletonScope();
|
||||||
|
|
||||||
// Enable the dirty indicator on uncloseable widgets.
|
// Enable the dirty indicator on uncloseable widgets.
|
||||||
rebind(TabBarRendererFactory).toFactory(context => () => {
|
rebind(TabBarRendererFactory).toFactory((context) => () => {
|
||||||
const contextMenuRenderer = context.container.get<ContextMenuRenderer>(ContextMenuRenderer);
|
const contextMenuRenderer = context.container.get<ContextMenuRenderer>(
|
||||||
const decoratorService = context.container.get<TabBarDecoratorService>(TabBarDecoratorService);
|
ContextMenuRenderer
|
||||||
const iconThemeService = context.container.get<IconThemeService>(IconThemeService);
|
);
|
||||||
return new TabBarRenderer(contextMenuRenderer, decoratorService, iconThemeService);
|
const decoratorService = context.container.get<TabBarDecoratorService>(
|
||||||
|
TabBarDecoratorService
|
||||||
|
);
|
||||||
|
const iconThemeService = context.container.get<IconThemeService>(
|
||||||
|
IconThemeService
|
||||||
|
);
|
||||||
|
return new TabBarRenderer(
|
||||||
|
contextMenuRenderer,
|
||||||
|
decoratorService,
|
||||||
|
iconThemeService
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Workaround for https://github.com/eclipse-theia/theia/issues/8722
|
// Workaround for https://github.com/eclipse-theia/theia/issues/8722
|
||||||
@@ -387,7 +685,12 @@ export default new ContainerModule((bind, unbind, isBound, rebind) => {
|
|||||||
rebind(TheiaDebugSessionManager).toService(DebugSessionManager);
|
rebind(TheiaDebugSessionManager).toService(DebugSessionManager);
|
||||||
// To remove the `Run` menu item from the application menu.
|
// To remove the `Run` menu item from the application menu.
|
||||||
bind(DebugFrontendApplicationContribution).toSelf().inSingletonScope();
|
bind(DebugFrontendApplicationContribution).toSelf().inSingletonScope();
|
||||||
rebind(TheiaDebugFrontendApplicationContribution).toService(DebugFrontendApplicationContribution);
|
rebind(TheiaDebugFrontendApplicationContribution).toService(
|
||||||
|
DebugFrontendApplicationContribution
|
||||||
|
);
|
||||||
|
// To be able to use a `launch.json` from outside of the workspace.
|
||||||
|
bind(DebugConfigurationManager).toSelf().inSingletonScope();
|
||||||
|
rebind(TheiaDebugConfigurationManager).toService(DebugConfigurationManager);
|
||||||
|
|
||||||
// Preferences
|
// Preferences
|
||||||
bindArduinoPreferences(bind);
|
bindArduinoPreferences(bind);
|
||||||
@@ -398,6 +701,102 @@ export default new ContainerModule((bind, unbind, isBound, rebind) => {
|
|||||||
bind(SettingsWidget).toSelf().inSingletonScope();
|
bind(SettingsWidget).toSelf().inSingletonScope();
|
||||||
bind(SettingsDialog).toSelf().inSingletonScope();
|
bind(SettingsDialog).toSelf().inSingletonScope();
|
||||||
bind(SettingsDialogProps).toConstantValue({
|
bind(SettingsDialogProps).toConstantValue({
|
||||||
title: 'Preferences'
|
title: nls.localize(
|
||||||
|
'vscode/preferences.contribution/preferences',
|
||||||
|
'Preferences'
|
||||||
|
),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
bind(StorageWrapper).toSelf().inSingletonScope();
|
||||||
|
bind(CommandContribution).toService(StorageWrapper);
|
||||||
|
|
||||||
|
bind(NotificationManager).toSelf().inSingletonScope();
|
||||||
|
rebind(TheiaNotificationManager).toService(NotificationManager);
|
||||||
|
bind(NotificationsRenderer).toSelf().inSingletonScope();
|
||||||
|
rebind(TheiaNotificationsRenderer).toService(NotificationsRenderer);
|
||||||
|
|
||||||
|
// UI for the Sketchbook
|
||||||
|
bind(SketchbookWidget).toSelf();
|
||||||
|
bind(SketchbookTreeWidget).toDynamicValue(({ container }) =>
|
||||||
|
createSketchbookTreeWidget(container)
|
||||||
|
);
|
||||||
|
bindViewContribution(bind, SketchbookWidgetContribution);
|
||||||
|
bind(FrontendApplicationContribution).toService(SketchbookWidgetContribution);
|
||||||
|
bind(WidgetFactory).toDynamicValue(({ container }) => ({
|
||||||
|
id: 'arduino-sketchbook-widget',
|
||||||
|
createWidget: () => container.get(SketchbookWidget),
|
||||||
|
}));
|
||||||
|
|
||||||
|
bind(CloudSketchbookWidget).toSelf();
|
||||||
|
rebind(SketchbookWidget).toService(CloudSketchbookWidget);
|
||||||
|
bind(CloudSketchbookTreeWidget).toDynamicValue(({ container }) =>
|
||||||
|
createCloudSketchbookTreeWidget(container)
|
||||||
|
);
|
||||||
|
bind(CreateApi).toSelf().inSingletonScope();
|
||||||
|
bind(SketchCache).toSelf().inSingletonScope();
|
||||||
|
|
||||||
|
bind(ShareSketchDialog).toSelf().inSingletonScope();
|
||||||
|
bind(AuthenticationClientService).toSelf().inSingletonScope();
|
||||||
|
bind(CommandContribution).toService(AuthenticationClientService);
|
||||||
|
bind(FrontendApplicationContribution).toService(AuthenticationClientService);
|
||||||
|
bind(AuthenticationService)
|
||||||
|
.toDynamicValue((context) =>
|
||||||
|
WebSocketConnectionProvider.createProxy(
|
||||||
|
context.container,
|
||||||
|
AuthenticationServicePath
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.inSingletonScope();
|
||||||
|
bind(CreateFsProvider).toSelf().inSingletonScope();
|
||||||
|
bind(FrontendApplicationContribution).toService(CreateFsProvider);
|
||||||
|
bind(FileServiceContribution).toService(CreateFsProvider);
|
||||||
|
bind(CloudSketchbookContribution).toSelf().inSingletonScope();
|
||||||
|
bind(CommandContribution).toService(CloudSketchbookContribution);
|
||||||
|
bind(LocalCacheFsProvider).toSelf().inSingletonScope();
|
||||||
|
bind(FileServiceContribution).toService(LocalCacheFsProvider);
|
||||||
|
bind(CloudSketchbookCompositeWidget).toSelf();
|
||||||
|
bind<WidgetFactory>(WidgetFactory).toDynamicValue((ctx) => ({
|
||||||
|
id: 'cloud-sketchbook-composite-widget',
|
||||||
|
createWidget: () => ctx.container.get(CloudSketchbookCompositeWidget),
|
||||||
|
}));
|
||||||
|
|
||||||
|
bind(UploadFirmwareDialogWidget).toSelf().inSingletonScope();
|
||||||
|
bind(UploadFirmwareDialog).toSelf().inSingletonScope();
|
||||||
|
bind(UploadFirmwareDialogProps).toConstantValue({
|
||||||
|
title: 'UploadFirmware',
|
||||||
|
});
|
||||||
|
bind(UploadCertificateDialogWidget).toSelf().inSingletonScope();
|
||||||
|
bind(UploadCertificateDialog).toSelf().inSingletonScope();
|
||||||
|
bind(UploadCertificateDialogProps).toConstantValue({
|
||||||
|
title: 'UploadCertificate',
|
||||||
|
});
|
||||||
|
|
||||||
|
bind(IDEUpdaterDialogWidget).toSelf().inSingletonScope();
|
||||||
|
bind(IDEUpdaterDialog).toSelf().inSingletonScope();
|
||||||
|
bind(IDEUpdaterDialogProps).toConstantValue({
|
||||||
|
title: 'IDEUpdater',
|
||||||
|
});
|
||||||
|
|
||||||
|
bind(UserFieldsDialogWidget).toSelf().inSingletonScope();
|
||||||
|
bind(UserFieldsDialog).toSelf().inSingletonScope();
|
||||||
|
bind(UserFieldsDialogProps).toConstantValue({
|
||||||
|
title: 'UserFields',
|
||||||
|
});
|
||||||
|
|
||||||
|
bind(IDEUpdaterCommands).toSelf().inSingletonScope();
|
||||||
|
bind(CommandContribution).toService(IDEUpdaterCommands);
|
||||||
|
|
||||||
|
// Frontend binding for the IDE Updater service
|
||||||
|
bind(IDEUpdaterClientImpl).toSelf().inSingletonScope();
|
||||||
|
bind(IDEUpdaterClient).toService(IDEUpdaterClientImpl);
|
||||||
|
bind(IDEUpdater)
|
||||||
|
.toDynamicValue((context) => {
|
||||||
|
const client = context.container.get(IDEUpdaterClientImpl);
|
||||||
|
return ElectronIpcConnectionProvider.createProxy(
|
||||||
|
context.container,
|
||||||
|
IDEUpdaterPath,
|
||||||
|
client
|
||||||
|
);
|
||||||
|
})
|
||||||
|
.inSingletonScope();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -4,70 +4,211 @@ import {
|
|||||||
PreferenceProxy,
|
PreferenceProxy,
|
||||||
PreferenceService,
|
PreferenceService,
|
||||||
PreferenceContribution,
|
PreferenceContribution,
|
||||||
PreferenceSchema
|
PreferenceSchema,
|
||||||
} from '@theia/core/lib/browser/preferences';
|
} from '@theia/core/lib/browser/preferences';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
import { CompilerWarningLiterals, CompilerWarnings } from '../common/protocol';
|
||||||
|
|
||||||
|
export enum UpdateChannel {
|
||||||
|
Stable = 'stable',
|
||||||
|
Nightly = 'nightly',
|
||||||
|
}
|
||||||
|
|
||||||
export const ArduinoConfigSchema: PreferenceSchema = {
|
export const ArduinoConfigSchema: PreferenceSchema = {
|
||||||
'type': 'object',
|
type: 'object',
|
||||||
'properties': {
|
properties: {
|
||||||
'arduino.language.log': {
|
'arduino.language.log': {
|
||||||
'type': 'boolean',
|
type: 'boolean',
|
||||||
'description': "True if the Arduino Language Server should generate log files into the sketch folder. Otherwise, false. It's false by default.",
|
description: nls.localize(
|
||||||
'default': false
|
'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.compile.verbose': {
|
'arduino.compile.verbose': {
|
||||||
'type': 'boolean',
|
type: 'boolean',
|
||||||
'description': 'True for verbose compile output. False by default',
|
description: nls.localize(
|
||||||
'default': false
|
'arduino/preferences/compile.verbose',
|
||||||
|
'True for verbose compile output. False by default'
|
||||||
|
),
|
||||||
|
default: false,
|
||||||
|
},
|
||||||
|
'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': {
|
'arduino.upload.verbose': {
|
||||||
'type': 'boolean',
|
type: 'boolean',
|
||||||
'description': 'True for verbose upload output. False by default.',
|
description: nls.localize(
|
||||||
'default': false
|
'arduino/preferences/upload.verbose',
|
||||||
|
'True for verbose upload output. False by default.'
|
||||||
|
),
|
||||||
|
default: false,
|
||||||
},
|
},
|
||||||
'arduino.upload.verify': {
|
'arduino.upload.verify': {
|
||||||
'type': 'boolean',
|
type: 'boolean',
|
||||||
'default': false
|
default: false,
|
||||||
},
|
},
|
||||||
'arduino.window.autoScale': {
|
'arduino.window.autoScale': {
|
||||||
'type': 'boolean',
|
type: 'boolean',
|
||||||
'description': 'True if the user interface automatically scales with the font size.',
|
description: nls.localize(
|
||||||
'default': true
|
'arduino/preferences/window.autoScale',
|
||||||
|
'True if the user interface automatically scales with the font size.'
|
||||||
|
),
|
||||||
|
default: true,
|
||||||
},
|
},
|
||||||
'arduino.window.zoomLevel': {
|
'arduino.window.zoomLevel': {
|
||||||
'type': 'number',
|
type: 'number',
|
||||||
'description': 'Adjust the zoom level of the window. The original size is 0 and each increment above (e.g. 1) or below (e.g. -1) represents zooming 20% larger or smaller. You can also enter decimals to adjust the zoom level with a finer granularity.',
|
description: nls.localize(
|
||||||
'default': 0
|
'arduino/preferences/window.zoomLevel',
|
||||||
|
'Adjust the zoom level of the window. The original size is 0 and each increment above (e.g. 1) or below (e.g. -1) represents zooming 20% larger or smaller. You can also enter decimals to adjust the zoom level with a finer granularity.'
|
||||||
|
),
|
||||||
|
default: 0,
|
||||||
|
},
|
||||||
|
'arduino.ide.updateChannel': {
|
||||||
|
type: 'string',
|
||||||
|
enum: Object.values(UpdateChannel) as UpdateChannel[],
|
||||||
|
default: UpdateChannel.Stable,
|
||||||
|
description: nls.localize(
|
||||||
|
'arduino/preferences/ide.updateChannel',
|
||||||
|
"Release channel to get updated from. 'stable' is the stable release, 'nightly' is the latest development build."
|
||||||
|
),
|
||||||
|
},
|
||||||
|
'arduino.ide.updateBaseUrl': {
|
||||||
|
type: 'string',
|
||||||
|
default: 'https://downloads.arduino.cc/arduino-ide',
|
||||||
|
description: nls.localize(
|
||||||
|
'arduino/preferences/ide.updateBaseUrl',
|
||||||
|
`The base URL where to download updates from. Defaults to 'https://downloads.arduino.cc/arduino-ide'`
|
||||||
|
),
|
||||||
|
},
|
||||||
|
'arduino.board.certificates': {
|
||||||
|
type: 'string',
|
||||||
|
description: nls.localize(
|
||||||
|
'arduino/preferences/board.certificates',
|
||||||
|
'List of certificates that can be uploaded to boards'
|
||||||
|
),
|
||||||
|
default: '',
|
||||||
|
},
|
||||||
|
'arduino.sketchbook.showAllFiles': {
|
||||||
|
type: 'boolean',
|
||||||
|
description: nls.localize(
|
||||||
|
'arduino/preferences/sketchbook.showAllFiles',
|
||||||
|
'True to show all sketch files inside the sketch. It is false by default.'
|
||||||
|
),
|
||||||
|
default: false,
|
||||||
|
},
|
||||||
|
'arduino.cloud.enabled': {
|
||||||
|
type: 'boolean',
|
||||||
|
description: nls.localize(
|
||||||
|
'arduino/preferences/cloud.enabled',
|
||||||
|
'True if the sketch sync functions are enabled. Defaults to true.'
|
||||||
|
),
|
||||||
|
default: true,
|
||||||
|
},
|
||||||
|
'arduino.cloud.pull.warn': {
|
||||||
|
type: 'boolean',
|
||||||
|
description: nls.localize(
|
||||||
|
'arduino/preferences/cloud.pull.warn',
|
||||||
|
'True if users should be warned before pulling a cloud sketch. Defaults to true.'
|
||||||
|
),
|
||||||
|
default: true,
|
||||||
|
},
|
||||||
|
'arduino.cloud.push.warn': {
|
||||||
|
type: 'boolean',
|
||||||
|
description: nls.localize(
|
||||||
|
'arduino/preferences/cloud.push.warn',
|
||||||
|
'True if users should be warned before pushing a cloud sketch. Defaults to true.'
|
||||||
|
),
|
||||||
|
default: true,
|
||||||
|
},
|
||||||
|
'arduino.cloud.pushpublic.warn': {
|
||||||
|
type: 'boolean',
|
||||||
|
description: nls.localize(
|
||||||
|
'arduino/preferences/cloud.pushpublic.warn',
|
||||||
|
'True if users should be warned before pushing a public sketch to the cloud. Defaults to true.'
|
||||||
|
),
|
||||||
|
default: true,
|
||||||
|
},
|
||||||
|
'arduino.cloud.sketchSyncEnpoint': {
|
||||||
|
type: 'string',
|
||||||
|
description: nls.localize(
|
||||||
|
'arduino/preferences/cloud.sketchSyncEnpoint',
|
||||||
|
'The endpoint used to push and pull sketches from a backend. By default it points to Arduino Cloud API.'
|
||||||
|
),
|
||||||
|
default: 'https://api2.arduino.cc/create',
|
||||||
|
},
|
||||||
|
'arduino.auth.clientID': {
|
||||||
|
type: 'string',
|
||||||
|
description: nls.localize(
|
||||||
|
'arduino/preferences/auth.clientID',
|
||||||
|
'The OAuth2 client ID.'
|
||||||
|
),
|
||||||
|
default: 'C34Ya6ex77jTNxyKWj01lCe1vAHIaPIo',
|
||||||
|
},
|
||||||
|
'arduino.auth.domain': {
|
||||||
|
type: 'string',
|
||||||
|
description: nls.localize(
|
||||||
|
'arduino/preferences/auth.domain',
|
||||||
|
'The OAuth2 domain.'
|
||||||
|
),
|
||||||
|
default: 'login.arduino.cc',
|
||||||
|
},
|
||||||
|
'arduino.auth.audience': {
|
||||||
|
type: 'string',
|
||||||
|
description: nls.localize(
|
||||||
|
'arduino/preferences/auth.audience',
|
||||||
|
'The OAuth2 audience.'
|
||||||
|
),
|
||||||
|
default: 'https://api.arduino.cc',
|
||||||
|
},
|
||||||
|
'arduino.auth.registerUri': {
|
||||||
|
type: 'string',
|
||||||
|
description: nls.localize(
|
||||||
|
'arduino/preferences/auth.registerUri',
|
||||||
|
'The URI used to register a new user.'
|
||||||
|
),
|
||||||
|
default: 'https://auth.arduino.cc/login#/register',
|
||||||
|
},
|
||||||
},
|
},
|
||||||
'arduino.ide.autoUpdate': {
|
|
||||||
'type': 'boolean',
|
|
||||||
'description': 'True to enable automatic update checks. The IDE will check for updates automatically and periodically.',
|
|
||||||
'default': true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export interface ArduinoConfiguration {
|
export interface ArduinoConfiguration {
|
||||||
'arduino.language.log': boolean;
|
'arduino.language.log': boolean;
|
||||||
'arduino.compile.verbose': boolean;
|
'arduino.compile.verbose': boolean;
|
||||||
|
'arduino.compile.warnings': CompilerWarnings;
|
||||||
'arduino.upload.verbose': boolean;
|
'arduino.upload.verbose': boolean;
|
||||||
'arduino.upload.verify': boolean;
|
'arduino.upload.verify': boolean;
|
||||||
'arduino.window.autoScale': boolean;
|
'arduino.window.autoScale': boolean;
|
||||||
'arduino.window.zoomLevel': number;
|
'arduino.window.zoomLevel': number;
|
||||||
'arduino.ide.autoUpdate': 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.sketchSyncEnpoint': string;
|
||||||
|
'arduino.auth.clientID': string;
|
||||||
|
'arduino.auth.domain': string;
|
||||||
|
'arduino.auth.audience': string;
|
||||||
|
'arduino.auth.registerUri': string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const ArduinoPreferences = Symbol('ArduinoPreferences');
|
export const ArduinoPreferences = Symbol('ArduinoPreferences');
|
||||||
export type ArduinoPreferences = PreferenceProxy<ArduinoConfiguration>;
|
export type ArduinoPreferences = PreferenceProxy<ArduinoConfiguration>;
|
||||||
|
|
||||||
export function createArduinoPreferences(preferences: PreferenceService): ArduinoPreferences {
|
|
||||||
return createPreferenceProxy(preferences, ArduinoConfigSchema);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function bindArduinoPreferences(bind: interfaces.Bind): void {
|
export function bindArduinoPreferences(bind: interfaces.Bind): void {
|
||||||
bind(ArduinoPreferences).toDynamicValue(ctx => {
|
bind(ArduinoPreferences).toDynamicValue((ctx) => {
|
||||||
const preferences = ctx.container.get<PreferenceService>(PreferenceService);
|
const preferences = ctx.container.get<PreferenceService>(PreferenceService);
|
||||||
return createArduinoPreferences(preferences);
|
return createPreferenceProxy(preferences, ArduinoConfigSchema);
|
||||||
|
});
|
||||||
|
bind(PreferenceContribution).toConstantValue({
|
||||||
|
schema: ArduinoConfigSchema,
|
||||||
});
|
});
|
||||||
bind(PreferenceContribution).toConstantValue({ schema: ArduinoConfigSchema });
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import { toUnix } from 'upath';
|
import { URI } from '@theia/core/shared/vscode-uri';
|
||||||
import URI from '@theia/core/lib/common/uri';
|
|
||||||
import { isWindows } from '@theia/core/lib/common/os';
|
import { isWindows } from '@theia/core/lib/common/os';
|
||||||
import { notEmpty } from '@theia/core/lib/common/objects';
|
import { notEmpty } from '@theia/core/lib/common/objects';
|
||||||
import { MaybePromise } from '@theia/core/lib/common/types';
|
import { MaybePromise } from '@theia/core/lib/common/types';
|
||||||
@@ -24,20 +23,24 @@ namespace ArduinoWorkspaceRootResolver {
|
|||||||
readonly isValid: (uri: string) => MaybePromise<boolean>;
|
readonly isValid: (uri: string) => MaybePromise<boolean>;
|
||||||
}
|
}
|
||||||
export interface ResolveOptions {
|
export interface ResolveOptions {
|
||||||
readonly hash?: string
|
readonly hash?: string;
|
||||||
readonly recentWorkspaces: string[];
|
readonly recentWorkspaces: string[];
|
||||||
// Gathered from the default sketch folder. The default sketch folder is defined by the CLI.
|
// Gathered from the default sketch folder. The default sketch folder is defined by the CLI.
|
||||||
readonly recentSketches: string[];
|
readonly recentSketches: string[];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
export class ArduinoWorkspaceRootResolver {
|
export class ArduinoWorkspaceRootResolver {
|
||||||
|
constructor(protected options: ArduinoWorkspaceRootResolver.InitOptions) {}
|
||||||
|
|
||||||
constructor(protected options: ArduinoWorkspaceRootResolver.InitOptions) {
|
async resolve(
|
||||||
}
|
options: ArduinoWorkspaceRootResolver.ResolveOptions
|
||||||
|
): Promise<{ uri: string } | undefined> {
|
||||||
async resolve(options: ArduinoWorkspaceRootResolver.ResolveOptions): Promise<{ uri: string } | undefined> {
|
|
||||||
const { hash, recentWorkspaces, recentSketches } = options;
|
const { hash, recentWorkspaces, recentSketches } = options;
|
||||||
for (const uri of [this.hashToUri(hash), ...recentWorkspaces, ...recentSketches].filter(notEmpty)) {
|
for (const uri of [
|
||||||
|
this.hashToUri(hash),
|
||||||
|
...recentWorkspaces,
|
||||||
|
...recentSketches,
|
||||||
|
].filter(notEmpty)) {
|
||||||
const valid = await this.isValid(uri);
|
const valid = await this.isValid(uri);
|
||||||
if (valid) {
|
if (valid) {
|
||||||
return { uri };
|
return { uri };
|
||||||
@@ -56,13 +59,10 @@ export class ArduinoWorkspaceRootResolver {
|
|||||||
// - https://github.com/eclipse-theia/theia/blob/8196e9dcf9c8de8ea0910efeb5334a974f426966/packages/workspace/src/browser/workspace-service.ts#L143 and
|
// - https://github.com/eclipse-theia/theia/blob/8196e9dcf9c8de8ea0910efeb5334a974f426966/packages/workspace/src/browser/workspace-service.ts#L143 and
|
||||||
// - https://github.com/eclipse-theia/theia/blob/8196e9dcf9c8de8ea0910efeb5334a974f426966/packages/workspace/src/browser/workspace-service.ts#L423
|
// - https://github.com/eclipse-theia/theia/blob/8196e9dcf9c8de8ea0910efeb5334a974f426966/packages/workspace/src/browser/workspace-service.ts#L423
|
||||||
protected hashToUri(hash: string | undefined): string | undefined {
|
protected hashToUri(hash: string | undefined): string | undefined {
|
||||||
if (hash
|
if (hash && hash.length > 1 && hash.startsWith('#')) {
|
||||||
&& hash.length > 1
|
const path = decodeURI(hash.slice(1)).replace(/\\/g, '/'); // Trim the leading `#`, decode the URI and replace Windows separators
|
||||||
&& hash.startsWith('#')) {
|
return URI.file(path.slice(isWindows && hash.startsWith('/') ? 1 : 0)).toString();
|
||||||
const path = hash.slice(1); // Trim the leading `#`.
|
|
||||||
return new URI(toUnix(path.slice(isWindows && hash.startsWith('/') ? 1 : 0))).withScheme('file').toString();
|
|
||||||
}
|
}
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,93 @@
|
|||||||
|
import { inject, injectable } from 'inversify';
|
||||||
|
import { Emitter } from '@theia/core/lib/common/event';
|
||||||
|
import { JsonRpcProxy } from '@theia/core/lib/common/messaging/proxy-factory';
|
||||||
|
import { WindowService } from '@theia/core/lib/browser/window/window-service';
|
||||||
|
import { DisposableCollection } from '@theia/core/lib/common/disposable';
|
||||||
|
import { FrontendApplicationContribution } from '@theia/core/lib/browser/frontend-application';
|
||||||
|
import {
|
||||||
|
CommandRegistry,
|
||||||
|
CommandContribution,
|
||||||
|
} from '@theia/core/lib/common/command';
|
||||||
|
import {
|
||||||
|
AuthenticationService,
|
||||||
|
AuthenticationServiceClient,
|
||||||
|
AuthenticationSession,
|
||||||
|
} from '../../common/protocol/authentication-service';
|
||||||
|
import { CloudUserCommands } from './cloud-user-commands';
|
||||||
|
import { serverPort } from '../../node/auth/authentication-server';
|
||||||
|
import { AuthOptions } from '../../node/auth/types';
|
||||||
|
import { ArduinoPreferences } from '../arduino-preferences';
|
||||||
|
|
||||||
|
@injectable()
|
||||||
|
export class AuthenticationClientService
|
||||||
|
implements
|
||||||
|
FrontendApplicationContribution,
|
||||||
|
CommandContribution,
|
||||||
|
AuthenticationServiceClient
|
||||||
|
{
|
||||||
|
@inject(AuthenticationService)
|
||||||
|
protected readonly service: JsonRpcProxy<AuthenticationService>;
|
||||||
|
|
||||||
|
@inject(WindowService)
|
||||||
|
protected readonly windowService: WindowService;
|
||||||
|
|
||||||
|
@inject(ArduinoPreferences)
|
||||||
|
protected readonly arduinoPreferences: ArduinoPreferences;
|
||||||
|
|
||||||
|
protected authOptions: AuthOptions;
|
||||||
|
protected _session: AuthenticationSession | undefined;
|
||||||
|
protected readonly toDispose = new DisposableCollection();
|
||||||
|
protected readonly onSessionDidChangeEmitter = new Emitter<
|
||||||
|
AuthenticationSession | undefined
|
||||||
|
>();
|
||||||
|
|
||||||
|
readonly onSessionDidChange = this.onSessionDidChangeEmitter.event;
|
||||||
|
|
||||||
|
onStart(): void {
|
||||||
|
this.toDispose.push(this.onSessionDidChangeEmitter);
|
||||||
|
this.service.setClient(this);
|
||||||
|
this.service
|
||||||
|
.session()
|
||||||
|
.then((session) => this.notifySessionDidChange(session));
|
||||||
|
this.setOptions();
|
||||||
|
this.arduinoPreferences.onPreferenceChanged((event) => {
|
||||||
|
if (event.preferenceName.startsWith('arduino.auth.')) {
|
||||||
|
this.setOptions();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
setOptions(): void {
|
||||||
|
this.service.setOptions({
|
||||||
|
redirectUri: `http://localhost:${serverPort}/callback`,
|
||||||
|
responseType: 'code',
|
||||||
|
clientID: this.arduinoPreferences['arduino.auth.clientID'],
|
||||||
|
domain: this.arduinoPreferences['arduino.auth.domain'],
|
||||||
|
audience: this.arduinoPreferences['arduino.auth.audience'],
|
||||||
|
registerUri: this.arduinoPreferences['arduino.auth.registerUri'],
|
||||||
|
scopes: ['openid', 'profile', 'email', 'offline_access'],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
protected updateSession(session?: AuthenticationSession | undefined) {
|
||||||
|
this._session = session;
|
||||||
|
this.onSessionDidChangeEmitter.fire(this._session);
|
||||||
|
}
|
||||||
|
|
||||||
|
get session(): AuthenticationSession | undefined {
|
||||||
|
return this._session;
|
||||||
|
}
|
||||||
|
|
||||||
|
registerCommands(registry: CommandRegistry): void {
|
||||||
|
registry.registerCommand(CloudUserCommands.LOGIN, {
|
||||||
|
execute: () => this.service.login(),
|
||||||
|
});
|
||||||
|
registry.registerCommand(CloudUserCommands.LOGOUT, {
|
||||||
|
execute: () => this.service.logout(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
notifySessionDidChange(session: AuthenticationSession | undefined): void {
|
||||||
|
this.updateSession(session);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import { Command } from '@theia/core/lib/common/command';
|
||||||
|
|
||||||
|
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'
|
||||||
|
);
|
||||||
|
|
||||||
|
export const OPEN_PROFILE_CONTEXT_MENU: Command = {
|
||||||
|
id: 'arduino-cloud-sketchbook--open-profile-menu',
|
||||||
|
label: 'Contextual menu',
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,11 +1,16 @@
|
|||||||
import { injectable, inject } from 'inversify';
|
import { injectable, inject } from 'inversify';
|
||||||
import { MessageService } from '@theia/core/lib/common/message-service';
|
import { MessageService } from '@theia/core/lib/common/message-service';
|
||||||
import { FrontendApplicationContribution } from '@theia/core/lib/browser/frontend-application';
|
import { FrontendApplicationContribution } from '@theia/core/lib/browser/frontend-application';
|
||||||
import { BoardsService, BoardsPackage } from '../../common/protocol/boards-service';
|
import {
|
||||||
|
BoardsService,
|
||||||
|
BoardsPackage,
|
||||||
|
Board,
|
||||||
|
} from '../../common/protocol/boards-service';
|
||||||
import { BoardsServiceProvider } from './boards-service-provider';
|
import { BoardsServiceProvider } from './boards-service-provider';
|
||||||
import { BoardsListWidgetFrontendContribution } from './boards-widget-frontend-contribution';
|
|
||||||
import { InstallationProgressDialog } from '../widgets/progress-dialog';
|
|
||||||
import { BoardsConfig } from './boards-config';
|
import { BoardsConfig } from './boards-config';
|
||||||
|
import { Installable, ResponseServiceArduino } from '../../common/protocol';
|
||||||
|
import { BoardsListWidgetFrontendContribution } from './boards-widget-frontend-contribution';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Listens on `BoardsConfig.Config` changes, if a board is selected which does not
|
* Listens on `BoardsConfig.Config` changes, if a board is selected which does not
|
||||||
@@ -13,7 +18,6 @@ import { BoardsConfig } from './boards-config';
|
|||||||
*/
|
*/
|
||||||
@injectable()
|
@injectable()
|
||||||
export class BoardsAutoInstaller implements FrontendApplicationContribution {
|
export class BoardsAutoInstaller implements FrontendApplicationContribution {
|
||||||
|
|
||||||
@inject(MessageService)
|
@inject(MessageService)
|
||||||
protected readonly messageService: MessageService;
|
protected readonly messageService: MessageService;
|
||||||
|
|
||||||
@@ -23,40 +27,106 @@ export class BoardsAutoInstaller implements FrontendApplicationContribution {
|
|||||||
@inject(BoardsServiceProvider)
|
@inject(BoardsServiceProvider)
|
||||||
protected readonly boardsServiceClient: BoardsServiceProvider;
|
protected readonly boardsServiceClient: BoardsServiceProvider;
|
||||||
|
|
||||||
|
@inject(ResponseServiceArduino)
|
||||||
|
protected readonly responseService: ResponseServiceArduino;
|
||||||
|
|
||||||
@inject(BoardsListWidgetFrontendContribution)
|
@inject(BoardsListWidgetFrontendContribution)
|
||||||
protected readonly boardsManagerFrontendContribution: BoardsListWidgetFrontendContribution;
|
protected readonly boardsManagerFrontendContribution: BoardsListWidgetFrontendContribution;
|
||||||
|
|
||||||
|
// Workaround for https://github.com/eclipse-theia/theia/issues/9349
|
||||||
|
protected notifications: Board[] = [];
|
||||||
|
|
||||||
onStart(): void {
|
onStart(): void {
|
||||||
this.boardsServiceClient.onBoardsConfigChanged(this.ensureCoreExists.bind(this));
|
this.boardsServiceClient.onBoardsConfigChanged(
|
||||||
|
this.ensureCoreExists.bind(this)
|
||||||
|
);
|
||||||
this.ensureCoreExists(this.boardsServiceClient.boardsConfig);
|
this.ensureCoreExists(this.boardsServiceClient.boardsConfig);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected ensureCoreExists(config: BoardsConfig.Config): void {
|
protected ensureCoreExists(config: BoardsConfig.Config): void {
|
||||||
const { selectedBoard } = config;
|
const { selectedBoard, selectedPort } = config;
|
||||||
if (selectedBoard) {
|
if (
|
||||||
this.boardsService.search({}).then(packages => {
|
selectedBoard &&
|
||||||
const candidates = packages
|
selectedPort &&
|
||||||
.filter(pkg => BoardsPackage.contains(selectedBoard, pkg))
|
!this.notifications.find((board) => Board.sameAs(board, selectedBoard))
|
||||||
.filter(({ installable, installedVersion }) => installable && !installedVersion);
|
) {
|
||||||
for (const candidate of candidates) {
|
this.notifications.push(selectedBoard);
|
||||||
|
this.boardsService.search({}).then((packages) => {
|
||||||
|
// filter packagesForBoard selecting matches from the cli (installed packages)
|
||||||
|
// and matches based on the board name
|
||||||
|
// NOTE: this ensures the Deprecated & new packages are all in the array
|
||||||
|
// so that we can check if any of the valid packages is already installed
|
||||||
|
const packagesForBoard = packages.filter(
|
||||||
|
(pkg) =>
|
||||||
|
BoardsPackage.contains(selectedBoard, pkg) ||
|
||||||
|
pkg.boards.some((board) => board.name === selectedBoard.name)
|
||||||
|
);
|
||||||
|
|
||||||
|
// check if one of the packages for the board is already installed. if so, no hint
|
||||||
|
if (
|
||||||
|
packagesForBoard.some(({ installedVersion }) => !!installedVersion)
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// filter the installable (not installed) packages,
|
||||||
|
// CLI returns the packages already sorted with the deprecated ones at the end of the list
|
||||||
|
// in order to ensure the new ones are preferred
|
||||||
|
const candidates = packagesForBoard.filter(
|
||||||
|
({ installable, installedVersion }) =>
|
||||||
|
installable && !installedVersion
|
||||||
|
);
|
||||||
|
|
||||||
|
const candidate = candidates[0];
|
||||||
|
if (candidate) {
|
||||||
|
const version = candidate.availableVersions[0]
|
||||||
|
? `[v ${candidate.availableVersions[0]}]`
|
||||||
|
: '';
|
||||||
|
const yes = nls.localize('vscode/extensionsUtils/yes', 'Yes');
|
||||||
|
const manualInstall = nls.localize(
|
||||||
|
'arduino/board/installManually',
|
||||||
|
'Install Manually'
|
||||||
|
);
|
||||||
// tslint:disable-next-line:max-line-length
|
// 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 => {
|
this.messageService
|
||||||
if (answer === 'Yes') {
|
.info(
|
||||||
const dialog = new InstallationProgressDialog(candidate.name, candidate.availableVersions[0]);
|
nls.localize(
|
||||||
dialog.open();
|
'arduino/board/installNow',
|
||||||
try {
|
'The "{0} {1}" core has to be installed for the currently selected "{2}" board. Do you want to install it now?',
|
||||||
await this.boardsService.install({ item: candidate });
|
candidate.name,
|
||||||
} finally {
|
version,
|
||||||
dialog.close();
|
selectedBoard.name
|
||||||
|
),
|
||||||
|
manualInstall,
|
||||||
|
yes
|
||||||
|
)
|
||||||
|
.then(async (answer) => {
|
||||||
|
const index = this.notifications.findIndex((board) =>
|
||||||
|
Board.sameAs(board, selectedBoard)
|
||||||
|
);
|
||||||
|
if (index !== -1) {
|
||||||
|
this.notifications.splice(index, 1);
|
||||||
}
|
}
|
||||||
|
if (answer === yes) {
|
||||||
|
await Installable.installWithProgress({
|
||||||
|
installable: this.boardsService,
|
||||||
|
item: candidate,
|
||||||
|
messageService: this.messageService,
|
||||||
|
responseService: this.responseService,
|
||||||
|
version: candidate.availableVersions[0],
|
||||||
|
});
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
if (answer) {
|
if (answer === manualInstall) {
|
||||||
this.boardsManagerFrontendContribution.openView({ reveal: true }).then(widget => widget.refresh(candidate.name.toLocaleLowerCase()));
|
this.boardsManagerFrontendContribution
|
||||||
|
.openView({ reveal: true })
|
||||||
|
.then((widget) =>
|
||||||
|
widget.refresh(candidate.name.toLocaleLowerCase())
|
||||||
|
);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import { NotificationCenter } from '../notification-center';
|
|||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export class BoardsConfigDialogWidget extends ReactWidget {
|
export class BoardsConfigDialogWidget extends ReactWidget {
|
||||||
|
|
||||||
@inject(BoardsService)
|
@inject(BoardsService)
|
||||||
protected readonly boardsService: BoardsService;
|
protected readonly boardsService: BoardsService;
|
||||||
|
|
||||||
@@ -20,7 +19,8 @@ export class BoardsConfigDialogWidget extends ReactWidget {
|
|||||||
protected readonly notificationCenter: NotificationCenter;
|
protected readonly notificationCenter: NotificationCenter;
|
||||||
|
|
||||||
protected readonly onFilterTextDidChangeEmitter = new Emitter<string>();
|
protected readonly onFilterTextDidChangeEmitter = new Emitter<string>();
|
||||||
protected readonly onBoardConfigChangedEmitter = new Emitter<BoardsConfig.Config>();
|
protected readonly onBoardConfigChangedEmitter =
|
||||||
|
new Emitter<BoardsConfig.Config>();
|
||||||
readonly onBoardConfigChanged = this.onBoardConfigChangedEmitter.event;
|
readonly onBoardConfigChanged = this.onBoardConfigChangedEmitter.event;
|
||||||
|
|
||||||
protected focusNode: HTMLElement | undefined;
|
protected focusNode: HTMLElement | undefined;
|
||||||
@@ -30,7 +30,7 @@ export class BoardsConfigDialogWidget extends ReactWidget {
|
|||||||
this.id = 'select-board-dialog';
|
this.id = 'select-board-dialog';
|
||||||
this.toDispose.pushAll([
|
this.toDispose.pushAll([
|
||||||
this.onBoardConfigChangedEmitter,
|
this.onBoardConfigChangedEmitter,
|
||||||
this.onFilterTextDidChangeEmitter
|
this.onFilterTextDidChangeEmitter,
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -40,21 +40,24 @@ export class BoardsConfigDialogWidget extends ReactWidget {
|
|||||||
|
|
||||||
protected fireConfigChanged = (config: BoardsConfig.Config) => {
|
protected fireConfigChanged = (config: BoardsConfig.Config) => {
|
||||||
this.onBoardConfigChangedEmitter.fire(config);
|
this.onBoardConfigChangedEmitter.fire(config);
|
||||||
}
|
};
|
||||||
|
|
||||||
protected setFocusNode = (element: HTMLElement | undefined) => {
|
protected setFocusNode = (element: HTMLElement | undefined) => {
|
||||||
this.focusNode = element;
|
this.focusNode = element;
|
||||||
}
|
};
|
||||||
|
|
||||||
protected render(): React.ReactNode {
|
protected render(): React.ReactNode {
|
||||||
return <div className='selectBoardContainer'>
|
return (
|
||||||
|
<div className="selectBoardContainer">
|
||||||
<BoardsConfig
|
<BoardsConfig
|
||||||
boardsServiceProvider={this.boardsServiceClient}
|
boardsServiceProvider={this.boardsServiceClient}
|
||||||
notificationCenter={this.notificationCenter}
|
notificationCenter={this.notificationCenter}
|
||||||
onConfigChange={this.fireConfigChanged}
|
onConfigChange={this.fireConfigChanged}
|
||||||
onFocusNodeSet={this.setFocusNode}
|
onFocusNodeSet={this.setFocusNode}
|
||||||
onFilteredTextDidChangeEvent={this.onFilterTextDidChangeEmitter.event} />
|
onFilteredTextDidChangeEvent={this.onFilterTextDidChangeEmitter.event}
|
||||||
</div>;
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected onActivateRequest(msg: Message): void {
|
protected onActivateRequest(msg: Message): void {
|
||||||
@@ -64,5 +67,4 @@ export class BoardsConfigDialogWidget extends ReactWidget {
|
|||||||
}
|
}
|
||||||
(this.focusNode || this.node).focus();
|
(this.focusNode || this.node).focus();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,18 +1,18 @@
|
|||||||
import { injectable, inject, postConstruct } from 'inversify';
|
import { injectable, inject, postConstruct } from 'inversify';
|
||||||
import { Message } from '@phosphor/messaging';
|
import { Message } from '@phosphor/messaging';
|
||||||
import { AbstractDialog, DialogProps, Widget, DialogError } from '@theia/core/lib/browser';
|
import { DialogProps, Widget, DialogError } from '@theia/core/lib/browser';
|
||||||
|
import { AbstractDialog } from '../theia/dialogs/dialogs';
|
||||||
import { BoardsConfig } from './boards-config';
|
import { BoardsConfig } from './boards-config';
|
||||||
import { BoardsService } from '../../common/protocol/boards-service';
|
import { BoardsService } from '../../common/protocol/boards-service';
|
||||||
import { BoardsServiceProvider } from './boards-service-provider';
|
import { BoardsServiceProvider } from './boards-service-provider';
|
||||||
import { BoardsConfigDialogWidget } from './boards-config-dialog-widget';
|
import { BoardsConfigDialogWidget } from './boards-config-dialog-widget';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export class BoardsConfigDialogProps extends DialogProps {
|
export class BoardsConfigDialogProps extends DialogProps {}
|
||||||
}
|
|
||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export class BoardsConfigDialog extends AbstractDialog<BoardsConfig.Config> {
|
export class BoardsConfigDialog extends AbstractDialog<BoardsConfig.Config> {
|
||||||
|
|
||||||
@inject(BoardsConfigDialogWidget)
|
@inject(BoardsConfigDialogWidget)
|
||||||
protected readonly widget: BoardsConfigDialogWidget;
|
protected readonly widget: BoardsConfigDialogWidget;
|
||||||
|
|
||||||
@@ -24,28 +24,37 @@ export class BoardsConfigDialog extends AbstractDialog<BoardsConfig.Config> {
|
|||||||
|
|
||||||
protected config: BoardsConfig.Config = {};
|
protected config: BoardsConfig.Config = {};
|
||||||
|
|
||||||
constructor(@inject(BoardsConfigDialogProps) protected readonly props: BoardsConfigDialogProps) {
|
constructor(
|
||||||
|
@inject(BoardsConfigDialogProps)
|
||||||
|
protected readonly props: BoardsConfigDialogProps
|
||||||
|
) {
|
||||||
super(props);
|
super(props);
|
||||||
|
|
||||||
this.contentNode.classList.add('select-board-dialog');
|
this.contentNode.classList.add('select-board-dialog');
|
||||||
this.contentNode.appendChild(this.createDescription());
|
this.contentNode.appendChild(this.createDescription());
|
||||||
|
|
||||||
this.appendCloseButton('CANCEL');
|
this.appendCloseButton(
|
||||||
this.appendAcceptButton('OK');
|
nls.localize('vscode/issueMainService/cancel', 'Cancel')
|
||||||
|
);
|
||||||
|
this.appendAcceptButton(nls.localize('vscode/issueMainService/ok', 'OK'));
|
||||||
}
|
}
|
||||||
|
|
||||||
@postConstruct()
|
@postConstruct()
|
||||||
protected init(): void {
|
protected init(): void {
|
||||||
this.toDispose.push(this.boardsServiceClient.onBoardsConfigChanged(config => {
|
this.toDispose.push(
|
||||||
|
this.boardsServiceClient.onBoardsConfigChanged((config) => {
|
||||||
this.config = config;
|
this.config = config;
|
||||||
this.update();
|
this.update();
|
||||||
}));
|
})
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Pass in an empty string if you want to reset the search term. Using `undefined` has no effect.
|
* Pass in an empty string if you want to reset the search term. Using `undefined` has no effect.
|
||||||
*/
|
*/
|
||||||
async open(query: string | undefined = undefined): Promise<BoardsConfig.Config | undefined> {
|
async open(
|
||||||
|
query: string | undefined = undefined
|
||||||
|
): Promise<BoardsConfig.Config | undefined> {
|
||||||
if (typeof query === 'string') {
|
if (typeof query === 'string') {
|
||||||
this.widget.search(query);
|
this.widget.search(query);
|
||||||
}
|
}
|
||||||
@@ -57,7 +66,10 @@ export class BoardsConfigDialog extends AbstractDialog<BoardsConfig.Config> {
|
|||||||
head.classList.add('head');
|
head.classList.add('head');
|
||||||
|
|
||||||
const title = document.createElement('div');
|
const title = document.createElement('div');
|
||||||
title.textContent = 'Select Other Board & Port';
|
title.textContent = nls.localize(
|
||||||
|
'arduino/board/configDialogTitle',
|
||||||
|
'Select Other Board & Port'
|
||||||
|
);
|
||||||
title.classList.add('title');
|
title.classList.add('title');
|
||||||
head.appendChild(title);
|
head.appendChild(title);
|
||||||
|
|
||||||
@@ -66,10 +78,16 @@ export class BoardsConfigDialog extends AbstractDialog<BoardsConfig.Config> {
|
|||||||
head.appendChild(text);
|
head.appendChild(text);
|
||||||
|
|
||||||
for (const paragraph of [
|
for (const paragraph of [
|
||||||
'Select both a Board and a Port if you want to upload a sketch.',
|
nls.localize(
|
||||||
'If you only select a Board you will be able just to compile, but not to upload your sketch.'
|
'arduino/board/configDialog1',
|
||||||
|
'Select both a Board and a Port if you want to upload a sketch.'
|
||||||
|
),
|
||||||
|
nls.localize(
|
||||||
|
'arduino/board/configDialog2',
|
||||||
|
'If you only select a Board you will be able to compile, but not to upload your sketch.'
|
||||||
|
),
|
||||||
]) {
|
]) {
|
||||||
const p = document.createElement('p');
|
const p = document.createElement('div');
|
||||||
p.textContent = paragraph;
|
p.textContent = paragraph;
|
||||||
text.appendChild(p);
|
text.appendChild(p);
|
||||||
}
|
}
|
||||||
@@ -82,10 +100,12 @@ export class BoardsConfigDialog extends AbstractDialog<BoardsConfig.Config> {
|
|||||||
Widget.detach(this.widget);
|
Widget.detach(this.widget);
|
||||||
}
|
}
|
||||||
Widget.attach(this.widget, this.contentNode);
|
Widget.attach(this.widget, this.contentNode);
|
||||||
this.toDisposeOnDetach.push(this.widget.onBoardConfigChanged(config => {
|
this.toDisposeOnDetach.push(
|
||||||
|
this.widget.onBoardConfigChanged((config) => {
|
||||||
this.config = config;
|
this.config = config;
|
||||||
this.update();
|
this.update();
|
||||||
}));
|
})
|
||||||
|
);
|
||||||
super.onAfterAttach(msg);
|
super.onAfterAttach(msg);
|
||||||
this.update();
|
this.update();
|
||||||
}
|
}
|
||||||
@@ -109,7 +129,10 @@ export class BoardsConfigDialog extends AbstractDialog<BoardsConfig.Config> {
|
|||||||
protected isValid(value: BoardsConfig.Config): DialogError {
|
protected isValid(value: BoardsConfig.Config): DialogError {
|
||||||
if (!value.selectedBoard) {
|
if (!value.selectedBoard) {
|
||||||
if (value.selectedPort) {
|
if (value.selectedPort) {
|
||||||
return 'Please pick a board connected to the port you have selected.';
|
return nls.localize(
|
||||||
|
'arduino/board/pleasePickBoard',
|
||||||
|
'Please pick a board connected to the port you have selected.'
|
||||||
|
);
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -119,5 +142,4 @@ export class BoardsConfigDialog extends AbstractDialog<BoardsConfig.Config> {
|
|||||||
get value(): BoardsConfig.Config {
|
get value(): BoardsConfig.Config {
|
||||||
return this.config;
|
return this.config;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,12 +3,21 @@ import { Event } from '@theia/core/lib/common/event';
|
|||||||
import { notEmpty } from '@theia/core/lib/common/objects';
|
import { notEmpty } from '@theia/core/lib/common/objects';
|
||||||
import { MaybePromise } from '@theia/core/lib/common/types';
|
import { MaybePromise } from '@theia/core/lib/common/types';
|
||||||
import { DisposableCollection } from '@theia/core/lib/common/disposable';
|
import { DisposableCollection } from '@theia/core/lib/common/disposable';
|
||||||
import { Board, Port, AttachedBoardsChangeEvent, BoardWithPackage } from '../../common/protocol/boards-service';
|
import {
|
||||||
|
Board,
|
||||||
|
Port,
|
||||||
|
AttachedBoardsChangeEvent,
|
||||||
|
BoardWithPackage,
|
||||||
|
} from '../../common/protocol/boards-service';
|
||||||
import { NotificationCenter } from '../notification-center';
|
import { NotificationCenter } from '../notification-center';
|
||||||
import { BoardsServiceProvider } from './boards-service-provider';
|
import {
|
||||||
|
AvailableBoard,
|
||||||
|
BoardsServiceProvider,
|
||||||
|
} from './boards-service-provider';
|
||||||
|
import { naturalCompare } from '../../common/utils';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
|
||||||
export namespace BoardsConfig {
|
export namespace BoardsConfig {
|
||||||
|
|
||||||
export interface Config {
|
export interface Config {
|
||||||
selectedBoard?: Board;
|
selectedBoard?: Board;
|
||||||
selectedPort?: Port;
|
selectedPort?: Port;
|
||||||
@@ -28,18 +37,16 @@ export namespace BoardsConfig {
|
|||||||
showAllPorts: boolean;
|
showAllPorts: boolean;
|
||||||
query: string;
|
query: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export abstract class Item<T> extends React.Component<{
|
export abstract class Item<T> extends React.Component<{
|
||||||
item: T,
|
item: T;
|
||||||
label: string,
|
label: string;
|
||||||
selected: boolean,
|
selected: boolean;
|
||||||
onClick: (item: T) => void,
|
onClick: (item: T) => void;
|
||||||
missing?: boolean,
|
missing?: boolean;
|
||||||
details?: string
|
details?: string;
|
||||||
}> {
|
}> {
|
||||||
|
|
||||||
render(): React.ReactNode {
|
render(): React.ReactNode {
|
||||||
const { selected, label, missing, details } = this.props;
|
const { selected, label, missing, details } = this.props;
|
||||||
const classNames = ['item'];
|
const classNames = ['item'];
|
||||||
@@ -47,25 +54,36 @@ export abstract class Item<T> extends React.Component<{
|
|||||||
classNames.push('selected');
|
classNames.push('selected');
|
||||||
}
|
}
|
||||||
if (missing === true) {
|
if (missing === true) {
|
||||||
classNames.push('missing')
|
classNames.push('missing');
|
||||||
}
|
}
|
||||||
return <div onClick={this.onClick} className={classNames.join(' ')} title={`${label}${!details ? '' : details}`}>
|
return (
|
||||||
<div className='label'>
|
<div
|
||||||
{label}
|
onClick={this.onClick}
|
||||||
|
className={classNames.join(' ')}
|
||||||
|
title={`${label}${!details ? '' : details}`}
|
||||||
|
>
|
||||||
|
<div className="label">{label}</div>
|
||||||
|
{!details ? '' : <div className="details">{details}</div>}
|
||||||
|
{!selected ? (
|
||||||
|
''
|
||||||
|
) : (
|
||||||
|
<div className="selected-icon">
|
||||||
|
<i className="fa fa-check" />
|
||||||
</div>
|
</div>
|
||||||
{!details ? '' : <div className='details'>{details}</div>}
|
)}
|
||||||
{!selected ? '' : <div className='selected-icon'><i className='fa fa-check' /></div>}
|
</div>
|
||||||
</div>;
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected onClick = () => {
|
protected onClick = () => {
|
||||||
this.props.onClick(this.props.item);
|
this.props.onClick(this.props.item);
|
||||||
}
|
};
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export class BoardsConfig extends React.Component<BoardsConfig.Props, BoardsConfig.State> {
|
export class BoardsConfig extends React.Component<
|
||||||
|
BoardsConfig.Props,
|
||||||
|
BoardsConfig.State
|
||||||
|
> {
|
||||||
protected toDispose = new DisposableCollection();
|
protected toDispose = new DisposableCollection();
|
||||||
|
|
||||||
constructor(props: BoardsConfig.Props) {
|
constructor(props: BoardsConfig.Props) {
|
||||||
@@ -77,24 +95,49 @@ export class BoardsConfig extends React.Component<BoardsConfig.Props, BoardsConf
|
|||||||
knownPorts: [],
|
knownPorts: [],
|
||||||
showAllPorts: false,
|
showAllPorts: false,
|
||||||
query: '',
|
query: '',
|
||||||
...boardsConfig
|
...boardsConfig,
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
componentDidMount() {
|
componentDidMount() {
|
||||||
this.updateBoards();
|
this.updateBoards();
|
||||||
this.updatePorts(this.props.boardsServiceProvider.availableBoards.map(({ port }) => port).filter(notEmpty));
|
this.updatePorts(
|
||||||
|
this.props.boardsServiceProvider.availableBoards
|
||||||
|
.map(({ port }) => port)
|
||||||
|
.filter(notEmpty)
|
||||||
|
);
|
||||||
this.toDispose.pushAll([
|
this.toDispose.pushAll([
|
||||||
this.props.notificationCenter.onAttachedBoardsChanged(event => this.updatePorts(event.newState.ports, AttachedBoardsChangeEvent.diff(event).detached.ports)),
|
this.props.notificationCenter.onAttachedBoardsChanged((event) =>
|
||||||
this.props.boardsServiceProvider.onBoardsConfigChanged(({ selectedBoard, selectedPort }) => {
|
this.updatePorts(
|
||||||
this.setState({ selectedBoard, selectedPort }, () => this.fireConfigChanged());
|
event.newState.ports,
|
||||||
}),
|
AttachedBoardsChangeEvent.diff(event).detached.ports
|
||||||
this.props.notificationCenter.onPlatformInstalled(() => this.updateBoards(this.state.query)),
|
)
|
||||||
this.props.notificationCenter.onPlatformUninstalled(() => this.updateBoards(this.state.query)),
|
),
|
||||||
this.props.notificationCenter.onIndexUpdated(() => this.updateBoards(this.state.query)),
|
this.props.boardsServiceProvider.onBoardsConfigChanged(
|
||||||
this.props.notificationCenter.onDaemonStarted(() => this.updateBoards(this.state.query)),
|
({ selectedBoard, selectedPort }) => {
|
||||||
this.props.notificationCenter.onDaemonStopped(() => this.setState({ searchResults: [] })),
|
this.setState({ selectedBoard, selectedPort }, () =>
|
||||||
this.props.onFilteredTextDidChangeEvent(query => this.setState({ query }, () => this.updateBoards(this.state.query)))
|
this.fireConfigChanged()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
),
|
||||||
|
this.props.notificationCenter.onPlatformInstalled(() =>
|
||||||
|
this.updateBoards(this.state.query)
|
||||||
|
),
|
||||||
|
this.props.notificationCenter.onPlatformUninstalled(() =>
|
||||||
|
this.updateBoards(this.state.query)
|
||||||
|
),
|
||||||
|
this.props.notificationCenter.onIndexUpdated(() =>
|
||||||
|
this.updateBoards(this.state.query)
|
||||||
|
),
|
||||||
|
this.props.notificationCenter.onDaemonStarted(() =>
|
||||||
|
this.updateBoards(this.state.query)
|
||||||
|
),
|
||||||
|
this.props.notificationCenter.onDaemonStopped(() =>
|
||||||
|
this.setState({ searchResults: [] })
|
||||||
|
),
|
||||||
|
this.props.onFilteredTextDidChangeEvent((query) =>
|
||||||
|
this.setState({ query }, () => this.updateBoards(this.state.query))
|
||||||
|
),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -107,73 +150,133 @@ export class BoardsConfig extends React.Component<BoardsConfig.Props, BoardsConf
|
|||||||
this.props.onConfigChange({ selectedBoard, selectedPort });
|
this.props.onConfigChange({ selectedBoard, selectedPort });
|
||||||
}
|
}
|
||||||
|
|
||||||
protected updateBoards = (eventOrQuery: React.ChangeEvent<HTMLInputElement> | string = '') => {
|
protected updateBoards = (
|
||||||
const query = typeof eventOrQuery === 'string'
|
eventOrQuery: React.ChangeEvent<HTMLInputElement> | string = ''
|
||||||
|
) => {
|
||||||
|
const query =
|
||||||
|
typeof eventOrQuery === 'string'
|
||||||
? eventOrQuery
|
? eventOrQuery
|
||||||
: eventOrQuery.target.value.toLowerCase();
|
: eventOrQuery.target.value.toLowerCase();
|
||||||
this.setState({ query });
|
this.setState({ query });
|
||||||
this.queryBoards({ query }).then(searchResults => this.setState({ searchResults }));
|
this.queryBoards({ query }).then((searchResults) =>
|
||||||
}
|
this.setState({ searchResults })
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
protected updatePorts = (ports: Port[] = [], removedPorts: Port[] = []) => {
|
protected updatePorts = (ports: Port[] = [], removedPorts: Port[] = []) => {
|
||||||
this.queryPorts(Promise.resolve(ports)).then(({ knownPorts }) => {
|
this.queryPorts(Promise.resolve(ports)).then(({ knownPorts }) => {
|
||||||
let { selectedPort } = this.state;
|
let { selectedPort } = this.state;
|
||||||
// If the currently selected port is not available anymore, unset the selected port.
|
// If the currently selected port is not available anymore, unset the selected port.
|
||||||
if (removedPorts.some(port => Port.equals(port, selectedPort))) {
|
if (removedPorts.some((port) => Port.sameAs(port, selectedPort))) {
|
||||||
selectedPort = undefined;
|
selectedPort = undefined;
|
||||||
}
|
}
|
||||||
this.setState({ knownPorts, selectedPort }, () => this.fireConfigChanged());
|
this.setState({ knownPorts, selectedPort }, () =>
|
||||||
|
this.fireConfigChanged()
|
||||||
|
);
|
||||||
});
|
});
|
||||||
}
|
};
|
||||||
|
|
||||||
protected queryBoards = (options: { query?: string } = {}): Promise<Array<BoardWithPackage>> => {
|
protected queryBoards = (
|
||||||
|
options: { query?: string } = {}
|
||||||
|
): Promise<Array<BoardWithPackage>> => {
|
||||||
return this.props.boardsServiceProvider.searchBoards(options);
|
return this.props.boardsServiceProvider.searchBoards(options);
|
||||||
}
|
};
|
||||||
|
|
||||||
protected get availablePorts(): MaybePromise<Port[]> {
|
protected get availablePorts(): MaybePromise<Port[]> {
|
||||||
return this.props.boardsServiceProvider.availableBoards.map(({ port }) => port).filter(notEmpty);
|
return this.props.boardsServiceProvider.availableBoards
|
||||||
|
.map(({ port }) => port)
|
||||||
|
.filter(notEmpty);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected queryPorts = async (availablePorts: MaybePromise<Port[]> = this.availablePorts) => {
|
protected get availableBoards(): AvailableBoard[] {
|
||||||
const ports = await availablePorts;
|
return this.props.boardsServiceProvider.availableBoards;
|
||||||
return { knownPorts: ports.sort(Port.compare) };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected queryPorts = async (
|
||||||
|
availablePorts: MaybePromise<Port[]> = this.availablePorts
|
||||||
|
) => {
|
||||||
|
// Available ports must be sorted in this order:
|
||||||
|
// 1. Serial with recognized boards
|
||||||
|
// 2. Serial with guessed boards
|
||||||
|
// 3. Serial with incomplete boards
|
||||||
|
// 4. Network with recognized boards
|
||||||
|
// 5. Other protocols with recognized boards
|
||||||
|
const ports = (await availablePorts).sort((left: Port, right: Port) => {
|
||||||
|
if (left.protocol === 'serial' && right.protocol !== 'serial') {
|
||||||
|
return -1;
|
||||||
|
} else if (left.protocol !== 'serial' && right.protocol === 'serial') {
|
||||||
|
return 1;
|
||||||
|
} else if (left.protocol === 'network' && right.protocol !== 'network') {
|
||||||
|
return -1;
|
||||||
|
} else if (left.protocol !== 'network' && right.protocol === 'network') {
|
||||||
|
return 1;
|
||||||
|
} else if (left.protocol === right.protocol) {
|
||||||
|
// We show ports, including those that have guessed
|
||||||
|
// or unrecognized boards, so we must sort those too.
|
||||||
|
const leftBoard = this.availableBoards.find(
|
||||||
|
(board) => board.port === left
|
||||||
|
);
|
||||||
|
const rightBoard = this.availableBoards.find(
|
||||||
|
(board) => board.port === right
|
||||||
|
);
|
||||||
|
if (leftBoard && !rightBoard) {
|
||||||
|
return -1;
|
||||||
|
} else if (!leftBoard && rightBoard) {
|
||||||
|
return 1;
|
||||||
|
} else if (leftBoard?.state! < rightBoard?.state!) {
|
||||||
|
return -1;
|
||||||
|
} else if (leftBoard?.state! > rightBoard?.state!) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return naturalCompare(left.address, right.address);
|
||||||
|
});
|
||||||
|
return { knownPorts: ports };
|
||||||
|
};
|
||||||
|
|
||||||
protected toggleFilterPorts = () => {
|
protected toggleFilterPorts = () => {
|
||||||
this.setState({ showAllPorts: !this.state.showAllPorts });
|
this.setState({ showAllPorts: !this.state.showAllPorts });
|
||||||
}
|
};
|
||||||
|
|
||||||
protected selectPort = (selectedPort: Port | undefined) => {
|
protected selectPort = (selectedPort: Port | undefined) => {
|
||||||
this.setState({ selectedPort }, () => this.fireConfigChanged());
|
this.setState({ selectedPort }, () => this.fireConfigChanged());
|
||||||
}
|
};
|
||||||
|
|
||||||
protected selectBoard = (selectedBoard: BoardWithPackage | undefined) => {
|
protected selectBoard = (selectedBoard: BoardWithPackage | undefined) => {
|
||||||
this.setState({ selectedBoard }, () => this.fireConfigChanged());
|
this.setState({ selectedBoard }, () => this.fireConfigChanged());
|
||||||
}
|
};
|
||||||
|
|
||||||
protected focusNodeSet = (element: HTMLElement | null) => {
|
protected focusNodeSet = (element: HTMLElement | null) => {
|
||||||
this.props.onFocusNodeSet(element || undefined);
|
this.props.onFocusNodeSet(element || undefined);
|
||||||
}
|
};
|
||||||
|
|
||||||
render(): React.ReactNode {
|
render(): React.ReactNode {
|
||||||
return <div className='body'>
|
return (
|
||||||
|
<div className="body">
|
||||||
{this.renderContainer('boards', this.renderBoards.bind(this))}
|
{this.renderContainer('boards', this.renderBoards.bind(this))}
|
||||||
{this.renderContainer('ports', this.renderPorts.bind(this), this.renderPortsFooter.bind(this))}
|
{this.renderContainer(
|
||||||
</div>;
|
'ports',
|
||||||
|
this.renderPorts.bind(this),
|
||||||
|
this.renderPortsFooter.bind(this)
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected renderContainer(title: string, contentRenderer: () => React.ReactNode, footerRenderer?: () => React.ReactNode): React.ReactNode {
|
protected renderContainer(
|
||||||
return <div className='container'>
|
title: string,
|
||||||
<div className='content'>
|
contentRenderer: () => React.ReactNode,
|
||||||
<div className='title'>
|
footerRenderer?: () => React.ReactNode
|
||||||
{title}
|
): React.ReactNode {
|
||||||
</div>
|
return (
|
||||||
|
<div className="container">
|
||||||
|
<div className="content">
|
||||||
|
<div className="title">{title}</div>
|
||||||
{contentRenderer()}
|
{contentRenderer()}
|
||||||
<div className='footer'>
|
<div className="footer">{footerRenderer ? footerRenderer() : ''}</div>
|
||||||
{(footerRenderer ? footerRenderer() : '')}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>;
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected renderBoards(): React.ReactNode {
|
protected renderBoards(): React.ReactNode {
|
||||||
@@ -181,7 +284,8 @@ export class BoardsConfig extends React.Component<BoardsConfig.Props, BoardsConf
|
|||||||
// Board names are not unique per core https://github.com/arduino/arduino-pro-ide/issues/262#issuecomment-661019560
|
// 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.
|
// It is tricky when the core is not yet installed, no FQBNs are available.
|
||||||
const distinctBoards = new Map<string, Board.Detailed>();
|
const distinctBoards = new Map<string, Board.Detailed>();
|
||||||
const toKey = ({ name, packageName, fqbn }: Board.Detailed) => !!fqbn ? `${name}-${packageName}-${fqbn}` : `${name}-${packageName}`;
|
const toKey = ({ name, packageName, fqbn }: Board.Detailed) =>
|
||||||
|
!!fqbn ? `${name}-${packageName}-${fqbn}` : `${name}-${packageName}`;
|
||||||
for (const board of Board.decorateBoards(selectedBoard, searchResults)) {
|
for (const board of Board.decorateBoards(selectedBoard, searchResults)) {
|
||||||
const key = toKey(board);
|
const key = toKey(board);
|
||||||
if (!distinctBoards.has(key)) {
|
if (!distinctBoards.has(key)) {
|
||||||
@@ -189,98 +293,172 @@ export class BoardsConfig extends React.Component<BoardsConfig.Props, BoardsConf
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return <React.Fragment>
|
return (
|
||||||
<div className='search'>
|
<React.Fragment>
|
||||||
|
<div className="search">
|
||||||
<input
|
<input
|
||||||
type='search'
|
type="search"
|
||||||
value={query}
|
value={query}
|
||||||
className='theia-input'
|
className="theia-input"
|
||||||
placeholder='SEARCH BOARD'
|
placeholder="SEARCH BOARD"
|
||||||
onChange={this.updateBoards}
|
onChange={this.updateBoards}
|
||||||
ref={this.focusNodeSet}
|
ref={this.focusNodeSet}
|
||||||
/>
|
/>
|
||||||
<i className='fa fa-search'></i>
|
<i className="fa fa-search"></i>
|
||||||
</div>
|
</div>
|
||||||
<div className='boards list'>
|
<div className="boards list">
|
||||||
{Array.from(distinctBoards.values()).map(board => <Item<BoardWithPackage>
|
{Array.from(distinctBoards.values()).map((board) => (
|
||||||
key={`${board.name}-${board.packageName}`}
|
<Item<BoardWithPackage>
|
||||||
|
key={toKey(board)}
|
||||||
item={board}
|
item={board}
|
||||||
label={board.name}
|
label={board.name}
|
||||||
details={board.details}
|
details={board.details}
|
||||||
selected={board.selected}
|
selected={board.selected}
|
||||||
onClick={this.selectBoard}
|
onClick={this.selectBoard}
|
||||||
missing={board.missing}
|
missing={board.missing}
|
||||||
/>)}
|
/>
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
</React.Fragment>;
|
</React.Fragment>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected renderPorts(): React.ReactNode {
|
protected renderPorts(): React.ReactNode {
|
||||||
const filter = this.state.showAllPorts ? () => true : Port.isBoardPort;
|
let ports = [] as Port[];
|
||||||
const ports = this.state.knownPorts.filter(filter);
|
if (this.state.showAllPorts) {
|
||||||
return !ports.length ?
|
ports = this.state.knownPorts;
|
||||||
(
|
} else {
|
||||||
<div className='loading noselect'>
|
ports = this.state.knownPorts.filter((port) => {
|
||||||
No ports discovered
|
if (port.protocol === 'serial') {
|
||||||
</div>
|
return true;
|
||||||
) :
|
}
|
||||||
(
|
// All other ports with different protocol are
|
||||||
<div className='ports list'>
|
// only shown if there is a recognized board
|
||||||
{ports.map(port => <Item<Port>
|
// connected
|
||||||
key={Port.toString(port)}
|
for (const board of this.availableBoards) {
|
||||||
|
if (board.port?.address === port.address) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return !ports.length ? (
|
||||||
|
<div className="loading noselect">No ports discovered</div>
|
||||||
|
) : (
|
||||||
|
<div className="ports list">
|
||||||
|
{ports.map((port) => (
|
||||||
|
<Item<Port>
|
||||||
|
key={`${port.id}`}
|
||||||
item={port}
|
item={port}
|
||||||
label={Port.toString(port)}
|
label={Port.toString(port)}
|
||||||
selected={Port.equals(this.state.selectedPort, port)}
|
selected={Port.sameAs(this.state.selectedPort, port)}
|
||||||
onClick={this.selectPort}
|
onClick={this.selectPort}
|
||||||
/>)}
|
/>
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected renderPortsFooter(): React.ReactNode {
|
protected renderPortsFooter(): React.ReactNode {
|
||||||
return <div className='noselect'>
|
return (
|
||||||
|
<div className="noselect">
|
||||||
<label
|
<label
|
||||||
title='Shows all available ports when enabled'>
|
title={nls.localize(
|
||||||
|
'arduino/board/showAllAvailablePorts',
|
||||||
|
'Shows all available ports when enabled'
|
||||||
|
)}
|
||||||
|
>
|
||||||
<input
|
<input
|
||||||
type='checkbox'
|
type="checkbox"
|
||||||
defaultChecked={this.state.showAllPorts}
|
defaultChecked={this.state.showAllPorts}
|
||||||
onChange={this.toggleFilterPorts}
|
onChange={this.toggleFilterPorts}
|
||||||
/>
|
/>
|
||||||
<span>Show all ports</span>
|
<span>Show all ports</span>
|
||||||
</label>
|
</label>
|
||||||
</div>;
|
</div>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export namespace BoardsConfig {
|
export namespace BoardsConfig {
|
||||||
|
|
||||||
export namespace Config {
|
export namespace Config {
|
||||||
|
|
||||||
export function sameAs(config: Config, other: Config | Board): boolean {
|
export function sameAs(config: Config, other: Config | Board): boolean {
|
||||||
const { selectedBoard, selectedPort } = config;
|
const { selectedBoard, selectedPort } = config;
|
||||||
if (Board.is(other)) {
|
if (Board.is(other)) {
|
||||||
return !!selectedBoard
|
return (
|
||||||
&& Board.equals(other, selectedBoard)
|
!!selectedBoard &&
|
||||||
&& Port.sameAs(selectedPort, other.port);
|
Board.equals(other, selectedBoard) &&
|
||||||
|
Port.sameAs(selectedPort, other.port)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
return sameAs(config, other);
|
return sameAs(config, other);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function equals(left: Config, right: Config): boolean {
|
export function equals(left: Config, right: Config): boolean {
|
||||||
return left.selectedBoard === right.selectedBoard
|
return (
|
||||||
&& left.selectedPort === right.selectedPort;
|
left.selectedBoard === right.selectedBoard &&
|
||||||
|
left.selectedPort === right.selectedPort
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function toString(config: Config, options: { default: string } = { default: '' }): string {
|
export function toString(
|
||||||
|
config: Config,
|
||||||
|
options: { default: string } = { default: '' }
|
||||||
|
): string {
|
||||||
const { selectedBoard, selectedPort: port } = config;
|
const { selectedBoard, selectedPort: port } = config;
|
||||||
if (!selectedBoard) {
|
if (!selectedBoard) {
|
||||||
return options.default;
|
return options.default;
|
||||||
}
|
}
|
||||||
const { name } = selectedBoard;
|
const { name } = selectedBoard;
|
||||||
return `${name}${port ? ' at ' + Port.toString(port) : ''}`;
|
return `${name}${port ? ` at ${port.address}` : ''}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function setConfig(
|
||||||
|
config: Config | undefined,
|
||||||
|
urlToAttachTo: URL
|
||||||
|
): URL {
|
||||||
|
const copy = new URL(urlToAttachTo.toString());
|
||||||
|
if (!config) {
|
||||||
|
copy.searchParams.delete('boards-config');
|
||||||
|
return copy;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const selectedBoard = config.selectedBoard
|
||||||
|
? {
|
||||||
|
name: config.selectedBoard.name,
|
||||||
|
fqbn: config.selectedBoard.fqbn,
|
||||||
|
}
|
||||||
|
: undefined;
|
||||||
|
const selectedPort = config.selectedPort
|
||||||
|
? {
|
||||||
|
protocol: config.selectedPort.protocol,
|
||||||
|
address: config.selectedPort.address,
|
||||||
|
}
|
||||||
|
: undefined;
|
||||||
|
const jsonConfig = JSON.stringify({ selectedBoard, selectedPort });
|
||||||
|
copy.searchParams.set('boards-config', encodeURIComponent(jsonConfig));
|
||||||
|
return copy;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getConfig(url: URL): Config | undefined {
|
||||||
|
const encoded = url.searchParams.get('boards-config');
|
||||||
|
if (!encoded) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const raw = decodeURIComponent(encoded);
|
||||||
|
const candidate = JSON.parse(raw);
|
||||||
|
if (typeof candidate === 'object') {
|
||||||
|
return candidate;
|
||||||
|
}
|
||||||
|
console.warn(
|
||||||
|
`Expected candidate to be an object. It was ${typeof candidate}. URL was: ${url}`
|
||||||
|
);
|
||||||
|
return undefined;
|
||||||
|
} catch (e) {
|
||||||
|
console.log(`Could not get board config from URL: ${url}.`, e);
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,17 +2,20 @@ import * as PQueue from 'p-queue';
|
|||||||
import { inject, injectable } from 'inversify';
|
import { inject, injectable } from 'inversify';
|
||||||
import { CommandRegistry } from '@theia/core/lib/common/command';
|
import { CommandRegistry } from '@theia/core/lib/common/command';
|
||||||
import { MenuModelRegistry } from '@theia/core/lib/common/menu';
|
import { MenuModelRegistry } from '@theia/core/lib/common/menu';
|
||||||
import { Disposable, DisposableCollection } from '@theia/core/lib/common/disposable';
|
import {
|
||||||
|
Disposable,
|
||||||
|
DisposableCollection,
|
||||||
|
} from '@theia/core/lib/common/disposable';
|
||||||
import { BoardsServiceProvider } from './boards-service-provider';
|
import { BoardsServiceProvider } from './boards-service-provider';
|
||||||
import { Board, ConfigOption, Programmer } from '../../common/protocol';
|
import { Board, ConfigOption, Programmer } from '../../common/protocol';
|
||||||
import { FrontendApplicationContribution } from '@theia/core/lib/browser';
|
import { FrontendApplicationContribution } from '@theia/core/lib/browser';
|
||||||
import { BoardsDataStore } from './boards-data-store';
|
import { BoardsDataStore } from './boards-data-store';
|
||||||
import { MainMenuManager } from '../../common/main-menu-manager';
|
import { MainMenuManager } from '../../common/main-menu-manager';
|
||||||
import { ArduinoMenus, unregisterSubmenu } from '../menu/arduino-menus';
|
import { ArduinoMenus, unregisterSubmenu } from '../menu/arduino-menus';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export class BoardsDataMenuUpdater implements FrontendApplicationContribution {
|
export class BoardsDataMenuUpdater implements FrontendApplicationContribution {
|
||||||
|
|
||||||
@inject(CommandRegistry)
|
@inject(CommandRegistry)
|
||||||
protected readonly commandRegistry: CommandRegistry;
|
protected readonly commandRegistry: CommandRegistry;
|
||||||
|
|
||||||
@@ -33,62 +36,123 @@ export class BoardsDataMenuUpdater implements FrontendApplicationContribution {
|
|||||||
|
|
||||||
async onStart(): Promise<void> {
|
async onStart(): Promise<void> {
|
||||||
this.updateMenuActions(this.boardsServiceClient.boardsConfig.selectedBoard);
|
this.updateMenuActions(this.boardsServiceClient.boardsConfig.selectedBoard);
|
||||||
this.boardsDataStore.onChanged(() => this.updateMenuActions(this.boardsServiceClient.boardsConfig.selectedBoard));
|
this.boardsDataStore.onChanged(() =>
|
||||||
this.boardsServiceClient.onBoardsConfigChanged(({ selectedBoard }) => this.updateMenuActions(selectedBoard));
|
this.updateMenuActions(
|
||||||
|
this.boardsServiceClient.boardsConfig.selectedBoard
|
||||||
|
)
|
||||||
|
);
|
||||||
|
this.boardsServiceClient.onBoardsConfigChanged(({ selectedBoard }) =>
|
||||||
|
this.updateMenuActions(selectedBoard)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected async updateMenuActions(selectedBoard: Board | undefined): Promise<void> {
|
protected async updateMenuActions(
|
||||||
|
selectedBoard: Board | undefined
|
||||||
|
): Promise<void> {
|
||||||
return this.queue.add(async () => {
|
return this.queue.add(async () => {
|
||||||
this.toDisposeOnBoardChange.dispose();
|
this.toDisposeOnBoardChange.dispose();
|
||||||
this.mainMenuManager.update();
|
this.mainMenuManager.update();
|
||||||
if (selectedBoard) {
|
if (selectedBoard) {
|
||||||
const { fqbn } = selectedBoard;
|
const { fqbn } = selectedBoard;
|
||||||
if (fqbn) {
|
if (fqbn) {
|
||||||
const { configOptions, programmers, selectedProgrammer } = await this.boardsDataStore.getData(fqbn);
|
const { configOptions, programmers, selectedProgrammer } =
|
||||||
|
await this.boardsDataStore.getData(fqbn);
|
||||||
if (configOptions.length) {
|
if (configOptions.length) {
|
||||||
const boardsConfigMenuPath = [...ArduinoMenus.TOOLS__BOARD_SETTINGS_GROUP, 'z01_boardsConfig']; // `z_` is for ordering.
|
const boardsConfigMenuPath = [
|
||||||
for (const { label, option, values } of configOptions.sort(ConfigOption.LABEL_COMPARATOR)) {
|
...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 menuPath = [...boardsConfigMenuPath, `${option}`];
|
||||||
const commands = new Map<string, Disposable & { label: string }>()
|
const commands = new Map<
|
||||||
|
string,
|
||||||
|
Disposable & { label: string }
|
||||||
|
>();
|
||||||
for (const value of values) {
|
for (const value of values) {
|
||||||
const id = `${fqbn}-${option}--${value.value}`;
|
const id = `${fqbn}-${option}--${value.value}`;
|
||||||
const command = { id };
|
const command = { id };
|
||||||
const selectedValue = value.value;
|
const selectedValue = value.value;
|
||||||
const handler = {
|
const handler = {
|
||||||
execute: () => this.boardsDataStore.selectConfigOption({ fqbn, option, selectedValue }),
|
execute: () =>
|
||||||
isToggled: () => value.selected
|
this.boardsDataStore.selectConfigOption({
|
||||||
|
fqbn,
|
||||||
|
option,
|
||||||
|
selectedValue,
|
||||||
|
}),
|
||||||
|
isToggled: () => value.selected,
|
||||||
};
|
};
|
||||||
commands.set(id, Object.assign(this.commandRegistry.registerCommand(command, handler), { label: value.label }));
|
commands.set(
|
||||||
|
id,
|
||||||
|
Object.assign(
|
||||||
|
this.commandRegistry.registerCommand(command, handler),
|
||||||
|
{ label: value.label }
|
||||||
|
)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
this.menuRegistry.registerSubmenu(menuPath, label);
|
this.menuRegistry.registerSubmenu(menuPath, label);
|
||||||
this.toDisposeOnBoardChange.pushAll([
|
this.toDisposeOnBoardChange.pushAll([
|
||||||
...commands.values(),
|
...commands.values(),
|
||||||
Disposable.create(() => unregisterSubmenu(menuPath, this.menuRegistry)),
|
Disposable.create(() =>
|
||||||
|
unregisterSubmenu(menuPath, this.menuRegistry)
|
||||||
|
),
|
||||||
...Array.from(commands.keys()).map((commandId, i) => {
|
...Array.from(commands.keys()).map((commandId, i) => {
|
||||||
const { label } = commands.get(commandId)!;
|
const { label } = commands.get(commandId)!;
|
||||||
this.menuRegistry.registerMenuAction(menuPath, { commandId, order: `${i}`, label });
|
this.menuRegistry.registerMenuAction(menuPath, {
|
||||||
return Disposable.create(() => this.menuRegistry.unregisterMenuAction(commandId));
|
commandId,
|
||||||
})
|
order: `${i}`,
|
||||||
|
label,
|
||||||
|
});
|
||||||
|
return Disposable.create(() =>
|
||||||
|
this.menuRegistry.unregisterMenuAction(commandId)
|
||||||
|
);
|
||||||
|
}),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (programmers.length) {
|
if (programmers.length) {
|
||||||
const programmersMenuPath = [...ArduinoMenus.TOOLS__BOARD_SETTINGS_GROUP, 'z02_programmers'];
|
const programmersMenuPath = [
|
||||||
const label = selectedProgrammer ? `Programmer: "${selectedProgrammer.name}"` : 'Programmer'
|
...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.menuRegistry.registerSubmenu(programmersMenuPath, label);
|
||||||
this.toDisposeOnBoardChange.push(Disposable.create(() => unregisterSubmenu(programmersMenuPath, this.menuRegistry)));
|
this.toDisposeOnBoardChange.push(
|
||||||
|
Disposable.create(() =>
|
||||||
|
unregisterSubmenu(programmersMenuPath, this.menuRegistry)
|
||||||
|
)
|
||||||
|
);
|
||||||
for (const programmer of programmers) {
|
for (const programmer of programmers) {
|
||||||
const { id, name } = programmer;
|
const { id, name } = programmer;
|
||||||
const command = { id: `${fqbn}-programmer--${id}` };
|
const command = { id: `${fqbn}-programmer--${id}` };
|
||||||
const handler = {
|
const handler = {
|
||||||
execute: () => this.boardsDataStore.selectProgrammer({ fqbn, selectedProgrammer: programmer }),
|
execute: () =>
|
||||||
isToggled: () => Programmer.equals(programmer, selectedProgrammer)
|
this.boardsDataStore.selectProgrammer({
|
||||||
|
fqbn,
|
||||||
|
selectedProgrammer: programmer,
|
||||||
|
}),
|
||||||
|
isToggled: () =>
|
||||||
|
Programmer.equals(programmer, selectedProgrammer),
|
||||||
};
|
};
|
||||||
this.menuRegistry.registerMenuAction(programmersMenuPath, { commandId: command.id, label: name });
|
this.menuRegistry.registerMenuAction(programmersMenuPath, {
|
||||||
|
commandId: command.id,
|
||||||
|
label: name,
|
||||||
|
});
|
||||||
this.commandRegistry.registerCommand(command, handler);
|
this.commandRegistry.registerCommand(command, handler);
|
||||||
this.toDisposeOnBoardChange.pushAll([
|
this.toDisposeOnBoardChange.pushAll([
|
||||||
Disposable.create(() => this.commandRegistry.unregisterCommand(command)),
|
Disposable.create(() =>
|
||||||
Disposable.create(() => this.menuRegistry.unregisterMenuAction(command.id))
|
this.commandRegistry.unregisterCommand(command)
|
||||||
|
),
|
||||||
|
Disposable.create(() =>
|
||||||
|
this.menuRegistry.unregisterMenuAction(command.id)
|
||||||
|
),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -97,5 +161,4 @@ export class BoardsDataMenuUpdater implements FrontendApplicationContribution {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,16 +1,22 @@
|
|||||||
import { injectable, inject, named } from 'inversify';
|
import { injectable, inject, named } from 'inversify';
|
||||||
import { ILogger } from '@theia/core/lib/common/logger';
|
import { ILogger } from '@theia/core/lib/common/logger';
|
||||||
import { deepClone } from '@theia/core/lib/common/objects';
|
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 { Event, Emitter } from '@theia/core/lib/common/event';
|
||||||
import { FrontendApplicationContribution, LocalStorageService } from '@theia/core/lib/browser';
|
import {
|
||||||
|
FrontendApplicationContribution,
|
||||||
|
LocalStorageService,
|
||||||
|
} from '@theia/core/lib/browser';
|
||||||
import { notEmpty } from '../../common/utils';
|
import { notEmpty } from '../../common/utils';
|
||||||
import { BoardsService, ConfigOption, Installable, BoardDetails, Programmer } from '../../common/protocol';
|
import {
|
||||||
|
BoardsService,
|
||||||
|
ConfigOption,
|
||||||
|
BoardDetails,
|
||||||
|
Programmer,
|
||||||
|
} from '../../common/protocol';
|
||||||
import { NotificationCenter } from '../notification-center';
|
import { NotificationCenter } from '../notification-center';
|
||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export class BoardsDataStore implements FrontendApplicationContribution {
|
export class BoardsDataStore implements FrontendApplicationContribution {
|
||||||
|
|
||||||
@inject(ILogger)
|
@inject(ILogger)
|
||||||
@named('store')
|
@named('store')
|
||||||
protected readonly logger: ILogger;
|
protected readonly logger: ILogger;
|
||||||
@@ -28,14 +34,15 @@ export class BoardsDataStore implements FrontendApplicationContribution {
|
|||||||
|
|
||||||
onStart(): void {
|
onStart(): void {
|
||||||
this.notificationCenter.onPlatformInstalled(async ({ item }) => {
|
this.notificationCenter.onPlatformInstalled(async ({ item }) => {
|
||||||
const { installedVersion: version } = item;
|
|
||||||
if (!version) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let shouldFireChanged = false;
|
let shouldFireChanged = false;
|
||||||
for (const fqbn of item.boards.map(({ fqbn }) => fqbn).filter(notEmpty).filter(fqbn => !!fqbn)) {
|
for (const fqbn of item.boards
|
||||||
const key = this.getStorageKey(fqbn, version);
|
.map(({ fqbn }) => fqbn)
|
||||||
let data = await this.storageService.getData<ConfigOption[] | undefined>(key);
|
.filter(notEmpty)
|
||||||
|
.filter((fqbn) => !!fqbn)) {
|
||||||
|
const key = this.getStorageKey(fqbn);
|
||||||
|
let data = await this.storageService.getData<
|
||||||
|
ConfigOption[] | undefined
|
||||||
|
>(key);
|
||||||
if (!data || !data.length) {
|
if (!data || !data.length) {
|
||||||
const details = await this.getBoardDetailsSafe(fqbn);
|
const details = await this.getBoardDetailsSafe(fqbn);
|
||||||
if (details) {
|
if (details) {
|
||||||
@@ -59,30 +66,23 @@ export class BoardsDataStore implements FrontendApplicationContribution {
|
|||||||
|
|
||||||
async appendConfigToFqbn(
|
async appendConfigToFqbn(
|
||||||
fqbn: string | undefined,
|
fqbn: string | undefined,
|
||||||
boardsPackageVersion: MaybePromise<Installable.Version | undefined> = this.getBoardsPackageVersion(fqbn)): Promise<string | undefined> {
|
): Promise<string | undefined> {
|
||||||
|
|
||||||
if (!fqbn) {
|
if (!fqbn) {
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
const { configOptions } = await this.getData(fqbn);
|
||||||
const { configOptions } = await this.getData(fqbn, boardsPackageVersion);
|
|
||||||
return ConfigOption.decorate(fqbn, configOptions);
|
return ConfigOption.decorate(fqbn, configOptions);
|
||||||
}
|
}
|
||||||
|
|
||||||
async getData(
|
async getData(fqbn: string | undefined): Promise<BoardsDataStore.Data> {
|
||||||
fqbn: string | undefined,
|
|
||||||
boardsPackageVersion: MaybePromise<Installable.Version | undefined> = this.getBoardsPackageVersion(fqbn)): Promise<BoardsDataStore.Data> {
|
|
||||||
|
|
||||||
if (!fqbn) {
|
if (!fqbn) {
|
||||||
return BoardsDataStore.Data.EMPTY;
|
return BoardsDataStore.Data.EMPTY;
|
||||||
}
|
}
|
||||||
|
|
||||||
const version = await boardsPackageVersion;
|
const key = this.getStorageKey(fqbn);
|
||||||
if (!version) {
|
let data = await this.storageService.getData<
|
||||||
return BoardsDataStore.Data.EMPTY;
|
BoardsDataStore.Data | undefined
|
||||||
}
|
>(key, undefined);
|
||||||
const key = this.getStorageKey(fqbn, version);
|
|
||||||
let data = await this.storageService.getData<BoardsDataStore.Data | undefined>(key, undefined);
|
|
||||||
if (BoardsDataStore.Data.is(data)) {
|
if (BoardsDataStore.Data.is(data)) {
|
||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
@@ -92,38 +92,44 @@ export class BoardsDataStore implements FrontendApplicationContribution {
|
|||||||
return BoardsDataStore.Data.EMPTY;
|
return BoardsDataStore.Data.EMPTY;
|
||||||
}
|
}
|
||||||
|
|
||||||
data = { configOptions: boardDetails.configOptions, programmers: boardDetails.programmers };
|
data = {
|
||||||
|
configOptions: boardDetails.configOptions,
|
||||||
|
programmers: boardDetails.programmers,
|
||||||
|
};
|
||||||
await this.storageService.setData(key, data);
|
await this.storageService.setData(key, data);
|
||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
async selectProgrammer(
|
async selectProgrammer(
|
||||||
{ fqbn, selectedProgrammer }: { fqbn: string, selectedProgrammer: Programmer },
|
{
|
||||||
boardsPackageVersion: MaybePromise<Installable.Version | undefined> = this.getBoardsPackageVersion(fqbn)): Promise<boolean> {
|
fqbn,
|
||||||
|
selectedProgrammer,
|
||||||
const data = deepClone(await this.getData(fqbn, boardsPackageVersion));
|
}: { fqbn: string; selectedProgrammer: Programmer },
|
||||||
|
): Promise<boolean> {
|
||||||
|
const data = deepClone(await this.getData(fqbn));
|
||||||
const { programmers } = data;
|
const { programmers } = data;
|
||||||
if (!programmers.find(p => Programmer.equals(selectedProgrammer, p))) {
|
if (!programmers.find((p) => Programmer.equals(selectedProgrammer, p))) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
const version = await boardsPackageVersion;
|
await this.setData({
|
||||||
if (!version) {
|
fqbn,
|
||||||
return false;
|
data: { ...data, selectedProgrammer },
|
||||||
}
|
});
|
||||||
|
|
||||||
await this.setData({ fqbn, data: { ...data, selectedProgrammer }, version });
|
|
||||||
this.fireChanged();
|
this.fireChanged();
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
async selectConfigOption(
|
async selectConfigOption(
|
||||||
{ fqbn, option, selectedValue }: { fqbn: string, option: string, selectedValue: string },
|
{
|
||||||
boardsPackageVersion: MaybePromise<Installable.Version | undefined> = this.getBoardsPackageVersion(fqbn)): Promise<boolean> {
|
fqbn,
|
||||||
|
option,
|
||||||
const data = deepClone(await this.getData(fqbn, boardsPackageVersion));
|
selectedValue,
|
||||||
|
}: { fqbn: string; option: string; selectedValue: string }
|
||||||
|
): Promise<boolean> {
|
||||||
|
const data = deepClone(await this.getData(fqbn));
|
||||||
const { configOptions } = data;
|
const { configOptions } = data;
|
||||||
const configOption = configOptions.find(c => c.option === option);
|
const configOption = configOptions.find((c) => c.option === option);
|
||||||
if (!configOption) {
|
if (!configOption) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -139,36 +145,46 @@ export class BoardsDataStore implements FrontendApplicationContribution {
|
|||||||
if (!updated) {
|
if (!updated) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
const version = await boardsPackageVersion;
|
await this.setData({ fqbn, data });
|
||||||
if (!version) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.setData({ fqbn, data, version });
|
|
||||||
this.fireChanged();
|
this.fireChanged();
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected async setData(
|
protected async setData({
|
||||||
{ fqbn, data, version }: { fqbn: string, data: BoardsDataStore.Data, version: Installable.Version }): Promise<void> {
|
fqbn,
|
||||||
|
data,
|
||||||
const key = this.getStorageKey(fqbn, version);
|
}: {
|
||||||
|
fqbn: string;
|
||||||
|
data: BoardsDataStore.Data;
|
||||||
|
}): Promise<void> {
|
||||||
|
const key = this.getStorageKey(fqbn);
|
||||||
return this.storageService.setData(key, data);
|
return this.storageService.setData(key, data);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected getStorageKey(fqbn: string, version: Installable.Version): string {
|
protected getStorageKey(fqbn: string): string {
|
||||||
return `.arduinoIDE-configOptions-${version}-${fqbn}`;
|
return `.arduinoIDE-configOptions-${fqbn}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected async getBoardDetailsSafe(fqbn: string): Promise<BoardDetails | undefined> {
|
protected async getBoardDetailsSafe(
|
||||||
|
fqbn: string
|
||||||
|
): Promise<BoardDetails | undefined> {
|
||||||
try {
|
try {
|
||||||
const details = this.boardsService.getBoardDetails({ fqbn });
|
const details = this.boardsService.getBoardDetails({ fqbn });
|
||||||
return details;
|
return details;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (err instanceof Error && err.message.includes('loading board data') && err.message.includes('is not installed')) {
|
if (
|
||||||
this.logger.warn(`The boards package is not installed for board with FQBN: ${fqbn}`);
|
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 {
|
} else {
|
||||||
this.logger.error(`An unexpected error occurred while retrieving the board details for ${fqbn}.`, err);
|
this.logger.error(
|
||||||
|
`An unexpected error occurred while retrieving the board details for ${fqbn}.`,
|
||||||
|
err
|
||||||
|
);
|
||||||
}
|
}
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
@@ -177,18 +193,6 @@ export class BoardsDataStore implements FrontendApplicationContribution {
|
|||||||
protected fireChanged(): void {
|
protected fireChanged(): void {
|
||||||
this.onChangedEmitter.fire();
|
this.onChangedEmitter.fire();
|
||||||
}
|
}
|
||||||
|
|
||||||
protected async getBoardsPackageVersion(fqbn: string | undefined): Promise<Installable.Version | undefined> {
|
|
||||||
if (!fqbn) {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
const boardsPackage = await this.boardsService.getContainerBoardPackage({ fqbn });
|
|
||||||
if (!boardsPackage) {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
return boardsPackage.installedVersion;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export namespace BoardsDataStore {
|
export namespace BoardsDataStore {
|
||||||
@@ -200,12 +204,16 @@ export namespace BoardsDataStore {
|
|||||||
export namespace Data {
|
export namespace Data {
|
||||||
export const EMPTY: Data = {
|
export const EMPTY: Data = {
|
||||||
configOptions: [],
|
configOptions: [],
|
||||||
programmers: []
|
programmers: [],
|
||||||
};
|
};
|
||||||
export function is(arg: any): arg is Data {
|
export function is(arg: any): arg is Data {
|
||||||
return !!arg
|
return (
|
||||||
&& 'configOptions' in arg && Array.isArray(arg['configOptions'])
|
!!arg &&
|
||||||
&& 'programmers' in arg && Array.isArray(arg['programmers'])
|
'configOptions' in arg &&
|
||||||
|
Array.isArray(arg['configOptions']) &&
|
||||||
|
'programmers' in arg &&
|
||||||
|
Array.isArray(arg['programmers'])
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,26 +1,31 @@
|
|||||||
import { inject, injectable, postConstruct } from 'inversify';
|
import { inject, injectable, postConstruct } from 'inversify';
|
||||||
import { BoardsPackage, BoardsService } from '../../common/protocol/boards-service';
|
import {
|
||||||
|
BoardsPackage,
|
||||||
|
BoardsService,
|
||||||
|
} from '../../common/protocol/boards-service';
|
||||||
import { ListWidget } from '../widgets/component-list/list-widget';
|
import { ListWidget } from '../widgets/component-list/list-widget';
|
||||||
import { ListItemRenderer } from '../widgets/component-list/list-item-renderer';
|
import { ListItemRenderer } from '../widgets/component-list/list-item-renderer';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export class BoardsListWidget extends ListWidget<BoardsPackage> {
|
export class BoardsListWidget extends ListWidget<BoardsPackage> {
|
||||||
|
|
||||||
static WIDGET_ID = 'boards-list-widget';
|
static WIDGET_ID = 'boards-list-widget';
|
||||||
static WIDGET_LABEL = 'Boards Manager';
|
static WIDGET_LABEL = nls.localize('arduino/boardsManager', 'Boards Manager');
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
@inject(BoardsService) protected service: BoardsService,
|
@inject(BoardsService) protected service: BoardsService,
|
||||||
@inject(ListItemRenderer) protected itemRenderer: ListItemRenderer<BoardsPackage>) {
|
@inject(ListItemRenderer)
|
||||||
|
protected itemRenderer: ListItemRenderer<BoardsPackage>
|
||||||
|
) {
|
||||||
super({
|
super({
|
||||||
id: BoardsListWidget.WIDGET_ID,
|
id: BoardsListWidget.WIDGET_ID,
|
||||||
label: BoardsListWidget.WIDGET_LABEL,
|
label: BoardsListWidget.WIDGET_LABEL,
|
||||||
iconClass: 'fa fa-microchip',
|
iconClass: 'fa fa-arduino-boards',
|
||||||
searchable: service,
|
searchable: service,
|
||||||
installable: service,
|
installable: service,
|
||||||
itemLabel: (item: BoardsPackage) => item.name,
|
itemLabel: (item: BoardsPackage) => item.name,
|
||||||
itemRenderer
|
itemDeprecated: (item: BoardsPackage) => item.deprecated,
|
||||||
|
itemRenderer,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -28,9 +33,52 @@ export class BoardsListWidget extends ListWidget<BoardsPackage> {
|
|||||||
protected init(): void {
|
protected init(): void {
|
||||||
super.init();
|
super.init();
|
||||||
this.toDispose.pushAll([
|
this.toDispose.pushAll([
|
||||||
this.notificationCenter.onPlatformInstalled(() => this.refresh(undefined)),
|
this.notificationCenter.onPlatformInstalled(() =>
|
||||||
this.notificationCenter.onPlatformUninstalled(() => this.refresh(undefined)),
|
this.refresh(undefined)
|
||||||
|
),
|
||||||
|
this.notificationCenter.onPlatformUninstalled(() =>
|
||||||
|
this.refresh(undefined)
|
||||||
|
),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected async install({
|
||||||
|
item,
|
||||||
|
progressId,
|
||||||
|
version,
|
||||||
|
}: {
|
||||||
|
item: BoardsPackage;
|
||||||
|
progressId: string;
|
||||||
|
version: string;
|
||||||
|
}): Promise<void> {
|
||||||
|
await super.install({ item, progressId, version });
|
||||||
|
this.messageService.info(
|
||||||
|
nls.localize(
|
||||||
|
'arduino/board/succesfullyInstalledPlatform',
|
||||||
|
'Successfully installed platform {0}:{1}',
|
||||||
|
item.name,
|
||||||
|
version
|
||||||
|
),
|
||||||
|
{ timeout: 3000 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected 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 }
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { injectable, inject } from 'inversify';
|
import { injectable, inject } from 'inversify';
|
||||||
import { Emitter } from '@theia/core/lib/common/event';
|
import { Emitter } from '@theia/core/lib/common/event';
|
||||||
import { ILogger } from '@theia/core/lib/common/logger';
|
import { ILogger } from '@theia/core/lib/common/logger';
|
||||||
|
import { CommandService } from '@theia/core/lib/common/command';
|
||||||
import { MessageService } from '@theia/core/lib/common/message-service';
|
import { 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 { FrontendApplicationContribution } from '@theia/core/lib/browser/frontend-application';
|
||||||
import { RecursiveRequired } from '../../common/types';
|
import { RecursiveRequired } from '../../common/types';
|
||||||
import {
|
import {
|
||||||
@@ -11,32 +11,24 @@ import {
|
|||||||
BoardsService,
|
BoardsService,
|
||||||
BoardsPackage,
|
BoardsPackage,
|
||||||
AttachedBoardsChangeEvent,
|
AttachedBoardsChangeEvent,
|
||||||
BoardWithPackage
|
BoardWithPackage,
|
||||||
|
BoardUserField,
|
||||||
} from '../../common/protocol';
|
} from '../../common/protocol';
|
||||||
import { BoardsConfig } from './boards-config';
|
import { BoardsConfig } from './boards-config';
|
||||||
import { naturalCompare } from '../../common/utils';
|
import { naturalCompare } from '../../common/utils';
|
||||||
import { compareAnything } from '../theia/monaco/comparers';
|
|
||||||
import { NotificationCenter } from '../notification-center';
|
import { NotificationCenter } from '../notification-center';
|
||||||
import { CommandService } from '@theia/core';
|
|
||||||
import { ArduinoCommands } from '../arduino-commands';
|
import { ArduinoCommands } from '../arduino-commands';
|
||||||
|
import { StorageWrapper } from '../storage-wrapper';
|
||||||
interface BoardMatch {
|
import { nls } from '@theia/core/lib/common';
|
||||||
readonly board: BoardWithPackage;
|
|
||||||
readonly matches: monaco.filters.IMatch[] | undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export class BoardsServiceProvider implements FrontendApplicationContribution {
|
export class BoardsServiceProvider implements FrontendApplicationContribution {
|
||||||
|
|
||||||
@inject(ILogger)
|
@inject(ILogger)
|
||||||
protected logger: ILogger;
|
protected logger: ILogger;
|
||||||
|
|
||||||
@inject(MessageService)
|
@inject(MessageService)
|
||||||
protected messageService: MessageService;
|
protected messageService: MessageService;
|
||||||
|
|
||||||
@inject(StorageService)
|
|
||||||
protected storageService: StorageService;
|
|
||||||
|
|
||||||
@inject(BoardsService)
|
@inject(BoardsService)
|
||||||
protected boardsService: BoardsService;
|
protected boardsService: BoardsService;
|
||||||
|
|
||||||
@@ -46,8 +38,12 @@ export class BoardsServiceProvider implements FrontendApplicationContribution {
|
|||||||
@inject(NotificationCenter)
|
@inject(NotificationCenter)
|
||||||
protected notificationCenter: NotificationCenter;
|
protected notificationCenter: NotificationCenter;
|
||||||
|
|
||||||
protected readonly onBoardsConfigChangedEmitter = new Emitter<BoardsConfig.Config>();
|
protected readonly onBoardsConfigChangedEmitter =
|
||||||
protected readonly onAvailableBoardsChangedEmitter = new Emitter<AvailableBoard[]>();
|
new Emitter<BoardsConfig.Config>();
|
||||||
|
protected readonly onAvailableBoardsChangedEmitter = new Emitter<
|
||||||
|
AvailableBoard[]
|
||||||
|
>();
|
||||||
|
protected readonly onAvailablePortsChangedEmitter = new Emitter<Port[]>();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Used for the auto-reconnecting. Sometimes, the attached board gets disconnected after uploading something to it.
|
* Used for the auto-reconnecting. Sometimes, the attached board gets disconnected after uploading something to it.
|
||||||
@@ -56,7 +52,9 @@ export class BoardsServiceProvider implements FrontendApplicationContribution {
|
|||||||
* We have to listen on such changes and auto-reconnect the same board on another port.
|
* 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
|
* See: https://arduino.slack.com/archives/CJJHJCJSJ/p1568645417013000?thread_ts=1568640504.009400&cid=CJJHJCJSJ
|
||||||
*/
|
*/
|
||||||
protected latestValidBoardsConfig: RecursiveRequired<BoardsConfig.Config> | undefined = undefined;
|
protected latestValidBoardsConfig:
|
||||||
|
| RecursiveRequired<BoardsConfig.Config>
|
||||||
|
| undefined = undefined;
|
||||||
protected latestBoardsConfig: BoardsConfig.Config | undefined = undefined;
|
protected latestBoardsConfig: BoardsConfig.Config | undefined = undefined;
|
||||||
protected _boardsConfig: BoardsConfig.Config = {};
|
protected _boardsConfig: BoardsConfig.Config = {};
|
||||||
protected _attachedBoards: Board[] = []; // This does not contain the `Unknown` boards. They're visible from the available ports only.
|
protected _attachedBoards: Board[] = []; // This does not contain the `Unknown` boards. They're visible from the available ports only.
|
||||||
@@ -68,35 +66,47 @@ export class BoardsServiceProvider implements FrontendApplicationContribution {
|
|||||||
* This even also fires, when the boards package was not available for the currently selected board,
|
* 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
|
* and the user installs the board package. Note: installing a board package will set the `fqbn` of the
|
||||||
* currently selected board.\
|
* currently selected board.\
|
||||||
* This even also emitted when the board package for the currently selected board was uninstalled.
|
* This event is also emitted when the board package for the currently selected board was uninstalled.
|
||||||
*/
|
*/
|
||||||
readonly onBoardsConfigChanged = this.onBoardsConfigChangedEmitter.event;
|
readonly onBoardsConfigChanged = this.onBoardsConfigChangedEmitter.event;
|
||||||
readonly onAvailableBoardsChanged = this.onAvailableBoardsChangedEmitter.event;
|
readonly onAvailableBoardsChanged =
|
||||||
|
this.onAvailableBoardsChangedEmitter.event;
|
||||||
|
readonly onAvailablePortsChanged = this.onAvailablePortsChangedEmitter.event;
|
||||||
|
|
||||||
onStart(): void {
|
onStart(): void {
|
||||||
this.notificationCenter.onAttachedBoardsChanged(this.notifyAttachedBoardsChanged.bind(this));
|
this.notificationCenter.onAttachedBoardsChanged(
|
||||||
this.notificationCenter.onPlatformInstalled(this.notifyPlatformInstalled.bind(this));
|
this.notifyAttachedBoardsChanged.bind(this)
|
||||||
this.notificationCenter.onPlatformUninstalled(this.notifyPlatformUninstalled.bind(this));
|
);
|
||||||
|
this.notificationCenter.onPlatformInstalled(
|
||||||
|
this.notifyPlatformInstalled.bind(this)
|
||||||
|
);
|
||||||
|
this.notificationCenter.onPlatformUninstalled(
|
||||||
|
this.notifyPlatformUninstalled.bind(this)
|
||||||
|
);
|
||||||
|
|
||||||
Promise.all([
|
Promise.all([
|
||||||
this.boardsService.getAttachedBoards(),
|
this.boardsService.getAttachedBoards(),
|
||||||
this.boardsService.getAvailablePorts(),
|
this.boardsService.getAvailablePorts(),
|
||||||
this.loadState()
|
this.loadState(),
|
||||||
]).then(([attachedBoards, availablePorts]) => {
|
]).then(([attachedBoards, availablePorts]) => {
|
||||||
this._attachedBoards = attachedBoards;
|
this._attachedBoards = attachedBoards;
|
||||||
this._availablePorts = availablePorts;
|
this._availablePorts = availablePorts;
|
||||||
|
this.onAvailablePortsChangedEmitter.fire(this._availablePorts);
|
||||||
this.reconcileAvailableBoards().then(() => this.tryReconnect());
|
this.reconcileAvailableBoards().then(() => this.tryReconnect());
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
protected notifyAttachedBoardsChanged(event: AttachedBoardsChangeEvent): void {
|
protected notifyAttachedBoardsChanged(
|
||||||
|
event: AttachedBoardsChangeEvent
|
||||||
|
): void {
|
||||||
if (!AttachedBoardsChangeEvent.isEmpty(event)) {
|
if (!AttachedBoardsChangeEvent.isEmpty(event)) {
|
||||||
this.logger.info('Attached boards and available ports changed:');
|
this.logger.info('Attached boards and available ports changed:');
|
||||||
this.logger.info(AttachedBoardsChangeEvent.toString(event));
|
this.logger.info(AttachedBoardsChangeEvent.toString(event));
|
||||||
this.logger.info(`------------------------------------------`);
|
this.logger.info('------------------------------------------');
|
||||||
}
|
}
|
||||||
this._attachedBoards = event.newState.boards;
|
this._attachedBoards = event.newState.boards;
|
||||||
this._availablePorts = event.newState.ports;
|
this._availablePorts = event.newState.ports;
|
||||||
|
this.onAvailablePortsChangedEmitter.fire(this._availablePorts);
|
||||||
this.reconcileAvailableBoards().then(() => this.tryReconnect());
|
this.reconcileAvailableBoards().then(() => this.tryReconnect());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -105,12 +115,19 @@ export class BoardsServiceProvider implements FrontendApplicationContribution {
|
|||||||
const { selectedBoard } = this.boardsConfig;
|
const { selectedBoard } = this.boardsConfig;
|
||||||
const { installedVersion, id } = event.item;
|
const { installedVersion, id } = event.item;
|
||||||
if (selectedBoard) {
|
if (selectedBoard) {
|
||||||
const installedBoard = event.item.boards.find(({ name }) => name === selectedBoard.name);
|
const installedBoard = event.item.boards.find(
|
||||||
if (installedBoard && (!selectedBoard.fqbn || selectedBoard.fqbn === installedBoard.fqbn)) {
|
({ name }) => name === selectedBoard.name
|
||||||
this.logger.info(`Board package ${id}[${installedVersion}] was installed. Updating the FQBN of the currently selected ${selectedBoard.name} board. [FQBN: ${installedBoard.fqbn}]`);
|
);
|
||||||
|
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 = {
|
||||||
...this.boardsConfig,
|
...this.boardsConfig,
|
||||||
selectedBoard: installedBoard
|
selectedBoard: installedBoard,
|
||||||
};
|
};
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -118,13 +135,32 @@ export class BoardsServiceProvider implements FrontendApplicationContribution {
|
|||||||
// This logic handles it "gracefully" by unselecting the board, so that we can avoid no FQBN is set error.
|
// This logic handles it "gracefully" by unselecting the board, so that we can avoid no FQBN is set error.
|
||||||
// https://github.com/arduino/arduino-cli/issues/620
|
// https://github.com/arduino/arduino-cli/issues/620
|
||||||
// https://github.com/arduino/arduino-pro-ide/issues/374
|
// https://github.com/arduino/arduino-pro-ide/issues/374
|
||||||
if (BoardWithPackage.is(selectedBoard) && selectedBoard.packageId === event.item.id && !installedBoard) {
|
if (
|
||||||
this.messageService.warn(`Could not find previously selected board '${selectedBoard.name}' in installed platform '${event.item.name}'. Please manually reselect the board you want to use. Do you want to reselect it now?`, 'Reselect later', 'Yes').then(async answer => {
|
BoardWithPackage.is(selectedBoard) &&
|
||||||
if (answer === 'Yes') {
|
selectedBoard.packageId === event.item.id &&
|
||||||
this.commandService.executeCommand(ArduinoCommands.OPEN_BOARDS_DIALOG.id, selectedBoard.name);
|
!installedBoard
|
||||||
|
) {
|
||||||
|
const yes = nls.localize('vscode/extensionsUtils/yes', 'Yes');
|
||||||
|
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,
|
||||||
|
event.item.name
|
||||||
|
),
|
||||||
|
nls.localize('arduino/board/reselectLater', 'Reselect later'),
|
||||||
|
yes
|
||||||
|
)
|
||||||
|
.then(async (answer) => {
|
||||||
|
if (answer === yes) {
|
||||||
|
this.commandService.executeCommand(
|
||||||
|
ArduinoCommands.OPEN_BOARDS_DIALOG.id,
|
||||||
|
selectedBoard.name
|
||||||
|
);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
this.boardsConfig = {}
|
this.boardsConfig = {};
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// Trigger a board re-set. See: https://github.com/arduino/arduino-cli/issues/954
|
// Trigger a board re-set. See: https://github.com/arduino/arduino-cli/issues/954
|
||||||
@@ -137,16 +173,37 @@ export class BoardsServiceProvider implements FrontendApplicationContribution {
|
|||||||
this.logger.info('Boards package uninstalled: ', JSON.stringify(event));
|
this.logger.info('Boards package uninstalled: ', JSON.stringify(event));
|
||||||
const { selectedBoard } = this.boardsConfig;
|
const { selectedBoard } = this.boardsConfig;
|
||||||
if (selectedBoard && selectedBoard.fqbn) {
|
if (selectedBoard && selectedBoard.fqbn) {
|
||||||
const uninstalledBoard = event.item.boards.find(({ name }) => name === selectedBoard.name);
|
const uninstalledBoard = event.item.boards.find(
|
||||||
|
({ name }) => name === selectedBoard.name
|
||||||
|
);
|
||||||
if (uninstalledBoard && uninstalledBoard.fqbn === selectedBoard.fqbn) {
|
if (uninstalledBoard && uninstalledBoard.fqbn === selectedBoard.fqbn) {
|
||||||
this.logger.info(`Board package ${event.item.id} was uninstalled. Discarding the FQBN of the currently selected ${selectedBoard.name} board.`);
|
// We should not unset the FQBN, if the selected board is an attached, recognized board.
|
||||||
|
// Attach Uno and install AVR, select Uno. Uninstall the AVR core while Uno is selected. We do not want to discard the FQBN of the Uno board.
|
||||||
|
// Dev note: We cannot assume the `selectedBoard` is a type of `AvailableBoard`.
|
||||||
|
// When the user selects an `AvailableBoard` it works, but between app start/stops,
|
||||||
|
// it is just a FQBN, so we need to find the `selected` board among the `AvailableBoards`
|
||||||
|
const selectedAvailableBoard = AvailableBoard.is(selectedBoard)
|
||||||
|
? selectedBoard
|
||||||
|
: this._availableBoards.find((availableBoard) =>
|
||||||
|
Board.sameAs(availableBoard, selectedBoard)
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
selectedAvailableBoard &&
|
||||||
|
selectedAvailableBoard.selected &&
|
||||||
|
selectedAvailableBoard.state === AvailableBoard.State.recognized
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.logger.info(
|
||||||
|
`Board package ${event.item.id} was uninstalled. Discarding the FQBN of the currently selected ${selectedBoard.name} board.`
|
||||||
|
);
|
||||||
const selectedBoardWithoutFqbn = {
|
const selectedBoardWithoutFqbn = {
|
||||||
name: selectedBoard.name
|
name: selectedBoard.name,
|
||||||
// No FQBN
|
// No FQBN
|
||||||
};
|
};
|
||||||
this.boardsConfig = {
|
this.boardsConfig = {
|
||||||
...this.boardsConfig,
|
...this.boardsConfig,
|
||||||
selectedBoard: selectedBoardWithoutFqbn
|
selectedBoard: selectedBoardWithoutFqbn,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -154,24 +211,31 @@ export class BoardsServiceProvider implements FrontendApplicationContribution {
|
|||||||
|
|
||||||
protected async tryReconnect(): Promise<boolean> {
|
protected async tryReconnect(): Promise<boolean> {
|
||||||
if (this.latestValidBoardsConfig && !this.canUploadTo(this.boardsConfig)) {
|
if (this.latestValidBoardsConfig && !this.canUploadTo(this.boardsConfig)) {
|
||||||
for (const board of this.availableBoards.filter(({ state }) => state !== AvailableBoard.State.incomplete)) {
|
for (const board of this.availableBoards.filter(
|
||||||
if (this.latestValidBoardsConfig.selectedBoard.fqbn === board.fqbn
|
({ state }) => state !== AvailableBoard.State.incomplete
|
||||||
&& this.latestValidBoardsConfig.selectedBoard.name === board.name
|
)) {
|
||||||
&& Port.sameAs(this.latestValidBoardsConfig.selectedPort, board.port)) {
|
if (
|
||||||
|
this.latestValidBoardsConfig.selectedBoard.fqbn === board.fqbn &&
|
||||||
|
this.latestValidBoardsConfig.selectedBoard.name === board.name &&
|
||||||
|
Port.sameAs(this.latestValidBoardsConfig.selectedPort, board.port)
|
||||||
|
) {
|
||||||
this.boardsConfig = this.latestValidBoardsConfig;
|
this.boardsConfig = this.latestValidBoardsConfig;
|
||||||
return true;
|
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.
|
// 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`.
|
// See documentation on `latestValidBoardsConfig`.
|
||||||
for (const board of this.availableBoards.filter(({ state }) => state !== AvailableBoard.State.incomplete)) {
|
for (const board of this.availableBoards.filter(
|
||||||
if (this.latestValidBoardsConfig.selectedBoard.fqbn === board.fqbn
|
({ state }) => state !== AvailableBoard.State.incomplete
|
||||||
&& this.latestValidBoardsConfig.selectedBoard.name === board.name) {
|
)) {
|
||||||
|
if (
|
||||||
|
this.latestValidBoardsConfig.selectedBoard.fqbn === board.fqbn &&
|
||||||
|
this.latestValidBoardsConfig.selectedBoard.name === board.name &&
|
||||||
|
this.latestValidBoardsConfig.selectedPort.protocol === board.port?.protocol
|
||||||
|
) {
|
||||||
this.boardsConfig = {
|
this.boardsConfig = {
|
||||||
...this.latestValidBoardsConfig,
|
...this.latestValidBoardsConfig,
|
||||||
selectedPort: board.port
|
selectedPort: board.port,
|
||||||
};
|
};
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -181,11 +245,19 @@ export class BoardsServiceProvider implements FrontendApplicationContribution {
|
|||||||
}
|
}
|
||||||
|
|
||||||
set boardsConfig(config: BoardsConfig.Config) {
|
set boardsConfig(config: BoardsConfig.Config) {
|
||||||
this.doSetBoardsConfig(config);
|
this.setBoardsConfig(config);
|
||||||
this.saveState().finally(() => this.reconcileAvailableBoards().finally(() => this.onBoardsConfigChangedEmitter.fire(this._boardsConfig)));
|
this.saveState().finally(() =>
|
||||||
|
this.reconcileAvailableBoards().finally(() =>
|
||||||
|
this.onBoardsConfigChangedEmitter.fire(this._boardsConfig)
|
||||||
|
)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected doSetBoardsConfig(config: BoardsConfig.Config): void {
|
get boardsConfig(): BoardsConfig.Config {
|
||||||
|
return this._boardsConfig;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected setBoardsConfig(config: BoardsConfig.Config): void {
|
||||||
this.logger.info('Board config changed: ', JSON.stringify(config));
|
this.logger.info('Board config changed: ', JSON.stringify(config));
|
||||||
this._boardsConfig = config;
|
this._boardsConfig = config;
|
||||||
this.latestBoardsConfig = this._boardsConfig;
|
this.latestBoardsConfig = this._boardsConfig;
|
||||||
@@ -194,42 +266,27 @@ export class BoardsServiceProvider implements FrontendApplicationContribution {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async searchBoards({ query, cores }: { query?: string, cores?: string[] }): Promise<Array<BoardWithPackage>> {
|
async searchBoards({
|
||||||
const boards = await this.boardsService.allBoards({});
|
query,
|
||||||
const coresFilter = !!cores && cores.length
|
cores,
|
||||||
? ((toFilter: BoardWithPackage) => cores.some(core => core === toFilter.packageName || core === toFilter.packageId))
|
}: {
|
||||||
: () => true;
|
query?: string;
|
||||||
if (!query) {
|
cores?: string[];
|
||||||
return boards.filter(coresFilter).sort(Board.compare);
|
}): Promise<BoardWithPackage[]> {
|
||||||
}
|
const boards = await this.boardsService.searchBoards({ query });
|
||||||
const toMatch = ((toFilter: BoardWithPackage) => (({ board: toFilter, matches: monaco.filters.matchesFuzzy(query, toFilter.name, true) })));
|
return boards;
|
||||||
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 {
|
async selectedBoardUserFields(): Promise<BoardUserField[]> {
|
||||||
return this._boardsConfig;
|
if (!this._boardsConfig.selectedBoard || !this._boardsConfig.selectedPort) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
const fqbn = this._boardsConfig.selectedBoard.fqbn;
|
||||||
|
if (!fqbn) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
const protocol = this._boardsConfig.selectedPort.protocol;
|
||||||
|
return await this.boardsService.getBoardUserFields({ fqbn, protocol });
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -237,15 +294,20 @@ export class BoardsServiceProvider implements FrontendApplicationContribution {
|
|||||||
*/
|
*/
|
||||||
canVerify(
|
canVerify(
|
||||||
config: BoardsConfig.Config | undefined = this.boardsConfig,
|
config: BoardsConfig.Config | undefined = this.boardsConfig,
|
||||||
options: { silent: boolean } = { silent: true }): config is BoardsConfig.Config & { selectedBoard: Board } {
|
options: { silent: boolean } = { silent: true }
|
||||||
|
): config is BoardsConfig.Config & { selectedBoard: Board } {
|
||||||
if (!config) {
|
if (!config) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!config.selectedBoard) {
|
if (!config.selectedBoard) {
|
||||||
if (!options.silent) {
|
if (!options.silent) {
|
||||||
this.messageService.warn('No boards selected.', { timeout: 3000 });
|
this.messageService.warn(
|
||||||
|
nls.localize('arduino/board/noneSelected', 'No boards selected.'),
|
||||||
|
{
|
||||||
|
timeout: 3000,
|
||||||
|
}
|
||||||
|
);
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -258,8 +320,8 @@ export class BoardsServiceProvider implements FrontendApplicationContribution {
|
|||||||
*/
|
*/
|
||||||
canUploadTo(
|
canUploadTo(
|
||||||
config: BoardsConfig.Config | undefined = this.boardsConfig,
|
config: BoardsConfig.Config | undefined = this.boardsConfig,
|
||||||
options: { silent: boolean } = { silent: true }): config is RecursiveRequired<BoardsConfig.Config> {
|
options: { silent: boolean } = { silent: true }
|
||||||
|
): config is RecursiveRequired<BoardsConfig.Config> {
|
||||||
if (!this.canVerify(config, options)) {
|
if (!this.canVerify(config, options)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -267,14 +329,30 @@ export class BoardsServiceProvider implements FrontendApplicationContribution {
|
|||||||
const { name } = config.selectedBoard;
|
const { name } = config.selectedBoard;
|
||||||
if (!config.selectedPort) {
|
if (!config.selectedPort) {
|
||||||
if (!options.silent) {
|
if (!options.silent) {
|
||||||
this.messageService.warn(`No ports selected for board: '${name}'.`, { timeout: 3000 });
|
this.messageService.warn(
|
||||||
|
nls.localize(
|
||||||
|
'arduino/board/noPortsSelected',
|
||||||
|
"No ports selected for board: '{0}'.",
|
||||||
|
name
|
||||||
|
),
|
||||||
|
{
|
||||||
|
timeout: 3000,
|
||||||
|
}
|
||||||
|
);
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!config.selectedBoard.fqbn) {
|
if (!config.selectedBoard.fqbn) {
|
||||||
if (!options.silent) {
|
if (!options.silent) {
|
||||||
this.messageService.warn(`The FQBN is not available for the selected board ${name}. Do you have the corresponding core installed?`, { timeout: 3000 });
|
this.messageService.warn(
|
||||||
|
nls.localize(
|
||||||
|
'arduino/board/noFQBN',
|
||||||
|
'The FQBN is not available for the selected board "{0}". Do you have the corresponding core installed?',
|
||||||
|
name
|
||||||
|
),
|
||||||
|
{ timeout: 3000 }
|
||||||
|
);
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -286,19 +364,33 @@ export class BoardsServiceProvider implements FrontendApplicationContribution {
|
|||||||
return this._availableBoards;
|
return this._availableBoards;
|
||||||
}
|
}
|
||||||
|
|
||||||
async waitUntilAvailable(what: Board & { port: Port }, timeout?: number): Promise<void> {
|
async waitUntilAvailable(
|
||||||
|
what: Board & { port: Port },
|
||||||
|
timeout?: number
|
||||||
|
): Promise<void> {
|
||||||
const find = (needle: Board & { port: Port }, haystack: AvailableBoard[]) =>
|
const find = (needle: Board & { port: Port }, haystack: AvailableBoard[]) =>
|
||||||
haystack.find(board => Board.equals(needle, board) && Port.equals(needle.port, board.port));
|
haystack.find(
|
||||||
const timeoutTask = !!timeout && timeout > 0
|
(board) =>
|
||||||
? new Promise<void>((_, reject) => setTimeout(() => reject(new Error(`Timeout after ${timeout} ms.`)), timeout))
|
Board.equals(needle, board) && Port.sameAs(needle.port, board.port)
|
||||||
: new Promise<void>(() => { /* never */ });
|
);
|
||||||
const waitUntilTask = new Promise<void>(resolve => {
|
const timeoutTask =
|
||||||
|
!!timeout && timeout > 0
|
||||||
|
? new Promise<void>((_, reject) =>
|
||||||
|
setTimeout(
|
||||||
|
() => reject(new Error(`Timeout after ${timeout} ms.`)),
|
||||||
|
timeout
|
||||||
|
)
|
||||||
|
)
|
||||||
|
: new Promise<void>(() => {
|
||||||
|
/* never */
|
||||||
|
});
|
||||||
|
const waitUntilTask = new Promise<void>((resolve) => {
|
||||||
let candidate = find(what, this.availableBoards);
|
let candidate = find(what, this.availableBoards);
|
||||||
if (candidate) {
|
if (candidate) {
|
||||||
resolve();
|
resolve();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const disposable = this.onAvailableBoardsChanged(availableBoards => {
|
const disposable = this.onAvailableBoardsChanged((availableBoards) => {
|
||||||
candidate = find(what, availableBoards);
|
candidate = find(what, availableBoards);
|
||||||
if (candidate) {
|
if (candidate) {
|
||||||
disposable.dispose();
|
disposable.dispose();
|
||||||
@@ -310,70 +402,118 @@ export class BoardsServiceProvider implements FrontendApplicationContribution {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected async reconcileAvailableBoards(): Promise<void> {
|
protected async reconcileAvailableBoards(): Promise<void> {
|
||||||
const attachedBoards = this._attachedBoards;
|
|
||||||
const availablePorts = this._availablePorts;
|
const availablePorts = this._availablePorts;
|
||||||
// Unset the port on the user's config, if it is not available anymore.
|
// 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))) {
|
if (
|
||||||
this.doSetBoardsConfig({ selectedBoard: this.boardsConfig.selectedBoard, selectedPort: undefined });
|
this.boardsConfig.selectedPort &&
|
||||||
|
!availablePorts.some((port) =>
|
||||||
|
Port.sameAs(port, this.boardsConfig.selectedPort)
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
this.setBoardsConfig({
|
||||||
|
selectedBoard: this.boardsConfig.selectedBoard,
|
||||||
|
selectedPort: undefined,
|
||||||
|
});
|
||||||
this.onBoardsConfigChangedEmitter.fire(this._boardsConfig);
|
this.onBoardsConfigChangedEmitter.fire(this._boardsConfig);
|
||||||
}
|
}
|
||||||
const boardsConfig = this.boardsConfig;
|
const boardsConfig = this.boardsConfig;
|
||||||
const currentAvailableBoards = this._availableBoards;
|
const currentAvailableBoards = this._availableBoards;
|
||||||
const availableBoards: AvailableBoard[] = [];
|
const availableBoards: AvailableBoard[] = [];
|
||||||
const availableBoardPorts = availablePorts.filter(Port.isBoardPort);
|
const attachedBoards = this._attachedBoards.filter(({ port }) => !!port);
|
||||||
const attachedSerialBoards = attachedBoards.filter(({ port }) => !!port);
|
const availableBoardPorts = availablePorts.filter((port) => {
|
||||||
|
if (port.protocol === 'serial') {
|
||||||
|
// We always show all serial ports, even if there
|
||||||
|
// is no recognized board connected to it
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// All other ports with different protocol are
|
||||||
|
// only shown if there is a recognized board
|
||||||
|
// connected
|
||||||
|
for (const board of attachedBoards) {
|
||||||
|
if (board.port?.address === port.address) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
|
||||||
for (const boardPort of availableBoardPorts) {
|
for (const boardPort of availableBoardPorts) {
|
||||||
let state = AvailableBoard.State.incomplete; // Initial pessimism.
|
const board = attachedBoards.find(({ port }) =>
|
||||||
let board = attachedSerialBoards.find(({ port }) => Port.sameAs(boardPort, port));
|
Port.sameAs(boardPort, port)
|
||||||
|
);
|
||||||
|
const lastSelectedBoard = await this.getLastSelectedBoardOnPort(
|
||||||
|
boardPort
|
||||||
|
);
|
||||||
|
|
||||||
|
let availableBoard = {} as AvailableBoard;
|
||||||
if (board) {
|
if (board) {
|
||||||
state = AvailableBoard.State.recognized;
|
availableBoard = {
|
||||||
} else {
|
...board,
|
||||||
|
state: AvailableBoard.State.recognized,
|
||||||
|
selected: BoardsConfig.Config.sameAs(boardsConfig, board),
|
||||||
|
port: boardPort,
|
||||||
|
};
|
||||||
|
} else if (lastSelectedBoard) {
|
||||||
// If the selected board is not recognized because it is a 3rd party board: https://github.com/arduino/arduino-cli/issues/623
|
// 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
|
// 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);
|
availableBoard = {
|
||||||
if (lastSelectedBoard) {
|
|
||||||
board = {
|
|
||||||
...lastSelectedBoard,
|
...lastSelectedBoard,
|
||||||
port: boardPort
|
state: AvailableBoard.State.guessed,
|
||||||
|
selected: BoardsConfig.Config.sameAs(boardsConfig, lastSelectedBoard),
|
||||||
|
port: boardPort,
|
||||||
};
|
};
|
||||||
state = AvailableBoard.State.guessed;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!board) {
|
|
||||||
availableBoards.push({ name: 'Unknown', port: boardPort, state });
|
|
||||||
} else {
|
} else {
|
||||||
const selected = BoardsConfig.Config.sameAs(boardsConfig, board);
|
availableBoard = {
|
||||||
availableBoards.push({ ...board, state, selected, port: boardPort });
|
name: nls.localize('arduino/common/unknown', 'Unknown'),
|
||||||
|
port: boardPort,
|
||||||
|
state: AvailableBoard.State.incomplete,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
availableBoards.push(availableBoard);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (boardsConfig.selectedBoard && !availableBoards.some(({ selected }) => selected)) {
|
if (
|
||||||
|
boardsConfig.selectedBoard &&
|
||||||
|
!availableBoards.some(({ selected }) => selected)
|
||||||
|
) {
|
||||||
|
// If the selected board has the same port of an unknown board
|
||||||
|
// that is already in availableBoards we might get a duplicate port.
|
||||||
|
// So we remove the one already in the array and add the selected one.
|
||||||
|
const found = availableBoards.findIndex(
|
||||||
|
(board) => board.port?.address === boardsConfig.selectedPort?.address
|
||||||
|
);
|
||||||
|
if (found >= 0) {
|
||||||
|
availableBoards.splice(found, 1);
|
||||||
|
}
|
||||||
availableBoards.push({
|
availableBoards.push({
|
||||||
...boardsConfig.selectedBoard,
|
...boardsConfig.selectedBoard,
|
||||||
port: boardsConfig.selectedPort,
|
port: boardsConfig.selectedPort,
|
||||||
selected: true,
|
selected: true,
|
||||||
state: AvailableBoard.State.incomplete
|
state: AvailableBoard.State.incomplete,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const sortedAvailableBoards = availableBoards.sort(AvailableBoard.compare);
|
availableBoards.sort(AvailableBoard.compare);
|
||||||
let hasChanged = sortedAvailableBoards.length !== currentAvailableBoards.length;
|
|
||||||
for (let i = 0; !hasChanged && i < sortedAvailableBoards.length; i++) {
|
let hasChanged = availableBoards.length !== currentAvailableBoards.length;
|
||||||
hasChanged = AvailableBoard.compare(sortedAvailableBoards[i], currentAvailableBoards[i]) !== 0;
|
for (let i = 0; !hasChanged && i < availableBoards.length; i++) {
|
||||||
|
const [left, right] = [availableBoards[i], currentAvailableBoards[i]];
|
||||||
|
hasChanged =
|
||||||
|
!!AvailableBoard.compare(left, right) ||
|
||||||
|
left.selected !== right.selected;
|
||||||
}
|
}
|
||||||
if (hasChanged) {
|
if (hasChanged) {
|
||||||
this._availableBoards = sortedAvailableBoards;
|
this._availableBoards = availableBoards;
|
||||||
this.onAvailableBoardsChangedEmitter.fire(this._availableBoards);
|
this.onAvailableBoardsChangedEmitter.fire(this._availableBoards);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected async getLastSelectedBoardOnPort(port: Port | string | undefined): Promise<Board | undefined> {
|
protected async getLastSelectedBoardOnPort(
|
||||||
if (!port) {
|
port: Port
|
||||||
return undefined;
|
): Promise<Board | undefined> {
|
||||||
}
|
|
||||||
const key = this.getLastSelectedBoardOnPortKey(port);
|
const key = this.getLastSelectedBoardOnPortKey(port);
|
||||||
return this.storageService.getData<Board>(key);
|
return this.getData<Board>(key);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected async saveState(): Promise<void> {
|
protected async saveState(): Promise<void> {
|
||||||
@@ -384,21 +524,24 @@ export class BoardsServiceProvider implements FrontendApplicationContribution {
|
|||||||
const { selectedBoard, selectedPort } = this.boardsConfig;
|
const { selectedBoard, selectedPort } = this.boardsConfig;
|
||||||
if (selectedBoard && selectedPort) {
|
if (selectedBoard && selectedPort) {
|
||||||
const key = this.getLastSelectedBoardOnPortKey(selectedPort);
|
const key = this.getLastSelectedBoardOnPortKey(selectedPort);
|
||||||
await this.storageService.setData(key, selectedBoard);
|
await this.setData(key, selectedBoard);
|
||||||
}
|
}
|
||||||
await Promise.all([
|
await Promise.all([
|
||||||
this.storageService.setData('latest-valid-boards-config', this.latestValidBoardsConfig),
|
this.setData('latest-valid-boards-config', this.latestValidBoardsConfig),
|
||||||
this.storageService.setData('latest-boards-config', this.latestBoardsConfig)
|
this.setData('latest-boards-config', this.latestBoardsConfig),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected getLastSelectedBoardOnPortKey(port: Port | string): string {
|
protected getLastSelectedBoardOnPortKey(port: Port | string): string {
|
||||||
// TODO: we lose the port's `protocol` info (`serial`, `network`, etc.) here if the `port` is a `string`.
|
// TODO: we lose the port's `protocol` info (`serial`, `network`, etc.) here if the `port` is a `string`.
|
||||||
return `last-selected-board-on-port:${typeof port === 'string' ? port : Port.toString(port)}`;
|
return `last-selected-board-on-port:${typeof port === 'string' ? port : port.address
|
||||||
|
}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected async loadState(): Promise<void> {
|
protected async loadState(): Promise<void> {
|
||||||
const storedLatestValidBoardsConfig = await this.storageService.getData<RecursiveRequired<BoardsConfig.Config>>('latest-valid-boards-config');
|
const storedLatestValidBoardsConfig = await this.getData<
|
||||||
|
RecursiveRequired<BoardsConfig.Config>
|
||||||
|
>('latest-valid-boards-config');
|
||||||
if (storedLatestValidBoardsConfig) {
|
if (storedLatestValidBoardsConfig) {
|
||||||
this.latestValidBoardsConfig = storedLatestValidBoardsConfig;
|
this.latestValidBoardsConfig = storedLatestValidBoardsConfig;
|
||||||
if (this.canUploadTo(this.latestValidBoardsConfig)) {
|
if (this.canUploadTo(this.latestValidBoardsConfig)) {
|
||||||
@@ -406,13 +549,36 @@ export class BoardsServiceProvider implements FrontendApplicationContribution {
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// If we could not restore the latest valid config, try to restore something, the board at least.
|
// If we could not restore the latest valid config, try to restore something, the board at least.
|
||||||
const storedLatestBoardsConfig = await this.storageService.getData<BoardsConfig.Config | undefined>('latest-boards-config');
|
let storedLatestBoardsConfig = await this.getData<
|
||||||
|
BoardsConfig.Config | undefined
|
||||||
|
>('latest-boards-config');
|
||||||
|
// Try to get from the URL if it was not persisted.
|
||||||
|
if (!storedLatestBoardsConfig) {
|
||||||
|
storedLatestBoardsConfig = BoardsConfig.Config.getConfig(
|
||||||
|
new URL(window.location.href)
|
||||||
|
);
|
||||||
|
}
|
||||||
if (storedLatestBoardsConfig) {
|
if (storedLatestBoardsConfig) {
|
||||||
this.latestBoardsConfig = storedLatestBoardsConfig;
|
this.latestBoardsConfig = storedLatestBoardsConfig;
|
||||||
this.boardsConfig = this.latestBoardsConfig;
|
this.boardsConfig = this.latestBoardsConfig;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private setData<T>(key: string, value: T): Promise<void> {
|
||||||
|
return this.commandService.executeCommand(
|
||||||
|
StorageWrapper.Commands.SET_DATA.id,
|
||||||
|
key,
|
||||||
|
value
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private getData<T>(key: string): Promise<T | undefined> {
|
||||||
|
return this.commandService.executeCommand<T>(
|
||||||
|
StorageWrapper.Commands.GET_DATA.id,
|
||||||
|
key
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -428,7 +594,6 @@ export interface AvailableBoard extends Board {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export namespace AvailableBoard {
|
export namespace AvailableBoard {
|
||||||
|
|
||||||
export enum State {
|
export enum State {
|
||||||
/**
|
/**
|
||||||
* Retrieved from the CLI via the `board list` command.
|
* Retrieved from the CLI via the `board list` command.
|
||||||
@@ -441,47 +606,52 @@ export namespace AvailableBoard {
|
|||||||
/**
|
/**
|
||||||
* We do not know anything about this board, probably a 3rd party. The user has not selected a board for this port yet.
|
* We do not know anything about this board, probably a 3rd party. The user has not selected a board for this port yet.
|
||||||
*/
|
*/
|
||||||
'incomplete'
|
'incomplete',
|
||||||
}
|
}
|
||||||
|
|
||||||
export function is(board: any): board is AvailableBoard {
|
export function is(board: any): board is AvailableBoard {
|
||||||
return Board.is(board) && 'state' in board;
|
return Board.is(board) && 'state' in board;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function hasPort(board: AvailableBoard): board is AvailableBoard & { port: Port } {
|
export function hasPort(
|
||||||
|
board: AvailableBoard
|
||||||
|
): board is AvailableBoard & { port: Port } {
|
||||||
return !!board.port;
|
return !!board.port;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Available boards must be sorted in this order:
|
||||||
|
// 1. Serial with recognized boards
|
||||||
|
// 2. Serial with guessed boards
|
||||||
|
// 3. Serial with incomplete boards
|
||||||
|
// 4. Network with recognized boards
|
||||||
|
// 5. Other protocols with recognized boards
|
||||||
export const compare = (left: AvailableBoard, right: AvailableBoard) => {
|
export const compare = (left: AvailableBoard, right: AvailableBoard) => {
|
||||||
if (left.selected && !right.selected) {
|
if (left.port?.protocol === 'serial' && right.port?.protocol !== 'serial') {
|
||||||
return -1;
|
return -1;
|
||||||
}
|
} else if (
|
||||||
if (right.selected && !left.selected) {
|
left.port?.protocol !== 'serial' &&
|
||||||
|
right.port?.protocol === 'serial'
|
||||||
|
) {
|
||||||
|
return 1;
|
||||||
|
} else if (
|
||||||
|
left.port?.protocol === 'network' &&
|
||||||
|
right.port?.protocol !== 'network'
|
||||||
|
) {
|
||||||
|
return -1;
|
||||||
|
} else if (
|
||||||
|
left.port?.protocol !== 'network' &&
|
||||||
|
right.port?.protocol === 'network'
|
||||||
|
) {
|
||||||
|
return 1;
|
||||||
|
} else if (left.port?.protocol === right.port?.protocol) {
|
||||||
|
// We show all ports, including those that have guessed
|
||||||
|
// or unrecognized boards, so we must sort those too.
|
||||||
|
if (left.state < right.state) {
|
||||||
|
return -1;
|
||||||
|
} else if (left.state > right.state) {
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
let result = naturalCompare(left.name, right.name);
|
|
||||||
if (result !== 0) {
|
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
if (left.fqbn && right.fqbn) {
|
return naturalCompare(left.port?.address!, right.port?.address!);
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,11 @@ import { DisposableCollection } from '@theia/core/lib/common/disposable';
|
|||||||
import { Port } from '../../common/protocol';
|
import { Port } from '../../common/protocol';
|
||||||
import { BoardsConfig } from './boards-config';
|
import { BoardsConfig } from './boards-config';
|
||||||
import { ArduinoCommands } from '../arduino-commands';
|
import { ArduinoCommands } from '../arduino-commands';
|
||||||
import { BoardsServiceProvider, AvailableBoard } from './boards-service-provider';
|
import {
|
||||||
|
BoardsServiceProvider,
|
||||||
|
AvailableBoard,
|
||||||
|
} from './boards-service-provider';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
|
||||||
export interface BoardsDropDownListCoords {
|
export interface BoardsDropDownListCoords {
|
||||||
readonly top: number;
|
readonly top: number;
|
||||||
@@ -17,13 +21,12 @@ export interface BoardsDropDownListCoords {
|
|||||||
export namespace BoardsDropDown {
|
export namespace BoardsDropDown {
|
||||||
export interface Props {
|
export interface Props {
|
||||||
readonly coords: BoardsDropDownListCoords | 'hidden';
|
readonly coords: BoardsDropDownListCoords | 'hidden';
|
||||||
readonly items: Array<AvailableBoard & { onClick: () => void, port: Port }>;
|
readonly items: Array<AvailableBoard & { onClick: () => void; port: Port }>;
|
||||||
readonly openBoardsConfig: () => void;
|
readonly openBoardsConfig: () => void;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export class BoardsDropDown extends React.Component<BoardsDropDown.Props> {
|
export class BoardsDropDown extends React.Component<BoardsDropDown.Props> {
|
||||||
|
|
||||||
protected dropdownElement: HTMLElement;
|
protected dropdownElement: HTMLElement;
|
||||||
|
|
||||||
constructor(props: BoardsDropDown.Props) {
|
constructor(props: BoardsDropDown.Props) {
|
||||||
@@ -47,35 +50,71 @@ export class BoardsDropDown extends React.Component<BoardsDropDown.Props> {
|
|||||||
if (coords === 'hidden') {
|
if (coords === 'hidden') {
|
||||||
return '';
|
return '';
|
||||||
}
|
}
|
||||||
return <div className='arduino-boards-dropdown-list'
|
const footerLabel = nls.localize(
|
||||||
|
'arduino/board/openBoardsConfig',
|
||||||
|
'Select other board and port…'
|
||||||
|
);
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="arduino-boards-dropdown-list"
|
||||||
style={{
|
style={{
|
||||||
position: 'absolute',
|
position: 'absolute',
|
||||||
...coords
|
...coords,
|
||||||
}}>
|
}}
|
||||||
{this.renderItem({
|
>
|
||||||
label: 'Select Other Board & Port',
|
{items
|
||||||
onClick: () => this.props.openBoardsConfig()
|
.map(({ name, port, selected, onClick }) => ({
|
||||||
})}
|
label: nls.localize(
|
||||||
{items.map(({ name, port, selected, onClick }) => ({ label: `${name} at ${Port.toString(port)}`, selected, onClick })).map(this.renderItem)}
|
'arduino/board/boardListItem',
|
||||||
|
'{0} at {1}',
|
||||||
|
name,
|
||||||
|
Port.toString(port)
|
||||||
|
),
|
||||||
|
selected,
|
||||||
|
onClick,
|
||||||
|
}))
|
||||||
|
.map(this.renderItem)}
|
||||||
|
<div
|
||||||
|
key={footerLabel}
|
||||||
|
className="arduino-boards-dropdown-item arduino-board-dropdown-footer"
|
||||||
|
onClick={() => this.props.openBoardsConfig()}
|
||||||
|
>
|
||||||
|
<div>{footerLabel}</div>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected renderItem({ label, selected, onClick }: { label: string, selected?: boolean, onClick: () => void }): React.ReactNode {
|
protected renderItem({
|
||||||
return <div key={label} className={`arduino-boards-dropdown-item ${selected ? 'selected' : ''}`} onClick={onClick}>
|
label,
|
||||||
<div>
|
selected,
|
||||||
{label}
|
onClick,
|
||||||
</div>
|
}: {
|
||||||
{selected ? <span className='fa fa-check' /> : ''}
|
label: string;
|
||||||
|
selected?: boolean;
|
||||||
|
onClick: () => void;
|
||||||
|
}): React.ReactNode {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={label}
|
||||||
|
className={`arduino-boards-dropdown-item ${selected ? 'selected' : ''}`}
|
||||||
|
onClick={onClick}
|
||||||
|
>
|
||||||
|
<div>{label}</div>
|
||||||
|
{selected ? <span className="fa fa-check" /> : ''}
|
||||||
</div>
|
</div>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export class BoardsToolBarItem extends React.Component<BoardsToolBarItem.Props, BoardsToolBarItem.State> {
|
export class BoardsToolBarItem extends React.Component<
|
||||||
|
BoardsToolBarItem.Props,
|
||||||
|
BoardsToolBarItem.State
|
||||||
|
> {
|
||||||
static TOOLBAR_ID: 'boards-toolbar';
|
static TOOLBAR_ID: 'boards-toolbar';
|
||||||
|
|
||||||
protected readonly toDispose: DisposableCollection = new DisposableCollection();
|
protected readonly toDispose: DisposableCollection =
|
||||||
|
new DisposableCollection();
|
||||||
|
|
||||||
constructor(props: BoardsToolBarItem.Props) {
|
constructor(props: BoardsToolBarItem.Props) {
|
||||||
super(props);
|
super(props);
|
||||||
@@ -83,7 +122,7 @@ export class BoardsToolBarItem extends React.Component<BoardsToolBarItem.Props,
|
|||||||
const { availableBoards } = props.boardsServiceClient;
|
const { availableBoards } = props.boardsServiceClient;
|
||||||
this.state = {
|
this.state = {
|
||||||
availableBoards,
|
availableBoards,
|
||||||
coords: 'hidden'
|
coords: 'hidden',
|
||||||
};
|
};
|
||||||
|
|
||||||
document.addEventListener('click', () => {
|
document.addEventListener('click', () => {
|
||||||
@@ -92,7 +131,9 @@ export class BoardsToolBarItem extends React.Component<BoardsToolBarItem.Props,
|
|||||||
}
|
}
|
||||||
|
|
||||||
componentDidMount() {
|
componentDidMount() {
|
||||||
this.props.boardsServiceClient.onAvailableBoardsChanged(availableBoards => this.setState({ availableBoards }));
|
this.props.boardsServiceClient.onAvailableBoardsChanged((availableBoards) =>
|
||||||
|
this.setState({ availableBoards })
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
componentWillUnmount(): void {
|
componentWillUnmount(): void {
|
||||||
@@ -109,8 +150,8 @@ export class BoardsToolBarItem extends React.Component<BoardsToolBarItem.Props,
|
|||||||
top: rect.top,
|
top: rect.top,
|
||||||
left: rect.left,
|
left: rect.left,
|
||||||
width: rect.width,
|
width: rect.width,
|
||||||
paddingTop: rect.height
|
paddingTop: rect.height,
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
this.setState({ coords: 'hidden' });
|
this.setState({ coords: 'hidden' });
|
||||||
@@ -123,63 +164,68 @@ export class BoardsToolBarItem extends React.Component<BoardsToolBarItem.Props,
|
|||||||
render(): React.ReactNode {
|
render(): React.ReactNode {
|
||||||
const { coords, availableBoards } = this.state;
|
const { coords, availableBoards } = this.state;
|
||||||
const boardsConfig = this.props.boardsServiceClient.boardsConfig;
|
const boardsConfig = this.props.boardsServiceClient.boardsConfig;
|
||||||
const title = BoardsConfig.Config.toString(boardsConfig, { default: 'no board selected' });
|
const title = BoardsConfig.Config.toString(boardsConfig, {
|
||||||
|
default: nls.localize(
|
||||||
|
'arduino/common/noBoardSelected',
|
||||||
|
'No board selected'
|
||||||
|
),
|
||||||
|
});
|
||||||
const decorator = (() => {
|
const decorator = (() => {
|
||||||
const selectedBoard = availableBoards.find(({ selected }) => selected);
|
const selectedBoard = availableBoards.find(({ selected }) => selected);
|
||||||
if (!selectedBoard || !selectedBoard.port) {
|
if (!selectedBoard || !selectedBoard.port) {
|
||||||
return 'fa fa-times notAttached'
|
return 'fa fa-times notAttached';
|
||||||
}
|
}
|
||||||
if (selectedBoard.state === AvailableBoard.State.guessed) {
|
if (selectedBoard.state === AvailableBoard.State.guessed) {
|
||||||
return 'fa fa-exclamation-triangle guessed'
|
return 'fa fa-exclamation-triangle guessed';
|
||||||
}
|
}
|
||||||
return ''
|
return '';
|
||||||
})();
|
})();
|
||||||
|
|
||||||
return <React.Fragment>
|
return (
|
||||||
<div className='arduino-boards-toolbar-item-container'>
|
<React.Fragment>
|
||||||
<div className='arduino-boards-toolbar-item' title={title}>
|
<div className="arduino-boards-toolbar-item-container">
|
||||||
<div className='inner-container' onClick={this.show}>
|
<div className="arduino-boards-toolbar-item" title={title}>
|
||||||
|
<div className="inner-container" onClick={this.show}>
|
||||||
<span className={decorator} />
|
<span className={decorator} />
|
||||||
<div className='label noWrapInfo'>
|
<div className="label noWrapInfo">
|
||||||
<div className='noWrapInfo noselect'>
|
<div className="noWrapInfo noselect">{title}</div>
|
||||||
{title}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
<span className="fa fa-caret-down caret" />
|
||||||
<span className='fa fa-caret-down caret' />
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<BoardsDropDown
|
<BoardsDropDown
|
||||||
coords={coords}
|
coords={coords}
|
||||||
items={availableBoards.filter(AvailableBoard.hasPort).map(board => ({
|
items={availableBoards
|
||||||
|
.filter(AvailableBoard.hasPort)
|
||||||
|
.map((board) => ({
|
||||||
...board,
|
...board,
|
||||||
onClick: () => {
|
onClick: () => {
|
||||||
if (board.state === AvailableBoard.State.incomplete) {
|
if (board.state === AvailableBoard.State.incomplete) {
|
||||||
this.props.boardsServiceClient.boardsConfig = {
|
this.props.boardsServiceClient.boardsConfig = {
|
||||||
selectedPort: board.port
|
selectedPort: board.port,
|
||||||
};
|
};
|
||||||
this.openDialog();
|
this.openDialog();
|
||||||
} else {
|
} else {
|
||||||
this.props.boardsServiceClient.boardsConfig = {
|
this.props.boardsServiceClient.boardsConfig = {
|
||||||
selectedBoard: board,
|
selectedBoard: board,
|
||||||
selectedPort: board.port
|
selectedPort: board.port,
|
||||||
}
|
};
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
},
|
||||||
}))}
|
}))}
|
||||||
openBoardsConfig={this.openDialog}>
|
openBoardsConfig={this.openDialog}
|
||||||
</BoardsDropDown>
|
></BoardsDropDown>
|
||||||
</React.Fragment>;
|
</React.Fragment>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected openDialog = () => {
|
protected openDialog = () => {
|
||||||
this.props.commands.executeCommand(ArduinoCommands.OPEN_BOARDS_DIALOG.id);
|
this.props.commands.executeCommand(ArduinoCommands.OPEN_BOARDS_DIALOG.id);
|
||||||
this.setState({ coords: 'hidden' });
|
this.setState({ coords: 'hidden' });
|
||||||
};
|
};
|
||||||
|
|
||||||
}
|
}
|
||||||
export namespace BoardsToolBarItem {
|
export namespace BoardsToolBarItem {
|
||||||
|
|
||||||
export interface Props {
|
export interface Props {
|
||||||
readonly boardsServiceClient: BoardsServiceProvider;
|
readonly boardsServiceClient: BoardsServiceProvider;
|
||||||
readonly commands: CommandRegistry;
|
readonly commands: CommandRegistry;
|
||||||
@@ -189,5 +235,4 @@ export namespace BoardsToolBarItem {
|
|||||||
availableBoards: AvailableBoard[];
|
availableBoards: AvailableBoard[];
|
||||||
coords: BoardsDropDownListCoords | 'hidden';
|
coords: BoardsDropDownListCoords | 'hidden';
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,22 +5,20 @@ import { ListWidgetFrontendContribution } from '../widgets/component-list/list-w
|
|||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export class BoardsListWidgetFrontendContribution extends ListWidgetFrontendContribution<BoardsPackage> {
|
export class BoardsListWidgetFrontendContribution extends ListWidgetFrontendContribution<BoardsPackage> {
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
super({
|
super({
|
||||||
widgetId: BoardsListWidget.WIDGET_ID,
|
widgetId: BoardsListWidget.WIDGET_ID,
|
||||||
widgetName: BoardsListWidget.WIDGET_LABEL,
|
widgetName: BoardsListWidget.WIDGET_LABEL,
|
||||||
defaultWidgetOptions: {
|
defaultWidgetOptions: {
|
||||||
area: 'left',
|
area: 'left',
|
||||||
rank: 600
|
rank: 2,
|
||||||
},
|
},
|
||||||
toggleCommandId: `${BoardsListWidget.WIDGET_ID}:toggle`,
|
toggleCommandId: `${BoardsListWidget.WIDGET_ID}:toggle`,
|
||||||
toggleKeybinding: 'CtrlCmd+Shift+B'
|
toggleKeybinding: 'CtrlCmd+Shift+B',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async initializeLayout(): Promise<void> {
|
async initializeLayout(): Promise<void> {
|
||||||
this.openView();
|
this.openView();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,16 +0,0 @@
|
|||||||
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');
|
|
||||||
});
|
|
||||||
@@ -1,309 +0,0 @@
|
|||||||
import * as fuzzy from 'fuzzy';
|
|
||||||
import { inject, injectable, postConstruct, named } from 'inversify';
|
|
||||||
import { ILogger } from '@theia/core/lib/common/logger';
|
|
||||||
import { CommandContribution, CommandRegistry, Command } from '@theia/core/lib/common/command';
|
|
||||||
import { KeybindingContribution, KeybindingRegistry } from '@theia/core/lib/browser/keybinding';
|
|
||||||
import { QuickOpenItem, QuickOpenModel, QuickOpenMode, QuickOpenGroupItem } from '@theia/core/lib/common/quick-open-model';
|
|
||||||
import {
|
|
||||||
QuickOpenService,
|
|
||||||
QuickOpenHandler,
|
|
||||||
QuickOpenOptions,
|
|
||||||
QuickOpenItemOptions,
|
|
||||||
QuickOpenContribution,
|
|
||||||
QuickOpenActionProvider,
|
|
||||||
QuickOpenHandlerRegistry,
|
|
||||||
QuickOpenGroupItemOptions
|
|
||||||
} from '@theia/core/lib/browser/quick-open';
|
|
||||||
import { naturalCompare } from '../../../common/utils';
|
|
||||||
import { BoardsService, Port, Board, ConfigOption, ConfigValue } from '../../../common/protocol';
|
|
||||||
import { BoardsDataStore } from '../boards-data-store';
|
|
||||||
import { BoardsServiceProvider, AvailableBoard } from '../boards-service-provider';
|
|
||||||
import { NotificationCenter } from '../../notification-center';
|
|
||||||
|
|
||||||
@injectable()
|
|
||||||
export class BoardsQuickOpenService implements QuickOpenContribution, QuickOpenModel, QuickOpenHandler, CommandContribution, KeybindingContribution, Command {
|
|
||||||
|
|
||||||
readonly id = 'arduino-boards-quick-open';
|
|
||||||
readonly prefix = '|';
|
|
||||||
readonly description = 'Configure Available Boards';
|
|
||||||
readonly label: 'Configure Available Boards';
|
|
||||||
|
|
||||||
@inject(ILogger)
|
|
||||||
@named('boards-quick-open')
|
|
||||||
protected readonly logger: ILogger;
|
|
||||||
|
|
||||||
@inject(QuickOpenService)
|
|
||||||
protected readonly quickOpenService: QuickOpenService;
|
|
||||||
|
|
||||||
@inject(BoardsService)
|
|
||||||
protected readonly boardsService: BoardsService;
|
|
||||||
|
|
||||||
@inject(BoardsServiceProvider)
|
|
||||||
protected readonly boardsServiceClient: BoardsServiceProvider;
|
|
||||||
|
|
||||||
@inject(BoardsDataStore)
|
|
||||||
protected readonly boardsDataStore: BoardsDataStore;
|
|
||||||
|
|
||||||
@inject(NotificationCenter)
|
|
||||||
protected notificationCenter: NotificationCenter;
|
|
||||||
|
|
||||||
protected isOpen: boolean = false;
|
|
||||||
protected currentQuery: string = '';
|
|
||||||
// Attached boards plus the user's config.
|
|
||||||
protected availableBoards: AvailableBoard[] = [];
|
|
||||||
// Only for the `selected` one from the `availableBoards`. Note: the `port` of the `selected` is optional.
|
|
||||||
protected data: BoardsDataStore.Data = BoardsDataStore.Data.EMPTY;
|
|
||||||
protected allBoards: Board.Detailed[] = []
|
|
||||||
protected selectedBoard?: (AvailableBoard & { port: Port });
|
|
||||||
|
|
||||||
// `init` name is used by the `QuickOpenHandler`.
|
|
||||||
@postConstruct()
|
|
||||||
protected postConstruct(): void {
|
|
||||||
this.notificationCenter.onIndexUpdated(() => this.update(this.availableBoards));
|
|
||||||
this.boardsServiceClient.onAvailableBoardsChanged(availableBoards => this.update(availableBoards));
|
|
||||||
this.update(this.boardsServiceClient.availableBoards);
|
|
||||||
}
|
|
||||||
|
|
||||||
registerCommands(registry: CommandRegistry): void {
|
|
||||||
registry.registerCommand(this, { execute: () => this.open() });
|
|
||||||
}
|
|
||||||
|
|
||||||
registerKeybindings(registry: KeybindingRegistry): void {
|
|
||||||
registry.registerKeybinding({ command: this.id, keybinding: 'ctrlCmd+k ctrlCmd+b' });
|
|
||||||
}
|
|
||||||
|
|
||||||
registerQuickOpenHandlers(registry: QuickOpenHandlerRegistry): void {
|
|
||||||
registry.registerHandler(this);
|
|
||||||
}
|
|
||||||
|
|
||||||
getModel(): QuickOpenModel {
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
getOptions(): QuickOpenOptions {
|
|
||||||
let placeholder = '';
|
|
||||||
if (!this.selectedBoard) {
|
|
||||||
placeholder += 'No board selected.';
|
|
||||||
}
|
|
||||||
placeholder += 'Type to filter boards';
|
|
||||||
if (this.data.configOptions.length) {
|
|
||||||
placeholder += ' or use the ↓↑ keys to adjust the board settings...';
|
|
||||||
} else {
|
|
||||||
placeholder += '...';
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
placeholder,
|
|
||||||
fuzzyMatchLabel: true,
|
|
||||||
onClose: () => this.isOpen = false
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
open(): void {
|
|
||||||
this.isOpen = true;
|
|
||||||
this.quickOpenService.open(this, this.getOptions());
|
|
||||||
}
|
|
||||||
|
|
||||||
onType(
|
|
||||||
lookFor: string,
|
|
||||||
acceptor: (items: QuickOpenItem<QuickOpenItemOptions>[], actionProvider?: QuickOpenActionProvider) => void): void {
|
|
||||||
|
|
||||||
this.currentQuery = lookFor;
|
|
||||||
const fuzzyFilter = this.fuzzyFilter(lookFor);
|
|
||||||
const availableBoards = this.availableBoards.filter(AvailableBoard.hasPort).filter(({ name }) => fuzzyFilter(name));
|
|
||||||
const toAccept: QuickOpenItem<QuickOpenItemOptions>[] = [];
|
|
||||||
|
|
||||||
// Show the selected attached in a different group.
|
|
||||||
if (this.selectedBoard && fuzzyFilter(this.selectedBoard.name)) {
|
|
||||||
toAccept.push(this.toQuickItem(this.selectedBoard, { groupLabel: 'Selected Board' }));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Filter the selected from the attached ones.
|
|
||||||
toAccept.push(...availableBoards.filter(board => board !== this.selectedBoard).map((board, i) => {
|
|
||||||
let group: QuickOpenGroupItemOptions | undefined = undefined;
|
|
||||||
if (i === 0) {
|
|
||||||
// If no `selectedBoard`, then this item is the top one, no borders required.
|
|
||||||
group = { groupLabel: 'Attached Boards', showBorder: !!this.selectedBoard };
|
|
||||||
}
|
|
||||||
return this.toQuickItem(board, group);
|
|
||||||
}));
|
|
||||||
|
|
||||||
// Show the config only if the `input` is empty.
|
|
||||||
if (!lookFor.trim().length) {
|
|
||||||
toAccept.push(...this.data.configOptions.map((config, i) => {
|
|
||||||
let group: QuickOpenGroupItemOptions | undefined = undefined;
|
|
||||||
if (i === 0) {
|
|
||||||
group = { groupLabel: 'Board Settings', showBorder: true };
|
|
||||||
}
|
|
||||||
return this.toQuickItem(config, group);
|
|
||||||
}));
|
|
||||||
} else {
|
|
||||||
toAccept.push(...this.allBoards.filter(({ name }) => fuzzyFilter(name)).map((board, i) => {
|
|
||||||
let group: QuickOpenGroupItemOptions | undefined = undefined;
|
|
||||||
if (i === 0) {
|
|
||||||
group = { groupLabel: 'Boards', showBorder: true };
|
|
||||||
}
|
|
||||||
return this.toQuickItem(board, group);
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
acceptor(toAccept);
|
|
||||||
}
|
|
||||||
|
|
||||||
private fuzzyFilter(lookFor: string): (inputString: string) => boolean {
|
|
||||||
const shouldFilter = !!lookFor.trim().length;
|
|
||||||
return (inputString: string) => shouldFilter ? fuzzy.test(lookFor.toLocaleLowerCase(), inputString.toLocaleLowerCase()) : true;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected async update(availableBoards: AvailableBoard[]): Promise<void> {
|
|
||||||
// `selectedBoard` is not an attached board, we need to show the board settings for it (TODO: clarify!)
|
|
||||||
const selectedBoard = availableBoards.filter(AvailableBoard.hasPort).find(({ selected }) => selected);
|
|
||||||
const [data, boards] = await Promise.all([
|
|
||||||
selectedBoard && selectedBoard.fqbn ? this.boardsDataStore.getData(selectedBoard.fqbn) : Promise.resolve(BoardsDataStore.Data.EMPTY),
|
|
||||||
this.boardsService.allBoards({})
|
|
||||||
]);
|
|
||||||
this.allBoards = Board.decorateBoards(selectedBoard, boards)
|
|
||||||
.filter(board => !availableBoards.some(availableBoard => Board.sameAs(availableBoard, board)));
|
|
||||||
this.availableBoards = availableBoards;
|
|
||||||
this.data = data;
|
|
||||||
this.selectedBoard = selectedBoard;
|
|
||||||
|
|
||||||
if (this.isOpen) {
|
|
||||||
// Hack, to update the state without closing and reopening the quick open widget.
|
|
||||||
(this.quickOpenService as any).onType(this.currentQuery);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
protected toQuickItem(item: BoardsQuickOpenService.Item, group?: QuickOpenGroupItemOptions): QuickOpenItem<QuickOpenItemOptions> {
|
|
||||||
let options: QuickOpenItemOptions;
|
|
||||||
if (AvailableBoard.is(item)) {
|
|
||||||
const description = `on ${Port.toString(item.port)}`
|
|
||||||
options = {
|
|
||||||
label: `${item.name}`,
|
|
||||||
description,
|
|
||||||
descriptionHighlights: [
|
|
||||||
{
|
|
||||||
start: 0,
|
|
||||||
end: description.length
|
|
||||||
}
|
|
||||||
],
|
|
||||||
run: this.toRun(() => this.boardsServiceClient.boardsConfig = ({ selectedBoard: item, selectedPort: item.port }))
|
|
||||||
};
|
|
||||||
} else if (ConfigOption.is(item)) {
|
|
||||||
const selected = item.values.find(({ selected }) => selected);
|
|
||||||
const value = selected ? selected.label : 'Not set';
|
|
||||||
const label = `${item.label}: ${value}`;
|
|
||||||
options = {
|
|
||||||
label,
|
|
||||||
// Intended to match the value part of a board setting.
|
|
||||||
// NOTE: this does not work, as `fuzzyMatchLabel: true` is set. Manual highlighting is ignored, apparently.
|
|
||||||
labelHighlights: [
|
|
||||||
{
|
|
||||||
start: label.length - value.length,
|
|
||||||
end: label.length
|
|
||||||
}
|
|
||||||
],
|
|
||||||
run: (mode) => {
|
|
||||||
if (mode === QuickOpenMode.OPEN) {
|
|
||||||
this.setConfig(item);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
if (!selected) {
|
|
||||||
options.description = 'Not set';
|
|
||||||
};
|
|
||||||
} else {
|
|
||||||
options = {
|
|
||||||
label: `${item.name}`,
|
|
||||||
description: `${item.missing ? '' : `[installed with '${item.packageName}']`}`,
|
|
||||||
run: (mode) => {
|
|
||||||
if (mode === QuickOpenMode.OPEN) {
|
|
||||||
this.selectBoard(item);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
if (group) {
|
|
||||||
return new QuickOpenGroupItem<QuickOpenGroupItemOptions>({ ...options, ...group });
|
|
||||||
} else {
|
|
||||||
return new QuickOpenItem<QuickOpenItemOptions>(options);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
protected toRun(run: (() => void)): ((mode: QuickOpenMode) => boolean) {
|
|
||||||
return (mode) => {
|
|
||||||
if (mode !== QuickOpenMode.OPEN) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
run();
|
|
||||||
return true;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
protected async selectBoard(board: Board): Promise<void> {
|
|
||||||
const allPorts = this.availableBoards.filter(AvailableBoard.hasPort).map(({ port }) => port).sort(Port.compare);
|
|
||||||
const toItem = (port: Port) => new QuickOpenItem<QuickOpenItemOptions>({
|
|
||||||
label: Port.toString(port, { useLabel: true }),
|
|
||||||
run: this.toRun(() => {
|
|
||||||
this.boardsServiceClient.boardsConfig = {
|
|
||||||
selectedBoard: board,
|
|
||||||
selectedPort: port
|
|
||||||
};
|
|
||||||
})
|
|
||||||
});
|
|
||||||
const options = {
|
|
||||||
placeholder: `Select a port for '${board.name}'. Press 'Enter' to confirm or 'Escape' to cancel.`,
|
|
||||||
fuzzyMatchLabel: true
|
|
||||||
}
|
|
||||||
this.quickOpenService.open({
|
|
||||||
onType: (lookFor, acceptor) => {
|
|
||||||
const fuzzyFilter = this.fuzzyFilter(lookFor);
|
|
||||||
acceptor(allPorts.filter(({ address }) => fuzzyFilter(address)).map(toItem));
|
|
||||||
}
|
|
||||||
}, options);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected async setConfig(config: ConfigOption): Promise<void> {
|
|
||||||
const toItem = (value: ConfigValue) => new QuickOpenItem<QuickOpenItemOptions>({
|
|
||||||
label: value.label,
|
|
||||||
iconClass: value.selected ? 'fa fa-check' : '',
|
|
||||||
run: this.toRun(() => {
|
|
||||||
if (!this.selectedBoard) {
|
|
||||||
this.logger.warn(`Could not alter the boards settings. No board selected. ${JSON.stringify(config)}`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!this.selectedBoard.fqbn) {
|
|
||||||
this.logger.warn(`Could not alter the boards settings. The selected board does not have a FQBN. ${JSON.stringify(this.selectedBoard)}`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const { fqbn } = this.selectedBoard;
|
|
||||||
this.boardsDataStore.selectConfigOption({
|
|
||||||
fqbn,
|
|
||||||
option: config.option,
|
|
||||||
selectedValue: value.value
|
|
||||||
});
|
|
||||||
})
|
|
||||||
});
|
|
||||||
const options = {
|
|
||||||
placeholder: `Configure '${config.label}'. Press 'Enter' to confirm or 'Escape' to cancel.`,
|
|
||||||
fuzzyMatchLabel: true
|
|
||||||
}
|
|
||||||
this.quickOpenService.open({
|
|
||||||
onType: (lookFor, acceptor) => {
|
|
||||||
const fuzzyFilter = this.fuzzyFilter(lookFor);
|
|
||||||
acceptor(config.values
|
|
||||||
.filter(({ label }) => fuzzyFilter(label))
|
|
||||||
.sort((left, right) => naturalCompare(left.label, right.label))
|
|
||||||
.map(toItem));
|
|
||||||
}
|
|
||||||
}, options);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
export namespace BoardsQuickOpenService {
|
|
||||||
export type Item = AvailableBoard & { port: Port } | Board.Detailed | ConfigOption;
|
|
||||||
}
|
|
||||||
28
arduino-ide-extension/src/browser/components/ProgressBar.tsx
Normal file
28
arduino-ide-extension/src/browser/components/ProgressBar.tsx
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
import * as React from '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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,16 +1,21 @@
|
|||||||
import { inject, injectable } from 'inversify';
|
import { inject, injectable } from 'inversify';
|
||||||
import * as moment from 'moment';
|
import * as moment from 'moment';
|
||||||
import { remote } from 'electron';
|
import * as remote from '@theia/core/electron-shared/@electron/remote';
|
||||||
import { isOSX, isWindows } from '@theia/core/lib/common/os';
|
import { isOSX, isWindows } from '@theia/core/lib/common/os';
|
||||||
import { ClipboardService } from '@theia/core/lib/browser/clipboard-service';
|
import { ClipboardService } from '@theia/core/lib/browser/clipboard-service';
|
||||||
import { FrontendApplicationConfigProvider } from '@theia/core/lib/browser/frontend-application-config-provider';
|
import { FrontendApplicationConfigProvider } from '@theia/core/lib/browser/frontend-application-config-provider';
|
||||||
import { Contribution, Command, MenuModelRegistry, CommandRegistry } from './contribution';
|
import {
|
||||||
|
Contribution,
|
||||||
|
Command,
|
||||||
|
MenuModelRegistry,
|
||||||
|
CommandRegistry,
|
||||||
|
} from './contribution';
|
||||||
import { ArduinoMenus } from '../menu/arduino-menus';
|
import { ArduinoMenus } from '../menu/arduino-menus';
|
||||||
import { ConfigService } from '../../common/protocol';
|
import { ConfigService } from '../../common/protocol';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export class About extends Contribution {
|
export class About extends Contribution {
|
||||||
|
|
||||||
@inject(ClipboardService)
|
@inject(ClipboardService)
|
||||||
protected readonly clipboardService: ClipboardService;
|
protected readonly clipboardService: ClipboardService;
|
||||||
|
|
||||||
@@ -19,31 +24,51 @@ export class About extends Contribution {
|
|||||||
|
|
||||||
registerCommands(registry: CommandRegistry): void {
|
registerCommands(registry: CommandRegistry): void {
|
||||||
registry.registerCommand(About.Commands.ABOUT_APP, {
|
registry.registerCommand(About.Commands.ABOUT_APP, {
|
||||||
execute: () => this.showAbout()
|
execute: () => this.showAbout(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
registerMenus(registry: MenuModelRegistry): void {
|
registerMenus(registry: MenuModelRegistry): void {
|
||||||
registry.registerMenuAction(ArduinoMenus.HELP__ABOUT_GROUP, {
|
registry.registerMenuAction(ArduinoMenus.HELP__ABOUT_GROUP, {
|
||||||
commandId: About.Commands.ABOUT_APP.id,
|
commandId: About.Commands.ABOUT_APP.id,
|
||||||
label: `About ${this.applicationName}`,
|
label: nls.localize(
|
||||||
order: '0'
|
'arduino/about/label',
|
||||||
|
'About {0}',
|
||||||
|
this.applicationName
|
||||||
|
),
|
||||||
|
order: '0',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async showAbout(): Promise<void> {
|
async showAbout(): Promise<void> {
|
||||||
const { version, commit, status: cliStatus } = await this.configService.getVersion();
|
const {
|
||||||
|
version,
|
||||||
|
commit,
|
||||||
|
status: cliStatus,
|
||||||
|
} = await this.configService.getVersion();
|
||||||
const buildDate = this.buildDate;
|
const buildDate = this.buildDate;
|
||||||
const detail = (showAll: boolean) => `Version: ${remote.app.getVersion()}
|
const detail = (showAll: boolean) =>
|
||||||
Date: ${buildDate ? buildDate : 'dev build'}${buildDate && showAll ? ` (${this.ago(buildDate)})` : ''}
|
nls.localize(
|
||||||
CLI Version: ${version}${cliStatus ? ` ${cliStatus}` : ''} [${commit}]
|
'arduino/about/detail',
|
||||||
|
'Version: {0}\nDate: {1}{2}\nCLI Version: {3}{4} [{5}]\n\n{6}',
|
||||||
${showAll ? `Copyright © ${new Date().getFullYear()} Arduino SA` : ''}
|
remote.app.getVersion(),
|
||||||
`;
|
buildDate ? buildDate : nls.localize('', 'dev build'),
|
||||||
const ok = 'OK';
|
buildDate && showAll ? ` (${this.ago(buildDate)})` : '',
|
||||||
const copy = 'Copy';
|
version,
|
||||||
|
cliStatus ? ` ${cliStatus}` : '',
|
||||||
|
commit,
|
||||||
|
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 buttons = !isWindows && !isOSX ? [copy, ok] : [ok, copy];
|
||||||
const { response } = await remote.dialog.showMessageBox(remote.getCurrentWindow(), {
|
const { response } = await remote.dialog.showMessageBox(
|
||||||
|
remote.getCurrentWindow(),
|
||||||
|
{
|
||||||
message: `${this.applicationName}`,
|
message: `${this.applicationName}`,
|
||||||
title: `${this.applicationName}`,
|
title: `${this.applicationName}`,
|
||||||
type: 'info',
|
type: 'info',
|
||||||
@@ -51,8 +76,9 @@ ${showAll ? `Copyright © ${new Date().getFullYear()} Arduino SA` : ''}
|
|||||||
buttons,
|
buttons,
|
||||||
noLink: true,
|
noLink: true,
|
||||||
defaultId: buttons.indexOf(ok),
|
defaultId: buttons.indexOf(ok),
|
||||||
cancelId: buttons.indexOf(ok)
|
cancelId: buttons.indexOf(ok),
|
||||||
});
|
}
|
||||||
|
);
|
||||||
|
|
||||||
if (buttons[response] === copy) {
|
if (buttons[response] === copy) {
|
||||||
await this.clipboardService.writeText(detail(false).trim());
|
await this.clipboardService.writeText(detail(false).trim());
|
||||||
@@ -72,34 +98,93 @@ ${showAll ? `Copyright © ${new Date().getFullYear()} Arduino SA` : ''}
|
|||||||
const other = moment(isoTime);
|
const other = moment(isoTime);
|
||||||
let result = now.diff(other, 'minute');
|
let result = now.diff(other, 'minute');
|
||||||
if (result < 60) {
|
if (result < 60) {
|
||||||
return result === 1 ? `${result} minute ago` : `${result} minute ago`;
|
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');
|
result = now.diff(other, 'hour');
|
||||||
if (result < 25) {
|
if (result < 25) {
|
||||||
return result === 1 ? `${result} hour ago` : `${result} hours ago`;
|
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');
|
result = now.diff(other, 'day');
|
||||||
if (result < 8) {
|
if (result < 8) {
|
||||||
return result === 1 ? `${result} day ago` : `${result} days ago`;
|
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');
|
result = now.diff(other, 'week');
|
||||||
if (result < 5) {
|
if (result < 5) {
|
||||||
return result === 1 ? `${result} week ago` : `${result} weeks ago`;
|
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');
|
result = now.diff(other, 'month');
|
||||||
if (result < 13) {
|
if (result < 13) {
|
||||||
return result === 1 ? `${result} month ago` : `${result} months ago`;
|
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');
|
result = now.diff(other, 'year');
|
||||||
return result === 1 ? `${result} year ago` : `${result} years ago`;
|
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 About {
|
||||||
export namespace Commands {
|
export namespace Commands {
|
||||||
export const ABOUT_APP: Command = {
|
export const ABOUT_APP: Command = {
|
||||||
id: 'arduino-about'
|
id: 'arduino-about',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,26 +1,32 @@
|
|||||||
import { inject, injectable } from 'inversify';
|
import { inject, injectable } from 'inversify';
|
||||||
import { remote } from 'electron';
|
import * as remote from '@theia/core/electron-shared/@electron/remote';
|
||||||
import { ArduinoMenus } from '../menu/arduino-menus';
|
import { ArduinoMenus } from '../menu/arduino-menus';
|
||||||
import { SketchContribution, Command, CommandRegistry, MenuModelRegistry, URI } from './contribution';
|
import {
|
||||||
|
SketchContribution,
|
||||||
|
Command,
|
||||||
|
CommandRegistry,
|
||||||
|
MenuModelRegistry,
|
||||||
|
URI,
|
||||||
|
} from './contribution';
|
||||||
import { FileDialogService } from '@theia/filesystem/lib/browser';
|
import { FileDialogService } from '@theia/filesystem/lib/browser';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export class AddFile extends SketchContribution {
|
export class AddFile extends SketchContribution {
|
||||||
|
|
||||||
@inject(FileDialogService)
|
@inject(FileDialogService)
|
||||||
protected readonly fileDialogService: FileDialogService;
|
protected readonly fileDialogService: FileDialogService;
|
||||||
|
|
||||||
registerCommands(registry: CommandRegistry): void {
|
registerCommands(registry: CommandRegistry): void {
|
||||||
registry.registerCommand(AddFile.Commands.ADD_FILE, {
|
registry.registerCommand(AddFile.Commands.ADD_FILE, {
|
||||||
execute: () => this.addFile()
|
execute: () => this.addFile(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
registerMenus(registry: MenuModelRegistry): void {
|
registerMenus(registry: MenuModelRegistry): void {
|
||||||
registry.registerMenuAction(ArduinoMenus.SKETCH__UTILS_GROUP, {
|
registry.registerMenuAction(ArduinoMenus.SKETCH__UTILS_GROUP, {
|
||||||
commandId: AddFile.Commands.ADD_FILE.id,
|
commandId: AddFile.Commands.ADD_FILE.id,
|
||||||
label: 'Add File...',
|
label: nls.localize('arduino/contributions/addFile', 'Add File') + '...',
|
||||||
order: '2'
|
order: '2',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -30,10 +36,10 @@ export class AddFile extends SketchContribution {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const toAddUri = await this.fileDialogService.showOpenDialog({
|
const toAddUri = await this.fileDialogService.showOpenDialog({
|
||||||
title: 'Add File',
|
title: nls.localize('arduino/contributions/addFile', 'Add File'),
|
||||||
canSelectFiles: true,
|
canSelectFiles: true,
|
||||||
canSelectFolders: false,
|
canSelectFolders: false,
|
||||||
canSelectMany: false
|
canSelectMany: false,
|
||||||
});
|
});
|
||||||
if (!toAddUri) {
|
if (!toAddUri) {
|
||||||
return;
|
return;
|
||||||
@@ -45,24 +51,39 @@ export class AddFile extends SketchContribution {
|
|||||||
if (exists) {
|
if (exists) {
|
||||||
const { response } = await remote.dialog.showMessageBox({
|
const { response } = await remote.dialog.showMessageBox({
|
||||||
type: 'question',
|
type: 'question',
|
||||||
title: 'Replace',
|
title: nls.localize('arduino/contributions/replaceTitle', 'Replace'),
|
||||||
buttons: ['Cancel', 'OK'],
|
buttons: [
|
||||||
message: `Replace the existing version of ${filename}?`
|
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
|
if (response === 0) {
|
||||||
|
// Cancel
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
await this.fileService.copy(toAddUri, targetUri, { overwrite: true });
|
await this.fileService.copy(toAddUri, targetUri, { overwrite: true });
|
||||||
this.messageService.info('One file added to the sketch.', { timeout: 2000 });
|
this.messageService.info(
|
||||||
|
nls.localize(
|
||||||
|
'arduino/contributions/fileAdded',
|
||||||
|
'One file added to the sketch.'
|
||||||
|
),
|
||||||
|
{
|
||||||
|
timeout: 2000,
|
||||||
|
}
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export namespace AddFile {
|
export namespace AddFile {
|
||||||
export namespace Commands {
|
export namespace Commands {
|
||||||
export const ADD_FILE: Command = {
|
export const ADD_FILE: Command = {
|
||||||
id: 'arduino-add-file'
|
id: 'arduino-add-file',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,154 @@
|
|||||||
|
import { inject, injectable } from 'inversify';
|
||||||
|
import * as remote from '@theia/core/electron-shared/@electron/remote';
|
||||||
|
import URI from '@theia/core/lib/common/uri';
|
||||||
|
import { ConfirmDialog } from '@theia/core/lib/browser/dialogs';
|
||||||
|
import { EnvVariablesServer } from '@theia/core/lib/common/env-variables';
|
||||||
|
import { ArduinoMenus } from '../menu/arduino-menus';
|
||||||
|
import {
|
||||||
|
Installable,
|
||||||
|
LibraryService,
|
||||||
|
ResponseServiceArduino,
|
||||||
|
} from '../../common/protocol';
|
||||||
|
import {
|
||||||
|
SketchContribution,
|
||||||
|
Command,
|
||||||
|
CommandRegistry,
|
||||||
|
MenuModelRegistry,
|
||||||
|
} from './contribution';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
|
||||||
|
@injectable()
|
||||||
|
export class AddZipLibrary extends SketchContribution {
|
||||||
|
@inject(EnvVariablesServer)
|
||||||
|
protected readonly envVariableServer: EnvVariablesServer;
|
||||||
|
|
||||||
|
@inject(ResponseServiceArduino)
|
||||||
|
protected readonly responseService: ResponseServiceArduino;
|
||||||
|
|
||||||
|
@inject(LibraryService)
|
||||||
|
protected readonly libraryService: LibraryService;
|
||||||
|
|
||||||
|
registerCommands(registry: CommandRegistry): void {
|
||||||
|
registry.registerCommand(AddZipLibrary.Commands.ADD_ZIP_LIBRARY, {
|
||||||
|
execute: () => this.addZipLibrary(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
registerMenus(registry: MenuModelRegistry): void {
|
||||||
|
const includeLibMenuPath = [
|
||||||
|
...ArduinoMenus.SKETCH__UTILS_GROUP,
|
||||||
|
'0_include',
|
||||||
|
];
|
||||||
|
// TODO: do we need it? calling `registerSubmenu` multiple times is noop, so it does not hurt.
|
||||||
|
registry.registerSubmenu(includeLibMenuPath, 'Include Library', {
|
||||||
|
order: '1',
|
||||||
|
});
|
||||||
|
registry.registerMenuAction([...includeLibMenuPath, '1_install'], {
|
||||||
|
commandId: AddZipLibrary.Commands.ADD_ZIP_LIBRARY.id,
|
||||||
|
label: nls.localize('arduino/library/addZip', 'Add .ZIP Library...'),
|
||||||
|
order: '1',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async addZipLibrary(): Promise<void> {
|
||||||
|
const homeUri = await this.envVariableServer.getHomeDirUri();
|
||||||
|
const defaultPath = await this.fileService.fsPath(new URI(homeUri));
|
||||||
|
const { canceled, filePaths } = await remote.dialog.showOpenDialog({
|
||||||
|
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 Installable.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',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,38 +1,54 @@
|
|||||||
import { injectable } from 'inversify';
|
import { injectable } from 'inversify';
|
||||||
import { remote } from 'electron';
|
import * as remote from '@theia/core/electron-shared/@electron/remote';
|
||||||
import * as dateFormat from 'dateformat';
|
import * as dateFormat from 'dateformat';
|
||||||
import URI from '@theia/core/lib/common/uri';
|
import URI from '@theia/core/lib/common/uri';
|
||||||
import { ArduinoMenus } from '../menu/arduino-menus';
|
import { ArduinoMenus } from '../menu/arduino-menus';
|
||||||
import { SketchContribution, Command, CommandRegistry, MenuModelRegistry } from './contribution';
|
import {
|
||||||
|
SketchContribution,
|
||||||
|
Command,
|
||||||
|
CommandRegistry,
|
||||||
|
MenuModelRegistry,
|
||||||
|
} from './contribution';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export class ArchiveSketch extends SketchContribution {
|
export class ArchiveSketch extends SketchContribution {
|
||||||
|
|
||||||
registerCommands(registry: CommandRegistry): void {
|
registerCommands(registry: CommandRegistry): void {
|
||||||
registry.registerCommand(ArchiveSketch.Commands.ARCHIVE_SKETCH, {
|
registry.registerCommand(ArchiveSketch.Commands.ARCHIVE_SKETCH, {
|
||||||
execute: () => this.archiveSketch()
|
execute: () => this.archiveSketch(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
registerMenus(registry: MenuModelRegistry): void {
|
registerMenus(registry: MenuModelRegistry): void {
|
||||||
registry.registerMenuAction(ArduinoMenus.TOOLS__MAIN_GROUP, {
|
registry.registerMenuAction(ArduinoMenus.TOOLS__MAIN_GROUP, {
|
||||||
commandId: ArchiveSketch.Commands.ARCHIVE_SKETCH.id,
|
commandId: ArchiveSketch.Commands.ARCHIVE_SKETCH.id,
|
||||||
label: 'Archive Sketch',
|
label: nls.localize('arduino/sketch/archiveSketch', 'Archive Sketch'),
|
||||||
order: '1'
|
order: '1',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
protected async archiveSketch(): Promise<void> {
|
protected async archiveSketch(): Promise<void> {
|
||||||
const [sketch, config] = await Promise.all([
|
const [sketch, config] = await Promise.all([
|
||||||
this.sketchServiceClient.currentSketch(),
|
this.sketchServiceClient.currentSketch(),
|
||||||
this.configService.getConfiguration()
|
this.configService.getConfiguration(),
|
||||||
]);
|
]);
|
||||||
if (!sketch) {
|
if (!sketch) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const archiveBasename = `${sketch.name}-${dateFormat(new Date(), 'yymmdd')}a.zip`;
|
const archiveBasename = `${sketch.name}-${dateFormat(
|
||||||
const defaultPath = await this.fileService.fsPath(new URI(config.sketchDirUri).resolve(archiveBasename));
|
new Date(),
|
||||||
const { filePath, canceled } = await remote.dialog.showSaveDialog({ title: 'Save sketch folder as...', defaultPath });
|
'yymmdd'
|
||||||
|
)}a.zip`;
|
||||||
|
const defaultPath = await this.fileService.fsPath(
|
||||||
|
new URI(config.sketchDirUri).resolve(archiveBasename)
|
||||||
|
);
|
||||||
|
const { filePath, canceled } = await remote.dialog.showSaveDialog({
|
||||||
|
title: nls.localize(
|
||||||
|
'arduino/sketch/saveSketchAs',
|
||||||
|
'Save sketch folder as...'
|
||||||
|
),
|
||||||
|
defaultPath,
|
||||||
|
});
|
||||||
if (!filePath || canceled) {
|
if (!filePath || canceled) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -41,15 +57,23 @@ export class ArchiveSketch extends SketchContribution {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
await this.sketchService.archive(sketch, destinationUri.toString());
|
await this.sketchService.archive(sketch, destinationUri.toString());
|
||||||
this.messageService.info(`Created archive '${archiveBasename}'.`, { timeout: 2000 });
|
this.messageService.info(
|
||||||
|
nls.localize(
|
||||||
|
'arduino/sketch/createdArchive',
|
||||||
|
"Created archive '{0}'.",
|
||||||
|
archiveBasename
|
||||||
|
),
|
||||||
|
{
|
||||||
|
timeout: 2000,
|
||||||
|
}
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export namespace ArchiveSketch {
|
export namespace ArchiveSketch {
|
||||||
export namespace Commands {
|
export namespace Commands {
|
||||||
export const ARCHIVE_SKETCH: Command = {
|
export const ARCHIVE_SKETCH: Command = {
|
||||||
id: 'arduino-archive-sketch'
|
id: 'arduino-archive-sketch',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +1,32 @@
|
|||||||
import { inject, injectable } from 'inversify';
|
import { inject, injectable } from 'inversify';
|
||||||
import { remote } from 'electron';
|
import * as remote from '@theia/core/electron-shared/@electron/remote';
|
||||||
import { MenuModelRegistry } from '@theia/core/lib/common/menu';
|
import { MenuModelRegistry } from '@theia/core/lib/common/menu';
|
||||||
import { DisposableCollection, Disposable } from '@theia/core/lib/common/disposable';
|
import {
|
||||||
|
DisposableCollection,
|
||||||
|
Disposable,
|
||||||
|
} from '@theia/core/lib/common/disposable';
|
||||||
import { firstToUpperCase } from '../../common/utils';
|
import { firstToUpperCase } from '../../common/utils';
|
||||||
import { BoardsConfig } from '../boards/boards-config';
|
import { BoardsConfig } from '../boards/boards-config';
|
||||||
import { MainMenuManager } from '../../common/main-menu-manager';
|
import { MainMenuManager } from '../../common/main-menu-manager';
|
||||||
import { BoardsListWidget } from '../boards/boards-list-widget';
|
import { BoardsListWidget } from '../boards/boards-list-widget';
|
||||||
import { NotificationCenter } from '../notification-center';
|
import { NotificationCenter } from '../notification-center';
|
||||||
import { BoardsServiceProvider } from '../boards/boards-service-provider';
|
import { BoardsServiceProvider } from '../boards/boards-service-provider';
|
||||||
import { ArduinoMenus, PlaceholderMenuNode, unregisterSubmenu } from '../menu/arduino-menus';
|
import {
|
||||||
import { BoardsService, InstalledBoardWithPackage, AvailablePorts, Port } from '../../common/protocol';
|
ArduinoMenus,
|
||||||
|
PlaceholderMenuNode,
|
||||||
|
unregisterSubmenu,
|
||||||
|
} from '../menu/arduino-menus';
|
||||||
|
import {
|
||||||
|
BoardsService,
|
||||||
|
InstalledBoardWithPackage,
|
||||||
|
AvailablePorts,
|
||||||
|
Port,
|
||||||
|
} from '../../common/protocol';
|
||||||
import { SketchContribution, Command, CommandRegistry } from './contribution';
|
import { SketchContribution, Command, CommandRegistry } from './contribution';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export class BoardSelection extends SketchContribution {
|
export class BoardSelection extends SketchContribution {
|
||||||
|
|
||||||
@inject(CommandRegistry)
|
@inject(CommandRegistry)
|
||||||
protected readonly commandRegistry: CommandRegistry;
|
protected readonly commandRegistry: CommandRegistry;
|
||||||
|
|
||||||
@@ -38,34 +50,53 @@ export class BoardSelection extends SketchContribution {
|
|||||||
registerCommands(registry: CommandRegistry): void {
|
registerCommands(registry: CommandRegistry): void {
|
||||||
registry.registerCommand(BoardSelection.Commands.GET_BOARD_INFO, {
|
registry.registerCommand(BoardSelection.Commands.GET_BOARD_INFO, {
|
||||||
execute: async () => {
|
execute: async () => {
|
||||||
const { selectedBoard, selectedPort } = this.boardsServiceProvider.boardsConfig;
|
const { selectedBoard, selectedPort } =
|
||||||
|
this.boardsServiceProvider.boardsConfig;
|
||||||
if (!selectedBoard) {
|
if (!selectedBoard) {
|
||||||
this.messageService.info('Please select a board to obtain board info.');
|
this.messageService.info(
|
||||||
|
nls.localize(
|
||||||
|
'arduino/board/selectBoardForInfo',
|
||||||
|
'Please select a board to obtain board info.'
|
||||||
|
)
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!selectedBoard.fqbn) {
|
if (!selectedBoard.fqbn) {
|
||||||
this.messageService.info(`The platform for the selected '${selectedBoard.name}' board is not installed.`);
|
this.messageService.info(
|
||||||
|
nls.localize(
|
||||||
|
'arduino/board/platformMissing',
|
||||||
|
"The platform for the selected '{0}' board is not installed.",
|
||||||
|
selectedBoard.name
|
||||||
|
)
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!selectedPort) {
|
if (!selectedPort) {
|
||||||
this.messageService.info('Please select a port to obtain board info.');
|
this.messageService.info(
|
||||||
|
nls.localize(
|
||||||
|
'arduino/board/selectPortForInfo',
|
||||||
|
'Please select a port to obtain board info.'
|
||||||
|
)
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const boardDetails = await this.boardsService.getBoardDetails({ fqbn: selectedBoard.fqbn });
|
const boardDetails = await this.boardsService.getBoardDetails({
|
||||||
|
fqbn: selectedBoard.fqbn,
|
||||||
|
});
|
||||||
if (boardDetails) {
|
if (boardDetails) {
|
||||||
const { VID, PID } = boardDetails;
|
const { VID, PID } = boardDetails;
|
||||||
const detail = `BN: ${selectedBoard.name}
|
const detail = `BN: ${selectedBoard.name}
|
||||||
VID: ${VID}
|
VID: ${VID}
|
||||||
PID: ${PID}`;
|
PID: ${PID}`;
|
||||||
await remote.dialog.showMessageBox(remote.getCurrentWindow(), {
|
await remote.dialog.showMessageBox(remote.getCurrentWindow(), {
|
||||||
message: 'Board Info',
|
message: nls.localize('arduino/board/boardInfo', 'Board Info'),
|
||||||
title: 'Board Info',
|
title: nls.localize('arduino/board/boardInfo', 'Board Info'),
|
||||||
type: 'info',
|
type: 'info',
|
||||||
detail,
|
detail,
|
||||||
buttons: ['OK']
|
buttons: [nls.localize('vscode/issueMainService/ok', 'OK')],
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -73,147 +104,255 @@ PID: ${PID}`;
|
|||||||
this.updateMenus();
|
this.updateMenus();
|
||||||
this.notificationCenter.onPlatformInstalled(this.updateMenus.bind(this));
|
this.notificationCenter.onPlatformInstalled(this.updateMenus.bind(this));
|
||||||
this.notificationCenter.onPlatformUninstalled(this.updateMenus.bind(this));
|
this.notificationCenter.onPlatformUninstalled(this.updateMenus.bind(this));
|
||||||
this.boardsServiceProvider.onBoardsConfigChanged(this.updateMenus.bind(this));
|
this.boardsServiceProvider.onBoardsConfigChanged(
|
||||||
this.boardsServiceProvider.onAvailableBoardsChanged(this.updateMenus.bind(this));
|
this.updateMenus.bind(this)
|
||||||
|
);
|
||||||
|
this.boardsServiceProvider.onAvailableBoardsChanged(
|
||||||
|
this.updateMenus.bind(this)
|
||||||
|
);
|
||||||
|
this.boardsServiceProvider.onAvailablePortsChanged(
|
||||||
|
this.updateMenus.bind(this)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected async updateMenus(): Promise<void> {
|
protected async updateMenus(): Promise<void> {
|
||||||
const [installedBoards, availablePorts, config] = await Promise.all([
|
const [installedBoards, availablePorts, config] = await Promise.all([
|
||||||
this.installedBoards(),
|
this.installedBoards(),
|
||||||
this.boardsService.getState(),
|
this.boardsService.getState(),
|
||||||
this.boardsServiceProvider.boardsConfig
|
this.boardsServiceProvider.boardsConfig,
|
||||||
]);
|
]);
|
||||||
this.rebuildMenus(installedBoards, availablePorts, config);
|
this.rebuildMenus(installedBoards, availablePorts, config);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected rebuildMenus(installedBoards: InstalledBoardWithPackage[], availablePorts: AvailablePorts, config: BoardsConfig.Config): void {
|
protected rebuildMenus(
|
||||||
|
installedBoards: InstalledBoardWithPackage[],
|
||||||
|
availablePorts: AvailablePorts,
|
||||||
|
config: BoardsConfig.Config
|
||||||
|
): void {
|
||||||
this.toDisposeBeforeMenuRebuild.dispose();
|
this.toDisposeBeforeMenuRebuild.dispose();
|
||||||
|
|
||||||
// Boards submenu
|
// Boards submenu
|
||||||
const boardsSubmenuPath = [...ArduinoMenus.TOOLS__BOARD_SELECTION_GROUP, '1_boards'];
|
const boardsSubmenuPath = [
|
||||||
|
...ArduinoMenus.TOOLS__BOARD_SELECTION_GROUP,
|
||||||
|
'1_boards',
|
||||||
|
];
|
||||||
const boardsSubmenuLabel = config.selectedBoard?.name;
|
const boardsSubmenuLabel = config.selectedBoard?.name;
|
||||||
// Note: The submenu order starts from `100` because `Auto Format`, `Serial Monitor`, etc starts from `0` index.
|
// 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.
|
// The board specific items, and the rest, have order with `z`. We needed something between `0` and `z` with natural-order.
|
||||||
this.menuModelRegistry.registerSubmenu(boardsSubmenuPath, `Board${!!boardsSubmenuLabel ? `: "${boardsSubmenuLabel}"` : ''}`, { order: '100' });
|
this.menuModelRegistry.registerSubmenu(
|
||||||
this.toDisposeBeforeMenuRebuild.push(Disposable.create(() => unregisterSubmenu(boardsSubmenuPath, this.menuModelRegistry)));
|
boardsSubmenuPath,
|
||||||
|
nls.localize(
|
||||||
|
'arduino/board/board',
|
||||||
|
'Board{0}',
|
||||||
|
!!boardsSubmenuLabel ? `: "${boardsSubmenuLabel}"` : ''
|
||||||
|
),
|
||||||
|
{ order: '100' }
|
||||||
|
);
|
||||||
|
this.toDisposeBeforeMenuRebuild.push(
|
||||||
|
Disposable.create(() =>
|
||||||
|
unregisterSubmenu(boardsSubmenuPath, this.menuModelRegistry)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
// Ports submenu
|
// Ports submenu
|
||||||
const portsSubmenuPath = [...ArduinoMenus.TOOLS__BOARD_SELECTION_GROUP, '2_ports'];
|
const portsSubmenuPath = [
|
||||||
|
...ArduinoMenus.TOOLS__BOARD_SELECTION_GROUP,
|
||||||
|
'2_ports',
|
||||||
|
];
|
||||||
const portsSubmenuLabel = config.selectedPort?.address;
|
const portsSubmenuLabel = config.selectedPort?.address;
|
||||||
this.menuModelRegistry.registerSubmenu(portsSubmenuPath, `Port${!!portsSubmenuLabel ? `: "${portsSubmenuLabel}"` : ''}`, { order: '101' });
|
this.menuModelRegistry.registerSubmenu(
|
||||||
this.toDisposeBeforeMenuRebuild.push(Disposable.create(() => unregisterSubmenu(portsSubmenuPath, this.menuModelRegistry)));
|
portsSubmenuPath,
|
||||||
|
nls.localize(
|
||||||
|
'arduino/board/port',
|
||||||
|
'Port{0}',
|
||||||
|
portsSubmenuLabel ? `: "${portsSubmenuLabel}"` : ''
|
||||||
|
),
|
||||||
|
{ order: '101' }
|
||||||
|
);
|
||||||
|
this.toDisposeBeforeMenuRebuild.push(
|
||||||
|
Disposable.create(() =>
|
||||||
|
unregisterSubmenu(portsSubmenuPath, this.menuModelRegistry)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
const getBoardInfo = { commandId: BoardSelection.Commands.GET_BOARD_INFO.id, label: 'Get Board Info', order: '103' };
|
const getBoardInfo = {
|
||||||
this.menuModelRegistry.registerMenuAction(ArduinoMenus.TOOLS__BOARD_SELECTION_GROUP, getBoardInfo);
|
commandId: BoardSelection.Commands.GET_BOARD_INFO.id,
|
||||||
this.toDisposeBeforeMenuRebuild.push(Disposable.create(() => this.menuModelRegistry.unregisterMenuAction(getBoardInfo)));
|
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 boardsManagerGroup = [...boardsSubmenuPath, '0_manager'];
|
||||||
const boardsPackagesGroup = [...boardsSubmenuPath, '1_packages'];
|
const boardsPackagesGroup = [...boardsSubmenuPath, '1_packages'];
|
||||||
|
|
||||||
this.menuModelRegistry.registerMenuAction(boardsManagerGroup, {
|
this.menuModelRegistry.registerMenuAction(boardsManagerGroup, {
|
||||||
commandId: `${BoardsListWidget.WIDGET_ID}:toggle`,
|
commandId: `${BoardsListWidget.WIDGET_ID}:toggle`,
|
||||||
label: 'Boards Manager...'
|
label: `${BoardsListWidget.WIDGET_LABEL}...`,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Installed boards
|
// Installed boards
|
||||||
for (const board of installedBoards) {
|
for (const board of installedBoards) {
|
||||||
const { packageId, packageName, fqbn, name } = board;
|
const { packageId, packageName, fqbn, name, manuallyInstalled } = board;
|
||||||
|
|
||||||
|
const packageLabel =
|
||||||
|
packageName +
|
||||||
|
`${manuallyInstalled
|
||||||
|
? nls.localize('arduino/board/inSketchbook', ' (in Sketchbook)')
|
||||||
|
: ''
|
||||||
|
}`;
|
||||||
// Platform submenu
|
// Platform submenu
|
||||||
const platformMenuPath = [...boardsPackagesGroup, packageId];
|
const platformMenuPath = [...boardsPackagesGroup, packageId];
|
||||||
// Note: Registering the same submenu twice is a noop. No need to group the boards per platform.
|
// Note: Registering the same submenu twice is a noop. No need to group the boards per platform.
|
||||||
this.menuModelRegistry.registerSubmenu(platformMenuPath, packageName);
|
this.menuModelRegistry.registerSubmenu(platformMenuPath, packageLabel, {
|
||||||
|
order: packageName.toLowerCase(),
|
||||||
|
});
|
||||||
|
|
||||||
const id = `arduino-select-board--${fqbn}`;
|
const id = `arduino-select-board--${fqbn}`;
|
||||||
const command = { id };
|
const command = { id };
|
||||||
const handler = {
|
const handler = {
|
||||||
execute: () => {
|
execute: () => {
|
||||||
if (fqbn !== this.boardsServiceProvider.boardsConfig.selectedBoard?.fqbn) {
|
if (
|
||||||
|
fqbn !== this.boardsServiceProvider.boardsConfig.selectedBoard?.fqbn
|
||||||
|
) {
|
||||||
this.boardsServiceProvider.boardsConfig = {
|
this.boardsServiceProvider.boardsConfig = {
|
||||||
selectedBoard: {
|
selectedBoard: {
|
||||||
name,
|
name,
|
||||||
fqbn,
|
fqbn,
|
||||||
port: this.boardsServiceProvider.boardsConfig.selectedBoard?.port // TODO: verify!
|
port: this.boardsServiceProvider.boardsConfig.selectedBoard
|
||||||
|
?.port, // TODO: verify!
|
||||||
},
|
},
|
||||||
selectedPort: this.boardsServiceProvider.boardsConfig.selectedPort
|
selectedPort:
|
||||||
}
|
this.boardsServiceProvider.boardsConfig.selectedPort,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
isToggled: () => fqbn === this.boardsServiceProvider.boardsConfig.selectedBoard?.fqbn
|
isToggled: () =>
|
||||||
|
fqbn === this.boardsServiceProvider.boardsConfig.selectedBoard?.fqbn,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Board menu
|
// Board menu
|
||||||
const menuAction = { commandId: id, label: name };
|
const menuAction = { commandId: id, label: name };
|
||||||
this.commandRegistry.registerCommand(command, handler);
|
this.commandRegistry.registerCommand(command, handler);
|
||||||
this.toDisposeBeforeMenuRebuild.push(Disposable.create(() => this.commandRegistry.unregisterCommand(command)));
|
this.toDisposeBeforeMenuRebuild.push(
|
||||||
|
Disposable.create(() => this.commandRegistry.unregisterCommand(command))
|
||||||
|
);
|
||||||
this.menuModelRegistry.registerMenuAction(platformMenuPath, menuAction);
|
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.
|
// Note: we do not dispose the menu actions individually. Calling `unregisterSubmenu` on the parent will wipe the children menu nodes recursively.
|
||||||
}
|
}
|
||||||
|
|
||||||
// Installed ports
|
// Installed ports
|
||||||
const registerPorts = (ports: AvailablePorts) => {
|
const registerPorts = (
|
||||||
const addresses = Object.keys(ports);
|
protocol: string,
|
||||||
if (!addresses.length) {
|
protocolOrder: number,
|
||||||
|
ports: AvailablePorts
|
||||||
|
) => {
|
||||||
|
const portIDs = Object.keys(ports);
|
||||||
|
if (!portIDs.length) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Register placeholder for protocol
|
// Register placeholder for protocol
|
||||||
const [port] = ports[addresses[0]];
|
const menuPath = [
|
||||||
const protocol = port.protocol;
|
...portsSubmenuPath,
|
||||||
const menuPath = [...portsSubmenuPath, protocol];
|
`${protocolOrder.toString()}_${protocol}`,
|
||||||
const placeholder = new PlaceholderMenuNode(menuPath, `${firstToUpperCase(port.protocol)} ports`);
|
];
|
||||||
|
const placeholder = new PlaceholderMenuNode(
|
||||||
|
menuPath,
|
||||||
|
`${firstToUpperCase(protocol)} ports`,
|
||||||
|
{ order: protocolOrder.toString() }
|
||||||
|
);
|
||||||
this.menuModelRegistry.registerMenuNode(menuPath, placeholder);
|
this.menuModelRegistry.registerMenuNode(menuPath, placeholder);
|
||||||
this.toDisposeBeforeMenuRebuild.push(Disposable.create(() => this.menuModelRegistry.unregisterMenuNode(placeholder.id)));
|
this.toDisposeBeforeMenuRebuild.push(
|
||||||
|
Disposable.create(() =>
|
||||||
|
this.menuModelRegistry.unregisterMenuNode(placeholder.id)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
for (const address of addresses) {
|
// First we show addresses with recognized boards connected,
|
||||||
if (!!ports[address]) {
|
// then all the rest.
|
||||||
const [port, boards] = ports[address];
|
const sortedIDs = Object.keys(ports).sort((left: string, right: string): number => {
|
||||||
if (!boards.length) {
|
const [, leftBoards] = ports[left];
|
||||||
boards.push({
|
const [, rightBoards] = ports[right];
|
||||||
name: ''
|
return rightBoards.length - leftBoards.length;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
for (let i = 0; i < sortedIDs.length; i++) {
|
||||||
|
const portID = sortedIDs[i];
|
||||||
|
const [port, boards] = ports[portID];
|
||||||
|
let label = `${port.address}`;
|
||||||
|
if (boards.length) {
|
||||||
|
const boardsList = boards.map((board) => board.name).join(', ');
|
||||||
|
label = `${label} (${boardsList})`;
|
||||||
}
|
}
|
||||||
for (const { name, fqbn } of boards) {
|
const id = `arduino-select-port--${portID}`;
|
||||||
const id = `arduino-select-port--${address}${fqbn ? `--${fqbn}` : ''}`;
|
|
||||||
const command = { id };
|
const command = { id };
|
||||||
const handler = {
|
const handler = {
|
||||||
execute: () => {
|
execute: () => {
|
||||||
if (!Port.equals(port, this.boardsServiceProvider.boardsConfig.selectedPort)) {
|
if (
|
||||||
|
!Port.sameAs(
|
||||||
|
port,
|
||||||
|
this.boardsServiceProvider.boardsConfig.selectedPort
|
||||||
|
)
|
||||||
|
) {
|
||||||
this.boardsServiceProvider.boardsConfig = {
|
this.boardsServiceProvider.boardsConfig = {
|
||||||
selectedBoard: this.boardsServiceProvider.boardsConfig.selectedBoard,
|
selectedBoard:
|
||||||
selectedPort: port
|
this.boardsServiceProvider.boardsConfig.selectedBoard,
|
||||||
}
|
selectedPort: port,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
isToggled: () => Port.equals(port, this.boardsServiceProvider.boardsConfig.selectedPort)
|
isToggled: () =>
|
||||||
|
Port.sameAs(
|
||||||
|
port,
|
||||||
|
this.boardsServiceProvider.boardsConfig.selectedPort
|
||||||
|
),
|
||||||
};
|
};
|
||||||
const label = `${address}${name ? ` (${name})` : ''}`;
|
|
||||||
const menuAction = {
|
const menuAction = {
|
||||||
commandId: id,
|
commandId: id,
|
||||||
label,
|
label,
|
||||||
order: `1${label}` // `1` comes after the placeholder which has order `0`
|
order: `${protocolOrder + i + 1}`,
|
||||||
};
|
};
|
||||||
this.commandRegistry.registerCommand(command, handler);
|
this.commandRegistry.registerCommand(command, handler);
|
||||||
this.toDisposeBeforeMenuRebuild.push(Disposable.create(() => this.commandRegistry.unregisterCommand(command)));
|
this.toDisposeBeforeMenuRebuild.push(
|
||||||
|
Disposable.create(() =>
|
||||||
|
this.commandRegistry.unregisterCommand(command)
|
||||||
|
)
|
||||||
|
);
|
||||||
this.menuModelRegistry.registerMenuAction(menuPath, menuAction);
|
this.menuModelRegistry.registerMenuAction(menuPath, menuAction);
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const { serial, network, unknown } = AvailablePorts.groupByProtocol(availablePorts);
|
const grouped = AvailablePorts.byProtocol(availablePorts);
|
||||||
registerPorts(serial);
|
let protocolOrder = 100;
|
||||||
registerPorts(network);
|
// We first show serial and network ports, then all the rest
|
||||||
registerPorts(unknown);
|
['serial', 'network'].forEach((protocol) => {
|
||||||
|
const ports = grouped.get(protocol);
|
||||||
|
if (ports) {
|
||||||
|
registerPorts(protocol, protocolOrder, ports);
|
||||||
|
grouped.delete(protocol);
|
||||||
|
protocolOrder = protocolOrder + 100;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
grouped.forEach((ports, protocol) => {
|
||||||
|
registerPorts(protocol, protocolOrder, ports);
|
||||||
|
protocolOrder = protocolOrder + 100;
|
||||||
|
});
|
||||||
|
|
||||||
this.mainMenuManager.update();
|
this.mainMenuManager.update();
|
||||||
}
|
}
|
||||||
|
|
||||||
protected async installedBoards(): Promise<InstalledBoardWithPackage[]> {
|
protected async installedBoards(): Promise<InstalledBoardWithPackage[]> {
|
||||||
const allBoards = await this.boardsService.allBoards({});
|
const allBoards = await this.boardsService.searchBoards({});
|
||||||
return allBoards.filter(InstalledBoardWithPackage.is);
|
return allBoards.filter(InstalledBoardWithPackage.is);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
export namespace BoardSelection {
|
export namespace BoardSelection {
|
||||||
export namespace Commands {
|
export namespace Commands {
|
||||||
|
|||||||
@@ -1,20 +1,25 @@
|
|||||||
import { inject, injectable } from 'inversify';
|
import { inject, injectable } from 'inversify';
|
||||||
import { OutputChannelManager } from '@theia/output/lib/common/output-channel';
|
import { OutputChannelManager } from '@theia/output/lib/browser/output-channel';
|
||||||
import { CoreService } from '../../common/protocol';
|
import { CoreService } from '../../common/protocol';
|
||||||
import { ArduinoMenus } from '../menu/arduino-menus';
|
import { ArduinoMenus } from '../menu/arduino-menus';
|
||||||
import { BoardsDataStore } from '../boards/boards-data-store';
|
import { BoardsDataStore } from '../boards/boards-data-store';
|
||||||
import { MonitorConnection } from '../monitor/monitor-connection';
|
import { SerialConnectionManager } from '../serial/serial-connection-manager';
|
||||||
import { BoardsServiceProvider } from '../boards/boards-service-provider';
|
import { BoardsServiceProvider } from '../boards/boards-service-provider';
|
||||||
import { SketchContribution, Command, CommandRegistry, MenuModelRegistry } from './contribution';
|
import {
|
||||||
|
SketchContribution,
|
||||||
|
Command,
|
||||||
|
CommandRegistry,
|
||||||
|
MenuModelRegistry,
|
||||||
|
} from './contribution';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export class BurnBootloader extends SketchContribution {
|
export class BurnBootloader extends SketchContribution {
|
||||||
|
|
||||||
@inject(CoreService)
|
@inject(CoreService)
|
||||||
protected readonly coreService: CoreService;
|
protected readonly coreService: CoreService;
|
||||||
|
|
||||||
@inject(MonitorConnection)
|
@inject(SerialConnectionManager)
|
||||||
protected readonly monitorConnection: MonitorConnection;
|
protected readonly serialConnection: SerialConnectionManager;
|
||||||
|
|
||||||
@inject(BoardsDataStore)
|
@inject(BoardsDataStore)
|
||||||
protected readonly boardsDataStore: BoardsDataStore;
|
protected readonly boardsDataStore: BoardsDataStore;
|
||||||
@@ -27,31 +32,33 @@ export class BurnBootloader extends SketchContribution {
|
|||||||
|
|
||||||
registerCommands(registry: CommandRegistry): void {
|
registerCommands(registry: CommandRegistry): void {
|
||||||
registry.registerCommand(BurnBootloader.Commands.BURN_BOOTLOADER, {
|
registry.registerCommand(BurnBootloader.Commands.BURN_BOOTLOADER, {
|
||||||
execute: () => this.burnBootloader()
|
execute: () => this.burnBootloader(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
registerMenus(registry: MenuModelRegistry): void {
|
registerMenus(registry: MenuModelRegistry): void {
|
||||||
registry.registerMenuAction(ArduinoMenus.TOOLS__BOARD_SETTINGS_GROUP, {
|
registry.registerMenuAction(ArduinoMenus.TOOLS__BOARD_SETTINGS_GROUP, {
|
||||||
commandId: BurnBootloader.Commands.BURN_BOOTLOADER.id,
|
commandId: BurnBootloader.Commands.BURN_BOOTLOADER.id,
|
||||||
label: 'Burn Bootloader',
|
label: nls.localize(
|
||||||
order: 'z99'
|
'arduino/bootloader/burnBootloader',
|
||||||
|
'Burn Bootloader'
|
||||||
|
),
|
||||||
|
order: 'z99',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async burnBootloader(): Promise<void> {
|
async burnBootloader(): Promise<void> {
|
||||||
const monitorConfig = this.monitorConnection.monitorConfig;
|
|
||||||
if (monitorConfig) {
|
|
||||||
await this.monitorConnection.disconnect();
|
|
||||||
}
|
|
||||||
try {
|
try {
|
||||||
const { boardsConfig } = this.boardsServiceClientImpl;
|
const { boardsConfig } = this.boardsServiceClientImpl;
|
||||||
const port = boardsConfig.selectedPort?.address;
|
const port = boardsConfig.selectedPort;
|
||||||
const [fqbn, { selectedProgrammer: programmer }, verify, verbose] = await Promise.all([
|
const [fqbn, { selectedProgrammer: programmer }, verify, verbose] =
|
||||||
this.boardsDataStore.appendConfigToFqbn(boardsConfig.selectedBoard?.fqbn),
|
await Promise.all([
|
||||||
|
this.boardsDataStore.appendConfigToFqbn(
|
||||||
|
boardsConfig.selectedBoard?.fqbn
|
||||||
|
),
|
||||||
this.boardsDataStore.getData(boardsConfig.selectedBoard?.fqbn),
|
this.boardsDataStore.getData(boardsConfig.selectedBoard?.fqbn),
|
||||||
this.preferences.get('arduino.upload.verify'),
|
this.preferences.get('arduino.upload.verify'),
|
||||||
this.preferences.get('arduino.upload.verbose')
|
this.preferences.get('arduino.upload.verbose'),
|
||||||
]);
|
]);
|
||||||
this.outputChannelManager.getChannel('Arduino').clear();
|
this.outputChannelManager.getChannel('Arduino').clear();
|
||||||
await this.coreService.burnBootloader({
|
await this.coreService.burnBootloader({
|
||||||
@@ -59,24 +66,35 @@ export class BurnBootloader extends SketchContribution {
|
|||||||
programmer,
|
programmer,
|
||||||
port,
|
port,
|
||||||
verify,
|
verify,
|
||||||
verbose
|
verbose,
|
||||||
});
|
});
|
||||||
this.messageService.info('Done burning bootloader.', { timeout: 1000 });
|
this.messageService.info(
|
||||||
|
nls.localize(
|
||||||
|
'arduino/bootloader/doneBurningBootloader',
|
||||||
|
'Done burning bootloader.'
|
||||||
|
),
|
||||||
|
{
|
||||||
|
timeout: 3000,
|
||||||
|
}
|
||||||
|
);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
this.messageService.error(e.toString());
|
let errorMessage = "";
|
||||||
|
if (typeof e === "string") {
|
||||||
|
errorMessage = e;
|
||||||
|
} else {
|
||||||
|
errorMessage = e.toString();
|
||||||
|
}
|
||||||
|
this.messageService.error(errorMessage);
|
||||||
} finally {
|
} finally {
|
||||||
if (monitorConfig) {
|
await this.serialConnection.reconnectAfterUpload();
|
||||||
await this.monitorConnection.connect(monitorConfig);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export namespace BurnBootloader {
|
export namespace BurnBootloader {
|
||||||
export namespace Commands {
|
export namespace Commands {
|
||||||
export const BURN_BOOTLOADER: Command = {
|
export const BURN_BOOTLOADER: Command = {
|
||||||
id: 'arduino-burn-bootloader'
|
id: 'arduino-burn-bootloader',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +1,27 @@
|
|||||||
import { inject, injectable } from 'inversify';
|
import { inject, injectable } from 'inversify';
|
||||||
import { toArray } from '@phosphor/algorithm';
|
import { toArray } from '@phosphor/algorithm';
|
||||||
import { remote } from 'electron';
|
import * as remote from '@theia/core/electron-shared/@electron/remote';
|
||||||
import { MonacoEditor } from '@theia/monaco/lib/browser/monaco-editor';
|
import { MonacoEditor } from '@theia/monaco/lib/browser/monaco-editor';
|
||||||
import { EditorManager } from '@theia/editor/lib/browser/editor-manager';
|
import { EditorManager } from '@theia/editor/lib/browser/editor-manager';
|
||||||
import { ApplicationShell } from '@theia/core/lib/browser/shell/application-shell';
|
import { ApplicationShell } from '@theia/core/lib/browser/shell/application-shell';
|
||||||
import { FrontendApplication } from '@theia/core/lib/browser/frontend-application';
|
import { FrontendApplication } from '@theia/core/lib/browser/frontend-application';
|
||||||
import { ArduinoMenus } from '../menu/arduino-menus';
|
import { ArduinoMenus } from '../menu/arduino-menus';
|
||||||
import { SaveAsSketch } from './save-as-sketch';
|
import { SaveAsSketch } from './save-as-sketch';
|
||||||
import { SketchContribution, Command, CommandRegistry, MenuModelRegistry, KeybindingRegistry, URI } from './contribution';
|
import {
|
||||||
|
SketchContribution,
|
||||||
|
Command,
|
||||||
|
CommandRegistry,
|
||||||
|
MenuModelRegistry,
|
||||||
|
KeybindingRegistry,
|
||||||
|
URI,
|
||||||
|
} from './contribution';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Closes the `current` closeable editor, or any closeable current widget from the main area, or the current sketch window.
|
* Closes the `current` closeable editor, or any closeable current widget from the main area, or the current sketch window.
|
||||||
*/
|
*/
|
||||||
@injectable()
|
@injectable()
|
||||||
export class Close extends SketchContribution {
|
export class Close extends SketchContribution {
|
||||||
|
|
||||||
@inject(EditorManager)
|
@inject(EditorManager)
|
||||||
protected readonly editorManager: EditorManager;
|
protected readonly editorManager: EditorManager;
|
||||||
|
|
||||||
@@ -27,7 +34,6 @@ export class Close extends SketchContribution {
|
|||||||
registerCommands(registry: CommandRegistry): void {
|
registerCommands(registry: CommandRegistry): void {
|
||||||
registry.registerCommand(Close.Commands.CLOSE, {
|
registry.registerCommand(Close.Commands.CLOSE, {
|
||||||
execute: async () => {
|
execute: async () => {
|
||||||
|
|
||||||
// Close current editor if closeable.
|
// Close current editor if closeable.
|
||||||
const { currentEditor } = this.editorManager;
|
const { currentEditor } = this.editorManager;
|
||||||
if (currentEditor && currentEditor.title.closable) {
|
if (currentEditor && currentEditor.title.closable) {
|
||||||
@@ -38,7 +44,9 @@ export class Close extends SketchContribution {
|
|||||||
// Close current widget from the main area if possible.
|
// Close current widget from the main area if possible.
|
||||||
const { currentWidget } = this.shell;
|
const { currentWidget } = this.shell;
|
||||||
if (currentWidget) {
|
if (currentWidget) {
|
||||||
const currentWidgetInMain = toArray(this.shell.mainPanel.widgets()).find(widget => widget === currentWidget);
|
const currentWidgetInMain = toArray(
|
||||||
|
this.shell.mainPanel.widgets()
|
||||||
|
).find((widget) => widget === currentWidget);
|
||||||
if (currentWidgetInMain && currentWidgetInMain.title.closable) {
|
if (currentWidgetInMain && currentWidgetInMain.title.closable) {
|
||||||
return currentWidgetInMain.close();
|
return currentWidgetInMain.close();
|
||||||
}
|
}
|
||||||
@@ -54,40 +62,62 @@ export class Close extends SketchContribution {
|
|||||||
if (!uri) {
|
if (!uri) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (isTemp && await this.wasTouched(uri)) {
|
if (isTemp && (await this.wasTouched(uri))) {
|
||||||
const { response } = await remote.dialog.showMessageBox({
|
const { response } = await remote.dialog.showMessageBox({
|
||||||
type: 'question',
|
type: 'question',
|
||||||
buttons: ["Don't Save", 'Cancel', 'Save'],
|
buttons: [
|
||||||
message: 'Do you want to save changes to this sketch before closing?',
|
nls.localize(
|
||||||
detail: "If you don't save, your changes will be lost."
|
'vscode/abstractTaskService/saveBeforeRun.dontSave',
|
||||||
|
"Don't Save"
|
||||||
|
),
|
||||||
|
nls.localize('vscode/issueMainService/cancel', 'Cancel'),
|
||||||
|
nls.localize(
|
||||||
|
'vscode/abstractTaskService/saveBeforeRun.save',
|
||||||
|
'Save'
|
||||||
|
),
|
||||||
|
],
|
||||||
|
message: nls.localize(
|
||||||
|
'arduino/common/saveChangesToSketch',
|
||||||
|
'Do you want to save changes to this sketch before closing?'
|
||||||
|
),
|
||||||
|
detail: nls.localize(
|
||||||
|
'arduino/common/loseChanges',
|
||||||
|
"If you don't save, your changes will be lost."
|
||||||
|
),
|
||||||
});
|
});
|
||||||
if (response === 1) { // Cancel
|
if (response === 1) {
|
||||||
|
// Cancel
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (response === 2) { // Save
|
if (response === 2) {
|
||||||
const saved = await this.commandService.executeCommand(SaveAsSketch.Commands.SAVE_AS_SKETCH.id, { openAfterMove: false, execOnlyIfTemp: true });
|
// Save
|
||||||
if (!saved) { // If it was not saved, do bail the close.
|
const saved = await this.commandService.executeCommand(
|
||||||
|
SaveAsSketch.Commands.SAVE_AS_SKETCH.id,
|
||||||
|
{ openAfterMove: false, execOnlyIfTemp: true }
|
||||||
|
);
|
||||||
|
if (!saved) {
|
||||||
|
// If it was not saved, do bail the close.
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
window.close();
|
window.close();
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
registerMenus(registry: MenuModelRegistry): void {
|
registerMenus(registry: MenuModelRegistry): void {
|
||||||
registry.registerMenuAction(ArduinoMenus.FILE__SKETCH_GROUP, {
|
registry.registerMenuAction(ArduinoMenus.FILE__SKETCH_GROUP, {
|
||||||
commandId: Close.Commands.CLOSE.id,
|
commandId: Close.Commands.CLOSE.id,
|
||||||
label: 'Close',
|
label: nls.localize('vscode/editor.contribution/close', 'Close'),
|
||||||
order: '5'
|
order: '5',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
registerKeybindings(registry: KeybindingRegistry): void {
|
registerKeybindings(registry: KeybindingRegistry): void {
|
||||||
registry.registerKeybinding({
|
registry.registerKeybinding({
|
||||||
command: Close.Commands.CLOSE.id,
|
command: Close.Commands.CLOSE.id,
|
||||||
keybinding: 'CtrlCmd+W'
|
keybinding: 'CtrlCmd+W',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -107,13 +137,12 @@ export class Close extends SketchContribution {
|
|||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export namespace Close {
|
export namespace Close {
|
||||||
export namespace Commands {
|
export namespace Commands {
|
||||||
export const CLOSE: Command = {
|
export const CLOSE: Command = {
|
||||||
id: 'arduino-close'
|
id: 'arduino-close',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,22 +9,60 @@ import { EditorManager } from '@theia/editor/lib/browser/editor-manager';
|
|||||||
import { MessageService } from '@theia/core/lib/common/message-service';
|
import { MessageService } from '@theia/core/lib/common/message-service';
|
||||||
import { WorkspaceService } from '@theia/workspace/lib/browser/workspace-service';
|
import { WorkspaceService } from '@theia/workspace/lib/browser/workspace-service';
|
||||||
import { open, OpenerService } from '@theia/core/lib/browser/opener-service';
|
import { open, OpenerService } from '@theia/core/lib/browser/opener-service';
|
||||||
import { MenuModelRegistry, MenuContribution } from '@theia/core/lib/common/menu';
|
import { OutputChannelManager } from '@theia/output/lib/browser/output-channel';
|
||||||
import { KeybindingRegistry, KeybindingContribution } from '@theia/core/lib/browser/keybinding';
|
import {
|
||||||
import { TabBarToolbarContribution, TabBarToolbarRegistry } from '@theia/core/lib/browser/shell/tab-bar-toolbar';
|
MenuModelRegistry,
|
||||||
import { FrontendApplicationContribution, FrontendApplication } from '@theia/core/lib/browser/frontend-application';
|
MenuContribution,
|
||||||
import { Command, CommandRegistry, CommandContribution, CommandService } from '@theia/core/lib/common/command';
|
} from '@theia/core/lib/common/menu';
|
||||||
|
import {
|
||||||
|
KeybindingRegistry,
|
||||||
|
KeybindingContribution,
|
||||||
|
} from '@theia/core/lib/browser/keybinding';
|
||||||
|
import {
|
||||||
|
TabBarToolbarContribution,
|
||||||
|
TabBarToolbarRegistry,
|
||||||
|
} from '@theia/core/lib/browser/shell/tab-bar-toolbar';
|
||||||
|
import {
|
||||||
|
FrontendApplicationContribution,
|
||||||
|
FrontendApplication,
|
||||||
|
} from '@theia/core/lib/browser/frontend-application';
|
||||||
|
import {
|
||||||
|
Command,
|
||||||
|
CommandRegistry,
|
||||||
|
CommandContribution,
|
||||||
|
CommandService,
|
||||||
|
} from '@theia/core/lib/common/command';
|
||||||
import { EditorMode } from '../editor-mode';
|
import { EditorMode } from '../editor-mode';
|
||||||
import { SettingsService } from '../settings';
|
import { SettingsService } from '../dialogs/settings/settings';
|
||||||
import { SketchesServiceClientImpl } from '../../common/protocol/sketches-service-client-impl';
|
import { SketchesServiceClientImpl } from '../../common/protocol/sketches-service-client-impl';
|
||||||
import { SketchesService, ConfigService, FileSystemExt, Sketch } from '../../common/protocol';
|
import {
|
||||||
|
SketchesService,
|
||||||
|
ConfigService,
|
||||||
|
FileSystemExt,
|
||||||
|
Sketch,
|
||||||
|
} from '../../common/protocol';
|
||||||
import { ArduinoPreferences } from '../arduino-preferences';
|
import { ArduinoPreferences } from '../arduino-preferences';
|
||||||
|
|
||||||
export { Command, CommandRegistry, MenuModelRegistry, KeybindingRegistry, TabBarToolbarRegistry, URI, Sketch, open };
|
export {
|
||||||
|
Command,
|
||||||
|
CommandRegistry,
|
||||||
|
MenuModelRegistry,
|
||||||
|
KeybindingRegistry,
|
||||||
|
TabBarToolbarRegistry,
|
||||||
|
URI,
|
||||||
|
Sketch,
|
||||||
|
open,
|
||||||
|
};
|
||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export abstract class Contribution implements CommandContribution, MenuContribution, KeybindingContribution, TabBarToolbarContribution, FrontendApplicationContribution {
|
export abstract class Contribution
|
||||||
|
implements
|
||||||
|
CommandContribution,
|
||||||
|
MenuContribution,
|
||||||
|
KeybindingContribution,
|
||||||
|
TabBarToolbarContribution,
|
||||||
|
FrontendApplicationContribution
|
||||||
|
{
|
||||||
@inject(ILogger)
|
@inject(ILogger)
|
||||||
protected readonly logger: ILogger;
|
protected readonly logger: ILogger;
|
||||||
|
|
||||||
@@ -46,26 +84,19 @@ export abstract class Contribution implements CommandContribution, MenuContribut
|
|||||||
@inject(SettingsService)
|
@inject(SettingsService)
|
||||||
protected readonly settingsService: SettingsService;
|
protected readonly settingsService: SettingsService;
|
||||||
|
|
||||||
onStart(app: FrontendApplication): MaybePromise<void> {
|
onStart(app: FrontendApplication): MaybePromise<void> {}
|
||||||
}
|
|
||||||
|
|
||||||
registerCommands(registry: CommandRegistry): void {
|
registerCommands(registry: CommandRegistry): void {}
|
||||||
}
|
|
||||||
|
|
||||||
registerMenus(registry: MenuModelRegistry): void {
|
registerMenus(registry: MenuModelRegistry): void {}
|
||||||
}
|
|
||||||
|
|
||||||
registerKeybindings(registry: KeybindingRegistry): void {
|
registerKeybindings(registry: KeybindingRegistry): void {}
|
||||||
}
|
|
||||||
|
|
||||||
registerToolbarItems(registry: TabBarToolbarRegistry): void {
|
|
||||||
}
|
|
||||||
|
|
||||||
|
registerToolbarItems(registry: TabBarToolbarRegistry): void {}
|
||||||
}
|
}
|
||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export abstract class SketchContribution extends Contribution {
|
export abstract class SketchContribution extends Contribution {
|
||||||
|
|
||||||
@inject(FileService)
|
@inject(FileService)
|
||||||
protected readonly fileService: FileService;
|
protected readonly fileService: FileService;
|
||||||
|
|
||||||
@@ -90,6 +121,9 @@ export abstract class SketchContribution extends Contribution {
|
|||||||
@inject(EditorManager)
|
@inject(EditorManager)
|
||||||
protected readonly editorManager: EditorManager;
|
protected readonly editorManager: EditorManager;
|
||||||
|
|
||||||
|
@inject(OutputChannelManager)
|
||||||
|
protected readonly outputChannelManager: OutputChannelManager;
|
||||||
|
|
||||||
protected async sourceOverride(): Promise<Record<string, string>> {
|
protected async sourceOverride(): Promise<Record<string, string>> {
|
||||||
const override: Record<string, string> = {};
|
const override: Record<string, string> = {};
|
||||||
const sketch = await this.sketchServiceClient.currentSketch();
|
const sketch = await this.sketchServiceClient.currentSketch();
|
||||||
@@ -103,11 +137,13 @@ export abstract class SketchContribution extends Contribution {
|
|||||||
}
|
}
|
||||||
return override;
|
return override;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export namespace Contribution {
|
export namespace Contribution {
|
||||||
export function configure<T>(bind: interfaces.Bind, serviceIdentifier: typeof Contribution): void {
|
export function configure<T>(
|
||||||
|
bind: interfaces.Bind,
|
||||||
|
serviceIdentifier: typeof Contribution
|
||||||
|
): void {
|
||||||
bind(serviceIdentifier).toSelf().inSingletonScope();
|
bind(serviceIdentifier).toSelf().inSingletonScope();
|
||||||
bind(CommandContribution).toService(serviceIdentifier);
|
bind(CommandContribution).toService(serviceIdentifier);
|
||||||
bind(MenuContribution).toService(serviceIdentifier);
|
bind(MenuContribution).toService(serviceIdentifier);
|
||||||
|
|||||||
@@ -5,11 +5,17 @@ import { ArduinoToolbar } from '../toolbar/arduino-toolbar';
|
|||||||
import { NotificationCenter } from '../notification-center';
|
import { NotificationCenter } from '../notification-center';
|
||||||
import { Board, BoardsService, ExecutableService } from '../../common/protocol';
|
import { Board, BoardsService, ExecutableService } from '../../common/protocol';
|
||||||
import { BoardsServiceProvider } from '../boards/boards-service-provider';
|
import { BoardsServiceProvider } from '../boards/boards-service-provider';
|
||||||
import { URI, Command, CommandRegistry, SketchContribution, TabBarToolbarRegistry } from './contribution';
|
import {
|
||||||
|
URI,
|
||||||
|
Command,
|
||||||
|
CommandRegistry,
|
||||||
|
SketchContribution,
|
||||||
|
TabBarToolbarRegistry,
|
||||||
|
} from './contribution';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export class Debug extends SketchContribution {
|
export class Debug extends SketchContribution {
|
||||||
|
|
||||||
@inject(HostedPluginSupport)
|
@inject(HostedPluginSupport)
|
||||||
protected hostedPluginSupport: HostedPluginSupport;
|
protected hostedPluginSupport: HostedPluginSupport;
|
||||||
|
|
||||||
@@ -28,9 +34,13 @@ export class Debug extends SketchContribution {
|
|||||||
/**
|
/**
|
||||||
* If `undefined`, debugging is enabled. Otherwise, the reason why it's disabled.
|
* If `undefined`, debugging is enabled. Otherwise, the reason why it's disabled.
|
||||||
*/
|
*/
|
||||||
protected _disabledMessages?: string = 'No board selected'; // Initial pessimism.
|
protected _disabledMessages?: string = nls.localize(
|
||||||
|
'arduino/common/noBoardSelected',
|
||||||
|
'No board selected'
|
||||||
|
); // Initial pessimism.
|
||||||
protected disabledMessageDidChangeEmitter = new Emitter<string | undefined>();
|
protected disabledMessageDidChangeEmitter = new Emitter<string | undefined>();
|
||||||
protected onDisabledMessageDidChange = this.disabledMessageDidChangeEmitter.event;
|
protected onDisabledMessageDidChange =
|
||||||
|
this.disabledMessageDidChangeEmitter.event;
|
||||||
|
|
||||||
protected get disabledMessage(): string | undefined {
|
protected get disabledMessage(): string | undefined {
|
||||||
return this._disabledMessages;
|
return this._disabledMessages;
|
||||||
@@ -43,36 +53,75 @@ export class Debug extends SketchContribution {
|
|||||||
protected readonly debugToolbarItem = {
|
protected readonly debugToolbarItem = {
|
||||||
id: Debug.Commands.START_DEBUGGING.id,
|
id: Debug.Commands.START_DEBUGGING.id,
|
||||||
command: Debug.Commands.START_DEBUGGING.id,
|
command: Debug.Commands.START_DEBUGGING.id,
|
||||||
tooltip: `${this.disabledMessage ? `Debug - ${this.disabledMessage}` : 'Start Debugging'}`,
|
tooltip: `${
|
||||||
|
this.disabledMessage
|
||||||
|
? nls.localize(
|
||||||
|
'arduino/debug/debugWithMessage',
|
||||||
|
'Debug - {0}',
|
||||||
|
this.disabledMessage
|
||||||
|
)
|
||||||
|
: Debug.Commands.START_DEBUGGING.label
|
||||||
|
}`,
|
||||||
priority: 3,
|
priority: 3,
|
||||||
onDidChange: this.onDisabledMessageDidChange as Event<void>
|
onDidChange: this.onDisabledMessageDidChange as Event<void>,
|
||||||
};
|
};
|
||||||
|
|
||||||
onStart(): void {
|
onStart(): void {
|
||||||
this.onDisabledMessageDidChange(() => this.debugToolbarItem.tooltip = `${this.disabledMessage ? `Debug - ${this.disabledMessage}` : 'Start Debugging'}`);
|
this.onDisabledMessageDidChange(
|
||||||
const refreshState = async (board: Board | undefined = this.boardsServiceProvider.boardsConfig.selectedBoard) => {
|
() =>
|
||||||
|
(this.debugToolbarItem.tooltip = `${
|
||||||
|
this.disabledMessage
|
||||||
|
? nls.localize(
|
||||||
|
'arduino/debug/debugWithMessage',
|
||||||
|
'Debug - {0}',
|
||||||
|
this.disabledMessage
|
||||||
|
)
|
||||||
|
: Debug.Commands.START_DEBUGGING.label
|
||||||
|
}`)
|
||||||
|
);
|
||||||
|
const refreshState = async (
|
||||||
|
board: Board | undefined = this.boardsServiceProvider.boardsConfig
|
||||||
|
.selectedBoard
|
||||||
|
) => {
|
||||||
if (!board) {
|
if (!board) {
|
||||||
this.disabledMessage = 'No board selected';
|
this.disabledMessage = nls.localize(
|
||||||
|
'arduino/common/noBoardSelected',
|
||||||
|
'No board selected'
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const fqbn = board.fqbn;
|
const fqbn = board.fqbn;
|
||||||
if (!fqbn) {
|
if (!fqbn) {
|
||||||
this.disabledMessage = `Platform is not installed for '${board.name}'`;
|
this.disabledMessage = nls.localize(
|
||||||
|
'arduino/debug/noPlatformInstalledFor',
|
||||||
|
"Platform is not installed for '{0}'",
|
||||||
|
board.name
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const details = await this.boardService.getBoardDetails({ fqbn });
|
const details = await this.boardService.getBoardDetails({ fqbn });
|
||||||
if (!details) {
|
if (!details) {
|
||||||
this.disabledMessage = `Platform is not installed for '${board.name}'`;
|
this.disabledMessage = nls.localize(
|
||||||
|
'arduino/debug/noPlatformInstalledFor',
|
||||||
|
"Platform is not installed for '{0}'",
|
||||||
|
board.name
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const { debuggingSupported } = details;
|
const { debuggingSupported } = details;
|
||||||
if (!debuggingSupported) {
|
if (!debuggingSupported) {
|
||||||
this.disabledMessage = `Debugging is not supported by '${board.name}'`;
|
this.disabledMessage = nls.localize(
|
||||||
|
'arduino/debug/debuggingNotSupported',
|
||||||
|
"Debugging is not supported by '{0}'",
|
||||||
|
board.name
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
this.disabledMessage = undefined;
|
this.disabledMessage = undefined;
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
this.boardsServiceProvider.onBoardsConfigChanged(({ selectedBoard }) => refreshState(selectedBoard));
|
this.boardsServiceProvider.onBoardsConfigChanged(({ selectedBoard }) =>
|
||||||
|
refreshState(selectedBoard)
|
||||||
|
);
|
||||||
this.notificationCenter.onPlatformInstalled(() => refreshState());
|
this.notificationCenter.onPlatformInstalled(() => refreshState());
|
||||||
this.notificationCenter.onPlatformUninstalled(() => refreshState());
|
this.notificationCenter.onPlatformUninstalled(() => refreshState());
|
||||||
refreshState();
|
refreshState();
|
||||||
@@ -81,8 +130,9 @@ export class Debug extends SketchContribution {
|
|||||||
registerCommands(registry: CommandRegistry): void {
|
registerCommands(registry: CommandRegistry): void {
|
||||||
registry.registerCommand(Debug.Commands.START_DEBUGGING, {
|
registry.registerCommand(Debug.Commands.START_DEBUGGING, {
|
||||||
execute: () => this.startDebug(),
|
execute: () => this.startDebug(),
|
||||||
isVisible: widget => ArduinoToolbar.is(widget) && widget.side === 'left',
|
isVisible: (widget) =>
|
||||||
isEnabled: () => !this.disabledMessage
|
ArduinoToolbar.is(widget) && widget.side === 'left',
|
||||||
|
isEnabled: () => !this.disabledMessage,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -90,7 +140,10 @@ export class Debug extends SketchContribution {
|
|||||||
registry.registerItem(this.debugToolbarItem);
|
registry.registerItem(this.debugToolbarItem);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected async startDebug(board: Board | undefined = this.boardsServiceProvider.boardsConfig.selectedBoard): Promise<void> {
|
protected async startDebug(
|
||||||
|
board: Board | undefined = this.boardsServiceProvider.boardsConfig
|
||||||
|
.selectedBoard
|
||||||
|
): Promise<void> {
|
||||||
if (!board) {
|
if (!board) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -101,34 +154,41 @@ export class Debug extends SketchContribution {
|
|||||||
await this.hostedPluginSupport.didStart;
|
await this.hostedPluginSupport.didStart;
|
||||||
const [sketch, executables] = await Promise.all([
|
const [sketch, executables] = await Promise.all([
|
||||||
this.sketchServiceClient.currentSketch(),
|
this.sketchServiceClient.currentSketch(),
|
||||||
this.executableService.list()
|
this.executableService.list(),
|
||||||
]);
|
]);
|
||||||
if (!sketch) {
|
if (!sketch) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const [cliPath, sketchPath] = await Promise.all([
|
const ideTempFolderUri = await this.sketchService.getIdeTempFolderUri(
|
||||||
|
sketch
|
||||||
|
);
|
||||||
|
const [cliPath, sketchPath, configPath] = await Promise.all([
|
||||||
this.fileService.fsPath(new URI(executables.cliUri)),
|
this.fileService.fsPath(new URI(executables.cliUri)),
|
||||||
this.fileService.fsPath(new URI(sketch.uri))
|
this.fileService.fsPath(new URI(sketch.uri)),
|
||||||
])
|
this.fileService.fsPath(new URI(ideTempFolderUri)),
|
||||||
|
]);
|
||||||
const config = {
|
const config = {
|
||||||
cliPath,
|
cliPath,
|
||||||
board: {
|
board: {
|
||||||
fqbn,
|
fqbn,
|
||||||
name
|
name,
|
||||||
},
|
},
|
||||||
sketchPath
|
sketchPath,
|
||||||
|
configPath,
|
||||||
};
|
};
|
||||||
return this.commandService.executeCommand('arduino.debug.start', config);
|
return this.commandService.executeCommand('arduino.debug.start', config);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export namespace Debug {
|
export namespace Debug {
|
||||||
export namespace Commands {
|
export namespace Commands {
|
||||||
export const START_DEBUGGING: Command = {
|
export const START_DEBUGGING = Command.toLocalizedCommand(
|
||||||
|
{
|
||||||
id: 'arduino-start-debug',
|
id: 'arduino-start-debug',
|
||||||
label: 'Start Debugging',
|
label: 'Start Debugging',
|
||||||
category: 'Arduino'
|
category: 'Arduino',
|
||||||
}
|
},
|
||||||
|
'vscode/debug.contribution/startDebuggingHelp'
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,14 +3,20 @@ import { CommonCommands } from '@theia/core/lib/browser/common-frontend-contribu
|
|||||||
import { ClipboardService } from '@theia/core/lib/browser/clipboard-service';
|
import { ClipboardService } from '@theia/core/lib/browser/clipboard-service';
|
||||||
import { PreferenceService } from '@theia/core/lib/browser/preferences/preference-service';
|
import { PreferenceService } from '@theia/core/lib/browser/preferences/preference-service';
|
||||||
import { MonacoEditorService } from '@theia/monaco/lib/browser/monaco-editor-service';
|
import { MonacoEditorService } from '@theia/monaco/lib/browser/monaco-editor-service';
|
||||||
import { Contribution, Command, MenuModelRegistry, KeybindingRegistry, CommandRegistry } from './contribution';
|
import {
|
||||||
|
Contribution,
|
||||||
|
Command,
|
||||||
|
MenuModelRegistry,
|
||||||
|
KeybindingRegistry,
|
||||||
|
CommandRegistry,
|
||||||
|
} from './contribution';
|
||||||
import { ArduinoMenus } from '../menu/arduino-menus';
|
import { ArduinoMenus } from '../menu/arduino-menus';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
|
||||||
// TODO: [macOS]: to remove `Start Dictation...` and `Emoji & Symbol` see this thread: https://github.com/electron/electron/issues/8283#issuecomment-269522072
|
// TODO: [macOS]: to remove `Start Dictation...` and `Emoji & Symbol` see this thread: https://github.com/electron/electron/issues/8283#issuecomment-269522072
|
||||||
// Depends on https://github.com/eclipse-theia/theia/pull/7964
|
// Depends on https://github.com/eclipse-theia/theia/pull/7964
|
||||||
@injectable()
|
@injectable()
|
||||||
export class EditContributions extends Contribution {
|
export class EditContributions extends Contribution {
|
||||||
|
|
||||||
@inject(MonacoEditorService)
|
@inject(MonacoEditorService)
|
||||||
protected readonly codeEditorService: MonacoEditorService;
|
protected readonly codeEditorService: MonacoEditorService;
|
||||||
|
|
||||||
@@ -21,14 +27,30 @@ export class EditContributions extends Contribution {
|
|||||||
protected readonly preferences: PreferenceService;
|
protected readonly preferences: PreferenceService;
|
||||||
|
|
||||||
registerCommands(registry: CommandRegistry): void {
|
registerCommands(registry: CommandRegistry): void {
|
||||||
registry.registerCommand(EditContributions.Commands.GO_TO_LINE, { execute: () => this.run('editor.action.gotoLine') });
|
registry.registerCommand(EditContributions.Commands.GO_TO_LINE, {
|
||||||
registry.registerCommand(EditContributions.Commands.TOGGLE_COMMENT, { execute: () => this.run('editor.action.commentLine') });
|
execute: () => this.run('editor.action.gotoLine'),
|
||||||
registry.registerCommand(EditContributions.Commands.INDENT_LINES, { execute: () => this.run('editor.action.indentLines') });
|
});
|
||||||
registry.registerCommand(EditContributions.Commands.OUTDENT_LINES, { execute: () => this.run('editor.action.outdentLines') });
|
registry.registerCommand(EditContributions.Commands.TOGGLE_COMMENT, {
|
||||||
registry.registerCommand(EditContributions.Commands.FIND, { execute: () => this.run('actions.find') });
|
execute: () => this.run('editor.action.commentLine'),
|
||||||
registry.registerCommand(EditContributions.Commands.FIND_NEXT, { execute: () => this.run('actions.findWithSelection') });
|
});
|
||||||
registry.registerCommand(EditContributions.Commands.FIND_PREVIOUS, { execute: () => this.run('editor.action.nextMatchFindAction') });
|
registry.registerCommand(EditContributions.Commands.INDENT_LINES, {
|
||||||
registry.registerCommand(EditContributions.Commands.USE_FOR_FIND, { execute: () => this.run('editor.action.previousSelectionMatchFindAction') });
|
execute: () => this.run('editor.action.indentLines'),
|
||||||
|
});
|
||||||
|
registry.registerCommand(EditContributions.Commands.OUTDENT_LINES, {
|
||||||
|
execute: () => this.run('editor.action.outdentLines'),
|
||||||
|
});
|
||||||
|
registry.registerCommand(EditContributions.Commands.FIND, {
|
||||||
|
execute: () => this.run('actions.find'),
|
||||||
|
});
|
||||||
|
registry.registerCommand(EditContributions.Commands.FIND_NEXT, {
|
||||||
|
execute: () => this.run('actions.findWithSelection'),
|
||||||
|
});
|
||||||
|
registry.registerCommand(EditContributions.Commands.FIND_PREVIOUS, {
|
||||||
|
execute: () => this.run('editor.action.nextMatchFindAction'),
|
||||||
|
});
|
||||||
|
registry.registerCommand(EditContributions.Commands.USE_FOR_FIND, {
|
||||||
|
execute: () => this.run('editor.action.previousSelectionMatchFindAction'),
|
||||||
|
});
|
||||||
registry.registerCommand(EditContributions.Commands.INCREASE_FONT_SIZE, {
|
registry.registerCommand(EditContributions.Commands.INCREASE_FONT_SIZE, {
|
||||||
execute: async () => {
|
execute: async () => {
|
||||||
const settings = await this.settingsService.settings();
|
const settings = await this.settingsService.settings();
|
||||||
@@ -39,7 +61,7 @@ export class EditContributions extends Contribution {
|
|||||||
}
|
}
|
||||||
await this.settingsService.update(settings);
|
await this.settingsService.update(settings);
|
||||||
await this.settingsService.save();
|
await this.settingsService.save();
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
registry.registerCommand(EditContributions.Commands.DECREASE_FONT_SIZE, {
|
registry.registerCommand(EditContributions.Commands.DECREASE_FONT_SIZE, {
|
||||||
execute: async () => {
|
execute: async () => {
|
||||||
@@ -51,117 +73,129 @@ export class EditContributions extends Contribution {
|
|||||||
}
|
}
|
||||||
await this.settingsService.update(settings);
|
await this.settingsService.update(settings);
|
||||||
await this.settingsService.save();
|
await this.settingsService.save();
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
/* Tools */registry.registerCommand(EditContributions.Commands.AUTO_FORMAT, { execute: () => this.run('editor.action.formatDocument') });
|
/* Tools */ registry.registerCommand(
|
||||||
|
EditContributions.Commands.AUTO_FORMAT,
|
||||||
|
{ execute: () => this.run('editor.action.formatDocument') }
|
||||||
|
);
|
||||||
registry.registerCommand(EditContributions.Commands.COPY_FOR_FORUM, {
|
registry.registerCommand(EditContributions.Commands.COPY_FOR_FORUM, {
|
||||||
execute: async () => {
|
|
||||||
const value = await this.currentValue();
|
|
||||||
if (value !== undefined) {
|
|
||||||
this.clipboardService.writeText(`[code]
|
|
||||||
${value}
|
|
||||||
[/code]`)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
registry.registerCommand(EditContributions.Commands.COPY_FOR_GITHUB, {
|
|
||||||
execute: async () => {
|
execute: async () => {
|
||||||
const value = await this.currentValue();
|
const value = await this.currentValue();
|
||||||
if (value !== undefined) {
|
if (value !== undefined) {
|
||||||
this.clipboardService.writeText(`\`\`\`cpp
|
this.clipboardService.writeText(`\`\`\`cpp
|
||||||
${value}
|
${value}
|
||||||
\`\`\``)
|
\`\`\``);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
registerMenus(registry: MenuModelRegistry): void {
|
registerMenus(registry: MenuModelRegistry): void {
|
||||||
registry.registerMenuAction(ArduinoMenus.EDIT__TEXT_CONTROL_GROUP, {
|
registry.registerMenuAction(ArduinoMenus.EDIT__TEXT_CONTROL_GROUP, {
|
||||||
commandId: CommonCommands.CUT.id,
|
commandId: CommonCommands.CUT.id,
|
||||||
order: '0'
|
order: '0',
|
||||||
});
|
});
|
||||||
registry.registerMenuAction(ArduinoMenus.EDIT__TEXT_CONTROL_GROUP, {
|
registry.registerMenuAction(ArduinoMenus.EDIT__TEXT_CONTROL_GROUP, {
|
||||||
commandId: CommonCommands.COPY.id,
|
commandId: CommonCommands.COPY.id,
|
||||||
order: '1'
|
order: '1',
|
||||||
});
|
});
|
||||||
registry.registerMenuAction(ArduinoMenus.EDIT__TEXT_CONTROL_GROUP, {
|
registry.registerMenuAction(ArduinoMenus.EDIT__TEXT_CONTROL_GROUP, {
|
||||||
commandId: EditContributions.Commands.COPY_FOR_FORUM.id,
|
commandId: EditContributions.Commands.COPY_FOR_FORUM.id,
|
||||||
label: 'Copy for Forum',
|
label: nls.localize(
|
||||||
order: '2'
|
'arduino/editor/copyForForum',
|
||||||
});
|
'Copy for Forum (Markdown)'
|
||||||
registry.registerMenuAction(ArduinoMenus.EDIT__TEXT_CONTROL_GROUP, {
|
),
|
||||||
commandId: EditContributions.Commands.COPY_FOR_GITHUB.id,
|
order: '2',
|
||||||
label: 'Copy for GitHub',
|
|
||||||
order: '3'
|
|
||||||
});
|
});
|
||||||
registry.registerMenuAction(ArduinoMenus.EDIT__TEXT_CONTROL_GROUP, {
|
registry.registerMenuAction(ArduinoMenus.EDIT__TEXT_CONTROL_GROUP, {
|
||||||
commandId: CommonCommands.PASTE.id,
|
commandId: CommonCommands.PASTE.id,
|
||||||
order: '4'
|
order: '3',
|
||||||
});
|
});
|
||||||
registry.registerMenuAction(ArduinoMenus.EDIT__TEXT_CONTROL_GROUP, {
|
registry.registerMenuAction(ArduinoMenus.EDIT__TEXT_CONTROL_GROUP, {
|
||||||
commandId: CommonCommands.SELECT_ALL.id,
|
commandId: CommonCommands.SELECT_ALL.id,
|
||||||
order: '5'
|
order: '4',
|
||||||
});
|
});
|
||||||
registry.registerMenuAction(ArduinoMenus.EDIT__TEXT_CONTROL_GROUP, {
|
registry.registerMenuAction(ArduinoMenus.EDIT__TEXT_CONTROL_GROUP, {
|
||||||
commandId: EditContributions.Commands.GO_TO_LINE.id,
|
commandId: EditContributions.Commands.GO_TO_LINE.id,
|
||||||
label: 'Go to Line...',
|
label: nls.localize(
|
||||||
order: '6'
|
'vscode/standaloneStrings/gotoLineActionLabel',
|
||||||
|
'Go to Line...'
|
||||||
|
),
|
||||||
|
order: '5',
|
||||||
});
|
});
|
||||||
|
|
||||||
registry.registerMenuAction(ArduinoMenus.EDIT__CODE_CONTROL_GROUP, {
|
registry.registerMenuAction(ArduinoMenus.EDIT__CODE_CONTROL_GROUP, {
|
||||||
commandId: EditContributions.Commands.TOGGLE_COMMENT.id,
|
commandId: EditContributions.Commands.TOGGLE_COMMENT.id,
|
||||||
label: 'Comment/Uncomment',
|
label: nls.localize(
|
||||||
order: '0'
|
'arduino/editor/commentUncomment',
|
||||||
|
'Comment/Uncomment'
|
||||||
|
),
|
||||||
|
order: '0',
|
||||||
});
|
});
|
||||||
registry.registerMenuAction(ArduinoMenus.EDIT__CODE_CONTROL_GROUP, {
|
registry.registerMenuAction(ArduinoMenus.EDIT__CODE_CONTROL_GROUP, {
|
||||||
commandId: EditContributions.Commands.INDENT_LINES.id,
|
commandId: EditContributions.Commands.INDENT_LINES.id,
|
||||||
label: 'Increase Indent',
|
label: nls.localize('arduino/editor/increaseIndent', 'Increase Indent'),
|
||||||
order: '1'
|
order: '1',
|
||||||
});
|
});
|
||||||
registry.registerMenuAction(ArduinoMenus.EDIT__CODE_CONTROL_GROUP, {
|
registry.registerMenuAction(ArduinoMenus.EDIT__CODE_CONTROL_GROUP, {
|
||||||
commandId: EditContributions.Commands.OUTDENT_LINES.id,
|
commandId: EditContributions.Commands.OUTDENT_LINES.id,
|
||||||
label: 'Decrease Indent',
|
label: nls.localize('arduino/editor/decreaseIndent', 'Decrease Indent'),
|
||||||
order: '2'
|
order: '2',
|
||||||
});
|
});
|
||||||
|
|
||||||
registry.registerMenuAction(ArduinoMenus.EDIT__FONT_CONTROL_GROUP, {
|
registry.registerMenuAction(ArduinoMenus.EDIT__FONT_CONTROL_GROUP, {
|
||||||
commandId: EditContributions.Commands.INCREASE_FONT_SIZE.id,
|
commandId: EditContributions.Commands.INCREASE_FONT_SIZE.id,
|
||||||
label: 'Increase Font Size',
|
label: nls.localize(
|
||||||
order: '0'
|
'arduino/editor/increaseFontSize',
|
||||||
|
'Increase Font Size'
|
||||||
|
),
|
||||||
|
order: '0',
|
||||||
});
|
});
|
||||||
registry.registerMenuAction(ArduinoMenus.EDIT__FONT_CONTROL_GROUP, {
|
registry.registerMenuAction(ArduinoMenus.EDIT__FONT_CONTROL_GROUP, {
|
||||||
commandId: EditContributions.Commands.DECREASE_FONT_SIZE.id,
|
commandId: EditContributions.Commands.DECREASE_FONT_SIZE.id,
|
||||||
label: 'Decrease Font Size',
|
label: nls.localize(
|
||||||
order: '1'
|
'arduino/editor/decreaseFontSize',
|
||||||
|
'Decrease Font Size'
|
||||||
|
),
|
||||||
|
order: '1',
|
||||||
});
|
});
|
||||||
|
|
||||||
registry.registerMenuAction(ArduinoMenus.EDIT__FIND_GROUP, {
|
registry.registerMenuAction(ArduinoMenus.EDIT__FIND_GROUP, {
|
||||||
commandId: EditContributions.Commands.FIND.id,
|
commandId: EditContributions.Commands.FIND.id,
|
||||||
label: 'Find',
|
label: nls.localize('vscode/findController/startFindAction', 'Find'),
|
||||||
order: '0'
|
order: '0',
|
||||||
});
|
});
|
||||||
registry.registerMenuAction(ArduinoMenus.EDIT__FIND_GROUP, {
|
registry.registerMenuAction(ArduinoMenus.EDIT__FIND_GROUP, {
|
||||||
commandId: EditContributions.Commands.FIND_NEXT.id,
|
commandId: EditContributions.Commands.FIND_NEXT.id,
|
||||||
label: 'Find Next',
|
label: nls.localize(
|
||||||
order: '1'
|
'vscode/findController/findNextMatchAction',
|
||||||
|
'Find Next'
|
||||||
|
),
|
||||||
|
order: '1',
|
||||||
});
|
});
|
||||||
registry.registerMenuAction(ArduinoMenus.EDIT__FIND_GROUP, {
|
registry.registerMenuAction(ArduinoMenus.EDIT__FIND_GROUP, {
|
||||||
commandId: EditContributions.Commands.FIND_PREVIOUS.id,
|
commandId: EditContributions.Commands.FIND_PREVIOUS.id,
|
||||||
label: 'Find Previous',
|
label: nls.localize(
|
||||||
order: '2'
|
'vscode/findController/findPreviousMatchAction',
|
||||||
|
'Find Previous'
|
||||||
|
),
|
||||||
|
order: '2',
|
||||||
});
|
});
|
||||||
registry.registerMenuAction(ArduinoMenus.EDIT__FIND_GROUP, {
|
registry.registerMenuAction(ArduinoMenus.EDIT__FIND_GROUP, {
|
||||||
commandId: EditContributions.Commands.USE_FOR_FIND.id,
|
commandId: EditContributions.Commands.USE_FOR_FIND.id,
|
||||||
label: 'Use Selection for Find', // XXX: The Java IDE uses `Use Selection For Find`.
|
label: nls.localize(
|
||||||
order: '3'
|
'vscode/findController/startFindWithSelectionAction',
|
||||||
|
'Use Selection for Find'
|
||||||
|
), // XXX: The Java IDE uses `Use Selection For Find`.
|
||||||
|
order: '3',
|
||||||
});
|
});
|
||||||
|
|
||||||
// `Tools`
|
// `Tools`
|
||||||
registry.registerMenuAction(ArduinoMenus.TOOLS__MAIN_GROUP, {
|
registry.registerMenuAction(ArduinoMenus.TOOLS__MAIN_GROUP, {
|
||||||
commandId: EditContributions.Commands.AUTO_FORMAT.id,
|
commandId: EditContributions.Commands.AUTO_FORMAT.id,
|
||||||
label: 'Auto Format', // XXX: The Java IDE uses `Use Selection For Find`.
|
label: nls.localize('arduino/editor/autoFormat', 'Auto Format'), // XXX: The Java IDE uses `Use Selection For Find`.
|
||||||
order: '0'
|
order: '0',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -169,60 +203,58 @@ ${value}
|
|||||||
registry.registerKeybinding({
|
registry.registerKeybinding({
|
||||||
command: EditContributions.Commands.COPY_FOR_FORUM.id,
|
command: EditContributions.Commands.COPY_FOR_FORUM.id,
|
||||||
keybinding: 'CtrlCmd+Shift+C',
|
keybinding: 'CtrlCmd+Shift+C',
|
||||||
when: 'editorFocus'
|
when: 'editorFocus',
|
||||||
});
|
|
||||||
registry.registerKeybinding({
|
|
||||||
command: EditContributions.Commands.COPY_FOR_GITHUB.id,
|
|
||||||
keybinding: 'CtrlCmd+Alt+C',
|
|
||||||
when: 'editorFocus'
|
|
||||||
});
|
});
|
||||||
registry.registerKeybinding({
|
registry.registerKeybinding({
|
||||||
command: EditContributions.Commands.GO_TO_LINE.id,
|
command: EditContributions.Commands.GO_TO_LINE.id,
|
||||||
keybinding: 'CtrlCmd+L',
|
keybinding: 'CtrlCmd+L',
|
||||||
when: 'editorFocus'
|
when: 'editorFocus',
|
||||||
});
|
});
|
||||||
|
|
||||||
registry.registerKeybinding({
|
registry.registerKeybinding({
|
||||||
command: EditContributions.Commands.TOGGLE_COMMENT.id,
|
command: EditContributions.Commands.TOGGLE_COMMENT.id,
|
||||||
keybinding: 'CtrlCmd+/',
|
keybinding: 'CtrlCmd+/',
|
||||||
when: 'editorFocus'
|
when: 'editorFocus',
|
||||||
});
|
});
|
||||||
|
|
||||||
registry.registerKeybinding({
|
registry.registerKeybinding({
|
||||||
command: EditContributions.Commands.INCREASE_FONT_SIZE.id,
|
command: EditContributions.Commands.INCREASE_FONT_SIZE.id,
|
||||||
keybinding: 'CtrlCmd+='
|
keybinding: 'CtrlCmd+=',
|
||||||
});
|
});
|
||||||
registry.registerKeybinding({
|
registry.registerKeybinding({
|
||||||
command: EditContributions.Commands.DECREASE_FONT_SIZE.id,
|
command: EditContributions.Commands.DECREASE_FONT_SIZE.id,
|
||||||
keybinding: 'CtrlCmd+-'
|
keybinding: 'CtrlCmd+-',
|
||||||
});
|
});
|
||||||
|
|
||||||
registry.registerKeybinding({
|
registry.registerKeybinding({
|
||||||
command: EditContributions.Commands.FIND.id,
|
command: EditContributions.Commands.FIND.id,
|
||||||
keybinding: 'CtrlCmd+F'
|
keybinding: 'CtrlCmd+F',
|
||||||
});
|
});
|
||||||
registry.registerKeybinding({
|
registry.registerKeybinding({
|
||||||
command: EditContributions.Commands.FIND_NEXT.id,
|
command: EditContributions.Commands.FIND_NEXT.id,
|
||||||
keybinding: 'CtrlCmd+G'
|
keybinding: 'CtrlCmd+G',
|
||||||
});
|
});
|
||||||
registry.registerKeybinding({
|
registry.registerKeybinding({
|
||||||
command: EditContributions.Commands.FIND_PREVIOUS.id,
|
command: EditContributions.Commands.FIND_PREVIOUS.id,
|
||||||
keybinding: 'CtrlCmd+Shift+G'
|
keybinding: 'CtrlCmd+Shift+G',
|
||||||
});
|
});
|
||||||
registry.registerKeybinding({
|
registry.registerKeybinding({
|
||||||
command: EditContributions.Commands.USE_FOR_FIND.id,
|
command: EditContributions.Commands.USE_FOR_FIND.id,
|
||||||
keybinding: 'CtrlCmd+E'
|
keybinding: 'CtrlCmd+E',
|
||||||
});
|
});
|
||||||
|
|
||||||
// `Tools`
|
// `Tools`
|
||||||
registry.registerKeybinding({
|
registry.registerKeybinding({
|
||||||
command: EditContributions.Commands.AUTO_FORMAT.id,
|
command: EditContributions.Commands.AUTO_FORMAT.id,
|
||||||
keybinding: 'CtrlCmd+T'
|
keybinding: 'CtrlCmd+T',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
protected async current(): Promise<monaco.editor.ICodeEditor | undefined> {
|
protected async current(): Promise<monaco.editor.ICodeEditor | undefined> {
|
||||||
return this.codeEditorService.getFocusedCodeEditor() || this.codeEditorService.getActiveCodeEditor();
|
return (
|
||||||
|
this.codeEditorService.getFocusedCodeEditor() ||
|
||||||
|
this.codeEditorService.getActiveCodeEditor()
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected async currentValue(): Promise<string | undefined> {
|
protected async currentValue(): Promise<string | undefined> {
|
||||||
@@ -246,49 +278,45 @@ ${value}
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export namespace EditContributions {
|
export namespace EditContributions {
|
||||||
export namespace Commands {
|
export namespace Commands {
|
||||||
export const COPY_FOR_FORUM: Command = {
|
export const COPY_FOR_FORUM: Command = {
|
||||||
id: 'arduino-copy-for-forum'
|
id: 'arduino-copy-for-forum',
|
||||||
};
|
|
||||||
export const COPY_FOR_GITHUB: Command = {
|
|
||||||
id: 'arduino-copy-for-github'
|
|
||||||
};
|
};
|
||||||
export const GO_TO_LINE: Command = {
|
export const GO_TO_LINE: Command = {
|
||||||
id: 'arduino-go-to-line'
|
id: 'arduino-go-to-line',
|
||||||
};
|
};
|
||||||
export const TOGGLE_COMMENT: Command = {
|
export const TOGGLE_COMMENT: Command = {
|
||||||
id: 'arduino-toggle-comment'
|
id: 'arduino-toggle-comment',
|
||||||
};
|
};
|
||||||
export const INDENT_LINES: Command = {
|
export const INDENT_LINES: Command = {
|
||||||
id: 'arduino-indent-lines'
|
id: 'arduino-indent-lines',
|
||||||
};
|
};
|
||||||
export const OUTDENT_LINES: Command = {
|
export const OUTDENT_LINES: Command = {
|
||||||
id: 'arduino-outdent-lines'
|
id: 'arduino-outdent-lines',
|
||||||
};
|
};
|
||||||
export const FIND: Command = {
|
export const FIND: Command = {
|
||||||
id: 'arduino-find'
|
id: 'arduino-find',
|
||||||
};
|
};
|
||||||
export const FIND_NEXT: Command = {
|
export const FIND_NEXT: Command = {
|
||||||
id: 'arduino-find-next'
|
id: 'arduino-find-next',
|
||||||
};
|
};
|
||||||
export const FIND_PREVIOUS: Command = {
|
export const FIND_PREVIOUS: Command = {
|
||||||
id: 'arduino-find-previous'
|
id: 'arduino-find-previous',
|
||||||
};
|
};
|
||||||
export const USE_FOR_FIND: Command = {
|
export const USE_FOR_FIND: Command = {
|
||||||
id: 'arduino-for-find'
|
id: 'arduino-for-find',
|
||||||
};
|
};
|
||||||
export const INCREASE_FONT_SIZE: Command = {
|
export const INCREASE_FONT_SIZE: Command = {
|
||||||
id: 'arduino-increase-font-size'
|
id: 'arduino-increase-font-size',
|
||||||
};
|
};
|
||||||
export const DECREASE_FONT_SIZE: Command = {
|
export const DECREASE_FONT_SIZE: Command = {
|
||||||
id: 'arduino-decrease-font-size'
|
id: 'arduino-decrease-font-size',
|
||||||
};
|
};
|
||||||
export const AUTO_FORMAT: Command = {
|
export const AUTO_FORMAT: Command = {
|
||||||
id: 'arduino-auto-format' // `Auto Format` should belong to `Tool`.
|
id: 'arduino-auto-format', // `Auto Format` should belong to `Tool`.
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,19 +1,31 @@
|
|||||||
import * as PQueue from 'p-queue';
|
import * as PQueue from 'p-queue';
|
||||||
import { inject, injectable, postConstruct } from 'inversify';
|
import { inject, injectable, postConstruct } from 'inversify';
|
||||||
import { MenuPath, CompositeMenuNode } from '@theia/core/lib/common/menu';
|
import { CommandHandler } from '@theia/core/lib/common/command';
|
||||||
import { Disposable, DisposableCollection } from '@theia/core/lib/common/disposable';
|
import {
|
||||||
|
MenuPath,
|
||||||
|
CompositeMenuNode,
|
||||||
|
SubMenuOptions,
|
||||||
|
} from '@theia/core/lib/common/menu';
|
||||||
|
import {
|
||||||
|
Disposable,
|
||||||
|
DisposableCollection,
|
||||||
|
} from '@theia/core/lib/common/disposable';
|
||||||
import { OpenSketch } from './open-sketch';
|
import { OpenSketch } from './open-sketch';
|
||||||
import { ArduinoMenus, PlaceholderMenuNode } from '../menu/arduino-menus';
|
import { ArduinoMenus, PlaceholderMenuNode } from '../menu/arduino-menus';
|
||||||
import { MainMenuManager } from '../../common/main-menu-manager';
|
import { MainMenuManager } from '../../common/main-menu-manager';
|
||||||
import { BoardsServiceProvider } from '../boards/boards-service-provider';
|
import { BoardsServiceProvider } from '../boards/boards-service-provider';
|
||||||
import { ExamplesService, ExampleContainer } from '../../common/protocol/examples-service';
|
import { ExamplesService } from '../../common/protocol/examples-service';
|
||||||
import { SketchContribution, CommandRegistry, MenuModelRegistry } from './contribution';
|
import {
|
||||||
|
SketchContribution,
|
||||||
|
CommandRegistry,
|
||||||
|
MenuModelRegistry,
|
||||||
|
} from './contribution';
|
||||||
import { NotificationCenter } from '../notification-center';
|
import { NotificationCenter } from '../notification-center';
|
||||||
import { Board } from '../../common/protocol';
|
import { Board, Sketch, SketchContainer } from '../../common/protocol';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export abstract class Examples extends SketchContribution {
|
export abstract class Examples extends SketchContribution {
|
||||||
|
|
||||||
@inject(CommandRegistry)
|
@inject(CommandRegistry)
|
||||||
protected readonly commandRegistry: CommandRegistry;
|
protected readonly commandRegistry: CommandRegistry;
|
||||||
|
|
||||||
@@ -33,7 +45,9 @@ export abstract class Examples extends SketchContribution {
|
|||||||
|
|
||||||
@postConstruct()
|
@postConstruct()
|
||||||
init(): void {
|
init(): void {
|
||||||
this.boardsServiceClient.onBoardsConfigChanged(({ selectedBoard }) => this.handleBoardChanged(selectedBoard));
|
this.boardsServiceClient.onBoardsConfigChanged(({ selectedBoard }) =>
|
||||||
|
this.handleBoardChanged(selectedBoard)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected handleBoardChanged(board: Board | undefined): void {
|
protected handleBoardChanged(board: Board | undefined): void {
|
||||||
@@ -45,7 +59,8 @@ export abstract class Examples extends SketchContribution {
|
|||||||
// This is a hack the ensures the desired menu ordering! We cannot use https://github.com/eclipse-theia/theia/pull/8377 due to ATL-222.
|
// This is a hack the ensures the desired menu ordering! We cannot use https://github.com/eclipse-theia/theia/pull/8377 due to ATL-222.
|
||||||
const index = ArduinoMenus.FILE__EXAMPLES_SUBMENU.length - 1;
|
const index = ArduinoMenus.FILE__EXAMPLES_SUBMENU.length - 1;
|
||||||
const menuId = ArduinoMenus.FILE__EXAMPLES_SUBMENU[index];
|
const menuId = ArduinoMenus.FILE__EXAMPLES_SUBMENU[index];
|
||||||
const groupPath = index === 0 ? [] : ArduinoMenus.FILE__EXAMPLES_SUBMENU.slice(0, index);
|
const groupPath =
|
||||||
|
index === 0 ? [] : ArduinoMenus.FILE__EXAMPLES_SUBMENU.slice(0, index);
|
||||||
const parent: CompositeMenuNode = (registry as any).findGroup(groupPath);
|
const parent: CompositeMenuNode = (registry as any).findGroup(groupPath);
|
||||||
const examples = new CompositeMenuNode(menuId, '', { order: '4' });
|
const examples = new CompositeMenuNode(menuId, '', { order: '4' });
|
||||||
parent.addNode(examples);
|
parent.addNode(examples);
|
||||||
@@ -55,72 +70,132 @@ export abstract class Examples extends SketchContribution {
|
|||||||
}
|
}
|
||||||
// Registering the same submenu multiple times has no side-effect.
|
// Registering the same submenu multiple times has no side-effect.
|
||||||
// TODO: unregister submenu? https://github.com/eclipse-theia/theia/issues/7300
|
// TODO: unregister submenu? https://github.com/eclipse-theia/theia/issues/7300
|
||||||
registry.registerSubmenu(ArduinoMenus.FILE__EXAMPLES_SUBMENU, 'Examples', { order: '4' });
|
registry.registerSubmenu(
|
||||||
|
ArduinoMenus.FILE__EXAMPLES_SUBMENU,
|
||||||
|
nls.localize('arduino/examples/menu', 'Examples'),
|
||||||
|
{
|
||||||
|
order: '4',
|
||||||
|
}
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
registerRecursively(
|
registerRecursively(
|
||||||
exampleContainerOrPlaceholder: ExampleContainer | string,
|
sketchContainerOrPlaceholder:
|
||||||
|
| SketchContainer
|
||||||
|
| (Sketch | SketchContainer)[]
|
||||||
|
| string,
|
||||||
menuPath: MenuPath,
|
menuPath: MenuPath,
|
||||||
pushToDispose: DisposableCollection = new DisposableCollection()): void {
|
pushToDispose: DisposableCollection = new DisposableCollection(),
|
||||||
|
subMenuOptions?: SubMenuOptions | undefined
|
||||||
if (typeof exampleContainerOrPlaceholder === 'string') {
|
): void {
|
||||||
const placeholder = new PlaceholderMenuNode(menuPath, exampleContainerOrPlaceholder);
|
if (typeof sketchContainerOrPlaceholder === 'string') {
|
||||||
|
const placeholder = new PlaceholderMenuNode(
|
||||||
|
menuPath,
|
||||||
|
sketchContainerOrPlaceholder
|
||||||
|
);
|
||||||
this.menuRegistry.registerMenuNode(menuPath, placeholder);
|
this.menuRegistry.registerMenuNode(menuPath, placeholder);
|
||||||
pushToDispose.push(Disposable.create(() => this.menuRegistry.unregisterMenuNode(placeholder.id)));
|
pushToDispose.push(
|
||||||
|
Disposable.create(() =>
|
||||||
|
this.menuRegistry.unregisterMenuNode(placeholder.id)
|
||||||
|
)
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
const { label, sketches, children } = exampleContainerOrPlaceholder;
|
const sketches: Sketch[] = [];
|
||||||
const submenuPath = [...menuPath, label];
|
const children: SketchContainer[] = [];
|
||||||
this.menuRegistry.registerSubmenu(submenuPath, label);
|
let submenuPath = menuPath;
|
||||||
children.forEach(child => this.registerRecursively(child, submenuPath, pushToDispose));
|
|
||||||
|
if (SketchContainer.is(sketchContainerOrPlaceholder)) {
|
||||||
|
const { label } = sketchContainerOrPlaceholder;
|
||||||
|
submenuPath = [...menuPath, label];
|
||||||
|
this.menuRegistry.registerSubmenu(submenuPath, label, subMenuOptions);
|
||||||
|
sketches.push(...sketchContainerOrPlaceholder.sketches);
|
||||||
|
children.push(...sketchContainerOrPlaceholder.children);
|
||||||
|
} else {
|
||||||
|
for (const sketchOrContainer of sketchContainerOrPlaceholder) {
|
||||||
|
if (SketchContainer.is(sketchOrContainer)) {
|
||||||
|
children.push(sketchOrContainer);
|
||||||
|
} else {
|
||||||
|
sketches.push(sketchOrContainer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
children.forEach((child) =>
|
||||||
|
this.registerRecursively(child, submenuPath, pushToDispose)
|
||||||
|
);
|
||||||
for (const sketch of sketches) {
|
for (const sketch of sketches) {
|
||||||
const { uri } = sketch;
|
const { uri } = sketch;
|
||||||
const commandId = `arduino-open-example-${submenuPath.join(':')}--${uri}`;
|
const commandId = `arduino-open-example-${submenuPath.join(
|
||||||
|
':'
|
||||||
|
)}--${uri}`;
|
||||||
const command = { id: commandId };
|
const command = { id: commandId };
|
||||||
const handler = {
|
const handler = this.createHandler(uri);
|
||||||
execute: async () => {
|
pushToDispose.push(
|
||||||
const sketch = await this.sketchService.cloneExample(uri);
|
this.commandRegistry.registerCommand(command, handler)
|
||||||
this.commandService.executeCommand(OpenSketch.Commands.OPEN_SKETCH.id, sketch);
|
);
|
||||||
}
|
this.menuRegistry.registerMenuAction(submenuPath, {
|
||||||
};
|
commandId,
|
||||||
pushToDispose.push(this.commandRegistry.registerCommand(command, handler));
|
label: sketch.name,
|
||||||
this.menuRegistry.registerMenuAction(submenuPath, { commandId, label: sketch.name });
|
order: sketch.name.toLocaleLowerCase(),
|
||||||
pushToDispose.push(Disposable.create(() => this.menuRegistry.unregisterMenuAction(command)));
|
});
|
||||||
|
pushToDispose.push(
|
||||||
|
Disposable.create(() =>
|
||||||
|
this.menuRegistry.unregisterMenuAction(command)
|
||||||
|
)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected createHandler(uri: string): CommandHandler {
|
||||||
|
return {
|
||||||
|
execute: async () => {
|
||||||
|
const sketch = await this.sketchService.cloneExample(uri);
|
||||||
|
return this.commandService.executeCommand(
|
||||||
|
OpenSketch.Commands.OPEN_SKETCH.id,
|
||||||
|
sketch
|
||||||
|
);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export class BuiltInExamples extends Examples {
|
export class BuiltInExamples extends Examples {
|
||||||
|
|
||||||
onStart(): void {
|
onStart(): void {
|
||||||
this.register(); // no `await`
|
this.register(); // no `await`
|
||||||
}
|
}
|
||||||
|
|
||||||
protected async register() {
|
protected async register(): Promise<void> {
|
||||||
let exampleContainers: ExampleContainer[] | undefined;
|
let sketchContainers: SketchContainer[] | undefined;
|
||||||
try {
|
try {
|
||||||
exampleContainers = await this.examplesService.builtIns();
|
sketchContainers = await this.examplesService.builtIns();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('Could not initialize built-in examples.', e);
|
console.error('Could not initialize built-in examples.', e);
|
||||||
this.messageService.error('Could not initialize built-in examples.');
|
this.messageService.error(
|
||||||
|
nls.localize(
|
||||||
|
'arduino/examples/couldNotInitializeExamples',
|
||||||
|
'Could not initialize built-in examples.'
|
||||||
|
)
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
this.toDispose.dispose();
|
this.toDispose.dispose();
|
||||||
for (const container of ['Built-in examples', ...exampleContainers]) {
|
for (const container of [
|
||||||
this.registerRecursively(container, ArduinoMenus.EXAMPLES__BUILT_IN_GROUP, this.toDispose);
|
nls.localize('arduino/examples/builtInExamples', 'Built-in examples'),
|
||||||
|
...sketchContainers,
|
||||||
|
]) {
|
||||||
|
this.registerRecursively(
|
||||||
|
container,
|
||||||
|
ArduinoMenus.EXAMPLES__BUILT_IN_GROUP,
|
||||||
|
this.toDispose
|
||||||
|
);
|
||||||
}
|
}
|
||||||
this.menuManager.update();
|
this.menuManager.update();
|
||||||
// TODO: remove
|
|
||||||
console.log(typeof this.menuRegistry);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export class LibraryExamples extends Examples {
|
export class LibraryExamples extends Examples {
|
||||||
|
|
||||||
@inject(NotificationCenter)
|
@inject(NotificationCenter)
|
||||||
protected readonly notificationCenter: NotificationCenter;
|
protected readonly notificationCenter: NotificationCenter;
|
||||||
|
|
||||||
@@ -136,34 +211,58 @@ export class LibraryExamples extends Examples {
|
|||||||
this.register(board);
|
this.register(board);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected async register(board: Board | undefined = this.boardsServiceClient.boardsConfig.selectedBoard) {
|
protected async register(
|
||||||
|
board: Board | undefined = this.boardsServiceClient.boardsConfig
|
||||||
|
.selectedBoard
|
||||||
|
): Promise<void> {
|
||||||
return this.queue.add(async () => {
|
return this.queue.add(async () => {
|
||||||
this.toDispose.dispose();
|
this.toDispose.dispose();
|
||||||
if (!board || !board.fqbn) {
|
const fqbn = board?.fqbn;
|
||||||
return;
|
const name = board?.name;
|
||||||
}
|
// Shows all examples when no board is selected, or the platform of the currently selected board is not installed.
|
||||||
const { fqbn, name } = board;
|
const { user, current, any } = await this.examplesService.installed({
|
||||||
const { user, current, any } = await this.examplesService.installed({ fqbn });
|
fqbn,
|
||||||
|
});
|
||||||
if (user.length) {
|
if (user.length) {
|
||||||
(user as any).unshift('Examples from Custom Libraries');
|
(user as any).unshift(
|
||||||
|
nls.localize(
|
||||||
|
'arduino/examples/customLibrary',
|
||||||
|
'Examples from Custom Libraries'
|
||||||
|
)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if (current.length) {
|
if (name && fqbn && current.length) {
|
||||||
(current as any).unshift(`Examples for ${name}`);
|
(current as any).unshift(
|
||||||
|
nls.localize('arduino/examples/for', 'Examples for {0}', name)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if (any.length) {
|
if (any.length) {
|
||||||
(any as any).unshift('Examples for any board');
|
(any as any).unshift(
|
||||||
|
nls.localize('arduino/examples/forAny', 'Examples for any board')
|
||||||
|
);
|
||||||
}
|
}
|
||||||
for (const container of user) {
|
for (const container of user) {
|
||||||
this.registerRecursively(container, ArduinoMenus.EXAMPLES__USER_LIBS_GROUP, this.toDispose);
|
this.registerRecursively(
|
||||||
|
container,
|
||||||
|
ArduinoMenus.EXAMPLES__USER_LIBS_GROUP,
|
||||||
|
this.toDispose
|
||||||
|
);
|
||||||
}
|
}
|
||||||
for (const container of current) {
|
for (const container of current) {
|
||||||
this.registerRecursively(container, ArduinoMenus.EXAMPLES__CURRENT_BOARD_GROUP, this.toDispose);
|
this.registerRecursively(
|
||||||
|
container,
|
||||||
|
ArduinoMenus.EXAMPLES__CURRENT_BOARD_GROUP,
|
||||||
|
this.toDispose
|
||||||
|
);
|
||||||
}
|
}
|
||||||
for (const container of any) {
|
for (const container of any) {
|
||||||
this.registerRecursively(container, ArduinoMenus.EXAMPLES__ANY_BOARD_GROUP, this.toDispose);
|
this.registerRecursively(
|
||||||
|
container,
|
||||||
|
ArduinoMenus.EXAMPLES__ANY_BOARD_GROUP,
|
||||||
|
this.toDispose
|
||||||
|
);
|
||||||
}
|
}
|
||||||
this.menuManager.update();
|
this.menuManager.update();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,13 +3,20 @@ import { MonacoEditor } from '@theia/monaco/lib/browser/monaco-editor';
|
|||||||
import { EditorManager } from '@theia/editor/lib/browser/editor-manager';
|
import { EditorManager } from '@theia/editor/lib/browser/editor-manager';
|
||||||
import { WindowService } from '@theia/core/lib/browser/window/window-service';
|
import { WindowService } from '@theia/core/lib/browser/window/window-service';
|
||||||
import { CommandHandler } from '@theia/core/lib/common/command';
|
import { CommandHandler } from '@theia/core/lib/common/command';
|
||||||
import { QuickInputService } from '@theia/core/lib/browser/quick-open/quick-input-service';
|
|
||||||
import { ArduinoMenus } from '../menu/arduino-menus';
|
import { ArduinoMenus } from '../menu/arduino-menus';
|
||||||
import { Contribution, Command, MenuModelRegistry, CommandRegistry, KeybindingRegistry } from './contribution';
|
import { QuickInputService } from '@theia/core/lib/browser/quick-input/quick-input-service';
|
||||||
|
import {
|
||||||
|
Contribution,
|
||||||
|
Command,
|
||||||
|
MenuModelRegistry,
|
||||||
|
CommandRegistry,
|
||||||
|
KeybindingRegistry,
|
||||||
|
} from './contribution';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
import { IDEUpdaterCommands } from '../ide-updater/ide-updater-commands';
|
||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export class Help extends Contribution {
|
export class Help extends Contribution {
|
||||||
|
|
||||||
@inject(EditorManager)
|
@inject(EditorManager)
|
||||||
protected readonly editorManager: EditorManager;
|
protected readonly editorManager: EditorManager;
|
||||||
|
|
||||||
@@ -20,14 +27,28 @@ export class Help extends Contribution {
|
|||||||
protected readonly quickInputService: QuickInputService;
|
protected readonly quickInputService: QuickInputService;
|
||||||
|
|
||||||
registerCommands(registry: CommandRegistry): void {
|
registerCommands(registry: CommandRegistry): void {
|
||||||
const open = (url: string) => this.windowService.openNewWindow(url, { external: true });
|
const open = (url: string) =>
|
||||||
const createOpenHandler = (url: string) => <CommandHandler>{
|
this.windowService.openNewWindow(url, { external: true });
|
||||||
execute: () => open(url)
|
const createOpenHandler = (url: string) =>
|
||||||
|
<CommandHandler>{
|
||||||
|
execute: () => open(url),
|
||||||
};
|
};
|
||||||
registry.registerCommand(Help.Commands.GETTING_STARTED, createOpenHandler('https://www.arduino.cc/en/Guide'));
|
registry.registerCommand(
|
||||||
registry.registerCommand(Help.Commands.ENVIRONMENT, createOpenHandler('https://www.arduino.cc/en/Guide/Environment'));
|
Help.Commands.GETTING_STARTED,
|
||||||
registry.registerCommand(Help.Commands.TROUBLESHOOTING, createOpenHandler('https://support.arduino.cc/hc/en-us'));
|
createOpenHandler('https://www.arduino.cc/en/Guide')
|
||||||
registry.registerCommand(Help.Commands.REFERENCE, createOpenHandler('https://www.arduino.cc/reference/en/'));
|
);
|
||||||
|
registry.registerCommand(
|
||||||
|
Help.Commands.ENVIRONMENT,
|
||||||
|
createOpenHandler('https://www.arduino.cc/en/Guide/Environment')
|
||||||
|
);
|
||||||
|
registry.registerCommand(
|
||||||
|
Help.Commands.TROUBLESHOOTING,
|
||||||
|
createOpenHandler('https://support.arduino.cc/hc/en-us')
|
||||||
|
);
|
||||||
|
registry.registerCommand(
|
||||||
|
Help.Commands.REFERENCE,
|
||||||
|
createOpenHandler('https://www.arduino.cc/reference/en/')
|
||||||
|
);
|
||||||
registry.registerCommand(Help.Commands.FIND_IN_REFERENCE, {
|
registry.registerCommand(Help.Commands.FIND_IN_REFERENCE, {
|
||||||
execute: async () => {
|
execute: async () => {
|
||||||
let searchFor: string | undefined = undefined;
|
let searchFor: string | undefined = undefined;
|
||||||
@@ -41,97 +62,110 @@ export class Help extends Contribution {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!searchFor) {
|
if (!searchFor) {
|
||||||
searchFor = await this.quickInputService.open({
|
searchFor = await this.quickInputService.input({
|
||||||
prompt: 'Search on Arduino.cc',
|
prompt: nls.localize('arduino/help/search', 'Search on Arduino.cc'),
|
||||||
placeHolder: 'Type a keyword'
|
placeHolder: nls.localize('arduino/help/keyword', 'Type a keyword'),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if (searchFor) {
|
if (searchFor) {
|
||||||
return open(`https://www.arduino.cc/search?q=${encodeURIComponent(searchFor)}&tab=reference`);
|
return open(
|
||||||
}
|
`https://www.arduino.cc/search?q=${encodeURIComponent(
|
||||||
|
searchFor
|
||||||
|
)}&tab=reference`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
},
|
||||||
});
|
});
|
||||||
registry.registerCommand(Help.Commands.FAQ, createOpenHandler('https://support.arduino.cc/hc/en-us'));
|
registry.registerCommand(
|
||||||
registry.registerCommand(Help.Commands.VISIT_ARDUINO, createOpenHandler('https://www.arduino.cc/'));
|
Help.Commands.FAQ,
|
||||||
|
createOpenHandler('https://support.arduino.cc/hc/en-us')
|
||||||
|
);
|
||||||
|
registry.registerCommand(
|
||||||
|
Help.Commands.VISIT_ARDUINO,
|
||||||
|
createOpenHandler('https://www.arduino.cc/')
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
registerMenus(registry: MenuModelRegistry): void {
|
registerMenus(registry: MenuModelRegistry): void {
|
||||||
registry.registerMenuAction(ArduinoMenus.HELP__MAIN_GROUP, {
|
registry.registerMenuAction(ArduinoMenus.HELP__MAIN_GROUP, {
|
||||||
commandId: Help.Commands.GETTING_STARTED.id,
|
commandId: Help.Commands.GETTING_STARTED.id,
|
||||||
order: '0'
|
order: '0',
|
||||||
});
|
});
|
||||||
registry.registerMenuAction(ArduinoMenus.HELP__MAIN_GROUP, {
|
registry.registerMenuAction(ArduinoMenus.HELP__MAIN_GROUP, {
|
||||||
commandId: Help.Commands.ENVIRONMENT.id,
|
commandId: Help.Commands.ENVIRONMENT.id,
|
||||||
order: '1'
|
order: '1',
|
||||||
});
|
});
|
||||||
registry.registerMenuAction(ArduinoMenus.HELP__MAIN_GROUP, {
|
registry.registerMenuAction(ArduinoMenus.HELP__MAIN_GROUP, {
|
||||||
commandId: Help.Commands.TROUBLESHOOTING.id,
|
commandId: Help.Commands.TROUBLESHOOTING.id,
|
||||||
order: '2'
|
order: '2',
|
||||||
});
|
});
|
||||||
registry.registerMenuAction(ArduinoMenus.HELP__MAIN_GROUP, {
|
registry.registerMenuAction(ArduinoMenus.HELP__MAIN_GROUP, {
|
||||||
commandId: Help.Commands.REFERENCE.id,
|
commandId: Help.Commands.REFERENCE.id,
|
||||||
order: '3'
|
order: '3',
|
||||||
});
|
});
|
||||||
|
|
||||||
registry.registerMenuAction(ArduinoMenus.HELP__FIND_GROUP, {
|
registry.registerMenuAction(ArduinoMenus.HELP__FIND_GROUP, {
|
||||||
commandId: Help.Commands.FIND_IN_REFERENCE.id,
|
commandId: Help.Commands.FIND_IN_REFERENCE.id,
|
||||||
order: '4'
|
order: '4',
|
||||||
});
|
});
|
||||||
registry.registerMenuAction(ArduinoMenus.HELP__FIND_GROUP, {
|
registry.registerMenuAction(ArduinoMenus.HELP__FIND_GROUP, {
|
||||||
commandId: Help.Commands.FAQ.id,
|
commandId: Help.Commands.FAQ.id,
|
||||||
order: '5'
|
order: '5',
|
||||||
});
|
});
|
||||||
registry.registerMenuAction(ArduinoMenus.HELP__FIND_GROUP, {
|
registry.registerMenuAction(ArduinoMenus.HELP__FIND_GROUP, {
|
||||||
commandId: Help.Commands.VISIT_ARDUINO.id,
|
commandId: Help.Commands.VISIT_ARDUINO.id,
|
||||||
order: '6'
|
order: '6',
|
||||||
|
});
|
||||||
|
registry.registerMenuAction(ArduinoMenus.HELP__FIND_GROUP, {
|
||||||
|
commandId: IDEUpdaterCommands.CHECK_FOR_UPDATES.id,
|
||||||
|
order: '7',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
registerKeybindings(registry: KeybindingRegistry): void {
|
registerKeybindings(registry: KeybindingRegistry): void {
|
||||||
registry.registerKeybinding({
|
registry.registerKeybinding({
|
||||||
command: Help.Commands.FIND_IN_REFERENCE.id,
|
command: Help.Commands.FIND_IN_REFERENCE.id,
|
||||||
keybinding: 'CtrlCmd+Shift+F'
|
keybinding: 'CtrlCmd+Shift+F',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export namespace Help {
|
export namespace Help {
|
||||||
export namespace Commands {
|
export namespace Commands {
|
||||||
export const GETTING_STARTED: Command = {
|
export const GETTING_STARTED: Command = {
|
||||||
id: 'arduino-getting-started',
|
id: 'arduino-getting-started',
|
||||||
label: 'Getting Started',
|
label: nls.localize('arduino/help/gettingStarted', 'Getting Started'),
|
||||||
category: 'Arduino'
|
category: 'Arduino',
|
||||||
};
|
};
|
||||||
export const ENVIRONMENT: Command = {
|
export const ENVIRONMENT: Command = {
|
||||||
id: 'arduino-environment',
|
id: 'arduino-environment',
|
||||||
label: 'Environment',
|
label: nls.localize('arduino/help/environment', 'Environment'),
|
||||||
category: 'Arduino'
|
category: 'Arduino',
|
||||||
};
|
};
|
||||||
export const TROUBLESHOOTING: Command = {
|
export const TROUBLESHOOTING: Command = {
|
||||||
id: 'arduino-troubleshooting',
|
id: 'arduino-troubleshooting',
|
||||||
label: 'Troubleshooting',
|
label: nls.localize('arduino/help/troubleshooting', 'Troubleshooting'),
|
||||||
category: 'Arduino'
|
category: 'Arduino',
|
||||||
};
|
};
|
||||||
export const REFERENCE: Command = {
|
export const REFERENCE: Command = {
|
||||||
id: 'arduino-reference',
|
id: 'arduino-reference',
|
||||||
label: 'Reference',
|
label: nls.localize('arduino/help/reference', 'Reference'),
|
||||||
category: 'Arduino'
|
category: 'Arduino',
|
||||||
};
|
};
|
||||||
export const FIND_IN_REFERENCE: Command = {
|
export const FIND_IN_REFERENCE: Command = {
|
||||||
id: 'arduino-find-in-reference',
|
id: 'arduino-find-in-reference',
|
||||||
label: 'Find in Reference',
|
label: nls.localize('arduino/help/findInReference', 'Find in Reference'),
|
||||||
category: 'Arduino'
|
category: 'Arduino',
|
||||||
};
|
};
|
||||||
export const FAQ: Command = {
|
export const FAQ: Command = {
|
||||||
id: 'arduino-faq',
|
id: 'arduino-faq',
|
||||||
label: 'Frequently Asked Questions',
|
label: nls.localize('arduino/help/faq', 'Frequently Asked Questions'),
|
||||||
category: 'Arduino'
|
category: 'Arduino',
|
||||||
};
|
};
|
||||||
export const VISIT_ARDUINO: Command = {
|
export const VISIT_ARDUINO: Command = {
|
||||||
id: 'arduino-visit-arduino',
|
id: 'arduino-visit-arduino',
|
||||||
label: 'Visit Arduino.cc',
|
label: nls.localize('arduino/help/visit', 'Visit Arduino.cc'),
|
||||||
category: 'Arduino'
|
category: 'Arduino',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,10 @@ import URI from '@theia/core/lib/common/uri';
|
|||||||
import { MonacoEditor } from '@theia/monaco/lib/browser/monaco-editor';
|
import { MonacoEditor } from '@theia/monaco/lib/browser/monaco-editor';
|
||||||
import { EditorManager } from '@theia/editor/lib/browser';
|
import { EditorManager } from '@theia/editor/lib/browser';
|
||||||
import { MenuModelRegistry, MenuPath } from '@theia/core/lib/common/menu';
|
import { MenuModelRegistry, MenuPath } from '@theia/core/lib/common/menu';
|
||||||
import { Disposable, DisposableCollection } from '@theia/core/lib/common/disposable';
|
import {
|
||||||
|
Disposable,
|
||||||
|
DisposableCollection,
|
||||||
|
} from '@theia/core/lib/common/disposable';
|
||||||
import { ArduinoMenus, PlaceholderMenuNode } from '../menu/arduino-menus';
|
import { ArduinoMenus, PlaceholderMenuNode } from '../menu/arduino-menus';
|
||||||
import { LibraryPackage, LibraryService } from '../../common/protocol';
|
import { LibraryPackage, LibraryService } from '../../common/protocol';
|
||||||
import { MainMenuManager } from '../../common/main-menu-manager';
|
import { MainMenuManager } from '../../common/main-menu-manager';
|
||||||
@@ -12,10 +15,10 @@ import { LibraryListWidget } from '../library/library-list-widget';
|
|||||||
import { BoardsServiceProvider } from '../boards/boards-service-provider';
|
import { BoardsServiceProvider } from '../boards/boards-service-provider';
|
||||||
import { SketchContribution, Command, CommandRegistry } from './contribution';
|
import { SketchContribution, Command, CommandRegistry } from './contribution';
|
||||||
import { NotificationCenter } from '../notification-center';
|
import { NotificationCenter } from '../notification-center';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export class IncludeLibrary extends SketchContribution {
|
export class IncludeLibrary extends SketchContribution {
|
||||||
|
|
||||||
@inject(CommandRegistry)
|
@inject(CommandRegistry)
|
||||||
protected readonly commandRegistry: CommandRegistry;
|
protected readonly commandRegistry: CommandRegistry;
|
||||||
|
|
||||||
@@ -42,18 +45,45 @@ export class IncludeLibrary extends SketchContribution {
|
|||||||
|
|
||||||
onStart(): void {
|
onStart(): void {
|
||||||
this.updateMenuActions();
|
this.updateMenuActions();
|
||||||
this.boardsServiceClient.onBoardsConfigChanged(() => this.updateMenuActions())
|
this.boardsServiceClient.onBoardsConfigChanged(() =>
|
||||||
|
this.updateMenuActions()
|
||||||
|
);
|
||||||
this.notificationCenter.onLibraryInstalled(() => this.updateMenuActions());
|
this.notificationCenter.onLibraryInstalled(() => this.updateMenuActions());
|
||||||
this.notificationCenter.onLibraryUninstalled(() => this.updateMenuActions());
|
this.notificationCenter.onLibraryUninstalled(() =>
|
||||||
|
this.updateMenuActions()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
registerMenus(registry: MenuModelRegistry): void {
|
||||||
|
// `Include Library` submenu
|
||||||
|
const includeLibMenuPath = [
|
||||||
|
...ArduinoMenus.SKETCH__UTILS_GROUP,
|
||||||
|
'0_include',
|
||||||
|
];
|
||||||
|
registry.registerSubmenu(
|
||||||
|
includeLibMenuPath,
|
||||||
|
nls.localize('arduino/library/include', 'Include Library'),
|
||||||
|
{
|
||||||
|
order: '1',
|
||||||
|
}
|
||||||
|
);
|
||||||
|
// `Manage Libraries...` group.
|
||||||
|
registry.registerMenuAction([...includeLibMenuPath, '0_manage'], {
|
||||||
|
commandId: `${LibraryListWidget.WIDGET_ID}:toggle`,
|
||||||
|
label: nls.localize(
|
||||||
|
'arduino/library/manageLibraries',
|
||||||
|
'Manage Libraries...'
|
||||||
|
),
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
registerCommands(registry: CommandRegistry): void {
|
registerCommands(registry: CommandRegistry): void {
|
||||||
registry.registerCommand(IncludeLibrary.Commands.INCLUDE_LIBRARY, {
|
registry.registerCommand(IncludeLibrary.Commands.INCLUDE_LIBRARY, {
|
||||||
execute: async arg => {
|
execute: async (arg) => {
|
||||||
if (LibraryPackage.is(arg)) {
|
if (LibraryPackage.is(arg)) {
|
||||||
this.includeLibrary(arg);
|
this.includeLibrary(arg);
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -61,23 +91,16 @@ export class IncludeLibrary extends SketchContribution {
|
|||||||
return this.queue.add(async () => {
|
return this.queue.add(async () => {
|
||||||
this.toDispose.dispose();
|
this.toDispose.dispose();
|
||||||
this.mainMenuManager.update();
|
this.mainMenuManager.update();
|
||||||
const libraries: LibraryPackage[] = []
|
const libraries: LibraryPackage[] = [];
|
||||||
const fqbn = this.boardsServiceClient.boardsConfig.selectedBoard?.fqbn;
|
const fqbn = this.boardsServiceClient.boardsConfig.selectedBoard?.fqbn;
|
||||||
// Do not show board specific examples, when no board is selected.
|
// Show all libraries, when no board is selected.
|
||||||
if (fqbn) {
|
// Otherwise, show libraries only for the selected board.
|
||||||
libraries.push(...await this.libraryService.list({ fqbn }));
|
libraries.push(...(await this.libraryService.list({ fqbn })));
|
||||||
}
|
|
||||||
|
|
||||||
// `Include Library` submenu
|
|
||||||
const includeLibMenuPath = [...ArduinoMenus.SKETCH__UTILS_GROUP, '0_include'];
|
|
||||||
this.menuRegistry.registerSubmenu(includeLibMenuPath, 'Include Library', { order: '1' });
|
|
||||||
// `Manage Libraries...` group.
|
|
||||||
this.menuRegistry.registerMenuAction([...includeLibMenuPath, '0_manage'], {
|
|
||||||
commandId: `${LibraryListWidget.WIDGET_ID}:toggle`,
|
|
||||||
label: 'Manage Libraries...'
|
|
||||||
});
|
|
||||||
this.toDispose.push(Disposable.create(() => this.menuRegistry.unregisterMenuAction({ commandId: `${LibraryListWidget.WIDGET_ID}:toggle` })));
|
|
||||||
|
|
||||||
|
const includeLibMenuPath = [
|
||||||
|
...ArduinoMenus.SKETCH__UTILS_GROUP,
|
||||||
|
'0_include',
|
||||||
|
];
|
||||||
// `Add .ZIP Library...`
|
// `Add .ZIP Library...`
|
||||||
// TODO: implement it
|
// TODO: implement it
|
||||||
|
|
||||||
@@ -86,10 +109,17 @@ export class IncludeLibrary extends SketchContribution {
|
|||||||
const userMenuPath = [...includeLibMenuPath, '3_contributed'];
|
const userMenuPath = [...includeLibMenuPath, '3_contributed'];
|
||||||
const { user, rest } = LibraryPackage.groupByLocation(libraries);
|
const { user, rest } = LibraryPackage.groupByLocation(libraries);
|
||||||
if (rest.length) {
|
if (rest.length) {
|
||||||
(rest as any).unshift('Arduino libraries');
|
(rest as any).unshift(
|
||||||
|
nls.localize('arduino/library/arduinoLibraries', 'Arduino libraries')
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if (user.length) {
|
if (user.length) {
|
||||||
(user as any).unshift('Contributed libraries');
|
(user as any).unshift(
|
||||||
|
nls.localize(
|
||||||
|
'arduino/library/contributedLibraries',
|
||||||
|
'Contributed libraries'
|
||||||
|
)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const library of user) {
|
for (const library of user) {
|
||||||
@@ -103,20 +133,36 @@ export class IncludeLibrary extends SketchContribution {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
protected registerLibrary(libraryOrPlaceholder: LibraryPackage | string, menuPath: MenuPath): Disposable {
|
protected registerLibrary(
|
||||||
|
libraryOrPlaceholder: LibraryPackage | string,
|
||||||
|
menuPath: MenuPath
|
||||||
|
): Disposable {
|
||||||
if (typeof libraryOrPlaceholder === 'string') {
|
if (typeof libraryOrPlaceholder === 'string') {
|
||||||
const placeholder = new PlaceholderMenuNode(menuPath, libraryOrPlaceholder);
|
const placeholder = new PlaceholderMenuNode(
|
||||||
|
menuPath,
|
||||||
|
libraryOrPlaceholder
|
||||||
|
);
|
||||||
this.menuRegistry.registerMenuNode(menuPath, placeholder);
|
this.menuRegistry.registerMenuNode(menuPath, placeholder);
|
||||||
return Disposable.create(() => this.menuRegistry.unregisterMenuNode(placeholder.id));
|
return Disposable.create(() =>
|
||||||
|
this.menuRegistry.unregisterMenuNode(placeholder.id)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
const commandId = `arduino-include-library--${libraryOrPlaceholder.name}:${libraryOrPlaceholder.author}`;
|
const commandId = `arduino-include-library--${libraryOrPlaceholder.name}:${libraryOrPlaceholder.author}`;
|
||||||
const command = { id: commandId };
|
const command = { id: commandId };
|
||||||
const handler = { execute: () => this.commandRegistry.executeCommand(IncludeLibrary.Commands.INCLUDE_LIBRARY.id, libraryOrPlaceholder) };
|
const handler = {
|
||||||
|
execute: () =>
|
||||||
|
this.commandRegistry.executeCommand(
|
||||||
|
IncludeLibrary.Commands.INCLUDE_LIBRARY.id,
|
||||||
|
libraryOrPlaceholder
|
||||||
|
),
|
||||||
|
};
|
||||||
const menuAction = { commandId, label: libraryOrPlaceholder.name };
|
const menuAction = { commandId, label: libraryOrPlaceholder.name };
|
||||||
this.menuRegistry.registerMenuAction(menuPath, menuAction);
|
this.menuRegistry.registerMenuAction(menuPath, menuAction);
|
||||||
return new DisposableCollection(
|
return new DisposableCollection(
|
||||||
this.commandRegistry.registerCommand(command, handler),
|
this.commandRegistry.registerCommand(command, handler),
|
||||||
Disposable.create(() => this.menuRegistry.unregisterMenuAction(menuAction)),
|
Disposable.create(() =>
|
||||||
|
this.menuRegistry.unregisterMenuAction(menuAction)
|
||||||
|
)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -130,7 +176,9 @@ export class IncludeLibrary extends SketchContribution {
|
|||||||
let codeEditor: monaco.editor.IStandaloneCodeEditor | undefined;
|
let codeEditor: monaco.editor.IStandaloneCodeEditor | undefined;
|
||||||
const editor = this.editorManager.currentEditor?.editor;
|
const editor = this.editorManager.currentEditor?.editor;
|
||||||
if (editor instanceof MonacoEditor) {
|
if (editor instanceof MonacoEditor) {
|
||||||
if (sketch.additionalFileUris.some(uri => uri === editor.uri.toString())) {
|
if (
|
||||||
|
sketch.additionalFileUris.some((uri) => uri === editor.uri.toString())
|
||||||
|
) {
|
||||||
codeEditor = editor.getControl();
|
codeEditor = editor.getControl();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -154,22 +202,29 @@ export class IncludeLibrary extends SketchContribution {
|
|||||||
const eol = textModel.getEOL();
|
const eol = textModel.getEOL();
|
||||||
const includes = library.includes.slice();
|
const includes = library.includes.slice();
|
||||||
includes.push(''); // For the trailing new line.
|
includes.push(''); // For the trailing new line.
|
||||||
const text = includes.map(include => include ? `#include <${include}>` : eol).join(eol);
|
const text = includes
|
||||||
|
.map((include) => (include ? `#include <${include}>` : eol))
|
||||||
|
.join(eol);
|
||||||
textModel.pushStackElement(); // Start a fresh operation.
|
textModel.pushStackElement(); // Start a fresh operation.
|
||||||
textModel.pushEditOperations(cursorState, [{
|
textModel.pushEditOperations(
|
||||||
|
cursorState,
|
||||||
|
[
|
||||||
|
{
|
||||||
range: new monaco.Range(1, 1, 1, 1),
|
range: new monaco.Range(1, 1, 1, 1),
|
||||||
text,
|
text,
|
||||||
forceMoveMarkers: true
|
forceMoveMarkers: true,
|
||||||
}], () => cursorState);
|
},
|
||||||
|
],
|
||||||
|
() => cursorState
|
||||||
|
);
|
||||||
textModel.pushStackElement(); // Make it undoable.
|
textModel.pushStackElement(); // Make it undoable.
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export namespace IncludeLibrary {
|
export namespace IncludeLibrary {
|
||||||
export namespace Commands {
|
export namespace Commands {
|
||||||
export const INCLUDE_LIBRARY: Command = {
|
export const INCLUDE_LIBRARY: Command = {
|
||||||
id: 'arduino-include-library'
|
id: 'arduino-include-library',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,33 +1,42 @@
|
|||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
import { injectable } from 'inversify';
|
import { injectable } from 'inversify';
|
||||||
import { ArduinoMenus } from '../menu/arduino-menus';
|
import { ArduinoMenus } from '../menu/arduino-menus';
|
||||||
import { ArduinoToolbar } from '../toolbar/arduino-toolbar';
|
import { ArduinoToolbar } from '../toolbar/arduino-toolbar';
|
||||||
import { SketchContribution, URI, Command, CommandRegistry, MenuModelRegistry, KeybindingRegistry, TabBarToolbarRegistry } from './contribution';
|
import {
|
||||||
|
SketchContribution,
|
||||||
|
URI,
|
||||||
|
Command,
|
||||||
|
CommandRegistry,
|
||||||
|
MenuModelRegistry,
|
||||||
|
KeybindingRegistry,
|
||||||
|
TabBarToolbarRegistry,
|
||||||
|
} from './contribution';
|
||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export class NewSketch extends SketchContribution {
|
export class NewSketch extends SketchContribution {
|
||||||
|
|
||||||
registerCommands(registry: CommandRegistry): void {
|
registerCommands(registry: CommandRegistry): void {
|
||||||
registry.registerCommand(NewSketch.Commands.NEW_SKETCH, {
|
registry.registerCommand(NewSketch.Commands.NEW_SKETCH, {
|
||||||
execute: () => this.newSketch()
|
execute: () => this.newSketch(),
|
||||||
});
|
});
|
||||||
registry.registerCommand(NewSketch.Commands.NEW_SKETCH__TOOLBAR, {
|
registry.registerCommand(NewSketch.Commands.NEW_SKETCH__TOOLBAR, {
|
||||||
isVisible: widget => ArduinoToolbar.is(widget) && widget.side === 'left',
|
isVisible: (widget) =>
|
||||||
execute: () => registry.executeCommand(NewSketch.Commands.NEW_SKETCH.id)
|
ArduinoToolbar.is(widget) && widget.side === 'left',
|
||||||
|
execute: () => registry.executeCommand(NewSketch.Commands.NEW_SKETCH.id),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
registerMenus(registry: MenuModelRegistry): void {
|
registerMenus(registry: MenuModelRegistry): void {
|
||||||
registry.registerMenuAction(ArduinoMenus.FILE__SKETCH_GROUP, {
|
registry.registerMenuAction(ArduinoMenus.FILE__SKETCH_GROUP, {
|
||||||
commandId: NewSketch.Commands.NEW_SKETCH.id,
|
commandId: NewSketch.Commands.NEW_SKETCH.id,
|
||||||
label: 'New',
|
label: nls.localize('arduino/sketch/new', 'New'),
|
||||||
order: '0'
|
order: '0',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
registerKeybindings(registry: KeybindingRegistry): void {
|
registerKeybindings(registry: KeybindingRegistry): void {
|
||||||
registry.registerKeybinding({
|
registry.registerKeybinding({
|
||||||
command: NewSketch.Commands.NEW_SKETCH.id,
|
command: NewSketch.Commands.NEW_SKETCH.id,
|
||||||
keybinding: 'CtrlCmd+N'
|
keybinding: 'CtrlCmd+N',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -35,8 +44,8 @@ export class NewSketch extends SketchContribution {
|
|||||||
registry.registerItem({
|
registry.registerItem({
|
||||||
id: NewSketch.Commands.NEW_SKETCH__TOOLBAR.id,
|
id: NewSketch.Commands.NEW_SKETCH__TOOLBAR.id,
|
||||||
command: NewSketch.Commands.NEW_SKETCH__TOOLBAR.id,
|
command: NewSketch.Commands.NEW_SKETCH__TOOLBAR.id,
|
||||||
tooltip: 'New',
|
tooltip: nls.localize('arduino/sketch/new', 'New'),
|
||||||
priority: 3
|
priority: 3,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -48,16 +57,15 @@ export class NewSketch extends SketchContribution {
|
|||||||
await this.messageService.error(e.toString());
|
await this.messageService.error(e.toString());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export namespace NewSketch {
|
export namespace NewSketch {
|
||||||
export namespace Commands {
|
export namespace Commands {
|
||||||
export const NEW_SKETCH: Command = {
|
export const NEW_SKETCH: Command = {
|
||||||
id: 'arduino-new-sketch'
|
id: 'arduino-new-sketch',
|
||||||
};
|
};
|
||||||
export const NEW_SKETCH__TOOLBAR: Command = {
|
export const NEW_SKETCH__TOOLBAR: Command = {
|
||||||
id: 'arduino-new-sketch--toolbar'
|
id: 'arduino-new-sketch--toolbar',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,23 @@
|
|||||||
import { inject, injectable } from 'inversify';
|
import { inject, injectable } from 'inversify';
|
||||||
import { WorkspaceServer } from '@theia/workspace/lib/common/workspace-protocol';
|
import { WorkspaceServer } from '@theia/workspace/lib/common/workspace-protocol';
|
||||||
import { Disposable, DisposableCollection } from '@theia/core/lib/common/disposable';
|
import {
|
||||||
import { SketchContribution, CommandRegistry, MenuModelRegistry, Sketch } from './contribution';
|
Disposable,
|
||||||
|
DisposableCollection,
|
||||||
|
} from '@theia/core/lib/common/disposable';
|
||||||
|
import {
|
||||||
|
SketchContribution,
|
||||||
|
CommandRegistry,
|
||||||
|
MenuModelRegistry,
|
||||||
|
Sketch,
|
||||||
|
} from './contribution';
|
||||||
import { ArduinoMenus } from '../menu/arduino-menus';
|
import { ArduinoMenus } from '../menu/arduino-menus';
|
||||||
import { MainMenuManager } from '../../common/main-menu-manager';
|
import { MainMenuManager } from '../../common/main-menu-manager';
|
||||||
import { OpenSketch } from './open-sketch';
|
import { OpenSketch } from './open-sketch';
|
||||||
import { NotificationCenter } from '../notification-center';
|
import { NotificationCenter } from '../notification-center';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export class OpenRecentSketch extends SketchContribution {
|
export class OpenRecentSketch extends SketchContribution {
|
||||||
|
|
||||||
@inject(CommandRegistry)
|
@inject(CommandRegistry)
|
||||||
protected readonly commandRegistry: CommandRegistry;
|
protected readonly commandRegistry: CommandRegistry;
|
||||||
|
|
||||||
@@ -32,16 +40,22 @@ export class OpenRecentSketch extends SketchContribution {
|
|||||||
this.register(sketches);
|
this.register(sketches);
|
||||||
this.mainMenuManager.update();
|
this.mainMenuManager.update();
|
||||||
};
|
};
|
||||||
this.notificationCenter.onRecentSketchesChanged(({ sketches }) => refreshMenu(sketches));
|
this.notificationCenter.onRecentSketchesChanged(({ sketches }) =>
|
||||||
|
refreshMenu(sketches)
|
||||||
|
);
|
||||||
this.sketchService.recentlyOpenedSketches().then(refreshMenu);
|
this.sketchService.recentlyOpenedSketches().then(refreshMenu);
|
||||||
}
|
}
|
||||||
|
|
||||||
registerMenus(registry: MenuModelRegistry): void {
|
registerMenus(registry: MenuModelRegistry): void {
|
||||||
registry.registerSubmenu(ArduinoMenus.FILE__OPEN_RECENT_SUBMENU, 'Open Recent', { order: '2' });
|
registry.registerSubmenu(
|
||||||
|
ArduinoMenus.FILE__OPEN_RECENT_SUBMENU,
|
||||||
|
nls.localize('arduino/sketch/openRecent', 'Open Recent'),
|
||||||
|
{ order: '2' }
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected register(sketches: Sketch[]): void {
|
protected register(sketches: Sketch[]): void {
|
||||||
let order = 0;
|
const order = 0;
|
||||||
for (const sketch of sketches) {
|
for (const sketch of sketches) {
|
||||||
const { uri } = sketch;
|
const { uri } = sketch;
|
||||||
const toDispose = this.toDisposeBeforeRegister.get(uri);
|
const toDispose = this.toDisposeBeforeRegister.get(uri);
|
||||||
@@ -49,14 +63,33 @@ export class OpenRecentSketch extends SketchContribution {
|
|||||||
toDispose.dispose();
|
toDispose.dispose();
|
||||||
}
|
}
|
||||||
const command = { id: `arduino-open-recent--${uri}` };
|
const command = { id: `arduino-open-recent--${uri}` };
|
||||||
const handler = { execute: () => this.commandRegistry.executeCommand(OpenSketch.Commands.OPEN_SKETCH.id, sketch) };
|
const handler = {
|
||||||
|
execute: () =>
|
||||||
|
this.commandRegistry.executeCommand(
|
||||||
|
OpenSketch.Commands.OPEN_SKETCH.id,
|
||||||
|
sketch
|
||||||
|
),
|
||||||
|
};
|
||||||
this.commandRegistry.registerCommand(command, handler);
|
this.commandRegistry.registerCommand(command, handler);
|
||||||
this.menuRegistry.registerMenuAction(ArduinoMenus.FILE__OPEN_RECENT_SUBMENU, { commandId: command.id, label: sketch.name, order: String(order) });
|
this.menuRegistry.registerMenuAction(
|
||||||
this.toDisposeBeforeRegister.set(sketch.uri, new DisposableCollection(
|
ArduinoMenus.FILE__OPEN_RECENT_SUBMENU,
|
||||||
Disposable.create(() => this.commandRegistry.unregisterCommand(command)),
|
{
|
||||||
Disposable.create(() => this.menuRegistry.unregisterMenuAction(command))
|
commandId: command.id,
|
||||||
));
|
label: sketch.name,
|
||||||
|
order: String(order),
|
||||||
|
}
|
||||||
|
);
|
||||||
|
this.toDisposeBeforeRegister.set(
|
||||||
|
sketch.uri,
|
||||||
|
new DisposableCollection(
|
||||||
|
Disposable.create(() =>
|
||||||
|
this.commandRegistry.unregisterCommand(command)
|
||||||
|
),
|
||||||
|
Disposable.create(() =>
|
||||||
|
this.menuRegistry.unregisterMenuAction(command)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,37 +1,43 @@
|
|||||||
import { injectable } from 'inversify';
|
import { injectable } from 'inversify';
|
||||||
import { remote } from 'electron';
|
import * as remote from '@theia/core/electron-shared/@electron/remote';
|
||||||
import URI from '@theia/core/lib/common/uri';
|
import URI from '@theia/core/lib/common/uri';
|
||||||
import { ArduinoMenus } from '../menu/arduino-menus';
|
import { ArduinoMenus } from '../menu/arduino-menus';
|
||||||
import { SketchContribution, Command, CommandRegistry, MenuModelRegistry, KeybindingRegistry } from './contribution';
|
import {
|
||||||
|
SketchContribution,
|
||||||
|
Command,
|
||||||
|
CommandRegistry,
|
||||||
|
MenuModelRegistry,
|
||||||
|
KeybindingRegistry,
|
||||||
|
} from './contribution';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export class OpenSketchExternal extends SketchContribution {
|
export class OpenSketchExternal extends SketchContribution {
|
||||||
|
|
||||||
registerCommands(registry: CommandRegistry): void {
|
registerCommands(registry: CommandRegistry): void {
|
||||||
registry.registerCommand(OpenSketchExternal.Commands.OPEN_EXTERNAL, {
|
registry.registerCommand(OpenSketchExternal.Commands.OPEN_EXTERNAL, {
|
||||||
execute: () => this.openExternal()
|
execute: () => this.openExternal(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
registerMenus(registry: MenuModelRegistry): void {
|
registerMenus(registry: MenuModelRegistry): void {
|
||||||
registry.registerMenuAction(ArduinoMenus.SKETCH__UTILS_GROUP, {
|
registry.registerMenuAction(ArduinoMenus.SKETCH__UTILS_GROUP, {
|
||||||
commandId: OpenSketchExternal.Commands.OPEN_EXTERNAL.id,
|
commandId: OpenSketchExternal.Commands.OPEN_EXTERNAL.id,
|
||||||
label: 'Show Sketch Folder',
|
label: nls.localize('arduino/sketch/showFolder', 'Show Sketch Folder'),
|
||||||
order: '0'
|
order: '0',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
registerKeybindings(registry: KeybindingRegistry): void {
|
registerKeybindings(registry: KeybindingRegistry): void {
|
||||||
registry.registerKeybinding({
|
registry.registerKeybinding({
|
||||||
command: OpenSketchExternal.Commands.OPEN_EXTERNAL.id,
|
command: OpenSketchExternal.Commands.OPEN_EXTERNAL.id,
|
||||||
keybinding: 'CtrlCmd+Alt+K'
|
keybinding: 'CtrlCmd+Alt+K',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
protected async openExternal(): Promise<void> {
|
protected async openExternal(): Promise<void> {
|
||||||
const uri = await this.sketchServiceClient.currentSketchFile();
|
const uri = await this.sketchServiceClient.currentSketchFile();
|
||||||
if (uri) {
|
if (uri) {
|
||||||
const exists = this.fileService.exists(new URI(uri));
|
const exists = await this.fileService.exists(new URI(uri));
|
||||||
if (exists) {
|
if (exists) {
|
||||||
const fsPath = await this.fileService.fsPath(new URI(uri));
|
const fsPath = await this.fileService.fsPath(new URI(uri));
|
||||||
if (fsPath) {
|
if (fsPath) {
|
||||||
@@ -40,13 +46,12 @@ export class OpenSketchExternal extends SketchContribution {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export namespace OpenSketchExternal {
|
export namespace OpenSketchExternal {
|
||||||
export namespace Commands {
|
export namespace Commands {
|
||||||
export const OPEN_EXTERNAL: Command = {
|
export const OPEN_EXTERNAL: Command = {
|
||||||
id: 'arduino-open-sketch-external'
|
id: 'arduino-open-sketch-external',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,17 +1,31 @@
|
|||||||
import { inject, injectable } from 'inversify';
|
import { inject, injectable } from 'inversify';
|
||||||
import { remote } from 'electron';
|
import * as remote from '@theia/core/electron-shared/@electron/remote';
|
||||||
import { MaybePromise } from '@theia/core/lib/common/types';
|
import { MaybePromise } from '@theia/core/lib/common/types';
|
||||||
import { Widget, ContextMenuRenderer } from '@theia/core/lib/browser';
|
import { Widget, ContextMenuRenderer } from '@theia/core/lib/browser';
|
||||||
import { Disposable, DisposableCollection } from '@theia/core/lib/common/disposable';
|
import {
|
||||||
|
Disposable,
|
||||||
|
DisposableCollection,
|
||||||
|
} from '@theia/core/lib/common/disposable';
|
||||||
import { ArduinoMenus } from '../menu/arduino-menus';
|
import { ArduinoMenus } from '../menu/arduino-menus';
|
||||||
import { ArduinoToolbar } from '../toolbar/arduino-toolbar';
|
import { ArduinoToolbar } from '../toolbar/arduino-toolbar';
|
||||||
import { SketchContribution, Sketch, URI, Command, CommandRegistry, MenuModelRegistry, KeybindingRegistry, TabBarToolbarRegistry } from './contribution';
|
import {
|
||||||
|
SketchContribution,
|
||||||
|
Sketch,
|
||||||
|
URI,
|
||||||
|
Command,
|
||||||
|
CommandRegistry,
|
||||||
|
MenuModelRegistry,
|
||||||
|
KeybindingRegistry,
|
||||||
|
TabBarToolbarRegistry,
|
||||||
|
} from './contribution';
|
||||||
import { ExamplesService } from '../../common/protocol/examples-service';
|
import { ExamplesService } from '../../common/protocol/examples-service';
|
||||||
import { BuiltInExamples } from './examples';
|
import { BuiltInExamples } from './examples';
|
||||||
|
import { Sketchbook } from './sketchbook';
|
||||||
|
import { SketchContainer } from '../../common/protocol';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export class OpenSketch extends SketchContribution {
|
export class OpenSketch extends SketchContribution {
|
||||||
|
|
||||||
@inject(MenuModelRegistry)
|
@inject(MenuModelRegistry)
|
||||||
protected readonly menuRegistry: MenuModelRegistry;
|
protected readonly menuRegistry: MenuModelRegistry;
|
||||||
|
|
||||||
@@ -24,20 +38,27 @@ export class OpenSketch extends SketchContribution {
|
|||||||
@inject(ExamplesService)
|
@inject(ExamplesService)
|
||||||
protected readonly examplesService: ExamplesService;
|
protected readonly examplesService: ExamplesService;
|
||||||
|
|
||||||
protected readonly toDisposeBeforeCreateNewContextMenu = new DisposableCollection();
|
@inject(Sketchbook)
|
||||||
|
protected readonly sketchbook: Sketchbook;
|
||||||
|
|
||||||
|
protected readonly toDispose = new DisposableCollection();
|
||||||
|
|
||||||
registerCommands(registry: CommandRegistry): void {
|
registerCommands(registry: CommandRegistry): void {
|
||||||
registry.registerCommand(OpenSketch.Commands.OPEN_SKETCH, {
|
registry.registerCommand(OpenSketch.Commands.OPEN_SKETCH, {
|
||||||
execute: arg => Sketch.is(arg) ? this.openSketch(arg) : this.openSketch()
|
execute: (arg) =>
|
||||||
|
Sketch.is(arg) ? this.openSketch(arg) : this.openSketch(),
|
||||||
});
|
});
|
||||||
registry.registerCommand(OpenSketch.Commands.OPEN_SKETCH__TOOLBAR, {
|
registry.registerCommand(OpenSketch.Commands.OPEN_SKETCH__TOOLBAR, {
|
||||||
isVisible: widget => ArduinoToolbar.is(widget) && widget.side === 'left',
|
isVisible: (widget) =>
|
||||||
|
ArduinoToolbar.is(widget) && widget.side === 'left',
|
||||||
execute: async (_: Widget, target: EventTarget) => {
|
execute: async (_: Widget, target: EventTarget) => {
|
||||||
const sketches = await this.sketchService.getSketches();
|
const container = await this.sketchService.getSketches({
|
||||||
if (!sketches.length) {
|
exclude: ['**/hardware/**'],
|
||||||
|
});
|
||||||
|
if (SketchContainer.isEmpty(container)) {
|
||||||
this.openSketch();
|
this.openSketch();
|
||||||
} else {
|
} else {
|
||||||
this.toDisposeBeforeCreateNewContextMenu.dispose();
|
this.toDispose.dispose();
|
||||||
if (!(target instanceof HTMLElement)) {
|
if (!(target instanceof HTMLElement)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -46,25 +67,36 @@ export class OpenSketch extends SketchContribution {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.menuRegistry.registerMenuAction(ArduinoMenus.OPEN_SKETCH__CONTEXT__OPEN_GROUP, {
|
this.menuRegistry.registerMenuAction(
|
||||||
|
ArduinoMenus.OPEN_SKETCH__CONTEXT__OPEN_GROUP,
|
||||||
|
{
|
||||||
commandId: OpenSketch.Commands.OPEN_SKETCH.id,
|
commandId: OpenSketch.Commands.OPEN_SKETCH.id,
|
||||||
label: 'Open...'
|
label: nls.localize(
|
||||||
});
|
'vscode/workspaceActions/openFileFolder',
|
||||||
this.toDisposeBeforeCreateNewContextMenu.push(Disposable.create(() => this.menuRegistry.unregisterMenuAction(OpenSketch.Commands.OPEN_SKETCH)));
|
'Open...'
|
||||||
for (const sketch of sketches) {
|
),
|
||||||
const command = { id: `arduino-open-sketch--${sketch.uri}` };
|
|
||||||
const handler = { execute: () => this.openSketch(sketch) };
|
|
||||||
this.toDisposeBeforeCreateNewContextMenu.push(registry.registerCommand(command, handler));
|
|
||||||
this.menuRegistry.registerMenuAction(ArduinoMenus.OPEN_SKETCH__CONTEXT__RECENT_GROUP, {
|
|
||||||
commandId: command.id,
|
|
||||||
label: sketch.name
|
|
||||||
});
|
|
||||||
this.toDisposeBeforeCreateNewContextMenu.push(Disposable.create(() => this.menuRegistry.unregisterMenuAction(command)));
|
|
||||||
}
|
}
|
||||||
|
);
|
||||||
|
this.toDispose.push(
|
||||||
|
Disposable.create(() =>
|
||||||
|
this.menuRegistry.unregisterMenuAction(
|
||||||
|
OpenSketch.Commands.OPEN_SKETCH
|
||||||
|
)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
this.sketchbook.registerRecursively(
|
||||||
|
[...container.children, ...container.sketches],
|
||||||
|
ArduinoMenus.OPEN_SKETCH__CONTEXT__RECENT_GROUP,
|
||||||
|
this.toDispose
|
||||||
|
);
|
||||||
try {
|
try {
|
||||||
const containers = await this.examplesService.builtIns();
|
const containers = await this.examplesService.builtIns();
|
||||||
for (const container of containers) {
|
for (const container of containers) {
|
||||||
this.builtInExamples.registerRecursively(container, ArduinoMenus.OPEN_SKETCH__CONTEXT__EXAMPLES_GROUP, this.toDisposeBeforeCreateNewContextMenu);
|
this.builtInExamples.registerRecursively(
|
||||||
|
container,
|
||||||
|
ArduinoMenus.OPEN_SKETCH__CONTEXT__EXAMPLES_GROUP,
|
||||||
|
this.toDispose
|
||||||
|
);
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('Error when collecting built-in examples.', e);
|
console.error('Error when collecting built-in examples.', e);
|
||||||
@@ -73,27 +105,29 @@ export class OpenSketch extends SketchContribution {
|
|||||||
menuPath: ArduinoMenus.OPEN_SKETCH__CONTEXT,
|
menuPath: ArduinoMenus.OPEN_SKETCH__CONTEXT,
|
||||||
anchor: {
|
anchor: {
|
||||||
x: parentElement.getBoundingClientRect().left,
|
x: parentElement.getBoundingClientRect().left,
|
||||||
y: parentElement.getBoundingClientRect().top + parentElement.offsetHeight
|
y:
|
||||||
}
|
parentElement.getBoundingClientRect().top +
|
||||||
}
|
parentElement.offsetHeight,
|
||||||
|
},
|
||||||
|
};
|
||||||
this.contextMenuRenderer.render(options);
|
this.contextMenuRenderer.render(options);
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
registerMenus(registry: MenuModelRegistry): void {
|
registerMenus(registry: MenuModelRegistry): void {
|
||||||
registry.registerMenuAction(ArduinoMenus.FILE__SKETCH_GROUP, {
|
registry.registerMenuAction(ArduinoMenus.FILE__SKETCH_GROUP, {
|
||||||
commandId: OpenSketch.Commands.OPEN_SKETCH.id,
|
commandId: OpenSketch.Commands.OPEN_SKETCH.id,
|
||||||
label: 'Open...',
|
label: nls.localize('vscode/workspaceActions/openFileFolder', 'Open...'),
|
||||||
order: '1'
|
order: '1',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
registerKeybindings(registry: KeybindingRegistry): void {
|
registerKeybindings(registry: KeybindingRegistry): void {
|
||||||
registry.registerKeybinding({
|
registry.registerKeybinding({
|
||||||
command: OpenSketch.Commands.OPEN_SKETCH.id,
|
command: OpenSketch.Commands.OPEN_SKETCH.id,
|
||||||
keybinding: 'CtrlCmd+O'
|
keybinding: 'CtrlCmd+O',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -101,12 +135,14 @@ export class OpenSketch extends SketchContribution {
|
|||||||
registry.registerItem({
|
registry.registerItem({
|
||||||
id: OpenSketch.Commands.OPEN_SKETCH__TOOLBAR.id,
|
id: OpenSketch.Commands.OPEN_SKETCH__TOOLBAR.id,
|
||||||
command: OpenSketch.Commands.OPEN_SKETCH__TOOLBAR.id,
|
command: OpenSketch.Commands.OPEN_SKETCH__TOOLBAR.id,
|
||||||
tooltip: 'Open',
|
tooltip: nls.localize('vscode/dialogMainService/open', 'Open'),
|
||||||
priority: 4
|
priority: 4,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async openSketch(toOpen: MaybePromise<Sketch | undefined> = this.selectSketch()): Promise<void> {
|
async openSketch(
|
||||||
|
toOpen: MaybePromise<Sketch | undefined> = this.selectSketch()
|
||||||
|
): Promise<void> {
|
||||||
const sketch = await toOpen;
|
const sketch = await toOpen;
|
||||||
if (sketch) {
|
if (sketch) {
|
||||||
this.workspaceService.open(new URI(sketch.uri));
|
this.workspaceService.open(new URI(sketch.uri));
|
||||||
@@ -115,22 +151,26 @@ export class OpenSketch extends SketchContribution {
|
|||||||
|
|
||||||
protected async selectSketch(): Promise<Sketch | undefined> {
|
protected async selectSketch(): Promise<Sketch | undefined> {
|
||||||
const config = await this.configService.getConfiguration();
|
const config = await this.configService.getConfiguration();
|
||||||
const defaultPath = await this.fileService.fsPath(new URI(config.sketchDirUri));
|
const defaultPath = await this.fileService.fsPath(
|
||||||
|
new URI(config.sketchDirUri)
|
||||||
|
);
|
||||||
const { filePaths } = await remote.dialog.showOpenDialog({
|
const { filePaths } = await remote.dialog.showOpenDialog({
|
||||||
defaultPath,
|
defaultPath,
|
||||||
properties: ['createDirectory', 'openFile'],
|
properties: ['createDirectory', 'openFile'],
|
||||||
filters: [
|
filters: [
|
||||||
{
|
{
|
||||||
name: 'Sketch',
|
name: nls.localize('arduino/sketch/sketch', 'Sketch'),
|
||||||
extensions: ['ino', 'pde']
|
extensions: ['ino', 'pde'],
|
||||||
}
|
},
|
||||||
]
|
],
|
||||||
});
|
});
|
||||||
if (!filePaths.length) {
|
if (!filePaths.length) {
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
if (filePaths.length > 1) {
|
if (filePaths.length > 1) {
|
||||||
this.logger.warn(`Multiple sketches were selected: ${filePaths}. Using the first one.`);
|
this.logger.warn(
|
||||||
|
`Multiple sketches were selected: ${filePaths}. Using the first one.`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
const sketchFilePath = filePaths[0];
|
const sketchFilePath = filePaths[0];
|
||||||
const sketchFileUri = await this.fileSystemExt.getUri(sketchFilePath);
|
const sketchFileUri = await this.fileSystemExt.getUri(sketchFilePath);
|
||||||
@@ -142,38 +182,53 @@ export class OpenSketch extends SketchContribution {
|
|||||||
const name = new URI(sketchFileUri).path.name;
|
const name = new URI(sketchFileUri).path.name;
|
||||||
const nameWithExt = this.labelProvider.getName(new URI(sketchFileUri));
|
const nameWithExt = this.labelProvider.getName(new URI(sketchFileUri));
|
||||||
const { response } = await remote.dialog.showMessageBox({
|
const { response } = await remote.dialog.showMessageBox({
|
||||||
title: 'Moving',
|
title: nls.localize('arduino/sketch/moving', 'Moving'),
|
||||||
type: 'question',
|
type: 'question',
|
||||||
buttons: ['Cancel', 'OK'],
|
buttons: [
|
||||||
message: `The file "${nameWithExt}" needs to be inside a sketch folder named as "${name}".\nCreate this folder, move the file, and continue?`
|
nls.localize('vscode/issueMainService/cancel', 'Cancel'),
|
||||||
|
nls.localize('vscode/issueMainService/ok', 'OK'),
|
||||||
|
],
|
||||||
|
message: nls.localize(
|
||||||
|
'arduino/sketch/movingMsg',
|
||||||
|
'The file "{0}" needs to be inside a sketch folder named "{1}".\nCreate this folder, move the file, and continue?',
|
||||||
|
nameWithExt,
|
||||||
|
name
|
||||||
|
),
|
||||||
});
|
});
|
||||||
if (response === 1) { // OK
|
if (response === 1) {
|
||||||
|
// OK
|
||||||
const newSketchUri = new URI(sketchFileUri).parent.resolve(name);
|
const newSketchUri = new URI(sketchFileUri).parent.resolve(name);
|
||||||
const exists = await this.fileService.exists(newSketchUri);
|
const exists = await this.fileService.exists(newSketchUri);
|
||||||
if (exists) {
|
if (exists) {
|
||||||
await remote.dialog.showMessageBox({
|
await remote.dialog.showMessageBox({
|
||||||
type: 'error',
|
type: 'error',
|
||||||
title: 'Error',
|
title: nls.localize('vscode/dialog/dialogErrorMessage', 'Error'),
|
||||||
message: `A folder named "${name}" already exists. Can't open sketch.`
|
message: nls.localize(
|
||||||
|
'arduino/sketch/cantOpen',
|
||||||
|
'A folder named "{0}" already exists. Can\'t open sketch.',
|
||||||
|
name
|
||||||
|
),
|
||||||
});
|
});
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
await this.fileService.createFolder(newSketchUri);
|
await this.fileService.createFolder(newSketchUri);
|
||||||
await this.fileService.move(new URI(sketchFileUri), new URI(newSketchUri.resolve(nameWithExt).toString()));
|
await this.fileService.move(
|
||||||
|
new URI(sketchFileUri),
|
||||||
|
new URI(newSketchUri.resolve(nameWithExt).toString())
|
||||||
|
);
|
||||||
return this.sketchService.getSketchFolder(newSketchUri.toString());
|
return this.sketchService.getSketchFolder(newSketchUri.toString());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export namespace OpenSketch {
|
export namespace OpenSketch {
|
||||||
export namespace Commands {
|
export namespace Commands {
|
||||||
export const OPEN_SKETCH: Command = {
|
export const OPEN_SKETCH: Command = {
|
||||||
id: 'arduino-open-sketch'
|
id: 'arduino-open-sketch',
|
||||||
};
|
};
|
||||||
export const OPEN_SKETCH__TOOLBAR: Command = {
|
export const OPEN_SKETCH__TOOLBAR: Command = {
|
||||||
id: 'arduino-open-sketch--toolbar'
|
id: 'arduino-open-sketch--toolbar',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,16 +1,22 @@
|
|||||||
import { injectable } from 'inversify';
|
import { injectable } from 'inversify';
|
||||||
import { remote } from 'electron';
|
import * as remote from '@theia/core/electron-shared/@electron/remote';
|
||||||
import { isOSX } from '@theia/core/lib/common/os';
|
import { isOSX } from '@theia/core/lib/common/os';
|
||||||
import { Contribution, Command, MenuModelRegistry, KeybindingRegistry, CommandRegistry } from './contribution';
|
import {
|
||||||
|
Contribution,
|
||||||
|
Command,
|
||||||
|
MenuModelRegistry,
|
||||||
|
KeybindingRegistry,
|
||||||
|
CommandRegistry,
|
||||||
|
} from './contribution';
|
||||||
import { ArduinoMenus } from '../menu/arduino-menus';
|
import { ArduinoMenus } from '../menu/arduino-menus';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export class QuitApp extends Contribution {
|
export class QuitApp extends Contribution {
|
||||||
|
|
||||||
registerCommands(registry: CommandRegistry): void {
|
registerCommands(registry: CommandRegistry): void {
|
||||||
if (!isOSX) {
|
if (!isOSX) {
|
||||||
registry.registerCommand(QuitApp.Commands.QUIT_APP, {
|
registry.registerCommand(QuitApp.Commands.QUIT_APP, {
|
||||||
execute: () => remote.app.quit()
|
execute: () => remote.app.quit(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -20,8 +26,8 @@ export class QuitApp extends Contribution {
|
|||||||
if (!isOSX) {
|
if (!isOSX) {
|
||||||
registry.registerMenuAction(ArduinoMenus.FILE__QUIT_GROUP, {
|
registry.registerMenuAction(ArduinoMenus.FILE__QUIT_GROUP, {
|
||||||
commandId: QuitApp.Commands.QUIT_APP.id,
|
commandId: QuitApp.Commands.QUIT_APP.id,
|
||||||
label: 'Quit',
|
label: nls.localize('vscode/bulkEditService/quit', 'Quit'),
|
||||||
order: '0'
|
order: '0',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -30,17 +36,16 @@ export class QuitApp extends Contribution {
|
|||||||
if (!isOSX) {
|
if (!isOSX) {
|
||||||
registry.registerKeybinding({
|
registry.registerKeybinding({
|
||||||
command: QuitApp.Commands.QUIT_APP.id,
|
command: QuitApp.Commands.QUIT_APP.id,
|
||||||
keybinding: 'CtrlCmd+Q'
|
keybinding: 'CtrlCmd+Q',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export namespace QuitApp {
|
export namespace QuitApp {
|
||||||
export namespace Commands {
|
export namespace Commands {
|
||||||
export const QUIT_APP: Command = {
|
export const QUIT_APP: Command = {
|
||||||
id: 'arduino-quit-app'
|
id: 'arduino-quit-app',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,37 +1,50 @@
|
|||||||
import { injectable } from 'inversify';
|
import { injectable } from 'inversify';
|
||||||
import { remote } from 'electron';
|
import * as remote from '@theia/core/electron-shared/@electron/remote';
|
||||||
import * as dateFormat from 'dateformat';
|
import * as dateFormat from 'dateformat';
|
||||||
import { ArduinoMenus } from '../menu/arduino-menus';
|
import { ArduinoMenus } from '../menu/arduino-menus';
|
||||||
import { SketchContribution, URI, Command, CommandRegistry, MenuModelRegistry, KeybindingRegistry } from './contribution';
|
import {
|
||||||
|
SketchContribution,
|
||||||
|
URI,
|
||||||
|
Command,
|
||||||
|
CommandRegistry,
|
||||||
|
MenuModelRegistry,
|
||||||
|
KeybindingRegistry,
|
||||||
|
} from './contribution';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export class SaveAsSketch extends SketchContribution {
|
export class SaveAsSketch extends SketchContribution {
|
||||||
|
|
||||||
registerCommands(registry: CommandRegistry): void {
|
registerCommands(registry: CommandRegistry): void {
|
||||||
registry.registerCommand(SaveAsSketch.Commands.SAVE_AS_SKETCH, {
|
registry.registerCommand(SaveAsSketch.Commands.SAVE_AS_SKETCH, {
|
||||||
execute: args => this.saveAs(args)
|
execute: (args) => this.saveAs(args),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
registerMenus(registry: MenuModelRegistry): void {
|
registerMenus(registry: MenuModelRegistry): void {
|
||||||
registry.registerMenuAction(ArduinoMenus.FILE__SKETCH_GROUP, {
|
registry.registerMenuAction(ArduinoMenus.FILE__SKETCH_GROUP, {
|
||||||
commandId: SaveAsSketch.Commands.SAVE_AS_SKETCH.id,
|
commandId: SaveAsSketch.Commands.SAVE_AS_SKETCH.id,
|
||||||
label: 'Save As...',
|
label: nls.localize('vscode/fileCommands/saveAs', 'Save As...'),
|
||||||
order: '7'
|
order: '7',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
registerKeybindings(registry: KeybindingRegistry): void {
|
registerKeybindings(registry: KeybindingRegistry): void {
|
||||||
registry.registerKeybinding({
|
registry.registerKeybinding({
|
||||||
command: SaveAsSketch.Commands.SAVE_AS_SKETCH.id,
|
command: SaveAsSketch.Commands.SAVE_AS_SKETCH.id,
|
||||||
keybinding: 'CtrlCmd+Shift+S'
|
keybinding: 'CtrlCmd+Shift+S',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Resolves `true` if the sketch was successfully saved as something.
|
* Resolves `true` if the sketch was successfully saved as something.
|
||||||
*/
|
*/
|
||||||
async saveAs({ execOnlyIfTemp, openAfterMove, wipeOriginal }: SaveAsSketch.Options = SaveAsSketch.Options.DEFAULT): Promise<boolean> {
|
async saveAs(
|
||||||
|
{
|
||||||
|
execOnlyIfTemp,
|
||||||
|
openAfterMove,
|
||||||
|
wipeOriginal,
|
||||||
|
}: SaveAsSketch.Options = SaveAsSketch.Options.DEFAULT
|
||||||
|
): Promise<boolean> {
|
||||||
const sketch = await this.sketchServiceClient.currentSketch();
|
const sketch = await this.sketchServiceClient.currentSketch();
|
||||||
if (!sketch) {
|
if (!sketch) {
|
||||||
return false;
|
return false;
|
||||||
@@ -44,13 +57,29 @@ export class SaveAsSketch extends SketchContribution {
|
|||||||
|
|
||||||
// If target does not exist, propose a `directories.user`/${sketch.name} path
|
// If target does not exist, propose a `directories.user`/${sketch.name} path
|
||||||
// If target exists, propose `directories.user`/${sketch.name}_copy_${yyyymmddHHMMss}
|
// If target exists, propose `directories.user`/${sketch.name}_copy_${yyyymmddHHMMss}
|
||||||
const sketchDirUri = new URI((await this.configService.getConfiguration()).sketchDirUri);
|
const sketchDirUri = new URI(
|
||||||
const exists = await this.fileService.exists(sketchDirUri.resolve(sketch.name));
|
(await this.configService.getConfiguration()).sketchDirUri
|
||||||
|
);
|
||||||
|
const exists = await this.fileService.exists(
|
||||||
|
sketchDirUri.resolve(sketch.name)
|
||||||
|
);
|
||||||
const defaultUri = exists
|
const defaultUri = exists
|
||||||
? sketchDirUri.resolve(sketchDirUri.resolve(`${sketch.name}_copy_${dateFormat(new Date(), 'yyyymmddHHMMss')}`).toString())
|
? sketchDirUri.resolve(
|
||||||
|
sketchDirUri
|
||||||
|
.resolve(
|
||||||
|
`${sketch.name}_copy_${dateFormat(new Date(), 'yyyymmddHHMMss')}`
|
||||||
|
)
|
||||||
|
.toString()
|
||||||
|
)
|
||||||
: sketchDirUri.resolve(sketch.name);
|
: sketchDirUri.resolve(sketch.name);
|
||||||
const defaultPath = await this.fileService.fsPath(defaultUri);
|
const defaultPath = await this.fileService.fsPath(defaultUri);
|
||||||
const { filePath, canceled } = await remote.dialog.showSaveDialog({ title: 'Save sketch folder as...', defaultPath });
|
const { filePath, canceled } = await remote.dialog.showSaveDialog({
|
||||||
|
title: nls.localize(
|
||||||
|
'arduino/sketch/saveFolderAs',
|
||||||
|
'Save sketch folder as...'
|
||||||
|
),
|
||||||
|
defaultPath,
|
||||||
|
});
|
||||||
if (!filePath || canceled) {
|
if (!filePath || canceled) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -58,24 +87,31 @@ export class SaveAsSketch extends SketchContribution {
|
|||||||
if (!destinationUri) {
|
if (!destinationUri) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
const workspaceUri = await this.sketchService.copy(sketch, { destinationUri });
|
const workspaceUri = await this.sketchService.copy(sketch, {
|
||||||
|
destinationUri,
|
||||||
|
});
|
||||||
if (workspaceUri && openAfterMove) {
|
if (workspaceUri && openAfterMove) {
|
||||||
if (wipeOriginal || (openAfterMove && execOnlyIfTemp)) {
|
if (wipeOriginal || (openAfterMove && execOnlyIfTemp)) {
|
||||||
try {
|
try {
|
||||||
await this.fileService.delete(new URI(sketch.uri), { recursive: true });
|
await this.fileService.delete(new URI(sketch.uri), {
|
||||||
} catch { /* NOOP: from time to time, it's not possible to wipe the old resource from the temp dir on Windows */ }
|
recursive: true,
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
/* NOOP: from time to time, it's not possible to wipe the old resource from the temp dir on Windows */
|
||||||
}
|
}
|
||||||
this.workspaceService.open(new URI(workspaceUri), { preserveWindow: true });
|
}
|
||||||
|
this.workspaceService.open(new URI(workspaceUri), {
|
||||||
|
preserveWindow: true,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
return !!workspaceUri;
|
return !!workspaceUri;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export namespace SaveAsSketch {
|
export namespace SaveAsSketch {
|
||||||
export namespace Commands {
|
export namespace Commands {
|
||||||
export const SAVE_AS_SKETCH: Command = {
|
export const SAVE_AS_SKETCH: Command = {
|
||||||
id: 'arduino-save-as-sketch'
|
id: 'arduino-save-as-sketch',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
export interface Options {
|
export interface Options {
|
||||||
@@ -90,7 +126,7 @@ export namespace SaveAsSketch {
|
|||||||
export const DEFAULT: Options = {
|
export const DEFAULT: Options = {
|
||||||
execOnlyIfTemp: false,
|
execOnlyIfTemp: false,
|
||||||
openAfterMove: true,
|
openAfterMove: true,
|
||||||
wipeOriginal: false
|
wipeOriginal: false,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,33 +2,43 @@ import { injectable } from 'inversify';
|
|||||||
import { CommonCommands } from '@theia/core/lib/browser/common-frontend-contribution';
|
import { CommonCommands } from '@theia/core/lib/browser/common-frontend-contribution';
|
||||||
import { ArduinoMenus } from '../menu/arduino-menus';
|
import { ArduinoMenus } from '../menu/arduino-menus';
|
||||||
import { ArduinoToolbar } from '../toolbar/arduino-toolbar';
|
import { ArduinoToolbar } from '../toolbar/arduino-toolbar';
|
||||||
import { SketchContribution, Command, CommandRegistry, MenuModelRegistry, KeybindingRegistry, TabBarToolbarRegistry } from './contribution';
|
import { SaveAsSketch } from './save-as-sketch';
|
||||||
|
import {
|
||||||
|
SketchContribution,
|
||||||
|
Command,
|
||||||
|
CommandRegistry,
|
||||||
|
MenuModelRegistry,
|
||||||
|
KeybindingRegistry,
|
||||||
|
TabBarToolbarRegistry,
|
||||||
|
} from './contribution';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export class SaveSketch extends SketchContribution {
|
export class SaveSketch extends SketchContribution {
|
||||||
|
|
||||||
registerCommands(registry: CommandRegistry): void {
|
registerCommands(registry: CommandRegistry): void {
|
||||||
registry.registerCommand(SaveSketch.Commands.SAVE_SKETCH, {
|
registry.registerCommand(SaveSketch.Commands.SAVE_SKETCH, {
|
||||||
execute: () => this.saveSketch()
|
execute: () => this.saveSketch(),
|
||||||
});
|
});
|
||||||
registry.registerCommand(SaveSketch.Commands.SAVE_SKETCH__TOOLBAR, {
|
registry.registerCommand(SaveSketch.Commands.SAVE_SKETCH__TOOLBAR, {
|
||||||
isVisible: widget => ArduinoToolbar.is(widget) && widget.side === 'left',
|
isVisible: (widget) =>
|
||||||
execute: () => registry.executeCommand(SaveSketch.Commands.SAVE_SKETCH.id)
|
ArduinoToolbar.is(widget) && widget.side === 'left',
|
||||||
|
execute: () =>
|
||||||
|
registry.executeCommand(SaveSketch.Commands.SAVE_SKETCH.id),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
registerMenus(registry: MenuModelRegistry): void {
|
registerMenus(registry: MenuModelRegistry): void {
|
||||||
registry.registerMenuAction(ArduinoMenus.FILE__SKETCH_GROUP, {
|
registry.registerMenuAction(ArduinoMenus.FILE__SKETCH_GROUP, {
|
||||||
commandId: SaveSketch.Commands.SAVE_SKETCH.id,
|
commandId: SaveSketch.Commands.SAVE_SKETCH.id,
|
||||||
label: 'Save',
|
label: nls.localize('vscode/fileCommands/save', 'Save'),
|
||||||
order: '6'
|
order: '6',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
registerKeybindings(registry: KeybindingRegistry): void {
|
registerKeybindings(registry: KeybindingRegistry): void {
|
||||||
registry.registerKeybinding({
|
registry.registerKeybinding({
|
||||||
command: SaveSketch.Commands.SAVE_SKETCH.id,
|
command: SaveSketch.Commands.SAVE_SKETCH.id,
|
||||||
keybinding: 'CtrlCmd+S'
|
keybinding: 'CtrlCmd+S',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -36,24 +46,39 @@ export class SaveSketch extends SketchContribution {
|
|||||||
registry.registerItem({
|
registry.registerItem({
|
||||||
id: SaveSketch.Commands.SAVE_SKETCH__TOOLBAR.id,
|
id: SaveSketch.Commands.SAVE_SKETCH__TOOLBAR.id,
|
||||||
command: SaveSketch.Commands.SAVE_SKETCH__TOOLBAR.id,
|
command: SaveSketch.Commands.SAVE_SKETCH__TOOLBAR.id,
|
||||||
tooltip: 'Save',
|
tooltip: nls.localize('vscode/fileCommands/save', 'Save'),
|
||||||
priority: 5
|
priority: 5,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async saveSketch(): Promise<void> {
|
async saveSketch(): Promise<void> {
|
||||||
return this.commandService.executeCommand(CommonCommands.SAVE_ALL.id);
|
const sketch = await this.sketchServiceClient.currentSketch();
|
||||||
|
if (!sketch) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const isTemp = await this.sketchService.isTemp(sketch);
|
||||||
|
if (isTemp) {
|
||||||
|
return this.commandService.executeCommand(
|
||||||
|
SaveAsSketch.Commands.SAVE_AS_SKETCH.id,
|
||||||
|
{
|
||||||
|
execOnlyIfTemp: false,
|
||||||
|
openAfterMove: true,
|
||||||
|
wipeOriginal: true,
|
||||||
|
}
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return this.commandService.executeCommand(CommonCommands.SAVE_ALL.id);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export namespace SaveSketch {
|
export namespace SaveSketch {
|
||||||
export namespace Commands {
|
export namespace Commands {
|
||||||
export const SAVE_SKETCH: Command = {
|
export const SAVE_SKETCH: Command = {
|
||||||
id: 'arduino-save-sketch'
|
id: 'arduino-save-sketch',
|
||||||
};
|
};
|
||||||
export const SAVE_SKETCH__TOOLBAR: Command = {
|
export const SAVE_SKETCH__TOOLBAR: Command = {
|
||||||
id: 'arduino-save-sketch--toolbar'
|
id: 'arduino-save-sketch--toolbar',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,18 @@
|
|||||||
import { inject, injectable } from 'inversify';
|
import { inject, injectable } from 'inversify';
|
||||||
import { Command, MenuModelRegistry, CommandRegistry, SketchContribution, KeybindingRegistry } from './contribution';
|
import {
|
||||||
|
Command,
|
||||||
|
MenuModelRegistry,
|
||||||
|
CommandRegistry,
|
||||||
|
SketchContribution,
|
||||||
|
KeybindingRegistry,
|
||||||
|
} from './contribution';
|
||||||
import { ArduinoMenus } from '../menu/arduino-menus';
|
import { ArduinoMenus } from '../menu/arduino-menus';
|
||||||
import { Settings as Preferences, SettingsDialog } from '../settings';
|
import { Settings as Preferences } from '../dialogs/settings/settings';
|
||||||
|
import { SettingsDialog } from '../dialogs/settings/settings-dialog';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export class Settings extends SketchContribution {
|
export class Settings extends SketchContribution {
|
||||||
|
|
||||||
@inject(SettingsDialog)
|
@inject(SettingsDialog)
|
||||||
protected readonly settingsDialog: SettingsDialog;
|
protected readonly settingsDialog: SettingsDialog;
|
||||||
|
|
||||||
@@ -28,16 +35,21 @@ export class Settings extends SketchContribution {
|
|||||||
await this.settingsService.reset();
|
await this.settingsService.reset();
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
isEnabled: () => !this.settingsOpened
|
isEnabled: () => !this.settingsOpened,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
registerMenus(registry: MenuModelRegistry): void {
|
registerMenus(registry: MenuModelRegistry): void {
|
||||||
registry.registerMenuAction(ArduinoMenus.FILE__SETTINGS_GROUP, {
|
registry.registerMenuAction(ArduinoMenus.FILE__PREFERENCES_GROUP, {
|
||||||
commandId: Settings.Commands.OPEN.id,
|
commandId: Settings.Commands.OPEN.id,
|
||||||
label: 'Preferences...',
|
label:
|
||||||
order: '0'
|
nls.localize(
|
||||||
|
'vscode/preferences.contribution/preferences',
|
||||||
|
'Preferences'
|
||||||
|
) + '...',
|
||||||
|
order: '0',
|
||||||
});
|
});
|
||||||
|
registry.registerSubmenu(ArduinoMenus.FILE__ADVANCED_SUBMENU, 'Advanced');
|
||||||
}
|
}
|
||||||
|
|
||||||
registerKeybindings(registry: KeybindingRegistry): void {
|
registerKeybindings(registry: KeybindingRegistry): void {
|
||||||
@@ -46,15 +58,18 @@ export class Settings extends SketchContribution {
|
|||||||
keybinding: 'CtrlCmd+,',
|
keybinding: 'CtrlCmd+,',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export namespace Settings {
|
export namespace Settings {
|
||||||
export namespace Commands {
|
export namespace Commands {
|
||||||
export const OPEN: Command = {
|
export const OPEN: Command = {
|
||||||
id: 'arduino-settings-open',
|
id: 'arduino-settings-open',
|
||||||
label: 'Open Preferences...',
|
label:
|
||||||
category: 'Arduino'
|
nls.localize(
|
||||||
}
|
'vscode/preferences.contribution/openSettings2',
|
||||||
|
'Open Preferences'
|
||||||
|
) + '...',
|
||||||
|
category: 'Arduino',
|
||||||
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,13 +3,28 @@ import { CommonCommands } from '@theia/core/lib/browser/common-frontend-contribu
|
|||||||
import { ApplicationShell } from '@theia/core/lib/browser/shell/application-shell';
|
import { ApplicationShell } from '@theia/core/lib/browser/shell/application-shell';
|
||||||
import { WorkspaceCommands } from '@theia/workspace/lib/browser';
|
import { WorkspaceCommands } from '@theia/workspace/lib/browser';
|
||||||
import { ContextMenuRenderer } from '@theia/core/lib/browser/context-menu-renderer';
|
import { ContextMenuRenderer } from '@theia/core/lib/browser/context-menu-renderer';
|
||||||
import { Disposable, DisposableCollection } from '@theia/core/lib/common/disposable';
|
import {
|
||||||
import { URI, SketchContribution, Command, CommandRegistry, MenuModelRegistry, KeybindingRegistry, TabBarToolbarRegistry, open } from './contribution';
|
Disposable,
|
||||||
import { ArduinoMenus } from '../menu/arduino-menus';
|
DisposableCollection,
|
||||||
|
} from '@theia/core/lib/common/disposable';
|
||||||
|
import {
|
||||||
|
URI,
|
||||||
|
SketchContribution,
|
||||||
|
Command,
|
||||||
|
CommandRegistry,
|
||||||
|
MenuModelRegistry,
|
||||||
|
KeybindingRegistry,
|
||||||
|
TabBarToolbarRegistry,
|
||||||
|
open,
|
||||||
|
} from './contribution';
|
||||||
|
import { ArduinoMenus, PlaceholderMenuNode } from '../menu/arduino-menus';
|
||||||
|
import { EditorManager } from '@theia/editor/lib/browser/editor-manager';
|
||||||
|
import { SketchesServiceClientImpl } from '../../common/protocol/sketches-service-client-impl';
|
||||||
|
import { LocalCacheFsProvider } from '../local-cache/local-cache-fs-provider';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export class SketchControl extends SketchContribution {
|
export class SketchControl extends SketchContribution {
|
||||||
|
|
||||||
@inject(ApplicationShell)
|
@inject(ApplicationShell)
|
||||||
protected readonly shell: ApplicationShell;
|
protected readonly shell: ApplicationShell;
|
||||||
|
|
||||||
@@ -19,11 +34,24 @@ export class SketchControl extends SketchContribution {
|
|||||||
@inject(ContextMenuRenderer)
|
@inject(ContextMenuRenderer)
|
||||||
protected readonly contextMenuRenderer: ContextMenuRenderer;
|
protected readonly contextMenuRenderer: ContextMenuRenderer;
|
||||||
|
|
||||||
protected readonly toDisposeBeforeCreateNewContextMenu = new DisposableCollection();
|
@inject(EditorManager)
|
||||||
|
protected readonly editorManager: EditorManager;
|
||||||
|
|
||||||
|
@inject(SketchesServiceClientImpl)
|
||||||
|
protected readonly sketchesServiceClient: SketchesServiceClientImpl;
|
||||||
|
|
||||||
|
@inject(LocalCacheFsProvider)
|
||||||
|
protected readonly localCacheFsProvider: LocalCacheFsProvider;
|
||||||
|
|
||||||
|
protected readonly toDisposeBeforeCreateNewContextMenu =
|
||||||
|
new DisposableCollection();
|
||||||
|
|
||||||
registerCommands(registry: CommandRegistry): void {
|
registerCommands(registry: CommandRegistry): void {
|
||||||
registry.registerCommand(SketchControl.Commands.OPEN_SKETCH_CONTROL__TOOLBAR, {
|
registry.registerCommand(
|
||||||
isVisible: widget => this.shell.getWidgets('main').indexOf(widget) !== -1,
|
SketchControl.Commands.OPEN_SKETCH_CONTROL__TOOLBAR,
|
||||||
|
{
|
||||||
|
isVisible: (widget) =>
|
||||||
|
this.shell.getWidgets('main').indexOf(widget) !== -1,
|
||||||
execute: async () => {
|
execute: async () => {
|
||||||
this.toDisposeBeforeCreateNewContextMenu.dispose();
|
this.toDisposeBeforeCreateNewContextMenu.dispose();
|
||||||
const sketch = await this.sketchServiceClient.currentSketch();
|
const sketch = await this.sketchServiceClient.currentSketch();
|
||||||
@@ -31,7 +59,9 @@ export class SketchControl extends SketchContribution {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const target = document.getElementById(SketchControl.Commands.OPEN_SKETCH_CONTROL__TOOLBAR.id);
|
const target = document.getElementById(
|
||||||
|
SketchControl.Commands.OPEN_SKETCH_CONTROL__TOOLBAR.id
|
||||||
|
);
|
||||||
if (!(target instanceof HTMLElement)) {
|
if (!(target instanceof HTMLElement)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -40,90 +70,213 @@ export class SketchControl extends SketchContribution {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const { mainFileUri, rootFolderFileUris } = await this.sketchService.loadSketch(sketch.uri);
|
const { mainFileUri, rootFolderFileUris } =
|
||||||
|
await this.sketchService.loadSketch(sketch.uri);
|
||||||
const uris = [mainFileUri, ...rootFolderFileUris];
|
const uris = [mainFileUri, ...rootFolderFileUris];
|
||||||
|
|
||||||
|
const currentSketch =
|
||||||
|
await this.sketchesServiceClient.currentSketch();
|
||||||
|
const parentsketchUri = this.editorManager.currentEditor
|
||||||
|
?.getResourceUri()
|
||||||
|
?.toString();
|
||||||
|
const parentsketch = await this.sketchService.getSketchFolder(
|
||||||
|
parentsketchUri || ''
|
||||||
|
);
|
||||||
|
|
||||||
|
// if the current file is in the current opened sketch, show extra menus
|
||||||
|
if (
|
||||||
|
currentSketch &&
|
||||||
|
parentsketch &&
|
||||||
|
parentsketch.uri === currentSketch.uri &&
|
||||||
|
this.allowRename(parentsketch.uri)
|
||||||
|
) {
|
||||||
|
this.menuRegistry.registerMenuAction(
|
||||||
|
ArduinoMenus.SKETCH_CONTROL__CONTEXT__MAIN_GROUP,
|
||||||
|
{
|
||||||
|
commandId: WorkspaceCommands.FILE_RENAME.id,
|
||||||
|
label: nls.localize('vscode/fileActions/rename', 'Rename'),
|
||||||
|
order: '1',
|
||||||
|
}
|
||||||
|
);
|
||||||
|
this.toDisposeBeforeCreateNewContextMenu.push(
|
||||||
|
Disposable.create(() =>
|
||||||
|
this.menuRegistry.unregisterMenuAction(
|
||||||
|
WorkspaceCommands.FILE_RENAME
|
||||||
|
)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
const renamePlaceholder = new PlaceholderMenuNode(
|
||||||
|
ArduinoMenus.SKETCH_CONTROL__CONTEXT__MAIN_GROUP,
|
||||||
|
nls.localize('vscode/fileActions/rename', 'Rename')
|
||||||
|
);
|
||||||
|
this.menuRegistry.registerMenuNode(
|
||||||
|
ArduinoMenus.SKETCH_CONTROL__CONTEXT__MAIN_GROUP,
|
||||||
|
renamePlaceholder
|
||||||
|
);
|
||||||
|
this.toDisposeBeforeCreateNewContextMenu.push(
|
||||||
|
Disposable.create(() =>
|
||||||
|
this.menuRegistry.unregisterMenuNode(renamePlaceholder.id)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
currentSketch &&
|
||||||
|
parentsketch &&
|
||||||
|
parentsketch.uri === currentSketch.uri &&
|
||||||
|
this.allowDelete(parentsketch.uri)
|
||||||
|
) {
|
||||||
|
this.menuRegistry.registerMenuAction(
|
||||||
|
ArduinoMenus.SKETCH_CONTROL__CONTEXT__MAIN_GROUP,
|
||||||
|
{
|
||||||
|
commandId: WorkspaceCommands.FILE_DELETE.id, // TODO: customize delete. Wipe sketch if deleting main file. Close window.
|
||||||
|
label: nls.localize('vscode/fileActions/delete', 'Delete'),
|
||||||
|
order: '2',
|
||||||
|
}
|
||||||
|
);
|
||||||
|
this.toDisposeBeforeCreateNewContextMenu.push(
|
||||||
|
Disposable.create(() =>
|
||||||
|
this.menuRegistry.unregisterMenuAction(
|
||||||
|
WorkspaceCommands.FILE_DELETE
|
||||||
|
)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
const deletePlaceholder = new PlaceholderMenuNode(
|
||||||
|
ArduinoMenus.SKETCH_CONTROL__CONTEXT__MAIN_GROUP,
|
||||||
|
nls.localize('vscode/fileActions/delete', 'Delete')
|
||||||
|
);
|
||||||
|
this.menuRegistry.registerMenuNode(
|
||||||
|
ArduinoMenus.SKETCH_CONTROL__CONTEXT__MAIN_GROUP,
|
||||||
|
deletePlaceholder
|
||||||
|
);
|
||||||
|
this.toDisposeBeforeCreateNewContextMenu.push(
|
||||||
|
Disposable.create(() =>
|
||||||
|
this.menuRegistry.unregisterMenuNode(deletePlaceholder.id)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
for (let i = 0; i < uris.length; i++) {
|
for (let i = 0; i < uris.length; i++) {
|
||||||
const uri = new URI(uris[i]);
|
const uri = new URI(uris[i]);
|
||||||
const command = { id: `arduino-focus-file--${uri.toString()}` };
|
|
||||||
const handler = { execute: () => open(this.openerService, uri) };
|
// focus on the opened sketch
|
||||||
this.toDisposeBeforeCreateNewContextMenu.push(registry.registerCommand(command, handler));
|
const command = {
|
||||||
this.menuRegistry.registerMenuAction(ArduinoMenus.SKETCH_CONTROL__CONTEXT__RESOURCES_GROUP, {
|
id: `arduino-focus-file--${uri.toString()}`,
|
||||||
|
};
|
||||||
|
const handler = {
|
||||||
|
execute: () => open(this.openerService, uri),
|
||||||
|
};
|
||||||
|
this.toDisposeBeforeCreateNewContextMenu.push(
|
||||||
|
registry.registerCommand(command, handler)
|
||||||
|
);
|
||||||
|
this.menuRegistry.registerMenuAction(
|
||||||
|
ArduinoMenus.SKETCH_CONTROL__CONTEXT__RESOURCES_GROUP,
|
||||||
|
{
|
||||||
commandId: command.id,
|
commandId: command.id,
|
||||||
label: this.labelProvider.getName(uri),
|
label: this.labelProvider.getName(uri),
|
||||||
order: `${i}`
|
order: `${i}`,
|
||||||
});
|
}
|
||||||
this.toDisposeBeforeCreateNewContextMenu.push(Disposable.create(() => this.menuRegistry.unregisterMenuAction(command)));
|
);
|
||||||
|
this.toDisposeBeforeCreateNewContextMenu.push(
|
||||||
|
Disposable.create(() =>
|
||||||
|
this.menuRegistry.unregisterMenuAction(command)
|
||||||
|
)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
const options = {
|
const options = {
|
||||||
menuPath: ArduinoMenus.SKETCH_CONTROL__CONTEXT,
|
menuPath: ArduinoMenus.SKETCH_CONTROL__CONTEXT,
|
||||||
anchor: {
|
anchor: {
|
||||||
x: parentElement.getBoundingClientRect().left,
|
x: parentElement.getBoundingClientRect().left,
|
||||||
y: parentElement.getBoundingClientRect().top + parentElement.offsetHeight
|
y:
|
||||||
}
|
parentElement.getBoundingClientRect().top +
|
||||||
}
|
parentElement.offsetHeight,
|
||||||
|
},
|
||||||
|
};
|
||||||
this.contextMenuRenderer.render(options);
|
this.contextMenuRenderer.render(options);
|
||||||
|
},
|
||||||
}
|
}
|
||||||
});
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
registerMenus(registry: MenuModelRegistry): void {
|
registerMenus(registry: MenuModelRegistry): void {
|
||||||
registry.registerMenuAction(ArduinoMenus.SKETCH_CONTROL__CONTEXT__MAIN_GROUP, {
|
registry.registerMenuAction(
|
||||||
|
ArduinoMenus.SKETCH_CONTROL__CONTEXT__MAIN_GROUP,
|
||||||
|
{
|
||||||
commandId: WorkspaceCommands.NEW_FILE.id,
|
commandId: WorkspaceCommands.NEW_FILE.id,
|
||||||
label: 'New Tab',
|
label: nls.localize('vscode/menubar/mNewTab', 'New Tab'),
|
||||||
order: '0'
|
order: '0',
|
||||||
});
|
}
|
||||||
registry.registerMenuAction(ArduinoMenus.SKETCH_CONTROL__CONTEXT__MAIN_GROUP, {
|
);
|
||||||
commandId: WorkspaceCommands.FILE_RENAME.id,
|
|
||||||
label: 'Rename',
|
|
||||||
order: '1'
|
|
||||||
});
|
|
||||||
registry.registerMenuAction(ArduinoMenus.SKETCH_CONTROL__CONTEXT__MAIN_GROUP, {
|
|
||||||
commandId: WorkspaceCommands.FILE_DELETE.id, // TODO: customize delete. Wipe sketch if deleting main file. Close window.
|
|
||||||
label: 'Delete',
|
|
||||||
order: '2'
|
|
||||||
});
|
|
||||||
|
|
||||||
registry.registerMenuAction(ArduinoMenus.SKETCH_CONTROL__CONTEXT__NAVIGATION_GROUP, {
|
registry.registerMenuAction(
|
||||||
|
ArduinoMenus.SKETCH_CONTROL__CONTEXT__NAVIGATION_GROUP,
|
||||||
|
{
|
||||||
commandId: CommonCommands.PREVIOUS_TAB.id,
|
commandId: CommonCommands.PREVIOUS_TAB.id,
|
||||||
label: 'Previous Tab',
|
label: nls.localize('vscode/menubar/mShowPreviousTab', 'Previous Tab'),
|
||||||
order: '0'
|
order: '0',
|
||||||
});
|
}
|
||||||
registry.registerMenuAction(ArduinoMenus.SKETCH_CONTROL__CONTEXT__NAVIGATION_GROUP, {
|
);
|
||||||
|
registry.registerMenuAction(
|
||||||
|
ArduinoMenus.SKETCH_CONTROL__CONTEXT__NAVIGATION_GROUP,
|
||||||
|
{
|
||||||
commandId: CommonCommands.NEXT_TAB.id,
|
commandId: CommonCommands.NEXT_TAB.id,
|
||||||
label: 'Next Tab',
|
label: nls.localize('vscode/menubar/mShowNextTab', 'Next Tab'),
|
||||||
order: '0'
|
order: '0',
|
||||||
});
|
}
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
registerKeybindings(registry: KeybindingRegistry): void {
|
registerKeybindings(registry: KeybindingRegistry): void {
|
||||||
registry.registerKeybinding({
|
registry.registerKeybinding({
|
||||||
command: WorkspaceCommands.NEW_FILE.id,
|
command: WorkspaceCommands.NEW_FILE.id,
|
||||||
keybinding: 'CtrlCmd+Shift+N'
|
keybinding: 'CtrlCmd+Shift+N',
|
||||||
});
|
});
|
||||||
registry.registerKeybinding({
|
registry.registerKeybinding({
|
||||||
command: CommonCommands.PREVIOUS_TAB.id,
|
command: CommonCommands.PREVIOUS_TAB.id,
|
||||||
keybinding: 'CtrlCmd+Alt+Left' // TODO: check why electron does not show the keybindings in the UI.
|
keybinding: 'CtrlCmd+Alt+Left', // TODO: check why electron does not show the keybindings in the UI.
|
||||||
});
|
});
|
||||||
registry.registerKeybinding({
|
registry.registerKeybinding({
|
||||||
command: CommonCommands.NEXT_TAB.id,
|
command: CommonCommands.NEXT_TAB.id,
|
||||||
keybinding: 'CtrlCmd+Alt+Right'
|
keybinding: 'CtrlCmd+Alt+Right',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
registerToolbarItems(registry: TabBarToolbarRegistry): void {
|
registerToolbarItems(registry: TabBarToolbarRegistry): void {
|
||||||
registry.registerItem({
|
registry.registerItem({
|
||||||
id: SketchControl.Commands.OPEN_SKETCH_CONTROL__TOOLBAR.id,
|
id: SketchControl.Commands.OPEN_SKETCH_CONTROL__TOOLBAR.id,
|
||||||
command: SketchControl.Commands.OPEN_SKETCH_CONTROL__TOOLBAR.id
|
command: SketchControl.Commands.OPEN_SKETCH_CONTROL__TOOLBAR.id,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected isCloudSketch(uri: string): boolean {
|
||||||
|
try {
|
||||||
|
const cloudCacheLocation = this.localCacheFsProvider.from(new URI(uri));
|
||||||
|
|
||||||
|
if (cloudCacheLocation) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected allowRename(uri: string): boolean {
|
||||||
|
return !this.isCloudSketch(uri);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected allowDelete(uri: string): boolean {
|
||||||
|
return !this.isCloudSketch(uri);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export namespace SketchControl {
|
export namespace SketchControl {
|
||||||
export namespace Commands {
|
export namespace Commands {
|
||||||
export const OPEN_SKETCH_CONTROL__TOOLBAR: Command = {
|
export const OPEN_SKETCH_CONTROL__TOOLBAR: Command = {
|
||||||
id: 'arduino-open-sketch-control--toolbar',
|
id: 'arduino-open-sketch-control--toolbar',
|
||||||
iconClass: 'fa fa-caret-down'
|
iconClass: 'fa fa-caret-down',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,16 @@
|
|||||||
import { inject, injectable } from 'inversify';
|
import { inject, injectable } from 'inversify';
|
||||||
import { Disposable, DisposableCollection } from '@theia/core/lib/common/disposable';
|
import { CommandHandler } from '@theia/core/lib/common/command';
|
||||||
import { SketchContribution, CommandRegistry, MenuModelRegistry, Sketch } from './contribution';
|
import { CommandRegistry, MenuModelRegistry } from './contribution';
|
||||||
import { ArduinoMenus } from '../menu/arduino-menus';
|
import { ArduinoMenus } from '../menu/arduino-menus';
|
||||||
import { MainMenuManager } from '../../common/main-menu-manager';
|
import { MainMenuManager } from '../../common/main-menu-manager';
|
||||||
import { NotificationCenter } from '../notification-center';
|
import { NotificationCenter } from '../notification-center';
|
||||||
|
import { Examples } from './examples';
|
||||||
|
import { SketchContainer } from '../../common/protocol';
|
||||||
import { OpenSketch } from './open-sketch';
|
import { OpenSketch } from './open-sketch';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export class Sketchbook extends SketchContribution {
|
export class Sketchbook extends Examples {
|
||||||
|
|
||||||
@inject(CommandRegistry)
|
@inject(CommandRegistry)
|
||||||
protected readonly commandRegistry: CommandRegistry;
|
protected readonly commandRegistry: CommandRegistry;
|
||||||
|
|
||||||
@@ -21,49 +23,45 @@ export class Sketchbook extends SketchContribution {
|
|||||||
@inject(NotificationCenter)
|
@inject(NotificationCenter)
|
||||||
protected readonly notificationCenter: NotificationCenter;
|
protected readonly notificationCenter: NotificationCenter;
|
||||||
|
|
||||||
protected toDisposePerSketch = new Map<string, DisposableCollection>();
|
|
||||||
|
|
||||||
onStart(): void {
|
onStart(): void {
|
||||||
this.sketchService.getSketches().then(sketches => {
|
this.sketchService.getSketches({}).then((container) => {
|
||||||
this.register(sketches);
|
this.register(container);
|
||||||
this.mainMenuManager.update();
|
this.mainMenuManager.update();
|
||||||
});
|
});
|
||||||
this.sketchServiceClient.onSketchbookDidChange(({ created, removed }) => {
|
this.sketchServiceClient.onSketchbookDidChange(() => {
|
||||||
this.unregister(removed);
|
this.sketchService.getSketches({}).then((container) => {
|
||||||
this.register(created);
|
this.register(container);
|
||||||
this.mainMenuManager.update();
|
this.mainMenuManager.update();
|
||||||
});
|
});
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
registerMenus(registry: MenuModelRegistry): void {
|
registerMenus(registry: MenuModelRegistry): void {
|
||||||
registry.registerSubmenu(ArduinoMenus.FILE__SKETCHBOOK_SUBMENU, 'Sketchbook', { order: '3' });
|
registry.registerSubmenu(
|
||||||
|
ArduinoMenus.FILE__SKETCHBOOK_SUBMENU,
|
||||||
|
nls.localize('arduino/sketch/sketchbook', 'Sketchbook'),
|
||||||
|
{ order: '3' }
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected register(sketches: Sketch[]): void {
|
protected register(container: SketchContainer): void {
|
||||||
for (const sketch of sketches) {
|
this.toDispose.dispose();
|
||||||
const { uri } = sketch;
|
this.registerRecursively(
|
||||||
const toDispose = this.toDisposePerSketch.get(uri);
|
[...container.children, ...container.sketches],
|
||||||
if (toDispose) {
|
ArduinoMenus.FILE__SKETCHBOOK_SUBMENU,
|
||||||
toDispose.dispose();
|
this.toDispose
|
||||||
}
|
);
|
||||||
const command = { id: `arduino-sketchbook-open--${uri}` };
|
|
||||||
const handler = { execute: () => this.commandRegistry.executeCommand(OpenSketch.Commands.OPEN_SKETCH.id, sketch) };
|
|
||||||
this.commandRegistry.registerCommand(command, handler);
|
|
||||||
this.menuRegistry.registerMenuAction(ArduinoMenus.FILE__SKETCHBOOK_SUBMENU, { commandId: command.id, label: sketch.name });
|
|
||||||
this.toDisposePerSketch.set(sketch.uri, new DisposableCollection(
|
|
||||||
Disposable.create(() => this.commandRegistry.unregisterCommand(command)),
|
|
||||||
Disposable.create(() => this.menuRegistry.unregisterMenuAction(command))
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected unregister(sketches: Sketch[]): void {
|
protected createHandler(uri: string): CommandHandler {
|
||||||
for (const { uri } of sketches) {
|
return {
|
||||||
const toDispose = this.toDisposePerSketch.get(uri);
|
execute: async () => {
|
||||||
if (toDispose) {
|
const sketch = await this.sketchService.loadSketch(uri);
|
||||||
toDispose.dispose();
|
return this.commandService.executeCommand(
|
||||||
|
OpenSketch.Commands.OPEN_SKETCH.id,
|
||||||
|
sketch
|
||||||
|
);
|
||||||
|
},
|
||||||
|
};
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,140 @@
|
|||||||
|
import { inject, injectable } from 'inversify';
|
||||||
|
import {
|
||||||
|
Command,
|
||||||
|
MenuModelRegistry,
|
||||||
|
CommandRegistry,
|
||||||
|
Contribution,
|
||||||
|
} from './contribution';
|
||||||
|
import { ArduinoMenus } from '../menu/arduino-menus';
|
||||||
|
import { UploadCertificateDialog } from '../dialogs/certificate-uploader/certificate-uploader-dialog';
|
||||||
|
import { ContextMenuRenderer } from '@theia/core/lib/browser/context-menu-renderer';
|
||||||
|
import {
|
||||||
|
PreferenceScope,
|
||||||
|
PreferenceService,
|
||||||
|
} from '@theia/core/lib/browser/preferences/preference-service';
|
||||||
|
import { ArduinoPreferences } from '../arduino-preferences';
|
||||||
|
import {
|
||||||
|
arduinoCert,
|
||||||
|
certificateList,
|
||||||
|
} from '../dialogs/certificate-uploader/utils';
|
||||||
|
import { ArduinoFirmwareUploader } from '../../common/protocol/arduino-firmware-uploader';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
|
||||||
|
@injectable()
|
||||||
|
export class UploadCertificate extends Contribution {
|
||||||
|
@inject(UploadCertificateDialog)
|
||||||
|
protected readonly dialog: UploadCertificateDialog;
|
||||||
|
|
||||||
|
@inject(ContextMenuRenderer)
|
||||||
|
protected readonly contextMenuRenderer: ContextMenuRenderer;
|
||||||
|
|
||||||
|
@inject(PreferenceService)
|
||||||
|
protected readonly preferenceService: PreferenceService;
|
||||||
|
|
||||||
|
@inject(ArduinoPreferences)
|
||||||
|
protected readonly arduinoPreferences: ArduinoPreferences;
|
||||||
|
|
||||||
|
@inject(ArduinoFirmwareUploader)
|
||||||
|
protected readonly arduinoFirmwareUploader: ArduinoFirmwareUploader;
|
||||||
|
|
||||||
|
protected dialogOpened = false;
|
||||||
|
|
||||||
|
registerCommands(registry: CommandRegistry): void {
|
||||||
|
registry.registerCommand(UploadCertificate.Commands.OPEN, {
|
||||||
|
execute: async () => {
|
||||||
|
try {
|
||||||
|
this.dialogOpened = true;
|
||||||
|
await this.dialog.open();
|
||||||
|
} finally {
|
||||||
|
this.dialogOpened = false;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
isEnabled: () => !this.dialogOpened,
|
||||||
|
});
|
||||||
|
|
||||||
|
registry.registerCommand(UploadCertificate.Commands.REMOVE_CERT, {
|
||||||
|
execute: async (certToRemove) => {
|
||||||
|
const certs = this.arduinoPreferences.get('arduino.board.certificates');
|
||||||
|
|
||||||
|
this.preferenceService.set(
|
||||||
|
'arduino.board.certificates',
|
||||||
|
certificateList(certs)
|
||||||
|
.filter((c) => c !== certToRemove)
|
||||||
|
.join(','),
|
||||||
|
PreferenceScope.User
|
||||||
|
);
|
||||||
|
},
|
||||||
|
isEnabled: (certToRemove) => certToRemove !== arduinoCert,
|
||||||
|
});
|
||||||
|
|
||||||
|
registry.registerCommand(UploadCertificate.Commands.UPLOAD_CERT, {
|
||||||
|
execute: async ({ fqbn, address, urls }) => {
|
||||||
|
return this.arduinoFirmwareUploader.uploadCertificates(
|
||||||
|
`-b ${fqbn} -a ${address} ${urls
|
||||||
|
.map((url: string) => `-u ${url}`)
|
||||||
|
.join(' ')}`
|
||||||
|
);
|
||||||
|
},
|
||||||
|
isEnabled: () => true,
|
||||||
|
});
|
||||||
|
|
||||||
|
registry.registerCommand(UploadCertificate.Commands.OPEN_CERT_CONTEXT, {
|
||||||
|
execute: async (args: any) => {
|
||||||
|
this.contextMenuRenderer.render({
|
||||||
|
menuPath: ArduinoMenus.ROOT_CERTIFICATES__CONTEXT,
|
||||||
|
anchor: {
|
||||||
|
x: args.x,
|
||||||
|
y: args.y,
|
||||||
|
},
|
||||||
|
args: [args.cert],
|
||||||
|
});
|
||||||
|
},
|
||||||
|
isEnabled: () => true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
registerMenus(registry: MenuModelRegistry): void {
|
||||||
|
registry.registerMenuAction(ArduinoMenus.TOOLS__FIRMWARE_UPLOADER_GROUP, {
|
||||||
|
commandId: UploadCertificate.Commands.OPEN.id,
|
||||||
|
label: UploadCertificate.Commands.OPEN.label,
|
||||||
|
order: '1',
|
||||||
|
});
|
||||||
|
|
||||||
|
registry.registerMenuAction(ArduinoMenus.ROOT_CERTIFICATES__CONTEXT, {
|
||||||
|
commandId: UploadCertificate.Commands.REMOVE_CERT.id,
|
||||||
|
label: UploadCertificate.Commands.REMOVE_CERT.label,
|
||||||
|
order: '1',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export namespace UploadCertificate {
|
||||||
|
export namespace Commands {
|
||||||
|
export const OPEN: Command = {
|
||||||
|
id: 'arduino-upload-certificate-open',
|
||||||
|
label: nls.localize(
|
||||||
|
'arduino/certificate/uploadRootCertificates',
|
||||||
|
'Upload SSL Root Certificates'
|
||||||
|
),
|
||||||
|
category: 'Arduino',
|
||||||
|
};
|
||||||
|
|
||||||
|
export const OPEN_CERT_CONTEXT: Command = {
|
||||||
|
id: 'arduino-certificate-open-context',
|
||||||
|
label: nls.localize('arduino/certificate/openContext', 'Open context'),
|
||||||
|
category: 'Arduino',
|
||||||
|
};
|
||||||
|
|
||||||
|
export const REMOVE_CERT: Command = {
|
||||||
|
id: 'arduino-certificate-remove',
|
||||||
|
label: nls.localize('arduino/certificate/remove', 'Remove'),
|
||||||
|
category: 'Arduino',
|
||||||
|
};
|
||||||
|
|
||||||
|
export const UPLOAD_CERT: Command = {
|
||||||
|
id: 'arduino-certificate-upload',
|
||||||
|
label: nls.localize('arduino/certificate/upload', 'Upload'),
|
||||||
|
category: 'Arduino',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import { inject, injectable } from 'inversify';
|
||||||
|
import {
|
||||||
|
Command,
|
||||||
|
MenuModelRegistry,
|
||||||
|
CommandRegistry,
|
||||||
|
Contribution,
|
||||||
|
} from './contribution';
|
||||||
|
import { ArduinoMenus } from '../menu/arduino-menus';
|
||||||
|
import { UploadFirmwareDialog } from '../dialogs/firmware-uploader/firmware-uploader-dialog';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
|
||||||
|
@injectable()
|
||||||
|
export class UploadFirmware extends Contribution {
|
||||||
|
@inject(UploadFirmwareDialog)
|
||||||
|
protected readonly dialog: UploadFirmwareDialog;
|
||||||
|
|
||||||
|
protected dialogOpened = false;
|
||||||
|
|
||||||
|
registerCommands(registry: CommandRegistry): void {
|
||||||
|
registry.registerCommand(UploadFirmware.Commands.OPEN, {
|
||||||
|
execute: async () => {
|
||||||
|
try {
|
||||||
|
this.dialogOpened = true;
|
||||||
|
await this.dialog.open();
|
||||||
|
} finally {
|
||||||
|
this.dialogOpened = false;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
isEnabled: () => !this.dialogOpened,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
registerMenus(registry: MenuModelRegistry): void {
|
||||||
|
registry.registerMenuAction(ArduinoMenus.TOOLS__FIRMWARE_UPLOADER_GROUP, {
|
||||||
|
commandId: UploadFirmware.Commands.OPEN.id,
|
||||||
|
label: UploadFirmware.Commands.OPEN.label,
|
||||||
|
order: '0',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export namespace UploadFirmware {
|
||||||
|
export namespace Commands {
|
||||||
|
export const OPEN: Command = {
|
||||||
|
id: 'arduino-upload-firmware-open',
|
||||||
|
label: nls.localize(
|
||||||
|
'arduino/firmware/updater',
|
||||||
|
'WiFi101 / WiFiNINA Firmware Updater'
|
||||||
|
),
|
||||||
|
category: 'Arduino',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,21 +1,32 @@
|
|||||||
import { inject, injectable } from 'inversify';
|
import { inject, injectable, postConstruct } from 'inversify';
|
||||||
import { OutputChannelManager } from '@theia/output/lib/common/output-channel';
|
import { Emitter } from '@theia/core/lib/common/event';
|
||||||
import { CoreService } from '../../common/protocol';
|
import { BoardUserField, CoreService } from '../../common/protocol';
|
||||||
import { ArduinoMenus } from '../menu/arduino-menus';
|
import { ArduinoMenus, PlaceholderMenuNode } from '../menu/arduino-menus';
|
||||||
import { ArduinoToolbar } from '../toolbar/arduino-toolbar';
|
import { ArduinoToolbar } from '../toolbar/arduino-toolbar';
|
||||||
import { BoardsDataStore } from '../boards/boards-data-store';
|
import { BoardsDataStore } from '../boards/boards-data-store';
|
||||||
import { MonitorConnection } from '../monitor/monitor-connection';
|
import { SerialConnectionManager } from '../serial/serial-connection-manager';
|
||||||
import { BoardsServiceProvider } from '../boards/boards-service-provider';
|
import { BoardsServiceProvider } from '../boards/boards-service-provider';
|
||||||
import { SketchContribution, Command, CommandRegistry, MenuModelRegistry, KeybindingRegistry, TabBarToolbarRegistry } from './contribution';
|
import {
|
||||||
|
SketchContribution,
|
||||||
|
Command,
|
||||||
|
CommandRegistry,
|
||||||
|
MenuModelRegistry,
|
||||||
|
KeybindingRegistry,
|
||||||
|
TabBarToolbarRegistry,
|
||||||
|
} from './contribution';
|
||||||
|
import { UserFieldsDialog } from '../dialogs/user-fields/user-fields-dialog';
|
||||||
|
import { DisposableCollection, nls } from '@theia/core/lib/common';
|
||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export class UploadSketch extends SketchContribution {
|
export class UploadSketch extends SketchContribution {
|
||||||
|
|
||||||
@inject(CoreService)
|
@inject(CoreService)
|
||||||
protected readonly coreService: CoreService;
|
protected readonly coreService: CoreService;
|
||||||
|
|
||||||
@inject(MonitorConnection)
|
@inject(SerialConnectionManager)
|
||||||
protected readonly monitorConnection: MonitorConnection;
|
protected readonly serialConnection: SerialConnectionManager;
|
||||||
|
|
||||||
|
@inject(MenuModelRegistry)
|
||||||
|
protected readonly menuRegistry: MenuModelRegistry;
|
||||||
|
|
||||||
@inject(BoardsDataStore)
|
@inject(BoardsDataStore)
|
||||||
protected readonly boardsDataStore: BoardsDataStore;
|
protected readonly boardsDataStore: BoardsDataStore;
|
||||||
@@ -23,43 +34,157 @@ export class UploadSketch extends SketchContribution {
|
|||||||
@inject(BoardsServiceProvider)
|
@inject(BoardsServiceProvider)
|
||||||
protected readonly boardsServiceClientImpl: BoardsServiceProvider;
|
protected readonly boardsServiceClientImpl: BoardsServiceProvider;
|
||||||
|
|
||||||
@inject(OutputChannelManager)
|
@inject(UserFieldsDialog)
|
||||||
protected readonly outputChannelManager: OutputChannelManager;
|
protected readonly userFieldsDialog: UserFieldsDialog;
|
||||||
|
|
||||||
|
protected cachedUserFields: Map<string, BoardUserField[]> = new Map();
|
||||||
|
|
||||||
|
protected readonly onDidChangeEmitter = new Emitter<Readonly<void>>();
|
||||||
|
readonly onDidChange = this.onDidChangeEmitter.event;
|
||||||
|
|
||||||
|
protected uploadInProgress = false;
|
||||||
|
protected boardRequiresUserFields = false;
|
||||||
|
|
||||||
|
protected readonly menuActionsDisposables = new DisposableCollection();
|
||||||
|
|
||||||
|
@postConstruct()
|
||||||
|
protected init(): void {
|
||||||
|
this.boardsServiceClientImpl.onBoardsConfigChanged(async () => {
|
||||||
|
const userFields =
|
||||||
|
await this.boardsServiceClientImpl.selectedBoardUserFields();
|
||||||
|
this.boardRequiresUserFields = userFields.length > 0;
|
||||||
|
this.registerMenus(this.menuRegistry);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private selectedFqbnAddress(): string {
|
||||||
|
const { boardsConfig } = this.boardsServiceClientImpl;
|
||||||
|
const fqbn = boardsConfig.selectedBoard?.fqbn;
|
||||||
|
if (!fqbn) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
const address =
|
||||||
|
boardsConfig.selectedBoard?.port?.address ||
|
||||||
|
boardsConfig.selectedPort?.address;
|
||||||
|
if (!address) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
return fqbn + '|' + address;
|
||||||
|
}
|
||||||
|
|
||||||
registerCommands(registry: CommandRegistry): void {
|
registerCommands(registry: CommandRegistry): void {
|
||||||
registry.registerCommand(UploadSketch.Commands.UPLOAD_SKETCH, {
|
registry.registerCommand(UploadSketch.Commands.UPLOAD_SKETCH, {
|
||||||
execute: () => this.uploadSketch()
|
execute: async () => {
|
||||||
|
const key = this.selectedFqbnAddress();
|
||||||
|
if (!key) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (this.boardRequiresUserFields && !this.cachedUserFields.has(key)) {
|
||||||
|
// Deep clone the array of board fields to avoid editing the cached ones
|
||||||
|
this.userFieldsDialog.value = (
|
||||||
|
await this.boardsServiceClientImpl.selectedBoardUserFields()
|
||||||
|
).map((f) => ({ ...f }));
|
||||||
|
const result = await this.userFieldsDialog.open();
|
||||||
|
if (!result) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.cachedUserFields.set(key, result);
|
||||||
|
}
|
||||||
|
this.uploadSketch();
|
||||||
|
},
|
||||||
|
isEnabled: () => !this.uploadInProgress,
|
||||||
});
|
});
|
||||||
registry.registerCommand(UploadSketch.Commands.UPLOAD_SKETCH_USING_PROGRAMMER, {
|
registry.registerCommand(UploadSketch.Commands.UPLOAD_WITH_CONFIGURATION, {
|
||||||
execute: () => this.uploadSketch(true)
|
execute: async () => {
|
||||||
|
const key = this.selectedFqbnAddress();
|
||||||
|
if (!key) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const cached = this.cachedUserFields.get(key);
|
||||||
|
// Deep clone the array of board fields to avoid editing the cached ones
|
||||||
|
this.userFieldsDialog.value = (
|
||||||
|
cached ??
|
||||||
|
(await this.boardsServiceClientImpl.selectedBoardUserFields())
|
||||||
|
).map((f) => ({ ...f }));
|
||||||
|
|
||||||
|
const result = await this.userFieldsDialog.open();
|
||||||
|
if (!result) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.cachedUserFields.set(key, result);
|
||||||
|
this.uploadSketch();
|
||||||
|
},
|
||||||
|
isEnabled: () => !this.uploadInProgress && this.boardRequiresUserFields,
|
||||||
});
|
});
|
||||||
|
registry.registerCommand(
|
||||||
|
UploadSketch.Commands.UPLOAD_SKETCH_USING_PROGRAMMER,
|
||||||
|
{
|
||||||
|
execute: () => this.uploadSketch(true),
|
||||||
|
isEnabled: () => !this.uploadInProgress,
|
||||||
|
}
|
||||||
|
);
|
||||||
registry.registerCommand(UploadSketch.Commands.UPLOAD_SKETCH_TOOLBAR, {
|
registry.registerCommand(UploadSketch.Commands.UPLOAD_SKETCH_TOOLBAR, {
|
||||||
isVisible: widget => ArduinoToolbar.is(widget) && widget.side === 'left',
|
isVisible: (widget) =>
|
||||||
execute: () => registry.executeCommand(UploadSketch.Commands.UPLOAD_SKETCH.id)
|
ArduinoToolbar.is(widget) && widget.side === 'left',
|
||||||
|
isEnabled: () => !this.uploadInProgress,
|
||||||
|
isToggled: () => this.uploadInProgress,
|
||||||
|
execute: () =>
|
||||||
|
registry.executeCommand(UploadSketch.Commands.UPLOAD_SKETCH.id),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
registerMenus(registry: MenuModelRegistry): void {
|
registerMenus(registry: MenuModelRegistry): void {
|
||||||
|
this.menuActionsDisposables.dispose();
|
||||||
|
|
||||||
|
this.menuActionsDisposables.push(
|
||||||
registry.registerMenuAction(ArduinoMenus.SKETCH__MAIN_GROUP, {
|
registry.registerMenuAction(ArduinoMenus.SKETCH__MAIN_GROUP, {
|
||||||
commandId: UploadSketch.Commands.UPLOAD_SKETCH.id,
|
commandId: UploadSketch.Commands.UPLOAD_SKETCH.id,
|
||||||
label: 'Upload',
|
label: nls.localize('arduino/sketch/upload', 'Upload'),
|
||||||
order: '1'
|
order: '1',
|
||||||
});
|
})
|
||||||
|
);
|
||||||
|
if (this.boardRequiresUserFields) {
|
||||||
|
this.menuActionsDisposables.push(
|
||||||
|
registry.registerMenuAction(ArduinoMenus.SKETCH__MAIN_GROUP, {
|
||||||
|
commandId: UploadSketch.Commands.UPLOAD_WITH_CONFIGURATION.id,
|
||||||
|
label: UploadSketch.Commands.UPLOAD_WITH_CONFIGURATION.label,
|
||||||
|
order: '2',
|
||||||
|
})
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
this.menuActionsDisposables.push(
|
||||||
|
registry.registerMenuNode(
|
||||||
|
ArduinoMenus.SKETCH__MAIN_GROUP,
|
||||||
|
new PlaceholderMenuNode(
|
||||||
|
ArduinoMenus.SKETCH__MAIN_GROUP,
|
||||||
|
// commandId: UploadSketch.Commands.UPLOAD_WITH_CONFIGURATION.id,
|
||||||
|
UploadSketch.Commands.UPLOAD_WITH_CONFIGURATION.label!,
|
||||||
|
{ order: '2' }
|
||||||
|
)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
this.menuActionsDisposables.push(
|
||||||
registry.registerMenuAction(ArduinoMenus.SKETCH__MAIN_GROUP, {
|
registry.registerMenuAction(ArduinoMenus.SKETCH__MAIN_GROUP, {
|
||||||
commandId: UploadSketch.Commands.UPLOAD_SKETCH_USING_PROGRAMMER.id,
|
commandId: UploadSketch.Commands.UPLOAD_SKETCH_USING_PROGRAMMER.id,
|
||||||
label: 'Upload Using Programmer',
|
label: nls.localize(
|
||||||
order: '2'
|
'arduino/sketch/uploadUsingProgrammer',
|
||||||
});
|
'Upload Using Programmer'
|
||||||
|
),
|
||||||
|
order: '3',
|
||||||
|
})
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
registerKeybindings(registry: KeybindingRegistry): void {
|
registerKeybindings(registry: KeybindingRegistry): void {
|
||||||
registry.registerKeybinding({
|
registry.registerKeybinding({
|
||||||
command: UploadSketch.Commands.UPLOAD_SKETCH.id,
|
command: UploadSketch.Commands.UPLOAD_SKETCH.id,
|
||||||
keybinding: 'CtrlCmd+U'
|
keybinding: 'CtrlCmd+U',
|
||||||
});
|
});
|
||||||
registry.registerKeybinding({
|
registry.registerKeybinding({
|
||||||
command: UploadSketch.Commands.UPLOAD_SKETCH_USING_PROGRAMMER.id,
|
command: UploadSketch.Commands.UPLOAD_SKETCH_USING_PROGRAMMER.id,
|
||||||
keybinding: 'CtrlCmd+Shift+U'
|
keybinding: 'CtrlCmd+Shift+U',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -67,40 +192,56 @@ export class UploadSketch extends SketchContribution {
|
|||||||
registry.registerItem({
|
registry.registerItem({
|
||||||
id: UploadSketch.Commands.UPLOAD_SKETCH_TOOLBAR.id,
|
id: UploadSketch.Commands.UPLOAD_SKETCH_TOOLBAR.id,
|
||||||
command: UploadSketch.Commands.UPLOAD_SKETCH_TOOLBAR.id,
|
command: UploadSketch.Commands.UPLOAD_SKETCH_TOOLBAR.id,
|
||||||
tooltip: 'Upload',
|
tooltip: nls.localize('arduino/sketch/upload', 'Upload'),
|
||||||
priority: 1
|
priority: 1,
|
||||||
|
onDidChange: this.onDidChange,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async uploadSketch(usingProgrammer: boolean = false): Promise<void> {
|
async uploadSketch(usingProgrammer = false): Promise<void> {
|
||||||
|
// even with buttons disabled, better to double check if an upload is already in progress
|
||||||
|
if (this.uploadInProgress) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// toggle the toolbar button and menu item state.
|
||||||
|
// uploadInProgress will be set to false whether the upload fails or not
|
||||||
|
this.uploadInProgress = true;
|
||||||
|
this.onDidChangeEmitter.fire();
|
||||||
const sketch = await this.sketchServiceClient.currentSketch();
|
const sketch = await this.sketchServiceClient.currentSketch();
|
||||||
if (!sketch) {
|
if (!sketch) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let shouldAutoConnect = false;
|
|
||||||
const monitorConfig = this.monitorConnection.monitorConfig;
|
|
||||||
if (monitorConfig) {
|
|
||||||
await this.monitorConnection.disconnect();
|
|
||||||
if (this.monitorConnection.autoConnect) {
|
|
||||||
shouldAutoConnect = true;
|
|
||||||
}
|
|
||||||
this.monitorConnection.autoConnect = false;
|
|
||||||
}
|
|
||||||
try {
|
try {
|
||||||
const { boardsConfig } = this.boardsServiceClientImpl;
|
const { boardsConfig } = this.boardsServiceClientImpl;
|
||||||
const [fqbn, { selectedProgrammer }, verify, verbose, sourceOverride] = await Promise.all([
|
const [fqbn, { selectedProgrammer }, verify, verbose, sourceOverride] =
|
||||||
this.boardsDataStore.appendConfigToFqbn(boardsConfig.selectedBoard?.fqbn),
|
await Promise.all([
|
||||||
|
this.boardsDataStore.appendConfigToFqbn(
|
||||||
|
boardsConfig.selectedBoard?.fqbn
|
||||||
|
),
|
||||||
this.boardsDataStore.getData(boardsConfig.selectedBoard?.fqbn),
|
this.boardsDataStore.getData(boardsConfig.selectedBoard?.fqbn),
|
||||||
this.preferences.get('arduino.upload.verify'),
|
this.preferences.get('arduino.upload.verify'),
|
||||||
this.preferences.get('arduino.upload.verbose'),
|
this.preferences.get('arduino.upload.verbose'),
|
||||||
this.sourceOverride()
|
this.sourceOverride(),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
let options: CoreService.Upload.Options | undefined = undefined;
|
let options: CoreService.Upload.Options | undefined = undefined;
|
||||||
const sketchUri = sketch.uri;
|
const sketchUri = sketch.uri;
|
||||||
const optimizeForDebug = this.editorMode.compileForDebug;
|
const optimizeForDebug = this.editorMode.compileForDebug;
|
||||||
const { selectedPort } = boardsConfig;
|
const { selectedPort } = boardsConfig;
|
||||||
const port = selectedPort?.address;
|
const port = selectedPort;
|
||||||
|
const userFields =
|
||||||
|
this.cachedUserFields.get(this.selectedFqbnAddress()) ?? [];
|
||||||
|
if (userFields.length === 0 && this.boardRequiresUserFields) {
|
||||||
|
this.messageService.error(
|
||||||
|
nls.localize(
|
||||||
|
'arduino/sketch/userFieldsNotFoundError',
|
||||||
|
"Can't find user fields for connected board"
|
||||||
|
)
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (usingProgrammer) {
|
if (usingProgrammer) {
|
||||||
const programmer = selectedProgrammer;
|
const programmer = selectedProgrammer;
|
||||||
@@ -112,7 +253,8 @@ export class UploadSketch extends SketchContribution {
|
|||||||
port,
|
port,
|
||||||
verbose,
|
verbose,
|
||||||
verify,
|
verify,
|
||||||
sourceOverride
|
sourceOverride,
|
||||||
|
userFields,
|
||||||
};
|
};
|
||||||
} else {
|
} else {
|
||||||
options = {
|
options = {
|
||||||
@@ -122,7 +264,8 @@ export class UploadSketch extends SketchContribution {
|
|||||||
port,
|
port,
|
||||||
verbose,
|
verbose,
|
||||||
verify,
|
verify,
|
||||||
sourceOverride
|
sourceOverride,
|
||||||
|
userFields,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
this.outputChannelManager.getChannel('Arduino').clear();
|
this.outputChannelManager.getChannel('Arduino').clear();
|
||||||
@@ -131,39 +274,45 @@ export class UploadSketch extends SketchContribution {
|
|||||||
} else {
|
} else {
|
||||||
await this.coreService.upload(options);
|
await this.coreService.upload(options);
|
||||||
}
|
}
|
||||||
this.messageService.info('Done uploading.', { timeout: 1000 });
|
this.messageService.info(
|
||||||
|
nls.localize('arduino/sketch/doneUploading', 'Done uploading.'),
|
||||||
|
{ timeout: 3000 }
|
||||||
|
);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
this.messageService.error(e.toString());
|
let errorMessage = '';
|
||||||
} finally {
|
if (typeof e === 'string') {
|
||||||
if (monitorConfig) {
|
errorMessage = e;
|
||||||
const { board, port } = monitorConfig;
|
|
||||||
try {
|
|
||||||
await this.boardsServiceClientImpl.waitUntilAvailable(Object.assign(board, { port }), 10_000);
|
|
||||||
if (shouldAutoConnect) {
|
|
||||||
// Enabling auto-connect will trigger a connect.
|
|
||||||
this.monitorConnection.autoConnect = true;
|
|
||||||
} else {
|
} else {
|
||||||
await this.monitorConnection.connect(monitorConfig);
|
errorMessage = e.toString();
|
||||||
}
|
|
||||||
} catch (waitError) {
|
|
||||||
this.messageService.error(`Could not reconnect to serial monitor. ${waitError.toString()}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
this.messageService.error(errorMessage);
|
||||||
|
} finally {
|
||||||
|
this.uploadInProgress = false;
|
||||||
|
this.onDidChangeEmitter.fire();
|
||||||
|
|
||||||
|
setTimeout(() => this.serialConnection.reconnectAfterUpload(), 5000);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export namespace UploadSketch {
|
export namespace UploadSketch {
|
||||||
export namespace Commands {
|
export namespace Commands {
|
||||||
export const UPLOAD_SKETCH: Command = {
|
export const UPLOAD_SKETCH: Command = {
|
||||||
id: 'arduino-upload-sketch'
|
id: 'arduino-upload-sketch',
|
||||||
|
};
|
||||||
|
export const UPLOAD_WITH_CONFIGURATION: Command = {
|
||||||
|
id: 'arduino-upload-with-configuration-sketch',
|
||||||
|
label: nls.localize(
|
||||||
|
'arduino/sketch/configureAndUpload',
|
||||||
|
'Configure And Upload'
|
||||||
|
),
|
||||||
|
category: 'Arduino',
|
||||||
};
|
};
|
||||||
export const UPLOAD_SKETCH_USING_PROGRAMMER: Command = {
|
export const UPLOAD_SKETCH_USING_PROGRAMMER: Command = {
|
||||||
id: 'arduino-upload-sketch-using-programmer'
|
id: 'arduino-upload-sketch-using-programmer',
|
||||||
};
|
};
|
||||||
export const UPLOAD_SKETCH_TOOLBAR: Command = {
|
export const UPLOAD_SKETCH_TOOLBAR: Command = {
|
||||||
id: 'arduino-upload-sketch--toolbar'
|
id: 'arduino-upload-sketch--toolbar',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,22 @@
|
|||||||
import { inject, injectable } from 'inversify';
|
import { inject, injectable } from 'inversify';
|
||||||
import { OutputChannelManager } from '@theia/output/lib/common/output-channel';
|
import { Emitter } from '@theia/core/lib/common/event';
|
||||||
import { CoreService } from '../../common/protocol';
|
import { CoreService } from '../../common/protocol';
|
||||||
import { ArduinoMenus } from '../menu/arduino-menus';
|
import { ArduinoMenus } from '../menu/arduino-menus';
|
||||||
import { ArduinoToolbar } from '../toolbar/arduino-toolbar';
|
import { ArduinoToolbar } from '../toolbar/arduino-toolbar';
|
||||||
import { BoardsDataStore } from '../boards/boards-data-store';
|
import { BoardsDataStore } from '../boards/boards-data-store';
|
||||||
import { BoardsServiceProvider } from '../boards/boards-service-provider';
|
import { BoardsServiceProvider } from '../boards/boards-service-provider';
|
||||||
import { SketchContribution, Command, CommandRegistry, MenuModelRegistry, KeybindingRegistry, TabBarToolbarRegistry } from './contribution';
|
import {
|
||||||
|
SketchContribution,
|
||||||
|
Command,
|
||||||
|
CommandRegistry,
|
||||||
|
MenuModelRegistry,
|
||||||
|
KeybindingRegistry,
|
||||||
|
TabBarToolbarRegistry,
|
||||||
|
} from './contribution';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export class VerifySketch extends SketchContribution {
|
export class VerifySketch extends SketchContribution {
|
||||||
|
|
||||||
@inject(CoreService)
|
@inject(CoreService)
|
||||||
protected readonly coreService: CoreService;
|
protected readonly coreService: CoreService;
|
||||||
|
|
||||||
@@ -19,43 +26,54 @@ export class VerifySketch extends SketchContribution {
|
|||||||
@inject(BoardsServiceProvider)
|
@inject(BoardsServiceProvider)
|
||||||
protected readonly boardsServiceClientImpl: BoardsServiceProvider;
|
protected readonly boardsServiceClientImpl: BoardsServiceProvider;
|
||||||
|
|
||||||
@inject(OutputChannelManager)
|
protected readonly onDidChangeEmitter = new Emitter<Readonly<void>>();
|
||||||
protected readonly outputChannelManager: OutputChannelManager;
|
readonly onDidChange = this.onDidChangeEmitter.event;
|
||||||
|
|
||||||
|
protected verifyInProgress = false;
|
||||||
|
|
||||||
registerCommands(registry: CommandRegistry): void {
|
registerCommands(registry: CommandRegistry): void {
|
||||||
registry.registerCommand(VerifySketch.Commands.VERIFY_SKETCH, {
|
registry.registerCommand(VerifySketch.Commands.VERIFY_SKETCH, {
|
||||||
execute: () => this.verifySketch()
|
execute: () => this.verifySketch(),
|
||||||
|
isEnabled: () => !this.verifyInProgress,
|
||||||
});
|
});
|
||||||
registry.registerCommand(VerifySketch.Commands.EXPORT_BINARIES, {
|
registry.registerCommand(VerifySketch.Commands.EXPORT_BINARIES, {
|
||||||
execute: () => this.verifySketch(true)
|
execute: () => this.verifySketch(true),
|
||||||
|
isEnabled: () => !this.verifyInProgress,
|
||||||
});
|
});
|
||||||
registry.registerCommand(VerifySketch.Commands.VERIFY_SKETCH_TOOLBAR, {
|
registry.registerCommand(VerifySketch.Commands.VERIFY_SKETCH_TOOLBAR, {
|
||||||
isVisible: widget => ArduinoToolbar.is(widget) && widget.side === 'left',
|
isVisible: (widget) =>
|
||||||
execute: () => registry.executeCommand(VerifySketch.Commands.VERIFY_SKETCH.id)
|
ArduinoToolbar.is(widget) && widget.side === 'left',
|
||||||
|
isEnabled: () => !this.verifyInProgress,
|
||||||
|
isToggled: () => this.verifyInProgress,
|
||||||
|
execute: () =>
|
||||||
|
registry.executeCommand(VerifySketch.Commands.VERIFY_SKETCH.id),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
registerMenus(registry: MenuModelRegistry): void {
|
registerMenus(registry: MenuModelRegistry): void {
|
||||||
registry.registerMenuAction(ArduinoMenus.SKETCH__MAIN_GROUP, {
|
registry.registerMenuAction(ArduinoMenus.SKETCH__MAIN_GROUP, {
|
||||||
commandId: VerifySketch.Commands.VERIFY_SKETCH.id,
|
commandId: VerifySketch.Commands.VERIFY_SKETCH.id,
|
||||||
label: 'Verify/Compile',
|
label: nls.localize('arduino/sketch/verifyOrCompile', 'Verify/Compile'),
|
||||||
order: '0'
|
order: '0',
|
||||||
});
|
});
|
||||||
registry.registerMenuAction(ArduinoMenus.SKETCH__MAIN_GROUP, {
|
registry.registerMenuAction(ArduinoMenus.SKETCH__MAIN_GROUP, {
|
||||||
commandId: VerifySketch.Commands.EXPORT_BINARIES.id,
|
commandId: VerifySketch.Commands.EXPORT_BINARIES.id,
|
||||||
label: 'Export compiled Binary',
|
label: nls.localize(
|
||||||
order: '3'
|
'arduino/sketch/exportBinary',
|
||||||
|
'Export Compiled Binary'
|
||||||
|
),
|
||||||
|
order: '4',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
registerKeybindings(registry: KeybindingRegistry): void {
|
registerKeybindings(registry: KeybindingRegistry): void {
|
||||||
registry.registerKeybinding({
|
registry.registerKeybinding({
|
||||||
command: VerifySketch.Commands.VERIFY_SKETCH.id,
|
command: VerifySketch.Commands.VERIFY_SKETCH.id,
|
||||||
keybinding: 'CtrlCmd+R'
|
keybinding: 'CtrlCmd+R',
|
||||||
});
|
});
|
||||||
registry.registerKeybinding({
|
registry.registerKeybinding({
|
||||||
command: VerifySketch.Commands.EXPORT_BINARIES.id,
|
command: VerifySketch.Commands.EXPORT_BINARIES.id,
|
||||||
keybinding: 'CtrlCmd+Alt+S'
|
keybinding: 'CtrlCmd+Alt+S',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -63,23 +81,37 @@ export class VerifySketch extends SketchContribution {
|
|||||||
registry.registerItem({
|
registry.registerItem({
|
||||||
id: VerifySketch.Commands.VERIFY_SKETCH_TOOLBAR.id,
|
id: VerifySketch.Commands.VERIFY_SKETCH_TOOLBAR.id,
|
||||||
command: VerifySketch.Commands.VERIFY_SKETCH_TOOLBAR.id,
|
command: VerifySketch.Commands.VERIFY_SKETCH_TOOLBAR.id,
|
||||||
tooltip: 'Verify',
|
tooltip: nls.localize('arduino/sketch/verify', 'Verify'),
|
||||||
priority: 0
|
priority: 0,
|
||||||
|
onDidChange: this.onDidChange,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async verifySketch(exportBinaries?: boolean): Promise<void> {
|
async verifySketch(exportBinaries?: boolean): Promise<void> {
|
||||||
|
// even with buttons disabled, better to double check if a verify is already in progress
|
||||||
|
if (this.verifyInProgress) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// toggle the toolbar button and menu item state.
|
||||||
|
// verifyInProgress will be set to false whether the compilation fails or not
|
||||||
|
this.verifyInProgress = true;
|
||||||
|
this.onDidChangeEmitter.fire();
|
||||||
const sketch = await this.sketchServiceClient.currentSketch();
|
const sketch = await this.sketchServiceClient.currentSketch();
|
||||||
|
|
||||||
if (!sketch) {
|
if (!sketch) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const { boardsConfig } = this.boardsServiceClientImpl;
|
const { boardsConfig } = this.boardsServiceClientImpl;
|
||||||
const [fqbn, sourceOverride] = await Promise.all([
|
const [fqbn, sourceOverride] = await Promise.all([
|
||||||
this.boardsDataStore.appendConfigToFqbn(boardsConfig.selectedBoard?.fqbn),
|
this.boardsDataStore.appendConfigToFqbn(
|
||||||
this.sourceOverride()
|
boardsConfig.selectedBoard?.fqbn
|
||||||
|
),
|
||||||
|
this.sourceOverride(),
|
||||||
]);
|
]);
|
||||||
const verbose = this.preferences.get('arduino.compile.verbose');
|
const verbose = this.preferences.get('arduino.compile.verbose');
|
||||||
|
const compilerWarnings = this.preferences.get('arduino.compile.warnings');
|
||||||
this.outputChannelManager.getChannel('Arduino').clear();
|
this.outputChannelManager.getChannel('Arduino').clear();
|
||||||
await this.coreService.compile({
|
await this.coreService.compile({
|
||||||
sketchUri: sketch.uri,
|
sketchUri: sketch.uri,
|
||||||
@@ -87,26 +119,38 @@ export class VerifySketch extends SketchContribution {
|
|||||||
optimizeForDebug: this.editorMode.compileForDebug,
|
optimizeForDebug: this.editorMode.compileForDebug,
|
||||||
verbose,
|
verbose,
|
||||||
exportBinaries,
|
exportBinaries,
|
||||||
sourceOverride
|
sourceOverride,
|
||||||
|
compilerWarnings,
|
||||||
});
|
});
|
||||||
this.messageService.info('Done compiling.', { timeout: 1000 });
|
this.messageService.info(
|
||||||
|
nls.localize('arduino/sketch/doneCompiling', 'Done compiling.'),
|
||||||
|
{ timeout: 3000 }
|
||||||
|
);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
this.messageService.error(e.toString());
|
let errorMessage = "";
|
||||||
|
if (typeof e === "string") {
|
||||||
|
errorMessage = e;
|
||||||
|
} else {
|
||||||
|
errorMessage = e.toString();
|
||||||
|
}
|
||||||
|
this.messageService.error(errorMessage);
|
||||||
|
} finally {
|
||||||
|
this.verifyInProgress = false;
|
||||||
|
this.onDidChangeEmitter.fire();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export namespace VerifySketch {
|
export namespace VerifySketch {
|
||||||
export namespace Commands {
|
export namespace Commands {
|
||||||
export const VERIFY_SKETCH: Command = {
|
export const VERIFY_SKETCH: Command = {
|
||||||
id: 'arduino-verify-sketch'
|
id: 'arduino-verify-sketch',
|
||||||
};
|
};
|
||||||
export const EXPORT_BINARIES: Command = {
|
export const EXPORT_BINARIES: Command = {
|
||||||
id: 'arduino-export-binaries'
|
id: 'arduino-export-binaries',
|
||||||
};
|
};
|
||||||
export const VERIFY_SKETCH_TOOLBAR: Command = {
|
export const VERIFY_SKETCH_TOOLBAR: Command = {
|
||||||
id: 'arduino-verify-sketch--toolbar'
|
id: 'arduino-verify-sketch--toolbar',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
518
arduino-ide-extension/src/browser/create/create-api.ts
Normal file
518
arduino-ide-extension/src/browser/create/create-api.ts
Normal file
@@ -0,0 +1,518 @@
|
|||||||
|
import { injectable, inject } from 'inversify';
|
||||||
|
import * as createPaths from './create-paths';
|
||||||
|
import { posix } from './create-paths';
|
||||||
|
import { AuthenticationClientService } from '../auth/authentication-client-service';
|
||||||
|
import { ArduinoPreferences } from '../arduino-preferences';
|
||||||
|
import { SketchCache } from '../widgets/cloud-sketchbook/cloud-sketch-cache';
|
||||||
|
import { Create, CreateError } from './typings';
|
||||||
|
|
||||||
|
export interface ResponseResultProvider {
|
||||||
|
(response: Response): Promise<any>;
|
||||||
|
}
|
||||||
|
export namespace ResponseResultProvider {
|
||||||
|
export const NOOP: ResponseResultProvider = async () => undefined;
|
||||||
|
export const TEXT: ResponseResultProvider = (response) => response.text();
|
||||||
|
export const JSON: ResponseResultProvider = (response) => response.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Utf8ArrayToStr(array: Uint8Array): string {
|
||||||
|
let out, i, c;
|
||||||
|
let char2, char3;
|
||||||
|
|
||||||
|
out = '';
|
||||||
|
const len = array.length;
|
||||||
|
i = 0;
|
||||||
|
while (i < len) {
|
||||||
|
c = array[i++];
|
||||||
|
switch (c >> 4) {
|
||||||
|
case 0:
|
||||||
|
case 1:
|
||||||
|
case 2:
|
||||||
|
case 3:
|
||||||
|
case 4:
|
||||||
|
case 5:
|
||||||
|
case 6:
|
||||||
|
case 7:
|
||||||
|
// 0xxxxxxx
|
||||||
|
out += String.fromCharCode(c);
|
||||||
|
break;
|
||||||
|
case 12:
|
||||||
|
case 13:
|
||||||
|
// 110x xxxx 10xx xxxx
|
||||||
|
char2 = array[i++];
|
||||||
|
out += String.fromCharCode(((c & 0x1f) << 6) | (char2 & 0x3f));
|
||||||
|
break;
|
||||||
|
case 14:
|
||||||
|
// 1110 xxxx 10xx xxxx 10xx xxxx
|
||||||
|
char2 = array[i++];
|
||||||
|
char3 = array[i++];
|
||||||
|
out += String.fromCharCode(
|
||||||
|
((c & 0x0f) << 12) | ((char2 & 0x3f) << 6) | ((char3 & 0x3f) << 0)
|
||||||
|
);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
type ResourceType = 'f' | 'd';
|
||||||
|
|
||||||
|
@injectable()
|
||||||
|
export class CreateApi {
|
||||||
|
@inject(SketchCache)
|
||||||
|
protected sketchCache: SketchCache;
|
||||||
|
|
||||||
|
protected authenticationService: AuthenticationClientService;
|
||||||
|
protected arduinoPreferences: ArduinoPreferences;
|
||||||
|
|
||||||
|
public init(
|
||||||
|
authenticationService: AuthenticationClientService,
|
||||||
|
arduinoPreferences: ArduinoPreferences
|
||||||
|
): CreateApi {
|
||||||
|
this.authenticationService = authenticationService;
|
||||||
|
this.arduinoPreferences = arduinoPreferences;
|
||||||
|
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
getSketchSecretStat(sketch: Create.Sketch): Create.Resource {
|
||||||
|
return {
|
||||||
|
href: `${sketch.href}${posix.sep}${Create.arduino_secrets_file}`,
|
||||||
|
modified_at: sketch.modified_at,
|
||||||
|
created_at: sketch.created_at,
|
||||||
|
name: `${Create.arduino_secrets_file}`,
|
||||||
|
path: `${sketch.path}${posix.sep}${Create.arduino_secrets_file}`,
|
||||||
|
mimetype: 'text/x-c++src; charset=utf-8',
|
||||||
|
type: 'file',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async sketch(id: string): Promise<Create.Sketch> {
|
||||||
|
const url = new URL(`${this.domain()}/sketches/byID/${id}`);
|
||||||
|
|
||||||
|
url.searchParams.set('user_id', 'me');
|
||||||
|
const headers = await this.headers();
|
||||||
|
const result = await this.run<Create.Sketch>(url, {
|
||||||
|
method: 'GET',
|
||||||
|
headers,
|
||||||
|
});
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
async sketches(): Promise<Create.Sketch[]> {
|
||||||
|
const url = new URL(`${this.domain()}/sketches`);
|
||||||
|
url.searchParams.set('user_id', 'me');
|
||||||
|
const headers = await this.headers();
|
||||||
|
const result = await this.run<{ sketches: Create.Sketch[] }>(url, {
|
||||||
|
method: 'GET',
|
||||||
|
headers,
|
||||||
|
});
|
||||||
|
result.sketches.forEach((sketch) => this.sketchCache.addSketch(sketch));
|
||||||
|
return result.sketches;
|
||||||
|
}
|
||||||
|
|
||||||
|
async createSketch(
|
||||||
|
posixPath: string,
|
||||||
|
content: string = CreateApi.defaultInoContent
|
||||||
|
): Promise<Create.Sketch> {
|
||||||
|
const url = new URL(`${this.domain()}/sketches`);
|
||||||
|
const headers = await this.headers();
|
||||||
|
const payload = {
|
||||||
|
ino: btoa(content),
|
||||||
|
path: posixPath,
|
||||||
|
user_id: 'me',
|
||||||
|
};
|
||||||
|
const init = {
|
||||||
|
method: 'PUT',
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
headers,
|
||||||
|
};
|
||||||
|
const result = await this.run<Create.Sketch>(url, init);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
async readDirectory(
|
||||||
|
posixPath: string,
|
||||||
|
options: {
|
||||||
|
recursive?: boolean;
|
||||||
|
match?: string;
|
||||||
|
skipSketchCache?: boolean;
|
||||||
|
} = {}
|
||||||
|
): Promise<Create.Resource[]> {
|
||||||
|
const url = new URL(
|
||||||
|
`${this.domain()}/files/d/$HOME/sketches_v2${posixPath}`
|
||||||
|
);
|
||||||
|
if (options.recursive) {
|
||||||
|
url.searchParams.set('deep', 'true');
|
||||||
|
}
|
||||||
|
if (options.match) {
|
||||||
|
url.searchParams.set('name_like', options.match);
|
||||||
|
}
|
||||||
|
const headers = await this.headers();
|
||||||
|
|
||||||
|
const cachedSketch = this.sketchCache.getSketch(posixPath);
|
||||||
|
|
||||||
|
const sketchPromise = options.skipSketchCache
|
||||||
|
? (cachedSketch && this.sketch(cachedSketch.id)) || Promise.resolve(null)
|
||||||
|
: Promise.resolve(this.sketchCache.getSketch(posixPath));
|
||||||
|
|
||||||
|
return Promise.all([
|
||||||
|
sketchPromise,
|
||||||
|
this.run<Create.RawResource[]>(url, {
|
||||||
|
method: 'GET',
|
||||||
|
headers,
|
||||||
|
}),
|
||||||
|
])
|
||||||
|
.then(async ([sketch, result]) => {
|
||||||
|
if (posixPath.length && posixPath !== posix.sep) {
|
||||||
|
if (sketch && sketch.secrets && sketch.secrets.length > 0) {
|
||||||
|
result.push(this.getSketchSecretStat(sketch));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result.filter(
|
||||||
|
(res) => !Create.do_not_sync_files.includes(res.name)
|
||||||
|
);
|
||||||
|
})
|
||||||
|
.catch((reason) => {
|
||||||
|
if (reason?.status === 404) return [] as Create.Resource[];
|
||||||
|
else throw reason;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async createDirectory(posixPath: string): Promise<void> {
|
||||||
|
const url = new URL(
|
||||||
|
`${this.domain()}/files/d/$HOME/sketches_v2${posixPath}`
|
||||||
|
);
|
||||||
|
const headers = await this.headers();
|
||||||
|
await this.run(url, {
|
||||||
|
method: 'POST',
|
||||||
|
headers,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async stat(posixPath: string): Promise<Create.Resource> {
|
||||||
|
// The root is a directory read.
|
||||||
|
if (posixPath === '/') {
|
||||||
|
throw new Error('Stating the root is not supported');
|
||||||
|
}
|
||||||
|
// The RESTful API has different endpoints for files and directories.
|
||||||
|
// The RESTful API does not provide specific error codes, only HTP 500.
|
||||||
|
// We query the parent directory and look for the file with the last segment.
|
||||||
|
const parentPosixPath = createPaths.parentPosix(posixPath);
|
||||||
|
const basename = createPaths.basename(posixPath);
|
||||||
|
|
||||||
|
let resources;
|
||||||
|
if (basename === Create.arduino_secrets_file) {
|
||||||
|
const sketch = this.sketchCache.getSketch(parentPosixPath);
|
||||||
|
resources = sketch ? [this.getSketchSecretStat(sketch)] : [];
|
||||||
|
} else {
|
||||||
|
resources = await this.readDirectory(parentPosixPath, {
|
||||||
|
match: basename,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const resource = resources.find(
|
||||||
|
({ path }) => createPaths.splitSketchPath(path)[1] === posixPath
|
||||||
|
);
|
||||||
|
if (!resource) {
|
||||||
|
throw new CreateError(`Not found: ${posixPath}.`, 404);
|
||||||
|
}
|
||||||
|
return resource;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async toggleSecretsInclude(
|
||||||
|
path: string,
|
||||||
|
data: string,
|
||||||
|
mode: 'add' | 'remove'
|
||||||
|
) {
|
||||||
|
const includeString = `#include "${Create.arduino_secrets_file}"`;
|
||||||
|
const includeRegexp = new RegExp(includeString + '\\s*', 'g');
|
||||||
|
|
||||||
|
const basename = createPaths.basename(path);
|
||||||
|
if (mode === 'add') {
|
||||||
|
const doesIncludeSecrets = includeRegexp.test(data);
|
||||||
|
|
||||||
|
if (doesIncludeSecrets) {
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
const sketch = this.sketchCache.getSketch(createPaths.parentPosix(path));
|
||||||
|
|
||||||
|
if (
|
||||||
|
sketch &&
|
||||||
|
(sketch.name + '.ino' === basename ||
|
||||||
|
sketch.name + '.pde' === basename) &&
|
||||||
|
sketch.secrets &&
|
||||||
|
sketch.secrets.length > 0
|
||||||
|
) {
|
||||||
|
return includeString + '\n' + data;
|
||||||
|
}
|
||||||
|
} else if (mode === 'remove') {
|
||||||
|
return data.replace(includeRegexp, '');
|
||||||
|
}
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
async readFile(posixPath: string): Promise<string> {
|
||||||
|
const basename = createPaths.basename(posixPath);
|
||||||
|
|
||||||
|
if (basename === Create.arduino_secrets_file) {
|
||||||
|
const parentPosixPath = createPaths.parentPosix(posixPath);
|
||||||
|
|
||||||
|
//retrieve the sketch id from the cache
|
||||||
|
const cacheSketch = this.sketchCache.getSketch(parentPosixPath);
|
||||||
|
if (!cacheSketch) {
|
||||||
|
throw new Error(`Unable to find sketch ${parentPosixPath} in cache`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// get a fresh copy of the sketch in order to guarantee fresh secrets
|
||||||
|
const sketch = await this.sketch(cacheSketch.id);
|
||||||
|
if (!sketch) {
|
||||||
|
throw new Error(
|
||||||
|
`Unable to get a fresh copy of the sketch ${cacheSketch.id}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
this.sketchCache.addSketch(sketch);
|
||||||
|
|
||||||
|
let file = '';
|
||||||
|
if (sketch && sketch.secrets) {
|
||||||
|
for (const item of sketch.secrets) {
|
||||||
|
file += `#define ${item.name} "${item.value}"\r\n`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return file;
|
||||||
|
}
|
||||||
|
|
||||||
|
const url = new URL(
|
||||||
|
`${this.domain()}/files/f/$HOME/sketches_v2${posixPath}`
|
||||||
|
);
|
||||||
|
const headers = await this.headers();
|
||||||
|
const result = await this.run<{ data: string; path: string }>(url, {
|
||||||
|
method: 'GET',
|
||||||
|
headers,
|
||||||
|
});
|
||||||
|
let { data } = result;
|
||||||
|
|
||||||
|
// add includes to main arduino file
|
||||||
|
data = await this.toggleSecretsInclude(posixPath, atob(data), 'add');
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
async writeFile(
|
||||||
|
posixPath: string,
|
||||||
|
content: string | Uint8Array
|
||||||
|
): Promise<void> {
|
||||||
|
const basename = createPaths.basename(posixPath);
|
||||||
|
|
||||||
|
if (basename === Create.arduino_secrets_file) {
|
||||||
|
const parentPosixPath = createPaths.parentPosix(posixPath);
|
||||||
|
|
||||||
|
const sketch = this.sketchCache.getSketch(parentPosixPath);
|
||||||
|
|
||||||
|
if (sketch) {
|
||||||
|
const url = new URL(`${this.domain()}/sketches/${sketch.id}`);
|
||||||
|
const headers = await this.headers();
|
||||||
|
|
||||||
|
// parse the secret file
|
||||||
|
const secrets = (
|
||||||
|
typeof content === 'string' ? content : Utf8ArrayToStr(content)
|
||||||
|
)
|
||||||
|
.split(/\r?\n/)
|
||||||
|
.reduce((prev, curr) => {
|
||||||
|
// check if the line contains a secret
|
||||||
|
const secret = curr.split('SECRET_')[1] || null;
|
||||||
|
if (!secret) {
|
||||||
|
return prev;
|
||||||
|
}
|
||||||
|
const regexp = /(\S*)\s+([\S\s]*)/g;
|
||||||
|
const tokens = regexp.exec(secret) || [];
|
||||||
|
const name = tokens[1].length > 0 ? `SECRET_${tokens[1]}` : '';
|
||||||
|
|
||||||
|
let value = '';
|
||||||
|
if (tokens[2].length > 0) {
|
||||||
|
value = JSON.parse(
|
||||||
|
JSON.stringify(
|
||||||
|
tokens[2].replace(/^['"]?/g, '').replace(/['"]?$/g, '')
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (name.length === 0) {
|
||||||
|
return prev;
|
||||||
|
}
|
||||||
|
|
||||||
|
return [...prev, { name, value }];
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
id: sketch.id,
|
||||||
|
libraries: sketch.libraries,
|
||||||
|
secrets: { data: secrets },
|
||||||
|
};
|
||||||
|
|
||||||
|
// replace the sketch in the cache with the one we are pushing
|
||||||
|
// TODO: we should do a get after the POST, in order to be sure the cache
|
||||||
|
// is updated the most recent metadata
|
||||||
|
this.sketchCache.addSketch(sketch);
|
||||||
|
|
||||||
|
const init = {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
headers,
|
||||||
|
};
|
||||||
|
await this.run(url, init);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// do not upload "do_not_sync" files/directoris and their descendants
|
||||||
|
const segments = posixPath.split(posix.sep) || [];
|
||||||
|
if (
|
||||||
|
segments.some((segment) => Create.do_not_sync_files.includes(segment))
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const url = new URL(
|
||||||
|
`${this.domain()}/files/f/$HOME/sketches_v2${posixPath}`
|
||||||
|
);
|
||||||
|
const headers = await this.headers();
|
||||||
|
|
||||||
|
let data: string =
|
||||||
|
typeof content === 'string' ? content : Utf8ArrayToStr(content);
|
||||||
|
data = await this.toggleSecretsInclude(posixPath, data, 'remove');
|
||||||
|
|
||||||
|
const payload = { data: btoa(data) };
|
||||||
|
const init = {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
headers,
|
||||||
|
};
|
||||||
|
await this.run(url, init);
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteFile(posixPath: string): Promise<void> {
|
||||||
|
await this.delete(posixPath, 'f');
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteDirectory(posixPath: string): Promise<void> {
|
||||||
|
await this.delete(posixPath, 'd');
|
||||||
|
}
|
||||||
|
|
||||||
|
private async delete(posixPath: string, type: ResourceType): Promise<void> {
|
||||||
|
const url = new URL(
|
||||||
|
`${this.domain()}/files/${type}/$HOME/sketches_v2${posixPath}`
|
||||||
|
);
|
||||||
|
const headers = await this.headers();
|
||||||
|
await this.run(url, {
|
||||||
|
method: 'DELETE',
|
||||||
|
headers,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async rename(fromPosixPath: string, toPosixPath: string): Promise<void> {
|
||||||
|
const url = new URL(`${this.domain('v3')}/files/mv`);
|
||||||
|
const headers = await this.headers();
|
||||||
|
const payload = {
|
||||||
|
from: `$HOME/sketches_v2${fromPosixPath}`,
|
||||||
|
to: `$HOME/sketches_v2${toPosixPath}`,
|
||||||
|
};
|
||||||
|
const init = {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
headers,
|
||||||
|
};
|
||||||
|
await this.run(url, init, ResponseResultProvider.NOOP);
|
||||||
|
}
|
||||||
|
|
||||||
|
async editSketch({
|
||||||
|
id,
|
||||||
|
params,
|
||||||
|
}: {
|
||||||
|
id: string;
|
||||||
|
params: Record<string, unknown>;
|
||||||
|
}): Promise<Create.Sketch> {
|
||||||
|
const url = new URL(`${this.domain()}/sketches/${id}`);
|
||||||
|
|
||||||
|
const headers = await this.headers();
|
||||||
|
const result = await this.run<Create.Sketch>(url, {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ id, ...params }),
|
||||||
|
headers,
|
||||||
|
});
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
async copy(fromPosixPath: string, toPosixPath: string): Promise<void> {
|
||||||
|
const payload = {
|
||||||
|
from: `$HOME/sketches_v2${fromPosixPath}`,
|
||||||
|
to: `$HOME/sketches_v2${toPosixPath}`,
|
||||||
|
};
|
||||||
|
const url = new URL(`${this.domain('v3')}/files/cp`);
|
||||||
|
const headers = await this.headers();
|
||||||
|
const init = {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
headers,
|
||||||
|
};
|
||||||
|
await this.run(url, init, ResponseResultProvider.NOOP);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async run<T>(
|
||||||
|
requestInfo: RequestInfo | URL,
|
||||||
|
init: RequestInit | undefined,
|
||||||
|
resultProvider: ResponseResultProvider = ResponseResultProvider.JSON
|
||||||
|
): Promise<T> {
|
||||||
|
const response = await fetch(
|
||||||
|
requestInfo instanceof URL ? requestInfo.toString() : requestInfo,
|
||||||
|
init
|
||||||
|
);
|
||||||
|
if (!response.ok) {
|
||||||
|
let details: string | undefined = undefined;
|
||||||
|
try {
|
||||||
|
details = await response.json();
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Cloud not get the error details.', e);
|
||||||
|
}
|
||||||
|
const { statusText, status } = response;
|
||||||
|
throw new CreateError(statusText, status, details);
|
||||||
|
}
|
||||||
|
const result = await resultProvider(response);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async headers(): Promise<Record<string, string>> {
|
||||||
|
const token = await this.token();
|
||||||
|
return {
|
||||||
|
'content-type': 'application/json',
|
||||||
|
accept: 'application/json',
|
||||||
|
authorization: `Bearer ${token}`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private domain(apiVersion = 'v2'): string {
|
||||||
|
const endpoint = this.arduinoPreferences['arduino.cloud.sketchSyncEnpoint'];
|
||||||
|
return `${endpoint}/${apiVersion}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async token(): Promise<string> {
|
||||||
|
return this.authenticationService.session?.accessToken || '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export namespace CreateApi {
|
||||||
|
export const defaultInoContent = `/*
|
||||||
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
void setup() {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
void loop() {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
`;
|
||||||
|
}
|
||||||
198
arduino-ide-extension/src/browser/create/create-fs-provider.ts
Normal file
198
arduino-ide-extension/src/browser/create/create-fs-provider.ts
Normal file
@@ -0,0 +1,198 @@
|
|||||||
|
import { inject, injectable } from 'inversify';
|
||||||
|
import URI from '@theia/core/lib/common/uri';
|
||||||
|
import { Event } from '@theia/core/lib/common/event';
|
||||||
|
import {
|
||||||
|
Disposable,
|
||||||
|
DisposableCollection,
|
||||||
|
} from '@theia/core/lib/common/disposable';
|
||||||
|
import { FrontendApplicationContribution } from '@theia/core/lib/browser/frontend-application';
|
||||||
|
import {
|
||||||
|
Stat,
|
||||||
|
FileType,
|
||||||
|
FileChange,
|
||||||
|
FileWriteOptions,
|
||||||
|
FileDeleteOptions,
|
||||||
|
FileOverwriteOptions,
|
||||||
|
FileSystemProvider,
|
||||||
|
FileSystemProviderError,
|
||||||
|
FileSystemProviderErrorCode,
|
||||||
|
FileSystemProviderCapabilities,
|
||||||
|
WatchOptions,
|
||||||
|
} from '@theia/filesystem/lib/common/files';
|
||||||
|
import {
|
||||||
|
FileService,
|
||||||
|
FileServiceContribution,
|
||||||
|
} from '@theia/filesystem/lib/browser/file-service';
|
||||||
|
import { AuthenticationClientService } from '../auth/authentication-client-service';
|
||||||
|
import { CreateApi } from './create-api';
|
||||||
|
import { CreateUri } from './create-uri';
|
||||||
|
import { SketchesService } from '../../common/protocol';
|
||||||
|
import { ArduinoPreferences } from '../arduino-preferences';
|
||||||
|
import { Create } from './typings';
|
||||||
|
|
||||||
|
@injectable()
|
||||||
|
export class CreateFsProvider
|
||||||
|
implements
|
||||||
|
FileSystemProvider,
|
||||||
|
FrontendApplicationContribution,
|
||||||
|
FileServiceContribution
|
||||||
|
{
|
||||||
|
@inject(AuthenticationClientService)
|
||||||
|
protected readonly authenticationService: AuthenticationClientService;
|
||||||
|
|
||||||
|
@inject(CreateApi)
|
||||||
|
protected readonly createApi: CreateApi;
|
||||||
|
|
||||||
|
@inject(SketchesService)
|
||||||
|
protected readonly sketchesService: SketchesService;
|
||||||
|
|
||||||
|
@inject(ArduinoPreferences)
|
||||||
|
protected readonly arduinoPreferences: ArduinoPreferences;
|
||||||
|
|
||||||
|
protected readonly toDispose = new DisposableCollection();
|
||||||
|
|
||||||
|
readonly onFileWatchError: Event<void> = Event.None;
|
||||||
|
readonly onDidChangeFile: Event<readonly FileChange[]> = Event.None;
|
||||||
|
readonly onDidChangeCapabilities: Event<void> = Event.None;
|
||||||
|
readonly capabilities: FileSystemProviderCapabilities =
|
||||||
|
FileSystemProviderCapabilities.FileReadWrite |
|
||||||
|
FileSystemProviderCapabilities.PathCaseSensitive |
|
||||||
|
FileSystemProviderCapabilities.Access;
|
||||||
|
|
||||||
|
onStop(): void {
|
||||||
|
this.toDispose.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
registerFileSystemProviders(service: FileService): void {
|
||||||
|
service.onWillActivateFileSystemProvider((event) => {
|
||||||
|
if (event.scheme === CreateUri.scheme) {
|
||||||
|
event.waitUntil(
|
||||||
|
(async () => {
|
||||||
|
service.registerProvider(CreateUri.scheme, this);
|
||||||
|
})()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(uri: URI, opts: WatchOptions): Disposable {
|
||||||
|
return Disposable.NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
async stat(uri: URI): Promise<Stat> {
|
||||||
|
if (CreateUri.equals(CreateUri.root, uri)) {
|
||||||
|
this.getCreateApi; // This will throw when not logged in.
|
||||||
|
return {
|
||||||
|
type: FileType.Directory,
|
||||||
|
ctime: 0,
|
||||||
|
mtime: 0,
|
||||||
|
size: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const resource = await this.getCreateApi.stat(uri.path.toString());
|
||||||
|
const mtime = Date.parse(resource.modified_at);
|
||||||
|
return {
|
||||||
|
type: this.toFileType(resource.type),
|
||||||
|
ctime: mtime,
|
||||||
|
mtime,
|
||||||
|
size: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async mkdir(uri: URI): Promise<void> {
|
||||||
|
await this.getCreateApi.createDirectory(uri.path.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
async readdir(uri: URI): Promise<[string, FileType][]> {
|
||||||
|
const resources = await this.getCreateApi.readDirectory(
|
||||||
|
uri.path.toString()
|
||||||
|
);
|
||||||
|
return resources.map(({ name, type }) => [name, this.toFileType(type)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
async delete(uri: URI, opts: FileDeleteOptions): Promise<void> {
|
||||||
|
if (!opts.recursive) {
|
||||||
|
throw new Error(
|
||||||
|
'Arduino Create file-system provider does not support non-recursive deletion.'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const stat = await this.stat(uri);
|
||||||
|
if (!stat) {
|
||||||
|
throw new FileSystemProviderError(
|
||||||
|
'File not found.',
|
||||||
|
FileSystemProviderErrorCode.FileNotFound
|
||||||
|
);
|
||||||
|
}
|
||||||
|
switch (stat.type) {
|
||||||
|
case FileType.Directory: {
|
||||||
|
await this.getCreateApi.deleteDirectory(uri.path.toString());
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case FileType.File: {
|
||||||
|
await this.getCreateApi.deleteFile(uri.path.toString());
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
default: {
|
||||||
|
throw new FileSystemProviderError(
|
||||||
|
`Unexpected file type '${stat.type}' for resource: ${uri.toString()}`,
|
||||||
|
FileSystemProviderErrorCode.Unknown
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async rename(
|
||||||
|
oldUri: URI,
|
||||||
|
newUri: URI,
|
||||||
|
options: FileOverwriteOptions
|
||||||
|
): Promise<void> {
|
||||||
|
await this.getCreateApi.rename(
|
||||||
|
oldUri.path.toString(),
|
||||||
|
newUri.path.toString()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async readFile(uri: URI): Promise<Uint8Array> {
|
||||||
|
const content = await this.getCreateApi.readFile(uri.path.toString());
|
||||||
|
return new TextEncoder().encode(content);
|
||||||
|
}
|
||||||
|
|
||||||
|
async writeFile(
|
||||||
|
uri: URI,
|
||||||
|
content: Uint8Array,
|
||||||
|
options: FileWriteOptions
|
||||||
|
): Promise<void> {
|
||||||
|
await this.getCreateApi.writeFile(uri.path.toString(), content);
|
||||||
|
}
|
||||||
|
|
||||||
|
async access(uri: URI, mode?: number): Promise<void> {
|
||||||
|
this.getCreateApi; // Will throw if not logged in.
|
||||||
|
}
|
||||||
|
|
||||||
|
public toFileType(type: Create.ResourceType): FileType {
|
||||||
|
switch (type) {
|
||||||
|
case 'file':
|
||||||
|
return FileType.File;
|
||||||
|
case 'sketch':
|
||||||
|
case 'folder':
|
||||||
|
return FileType.Directory;
|
||||||
|
default:
|
||||||
|
return FileType.Unknown;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private get getCreateApi(): CreateApi {
|
||||||
|
const { session } = this.authenticationService;
|
||||||
|
if (!session) {
|
||||||
|
throw new FileSystemProviderError(
|
||||||
|
'Not logged in.',
|
||||||
|
FileSystemProviderErrorCode.NoPermissions
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.createApi.init(
|
||||||
|
this.authenticationService,
|
||||||
|
this.arduinoPreferences
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
59
arduino-ide-extension/src/browser/create/create-paths.ts
Normal file
59
arduino-ide-extension/src/browser/create/create-paths.ts
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
export const posix = { sep: '/' };
|
||||||
|
|
||||||
|
// TODO: poor man's `path.join(path, '..')` in the browser.
|
||||||
|
export function parentPosix(path: string): string {
|
||||||
|
const segments = path.split(posix.sep) || [];
|
||||||
|
segments.pop();
|
||||||
|
let modified = segments.join(posix.sep);
|
||||||
|
if (path.charAt(path.length - 1) === posix.sep) {
|
||||||
|
modified += posix.sep;
|
||||||
|
}
|
||||||
|
return modified;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function basename(path: string): string {
|
||||||
|
const segments = path.split(posix.sep) || [];
|
||||||
|
return segments.pop()!;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function posixSegments(posixPath: string): string[] {
|
||||||
|
return posixPath.split(posix.sep).filter((segment) => !!segment);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Splits the `raw` path into two segments, a root that contains user information and the relevant POSIX path. \
|
||||||
|
* For examples:
|
||||||
|
* ```
|
||||||
|
* `29ad0829759028dde9b877343fa3b0e1:testrest/sketches_v2/xxx_folder/xxx_sub_folder/sketch_in_folder/sketch_in_folder.ino`
|
||||||
|
* ```
|
||||||
|
* will be:
|
||||||
|
* ```
|
||||||
|
* ['29ad0829759028dde9b877343fa3b0e1:testrest/sketches_v2', '/xxx_folder/xxx_sub_folder/sketch_in_folder/sketch_in_folder.ino']
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
export function splitSketchPath(
|
||||||
|
raw: string,
|
||||||
|
sep = '/sketches_v2/'
|
||||||
|
): [string, string] {
|
||||||
|
if (!sep) {
|
||||||
|
throw new Error('Invalid separator. Cannot be zero length.');
|
||||||
|
}
|
||||||
|
const index = raw.indexOf(sep);
|
||||||
|
if (index === -1) {
|
||||||
|
throw new Error(`Invalid path pattern. Raw path was '${raw}'.`);
|
||||||
|
}
|
||||||
|
const createRoot = raw.substring(0, index + sep.length - 1); // TODO: validate the `createRoot` format.
|
||||||
|
const posixPath = raw.substr(index + sep.length - 1);
|
||||||
|
if (!posixPath) {
|
||||||
|
throw new Error(`Could not extract POSIX path from '${raw}'.`);
|
||||||
|
}
|
||||||
|
return [createRoot, posixPath];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function toPosixPath(raw: string): string {
|
||||||
|
if (raw === posix.sep) {
|
||||||
|
return posix.sep; // Handles the root resource case.
|
||||||
|
}
|
||||||
|
const [, posixPath] = splitSketchPath(raw);
|
||||||
|
return posixPath;
|
||||||
|
}
|
||||||
37
arduino-ide-extension/src/browser/create/create-uri.ts
Normal file
37
arduino-ide-extension/src/browser/create/create-uri.ts
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
import { URI as Uri } from 'vscode-uri';
|
||||||
|
import URI from '@theia/core/lib/common/uri';
|
||||||
|
import { toPosixPath, parentPosix, posix } from './create-paths';
|
||||||
|
import { Create } from './typings';
|
||||||
|
|
||||||
|
export namespace CreateUri {
|
||||||
|
export const scheme = 'arduino-create';
|
||||||
|
export const root = toUri(posix.sep);
|
||||||
|
|
||||||
|
export function toUri(posixPathOrResource: string | Create.Resource): URI {
|
||||||
|
const posixPath =
|
||||||
|
typeof posixPathOrResource === 'string'
|
||||||
|
? posixPathOrResource
|
||||||
|
: toPosixPath(posixPathOrResource.path);
|
||||||
|
return new URI(Uri.parse(posixPath).with({ scheme, authority: 'create' }));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function is(uri: URI): boolean {
|
||||||
|
return uri.scheme === scheme;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function equals(left: URI, right: URI): boolean {
|
||||||
|
return is(left) && is(right) && left.toString() === right.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parent(uri: URI): URI {
|
||||||
|
if (!is(uri)) {
|
||||||
|
throw new Error(
|
||||||
|
`Invalid URI scheme. Expected '${scheme}' got '${uri.scheme}' instead.`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (equals(uri, root)) {
|
||||||
|
return uri;
|
||||||
|
}
|
||||||
|
return toUri(parentPosix(uri.path.toString()));
|
||||||
|
}
|
||||||
|
}
|
||||||
73
arduino-ide-extension/src/browser/create/typings.ts
Normal file
73
arduino-ide-extension/src/browser/create/typings.ts
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
export namespace Create {
|
||||||
|
export interface Sketch {
|
||||||
|
readonly name: string;
|
||||||
|
readonly path: string;
|
||||||
|
readonly modified_at: string;
|
||||||
|
readonly created_at: string;
|
||||||
|
|
||||||
|
readonly secrets?: { name: string; value: string }[];
|
||||||
|
|
||||||
|
readonly id: string;
|
||||||
|
readonly is_public: boolean;
|
||||||
|
readonly board_fqbn: '';
|
||||||
|
readonly board_name: '';
|
||||||
|
readonly board_type: 'serial' | 'network' | 'cloud' | '';
|
||||||
|
readonly href?: string;
|
||||||
|
readonly libraries: string[];
|
||||||
|
readonly tutorials: string[] | null;
|
||||||
|
readonly types: string[] | null;
|
||||||
|
readonly user_id: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ResourceType = 'sketch' | 'folder' | 'file';
|
||||||
|
export const arduino_secrets_file = 'arduino_secrets.h';
|
||||||
|
export const do_not_sync_files = ['.theia', 'sketch.json'];
|
||||||
|
export interface Resource {
|
||||||
|
readonly name: string;
|
||||||
|
/**
|
||||||
|
* Note: this path is **not** the POSIX path we use. It has the leading segments with the `user_id`.
|
||||||
|
*/
|
||||||
|
readonly path: string;
|
||||||
|
readonly type: ResourceType;
|
||||||
|
readonly sketchId?: string;
|
||||||
|
readonly modified_at: string; // As an ISO-8601 formatted string: `YYYY-MM-DDTHH:mm:ss.sssZ`
|
||||||
|
readonly created_at: string; // As an ISO-8601 formatted string: `YYYY-MM-DDTHH:mm:ss.sssZ`
|
||||||
|
readonly children?: number; // For 'sketch' and 'folder' types.
|
||||||
|
readonly size?: number; // For 'sketch' type only.
|
||||||
|
readonly isPublic?: boolean; // For 'sketch' type only.
|
||||||
|
|
||||||
|
readonly mimetype?: string; // For 'file' type.
|
||||||
|
readonly href?: string;
|
||||||
|
}
|
||||||
|
export namespace Resource {
|
||||||
|
export function is(arg: any): arg is Resource {
|
||||||
|
return (
|
||||||
|
!!arg &&
|
||||||
|
'name' in arg &&
|
||||||
|
typeof arg['name'] === 'string' &&
|
||||||
|
'path' in arg &&
|
||||||
|
typeof arg['path'] === 'string' &&
|
||||||
|
'type' in arg &&
|
||||||
|
typeof arg['type'] === 'string' &&
|
||||||
|
'modified_at' in arg &&
|
||||||
|
typeof arg['modified_at'] === 'string' &&
|
||||||
|
(arg['type'] === 'sketch' ||
|
||||||
|
arg['type'] === 'folder' ||
|
||||||
|
arg['type'] === 'file')
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export type RawResource = Omit<Resource, 'sketchId' | 'isPublic'>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class CreateError extends Error {
|
||||||
|
constructor(
|
||||||
|
message: string,
|
||||||
|
readonly status: number,
|
||||||
|
readonly details?: string
|
||||||
|
) {
|
||||||
|
super(message);
|
||||||
|
Object.setPrototypeOf(this, CreateError.prototype);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -28,7 +28,8 @@
|
|||||||
"scope": [
|
"scope": [
|
||||||
"meta.function.c",
|
"meta.function.c",
|
||||||
"entity.name.function",
|
"entity.name.function",
|
||||||
"meta.function-call.c"
|
"meta.function-call.c",
|
||||||
|
"variable.other"
|
||||||
],
|
],
|
||||||
"settings": {
|
"settings": {
|
||||||
"foreground": "#D35400"
|
"foreground": "#D35400"
|
||||||
@@ -42,16 +43,19 @@
|
|||||||
"meta.block.c",
|
"meta.block.c",
|
||||||
"meta.function.c",
|
"meta.function.c",
|
||||||
"entity.name.function.preprocessor.c",
|
"entity.name.function.preprocessor.c",
|
||||||
"meta.preprocessor.macro.c"
|
"meta.preprocessor.macro.c",
|
||||||
|
"variable",
|
||||||
|
"variable.name"
|
||||||
],
|
],
|
||||||
"settings": {
|
"settings": {
|
||||||
"foreground": "#434f54"
|
"foreground": "#434f54"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "strings",
|
"name": "constants",
|
||||||
"scope": [
|
"scope": [
|
||||||
"string.quoted.double"
|
"string.quoted.double",
|
||||||
|
"constant"
|
||||||
],
|
],
|
||||||
"settings": {
|
"settings": {
|
||||||
"foreground": "#005C5F"
|
"foreground": "#005C5F"
|
||||||
@@ -80,22 +84,28 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"colors": {
|
"colors": {
|
||||||
"list.highlightForeground": "#006468",
|
"list.highlightForeground": "#005c5f",
|
||||||
"list.activeSelectionBackground": "#006468",
|
"list.activeSelectionForeground": "#424242",
|
||||||
|
"list.activeSelectionBackground": "#DAE3E3",
|
||||||
|
"list.inactiveSelectionForeground": "#424242",
|
||||||
|
"list.inactiveSelectionBackground": "#DAE3E3",
|
||||||
|
"list.hoverBackground": "#ECF1F1",
|
||||||
|
"progressBar.background": "#005c5f",
|
||||||
"editor.background": "#ffffff",
|
"editor.background": "#ffffff",
|
||||||
"editorCursor.foreground": "#434f54",
|
"editorCursor.foreground": "#434f54",
|
||||||
"editor.foreground": "#434f54",
|
"editor.foreground": "#434f54",
|
||||||
"editorWhitespace.foreground": "#bfbfbf",
|
"editorWhitespace.foreground": "#bfbfbf",
|
||||||
"editor.lineHighlightBackground": "#434f5410",
|
"editor.lineHighlightBackground": "#434f5410",
|
||||||
"editor.selectionBackground": "#ffcb00",
|
"editor.selectionBackground": "#ffcb00",
|
||||||
"focusBorder": "#4db7bb99",
|
"editorWidget.background": "#F7F9F9",
|
||||||
|
"focusBorder": "#7fcbcd99",
|
||||||
"menubar.selectionBackground": "#ffffff",
|
"menubar.selectionBackground": "#ffffff",
|
||||||
"menubar.selectionForeground": "#212121",
|
"menubar.selectionForeground": "#212121",
|
||||||
"menu.selectionBackground": "#dae3e3",
|
"menu.selectionBackground": "#dae3e3",
|
||||||
"menu.selectionForeground": "#212121",
|
"menu.selectionForeground": "#212121",
|
||||||
"editorGroupHeader.tabsBackground": "#f7f9f9",
|
"editorGroupHeader.tabsBackground": "#f7f9f9",
|
||||||
"button.background": "#4db7bb",
|
"button.background": "#7fcbcd",
|
||||||
"titleBar.activeBackground": "#006468",
|
"titleBar.activeBackground": "#005c5f",
|
||||||
"titleBar.activeForeground": "#ffffff",
|
"titleBar.activeForeground": "#ffffff",
|
||||||
"terminal.background": "#000000",
|
"terminal.background": "#000000",
|
||||||
"terminal.foreground": "#e0e0e0",
|
"terminal.foreground": "#e0e0e0",
|
||||||
@@ -103,8 +113,9 @@
|
|||||||
"dropdown.background": "#ececec",
|
"dropdown.background": "#ececec",
|
||||||
"activityBar.background": "#ececec",
|
"activityBar.background": "#ececec",
|
||||||
"activityBar.foreground": "#616161",
|
"activityBar.foreground": "#616161",
|
||||||
"statusBar.background": "#006468",
|
"statusBar.background": "#005c5f",
|
||||||
"secondaryButton.background": "#b5c8c9",
|
"secondaryButton.background": "#b5c8c9",
|
||||||
|
"secondaryButton.foreground": "#ececec",
|
||||||
"secondaryButton.hoverBackground": "#dae3e3",
|
"secondaryButton.hoverBackground": "#dae3e3",
|
||||||
"arduino.branding.primary": "#00979d",
|
"arduino.branding.primary": "#00979d",
|
||||||
"arduino.branding.secondary": "#b5c8c9",
|
"arduino.branding.secondary": "#b5c8c9",
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
import * as React from 'react';
|
||||||
|
|
||||||
|
export const CertificateAddComponent = ({
|
||||||
|
addCertificate,
|
||||||
|
}: {
|
||||||
|
addCertificate: (cert: string) => void;
|
||||||
|
}): React.ReactElement => {
|
||||||
|
const [value, setValue] = React.useState('');
|
||||||
|
|
||||||
|
const handleChange = React.useCallback((event) => {
|
||||||
|
setValue(event.target.value);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form
|
||||||
|
className="certificate-add"
|
||||||
|
onSubmit={(event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopPropagation();
|
||||||
|
addCertificate(value);
|
||||||
|
setValue('');
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<label>
|
||||||
|
<div>
|
||||||
|
{nls.localize(
|
||||||
|
'arduino/certificate/addURL',
|
||||||
|
'Add URL to fetch SSL certificate'
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<input
|
||||||
|
className="theia-input"
|
||||||
|
placeholder={nls.localize(
|
||||||
|
'arduino/certificate/enterURL',
|
||||||
|
'Enter URL'
|
||||||
|
)}
|
||||||
|
type="text"
|
||||||
|
name="add"
|
||||||
|
onChange={handleChange}
|
||||||
|
value={value}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import * as React from 'react';
|
||||||
|
|
||||||
|
export const CertificateListComponent = ({
|
||||||
|
certificates,
|
||||||
|
selectedCerts,
|
||||||
|
setSelectedCerts,
|
||||||
|
openContextMenu,
|
||||||
|
}: {
|
||||||
|
certificates: string[];
|
||||||
|
selectedCerts: string[];
|
||||||
|
setSelectedCerts: React.Dispatch<React.SetStateAction<string[]>>;
|
||||||
|
openContextMenu: (x: number, y: number, cert: string) => void;
|
||||||
|
}): React.ReactElement => {
|
||||||
|
const handleOnChange = (event: any) => {
|
||||||
|
const target = event.target;
|
||||||
|
|
||||||
|
const newSelectedCerts = selectedCerts.filter(
|
||||||
|
(cert) => cert !== target.name
|
||||||
|
);
|
||||||
|
|
||||||
|
if (target.checked) {
|
||||||
|
newSelectedCerts.push(target.name);
|
||||||
|
}
|
||||||
|
|
||||||
|
setSelectedCerts(newSelectedCerts);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleContextMenu = (event: React.MouseEvent, cert: string) => {
|
||||||
|
openContextMenu(event.clientX, event.clientY, cert);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="certificate-list">
|
||||||
|
{certificates.map((certificate, i) => (
|
||||||
|
<label
|
||||||
|
key={i}
|
||||||
|
className="certificate-row"
|
||||||
|
onContextMenu={(e) => handleContextMenu(e, certificate)}
|
||||||
|
>
|
||||||
|
<span className="fl1">{certificate}</span>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
name={certificate}
|
||||||
|
checked={selectedCerts.includes(certificate)}
|
||||||
|
onChange={handleOnChange}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,178 @@
|
|||||||
|
import * as React from 'react';
|
||||||
|
import Tippy from '@tippyjs/react';
|
||||||
|
import { AvailableBoard } from '../../boards/boards-service-provider';
|
||||||
|
import { CertificateListComponent } from './certificate-list';
|
||||||
|
import { SelectBoardComponent } from './select-board-components';
|
||||||
|
import { CertificateAddComponent } from './certificate-add-new';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
|
||||||
|
export const CertificateUploaderComponent = ({
|
||||||
|
availableBoards,
|
||||||
|
certificates,
|
||||||
|
addCertificate,
|
||||||
|
updatableFqbns,
|
||||||
|
uploadCertificates,
|
||||||
|
openContextMenu,
|
||||||
|
}: {
|
||||||
|
availableBoards: AvailableBoard[];
|
||||||
|
certificates: string[];
|
||||||
|
addCertificate: (cert: string) => void;
|
||||||
|
updatableFqbns: string[];
|
||||||
|
uploadCertificates: (
|
||||||
|
fqbn: string,
|
||||||
|
address: string,
|
||||||
|
urls: string[]
|
||||||
|
) => Promise<any>;
|
||||||
|
openContextMenu: (x: number, y: number, cert: string) => void;
|
||||||
|
}): React.ReactElement => {
|
||||||
|
const [installFeedback, setInstallFeedback] = React.useState<
|
||||||
|
'ok' | 'fail' | 'installing' | null
|
||||||
|
>(null);
|
||||||
|
|
||||||
|
const [showAdd, setShowAdd] = React.useState(false);
|
||||||
|
|
||||||
|
const [selectedCerts, setSelectedCerts] = React.useState<string[]>([]);
|
||||||
|
|
||||||
|
const [selectedBoard, setSelectedBoard] =
|
||||||
|
React.useState<AvailableBoard | null>(null);
|
||||||
|
|
||||||
|
const installCertificates = async () => {
|
||||||
|
if (!selectedBoard || !selectedBoard.fqbn || !selectedBoard.port) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setInstallFeedback('installing');
|
||||||
|
|
||||||
|
try {
|
||||||
|
await uploadCertificates(
|
||||||
|
selectedBoard.fqbn,
|
||||||
|
selectedBoard.port.address,
|
||||||
|
selectedCerts
|
||||||
|
);
|
||||||
|
setInstallFeedback('ok');
|
||||||
|
} catch {
|
||||||
|
setInstallFeedback('fail');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const onBoardSelect = React.useCallback(
|
||||||
|
(board: AvailableBoard) => {
|
||||||
|
const newFqbn = (board && board.fqbn) || null;
|
||||||
|
const prevFqbn = (selectedBoard && selectedBoard.fqbn) || null;
|
||||||
|
|
||||||
|
if (newFqbn !== prevFqbn) {
|
||||||
|
setInstallFeedback(null);
|
||||||
|
setSelectedBoard(board);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[selectedBoard]
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div className="dialogSection">
|
||||||
|
<div className="dialogRow">
|
||||||
|
<strong className="fl1">
|
||||||
|
{nls.localize(
|
||||||
|
'arduino/certificate/selectCertificateToUpload',
|
||||||
|
'1. Select certificate to upload'
|
||||||
|
)}
|
||||||
|
</strong>
|
||||||
|
<Tippy
|
||||||
|
content={
|
||||||
|
<CertificateAddComponent
|
||||||
|
addCertificate={(cert) => {
|
||||||
|
addCertificate(cert);
|
||||||
|
setShowAdd(false);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
placement="bottom-end"
|
||||||
|
onClickOutside={() => setShowAdd(false)}
|
||||||
|
visible={showAdd}
|
||||||
|
interactive={true}
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="theia-button primary add-cert-btn"
|
||||||
|
onClick={() => {
|
||||||
|
showAdd ? setShowAdd(false) : setShowAdd(true);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{nls.localize('arduino/certificate/addNew', 'Add New')}{' '}
|
||||||
|
<span className="fa fa-caret-down caret"></span>
|
||||||
|
</button>
|
||||||
|
</Tippy>
|
||||||
|
</div>
|
||||||
|
<div className="dialogRow">
|
||||||
|
<CertificateListComponent
|
||||||
|
certificates={certificates}
|
||||||
|
selectedCerts={selectedCerts}
|
||||||
|
setSelectedCerts={setSelectedCerts}
|
||||||
|
openContextMenu={openContextMenu}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="dialogSection">
|
||||||
|
<div className="dialogRow">
|
||||||
|
<strong>
|
||||||
|
{nls.localize(
|
||||||
|
'arduino/certificate/selectDestinationBoardToUpload',
|
||||||
|
'2. Select destination board and upload certificate'
|
||||||
|
)}
|
||||||
|
</strong>
|
||||||
|
</div>
|
||||||
|
<div className="dialogRow">
|
||||||
|
<div className="fl1">
|
||||||
|
<SelectBoardComponent
|
||||||
|
availableBoards={availableBoards}
|
||||||
|
updatableFqbns={updatableFqbns}
|
||||||
|
onBoardSelect={onBoardSelect}
|
||||||
|
selectedBoard={selectedBoard}
|
||||||
|
busy={installFeedback === 'installing'}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="dialogRow">
|
||||||
|
<div className="upload-status">
|
||||||
|
{installFeedback === 'installing' && (
|
||||||
|
<div className="success">
|
||||||
|
<div className="spinner" />
|
||||||
|
{nls.localize(
|
||||||
|
'arduino/certificate/uploadingCertificates',
|
||||||
|
'Uploading certificates.'
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{installFeedback === 'ok' && (
|
||||||
|
<div className="success">
|
||||||
|
<i className="fa fa-info status-icon" />
|
||||||
|
{nls.localize(
|
||||||
|
'arduino/certificate/certificatesUploaded',
|
||||||
|
'Certificates uploaded.'
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{installFeedback === 'fail' && (
|
||||||
|
<div className="warn">
|
||||||
|
<i className="fa fa-exclamation status-icon" />
|
||||||
|
{nls.localize(
|
||||||
|
'arduino/certificate/uploadFailed',
|
||||||
|
'Upload failed. Please try again.'
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="theia-button primary install-cert-btn"
|
||||||
|
onClick={installCertificates}
|
||||||
|
disabled={selectedCerts.length === 0 || !selectedBoard}
|
||||||
|
>
|
||||||
|
{nls.localize('arduino/certificate/upload', 'Upload')}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,197 @@
|
|||||||
|
import * as React from 'react';
|
||||||
|
import { inject, injectable, postConstruct } from 'inversify';
|
||||||
|
import { DialogProps } from '@theia/core/lib/browser/dialogs';
|
||||||
|
import { AbstractDialog } from '../../theia/dialogs/dialogs';
|
||||||
|
import { Widget } from '@phosphor/widgets';
|
||||||
|
import { Message } from '@phosphor/messaging';
|
||||||
|
import { ReactWidget } from '@theia/core/lib/browser/widgets/react-widget';
|
||||||
|
import {
|
||||||
|
AvailableBoard,
|
||||||
|
BoardsServiceProvider,
|
||||||
|
} from '../../boards/boards-service-provider';
|
||||||
|
import { CertificateUploaderComponent } from './certificate-uploader-component';
|
||||||
|
import { ArduinoPreferences } from '../../arduino-preferences';
|
||||||
|
import {
|
||||||
|
PreferenceScope,
|
||||||
|
PreferenceService,
|
||||||
|
} from '@theia/core/lib/browser/preferences/preference-service';
|
||||||
|
import { CommandRegistry } from '@theia/core/lib/common/command';
|
||||||
|
import { certificateList, sanifyCertString } from './utils';
|
||||||
|
import { ArduinoFirmwareUploader } from '../../../common/protocol/arduino-firmware-uploader';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
|
||||||
|
@injectable()
|
||||||
|
export class UploadCertificateDialogWidget extends ReactWidget {
|
||||||
|
@inject(BoardsServiceProvider)
|
||||||
|
protected readonly boardsServiceClient: BoardsServiceProvider;
|
||||||
|
|
||||||
|
@inject(ArduinoPreferences)
|
||||||
|
protected readonly arduinoPreferences: ArduinoPreferences;
|
||||||
|
|
||||||
|
@inject(PreferenceService)
|
||||||
|
protected readonly preferenceService: PreferenceService;
|
||||||
|
|
||||||
|
@inject(CommandRegistry)
|
||||||
|
protected readonly commandRegistry: CommandRegistry;
|
||||||
|
|
||||||
|
@inject(ArduinoFirmwareUploader)
|
||||||
|
protected readonly arduinoFirmwareUploader: ArduinoFirmwareUploader;
|
||||||
|
|
||||||
|
protected certificates: string[] = [];
|
||||||
|
protected updatableFqbns: string[] = [];
|
||||||
|
protected availableBoards: AvailableBoard[] = [];
|
||||||
|
|
||||||
|
public busyCallback = (busy: boolean) => {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
|
||||||
|
@postConstruct()
|
||||||
|
protected init(): void {
|
||||||
|
this.arduinoPreferences.ready.then(() => {
|
||||||
|
this.certificates = certificateList(
|
||||||
|
this.arduinoPreferences.get('arduino.board.certificates')
|
||||||
|
);
|
||||||
|
});
|
||||||
|
this.arduinoPreferences.onPreferenceChanged((event) => {
|
||||||
|
if (
|
||||||
|
event.preferenceName === 'arduino.board.certificates' &&
|
||||||
|
event.newValue !== event.oldValue
|
||||||
|
) {
|
||||||
|
this.certificates = certificateList(event.newValue);
|
||||||
|
this.update();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
this.arduinoFirmwareUploader.updatableBoards().then((fqbns) => {
|
||||||
|
this.updatableFqbns = fqbns;
|
||||||
|
this.update();
|
||||||
|
});
|
||||||
|
|
||||||
|
this.boardsServiceClient.onAvailableBoardsChanged((availableBoards) => {
|
||||||
|
this.availableBoards = availableBoards;
|
||||||
|
this.update();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private addCertificate(certificate: string) {
|
||||||
|
const certString = sanifyCertString(certificate);
|
||||||
|
|
||||||
|
if (certString.length > 0) {
|
||||||
|
this.certificates.push(sanifyCertString(certificate));
|
||||||
|
}
|
||||||
|
|
||||||
|
this.preferenceService.set(
|
||||||
|
'arduino.board.certificates',
|
||||||
|
this.certificates.join(','),
|
||||||
|
PreferenceScope.User
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected openContextMenu(x: number, y: number, cert: string): void {
|
||||||
|
this.commandRegistry.executeCommand(
|
||||||
|
'arduino-certificate-open-context',
|
||||||
|
Object.assign({}, { x, y, cert })
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected uploadCertificates(
|
||||||
|
fqbn: string,
|
||||||
|
address: string,
|
||||||
|
urls: string[]
|
||||||
|
): Promise<any> {
|
||||||
|
this.busyCallback(true);
|
||||||
|
return this.commandRegistry
|
||||||
|
.executeCommand('arduino-certificate-upload', {
|
||||||
|
fqbn,
|
||||||
|
address,
|
||||||
|
urls,
|
||||||
|
})
|
||||||
|
.finally(() => this.busyCallback(false));
|
||||||
|
}
|
||||||
|
|
||||||
|
protected render(): React.ReactNode {
|
||||||
|
return (
|
||||||
|
<CertificateUploaderComponent
|
||||||
|
availableBoards={this.availableBoards}
|
||||||
|
certificates={this.certificates}
|
||||||
|
updatableFqbns={this.updatableFqbns}
|
||||||
|
addCertificate={this.addCertificate.bind(this)}
|
||||||
|
uploadCertificates={this.uploadCertificates.bind(this)}
|
||||||
|
openContextMenu={this.openContextMenu.bind(this)}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@injectable()
|
||||||
|
export class UploadCertificateDialogProps extends DialogProps {}
|
||||||
|
|
||||||
|
@injectable()
|
||||||
|
export class UploadCertificateDialog extends AbstractDialog<void> {
|
||||||
|
@inject(UploadCertificateDialogWidget)
|
||||||
|
protected readonly widget: UploadCertificateDialogWidget;
|
||||||
|
|
||||||
|
private busy = false;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
@inject(UploadCertificateDialogProps)
|
||||||
|
protected readonly props: UploadCertificateDialogProps
|
||||||
|
) {
|
||||||
|
super({
|
||||||
|
title: nls.localize(
|
||||||
|
'arduino/certificate/uploadRootCertificates',
|
||||||
|
'Upload SSL Root Certificates'
|
||||||
|
),
|
||||||
|
});
|
||||||
|
this.contentNode.classList.add('certificate-uploader-dialog');
|
||||||
|
this.acceptButton = undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
get value(): void {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected onAfterAttach(msg: Message): void {
|
||||||
|
if (this.widget.isAttached) {
|
||||||
|
Widget.detach(this.widget);
|
||||||
|
}
|
||||||
|
Widget.attach(this.widget, this.contentNode);
|
||||||
|
this.widget.busyCallback = this.busyCallback.bind(this);
|
||||||
|
super.onAfterAttach(msg);
|
||||||
|
this.update();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected onUpdateRequest(msg: Message): void {
|
||||||
|
super.onUpdateRequest(msg);
|
||||||
|
this.widget.update();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected onActivateRequest(msg: Message): void {
|
||||||
|
super.onActivateRequest(msg);
|
||||||
|
this.widget.activate();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected handleEnter(event: KeyboardEvent): boolean | void {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
close(): void {
|
||||||
|
if (this.busy) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
super.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
busyCallback(busy: boolean): void {
|
||||||
|
this.busy = busy;
|
||||||
|
if (busy) {
|
||||||
|
this.closeCrossNode.classList.add('disabled');
|
||||||
|
} else {
|
||||||
|
this.closeCrossNode.classList.remove('disabled');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
import * as React from 'react';
|
||||||
|
import { AvailableBoard } from '../../boards/boards-service-provider';
|
||||||
|
import { ArduinoSelect } from '../../widgets/arduino-select';
|
||||||
|
|
||||||
|
type BoardOption = { value: string; label: string };
|
||||||
|
|
||||||
|
export const SelectBoardComponent = ({
|
||||||
|
availableBoards,
|
||||||
|
updatableFqbns,
|
||||||
|
onBoardSelect,
|
||||||
|
selectedBoard,
|
||||||
|
busy,
|
||||||
|
}: {
|
||||||
|
availableBoards: AvailableBoard[];
|
||||||
|
updatableFqbns: string[];
|
||||||
|
onBoardSelect: (board: AvailableBoard | null) => void;
|
||||||
|
selectedBoard: AvailableBoard | null;
|
||||||
|
busy: boolean;
|
||||||
|
}): React.ReactElement => {
|
||||||
|
const [selectOptions, setSelectOptions] = React.useState<BoardOption[]>([]);
|
||||||
|
|
||||||
|
const [selectBoardPlaceholder, setSelectBoardPlaceholder] =
|
||||||
|
React.useState('');
|
||||||
|
|
||||||
|
const selectOption = React.useCallback(
|
||||||
|
(boardOpt: BoardOption) => {
|
||||||
|
onBoardSelect(
|
||||||
|
(boardOpt &&
|
||||||
|
availableBoards.find((board) => board.fqbn === boardOpt.value)) ||
|
||||||
|
null
|
||||||
|
);
|
||||||
|
},
|
||||||
|
[availableBoards, onBoardSelect]
|
||||||
|
);
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
// if there is activity going on, skip updating the boards (avoid flickering)
|
||||||
|
if (busy) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let placeholderTxt = nls.localize(
|
||||||
|
'arduino/certificate/selectBoard',
|
||||||
|
'Select a board...'
|
||||||
|
);
|
||||||
|
let selBoard = -1;
|
||||||
|
const updatableBoards = availableBoards.filter(
|
||||||
|
(board) => board.port && board.fqbn && updatableFqbns.includes(board.fqbn)
|
||||||
|
);
|
||||||
|
const boardsList: BoardOption[] = updatableBoards.map((board, i) => {
|
||||||
|
if (board.selected) {
|
||||||
|
selBoard = i;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
label: nls.localize(
|
||||||
|
'arduino/certificate/boardAtPort',
|
||||||
|
'{0} at {1}',
|
||||||
|
board.name,
|
||||||
|
board.port?.address ?? ''
|
||||||
|
),
|
||||||
|
value: board.fqbn || '',
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
if (boardsList.length === 0) {
|
||||||
|
placeholderTxt = nls.localize(
|
||||||
|
'arduino/certificate/noSupportedBoardConnected',
|
||||||
|
'No supported board connected'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
setSelectBoardPlaceholder(placeholderTxt);
|
||||||
|
setSelectOptions(boardsList);
|
||||||
|
|
||||||
|
if (selectedBoard) {
|
||||||
|
selBoard = boardsList
|
||||||
|
.map((boardOpt) => boardOpt.value)
|
||||||
|
.indexOf(selectedBoard.fqbn || '');
|
||||||
|
}
|
||||||
|
|
||||||
|
selectOption(boardsList[selBoard] || null);
|
||||||
|
}, [busy, availableBoards, selectOption, updatableFqbns, selectedBoard]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ArduinoSelect
|
||||||
|
id="board-select"
|
||||||
|
menuPosition="fixed"
|
||||||
|
isDisabled={selectOptions.length === 0 || busy}
|
||||||
|
placeholder={selectBoardPlaceholder}
|
||||||
|
options={selectOptions}
|
||||||
|
value={
|
||||||
|
(selectedBoard && {
|
||||||
|
value: selectedBoard.fqbn,
|
||||||
|
label: nls.localize(
|
||||||
|
'arduino/certificate/boardAtPort',
|
||||||
|
'{0} at {1}',
|
||||||
|
selectedBoard.name,
|
||||||
|
selectedBoard.port?.address ?? ''
|
||||||
|
),
|
||||||
|
}) ||
|
||||||
|
null
|
||||||
|
}
|
||||||
|
tabSelectsValue={false}
|
||||||
|
onChange={selectOption}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
export const arduinoCert = 'arduino.cc:443';
|
||||||
|
|
||||||
|
export function sanifyCertString(cert: string): string {
|
||||||
|
const regex = /^(?:.*:\/\/)*(\S+\.+[^:]*):*(\d*)*$/gm;
|
||||||
|
|
||||||
|
const m = regex.exec(cert);
|
||||||
|
|
||||||
|
if (!m) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
const domain = m[1] || '';
|
||||||
|
const port = m[2] || '443';
|
||||||
|
|
||||||
|
if (domain.length === 0 || port.length === 0) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
return `${domain}:${port}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function certificateList(certificates: string): string[] {
|
||||||
|
let certs = certificates
|
||||||
|
.split(',')
|
||||||
|
.map((cert) => sanifyCertString(cert.trim()))
|
||||||
|
.filter((cert) => {
|
||||||
|
// remove empty certificates
|
||||||
|
if (!cert || cert.length === 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
|
||||||
|
// add arduino certificate at the top of the list
|
||||||
|
certs = certs.filter((cert) => cert !== arduinoCert);
|
||||||
|
certs.unshift(arduinoCert);
|
||||||
|
return certs;
|
||||||
|
}
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
import * as React from 'react';
|
||||||
|
import { inject, injectable } from 'inversify';
|
||||||
|
import { Widget } from '@phosphor/widgets';
|
||||||
|
import { Message } from '@phosphor/messaging';
|
||||||
|
import { clipboard } from 'electron';
|
||||||
|
import { ReactWidget, DialogProps } from '@theia/core/lib/browser';
|
||||||
|
import { AbstractDialog } from '../theia/dialogs/dialogs';
|
||||||
|
import { CreateApi } from '../create/create-api';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
|
||||||
|
const RadioButton = (props: {
|
||||||
|
id: string;
|
||||||
|
changed: (evt: React.BaseSyntheticEvent) => void;
|
||||||
|
value: string;
|
||||||
|
isSelected: boolean;
|
||||||
|
isDisabled: boolean;
|
||||||
|
label: string;
|
||||||
|
}) => {
|
||||||
|
return (
|
||||||
|
<p className="RadioButton">
|
||||||
|
<input
|
||||||
|
id={props.id}
|
||||||
|
onChange={props.changed}
|
||||||
|
value={props.value}
|
||||||
|
type="radio"
|
||||||
|
checked={props.isSelected}
|
||||||
|
disabled={props.isDisabled}
|
||||||
|
/>
|
||||||
|
<label htmlFor={props.id}>{props.label}</label>
|
||||||
|
</p>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const ShareSketchComponent = ({
|
||||||
|
treeNode,
|
||||||
|
createApi,
|
||||||
|
domain = 'https://create.arduino.cc',
|
||||||
|
}: {
|
||||||
|
treeNode: any;
|
||||||
|
createApi: CreateApi;
|
||||||
|
domain?: string;
|
||||||
|
}): React.ReactElement => {
|
||||||
|
const [loading, setloading] = React.useState<boolean>(false);
|
||||||
|
|
||||||
|
const radioChangeHandler = async (event: React.BaseSyntheticEvent) => {
|
||||||
|
setloading(true);
|
||||||
|
const sketch = await createApi.editSketch({
|
||||||
|
id: treeNode.sketchId,
|
||||||
|
params: {
|
||||||
|
is_public: event.target.value === 'private' ? false : true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
// setPublicVisibility(sketch.is_public);
|
||||||
|
treeNode.isPublic = sketch.is_public;
|
||||||
|
setloading(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
const sketchLink = `${domain}/editor/_/${treeNode.sketchId}/preview`;
|
||||||
|
const embedLink = `<iframe src="${sketchLink}?embed" style="height:510px;width:100%;margin:10px 0" frameborder=0></iframe>`;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div id="widget-container arduino-sharesketch-dialog">
|
||||||
|
<p>
|
||||||
|
{nls.localize(
|
||||||
|
'arduino/cloud/chooseSketchVisibility',
|
||||||
|
'Choose visibility of your Sketch:'
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
<RadioButton
|
||||||
|
changed={radioChangeHandler}
|
||||||
|
id="1"
|
||||||
|
isSelected={treeNode.isPublic === false}
|
||||||
|
label={nls.localize(
|
||||||
|
'arduino/cloud/privateVisibility',
|
||||||
|
'Private. Only you can view the Sketch.'
|
||||||
|
)}
|
||||||
|
value="private"
|
||||||
|
isDisabled={loading}
|
||||||
|
/>
|
||||||
|
<RadioButton
|
||||||
|
changed={radioChangeHandler}
|
||||||
|
id="2"
|
||||||
|
isSelected={treeNode.isPublic === true}
|
||||||
|
label={nls.localize(
|
||||||
|
'arduino/cloud/publicVisibility',
|
||||||
|
'Public. Anyone with the link can view the Sketch.'
|
||||||
|
)}
|
||||||
|
value="public"
|
||||||
|
isDisabled={loading}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{treeNode.isPublic && (
|
||||||
|
<div>
|
||||||
|
<p>{nls.localize('arduino/cloud/link', 'Link:')}</p>
|
||||||
|
<div className="sketch-link">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
readOnly
|
||||||
|
value={sketchLink}
|
||||||
|
className="theia-input"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
onClick={() => clipboard.writeText(sketchLink)}
|
||||||
|
value="copy"
|
||||||
|
className="theia-button secondary"
|
||||||
|
>
|
||||||
|
{nls.localize('vscode/textInputActions/copy', 'Copy')}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<p>{nls.localize('arduino/cloud/embed', 'Embed:')}</p>
|
||||||
|
<div className="sketch-link-embed">
|
||||||
|
<textarea
|
||||||
|
readOnly
|
||||||
|
value={embedLink}
|
||||||
|
className="theia-input stretch"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
@injectable()
|
||||||
|
export class ShareSketchWidget extends ReactWidget {
|
||||||
|
constructor(private treeNode: any, private createApi: CreateApi) {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected render(): React.ReactNode {
|
||||||
|
return (
|
||||||
|
<ShareSketchComponent
|
||||||
|
treeNode={this.treeNode}
|
||||||
|
createApi={this.createApi}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@injectable()
|
||||||
|
export class ShareSketchDialogProps extends DialogProps {
|
||||||
|
readonly node: any;
|
||||||
|
readonly createApi: CreateApi;
|
||||||
|
}
|
||||||
|
|
||||||
|
@injectable()
|
||||||
|
export class ShareSketchDialog extends AbstractDialog<void> {
|
||||||
|
protected widget: ShareSketchWidget;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
@inject(ShareSketchDialogProps)
|
||||||
|
protected readonly props: ShareSketchDialogProps
|
||||||
|
) {
|
||||||
|
super({ title: props.title });
|
||||||
|
this.contentNode.classList.add('arduino-share-sketch-dialog');
|
||||||
|
this.widget = new ShareSketchWidget(props.node, props.createApi);
|
||||||
|
}
|
||||||
|
|
||||||
|
get value(): void {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
protected onAfterAttach(msg: Message): void {
|
||||||
|
if (this.widget.isAttached) {
|
||||||
|
Widget.detach(this.widget);
|
||||||
|
}
|
||||||
|
Widget.attach(this.widget, this.contentNode);
|
||||||
|
super.onAfterAttach(msg);
|
||||||
|
this.update();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected onUpdateRequest(msg: Message): void {
|
||||||
|
super.onUpdateRequest(msg);
|
||||||
|
this.widget.update();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected onActivateRequest(msg: Message): void {
|
||||||
|
super.onActivateRequest(msg);
|
||||||
|
this.widget.activate();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
import { inject, injectable } from 'inversify';
|
||||||
|
import { Widget } from '@phosphor/widgets';
|
||||||
|
import { CancellationTokenSource } from '@theia/core/lib/common/cancellation';
|
||||||
|
import {
|
||||||
|
ConfirmDialog,
|
||||||
|
ConfirmDialogProps,
|
||||||
|
DialogError,
|
||||||
|
} from '@theia/core/lib/browser/dialogs';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
|
||||||
|
@injectable()
|
||||||
|
export class DoNotAskAgainDialogProps extends ConfirmDialogProps {
|
||||||
|
readonly onAccept: () => Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
@injectable()
|
||||||
|
export class DoNotAskAgainConfirmDialog extends ConfirmDialog {
|
||||||
|
protected readonly doNotAskAgainCheckbox: HTMLInputElement;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
@inject(DoNotAskAgainDialogProps)
|
||||||
|
protected readonly props: DoNotAskAgainDialogProps
|
||||||
|
) {
|
||||||
|
super(props);
|
||||||
|
this.controlPanel.removeChild(this.errorMessageNode);
|
||||||
|
const doNotAskAgainNode = document.createElement('div');
|
||||||
|
doNotAskAgainNode.setAttribute('style', 'flex: 2');
|
||||||
|
this.controlPanel.insertBefore(
|
||||||
|
doNotAskAgainNode,
|
||||||
|
this.controlPanel.firstChild
|
||||||
|
);
|
||||||
|
const doNotAskAgainLabel = document.createElement('label');
|
||||||
|
doNotAskAgainLabel.classList.add('flex-line');
|
||||||
|
doNotAskAgainNode.appendChild(doNotAskAgainLabel);
|
||||||
|
doNotAskAgainLabel.textContent = nls.localize(
|
||||||
|
'arduino/dialog/dontAskAgain',
|
||||||
|
"Don't ask again"
|
||||||
|
);
|
||||||
|
this.doNotAskAgainCheckbox = document.createElement('input');
|
||||||
|
this.doNotAskAgainCheckbox.setAttribute('align-self', 'center');
|
||||||
|
doNotAskAgainLabel.appendChild(this.doNotAskAgainCheckbox);
|
||||||
|
this.doNotAskAgainCheckbox.type = 'checkbox';
|
||||||
|
}
|
||||||
|
|
||||||
|
protected async accept(): Promise<void> {
|
||||||
|
if (!this.resolve) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.acceptCancellationSource.cancel();
|
||||||
|
this.acceptCancellationSource = new CancellationTokenSource();
|
||||||
|
const token = this.acceptCancellationSource.token;
|
||||||
|
const value = this.value;
|
||||||
|
const error = await this.isValid(value, 'open');
|
||||||
|
if (token.isCancellationRequested) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!DialogError.getResult(error)) {
|
||||||
|
this.setErrorMessage(error);
|
||||||
|
} else {
|
||||||
|
if (this.doNotAskAgainCheckbox.checked) {
|
||||||
|
await this.props.onAccept();
|
||||||
|
}
|
||||||
|
this.resolve(value);
|
||||||
|
Widget.detach(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected setErrorMessage(error: DialogError): void {
|
||||||
|
if (this.acceptButton) {
|
||||||
|
this.acceptButton.disabled = !DialogError.getResult(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,222 @@
|
|||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
import * as React from 'react';
|
||||||
|
import {
|
||||||
|
ArduinoFirmwareUploader,
|
||||||
|
FirmwareInfo,
|
||||||
|
} from '../../../common/protocol/arduino-firmware-uploader';
|
||||||
|
import { AvailableBoard } from '../../boards/boards-service-provider';
|
||||||
|
import { ArduinoSelect } from '../../widgets/arduino-select';
|
||||||
|
import { SelectBoardComponent } from '../certificate-uploader/select-board-components';
|
||||||
|
|
||||||
|
type FirmwareOption = { value: string; label: string };
|
||||||
|
|
||||||
|
export const FirmwareUploaderComponent = ({
|
||||||
|
availableBoards,
|
||||||
|
firmwareUploader,
|
||||||
|
updatableFqbns,
|
||||||
|
flashFirmware,
|
||||||
|
isOpen,
|
||||||
|
}: {
|
||||||
|
availableBoards: AvailableBoard[];
|
||||||
|
firmwareUploader: ArduinoFirmwareUploader;
|
||||||
|
updatableFqbns: string[];
|
||||||
|
flashFirmware: (firmware: FirmwareInfo, port: string) => Promise<any>;
|
||||||
|
isOpen: any;
|
||||||
|
}): React.ReactElement => {
|
||||||
|
// boolean states for buttons
|
||||||
|
const [firmwaresFetching, setFirmwaresFetching] = React.useState(false);
|
||||||
|
|
||||||
|
const [installFeedback, setInstallFeedback] = React.useState<
|
||||||
|
'ok' | 'fail' | 'installing' | null
|
||||||
|
>(null);
|
||||||
|
|
||||||
|
const [selectedBoard, setSelectedBoard] =
|
||||||
|
React.useState<AvailableBoard | null>(null);
|
||||||
|
|
||||||
|
const [availableFirmwares, setAvailableFirmwares] = React.useState<
|
||||||
|
FirmwareInfo[]
|
||||||
|
>([]);
|
||||||
|
React.useEffect(() => {
|
||||||
|
setAvailableFirmwares([]);
|
||||||
|
}, [isOpen]);
|
||||||
|
const [selectedFirmware, setSelectedFirmware] =
|
||||||
|
React.useState<FirmwareOption | null>(null);
|
||||||
|
|
||||||
|
const [firmwareOptions, setFirmwareOptions] = React.useState<
|
||||||
|
FirmwareOption[]
|
||||||
|
>([]);
|
||||||
|
|
||||||
|
const fetchFirmwares = React.useCallback(async () => {
|
||||||
|
setInstallFeedback(null);
|
||||||
|
setFirmwaresFetching(true);
|
||||||
|
if (!selectedBoard) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// fetch the firmwares for the selected board
|
||||||
|
const firmwaresForFqbn = await firmwareUploader.availableFirmwares(
|
||||||
|
selectedBoard.fqbn || ''
|
||||||
|
);
|
||||||
|
setAvailableFirmwares(firmwaresForFqbn);
|
||||||
|
|
||||||
|
const firmwaresOpts = firmwaresForFqbn.map((f) => ({
|
||||||
|
label: f.firmware_version,
|
||||||
|
value: f.firmware_version,
|
||||||
|
}));
|
||||||
|
|
||||||
|
setFirmwareOptions(firmwaresOpts);
|
||||||
|
|
||||||
|
if (firmwaresForFqbn.length > 0) setSelectedFirmware(firmwaresOpts[0]);
|
||||||
|
setFirmwaresFetching(false);
|
||||||
|
}, [firmwareUploader, selectedBoard]);
|
||||||
|
|
||||||
|
const installFirmware = React.useCallback(async () => {
|
||||||
|
setInstallFeedback('installing');
|
||||||
|
|
||||||
|
const firmwareToFlash = availableFirmwares.find(
|
||||||
|
(firmware) => firmware.firmware_version === selectedFirmware?.value
|
||||||
|
);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const installStatus =
|
||||||
|
!!firmwareToFlash &&
|
||||||
|
!!selectedBoard?.port &&
|
||||||
|
(await flashFirmware(firmwareToFlash, selectedBoard?.port.address));
|
||||||
|
|
||||||
|
setInstallFeedback((installStatus && 'ok') || 'fail');
|
||||||
|
} catch {
|
||||||
|
setInstallFeedback('fail');
|
||||||
|
}
|
||||||
|
}, [firmwareUploader, selectedBoard, selectedFirmware, availableFirmwares]);
|
||||||
|
|
||||||
|
const onBoardSelect = React.useCallback(
|
||||||
|
(board: AvailableBoard) => {
|
||||||
|
const newFqbn = (board && board.fqbn) || null;
|
||||||
|
const prevFqbn = (selectedBoard && selectedBoard.fqbn) || null;
|
||||||
|
|
||||||
|
if (newFqbn !== prevFqbn) {
|
||||||
|
setInstallFeedback(null);
|
||||||
|
setAvailableFirmwares([]);
|
||||||
|
setSelectedBoard(board);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[selectedBoard]
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div className="dialogSection">
|
||||||
|
<div className="dialogRow">
|
||||||
|
<label htmlFor="board-select">
|
||||||
|
{nls.localize('arduino/firmware/selectBoard', 'Select Board')}
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div className="dialogRow">
|
||||||
|
<div className="fl1">
|
||||||
|
<SelectBoardComponent
|
||||||
|
availableBoards={availableBoards}
|
||||||
|
updatableFqbns={updatableFqbns}
|
||||||
|
onBoardSelect={onBoardSelect}
|
||||||
|
selectedBoard={selectedBoard}
|
||||||
|
busy={installFeedback === 'installing'}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="theia-button secondary"
|
||||||
|
disabled={
|
||||||
|
selectedBoard === null ||
|
||||||
|
firmwaresFetching ||
|
||||||
|
installFeedback === 'installing'
|
||||||
|
}
|
||||||
|
onClick={fetchFirmwares}
|
||||||
|
>
|
||||||
|
{nls.localize('arduino/firmware/checkUpdates', 'Check Updates')}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{availableFirmwares.length > 0 && (
|
||||||
|
<>
|
||||||
|
<div className="dialogSection">
|
||||||
|
<div className="dialogRow">
|
||||||
|
<label htmlFor="firmware-select" className="fl1">
|
||||||
|
{nls.localize(
|
||||||
|
'arduino/firmware/selectVersion',
|
||||||
|
'Select firmware version'
|
||||||
|
)}
|
||||||
|
</label>
|
||||||
|
<ArduinoSelect
|
||||||
|
id="firmware-select"
|
||||||
|
menuPosition="fixed"
|
||||||
|
isDisabled={
|
||||||
|
!selectedBoard ||
|
||||||
|
firmwaresFetching ||
|
||||||
|
installFeedback === 'installing'
|
||||||
|
}
|
||||||
|
options={firmwareOptions}
|
||||||
|
value={selectedFirmware}
|
||||||
|
tabSelectsValue={false}
|
||||||
|
onChange={(value) => {
|
||||||
|
if (value) {
|
||||||
|
setInstallFeedback(null);
|
||||||
|
setSelectedFirmware(value);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="theia-button primary"
|
||||||
|
disabled={
|
||||||
|
selectedFirmware === null ||
|
||||||
|
firmwaresFetching ||
|
||||||
|
installFeedback === 'installing'
|
||||||
|
}
|
||||||
|
onClick={installFirmware}
|
||||||
|
>
|
||||||
|
{nls.localize('arduino/firmware/install', 'Install')}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="dialogSection">
|
||||||
|
{installFeedback === null && (
|
||||||
|
<div className="dialogRow warn">
|
||||||
|
<i className="fa fa-exclamation status-icon" />
|
||||||
|
{nls.localize(
|
||||||
|
'arduino/firmware/overwriteSketch',
|
||||||
|
'Installation will overwrite the Sketch on the board.'
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{installFeedback === 'installing' && (
|
||||||
|
<div className="dialogRow success">
|
||||||
|
<div className="spinner" />
|
||||||
|
{nls.localize(
|
||||||
|
'arduino/firmware/installingFirmware',
|
||||||
|
'Installing firmware.'
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{installFeedback === 'ok' && (
|
||||||
|
<div className="dialogRow success">
|
||||||
|
<i className="fa fa-info status-icon" />
|
||||||
|
{nls.localize(
|
||||||
|
'arduino/firmware/successfullyInstalled',
|
||||||
|
'Firmware successfully installed.'
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{installFeedback === 'fail' && (
|
||||||
|
<div className="dialogRow warn">
|
||||||
|
<i className="fa fa-exclamation status-icon" />
|
||||||
|
{nls.localize(
|
||||||
|
'arduino/firmware/failedInstall',
|
||||||
|
'Installation failed. Please try again.'
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
import * as React from 'react';
|
||||||
|
import { inject, injectable, postConstruct } from 'inversify';
|
||||||
|
import { DialogProps } from '@theia/core/lib/browser/dialogs';
|
||||||
|
import { AbstractDialog } from '../../theia/dialogs/dialogs';
|
||||||
|
import { Widget } from '@phosphor/widgets';
|
||||||
|
import { Message } from '@phosphor/messaging';
|
||||||
|
import { ReactWidget } from '@theia/core/lib/browser/widgets/react-widget';
|
||||||
|
import {
|
||||||
|
AvailableBoard,
|
||||||
|
BoardsServiceProvider,
|
||||||
|
} from '../../boards/boards-service-provider';
|
||||||
|
import {
|
||||||
|
ArduinoFirmwareUploader,
|
||||||
|
FirmwareInfo,
|
||||||
|
} from '../../../common/protocol/arduino-firmware-uploader';
|
||||||
|
import { FirmwareUploaderComponent } from './firmware-uploader-component';
|
||||||
|
import { UploadFirmware } from '../../contributions/upload-firmware';
|
||||||
|
|
||||||
|
@injectable()
|
||||||
|
export class UploadFirmwareDialogWidget extends ReactWidget {
|
||||||
|
@inject(BoardsServiceProvider)
|
||||||
|
protected readonly boardsServiceClient: BoardsServiceProvider;
|
||||||
|
|
||||||
|
@inject(ArduinoFirmwareUploader)
|
||||||
|
protected readonly arduinoFirmwareUploader: ArduinoFirmwareUploader;
|
||||||
|
|
||||||
|
protected updatableFqbns: string[] = [];
|
||||||
|
protected availableBoards: AvailableBoard[] = [];
|
||||||
|
protected isOpen = new Object();
|
||||||
|
|
||||||
|
public busyCallback = (busy: boolean) => {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
|
||||||
|
@postConstruct()
|
||||||
|
protected init(): void {
|
||||||
|
this.arduinoFirmwareUploader.updatableBoards().then((fqbns) => {
|
||||||
|
this.updatableFqbns = fqbns;
|
||||||
|
this.update();
|
||||||
|
});
|
||||||
|
|
||||||
|
this.boardsServiceClient.onAvailableBoardsChanged((availableBoards) => {
|
||||||
|
this.availableBoards = availableBoards;
|
||||||
|
this.update();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
protected flashFirmware(firmware: FirmwareInfo, port: string): Promise<any> {
|
||||||
|
this.busyCallback(true);
|
||||||
|
return this.arduinoFirmwareUploader
|
||||||
|
.flash(firmware, port)
|
||||||
|
.finally(() => this.busyCallback(false));
|
||||||
|
}
|
||||||
|
|
||||||
|
onCloseRequest(msg: Message): void {
|
||||||
|
super.onCloseRequest(msg);
|
||||||
|
this.isOpen = new Object();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected render(): React.ReactNode {
|
||||||
|
return (
|
||||||
|
<form>
|
||||||
|
<FirmwareUploaderComponent
|
||||||
|
availableBoards={this.availableBoards}
|
||||||
|
firmwareUploader={this.arduinoFirmwareUploader}
|
||||||
|
flashFirmware={this.flashFirmware.bind(this)}
|
||||||
|
updatableFqbns={this.updatableFqbns}
|
||||||
|
isOpen={this.isOpen}
|
||||||
|
/>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@injectable()
|
||||||
|
export class UploadFirmwareDialogProps extends DialogProps {}
|
||||||
|
|
||||||
|
@injectable()
|
||||||
|
export class UploadFirmwareDialog extends AbstractDialog<void> {
|
||||||
|
@inject(UploadFirmwareDialogWidget)
|
||||||
|
protected readonly widget: UploadFirmwareDialogWidget;
|
||||||
|
|
||||||
|
private busy = false;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
@inject(UploadFirmwareDialogProps)
|
||||||
|
protected readonly props: UploadFirmwareDialogProps
|
||||||
|
) {
|
||||||
|
super({ title: UploadFirmware.Commands.OPEN.label || '' });
|
||||||
|
this.contentNode.classList.add('firmware-uploader-dialog');
|
||||||
|
this.acceptButton = undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
get value(): void {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected onAfterAttach(msg: Message): void {
|
||||||
|
if (this.widget.isAttached) {
|
||||||
|
Widget.detach(this.widget);
|
||||||
|
}
|
||||||
|
Widget.attach(this.widget, this.contentNode);
|
||||||
|
this.widget.busyCallback = this.busyCallback.bind(this);
|
||||||
|
super.onAfterAttach(msg);
|
||||||
|
this.update();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected onUpdateRequest(msg: Message): void {
|
||||||
|
super.onUpdateRequest(msg);
|
||||||
|
this.widget.update();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected onActivateRequest(msg: Message): void {
|
||||||
|
super.onActivateRequest(msg);
|
||||||
|
this.widget.activate();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected handleEnter(event: KeyboardEvent): boolean | void {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
close(): void {
|
||||||
|
if (this.busy) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.widget.close();
|
||||||
|
super.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
busyCallback(busy: boolean): void {
|
||||||
|
this.busy = busy;
|
||||||
|
if (busy) {
|
||||||
|
this.closeCrossNode.classList.add('disabled');
|
||||||
|
} else {
|
||||||
|
this.closeCrossNode.classList.remove('disabled');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,210 @@
|
|||||||
|
import { WindowService } from '@theia/core/lib/browser/window/window-service';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
import { shell } from 'electron';
|
||||||
|
import * as React from 'react';
|
||||||
|
import * as ReactDOM from 'react-dom';
|
||||||
|
import ReactMarkdown from 'react-markdown';
|
||||||
|
import { ProgressInfo, UpdateInfo } from '../../../common/protocol/ide-updater';
|
||||||
|
import ProgressBar from '../../components/ProgressBar';
|
||||||
|
|
||||||
|
export type IDEUpdaterComponentProps = {
|
||||||
|
updateInfo: UpdateInfo;
|
||||||
|
windowService: WindowService;
|
||||||
|
downloadFinished?: boolean;
|
||||||
|
downloadStarted?: boolean;
|
||||||
|
progress?: ProgressInfo;
|
||||||
|
error?: Error;
|
||||||
|
onDownload: () => void;
|
||||||
|
onClose: () => void;
|
||||||
|
onSkipVersion: () => void;
|
||||||
|
onCloseAndInstall: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const IDEUpdaterComponent = ({
|
||||||
|
updateInfo: { version, releaseNotes },
|
||||||
|
downloadStarted = false,
|
||||||
|
downloadFinished = false,
|
||||||
|
windowService,
|
||||||
|
progress,
|
||||||
|
error,
|
||||||
|
onDownload,
|
||||||
|
onClose,
|
||||||
|
onSkipVersion,
|
||||||
|
onCloseAndInstall,
|
||||||
|
}: IDEUpdaterComponentProps): React.ReactElement => {
|
||||||
|
const changelogDivRef = React.useRef() as React.MutableRefObject<
|
||||||
|
HTMLDivElement
|
||||||
|
>;
|
||||||
|
React.useEffect(() => {
|
||||||
|
if (!!releaseNotes) {
|
||||||
|
let changelog: string;
|
||||||
|
if (typeof releaseNotes === 'string') changelog = releaseNotes;
|
||||||
|
else
|
||||||
|
changelog = releaseNotes.reduce((acc, item) => {
|
||||||
|
return item.note ? (acc += `${item.note}\n\n`) : acc;
|
||||||
|
}, '');
|
||||||
|
ReactDOM.render(
|
||||||
|
<ReactMarkdown
|
||||||
|
components={{
|
||||||
|
a: ({ href, children, ...props }) => (
|
||||||
|
<a onClick={() => href && shell.openExternal(href)} {...props}>
|
||||||
|
{children}
|
||||||
|
</a>
|
||||||
|
),
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{changelog}
|
||||||
|
</ReactMarkdown>,
|
||||||
|
changelogDivRef.current
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}, [releaseNotes]);
|
||||||
|
const closeButton = (
|
||||||
|
<button onClick={onClose} type="button" className="theia-button secondary">
|
||||||
|
{nls.localize('arduino/ide-updater/notNowButton', 'Not now')}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
|
||||||
|
const DownloadCompleted: () => React.ReactElement = () => (
|
||||||
|
<div className="ide-updater-dialog--downloaded">
|
||||||
|
<div>
|
||||||
|
{nls.localize(
|
||||||
|
'arduino/ide-updater/versionDownloaded',
|
||||||
|
'Arduino IDE {0} has been downloaded.',
|
||||||
|
version
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
{nls.localize(
|
||||||
|
'arduino/ide-updater/closeToInstallNotice',
|
||||||
|
'Close the software and install the update on your machine.'
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="buttons-container">
|
||||||
|
{closeButton}
|
||||||
|
<button
|
||||||
|
onClick={onCloseAndInstall}
|
||||||
|
type="button"
|
||||||
|
className="theia-button close-and-install"
|
||||||
|
>
|
||||||
|
{nls.localize(
|
||||||
|
'arduino/ide-updater/closeAndInstallButton',
|
||||||
|
'Close and Install'
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
const DownloadStarted: () => React.ReactElement = () => (
|
||||||
|
<div className="ide-updater-dialog--downloading">
|
||||||
|
<div>
|
||||||
|
{nls.localize(
|
||||||
|
'arduino/ide-updater/downloadingNotice',
|
||||||
|
'Downloading the latest version of the Arduino IDE.'
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<ProgressBar percent={progress?.percent} showPercentage />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
const PreDownload: () => React.ReactElement = () => (
|
||||||
|
<div className="ide-updater-dialog--pre-download">
|
||||||
|
<div className="ide-updater-dialog--logo-container">
|
||||||
|
<div className="ide-updater-dialog--logo"></div>
|
||||||
|
</div>
|
||||||
|
<div className="ide-updater-dialog--new-version-text dialogSection">
|
||||||
|
<div className="dialogRow">
|
||||||
|
<div className="bold">
|
||||||
|
{nls.localize(
|
||||||
|
'arduino/ide-updater/updateAvailable',
|
||||||
|
'Update Available'
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="dialogRow">
|
||||||
|
{nls.localize(
|
||||||
|
'arduino/ide-updater/newVersionAvailable',
|
||||||
|
'A new version of Arduino IDE ({0}) is available for download.',
|
||||||
|
version
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{releaseNotes && (
|
||||||
|
<div className="dialogRow">
|
||||||
|
<div className="changelog-container" ref={changelogDivRef} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="buttons-container">
|
||||||
|
<button
|
||||||
|
onClick={onSkipVersion}
|
||||||
|
type="button"
|
||||||
|
className="theia-button secondary skip-version"
|
||||||
|
>
|
||||||
|
{nls.localize(
|
||||||
|
'arduino/ide-updater/skipVersionButton',
|
||||||
|
'Skip Version'
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
<div className="push"></div>
|
||||||
|
{closeButton}
|
||||||
|
<button
|
||||||
|
onClick={onDownload}
|
||||||
|
type="button"
|
||||||
|
className="theia-button primary"
|
||||||
|
>
|
||||||
|
{nls.localize('arduino/ide-updater/downloadButton', 'Download')}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
const onGoToDownloadClick = (
|
||||||
|
event: React.SyntheticEvent<HTMLAnchorElement, Event>
|
||||||
|
) => {
|
||||||
|
const { target } = event.nativeEvent;
|
||||||
|
if (target instanceof HTMLAnchorElement) {
|
||||||
|
event.nativeEvent.preventDefault();
|
||||||
|
windowService.openNewWindow(target.href, { external: true });
|
||||||
|
onClose();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const GoToDownloadPage: () => React.ReactElement = () => (
|
||||||
|
<div className="ide-updater-dialog--go-to-download-page">
|
||||||
|
<div>
|
||||||
|
{nls.localize(
|
||||||
|
'arduino/ide-updater/goToDownloadPage',
|
||||||
|
"An update for the Arduino IDE is available, but we're not able to download and install it automatically. Please go to the download page and download the latest version from there."
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="buttons-container">
|
||||||
|
{closeButton}
|
||||||
|
<a
|
||||||
|
className="theia-button primary"
|
||||||
|
href="https://www.arduino.cc/en/software#experimental-software"
|
||||||
|
onClick={onGoToDownloadClick}
|
||||||
|
>
|
||||||
|
{nls.localize(
|
||||||
|
'arduino/ide-updater/goToDownloadButton',
|
||||||
|
'Go To Download'
|
||||||
|
)}
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="ide-updater-dialog--content">
|
||||||
|
{!!error ? (
|
||||||
|
<GoToDownloadPage />
|
||||||
|
) : downloadFinished ? (
|
||||||
|
<DownloadCompleted />
|
||||||
|
) : downloadStarted ? (
|
||||||
|
<DownloadStarted />
|
||||||
|
) : (
|
||||||
|
<PreDownload />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
import * as React from 'react';
|
||||||
|
import { inject, injectable } from 'inversify';
|
||||||
|
import { DialogProps } from '@theia/core/lib/browser/dialogs';
|
||||||
|
import { AbstractDialog } from '../../theia/dialogs/dialogs';
|
||||||
|
import { Widget } from '@phosphor/widgets';
|
||||||
|
import { Message } from '@phosphor/messaging';
|
||||||
|
import { ReactWidget } from '@theia/core/lib/browser/widgets/react-widget';
|
||||||
|
import { nls } from '@theia/core';
|
||||||
|
import { IDEUpdaterComponent } from './ide-updater-component';
|
||||||
|
|
||||||
|
import {
|
||||||
|
IDEUpdater,
|
||||||
|
IDEUpdaterClient,
|
||||||
|
ProgressInfo,
|
||||||
|
UpdateInfo,
|
||||||
|
} from '../../../common/protocol/ide-updater';
|
||||||
|
import { LocalStorageService } from '@theia/core/lib/browser';
|
||||||
|
import { SKIP_IDE_VERSION } from '../../arduino-frontend-contribution';
|
||||||
|
import { WindowService } from '@theia/core/lib/browser/window/window-service';
|
||||||
|
|
||||||
|
@injectable()
|
||||||
|
export class IDEUpdaterDialogWidget extends ReactWidget {
|
||||||
|
protected isOpen = new Object();
|
||||||
|
updateInfo: UpdateInfo;
|
||||||
|
progressInfo: ProgressInfo | undefined;
|
||||||
|
error: Error | undefined;
|
||||||
|
downloadFinished: boolean;
|
||||||
|
downloadStarted: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
|
||||||
|
@inject(IDEUpdater)
|
||||||
|
protected readonly updater: IDEUpdater;
|
||||||
|
|
||||||
|
@inject(IDEUpdaterClient)
|
||||||
|
protected readonly updaterClient: IDEUpdaterClient;
|
||||||
|
|
||||||
|
@inject(LocalStorageService)
|
||||||
|
protected readonly localStorageService: LocalStorageService;
|
||||||
|
|
||||||
|
@inject(WindowService)
|
||||||
|
protected windowService: WindowService;
|
||||||
|
|
||||||
|
init(updateInfo: UpdateInfo, onClose: () => void): void {
|
||||||
|
this.updateInfo = updateInfo;
|
||||||
|
this.progressInfo = undefined;
|
||||||
|
this.error = undefined;
|
||||||
|
this.downloadStarted = false;
|
||||||
|
this.downloadFinished = false;
|
||||||
|
this.onClose = onClose;
|
||||||
|
|
||||||
|
this.updaterClient.onError((e) => {
|
||||||
|
this.error = e;
|
||||||
|
this.update();
|
||||||
|
});
|
||||||
|
this.updaterClient.onDownloadProgressChanged((e) => {
|
||||||
|
this.progressInfo = e;
|
||||||
|
this.update();
|
||||||
|
});
|
||||||
|
this.updaterClient.onDownloadFinished((e) => {
|
||||||
|
this.downloadFinished = true;
|
||||||
|
this.update();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async onSkipVersion(): Promise<void> {
|
||||||
|
this.localStorageService.setData<string>(
|
||||||
|
SKIP_IDE_VERSION,
|
||||||
|
this.updateInfo.version
|
||||||
|
);
|
||||||
|
this.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
close(): void {
|
||||||
|
super.close();
|
||||||
|
this.onClose();
|
||||||
|
}
|
||||||
|
|
||||||
|
onDispose(): void {
|
||||||
|
if (this.downloadStarted && !this.downloadFinished)
|
||||||
|
this.updater.stopDownload();
|
||||||
|
}
|
||||||
|
|
||||||
|
async onDownload(): Promise<void> {
|
||||||
|
this.progressInfo = undefined;
|
||||||
|
this.downloadStarted = true;
|
||||||
|
this.error = undefined;
|
||||||
|
this.updater.downloadUpdate();
|
||||||
|
this.update();
|
||||||
|
}
|
||||||
|
|
||||||
|
onCloseAndInstall(): void {
|
||||||
|
this.updater.quitAndInstall();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected render(): React.ReactNode {
|
||||||
|
return !!this.updateInfo ? (
|
||||||
|
<form>
|
||||||
|
<IDEUpdaterComponent
|
||||||
|
updateInfo={this.updateInfo}
|
||||||
|
windowService={this.windowService}
|
||||||
|
downloadStarted={this.downloadStarted}
|
||||||
|
downloadFinished={this.downloadFinished}
|
||||||
|
progress={this.progressInfo}
|
||||||
|
error={this.error}
|
||||||
|
onClose={this.close.bind(this)}
|
||||||
|
onSkipVersion={this.onSkipVersion.bind(this)}
|
||||||
|
onDownload={this.onDownload.bind(this)}
|
||||||
|
onCloseAndInstall={this.onCloseAndInstall.bind(this)}
|
||||||
|
/>
|
||||||
|
</form>
|
||||||
|
) : null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@injectable()
|
||||||
|
export class IDEUpdaterDialogProps extends DialogProps {}
|
||||||
|
|
||||||
|
@injectable()
|
||||||
|
export class IDEUpdaterDialog extends AbstractDialog<UpdateInfo> {
|
||||||
|
@inject(IDEUpdaterDialogWidget)
|
||||||
|
protected readonly widget: IDEUpdaterDialogWidget;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
@inject(IDEUpdaterDialogProps)
|
||||||
|
protected readonly props: IDEUpdaterDialogProps
|
||||||
|
) {
|
||||||
|
super({
|
||||||
|
title: nls.localize(
|
||||||
|
'arduino/ide-updater/ideUpdaterDialog',
|
||||||
|
'Software Update'
|
||||||
|
),
|
||||||
|
});
|
||||||
|
this.contentNode.classList.add('ide-updater-dialog');
|
||||||
|
this.acceptButton = undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
get value(): UpdateInfo {
|
||||||
|
return this.widget.updateInfo;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected onAfterAttach(msg: Message): void {
|
||||||
|
if (this.widget.isAttached) {
|
||||||
|
Widget.detach(this.widget);
|
||||||
|
}
|
||||||
|
Widget.attach(this.widget, this.contentNode);
|
||||||
|
super.onAfterAttach(msg);
|
||||||
|
this.update();
|
||||||
|
}
|
||||||
|
|
||||||
|
async open(
|
||||||
|
data: UpdateInfo | undefined = undefined
|
||||||
|
): Promise<UpdateInfo | undefined> {
|
||||||
|
if (data && data.version) {
|
||||||
|
this.widget.init(data, this.close.bind(this));
|
||||||
|
return super.open();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected onUpdateRequest(msg: Message): void {
|
||||||
|
super.onUpdateRequest(msg);
|
||||||
|
this.widget.update();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected onActivateRequest(msg: Message): void {
|
||||||
|
super.onActivateRequest(msg);
|
||||||
|
this.widget.activate();
|
||||||
|
}
|
||||||
|
|
||||||
|
close(): void {
|
||||||
|
this.widget.dispose();
|
||||||
|
super.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,703 @@
|
|||||||
|
import * as React from 'react';
|
||||||
|
import { Tab, Tabs, TabList, TabPanel } from 'react-tabs';
|
||||||
|
import 'react-tabs/style/react-tabs.css';
|
||||||
|
import { Disable } from 'react-disable';
|
||||||
|
import { deepClone } from '@theia/core/lib/common/objects';
|
||||||
|
import { FileService } from '@theia/filesystem/lib/browser/file-service';
|
||||||
|
import { ThemeService } from '@theia/core/lib/browser/theming';
|
||||||
|
import { WindowService } from '@theia/core/lib/browser/window/window-service';
|
||||||
|
import { FileDialogService } from '@theia/filesystem/lib/browser/file-dialog/file-dialog-service';
|
||||||
|
import { DisposableCollection } from '@theia/core/lib/common/disposable';
|
||||||
|
import {
|
||||||
|
CompilerWarningLiterals,
|
||||||
|
Network,
|
||||||
|
ProxySettings,
|
||||||
|
} from '../../../common/protocol';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
import { Settings, SettingsService } from './settings';
|
||||||
|
import { AdditionalUrlsDialog } from './settings-dialog';
|
||||||
|
import { AsyncLocalizationProvider } from '@theia/core/lib/common/i18n/localization';
|
||||||
|
|
||||||
|
export class SettingsComponent extends React.Component<
|
||||||
|
SettingsComponent.Props,
|
||||||
|
SettingsComponent.State
|
||||||
|
> {
|
||||||
|
readonly toDispose = new DisposableCollection();
|
||||||
|
|
||||||
|
constructor(props: SettingsComponent.Props) {
|
||||||
|
super(props);
|
||||||
|
}
|
||||||
|
|
||||||
|
componentDidUpdate(
|
||||||
|
_: SettingsComponent.Props,
|
||||||
|
prevState: SettingsComponent.State
|
||||||
|
): void {
|
||||||
|
if (
|
||||||
|
this.state &&
|
||||||
|
prevState &&
|
||||||
|
JSON.stringify(this.state) !== JSON.stringify(prevState)
|
||||||
|
) {
|
||||||
|
this.props.settingsService.update(this.state, true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
componentDidMount(): void {
|
||||||
|
this.props.settingsService
|
||||||
|
.settings()
|
||||||
|
.then((settings) => this.setState(settings));
|
||||||
|
this.toDispose.push(
|
||||||
|
this.props.settingsService.onDidChange((settings) =>
|
||||||
|
this.setState(settings)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
componentWillUnmount(): void {
|
||||||
|
this.toDispose.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
render(): React.ReactNode {
|
||||||
|
if (!this.state) {
|
||||||
|
return <div />;
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<Tabs>
|
||||||
|
<TabList>
|
||||||
|
<Tab>{nls.localize('vscode/settingsTree/settings', 'Settings')}</Tab>
|
||||||
|
<Tab>{nls.localize('arduino/preferences/network', 'Network')}</Tab>
|
||||||
|
</TabList>
|
||||||
|
<TabPanel>{this.renderSettings()}</TabPanel>
|
||||||
|
<TabPanel>{this.renderNetwork()}</TabPanel>
|
||||||
|
</Tabs>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected renderSettings(): React.ReactNode {
|
||||||
|
return (
|
||||||
|
<div className="content noselect">
|
||||||
|
{nls.localize(
|
||||||
|
'arduino/preferences/sketchbook.location',
|
||||||
|
'Sketchbook location'
|
||||||
|
) + ':'}
|
||||||
|
<div className="flex-line">
|
||||||
|
<input
|
||||||
|
className="theia-input stretch"
|
||||||
|
type="text"
|
||||||
|
value={this.state.sketchbookPath}
|
||||||
|
onChange={this.sketchpathDidChange}
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
className="theia-button shrink"
|
||||||
|
onClick={this.browseSketchbookDidClick}
|
||||||
|
>
|
||||||
|
{nls.localize('arduino/preferences/browse', 'Browse')}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<label className="flex-line">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={this.state.sketchbookShowAllFiles === true}
|
||||||
|
onChange={this.sketchbookShowAllFilesDidChange}
|
||||||
|
/>
|
||||||
|
{nls.localize(
|
||||||
|
'arduino/preferences/files.inside.sketches',
|
||||||
|
'Show files inside Sketches'
|
||||||
|
)}
|
||||||
|
</label>
|
||||||
|
<div className="flex-line">
|
||||||
|
<div className="column">
|
||||||
|
<div className="flex-line">
|
||||||
|
{nls.localize(
|
||||||
|
'arduino/preferences/editorFontSize',
|
||||||
|
'Editor font size'
|
||||||
|
) + ':'}
|
||||||
|
</div>
|
||||||
|
<div className="flex-line">
|
||||||
|
{nls.localize(
|
||||||
|
'arduino/preferences/interfaceScale',
|
||||||
|
'Interface scale'
|
||||||
|
) + ':'}
|
||||||
|
</div>
|
||||||
|
<div className="flex-line">
|
||||||
|
{nls.localize(
|
||||||
|
'vscode/themes.contribution/selectTheme.label',
|
||||||
|
'Theme'
|
||||||
|
) + ':'}
|
||||||
|
</div>
|
||||||
|
<div className="flex-line">
|
||||||
|
{nls.localize(
|
||||||
|
'vscode/editorStatus/status.editor.mode',
|
||||||
|
'Language'
|
||||||
|
) + ':'}
|
||||||
|
</div>
|
||||||
|
<div className="flex-line">
|
||||||
|
{nls.localize(
|
||||||
|
'arduino/preferences/showVerbose',
|
||||||
|
'Show verbose output during'
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="flex-line">
|
||||||
|
{nls.localize(
|
||||||
|
'arduino/preferences/compilerWarnings',
|
||||||
|
'Compiler warnings'
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="column">
|
||||||
|
<div className="flex-line">
|
||||||
|
<input
|
||||||
|
className="theia-input small"
|
||||||
|
type="number"
|
||||||
|
step={1}
|
||||||
|
pattern="[0-9]+"
|
||||||
|
onKeyDown={this.numbersOnlyKeyDown}
|
||||||
|
value={this.state.editorFontSize}
|
||||||
|
onChange={this.editorFontSizeDidChange}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex-line">
|
||||||
|
<label className="flex-line">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={this.state.autoScaleInterface}
|
||||||
|
onChange={this.autoScaleInterfaceDidChange}
|
||||||
|
/>
|
||||||
|
{nls.localize('arduino/preferences/automatic', 'Automatic')}
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
className="theia-input small with-margin"
|
||||||
|
type="number"
|
||||||
|
step={20}
|
||||||
|
pattern="[0-9]+"
|
||||||
|
onKeyDown={this.noopKeyDown}
|
||||||
|
value={100 + this.state.interfaceScale * 20}
|
||||||
|
onChange={this.interfaceScaleDidChange}
|
||||||
|
/>
|
||||||
|
%
|
||||||
|
</div>
|
||||||
|
<div className="flex-line">
|
||||||
|
<select
|
||||||
|
className="theia-select"
|
||||||
|
value={
|
||||||
|
ThemeService.get()
|
||||||
|
.getThemes()
|
||||||
|
.find(({ id }) => id === this.state.themeId)?.label ||
|
||||||
|
nls.localize('arduino/common/unknown', 'Unknown')
|
||||||
|
}
|
||||||
|
onChange={this.themeDidChange}
|
||||||
|
>
|
||||||
|
{ThemeService.get()
|
||||||
|
.getThemes()
|
||||||
|
.map(({ id, label }) => (
|
||||||
|
<option key={id} value={label}>
|
||||||
|
{label}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div className="flex-line">
|
||||||
|
<select
|
||||||
|
className="theia-select"
|
||||||
|
value={this.state.currentLanguage}
|
||||||
|
onChange={this.languageDidChange}
|
||||||
|
>
|
||||||
|
{this.state.languages.map((label) => (
|
||||||
|
<option key={label} value={label}>
|
||||||
|
{label}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
<span style={{ marginLeft: '5px' }}>
|
||||||
|
(
|
||||||
|
{nls.localize(
|
||||||
|
'vscode/extensionsActions/reloadRequired',
|
||||||
|
'Reload required'
|
||||||
|
)}
|
||||||
|
)
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex-line">
|
||||||
|
<label className="flex-line">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={this.state.verboseOnCompile}
|
||||||
|
onChange={this.verboseOnCompileDidChange}
|
||||||
|
/>
|
||||||
|
{nls.localize('arduino/preferences/compile', 'compile')}
|
||||||
|
</label>
|
||||||
|
<label className="flex-line">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={this.state.verboseOnUpload}
|
||||||
|
onChange={this.verboseOnUploadDidChange}
|
||||||
|
/>
|
||||||
|
{nls.localize('arduino/preferences/upload', 'upload')}
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div className="flex-line">
|
||||||
|
<select
|
||||||
|
className="theia-select"
|
||||||
|
value={this.state.compilerWarnings}
|
||||||
|
onChange={this.compilerWarningsDidChange}
|
||||||
|
>
|
||||||
|
{CompilerWarningLiterals.map((value) => (
|
||||||
|
<option key={value} value={value}>
|
||||||
|
{value}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<label className="flex-line">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={this.state.verifyAfterUpload}
|
||||||
|
onChange={this.verifyAfterUploadDidChange}
|
||||||
|
/>
|
||||||
|
{nls.localize(
|
||||||
|
'arduino/preferences/verifyAfterUpload',
|
||||||
|
'Verify code after upload'
|
||||||
|
)}
|
||||||
|
</label>
|
||||||
|
<label className="flex-line">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={this.state.autoSave === 'on'}
|
||||||
|
onChange={this.autoSaveDidChange}
|
||||||
|
/>
|
||||||
|
{nls.localize(
|
||||||
|
'vscode/fileActions.contribution/miAutoSave',
|
||||||
|
'Auto save'
|
||||||
|
)}
|
||||||
|
</label>
|
||||||
|
<label className="flex-line">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={this.state.quickSuggestions.other === true}
|
||||||
|
onChange={this.quickSuggestionsOtherDidChange}
|
||||||
|
/>
|
||||||
|
{nls.localize(
|
||||||
|
'arduino/preferences/editorQuickSuggestions',
|
||||||
|
'Editor Quick Suggestions'
|
||||||
|
)}
|
||||||
|
</label>
|
||||||
|
<div className="flex-line">
|
||||||
|
{nls.localize(
|
||||||
|
'arduino/preferences/additionalManagerURLs',
|
||||||
|
'Additional boards manager URLs'
|
||||||
|
) + ':'}
|
||||||
|
<input
|
||||||
|
className="theia-input stretch with-margin"
|
||||||
|
type="text"
|
||||||
|
value={this.state.additionalUrls.join(',')}
|
||||||
|
onChange={this.additionalUrlsDidChange}
|
||||||
|
/>
|
||||||
|
<i
|
||||||
|
className="fa fa-window-restore theia-button shrink"
|
||||||
|
onClick={this.editAdditionalUrlDidClick}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected renderNetwork(): React.ReactNode {
|
||||||
|
return (
|
||||||
|
<div className="content noselect">
|
||||||
|
<form>
|
||||||
|
<label className="flex-line">
|
||||||
|
<input
|
||||||
|
type="radio"
|
||||||
|
checked={this.state.network === 'none'}
|
||||||
|
onChange={this.noProxyDidChange}
|
||||||
|
/>
|
||||||
|
{nls.localize('arduino/preferences/noProxy', 'No proxy')}
|
||||||
|
</label>
|
||||||
|
<label className="flex-line">
|
||||||
|
<input
|
||||||
|
type="radio"
|
||||||
|
checked={this.state.network !== 'none'}
|
||||||
|
onChange={this.manualProxyDidChange}
|
||||||
|
/>
|
||||||
|
{nls.localize(
|
||||||
|
'arduino/preferences/manualProxy',
|
||||||
|
'Manual proxy configuration'
|
||||||
|
)}
|
||||||
|
</label>
|
||||||
|
</form>
|
||||||
|
{this.renderProxySettings()}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected renderProxySettings(): React.ReactNode {
|
||||||
|
const disabled = this.state.network === 'none';
|
||||||
|
return (
|
||||||
|
<Disable disabled={disabled}>
|
||||||
|
<div className="proxy-settings" aria-disabled={disabled}>
|
||||||
|
<form className="flex-line">
|
||||||
|
<input
|
||||||
|
type="radio"
|
||||||
|
checked={
|
||||||
|
this.state.network === 'none'
|
||||||
|
? true
|
||||||
|
: this.state.network.protocol === 'http'
|
||||||
|
}
|
||||||
|
onChange={this.httpProtocolDidChange}
|
||||||
|
/>
|
||||||
|
HTTP
|
||||||
|
<label className="flex-line">
|
||||||
|
<input
|
||||||
|
type="radio"
|
||||||
|
checked={
|
||||||
|
this.state.network === 'none'
|
||||||
|
? false
|
||||||
|
: this.state.network.protocol !== 'http'
|
||||||
|
}
|
||||||
|
onChange={this.socksProtocolDidChange}
|
||||||
|
/>
|
||||||
|
SOCKS
|
||||||
|
</label>
|
||||||
|
</form>
|
||||||
|
<div className="flex-line proxy-settings">
|
||||||
|
<div className="column">
|
||||||
|
<div className="flex-line">Host name:</div>
|
||||||
|
<div className="flex-line">Port number:</div>
|
||||||
|
<div className="flex-line">Username:</div>
|
||||||
|
<div className="flex-line">Password:</div>
|
||||||
|
</div>
|
||||||
|
<div className="column stretch">
|
||||||
|
<div className="flex-line">
|
||||||
|
<input
|
||||||
|
className="theia-input stretch with-margin"
|
||||||
|
type="text"
|
||||||
|
value={
|
||||||
|
this.state.network === 'none'
|
||||||
|
? ''
|
||||||
|
: this.state.network.hostname
|
||||||
|
}
|
||||||
|
onChange={this.hostnameDidChange}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex-line">
|
||||||
|
<input
|
||||||
|
className="theia-input small with-margin"
|
||||||
|
type="number"
|
||||||
|
pattern="[0-9]"
|
||||||
|
value={
|
||||||
|
this.state.network === 'none' ? '' : this.state.network.port
|
||||||
|
}
|
||||||
|
onKeyDown={this.numbersOnlyKeyDown}
|
||||||
|
onChange={this.portDidChange}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex-line">
|
||||||
|
<input
|
||||||
|
className="theia-input stretch with-margin"
|
||||||
|
type="text"
|
||||||
|
value={
|
||||||
|
this.state.network === 'none'
|
||||||
|
? ''
|
||||||
|
: this.state.network.username
|
||||||
|
}
|
||||||
|
onChange={this.usernameDidChange}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex-line">
|
||||||
|
<input
|
||||||
|
className="theia-input stretch with-margin"
|
||||||
|
type="password"
|
||||||
|
value={
|
||||||
|
this.state.network === 'none'
|
||||||
|
? ''
|
||||||
|
: this.state.network.password
|
||||||
|
}
|
||||||
|
onChange={this.passwordDidChange}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Disable>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private isControlKey(event: React.KeyboardEvent<HTMLInputElement>): boolean {
|
||||||
|
return (
|
||||||
|
!!event.key &&
|
||||||
|
['tab', 'delete', 'backspace', 'arrowleft', 'arrowright'].some(
|
||||||
|
(key) => event.key.toLocaleLowerCase() === key
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected noopKeyDown = (
|
||||||
|
event: React.KeyboardEvent<HTMLInputElement>
|
||||||
|
): void => {
|
||||||
|
if (this.isControlKey(event)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
event.nativeEvent.preventDefault();
|
||||||
|
event.nativeEvent.returnValue = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
protected numbersOnlyKeyDown = (
|
||||||
|
event: React.KeyboardEvent<HTMLInputElement>
|
||||||
|
): void => {
|
||||||
|
if (this.isControlKey(event)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const key = Number(event.key);
|
||||||
|
if (isNaN(key) || event.key === null || event.key === ' ') {
|
||||||
|
event.nativeEvent.preventDefault();
|
||||||
|
event.nativeEvent.returnValue = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
protected browseSketchbookDidClick = async (): Promise<void> => {
|
||||||
|
const uri = await this.props.fileDialogService.showOpenDialog({
|
||||||
|
title: nls.localize(
|
||||||
|
'arduino/preferences/newSketchbookLocation',
|
||||||
|
'Select new sketchbook location'
|
||||||
|
),
|
||||||
|
openLabel: nls.localize('arduino/preferences/choose', 'Choose'),
|
||||||
|
canSelectFiles: false,
|
||||||
|
canSelectMany: false,
|
||||||
|
canSelectFolders: true,
|
||||||
|
});
|
||||||
|
if (uri) {
|
||||||
|
const sketchbookPath = await this.props.fileService.fsPath(uri);
|
||||||
|
this.setState({ sketchbookPath });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
protected editAdditionalUrlDidClick = async (): Promise<void> => {
|
||||||
|
const additionalUrls = await new AdditionalUrlsDialog(
|
||||||
|
this.state.additionalUrls,
|
||||||
|
this.props.windowService
|
||||||
|
).open();
|
||||||
|
if (additionalUrls) {
|
||||||
|
this.setState({ additionalUrls });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
protected editorFontSizeDidChange = (
|
||||||
|
event: React.ChangeEvent<HTMLInputElement>
|
||||||
|
): void => {
|
||||||
|
const { value } = event.target;
|
||||||
|
if (value) {
|
||||||
|
this.setState({ editorFontSize: parseInt(value, 10) });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
protected additionalUrlsDidChange = (
|
||||||
|
event: React.ChangeEvent<HTMLInputElement>
|
||||||
|
): void => {
|
||||||
|
this.setState({
|
||||||
|
additionalUrls: event.target.value.split(',').map((url) => url.trim()),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
protected autoScaleInterfaceDidChange = (
|
||||||
|
event: React.ChangeEvent<HTMLInputElement>
|
||||||
|
): void => {
|
||||||
|
this.setState({ autoScaleInterface: event.target.checked });
|
||||||
|
};
|
||||||
|
|
||||||
|
protected interfaceScaleDidChange = (
|
||||||
|
event: React.ChangeEvent<HTMLInputElement>
|
||||||
|
): void => {
|
||||||
|
const { value } = event.target;
|
||||||
|
const percentage = parseInt(value, 10);
|
||||||
|
if (isNaN(percentage)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const interfaceScale = (percentage - 100) / 20;
|
||||||
|
if (!isNaN(interfaceScale)) {
|
||||||
|
this.setState({ interfaceScale });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
protected verifyAfterUploadDidChange = (
|
||||||
|
event: React.ChangeEvent<HTMLInputElement>
|
||||||
|
): void => {
|
||||||
|
this.setState({ verifyAfterUpload: event.target.checked });
|
||||||
|
};
|
||||||
|
|
||||||
|
protected sketchbookShowAllFilesDidChange = (
|
||||||
|
event: React.ChangeEvent<HTMLInputElement>
|
||||||
|
): void => {
|
||||||
|
this.setState({ sketchbookShowAllFiles: event.target.checked });
|
||||||
|
};
|
||||||
|
|
||||||
|
protected autoSaveDidChange = (
|
||||||
|
event: React.ChangeEvent<HTMLInputElement>
|
||||||
|
): void => {
|
||||||
|
this.setState({ autoSave: event.target.checked ? 'on' : 'off' });
|
||||||
|
};
|
||||||
|
|
||||||
|
protected quickSuggestionsOtherDidChange = (
|
||||||
|
event: React.ChangeEvent<HTMLInputElement>
|
||||||
|
): void => {
|
||||||
|
// need to persist react events through lifecycle https://reactjs.org/docs/events.html#event-pooling
|
||||||
|
const newVal = event.target.checked ? true : false;
|
||||||
|
|
||||||
|
this.setState((prevState) => {
|
||||||
|
return {
|
||||||
|
quickSuggestions: {
|
||||||
|
...prevState.quickSuggestions,
|
||||||
|
other: newVal,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
protected themeDidChange = (
|
||||||
|
event: React.ChangeEvent<HTMLSelectElement>
|
||||||
|
): void => {
|
||||||
|
const { selectedIndex } = event.target.options;
|
||||||
|
const theme = ThemeService.get().getThemes()[selectedIndex];
|
||||||
|
if (theme) {
|
||||||
|
this.setState({ themeId: theme.id });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
protected languageDidChange = (
|
||||||
|
event: React.ChangeEvent<HTMLSelectElement>
|
||||||
|
): void => {
|
||||||
|
const selectedLanguage = event.target.value;
|
||||||
|
this.setState({ currentLanguage: selectedLanguage });
|
||||||
|
};
|
||||||
|
|
||||||
|
protected compilerWarningsDidChange = (
|
||||||
|
event: React.ChangeEvent<HTMLSelectElement>
|
||||||
|
): void => {
|
||||||
|
const { selectedIndex } = event.target.options;
|
||||||
|
const compilerWarnings = CompilerWarningLiterals[selectedIndex];
|
||||||
|
if (compilerWarnings) {
|
||||||
|
this.setState({ compilerWarnings });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
protected verboseOnCompileDidChange = (
|
||||||
|
event: React.ChangeEvent<HTMLInputElement>
|
||||||
|
): void => {
|
||||||
|
this.setState({ verboseOnCompile: event.target.checked });
|
||||||
|
};
|
||||||
|
|
||||||
|
protected verboseOnUploadDidChange = (
|
||||||
|
event: React.ChangeEvent<HTMLInputElement>
|
||||||
|
): void => {
|
||||||
|
this.setState({ verboseOnUpload: event.target.checked });
|
||||||
|
};
|
||||||
|
|
||||||
|
protected sketchpathDidChange = (
|
||||||
|
event: React.ChangeEvent<HTMLInputElement>
|
||||||
|
): void => {
|
||||||
|
const sketchbookPath = event.target.value;
|
||||||
|
if (sketchbookPath) {
|
||||||
|
this.setState({ sketchbookPath });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
protected noProxyDidChange = (
|
||||||
|
event: React.ChangeEvent<HTMLInputElement>
|
||||||
|
): void => {
|
||||||
|
if (event.target.checked) {
|
||||||
|
this.setState({ network: 'none' });
|
||||||
|
} else {
|
||||||
|
this.setState({ network: Network.Default() });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
protected manualProxyDidChange = (
|
||||||
|
event: React.ChangeEvent<HTMLInputElement>
|
||||||
|
): void => {
|
||||||
|
if (event.target.checked) {
|
||||||
|
this.setState({ network: Network.Default() });
|
||||||
|
} else {
|
||||||
|
this.setState({ network: 'none' });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
protected httpProtocolDidChange = (
|
||||||
|
event: React.ChangeEvent<HTMLInputElement>
|
||||||
|
): void => {
|
||||||
|
if (this.state.network !== 'none') {
|
||||||
|
const network = this.cloneProxySettings;
|
||||||
|
network.protocol = event.target.checked ? 'http' : 'socks';
|
||||||
|
this.setState({ network });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
protected socksProtocolDidChange = (
|
||||||
|
event: React.ChangeEvent<HTMLInputElement>
|
||||||
|
): void => {
|
||||||
|
if (this.state.network !== 'none') {
|
||||||
|
const network = this.cloneProxySettings;
|
||||||
|
network.protocol = event.target.checked ? 'socks' : 'http';
|
||||||
|
this.setState({ network });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
protected hostnameDidChange = (
|
||||||
|
event: React.ChangeEvent<HTMLInputElement>
|
||||||
|
): void => {
|
||||||
|
if (this.state.network !== 'none') {
|
||||||
|
const network = this.cloneProxySettings;
|
||||||
|
network.hostname = event.target.value;
|
||||||
|
this.setState({ network });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
protected portDidChange = (
|
||||||
|
event: React.ChangeEvent<HTMLInputElement>
|
||||||
|
): void => {
|
||||||
|
if (this.state.network !== 'none') {
|
||||||
|
const network = this.cloneProxySettings;
|
||||||
|
network.port = event.target.value;
|
||||||
|
this.setState({ network });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
protected usernameDidChange = (
|
||||||
|
event: React.ChangeEvent<HTMLInputElement>
|
||||||
|
): void => {
|
||||||
|
if (this.state.network !== 'none') {
|
||||||
|
const network = this.cloneProxySettings;
|
||||||
|
network.username = event.target.value;
|
||||||
|
this.setState({ network });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
protected passwordDidChange = (
|
||||||
|
event: React.ChangeEvent<HTMLInputElement>
|
||||||
|
): void => {
|
||||||
|
if (this.state.network !== 'none') {
|
||||||
|
const network = this.cloneProxySettings;
|
||||||
|
network.password = event.target.value;
|
||||||
|
this.setState({ network });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
private get cloneProxySettings(): ProxySettings {
|
||||||
|
const { network } = this.state;
|
||||||
|
if (network === 'none') {
|
||||||
|
throw new Error('Must be called when proxy is enabled.');
|
||||||
|
}
|
||||||
|
const copyNetwork = deepClone(network);
|
||||||
|
return copyNetwork;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
export namespace SettingsComponent {
|
||||||
|
export interface Props {
|
||||||
|
readonly settingsService: SettingsService;
|
||||||
|
readonly fileService: FileService;
|
||||||
|
readonly fileDialogService: FileDialogService;
|
||||||
|
readonly windowService: WindowService;
|
||||||
|
readonly localizationProvider: AsyncLocalizationProvider;
|
||||||
|
}
|
||||||
|
export type State = Settings & { languages: string[] };
|
||||||
|
}
|
||||||
@@ -0,0 +1,193 @@
|
|||||||
|
import * as React from 'react';
|
||||||
|
import { injectable, inject, postConstruct } from 'inversify';
|
||||||
|
import { Widget } from '@phosphor/widgets';
|
||||||
|
import { Message } from '@phosphor/messaging';
|
||||||
|
import { DialogError, ReactWidget } from '@theia/core/lib/browser';
|
||||||
|
import { AbstractDialog, DialogProps } from '@theia/core/lib/browser';
|
||||||
|
import { Settings, SettingsService } from './settings';
|
||||||
|
import { FileService } from '@theia/filesystem/lib/browser/file-service';
|
||||||
|
import { WindowService } from '@theia/core/lib/browser/window/window-service';
|
||||||
|
import { FileDialogService } from '@theia/filesystem/lib/browser/file-dialog/file-dialog-service';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
import { SettingsComponent } from './settings-component';
|
||||||
|
import { AsyncLocalizationProvider } from '@theia/core/lib/common/i18n/localization';
|
||||||
|
|
||||||
|
@injectable()
|
||||||
|
export class SettingsWidget extends ReactWidget {
|
||||||
|
@inject(SettingsService)
|
||||||
|
protected readonly settingsService: SettingsService;
|
||||||
|
|
||||||
|
@inject(FileService)
|
||||||
|
protected readonly fileService: FileService;
|
||||||
|
|
||||||
|
@inject(FileDialogService)
|
||||||
|
protected readonly fileDialogService: FileDialogService;
|
||||||
|
|
||||||
|
@inject(WindowService)
|
||||||
|
protected readonly windowService: WindowService;
|
||||||
|
|
||||||
|
@inject(AsyncLocalizationProvider)
|
||||||
|
protected readonly localizationProvider: AsyncLocalizationProvider;
|
||||||
|
|
||||||
|
protected render(): React.ReactNode {
|
||||||
|
return (
|
||||||
|
<SettingsComponent
|
||||||
|
settingsService={this.settingsService}
|
||||||
|
fileService={this.fileService}
|
||||||
|
fileDialogService={this.fileDialogService}
|
||||||
|
windowService={this.windowService}
|
||||||
|
localizationProvider={this.localizationProvider}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@injectable()
|
||||||
|
export class SettingsDialogProps extends DialogProps {}
|
||||||
|
|
||||||
|
@injectable()
|
||||||
|
export class SettingsDialog extends AbstractDialog<Promise<Settings>> {
|
||||||
|
@inject(SettingsService)
|
||||||
|
protected readonly settingsService: SettingsService;
|
||||||
|
|
||||||
|
@inject(SettingsWidget)
|
||||||
|
protected readonly widget: SettingsWidget;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
@inject(SettingsDialogProps)
|
||||||
|
protected readonly props: SettingsDialogProps
|
||||||
|
) {
|
||||||
|
super(props);
|
||||||
|
this.contentNode.classList.add('arduino-settings-dialog');
|
||||||
|
this.appendCloseButton(
|
||||||
|
nls.localize('vscode/issueMainService/cancel', 'Cancel')
|
||||||
|
);
|
||||||
|
this.appendAcceptButton(nls.localize('vscode/issueMainService/ok', 'OK'));
|
||||||
|
}
|
||||||
|
|
||||||
|
@postConstruct()
|
||||||
|
protected init(): void {
|
||||||
|
this.toDispose.push(
|
||||||
|
this.settingsService.onDidChange(this.validate.bind(this))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected async isValid(settings: Promise<Settings>): Promise<DialogError> {
|
||||||
|
const result = await this.settingsService.validate(settings);
|
||||||
|
if (typeof result === 'string') {
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
get value(): Promise<Settings> {
|
||||||
|
return this.settingsService.settings();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected onAfterAttach(msg: Message): void {
|
||||||
|
if (this.widget.isAttached) {
|
||||||
|
Widget.detach(this.widget);
|
||||||
|
}
|
||||||
|
Widget.attach(this.widget, this.contentNode);
|
||||||
|
this.toDisposeOnDetach.push(
|
||||||
|
this.settingsService.onDidChange(() => 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);
|
||||||
|
|
||||||
|
// calling settingsService.reset() in order to reload the settings from the preferenceService
|
||||||
|
// and update the UI including changes triggerd from the command palette
|
||||||
|
this.settingsService.reset();
|
||||||
|
|
||||||
|
this.widget.activate();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class AdditionalUrlsDialog extends AbstractDialog<string[]> {
|
||||||
|
protected readonly textArea: HTMLTextAreaElement;
|
||||||
|
|
||||||
|
constructor(urls: string[], windowService: WindowService) {
|
||||||
|
super({
|
||||||
|
title: nls.localize(
|
||||||
|
'arduino/preferences/additionalManagerURLs',
|
||||||
|
'Additional Boards Manager URLs'
|
||||||
|
),
|
||||||
|
});
|
||||||
|
|
||||||
|
this.contentNode.classList.add('additional-urls-dialog');
|
||||||
|
|
||||||
|
const description = document.createElement('div');
|
||||||
|
description.textContent = nls.localize(
|
||||||
|
'arduino/preferences/enterAdditionalURLs',
|
||||||
|
'Enter additional URLs, one for each row'
|
||||||
|
);
|
||||||
|
description.style.marginBottom = '5px';
|
||||||
|
this.contentNode.appendChild(description);
|
||||||
|
|
||||||
|
this.textArea = document.createElement('textarea');
|
||||||
|
this.textArea.className = 'theia-input';
|
||||||
|
this.textArea.setAttribute('style', 'flex: 0;');
|
||||||
|
this.textArea.value = urls
|
||||||
|
.filter((url) => url.trim())
|
||||||
|
.filter((url) => !!url)
|
||||||
|
.join('\n');
|
||||||
|
this.textArea.wrap = 'soft';
|
||||||
|
this.textArea.cols = 90;
|
||||||
|
this.textArea.rows = 5;
|
||||||
|
this.contentNode.appendChild(this.textArea);
|
||||||
|
|
||||||
|
const anchor = document.createElement('div');
|
||||||
|
anchor.classList.add('link');
|
||||||
|
anchor.textContent = nls.localize(
|
||||||
|
'arduino/preferences/unofficialBoardSupport',
|
||||||
|
'Click for a list of unofficial board support URLs'
|
||||||
|
);
|
||||||
|
anchor.style.marginTop = '5px';
|
||||||
|
anchor.style.cursor = 'pointer';
|
||||||
|
this.addEventListener(anchor, 'click', () =>
|
||||||
|
windowService.openNewWindow(
|
||||||
|
'https://github.com/arduino/Arduino/wiki/Unofficial-list-of-3rd-party-boards-support-urls',
|
||||||
|
{ external: true }
|
||||||
|
)
|
||||||
|
);
|
||||||
|
this.contentNode.appendChild(anchor);
|
||||||
|
|
||||||
|
this.appendAcceptButton(nls.localize('vscode/issueMainService/ok', 'OK'));
|
||||||
|
this.appendCloseButton(
|
||||||
|
nls.localize('vscode/issueMainService/cancel', 'Cancel')
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
get value(): string[] {
|
||||||
|
return this.textArea.value
|
||||||
|
.split('\n')
|
||||||
|
.map((url) => url.trim())
|
||||||
|
.filter((url) => !!url);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected onAfterAttach(message: Message): void {
|
||||||
|
super.onAfterAttach(message);
|
||||||
|
this.addUpdateListener(this.textArea, 'input');
|
||||||
|
}
|
||||||
|
|
||||||
|
protected onActivateRequest(message: Message): void {
|
||||||
|
super.onActivateRequest(message);
|
||||||
|
this.textArea.focus();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected handleEnter(event: KeyboardEvent): boolean | void {
|
||||||
|
if (event.target instanceof HTMLInputElement) {
|
||||||
|
return super.handleEnter(event);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
281
arduino-ide-extension/src/browser/dialogs/settings/settings.tsx
Normal file
281
arduino-ide-extension/src/browser/dialogs/settings/settings.tsx
Normal file
@@ -0,0 +1,281 @@
|
|||||||
|
import { injectable, inject, postConstruct } from 'inversify';
|
||||||
|
import URI from '@theia/core/lib/common/uri';
|
||||||
|
import { Emitter } from '@theia/core/lib/common/event';
|
||||||
|
import { Deferred, timeout } from '@theia/core/lib/common/promise-util';
|
||||||
|
import { deepClone } from '@theia/core/lib/common/objects';
|
||||||
|
import { FileService } from '@theia/filesystem/lib/browser/file-service';
|
||||||
|
import { ThemeService } from '@theia/core/lib/browser/theming';
|
||||||
|
import { MaybePromise } from '@theia/core/lib/common/types';
|
||||||
|
import { FrontendApplicationStateService } from '@theia/core/lib/browser/frontend-application-state';
|
||||||
|
import { PreferenceService, PreferenceScope } from '@theia/core/lib/browser';
|
||||||
|
import { Index } from '../../../common/types';
|
||||||
|
import {
|
||||||
|
CompilerWarnings,
|
||||||
|
ConfigService,
|
||||||
|
FileSystemExt,
|
||||||
|
Network,
|
||||||
|
} from '../../../common/protocol';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
import { AsyncLocalizationProvider } from '@theia/core/lib/common/i18n/localization';
|
||||||
|
|
||||||
|
export const EDITOR_SETTING = 'editor';
|
||||||
|
export const FONT_SIZE_SETTING = `${EDITOR_SETTING}.fontSize`;
|
||||||
|
export const AUTO_SAVE_SETTING = `${EDITOR_SETTING}.autoSave`;
|
||||||
|
export const QUICK_SUGGESTIONS_SETTING = `${EDITOR_SETTING}.quickSuggestions`;
|
||||||
|
export const ARDUINO_SETTING = 'arduino';
|
||||||
|
export const WINDOW_SETTING = `${ARDUINO_SETTING}.window`;
|
||||||
|
export const COMPILE_SETTING = `${ARDUINO_SETTING}.compile`;
|
||||||
|
export const UPLOAD_SETTING = `${ARDUINO_SETTING}.upload`;
|
||||||
|
export const SKETCHBOOK_SETTING = `${ARDUINO_SETTING}.sketchbook`;
|
||||||
|
export const AUTO_SCALE_SETTING = `${WINDOW_SETTING}.autoScale`;
|
||||||
|
export const ZOOM_LEVEL_SETTING = `${WINDOW_SETTING}.zoomLevel`;
|
||||||
|
export const COMPILE_VERBOSE_SETTING = `${COMPILE_SETTING}.verbose`;
|
||||||
|
export const COMPILE_WARNINGS_SETTING = `${COMPILE_SETTING}.warnings`;
|
||||||
|
export const UPLOAD_VERBOSE_SETTING = `${UPLOAD_SETTING}.verbose`;
|
||||||
|
export const UPLOAD_VERIFY_SETTING = `${UPLOAD_SETTING}.verify`;
|
||||||
|
export const SHOW_ALL_FILES_SETTING = `${SKETCHBOOK_SETTING}.showAllFiles`;
|
||||||
|
|
||||||
|
export interface Settings extends Index {
|
||||||
|
editorFontSize: number; // `editor.fontSize`
|
||||||
|
themeId: string; // `workbench.colorTheme`
|
||||||
|
autoSave: 'on' | 'off'; // `editor.autoSave`
|
||||||
|
quickSuggestions: Record<'other' | 'comments' | 'strings', boolean>; // `editor.quickSuggestions`
|
||||||
|
|
||||||
|
languages: string[]; // `languages from the plugins`
|
||||||
|
currentLanguage: string;
|
||||||
|
|
||||||
|
autoScaleInterface: boolean; // `arduino.window.autoScale`
|
||||||
|
interfaceScale: number; // `arduino.window.zoomLevel` https://github.com/eclipse-theia/theia/issues/8751
|
||||||
|
verboseOnCompile: boolean; // `arduino.compile.verbose`
|
||||||
|
compilerWarnings: CompilerWarnings; // `arduino.compile.warnings`
|
||||||
|
verboseOnUpload: boolean; // `arduino.upload.verbose`
|
||||||
|
verifyAfterUpload: boolean; // `arduino.upload.verify`
|
||||||
|
sketchbookShowAllFiles: boolean; // `arduino.sketchbook.showAllFiles`
|
||||||
|
|
||||||
|
sketchbookPath: string; // CLI
|
||||||
|
additionalUrls: string[]; // CLI
|
||||||
|
network: Network; // CLI
|
||||||
|
}
|
||||||
|
export namespace Settings {
|
||||||
|
export function belongsToCli<K extends keyof Settings>(key: K): boolean {
|
||||||
|
return key === 'sketchbookPath' || key === 'additionalUrls';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@injectable()
|
||||||
|
export class SettingsService {
|
||||||
|
@inject(FileService)
|
||||||
|
protected readonly fileService: FileService;
|
||||||
|
|
||||||
|
@inject(FileSystemExt)
|
||||||
|
protected readonly fileSystemExt: FileSystemExt;
|
||||||
|
|
||||||
|
@inject(ConfigService)
|
||||||
|
protected readonly configService: ConfigService;
|
||||||
|
|
||||||
|
@inject(PreferenceService)
|
||||||
|
protected readonly preferenceService: PreferenceService;
|
||||||
|
|
||||||
|
@inject(FrontendApplicationStateService)
|
||||||
|
protected readonly appStateService: FrontendApplicationStateService;
|
||||||
|
|
||||||
|
@inject(AsyncLocalizationProvider)
|
||||||
|
protected readonly localizationProvider: AsyncLocalizationProvider;
|
||||||
|
|
||||||
|
protected readonly onDidChangeEmitter = new Emitter<Readonly<Settings>>();
|
||||||
|
readonly onDidChange = this.onDidChangeEmitter.event;
|
||||||
|
|
||||||
|
protected ready = new Deferred<void>();
|
||||||
|
protected _settings: Settings;
|
||||||
|
|
||||||
|
@postConstruct()
|
||||||
|
protected async init(): Promise<void> {
|
||||||
|
const settings = await this.loadSettings();
|
||||||
|
this._settings = deepClone(settings);
|
||||||
|
this.ready.resolve();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected async loadSettings(): Promise<Settings> {
|
||||||
|
await this.preferenceService.ready;
|
||||||
|
const [
|
||||||
|
languages,
|
||||||
|
currentLanguage,
|
||||||
|
editorFontSize,
|
||||||
|
themeId,
|
||||||
|
autoSave,
|
||||||
|
quickSuggestions,
|
||||||
|
autoScaleInterface,
|
||||||
|
interfaceScale,
|
||||||
|
verboseOnCompile,
|
||||||
|
compilerWarnings,
|
||||||
|
verboseOnUpload,
|
||||||
|
verifyAfterUpload,
|
||||||
|
sketchbookShowAllFiles,
|
||||||
|
cliConfig,
|
||||||
|
] = await Promise.all([
|
||||||
|
['en', ...(await this.localizationProvider.getAvailableLanguages())],
|
||||||
|
this.localizationProvider.getCurrentLanguage(),
|
||||||
|
this.preferenceService.get<number>(FONT_SIZE_SETTING, 12),
|
||||||
|
this.preferenceService.get<string>(
|
||||||
|
'workbench.colorTheme',
|
||||||
|
'arduino-theme'
|
||||||
|
),
|
||||||
|
this.preferenceService.get<'on' | 'off'>(AUTO_SAVE_SETTING, 'on'),
|
||||||
|
this.preferenceService.get<
|
||||||
|
Record<'other' | 'comments' | 'strings', boolean>
|
||||||
|
>(QUICK_SUGGESTIONS_SETTING, {
|
||||||
|
other: false,
|
||||||
|
comments: false,
|
||||||
|
strings: false,
|
||||||
|
}),
|
||||||
|
this.preferenceService.get<boolean>(AUTO_SCALE_SETTING, true),
|
||||||
|
this.preferenceService.get<number>(ZOOM_LEVEL_SETTING, 0),
|
||||||
|
this.preferenceService.get<boolean>(COMPILE_VERBOSE_SETTING, true),
|
||||||
|
this.preferenceService.get<any>(COMPILE_WARNINGS_SETTING, 'None'),
|
||||||
|
this.preferenceService.get<boolean>(UPLOAD_VERBOSE_SETTING, true),
|
||||||
|
this.preferenceService.get<boolean>(UPLOAD_VERIFY_SETTING, true),
|
||||||
|
this.preferenceService.get<boolean>(SHOW_ALL_FILES_SETTING, false),
|
||||||
|
this.configService.getConfiguration(),
|
||||||
|
]);
|
||||||
|
const { additionalUrls, sketchDirUri, network } = cliConfig;
|
||||||
|
const sketchbookPath = await this.fileService.fsPath(new URI(sketchDirUri));
|
||||||
|
return {
|
||||||
|
editorFontSize,
|
||||||
|
themeId,
|
||||||
|
languages,
|
||||||
|
currentLanguage,
|
||||||
|
autoSave,
|
||||||
|
quickSuggestions,
|
||||||
|
autoScaleInterface,
|
||||||
|
interfaceScale,
|
||||||
|
verboseOnCompile,
|
||||||
|
compilerWarnings,
|
||||||
|
verboseOnUpload,
|
||||||
|
verifyAfterUpload,
|
||||||
|
sketchbookShowAllFiles,
|
||||||
|
additionalUrls,
|
||||||
|
sketchbookPath,
|
||||||
|
network,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async settings(): Promise<Settings> {
|
||||||
|
await this.ready.promise;
|
||||||
|
return this._settings;
|
||||||
|
}
|
||||||
|
|
||||||
|
async update(settings: Settings, fireDidChange = false): Promise<void> {
|
||||||
|
await this.ready.promise;
|
||||||
|
for (const key of Object.keys(settings)) {
|
||||||
|
this._settings[key] = settings[key];
|
||||||
|
}
|
||||||
|
if (fireDidChange) {
|
||||||
|
this.onDidChangeEmitter.fire(this._settings);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async reset(): Promise<void> {
|
||||||
|
const settings = await this.loadSettings();
|
||||||
|
return this.update(settings, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
async validate(
|
||||||
|
settings: MaybePromise<Settings> = this.settings()
|
||||||
|
): Promise<string | true> {
|
||||||
|
try {
|
||||||
|
const { sketchbookPath, editorFontSize, themeId } = await settings;
|
||||||
|
const sketchbookDir = await this.fileSystemExt.getUri(sketchbookPath);
|
||||||
|
if (!(await this.fileService.exists(new URI(sketchbookDir)))) {
|
||||||
|
return nls.localize(
|
||||||
|
'arduino/preferences/invalid.sketchbook.location',
|
||||||
|
'Invalid sketchbook location: {0}',
|
||||||
|
sketchbookPath
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (editorFontSize <= 0) {
|
||||||
|
return nls.localize(
|
||||||
|
'arduino/preferences/invalid.editorFontSize',
|
||||||
|
'Invalid editor font size. It must be a positive integer.'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
!ThemeService.get()
|
||||||
|
.getThemes()
|
||||||
|
.find(({ id }) => id === themeId)
|
||||||
|
) {
|
||||||
|
return nls.localize(
|
||||||
|
'arduino/preferences/invalid.theme',
|
||||||
|
'Invalid theme.'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof Error) {
|
||||||
|
return err.message;
|
||||||
|
}
|
||||||
|
return String(err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async savePreference(name: string, value: unknown): Promise<void> {
|
||||||
|
await this.preferenceService.set(name, value, PreferenceScope.User);
|
||||||
|
await timeout(5);
|
||||||
|
}
|
||||||
|
|
||||||
|
async save(): Promise<string | true> {
|
||||||
|
await this.ready.promise;
|
||||||
|
const {
|
||||||
|
currentLanguage,
|
||||||
|
editorFontSize,
|
||||||
|
themeId,
|
||||||
|
autoSave,
|
||||||
|
quickSuggestions,
|
||||||
|
autoScaleInterface,
|
||||||
|
interfaceScale,
|
||||||
|
verboseOnCompile,
|
||||||
|
compilerWarnings,
|
||||||
|
verboseOnUpload,
|
||||||
|
verifyAfterUpload,
|
||||||
|
sketchbookPath,
|
||||||
|
additionalUrls,
|
||||||
|
network,
|
||||||
|
sketchbookShowAllFiles,
|
||||||
|
} = this._settings;
|
||||||
|
const [config, sketchDirUri] = await Promise.all([
|
||||||
|
this.configService.getConfiguration(),
|
||||||
|
this.fileSystemExt.getUri(sketchbookPath),
|
||||||
|
]);
|
||||||
|
(config as any).additionalUrls = additionalUrls;
|
||||||
|
(config as any).sketchDirUri = sketchDirUri;
|
||||||
|
(config as any).network = network;
|
||||||
|
(config as any).locale = currentLanguage;
|
||||||
|
|
||||||
|
await this.savePreference('editor.fontSize', editorFontSize);
|
||||||
|
await this.savePreference('workbench.colorTheme', themeId);
|
||||||
|
await this.savePreference('editor.autoSave', autoSave);
|
||||||
|
await this.savePreference('editor.quickSuggestions', quickSuggestions);
|
||||||
|
await this.savePreference(AUTO_SCALE_SETTING, autoScaleInterface);
|
||||||
|
await this.savePreference(ZOOM_LEVEL_SETTING, interfaceScale);
|
||||||
|
await this.savePreference(ZOOM_LEVEL_SETTING, interfaceScale);
|
||||||
|
await this.savePreference(COMPILE_VERBOSE_SETTING, verboseOnCompile);
|
||||||
|
await this.savePreference(COMPILE_WARNINGS_SETTING, compilerWarnings);
|
||||||
|
await this.savePreference(UPLOAD_VERBOSE_SETTING, verboseOnUpload);
|
||||||
|
await this.savePreference(UPLOAD_VERIFY_SETTING, verifyAfterUpload);
|
||||||
|
await this.savePreference(SHOW_ALL_FILES_SETTING, sketchbookShowAllFiles);
|
||||||
|
await this.configService.setConfiguration(config);
|
||||||
|
this.onDidChangeEmitter.fire(this._settings);
|
||||||
|
|
||||||
|
// after saving all the settings, if we need to change the language we need to perform a reload
|
||||||
|
// Only reload if the language differs from the current locale. `nls.locale === undefined` signals english as well
|
||||||
|
if (currentLanguage !== nls.locale && !(currentLanguage === 'en' && nls.locale === undefined)) {
|
||||||
|
if (currentLanguage === 'en') {
|
||||||
|
window.localStorage.removeItem(nls.localeId);
|
||||||
|
} else {
|
||||||
|
window.localStorage.setItem(nls.localeId, currentLanguage);
|
||||||
|
}
|
||||||
|
window.location.reload();
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
import * as React from 'react';
|
||||||
|
import { BoardUserField } from '../../../common/protocol';
|
||||||
|
import { nls } from '@theia/core/lib/common';
|
||||||
|
|
||||||
|
export const UserFieldsComponent = ({
|
||||||
|
initialBoardUserFields,
|
||||||
|
updateUserFields,
|
||||||
|
cancel,
|
||||||
|
accept,
|
||||||
|
}: {
|
||||||
|
initialBoardUserFields: BoardUserField[];
|
||||||
|
updateUserFields: (userFields: BoardUserField[]) => void;
|
||||||
|
cancel: () => void;
|
||||||
|
accept: () => Promise<void>;
|
||||||
|
}): React.ReactElement => {
|
||||||
|
const [boardUserFields, setBoardUserFields] = React.useState<
|
||||||
|
BoardUserField[]
|
||||||
|
>(initialBoardUserFields);
|
||||||
|
|
||||||
|
const [uploadButtonDisabled, setUploadButtonDisabled] =
|
||||||
|
React.useState<boolean>(true);
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
setBoardUserFields(initialBoardUserFields);
|
||||||
|
}, [initialBoardUserFields]);
|
||||||
|
|
||||||
|
const updateUserField =
|
||||||
|
(index: number) => (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const newBoardUserFields = [...boardUserFields];
|
||||||
|
newBoardUserFields[index].value = e.target.value;
|
||||||
|
setBoardUserFields(newBoardUserFields);
|
||||||
|
};
|
||||||
|
|
||||||
|
const allFieldsHaveValues = (userFields: BoardUserField[]): boolean => {
|
||||||
|
return (
|
||||||
|
userFields &&
|
||||||
|
userFields.length > 0 &&
|
||||||
|
userFields
|
||||||
|
.map<boolean>((field: BoardUserField): boolean => {
|
||||||
|
return field.value.length > 0;
|
||||||
|
})
|
||||||
|
.reduce((previous: boolean, current: boolean): boolean => {
|
||||||
|
return previous && current;
|
||||||
|
})
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
updateUserFields(boardUserFields);
|
||||||
|
setUploadButtonDisabled(!allFieldsHaveValues(boardUserFields));
|
||||||
|
}, [boardUserFields]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div className="user-fields-container">
|
||||||
|
<div className="user-fields-list">
|
||||||
|
{boardUserFields.map((field, index) => {
|
||||||
|
return (
|
||||||
|
<div className="dialogSection" key={index}>
|
||||||
|
<div className="dialogRow">
|
||||||
|
<label className="field-label">{field.label}</label>
|
||||||
|
</div>
|
||||||
|
<div className="dialogRow">
|
||||||
|
<input
|
||||||
|
type={field.secret ? 'password' : 'text'}
|
||||||
|
value={field.value}
|
||||||
|
className="theia-input"
|
||||||
|
placeholder={'Enter ' + field.label}
|
||||||
|
onChange={updateUserField(index)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="dialogSection">
|
||||||
|
<div className="dialogRow button-container">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="theia-button secondary install-cert-btn"
|
||||||
|
onClick={cancel}
|
||||||
|
>
|
||||||
|
{nls.localize('arduino/userFields/cancel', 'Cancel')}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="theia-button primary install-cert-btn"
|
||||||
|
disabled={uploadButtonDisabled}
|
||||||
|
onClick={accept}
|
||||||
|
>
|
||||||
|
{nls.localize('arduino/userFields/upload', 'Upload')}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user