Author SHA1 Message Date
vcoppe 45f877ec78 route export, filter out anchors at high zoom level 2026-10-26 19:27:12 +01:00
vcoppe 0f957fb1f2 create route file action 2026-10-26 19:22:14 +01:00
vcoppe 764d0b233a route - track conversion 2026-10-26 19:06:19 +01:00
vcoppe b6c0f5190a route full support 2026-10-26 18:51:56 +01:00
vcoppe c842da8dc1 reorder context menu items 2026-10-18 19:09:06 +02:00
vcoppe 5bc35f30d9 strip native menu 2026-10-18 18:43:12 +02:00
vcoppe 873e2e1654 Merge branch 'dev' into tauri 2026-10-18 18:15:37 +02:00
vcoppe 6c2d2879f4 use new endpoint for openhikingmap 2026-10-18 17:20:09 +02:00
vcoppe f5670cdd8e remove custom ign styles 2026-10-18 17:14:50 +02:00
vcoppe 741d35db1e sparse desktop build 2026-10-18 16:53:39 +02:00
vcoppe 6556c29492 fix 2026-10-18 16:38:59 +02:00
vcoppe 7fa850e4c8 fix routing control size 2026-10-18 16:34:03 +02:00
vcoppe f9e8d4c644 show popup once data is loaded 2026-10-18 16:27:51 +02:00
vcoppe a07da16163 sparser data transfers 2026-10-18 16:20:32 +02:00
vcoppe 4583874e7e sparser data transfers 2026-10-18 12:35:32 +02:00
vcoppe 48325e6016 performance improvements 2026-10-18 10:50:34 +02:00
vcoppe 9033401094 improved preview 2026-10-18 09:32:18 +02:00
vcoppe b64c192c4f consistent highlight color 2026-10-18 09:17:01 +02:00
vcoppe 9dd4af98a5 small fix 2026-10-18 09:09:00 +02:00
vcoppe 05510ece92 full screen 2026-10-18 00:38:53 +02:00
vcoppe 8bbcbdc097 remove focus-ring 2026-10-18 00:33:03 +02:00
vcoppe 3012f6bf73 fixes 2026-10-18 00:24:16 +02:00
vcoppe 5373d0f0d4 cleaning 2026-10-17 23:55:46 +02:00
vcoppe 8fd47d8b18 drop anywhere in folder 2026-10-17 23:39:44 +02:00
vcoppe a5c1f6ad33 fix folder styling 2026-10-17 23:35:56 +02:00
vcoppe 3ef2bf135a explorer actions 2026-10-17 23:23:29 +02:00
vcoppe adbf89e318 clarify filename 2026-10-17 22:17:17 +02:00
vcoppe 11709316d2 avoid selecting on resize 2026-10-17 20:02:09 +02:00
vcoppe d52b61f707 commit missing changes 2026-10-17 20:01:59 +02:00
vcoppe 358253b7a9 open links in browser 2026-10-17 19:57:50 +02:00
vcoppe 8d6885d58b remember language 2026-10-17 19:36:57 +02:00
vcoppe 128338aa05 fix sorting 2026-10-17 19:10:50 +02:00
vcoppe c84e1c9a06 fix routing on other file 2026-10-17 19:03:33 +02:00
vcoppe 9f49119eec no file delete on desktop 2026-10-17 18:57:40 +02:00
vcoppe 67a47cf065 fix tab size 2026-10-17 18:50:23 +02:00
vcoppe e57949dc01 fix 2026-10-17 18:33:50 +02:00
vcoppe da92fd15d2 fix sortable 2026-10-17 18:28:32 +02:00
vcoppe 01443943b3 fix sortable 2026-10-17 17:21:56 +02:00
vcoppe 970cf7d1e1 improved sticky folders 2026-10-17 16:39:41 +02:00
vcoppe 593b43e433 sticky folders 2026-10-17 16:24:19 +02:00
vcoppe 8fa88680b3 fix 2026-10-17 16:17:45 +02:00
vcoppe b2495d1466 progress 2026-10-17 16:14:17 +02:00
vcoppe ed90ba6a1f file explorer 2026-10-17 14:42:49 +02:00
vcoppe b0a3c3a9ba progress 2026-10-16 18:14:59 +02:00
vcoppe 005cc7b305 fix 2026-10-16 09:05:45 +02:00
vcoppe 1bfd319758 use history variant 2026-10-16 09:02:31 +02:00
vcoppe 187296a277 keep original flag 2026-10-16 08:54:40 +02:00
vcoppe 55a8b020e0 per file history 2026-10-16 08:42:45 +02:00
vcoppe 1ba5436af3 progress 2026-10-14 19:15:02 +02:00
vcoppe 2e1ca00afa fix 2026-10-14 09:41:07 +02:00
vcoppe 97d597e139 progress 2026-10-14 09:22:07 +02:00
vcoppe 41b9116c6a progress 2026-10-14 08:51:38 +02:00
vcoppe ce8398f749 renaming 2026-10-14 08:17:51 +02:00
vcoppe 3c2055b50e improve flow 2026-10-14 08:07:58 +02:00
vcoppe 1d13972014 fix 2026-10-11 11:19:57 +02:00
vcoppe 890bcd765a refactoring 2026-10-11 11:18:36 +02:00
vcoppe 4795513344 reorder methods 2026-10-11 10:58:15 +02:00
vcoppe d84ca47745 refactoring 2026-10-11 10:54:06 +02:00
vcoppe 9adb8e7221 outdated state 2026-10-11 10:48:43 +02:00
vcoppe a2b4d89150 cross-tab sync 2026-10-10 11:07:07 +02:00
vcoppe 77929cfa04 per-chunk categories storage 2026-10-09 17:55:07 +02:00
vcoppe dc36de2a48 import and export of routes, ref #192 2026-10-09 09:26:38 +02:00
vcoppe da9abbae5e refactoring and tests 2026-10-09 08:58:00 +02:00
vcoppe 3bb553d6b5 remove unused fields 2026-10-08 21:19:53 +02:00
vcoppe 83b76bb838 fix link fields 2026-10-08 21:13:44 +02:00
vcoppe 42a55e6759 progress 2026-10-08 21:04:29 +02:00
vcoppe b085a1d476 cleaning 2026-10-08 19:04:46 +02:00
vcoppe 840e943626 update readme 2026-10-08 18:41:27 +02:00
vcoppe 16e2e0f679 remove todo 2026-10-08 18:37:46 +02:00
vcoppe 0f9557ea82 remove gpx js package 2026-10-08 18:37:40 +02:00
vcoppe 67a4c090bd progress 2026-10-08 18:34:19 +02:00
vcoppe 606a0e974a export 2026-10-08 09:24:15 +02:00
vcoppe e8c4eb92f9 handle corrupt time data 2026-10-08 08:59:53 +02:00
vcoppe f0851086c0 fix reactivity 2026-10-08 08:47:14 +02:00
vcoppe bec1ce4c9b reduce 2026-10-08 08:36:29 +02:00
vcoppe b29c4cdb08 fix bounds for waypoints 2026-10-08 08:15:22 +02:00
vcoppe 63ba8596a7 time tool 2026-10-08 08:12:44 +02:00
vcoppe 82d2f79da0 progress 2026-10-07 22:20:40 +02:00
vcoppe f642d60f42 merge 2026-10-07 19:57:27 +02:00
vcoppe 24b877c4ee split 2026-10-07 19:38:21 +02:00
vcoppe e07ec97e12 crop 2026-10-07 18:54:00 +02:00
vcoppe 290f4d8c44 reverse 2026-10-07 18:45:56 +02:00
vcoppe a48608840f reverse 2026-10-07 18:36:00 +02:00
vcoppe df07892e76 refactoring 2026-10-07 18:22:30 +02:00
vcoppe 594dd8979a routing 2026-10-07 17:58:17 +02:00
vcoppe 29850c1c8f speed fix 2026-10-07 09:35:27 +02:00
vcoppe adbe4a2693 copy on wasm side to avoid any data corruption 2026-10-07 08:57:37 +02:00
vcoppe b843a18441 reduce data exchanges across boundary 2026-10-07 08:45:50 +02:00
vcoppe da8a9e3d84 handle self closing elements 2026-10-04 22:01:23 +02:00
vcoppe c6bd5b06e8 clean tool 2026-10-04 20:38:46 +02:00
vcoppe c04367dd86 progress 2026-10-04 19:19:53 +02:00
vcoppe 5e2f506120 progress 2026-10-04 19:14:41 +02:00
vcoppe c536e6247b progress 2026-10-04 17:29:57 +02:00
vcoppe 594d714b7f small fix 2026-10-04 17:19:35 +02:00
vcoppe 543fecadb8 fix popups 2026-10-04 17:09:41 +02:00
vcoppe 017d8521d6 use engine info 2026-10-04 16:27:03 +02:00
vcoppe 78e9d45072 small fix 2026-10-04 16:21:48 +02:00
vcoppe 7651d859c4 progress 2026-10-04 16:11:44 +02:00
vcoppe ec448b72e2 progress 2026-10-04 15:47:09 +02:00
vcoppe bf946f179a progress 2026-10-04 15:26:58 +02:00
vcoppe 9ff9b5475a progress 2026-10-04 15:03:37 +02:00
vcoppe 55f1d275b7 progress 2026-10-04 14:49:53 +02:00
vcoppe 1d534881f8 progress 2026-10-04 13:18:18 +02:00
vcoppe 03cbacfbb4 fix 2026-10-04 12:33:15 +02:00
vcoppe 9d0905959b fix markers 2026-10-04 12:23:42 +02:00
vcoppe b7ca462f58 progress 2026-10-04 11:52:46 +02:00
vcoppe 9015da4876 fixes 2026-10-04 11:07:12 +02:00
vcoppe f458a1104f progress 2026-10-04 11:00:46 +02:00
vcoppe caba9388af progress 2026-10-04 10:29:39 +02:00
vcoppe 763a7406ce progress 2026-10-04 10:15:51 +02:00
vcoppe 68c8933c35 progress 2026-10-04 09:55:08 +02:00
vcoppe 84b1558b2e progress 2026-10-04 09:50:34 +02:00
vcoppe cd870f0186 visibility 2026-10-04 09:40:17 +02:00
vcoppe 9ac2a2b69c progress 2026-10-04 08:53:00 +02:00
vcoppe 86aba8f4b1 progress 2026-10-04 08:26:15 +02:00
vcoppe 74b674e8e8 progress 2026-10-04 08:21:39 +02:00
vcoppe f1904bc12f cleaning 2026-10-03 20:54:05 +02:00
vcoppe 9afba53e5d progress 2026-10-03 19:50:38 +02:00
vcoppe fd76e0fa46 progress 2026-10-03 19:17:58 +02:00
vcoppe 438a87f06f progress 2026-10-03 19:08:56 +02:00
vcoppe a994e16f51 splice 2026-10-03 18:03:13 +02:00
vcoppe 639e7491eb merge methods into 1 2026-10-03 17:47:04 +02:00
vcoppe 891a08a3cc progress 2026-10-03 17:42:26 +02:00
vcoppe 0c07164dec remove (copy) in name 2026-10-03 17:26:53 +02:00
vcoppe f133d55889 progress 2026-10-03 17:21:16 +02:00
vcoppe fbb636cb06 progress 2026-10-03 16:52:21 +02:00
vcoppe bddceb28aa keep style info 2026-10-03 16:43:53 +02:00
vcoppe bff84fa24c progress 2026-10-03 16:40:17 +02:00
vcoppe 64914f9aa0 progress 2026-10-03 16:16:47 +02:00
vcoppe 2abf46c747 progress 2026-10-03 15:33:44 +02:00
vcoppe 888f41e979 refactoring 2026-10-03 13:56:16 +02:00
vcoppe 17533586ef progress 2026-10-03 13:41:58 +02:00
vcoppe c6ad088947 fix 2026-10-03 13:40:49 +02:00
vcoppe 87d6d5f30e change type 2026-10-03 11:49:10 +02:00
vcoppe dbe894b3a3 reorganize 2026-10-03 10:03:22 +02:00
vcoppe a921d4b9cd fixes 2026-10-02 18:50:10 +02:00
vcoppe b7db73cf77 progress 2026-10-02 18:06:45 +02:00
vcoppe 5868595a6c progress 2026-10-01 18:42:31 +02:00
vcoppe eb8e09b835 progress 2026-09-30 19:19:23 +02:00
vcoppe 41dc853f65 progress 2026-09-25 12:09:58 +02:00
vcoppe 27c0a57cc1 progress 2026-09-24 20:55:30 +02:00
vcoppe 497ac120ec progress 2026-09-23 19:53:39 +02:00
vcoppe a486016d96 progress 2026-09-21 23:49:57 +02:00
vcoppe cc5f5653ef progress 2026-09-20 13:58:27 +02:00
vcoppe 20222c450d parsing continued 2026-09-18 09:50:04 +02:00
vcoppe 69049e1345 parsing start 2026-09-18 09:03:51 +02:00
vcoppe ed6264444f wasm first steps 2026-07-14 18:36:30 +02:00
490 changed files with 3871 additions and 10124 deletions

No files matched your search

+29 -21
View File
@@ -1,21 +1,11 @@
name: Deploy to Cloudflare Pages
name: Deploy to GitHub Pages
on:
push:
branches: ['main', 'dev']
workflow_dispatch:
concurrency:
group: cloudflare-${{ github.ref }}
cancel-in-progress: true
branches: 'main'
jobs:
deploy:
build_site:
runs-on: ubuntu-latest
permissions:
contents: read
deployments: write
steps:
- name: Checkout
uses: actions/checkout@v5
@@ -51,17 +41,35 @@ jobs:
run: npm test --prefix website
- name: Create env file
run: echo PUBLIC_MAPTILER_KEY=${{ secrets.PUBLIC_MAPTILER_KEY }} >> website/.env
run: |
touch website/.env
echo PUBLIC_MAPTILER_KEY=${{ secrets.PUBLIC_MAPTILER_KEY }} >> website/.env
cat website/.env
- name: Build website
env:
BASE_PATH: ''
run: npm run build --prefix website
run: |
npm run build --prefix website
- name: Deploy to Cloudflare Pages
uses: cloudflare/wrangler-action@v3
- name: Upload Artifacts
uses: actions/upload-pages-artifact@v4
with:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
command: pages deploy website/build --project-name=${{ vars.CLOUDFLARE_PROJECT_NAME || 'gpxstudio' }} --branch=${{ github.ref_name }} --commit-dirty=true
gitHubToken: ${{ secrets.GITHUB_TOKEN }}
path: 'website/build/'
deploy:
needs: build_site
runs-on: ubuntu-latest
permissions:
pages: write
id-token: write
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- name: Deploy
id: deployment
uses: actions/deploy-pages@v4
-214
View File
@@ -1,214 +0,0 @@
name: Desktop release
# run by hand: from `main` for a release, from `dev` for a pre-release
on:
workflow_dispatch:
concurrency:
group: desktop-${{ github.ref }}
jobs:
# the release stays a draft until every platform is built and tested
prepare:
runs-on: ubuntu-latest
permissions:
contents: write
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
outputs:
version: ${{ steps.version.outputs.version }}
draft_tag: ${{ steps.version.outputs.draft_tag }}
release_id: ${{ steps.draft.outputs.release_id }}
steps:
- name: Checkout
uses: actions/checkout@v5
- name: Choose version
id: version
run: |
base=$(jq -r .version tauri/tauri.conf.json)
if [[ ! "$base" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "::error::The version in tauri.conf.json should be x.y.z, not $base"
exit 1
fi
case "$GITHUB_REF_NAME" in
main)
version=$base
draft_tag=desktop-v$base
if git ls-remote --exit-code --tags origin "refs/tags/$draft_tag"; then
echo "::error::$draft_tag is already released: bump the version in tauri.conf.json"
exit 1
fi
if [ -z "$(jq -r '.plugins.updater.pubkey' tauri/tauri.conf.json)" ]; then
echo "::error::The public key of the updater is missing from tauri.conf.json"
exit 1
fi
;;
dev)
version=$base-beta.$GITHUB_RUN_NUMBER
draft_tag=desktop-beta-$GITHUB_RUN_NUMBER
;;
*)
echo "::error::Desktop builds are made from main or dev, not $GITHUB_REF_NAME"
exit 1
;;
esac
echo "version=$version" >> "$GITHUB_OUTPUT"
echo "draft_tag=$draft_tag" >> "$GITHUB_OUTPUT"
- name: Create draft release
id: draft
env:
VERSION: ${{ steps.version.outputs.version }}
DRAFT_TAG: ${{ steps.version.outputs.draft_tag }}
run: |
# what a previous attempt left: this tag is not released, so it can only be a draft
gh release delete "$DRAFT_TAG" --yes || true
if [ "$GITHUB_REF_NAME" = main ]; then
gh release create "$DRAFT_TAG" --draft --target "$GITHUB_SHA" \
--title "Desktop $VERSION" --generate-notes
else
gh release create "$DRAFT_TAG" --draft --prerelease --target "$GITHUB_SHA" \
--title "Desktop beta $VERSION" \
--notes "Beta of the desktop app, built from $GITHUB_SHA on the dev branch. The builds are not signed yet: macOS and Windows will warn before opening them."
fi
echo "release_id=$(gh release view "$DRAFT_TAG" --json databaseId --jq .databaseId)" >> "$GITHUB_OUTPUT"
build:
needs: prepare
strategy:
fail-fast: false
matrix:
include:
- platform: macos-latest
rust_targets: aarch64-apple-darwin,x86_64-apple-darwin,wasm32-unknown-unknown
args: --target universal-apple-darwin
# the oldest supported Ubuntu, so that the AppImage runs on older systems too
- platform: ubuntu-22.04
rust_targets: wasm32-unknown-unknown
args: ''
- platform: windows-latest
rust_targets: wasm32-unknown-unknown
args: ''
runs-on: ${{ matrix.platform }}
permissions:
contents: write
steps:
- name: Checkout
uses: actions/checkout@v5
- name: Install Linux dependencies
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf
- name: Install Node.js
uses: actions/setup-node@v6
with:
node-version: 24
cache: npm
cache-dependency-path: website/package-lock.json
- name: Install Rust
uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.rust_targets }}
- name: Cache Rust build
uses: Swatinem/rust-cache@v2
- name: Install wasm-pack
uses: taiki-e/install-action@v2
with:
tool: wasm-pack
# the desktop app does not use it, but the website depends on its package
- name: Build wasm
run: wasm-pack build --target bundler
working-directory: wasm
- name: Install dependencies for website
run: npm install --prefix website
# the key would be readable in the app: it is left empty, so only the MapTiler layer fails
- name: Create env file
run: echo "PUBLIC_MAPTILER_KEY=" >> website/.env
# only the releases update themselves: they need the updater files, and the signing key
- name: Set version and updater files
shell: bash
env:
VERSION: ${{ needs.prepare.outputs.version }}
UPDATER: ${{ github.ref_name == 'main' }}
run: |
node -e "
const fs = require('fs');
const path = 'tauri/tauri.conf.json';
const config = JSON.parse(fs.readFileSync(path));
config.version = process.env.VERSION;
config.bundle.createUpdaterArtifacts = process.env.UPDATER === 'true';
fs.writeFileSync(path, JSON.stringify(config, null, 4));
"
- name: Build app and upload it to the draft
uses: tauri-apps/tauri-action@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_SIGNING_PRIVATE_KEY: ${{ github.ref_name == 'main' && secrets.TAURI_SIGNING_PRIVATE_KEY || '' }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ github.ref_name == 'main' && secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD || '' }}
with:
projectPath: tauri
tauriScript: npx --yes @tauri-apps/cli@2
args: ${{ matrix.args }}
releaseId: ${{ needs.prepare.outputs.release_id }}
# given with the id for the addresses in `latest.json`
tagName: ${{ needs.prepare.outputs.draft_tag }}
uploadUpdaterJson: ${{ github.ref_name == 'main' }}
# after the build, which gives the app the website it embeds
- name: Test engine and app
run: cargo test -p gpx-engine -p gpx-studio-desktop
# `releases/latest`, which the updater reads, only changes here
publish:
needs: [prepare, build]
runs-on: ubuntu-latest
permissions:
contents: write
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
DRAFT_TAG: ${{ needs.prepare.outputs.draft_tag }}
steps:
# the builds of the platforms add themselves to it in parallel, and could overwrite each other
- name: Check updater file
if: github.ref_name == 'main'
run: |
gh release download "$DRAFT_TAG" --pattern latest.json
for platform in darwin-aarch64 darwin-x86_64 linux-x86_64 windows-x86_64; do
if ! jq -e --arg platform "$platform" '.platforms[$platform].signature | length > 0' latest.json; then
echo "::error::latest.json has no signed update for $platform"
exit 1
fi
done
- name: Publish release
if: github.ref_name == 'main'
run: gh release edit "$DRAFT_TAG" --draft=false --latest
- name: Replace beta release
if: github.ref_name == 'dev'
run: |
gh release delete desktop-beta --cleanup-tag --yes || true
gh release edit "$DRAFT_TAG" --tag desktop-beta --draft=false --prerelease --latest=false
Generated
+9 -516
View File
@@ -475,12 +475,6 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
[[package]]
name = "cfg_aliases"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
[[package]]
name = "chrono"
version = "0.4.45"
@@ -543,16 +537,6 @@ dependencies = [
"version_check",
]
[[package]]
name = "core-foundation"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]]
name = "core-foundation"
version = "0.10.1"
@@ -576,7 +560,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "064badf302c3194842cf2c5d61f56cc88e54a759313879cdf03abdd27d0c3b97"
dependencies = [
"bitflags 2.13.2",
"core-foundation 0.10.1",
"core-foundation",
"core-graphics-types",
"foreign-types",
"libc",
@@ -589,7 +573,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb"
dependencies = [
"bitflags 2.13.2",
"core-foundation 0.10.1",
"core-foundation",
"libc",
]
@@ -1036,16 +1020,6 @@ dependencies = [
"rustc_version",
]
[[package]]
name = "filetime"
version = "0.2.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759"
dependencies = [
"cfg-if",
"libc",
]
[[package]]
name = "find-msvc-tools"
version = "0.1.12"
@@ -1313,17 +1287,6 @@ dependencies = [
"version_check",
]
[[package]]
name = "getrandom"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
dependencies = [
"cfg-if",
"libc",
"wasi",
]
[[package]]
name = "getrandom"
version = "0.3.4"
@@ -1343,10 +1306,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
dependencies = [
"cfg-if",
"js-sys",
"libc",
"r-efi 6.0.0",
"wasm-bindgen",
]
[[package]]
@@ -1470,9 +1431,7 @@ dependencies = [
"tauri-build",
"tauri-plugin-dialog",
"tauri-plugin-opener",
"tauri-plugin-process",
"tauri-plugin-single-instance",
"tauri-plugin-updater",
"trash",
"uuid",
]
@@ -1672,21 +1631,6 @@ dependencies = [
"want",
]
[[package]]
name = "hyper-rustls"
version = "0.27.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53"
dependencies = [
"http",
"hyper",
"hyper-util",
"rustls",
"tokio",
"tokio-rustls",
"tower-service",
]
[[package]]
name = "hyper-util"
version = "0.1.21"
@@ -1706,11 +1650,9 @@ dependencies = [
"percent-encoding",
"pin-project-lite",
"socket2",
"system-configuration",
"tokio",
"tower-service",
"tracing",
"windows-registry",
]
[[package]]
@@ -2048,36 +1990,6 @@ dependencies = [
"windows-sys 0.45.0",
]
[[package]]
name = "jni"
version = "0.22.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498"
dependencies = [
"cfg-if",
"combine",
"jni-macros",
"jni-sys 0.4.1",
"log",
"simd_cesu8",
"thiserror 2.0.21",
"walkdir",
"windows-link",
]
[[package]]
name = "jni-macros"
version = "0.22.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3"
dependencies = [
"proc-macro2",
"quote",
"rustc_version",
"simd_cesu8",
"syn 2.0.118",
]
[[package]]
name = "jni-sys"
version = "0.3.1"
@@ -2302,12 +2214,6 @@ dependencies = [
"walkdir",
]
[[package]]
name = "minisign-verify"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "871285dc19d8d0ebe0eef3d0e99a205f2a71363b122632cbbfa4a6c370a960ce"
[[package]]
name = "miniz_oxide"
version = "0.8.9"
@@ -2397,18 +2303,6 @@ version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
[[package]]
name = "nix"
version = "0.31.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d"
dependencies = [
"bitflags 2.13.2",
"cfg-if",
"cfg_aliases",
"libc",
]
[[package]]
name = "notify"
version = "8.2.0"
@@ -2635,18 +2529,6 @@ dependencies = [
"objc2-core-foundation",
]
[[package]]
name = "objc2-osa-kit"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f112d1746737b0da274ef79a23aac283376f335f4095a083a267a082f21db0c0"
dependencies = [
"bitflags 2.13.2",
"objc2",
"objc2-app-kit",
"objc2-foundation",
]
[[package]]
name = "objc2-quartz-core"
version = "0.3.2"
@@ -2727,12 +2609,6 @@ dependencies = [
"libc",
]
[[package]]
name = "openssl-probe"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1"
[[package]]
name = "option-ext"
version = "0.2.0"
@@ -2749,20 +2625,6 @@ dependencies = [
"pin-project-lite",
]
[[package]]
name = "osakit"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "732c71caeaa72c065bb69d7ea08717bd3f4863a4f451402fc9513e29dbd5261b"
dependencies = [
"objc2",
"objc2-foundation",
"objc2-osa-kit",
"serde",
"serde_json",
"thiserror 2.0.21",
]
[[package]]
name = "pango"
version = "0.18.3"
@@ -3187,20 +3049,15 @@ dependencies = [
"http-body",
"http-body-util",
"hyper",
"hyper-rustls",
"hyper-util",
"js-sys",
"log",
"percent-encoding",
"pin-project-lite",
"rustls",
"rustls-pki-types",
"rustls-platform-verifier",
"serde",
"serde_json",
"sync_wrapper",
"tokio",
"tokio-rustls",
"tokio-util",
"tower",
"tower-http",
@@ -3236,20 +3093,6 @@ dependencies = [
"windows-sys 0.60.2",
]
[[package]]
name = "ring"
version = "0.17.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
dependencies = [
"cc",
"cfg-if",
"getrandom 0.2.17",
"libc",
"untrusted",
"windows-sys 0.52.0",
]
[[package]]
name = "rustc-hash"
version = "2.1.3"
@@ -3278,79 +3121,6 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "rustls"
version = "0.23.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
dependencies = [
"once_cell",
"ring",
"rustls-pki-types",
"rustls-webpki",
"subtle",
"zeroize",
]
[[package]]
name = "rustls-native-certs"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4"
dependencies = [
"openssl-probe",
"rustls-pki-types",
"schannel",
"security-framework",
]
[[package]]
name = "rustls-pki-types"
version = "1.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"
dependencies = [
"zeroize",
]
[[package]]
name = "rustls-platform-verifier"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98"
dependencies = [
"core-foundation 0.10.1",
"core-foundation-sys",
"jni 0.22.4",
"log",
"once_cell",
"rustls",
"rustls-native-certs",
"rustls-platform-verifier-android",
"rustls-webpki",
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.61.2",
]
[[package]]
name = "rustls-platform-verifier-android"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f"
[[package]]
name = "rustls-webpki"
version = "0.103.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281"
dependencies = [
"ring",
"rustls-pki-types",
"untrusted",
]
[[package]]
name = "rustversion"
version = "1.0.23"
@@ -3366,15 +3136,6 @@ dependencies = [
"winapi-util",
]
[[package]]
name = "schannel"
version = "0.1.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5"
dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "schemars"
version = "0.8.22"
@@ -3432,29 +3193,6 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "security-framework"
version = "3.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"
dependencies = [
"bitflags 2.13.2",
"core-foundation 0.10.1",
"core-foundation-sys",
"libc",
"security-framework-sys",
]
[[package]]
name = "security-framework-sys"
version = "2.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]]
name = "selectors"
version = "0.38.0"
@@ -3687,22 +3425,6 @@ version = "0.3.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
[[package]]
name = "simd_cesu8"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520"
dependencies = [
"rustc_version",
"simdutf8",
]
[[package]]
name = "simdutf8"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"
[[package]]
name = "siphasher"
version = "1.0.4"
@@ -3824,12 +3546,6 @@ version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "subtle"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "swift-rs"
version = "1.0.9"
@@ -3893,27 +3609,6 @@ dependencies = [
"syn 3.0.6",
]
[[package]]
name = "system-configuration"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b"
dependencies = [
"bitflags 2.13.2",
"core-foundation 0.9.4",
"system-configuration-sys",
]
[[package]]
name = "system-configuration-sys"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]]
name = "system-deps"
version = "6.2.2"
@@ -3935,7 +3630,7 @@ checksum = "f37f381f4e048e6cdf038b5705f8cf14ad108279d46eb968140a7b291aba9400"
dependencies = [
"bitflags 2.13.2",
"block2",
"core-foundation 0.10.1",
"core-foundation",
"core-graphics",
"crossbeam-channel",
"dbus",
@@ -3945,7 +3640,7 @@ dependencies = [
"gdkwayland-sys",
"gdkx11-sys",
"gtk",
"jni 0.21.1",
"jni",
"libc",
"log",
"ndk",
@@ -3978,17 +3673,6 @@ dependencies = [
"syn 2.0.118",
]
[[package]]
name = "tar"
version = "0.4.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840"
dependencies = [
"filetime",
"libc",
"xattr",
]
[[package]]
name = "target-lexicon"
version = "0.12.16"
@@ -4012,7 +3696,7 @@ dependencies = [
"gtk",
"heck 0.5.0",
"http",
"jni 0.21.1",
"jni",
"libc",
"log",
"mime",
@@ -4188,16 +3872,6 @@ dependencies = [
"zbus",
]
[[package]]
name = "tauri-plugin-process"
version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "74ae3d8549ae564c0397377373e262f340908eb23a5b9fbe03f2a00007dc0038"
dependencies = [
"tauri",
"tauri-plugin",
]
[[package]]
name = "tauri-plugin-single-instance"
version = "2.5.3"
@@ -4214,40 +3888,6 @@ dependencies = [
"zbus",
]
[[package]]
name = "tauri-plugin-updater"
version = "2.14.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d957abbcb3f9f6c76d22a3a0f012f30880640d0bccb5634d2b12a9937e4c872b"
dependencies = [
"base64 0.23.1",
"dirs",
"flate2",
"futures-util",
"http",
"infer",
"libc",
"log",
"minisign-verify",
"osakit",
"percent-encoding",
"reqwest",
"rustls",
"semver",
"serde",
"serde_json",
"tar",
"tauri",
"tauri-plugin",
"tempfile",
"thiserror 2.0.21",
"time",
"tokio",
"url",
"windows-sys 0.61.2",
"zip",
]
[[package]]
name = "tauri-runtime"
version = "2.12.1"
@@ -4258,7 +3898,7 @@ dependencies = [
"dpi",
"gtk",
"http",
"jni 0.21.1",
"jni",
"objc2",
"objc2-ui-kit",
"objc2-web-kit",
@@ -4281,7 +3921,7 @@ checksum = "7f9e7e0c9f80a5130773cfabb6df4dc924518fb1b2c923726966804634b57d22"
dependencies = [
"gtk",
"http",
"jni 0.21.1",
"jni",
"log",
"objc2",
"objc2-app-kit",
@@ -4470,16 +4110,6 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "tokio-rustls"
version = "0.26.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db"
dependencies = [
"rustls",
"tokio",
]
[[package]]
name = "tokio-util"
version = "0.7.20"
@@ -4711,12 +4341,6 @@ version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
[[package]]
name = "typed-path"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e"
[[package]]
name = "typeid"
version = "1.0.3"
@@ -4752,12 +4376,6 @@ version = "1.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
[[package]]
name = "untrusted"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
[[package]]
name = "url"
version = "2.5.8"
@@ -5057,15 +4675,6 @@ dependencies = [
"system-deps",
]
[[package]]
name = "webpki-root-certs"
version = "1.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a"
dependencies = [
"rustls-pki-types",
]
[[package]]
name = "webview2-com"
version = "0.39.1"
@@ -5230,17 +4839,6 @@ dependencies = [
"windows-link",
]
[[package]]
name = "windows-registry"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720"
dependencies = [
"windows-link",
"windows-result",
"windows-strings",
]
[[package]]
name = "windows-result"
version = "0.4.1"
@@ -5268,15 +4866,6 @@ dependencies = [
"windows-targets 0.42.2",
]
[[package]]
name = "windows-sys"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
dependencies = [
"windows-targets 0.52.6",
]
[[package]]
name = "windows-sys"
version = "0.60.2"
@@ -5310,22 +4899,6 @@ dependencies = [
"windows_x86_64_msvc 0.42.2",
]
[[package]]
name = "windows-targets"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
dependencies = [
"windows_aarch64_gnullvm 0.52.6",
"windows_aarch64_msvc 0.52.6",
"windows_i686_gnu 0.52.6",
"windows_i686_gnullvm 0.52.6",
"windows_i686_msvc 0.52.6",
"windows_x86_64_gnu 0.52.6",
"windows_x86_64_gnullvm 0.52.6",
"windows_x86_64_msvc 0.52.6",
]
[[package]]
name = "windows-targets"
version = "0.53.5"
@@ -5336,7 +4909,7 @@ dependencies = [
"windows_aarch64_gnullvm 0.53.1",
"windows_aarch64_msvc 0.53.1",
"windows_i686_gnu 0.53.1",
"windows_i686_gnullvm 0.53.1",
"windows_i686_gnullvm",
"windows_i686_msvc 0.53.1",
"windows_x86_64_gnu 0.53.1",
"windows_x86_64_gnullvm 0.53.1",
@@ -5367,12 +4940,6 @@ version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8"
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.53.1"
@@ -5385,12 +4952,6 @@ version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
[[package]]
name = "windows_aarch64_msvc"
version = "0.53.1"
@@ -5403,24 +4964,12 @@ version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f"
[[package]]
name = "windows_i686_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
[[package]]
name = "windows_i686_gnu"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3"
[[package]]
name = "windows_i686_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
[[package]]
name = "windows_i686_gnullvm"
version = "0.53.1"
@@ -5433,12 +4982,6 @@ version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060"
[[package]]
name = "windows_i686_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
[[package]]
name = "windows_i686_msvc"
version = "0.53.1"
@@ -5451,12 +4994,6 @@ version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36"
[[package]]
name = "windows_x86_64_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
[[package]]
name = "windows_x86_64_gnu"
version = "0.53.1"
@@ -5469,12 +5006,6 @@ version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.53.1"
@@ -5487,12 +5018,6 @@ version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "windows_x86_64_msvc"
version = "0.53.1"
@@ -5557,7 +5082,7 @@ dependencies = [
"gtk",
"http",
"javascriptcore-rs",
"jni 0.21.1",
"jni",
"libc",
"ndk",
"objc2",
@@ -5604,16 +5129,6 @@ dependencies = [
"pkg-config",
]
[[package]]
name = "xattr"
version = "1.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"
dependencies = [
"libc",
"rustix",
]
[[package]]
name = "yoke"
version = "0.8.3"
@@ -5728,12 +5243,6 @@ dependencies = [
"synstructure",
]
[[package]]
name = "zeroize"
version = "1.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"
[[package]]
name = "zerotrie"
version = "0.2.5"
@@ -5767,22 +5276,6 @@ dependencies = [
"syn 3.0.6",
]
[[package]]
name = "zip"
version = "9.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eaeb7f16d2605b49aef586996ded29e65642fab7259a3077e537351df6d80426"
dependencies = [
"crc32fast",
"getrandom 0.4.3",
"indexmap 2.14.2",
"libc",
"memchr",
"nix",
"typed-path",
"windows-sys 0.61.2",
]
[[package]]
name = "zlib-rs"
version = "0.6.8"
-23
View File
@@ -52,18 +52,6 @@ npm install
npm run dev
```
### Testing
Each part has its own tests:
```bash
cargo test # the engine (gpx-rs), from the root of the repository
(cd wasm && wasm-pack test --node) # the WebAssembly bindings
npm test --prefix website # the website, once the WebAssembly engine is built
```
See [`tauri`](tauri/README.md) for the tests of the desktop app.
## Credits
This project has been made possible thanks to the following open source projects:
@@ -71,7 +59,6 @@ This project has been made possible thanks to the following open source projects
- Development:
- [Svelte](https://github.com/sveltejs/svelte) and [SvelteKit](https://github.com/sveltejs/kit) — seamless development experience
- [MDsveX](https://github.com/pngwn/MDsveX) — allowing a Markdown-based documentation
- [Tauri](https://github.com/tauri-apps/tauri) – making a desktop app possible
- Design:
- [shadcn-svelte](https://github.com/huntabyte/shadcn-svelte) — beautiful components
- [@lucide/svelte](https://github.com/lucide-icons/lucide/tree/main/packages/svelte) — beautiful icons
@@ -87,16 +74,6 @@ This project has been made possible thanks to the following open source projects
- Search:
- [DocSearch](https://github.com/algolia/docsearch) — search engine for the documentation
## Integration
There are several ways to integrate **gpx.studio** into your website or tools:
- **Embedding**: show your GPX files on an interactive map in your website. See the [documentation](https://gpx.studio/help/integration) to configure the map and generate the HTML code.
- **Map object**: `window._map` gives access to the [MapLibre GL JS](https://maplibre.org/maplibre-gl-js/docs/) map instance.
- **Extension API**: `window.gpxstudio` lets browser extensions add map overlays that appear in the layer menu like built-in ones. See [`extension-api.ts`](website/src/lib/components/map/layer-control/extension-api.ts) for the reference.
To be notified about changes that may affect your integration, subscribe to [this discussion](https://github.com/gpxstudio/gpx.studio/discussions/410).
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
-505
View File
@@ -1,505 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<gpx xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.topografix.com/GPX/1/1"
xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd
http://www.garmin.com/xmlschemas/GpxExtensions/v3 http://www.garmin.com/xmlschemas/GpxExtensionsv3.xsd
http://www.garmin.com/xmlschemas/TrackPointExtension/v1 http://www.garmin.com/xmlschemas/TrackPointExtensionv1.xsd
http://www.topografix.com/GPX/gpx_style/0/2 http://www.topografix.com/GPX/gpx_style/0/2/gpx_style.xsd"
xmlns:gpxtpx="http://www.garmin.com/xmlschemas/TrackPointExtension/v1"
xmlns:gpxpx="http://www.garmin.com/xmlschemas/PowerExtension/v1"
xmlns:gpx_style="http://www.topografix.com/GPX/gpx_style/0/2" version="1.1"
creator="https://gpx.studio">
<metadata>
<name>with_power</name>
<author>
<name>gpx.studio</name>
<link href="https://gpx.studio"></link>
</author>
</metadata>
<trk>
<name>with_power</name>
<type>Cycling</type>
<trkseg>
<trkpt lat="50.790867" lon="4.404968">
<ele>109.0</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.790714" lon="4.405036">
<ele>110.8</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.790336" lon="4.405259">
<ele>110.3</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.790165" lon="4.405331">
<ele>110.0</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.790008" lon="4.405359">
<ele>110.3</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.789818" lon="4.405359">
<ele>109.3</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.789409" lon="4.40534">
<ele>107.0</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.789105" lon="4.405411">
<ele>106.0</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.788799" lon="4.405527">
<ele>108.5</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.788645" lon="4.405606">
<ele>109.8</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.7885" lon="4.405711">
<ele>110.8</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.78822" lon="4.405959">
<ele>112.0</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.787956" lon="4.406092">
<ele>112.8</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.787814" lon="4.406143">
<ele>113.5</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.787674" lon="4.406177">
<ele>114.3</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.787451" lon="4.406199">
<ele>115.3</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.787297" lon="4.406177">
<ele>114.8</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.78716" lon="4.406098">
<ele>114.3</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.787045" lon="4.405984">
<ele>114.3</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.786683" lon="4.405653">
<ele>114.5</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.786538" lon="4.405543">
<ele>115.0</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.78635" lon="4.405441">
<ele>115.8</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.786275" lon="4.40542">
<ele>115.8</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.786182" lon="4.405435">
<ele>116.0</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.786121" lon="4.405475">
<ele>115.8</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.786042" lon="4.405558">
<ele>115.5</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.785821" lon="4.405925">
<ele>114.5</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.785672" lon="4.406119">
<ele>112.5</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.785516" lon="4.406256">
<ele>110.8</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.785384" lon="4.406364">
<ele>109.0</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.785126" lon="4.406475">
<ele>106.3</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.784697" lon="4.406537">
<ele>104.3</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.784591" lon="4.40657">
<ele>104.0</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.784507" lon="4.406612">
<ele>103.8</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.784435" lon="4.40669">
<ele>103.3</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.784209" lon="4.407148">
<ele>103.5</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.784162" lon="4.407257">
<ele>103.8</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.784077" lon="4.407372">
<ele>104.8</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.784006" lon="4.407435">
<ele>105.8</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.783924" lon="4.407471">
<ele>106.8</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.783837" lon="4.407486">
<ele>107.8</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.783771" lon="4.407472">
<ele>108.5</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.783697" lon="4.407428">
<ele>109.3</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.783626" lon="4.407363">
<ele>110.0</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.783548" lon="4.407274">
<ele>110.5</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.783458" lon="4.407134">
<ele>110.8</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.783123" lon="4.406435">
<ele>111.8</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.782982" lon="4.406168">
<ele>112.8</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.782871" lon="4.406044">
<ele>113.3</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.78279" lon="4.406021">
<ele>113.5</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.782714" lon="4.406018">
<ele>113.5</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.782607" lon="4.406047">
<ele>113.8</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.782405" lon="4.406194">
<ele>114.8</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.782175" lon="4.406413">
<ele>115.8</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.781749" lon="4.407018">
<ele>118.5</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.781654" lon="4.407316">
<ele>119.5</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.781563" lon="4.407764">
<ele>121.3</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.781487" lon="4.407984">
<ele>122.0</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.781422" lon="4.408216">
<ele>122.8</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.781395" lon="4.408508">
<ele>123.5</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.781399" lon="4.409114">
<ele>126.3</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.781367" lon="4.409428">
<ele>128.0</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.781286" lon="4.409607">
<ele>129.0</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.78116" lon="4.409789">
<ele>130.0</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.780804" lon="4.409993">
<ele>130.8</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.780389" lon="4.410334">
<ele>131.8</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.780232" lon="4.410563">
<ele>132.3</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.780094" lon="4.410827">
<ele>132.8</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.779723" lon="4.411582">
<ele>135.8</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.779591" lon="4.411791">
<ele>135.5</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.779125" lon="4.412435">
<ele>132.5</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.778676" lon="4.412979">
<ele>134.0</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.778194" lon="4.413466">
<ele>136.8</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.777427" lon="4.414302">
<ele>137.5</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.777165" lon="4.414736">
<ele>137.3</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.776927" lon="4.415201">
<ele>137.5</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.776778" lon="4.415613">
<ele>137.3</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.776553" lon="4.416425">
<ele>134.8</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.776326" lon="4.417304">
<ele>132.3</ele>
<extensions>
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
</extensions>
</trkpt>
<trkpt lat="50.776129" lon="4.418383">
<ele>129.5</ele>
<extensions>
<gpxpx:PowerInWatts>210</gpxpx:PowerInWatts>
</extensions>
</trkpt>
</trkseg>
</trk>
</gpx>
+2 -2
View File
@@ -205,8 +205,8 @@ pub fn load_files<H: History>(
}
/// Brings changes of the files from the outside in (see [`engine::SyncFiles`]): each file is
/// `(id, data, name)`, and replaces the file of that id, or is added if there is none; `name` is
/// its name when its data has none. The files to `remove` are deleted. The selection is left alone.
/// `(id, data, name)`, and replaces the file of that id, or is added if there is none; it is called
/// `name`, whatever its data says. The files to `remove` are deleted. The selection is left alone.
pub fn sync_files<H: History>(
engine: &mut Engine<H>,
files: &[(Uuid, &[u8], &str)],
+20
View File
@@ -560,6 +560,26 @@ impl WaypointDetails {
}
}
#[derive(Serialize)]
pub struct TrackpointDetails {
lng: f64,
lat: f64,
ele: f64,
#[serde(skip_serializing_if = "Option::is_none")]
time: Option<f64>,
}
impl TrackpointDetails {
pub fn new(pt: &engine::Trackpoint) -> Self {
Self {
lng: pt.coordinates.lng,
lat: pt.coordinates.lat,
ele: pt.ele,
time: pt.time.map(|t| t as f64),
}
}
}
/// A trackpoint of the selection: what the statistics buffers do not hold for each trackpoint.
/// Absent fields are unknown.
#[derive(Serialize)]
+12
View File
@@ -63,6 +63,18 @@ pub fn waypoint<H: History>(
.map(WaypointDetails::new)
}
/// A trackpoint of a segment of a file, `None` if it does not exist.
pub fn trackpoint<H: History>(
engine: &Engine<H>,
file_id: Uuid,
segment_id: Uuid,
index: usize,
) -> Option<TrackpointDetails> {
engine
.trackpoint(&FileId(file_id), &engine::TrackSegmentId(segment_id), index)
.map(TrackpointDetails::new)
}
/// A file as GPX (UTF-8 bytes), `None` if it does not exist. The options say which data of the
/// trackpoints to keep.
pub fn export_file<H: History>(
+20 -52
View File
@@ -44,24 +44,14 @@ where
let last = trkseg.last_index().unwrap();
let mut kept = vec![(first, None)];
ramer_douglas_peucker_ranges(trkseg, first, last, measure, epsilon, &mut kept);
ramer_douglas_peucker_helper(trkseg, first, last, measure, epsilon, &mut kept);
kept.push((last, None));
kept
}
}
}
/// What is left to do for the points between two ends, in the order of the points.
enum Step {
/// Looks for the point to keep between these two.
Range(TrackSegmentIndex, TrackSegmentIndex),
/// Keeps a point, selected at this distance.
Keep(TrackSegmentIndex, f64),
}
/// Adds the points to keep between `start` and `end` to `kept`, in order. It does not recurse: a
/// track can make it go as deep as it has points, which would overflow the stack.
fn ramer_douglas_peucker_ranges<M>(
fn ramer_douglas_peucker_helper<M>(
trkseg: &TrackSegment,
start: TrackSegmentIndex,
end: TrackSegmentIndex,
@@ -71,40 +61,28 @@ fn ramer_douglas_peucker_ranges<M>(
) where
M: Fn(TrackSegmentIndex, TrackSegmentIndex, TrackSegmentIndex) -> f64,
{
let mut steps = vec![Step::Range(start, end)];
while let Some(step) = steps.pop() {
let (start, end) = match step {
Step::Keep(idx, dist) => {
kept.push((idx, Some(dist)));
continue;
}
Step::Range(start, end) => (start, end),
};
let mut max_idx = None;
let mut max_dist = 0.0;
let mut max_idx = None;
let mut max_dist = 0.0;
let mut cur = trkseg.next_index(Some(start));
while let Some(idx) = cur {
if idx == end {
break;
}
let dist = measure(start, end, idx);
if dist > max_dist {
max_idx = Some(idx);
max_dist = dist;
}
cur = trkseg.next_index(cur);
let mut cur = trkseg.next_index(Some(start));
while let Some(idx) = cur {
if idx == end {
break;
}
if let Some(idx) = max_idx.filter(|_| max_dist > epsilon) {
// the last one pushed is done first
steps.push(Step::Range(idx, end));
steps.push(Step::Keep(idx, max_dist));
steps.push(Step::Range(start, idx));
let dist = measure(start, end, idx);
if dist > max_dist {
max_idx = Some(idx);
max_dist = dist;
}
cur = trkseg.next_index(cur);
}
if let Some(idx) = max_idx.filter(|_| max_dist > epsilon) {
ramer_douglas_peucker_helper(trkseg, start, idx, measure, epsilon, kept);
kept.push((idx, Some(max_dist)));
ramer_douglas_peucker_helper(trkseg, idx, end, measure, epsilon, kept);
}
}
@@ -217,16 +195,6 @@ mod tests {
.collect()
}
#[test]
fn test_goes_as_deep_as_the_segment_is_long_in_order() {
let n = 12_000;
let trkseg = segment(&vec![0.0; n]);
// the point before the end is always the farthest one, so each range only loses one point
let kept = ramer_douglas_peucker_by(&trkseg, &|_, _, idx| idx.flat as f64 + 1.0, 0.5);
let kept: Vec<usize> = kept.iter().map(|(idx, _)| idx.flat).collect();
assert_eq!(kept, (0..n).collect::<Vec<_>>());
}
#[test]
fn test_empty_and_single_point() {
assert!(simplify(&[], 1.0).is_empty());
+11 -228
View File
@@ -3,11 +3,11 @@ use crate::{
TrackpointCategories, TrackpointChunk, Waypoint, WaypointChunk, distance,
};
use chrono::DateTime;
use quick_xml::Error;
use quick_xml::escape::resolve_predefined_entity;
use quick_xml::events::Event;
use quick_xml::events::attributes::{Attribute, Attributes};
use quick_xml::events::attributes::Attributes;
use quick_xml::reader::Reader;
use quick_xml::{Error, XmlVersion};
enum GPXElement {
Metadata,
@@ -37,8 +37,6 @@ enum GPXElement {
Symbol,
Type,
Color,
/// The color of a track or a route in the Garmin extensions (`gpxx:DisplayColor`).
DisplayColor,
Opacity,
Width,
}
@@ -60,50 +58,6 @@ fn is_route_point_extension(name: &str) -> bool {
name == "rpt" || name.ends_with(":rpt")
}
/// The color of a track (`RRGGBB`, the format of the style schema) and its opacity, from a color
/// that may start with `#` and may have an alpha channel first (`AARRGGBB`), as some applications
/// write it. A color in any other format is kept as it is, without opacity.
fn parse_color(value: &str) -> (String, Option<f64>) {
let value = value.trim();
let hex = value.strip_prefix('#').unwrap_or(value);
if !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
return (value.to_owned(), None);
}
match hex.len() {
6 => (hex.to_owned(), None),
8 => {
let alpha = u8::from_str_radix(&hex[..2], 16).unwrap_or(u8::MAX);
let opacity = (f64::from(alpha) / 255.0 * 100.0).round() / 100.0;
(hex[2..].to_owned(), Some(opacity))
}
_ => (value.to_owned(), None),
}
}
/// The hexadecimal color of a value of `DisplayColor_t` in the Garmin extensions. None for
/// `Transparent` and for what is not part of the schema.
fn garmin_display_color(name: &str) -> Option<&'static str> {
match name.trim() {
"Black" => Some("000000"),
"DarkRed" => Some("800000"),
"DarkGreen" => Some("008000"),
"DarkYellow" => Some("808000"),
"DarkBlue" => Some("000080"),
"DarkMagenta" => Some("800080"),
"DarkCyan" => Some("008080"),
"LightGray" => Some("c0c0c0"),
"DarkGray" => Some("808080"),
"Red" => Some("ff0000"),
"Green" => Some("00ff00"),
"Yellow" => Some("ffff00"),
"Blue" => Some("0000ff"),
"Magenta" => Some("ff00ff"),
"Cyan" => Some("00ffff"),
"White" => Some("ffffff"),
_ => None,
}
}
/// Whether the element holds a value, which is its text.
fn holds_text(element: Option<&GPXElement>) -> bool {
matches!(
@@ -127,7 +81,6 @@ fn holds_text(element: Option<&GPXElement>) -> bool {
| GPXElement::Symbol
| GPXElement::Type
| GPXElement::Color
| GPXElement::DisplayColor
| GPXElement::Opacity
| GPXElement::Width
)
@@ -213,21 +166,16 @@ fn apply_text(
}
Some(GPXElement::Time) => {
stack.pop();
let time = DateTime::parse_from_rfc3339(e)
.ok()
.map(|time| time.timestamp_millis());
match stack.last_mut() {
Some(GPXElement::Trackpoint(trkpt)) => trkpt.time = time,
Some(GPXElement::Waypoint(wpt)) => wpt.time = time,
Some(GPXElement::Metadata) => gpx.info.time = time,
_ => (),
if let Some(GPXElement::Trackpoint(trkpt)) = stack.last_mut() {
trkpt.time = DateTime::parse_from_rfc3339(e)
.ok()
.map(|time| time.timestamp_millis());
}
}
Some(GPXElement::Temperature) => {
stack.pop();
if let Some(GPXElement::Trackpoint(trkpt)) = stack.last_mut() {
// Garmin Connect writes whole degrees as "21.0"
trkpt.atemp = e.parse::<f64>().ok().map(|t| t.round() as i16);
trkpt.atemp = e.parse().ok();
}
}
Some(GPXElement::Heartrate) => {
@@ -293,21 +241,7 @@ fn apply_text(
Some(GPXElement::Color) => {
stack.pop();
if let Some(GPXElement::Track(trk)) = stack.last_mut() {
let (color, opacity) = parse_color(e);
trk.info.color = Some(color);
// The opacity of the style schema has priority, wherever it is in the extensions
if trk.info.opacity.is_none() {
trk.info.opacity = opacity;
}
}
}
// The color of the style schema has priority, wherever it is in the extensions
Some(GPXElement::DisplayColor) => {
stack.pop();
if let Some(GPXElement::Track(trk)) = stack.last_mut()
&& trk.info.color.is_none()
{
trk.info.color = garmin_display_color(e).map(str::to_owned);
trk.info.color = Some(e.to_owned());
}
}
Some(GPXElement::Opacity) => {
@@ -326,13 +260,6 @@ fn apply_text(
}
}
/// The text of an attribute, without its escaping (`&amp;` is `&`), which is written back when the
/// file is. As it is in the file if it cannot be read.
fn attribute_text(attr: &Attribute<'_>) -> String {
attr.normalized_value(XmlVersion::Implicit1_0)
.map_or_else(|_| attr.value.to_string(), |text| text.into_owned())
}
/// The email of the author, given as the `id` and `domain` attributes of the element.
fn set_email(stack: &mut [GPXElement], attributes: Attributes<'_>) {
let Some(GPXElement::Author(author)) = stack.last_mut() else {
@@ -341,8 +268,8 @@ fn set_email(stack: &mut [GPXElement], attributes: Attributes<'_>) {
let (mut id, mut domain) = (None, None);
for attr in attributes.flatten() {
match attr.key.as_ref() {
"id" => id = Some(attribute_text(&attr)),
"domain" => domain = Some(attribute_text(&attr)),
"id" => id = Some(attr.value.to_string()),
"domain" => domain = Some(attr.value.to_string()),
_ => (),
}
}
@@ -356,7 +283,7 @@ fn parse_link(attributes: Attributes<'_>) -> Link {
let mut link = Link::default();
for attr in attributes.flatten() {
if attr.key.as_ref() == "href" {
link.href = attribute_text(&attr);
link.href = attr.value.to_string();
}
}
link
@@ -521,7 +448,6 @@ pub fn parse(data: &[u8], categories: &mut TrackpointCategories) -> Result<File,
"sym" => stack.push(GPXElement::Symbol),
"type" => stack.push(GPXElement::Type),
e if e.ends_with("color") => stack.push(GPXElement::Color),
e if e.ends_with("DisplayColor") => stack.push(GPXElement::DisplayColor),
e if e.ends_with("opacity") => stack.push(GPXElement::Opacity),
e if e.ends_with("width") => stack.push(GPXElement::Width),
_ => (),
@@ -700,14 +626,6 @@ mod tests {
.unwrap()
}
#[test]
fn test_link_href_is_unescaped_and_written_back_once() {
let data =
r#"<gpx><metadata><link href="https://a.example/?x=1&amp;y=2"/></metadata></gpx>"#;
let gpx = parse(data.as_bytes(), &mut Default::default()).unwrap();
assert_eq!(gpx.info.links[0].href, "https://a.example/?x=1&y=2");
}
#[test]
fn test_parse_entities_and_cdata_in_text() {
let data = r#"<gpx><metadata><name>Tom &amp; Jerry &lt;3 &#233;&#x41; &quot;x&quot; &apos;y&apos;</name>
@@ -1147,20 +1065,6 @@ mod tests {
assert!(wpt.type_.as_ref().is_some_and(|t| t == "Bike Trail"));
}
#[test]
fn test_parse_waypoint_time() {
let data = r#"<gpx><wpt lat="1" lon="2"><time>2024-05-01T06:10:00Z</time></wpt></gpx>"#;
let gpx = parse(data.as_bytes(), &mut Default::default()).unwrap();
assert_eq!(gpx.wpt[0].time, Some(1714543800000));
}
#[test]
fn test_parse_metadata_time() {
let data = r#"<gpx><metadata><time>2024-05-01T06:10:00Z</time></metadata></gpx>"#;
let gpx = parse(data.as_bytes(), &mut Default::default()).unwrap();
assert_eq!(gpx.info.time, Some(1714543800000));
}
#[test]
fn test_parse_trackpoint_time() {
let gpx = parse_data("with_time");
@@ -1318,19 +1222,6 @@ mod tests {
assert!(trkpt.power.is_some_and(|p| p == 200));
}
#[test]
fn test_parse_trackpoint_power_3() {
let gpx = parse_data("with_power_3");
assert_eq!(gpx.trk.len(), 1);
let trk = &gpx.trk[0];
assert_eq!(trk.trkseg.len(), 1);
let trkseg = &trk.trkseg[0];
assert!(!trkseg.is_empty());
let trkpt = &trkseg[0];
assert!(trkpt.power.is_some_and(|p| p == 200));
}
#[test]
fn test_parse_trackpoint_atemp() {
let gpx = parse_data("with_temp");
@@ -1344,14 +1235,6 @@ mod tests {
assert!(trkpt.atemp.is_some_and(|t| t == 21));
}
#[test]
fn test_parse_trackpoint_decimal_atemp() {
let data = r#"<gpx><trk><trkseg><trkpt lat="1" lon="2"><extensions><gpxtpx:TrackPointExtension>
<gpxtpx:atemp>21.0</gpxtpx:atemp></gpxtpx:TrackPointExtension></extensions></trkpt></trkseg></trk></gpx>"#;
let gpx = parse(data.as_bytes(), &mut Default::default()).unwrap();
assert_eq!(gpx.trk[0].trkseg[0][0].atemp, Some(21));
}
#[test]
fn test_parse_track_style() {
let gpx = parse_data("with_style");
@@ -1363,104 +1246,4 @@ mod tests {
assert!(trk.info.opacity.is_some_and(|o| o == 0.5));
assert!(trk.info.width.is_some_and(|w| w == 6.0));
}
fn parse_text(text: &str) -> File {
parse(text.as_bytes(), &mut Default::default()).unwrap()
}
#[test]
fn test_parse_garmin_display_color_of_tracks_and_routes() {
let gpx = parse_text(
r#"<gpx xmlns:gpxx="http://www.garmin.com/xmlschemas/GpxExtensions/v3"
xmlns:gpxtrx="http://www.garmin.com/xmlschemas/GpxExtensions/v3">
<trk><extensions><gpxx:TrackExtension>
<gpxx:DisplayColor>Blue</gpxx:DisplayColor>
</gpxx:TrackExtension></extensions></trk>
<trk><extensions><gpxtrx:TrackExtension>
<gpxtrx:DisplayColor>DarkRed</gpxtrx:DisplayColor>
</gpxtrx:TrackExtension></extensions></trk>
<rte><extensions><gpxx:RouteExtension>
<gpxx:DisplayColor>Green</gpxx:DisplayColor>
</gpxx:RouteExtension></extensions></rte>
</gpx>"#,
);
assert_eq!(gpx.trk[0].info.color.as_deref(), Some("0000ff"));
assert_eq!(gpx.trk[1].info.color.as_deref(), Some("800000"));
assert_eq!(gpx.rte[0].info.color.as_deref(), Some("00ff00"));
}
#[test]
fn test_garmin_display_color_without_a_color_leaves_the_track_uncolored() {
let gpx = parse_text(
r#"<gpx>
<trk><extensions><gpxx:TrackExtension>
<gpxx:DisplayColor>Transparent</gpxx:DisplayColor>
</gpxx:TrackExtension></extensions></trk>
<trk><extensions><gpxx:TrackExtension>
<gpxx:DisplayColor>Mauve</gpxx:DisplayColor>
</gpxx:TrackExtension></extensions></trk>
</gpx>"#,
);
assert_eq!(gpx.trk[0].info.color, None);
assert_eq!(gpx.trk[1].info.color, None);
}
#[test]
fn test_style_color_has_priority_over_garmin_display_color() {
let gpx = parse_text(
r#"<gpx>
<trk><extensions>
<gpxx:TrackExtension><gpxx:DisplayColor>Red</gpxx:DisplayColor></gpxx:TrackExtension>
<gpx_style:line><gpx_style:color>2d3ee9</gpx_style:color></gpx_style:line>
</extensions></trk>
<trk><extensions>
<gpx_style:line><gpx_style:color>2d3ee9</gpx_style:color></gpx_style:line>
<gpxx:TrackExtension><gpxx:DisplayColor>Red</gpxx:DisplayColor></gpxx:TrackExtension>
</extensions></trk>
</gpx>"#,
);
assert_eq!(gpx.trk[0].info.color.as_deref(), Some("2d3ee9"));
assert_eq!(gpx.trk[1].info.color.as_deref(), Some("2d3ee9"));
}
#[test]
fn test_parse_color_with_hash_and_alpha() {
assert_eq!(parse_color("2d3ee9"), ("2d3ee9".into(), None));
assert_eq!(parse_color("#0000FF"), ("0000FF".into(), None));
assert_eq!(parse_color("#800000FF"), ("0000FF".into(), Some(0.5)));
assert_eq!(parse_color("FF0000FF"), ("0000FF".into(), Some(1.0)));
assert_eq!(parse_color("#00ff0000"), ("ff0000".into(), Some(0.0)));
assert_eq!(parse_color("red"), ("red".into(), None));
assert_eq!(parse_color("#abc"), ("#abc".into(), None));
}
#[test]
fn test_parse_track_color_with_alpha() {
let gpx = parse_text(
r#"<gpx>
<trk><extensions><xsi:gpx>
<physicalColor>#400000FF</physicalColor>
<width>4</width>
<color>#800000FF</color>
</xsi:gpx></extensions></trk>
<trk><extensions><gpx_style:line>
<gpx_style:opacity>0.3</gpx_style:opacity>
<gpx_style:color>#800000FF</gpx_style:color>
</gpx_style:line></extensions></trk>
<trk><extensions><gpx_style:line>
<gpx_style:color>#800000FF</gpx_style:color>
<gpx_style:opacity>0.3</gpx_style:opacity>
</gpx_style:line></extensions></trk>
</gpx>"#,
);
assert_eq!(gpx.trk[0].info.color.as_deref(), Some("0000FF"));
assert_eq!(gpx.trk[0].info.opacity, Some(0.5));
assert_eq!(gpx.trk[0].info.width, Some(4.0));
assert_eq!(gpx.trk[1].info.opacity, Some(0.3));
assert_eq!(gpx.trk[2].info.opacity, Some(0.3));
}
}
+2 -14
View File
@@ -402,10 +402,9 @@ fn write_point(
Ok(())
})?;
}
// `PowerInWatts` is itself the root element of Garmin's power extension, without a
// wrapper
if let Some(power) = power {
number(w, "gpxpx:PowerInWatts", power)?;
w.create_element("gpxpx:PowerExtension")
.write_inner_content(|w| number(w, "gpxpx:PowerInWatts", power))?;
}
if !path.is_empty() {
w.create_element("gpxx:RoutePointExtension")
@@ -512,7 +511,6 @@ mod tests {
"with_temp",
"with_power_1",
"with_power_2",
"with_power_3",
"with_surface",
"with_highway",
"with_style",
@@ -580,16 +578,6 @@ mod tests {
assert_eq!(again.trk[0].info.name.as_deref(), Some("a <b> & c"));
}
#[test]
fn test_power_is_written_without_a_wrapper() {
let (file, categories) = read("with_power_2");
let text: String = written_text(&file, &categories, ExportOptions::ALL)
.split_whitespace()
.collect();
assert!(text.contains("<extensions><gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>"));
assert!(!text.contains("<gpxpx:PowerExtension>"));
}
#[test]
fn test_exportable_data() {
let (file, _) = read("with_time");
+8
View File
@@ -24,6 +24,14 @@ pub struct Statistics {
}
impl Statistics {
pub fn total_speed(&self) -> Option<f64> {
self.global.total_speed()
}
pub fn moving_speed(&self) -> Option<f64> {
self.global.moving_speed()
}
pub fn compute(trkseg: &TrackSegment) -> Self {
let mut stats = Self::default();
if trkseg.is_empty() {
+23 -58
View File
@@ -9,12 +9,10 @@ use crate::{Apply, CommandError, FileId, Route, Selection, State, Track};
/// after the routes;
/// - a track becomes one route per segment, as a route has a single segment, and goes away. A
/// selected segment becomes a route and leaves its track, which stays even if it has no segment
/// left. The routes have the information of their track, and go after the other routes;
/// - a file with routes only has all of them converted to tracks, and a file with tracks only
/// has all of them converted to routes. The files with both, or neither, stay as they are.
/// left. The routes have the information of their track, and go after the other routes.
///
/// The segments keep their ids, the new routes and tracks are selected (the files stay selected).
/// There is nothing to do for the other selections, or for tracks without segments.
/// The segments keep their ids, the new routes and tracks are selected. There is nothing to do
/// for the other selections, or for tracks without segments.
#[derive(Debug)]
pub struct Convert;
@@ -33,7 +31,14 @@ impl Apply for Convert {
.into_iter()
.partition::<Vec<_>, _>(|rte| rte_ids.contains(&rte.id));
file.rte = kept;
let tracks = to_tracks(converted);
let tracks: Vec<Track> = converted
.into_iter()
.map(|rte| Track {
id: Default::default(),
info: rte.info,
trkseg: vec![rte.seg],
})
.collect();
let trk_ids: HashSet<_> = tracks.iter().map(|trk| trk.id).collect();
file.trk.splice(0..0, tracks);
Selection::Track {
@@ -52,7 +57,14 @@ impl Apply for Convert {
.into_iter()
.partition::<Vec<_>, _>(|trk| trk_ids.contains(&trk.id));
file.trk = kept;
add_routes(&mut file.rte, *file_id, to_routes(converted))
let routes = converted.into_iter().flat_map(|trk| {
trk.trkseg.into_iter().map(move |seg| Route {
id: Default::default(),
info: trk.info.clone(),
seg,
})
});
add_routes(&mut file.rte, *file_id, routes)
}
Selection::TrackSegment {
file_id,
@@ -82,34 +94,10 @@ impl Apply for Convert {
});
add_routes(&mut file.rte, *file_id, routes)
}
Selection::File { file_ids } => {
let mut converted = false;
for file_id in file_ids {
let Some(file) = state.files.get_mut(file_id) else {
continue;
};
if !file.rte.is_empty() && file.trk.is_empty() {
let file = Rc::make_mut(file);
file.trk = to_tracks(std::mem::take(&mut file.rte));
} else if file.rte.is_empty()
&& file.trk.iter().any(|trk| !trk.trkseg.is_empty())
{
let file = Rc::make_mut(file);
file.rte = to_routes(std::mem::take(&mut file.trk)).collect();
} else {
continue;
}
converted = true;
}
return if converted {
Ok(())
} else {
Err(CommandError::NothingToDo)
};
}
Selection::Empty | Selection::Waypoints { .. } | Selection::Waypoint { .. } => {
return Err(CommandError::NothingToDo);
}
Selection::Empty
| Selection::File { .. }
| Selection::Waypoints { .. }
| Selection::Waypoint { .. } => return Err(CommandError::NothingToDo),
};
let empty = match &next {
Selection::Route { rte_ids, .. } => rte_ids.is_empty(),
@@ -125,29 +113,6 @@ impl Apply for Convert {
}
}
/// The tracks of the routes, each with the segment of its route.
fn to_tracks(routes: Vec<Route>) -> Vec<Track> {
routes
.into_iter()
.map(|rte| Track {
id: Default::default(),
info: rte.info,
trkseg: vec![rte.seg],
})
.collect()
}
/// The routes of the tracks, one per segment, each with the information of its track.
fn to_routes(tracks: Vec<Track>) -> impl Iterator<Item = Route> {
tracks.into_iter().flat_map(|trk| {
trk.trkseg.into_iter().map(move |seg| Route {
id: Default::default(),
info: trk.info.clone(),
seg,
})
})
}
/// Adds the routes after the other routes, and gives the selection of them.
fn add_routes(
rte: &mut Vec<Route>,
+9 -5
View File
@@ -7,8 +7,8 @@ use crate::{Apply, CommandError, FileId, Load, State};
pub struct ExternalFile<'a> {
pub id: FileId,
pub data: &'a [u8],
/// Name of the file when the data has none (the name of the file on the disk, without its
/// extension).
/// Name of the file outside (the name of the file on the disk, without its extension), which
/// is its name here whatever the data says: a file has a single name.
pub name: &'a str,
}
@@ -16,7 +16,8 @@ pub struct ExternalFile<'a> {
/// that are given replace the ones of the same id (which stay where they are in the order, and keep
/// their id), or are added at the end if there are none; the ones to `remove` are deleted.
///
/// Unlike [`crate::LoadFiles`], the selection is left alone (what it holds of a file that was
/// Unlike [`crate::LoadFiles`], the files are named as they are outside (see [`ExternalFile`]), and
/// the selection is left alone (what it holds of a file that was
/// replaced or deleted is dropped by the engine afterwards, as with any edit).
///
/// The files that cannot be read are skipped, and the files that are here stay as they are. It is an
@@ -39,6 +40,9 @@ impl Apply for SyncFiles<'_> {
match load.parse(state.categories) {
Ok(mut file) => {
file.id = external.id;
if !external.name.trim().is_empty() {
file.info.name = external.name.to_owned();
}
if state.files.insert(external.id, Rc::new(file)).is_none() {
state.order.0.push(external.id);
}
@@ -103,8 +107,8 @@ mod tests {
.apply(&mut fx.state())
.unwrap();
assert_eq!(fx.order.0, [first, second]);
// named as the data says, the name outside is only for a file that has none
assert_eq!(fx.files[&first].info.name, "from disk");
// named as it is outside, not as the data says
assert_eq!(fx.files[&first].info.name, "name");
assert_eq!(fx.files[&first].id, first);
// the selection is not changed
assert_eq!(fx.selected_files(), [second].into());
-40
View File
@@ -682,43 +682,3 @@ fn test_convert_segments_to_routes_keeps_their_track() {
);
}
}
#[test]
fn test_convert_a_file_with_routes_or_tracks_only() {
let (mut fx, id) = fixture();
let before = file(&fx, id).clone();
let only_tracks = File {
trk: before.trk.clone(),
..File::default()
};
let only_tracks_id = only_tracks.id;
fx.files.insert(only_tracks_id, Rc::new(only_tracks));
fx.order.0.push(only_tracks_id);
// the file with both stays as it is, the other gets one route per segment
fx.selection = Selection::File {
file_ids: [id, only_tracks_id].into(),
};
Convert.apply(&mut fx.state()).unwrap();
assert_eq!(lengths(file(&fx, id)), lengths(&before));
let routes = file(&fx, only_tracks_id);
assert_eq!((routes.rte.len(), routes.trk.len()), (4, 0));
assert_eq!(routes.rte[0].seg.id, before.trk[0].trkseg[0].id);
assert_eq!(routes.rte[0].info, before.trk[0].info);
// and back: one track per route
fx.selection = Selection::File {
file_ids: [only_tracks_id].into(),
};
Convert.apply(&mut fx.state()).unwrap();
let tracks = file(&fx, only_tracks_id);
assert_eq!((tracks.rte.len(), tracks.trk.len()), (0, 4));
assert_eq!(tracks.trk[0].trkseg[0].id, before.trk[0].trkseg[0].id);
// nothing to do for a file with both
fx.selection = whole(id);
assert_eq!(
Convert.apply(&mut fx.state()),
Err(CommandError::NothingToDo)
);
}
@@ -36,7 +36,6 @@ impl StatisticsCache {
}
/// Statistics of the segments of the selection.
#[cfg(test)]
pub fn get<'a>(
&'a self,
state: Option<&'a Files>,
+17 -1
View File
@@ -11,7 +11,7 @@ pub use outcome::*;
pub use state::*;
use crate::{
ExportOptions, FileId, GlobalStatistics, Restored, Snapshot, TrackSegmentId,
ExportOptions, FileId, GlobalStatistics, Restored, Snapshot, TrackSegmentId, Trackpoint,
TrackpointCategories, Waypoint, WaypointId, reduction_distances, write,
};
@@ -82,6 +82,22 @@ impl<H: History> Engine<H> {
.find(|wpt| wpt.id == *id)
}
/// A trackpoint of a segment (of a route or a track) of a file. `None` if it does not exist.
pub fn trackpoint(
&self,
file_id: &FileId,
segment_id: &TrackSegmentId,
index: usize,
) -> Option<&Trackpoint> {
let segment = self
.history
.current()?
.get(file_id)?
.segments()
.find(|seg| seg.id == *segment_id)?;
(index < segment.len()).then(|| &segment[index])
}
/// For each trackpoint of the selection (numbered as in the statistics), the tolerance up to
/// which `Reduce` keeps it, see [`reduction_distances`].
pub fn reduction_distances(&self) -> Vec<f64> {
+18
View File
@@ -1169,6 +1169,24 @@ fn test_categories_are_shared_and_kept_by_the_history() {
assert_eq!(expand(&engine.statistics().surface, 5), [1, 1, 0, 2, 2]);
}
#[test]
fn test_trackpoint() {
let mut engine = TestEngine::default();
load(&mut engine, "data/simple.gpx");
let file = engine.order()[0];
let structure = engine.file_structure(&file).unwrap();
let seg = &structure.tracks[0].segments[0];
let (seg_id, len) = (seg.id, seg.len);
let coordinates = engine.segment_coordinates(&seg_id).to_vec();
let last = engine.trackpoint(&file, &seg_id, len - 1).unwrap();
assert_eq!(
[last.coordinates.lng, last.coordinates.lat],
coordinates[(len - 1) * 2..]
);
assert!(engine.trackpoint(&file, &seg_id, len).is_none());
assert!(engine.trackpoint(&Default::default(), &seg_id, 0).is_none());
}
#[test]
fn test_export_writes_the_file_as_it_is() {
let mut engine = TestEngine::default();
+3 -5
View File
@@ -1,9 +1,9 @@
use std::cell::RefCell;
use std::collections::HashMap;
#[cfg(test)]
use crate::ChunkKind;
use crate::{Batch, ChunkKey, CommitError, FileId, Revision, Storage, StorageError, StoredData};
use crate::{
Batch, ChunkKey, ChunkKind, CommitError, FileId, Revision, Storage, StorageError, StoredData,
};
/// A storage that lives as long as the session. It is what an engine without a host storage uses,
/// and what the tests use.
@@ -22,7 +22,6 @@ struct State {
}
/// How much there is in a storage.
#[cfg(test)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StorageCounts {
pub files: usize,
@@ -30,7 +29,6 @@ pub struct StorageCounts {
pub waypoint_chunks: usize,
}
#[cfg(test)]
impl MemoryStorage {
/// How many files and chunks are stored.
pub fn counts(&self) -> StorageCounts {
-13
View File
@@ -7,15 +7,6 @@ edition = "2024"
[lib]
name = "gpx_studio_desktop_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
# the tests are in `tests/app`: on Windows, a test binary of the library or of the app could not
# start without the manifest, which `build.rs` only gives to the binaries of `tests`
test = false
doctest = false
[[bin]]
name = "gpx-studio-desktop"
path = "src/main.rs"
test = false
[dev-dependencies]
tauri = { version = "2", features = ["test"] }
@@ -37,7 +28,3 @@ tauri-plugin-single-instance = "2.5.3"
tauri-plugin-opener = "2"
trash = "5"
[target.'cfg(any(target_os = "macos", windows, target_os = "linux"))'.dependencies]
tauri-plugin-process = "2.4.0"
tauri-plugin-updater = "2.14.1"
-38
View File
@@ -1,38 +0,0 @@
# tauri
The desktop app of gpx.studio, built with [Tauri 2](https://v2.tauri.app/).
Its UI is the website ([`../website`](../website)), and it runs the engine of [`../gpx-rs`](../gpx-rs) natively instead of in WebAssembly.
## Development
You will need the same tools as for the website: [Node.js](https://nodejs.org/), [Rust](https://rustup.rs/) and [wasm-pack](https://rustwasm.github.io/wasm-pack/).
To run the app in development mode, you will also need to install the [system dependencies of Tauri](https://v2.tauri.app/start/prerequisites/) for your platform and the Tauri CLI:
```bash
cargo install tauri-cli --version "^2"
```
### Setting up the frontend
The desktop app does not use the WebAssembly engine, but the website depends on its package.
From the root of the repository, build it once and install the website’s dependencies:
```bash
cd wasm && wasm-pack build --target bundler && cd ..
npm install --prefix website
```
For the MapTiler layers, add your key to `website/.env`, as explained in the [main README](../README.md#running-the-website).
### Running the app
```bash
cd tauri
cargo tauri dev
```
### Testing
```bash
cargo test -p gpx-studio-desktop
```
-17
View File
@@ -1,20 +1,3 @@
fn main() {
// On Windows, the dialogs need Common Controls v6, which a binary only gets with a manifest that
// asks for it: tauri-build gives one to the app, but not to the test binaries, which would stop
// with STATUS_ENTRYPOINT_NOT_FOUND before running any test. This gives them the same manifest
// (`-tests` only reaches the binaries of `tests`, hence the tests are there).
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows")
&& std::env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("msvc")
{
let manifest = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join("windows-test.manifest");
println!("cargo:rerun-if-changed={}", manifest.display());
println!("cargo:rustc-link-arg-tests=/MANIFEST:EMBED");
println!(
"cargo:rustc-link-arg-tests=/MANIFESTINPUT:{}",
manifest.display()
);
}
tauri_build::build()
}
+1 -1
View File
@@ -3,5 +3,5 @@
"identifier": "default",
"description": "Permissions for the main window",
"windows": ["main"],
"permissions": ["core:default", "updater:default", "process:allow-restart"]
"permissions": ["core:default"]
}
+19 -18
View File
@@ -14,6 +14,7 @@ use tauri::{AppHandle, Runtime, State};
use tauri_plugin_dialog::{DialogExt, FilePath};
use uuid::Uuid;
use crate::commands::edit;
use crate::state::AppState;
use crate::workspace::{Entry, Unsaved, WorkspaceState, free_path};
@@ -385,28 +386,28 @@ pub fn create_folder(
state.core(move |core| core.workspace.create_folder(&parent, &name))
}
/// Renames a file or a folder of the open folder, on the disk only: an open file keeps its name,
/// and follows. Not undoable.
/// Renames a file or a folder of the open folder. An open file is renamed like in its info (it is
/// selected), which can be undone; the rest is renamed on the disk, and the open files that are in
/// a folder that is renamed follow.
#[tauri::command(async)]
pub fn rename_path(state: State<AppState>, path: PathBuf, name: String) -> Result<(), String> {
pub fn rename_path(
state: State<AppState>,
path: PathBuf,
name: String,
) -> Result<api::Outcome, String> {
state.core(move |core| {
if let Some(id) = core.workspace.linked(&path) {
let selected = api::select(&mut core.engine, &[id], gpx_engine::SelectMode::Replace);
let desc = core
.engine
.file_structure(&FileId(id))
.and_then(|structure| structure.desc.clone())
.unwrap_or_default();
return Ok(selected.merge(edit::rename_selection(core, name, desc)));
}
core.workspace.rename_path(&path, &name)?;
core.commit(None);
Ok(())
})
}
/// Renames the file on the disk of an open file, next to where it is (see `Workspace::rename_file`).
/// Not undoable, the name of the file in the engine is not changed. Says whether it was renamed:
/// not for a file that is not on the disk.
#[tauri::command(async)]
pub fn rename_file(state: State<AppState>, file_id: Uuid, name: String) -> Result<bool, String> {
state.core(move |core| {
let renamed = core.workspace.rename_file(file_id, &name)?;
if renamed {
core.commit(None);
}
Ok(renamed)
Ok(api::Outcome::failed_none())
})
}
+19 -5
View File
@@ -1,17 +1,31 @@
//! Editing the metadata, the style, the structure and the waypoints of the files, and the tools:
//! reversing, cropping, reducing, timestamps, merging, cleaning...
use gpx_engine::{CleanType, MergeType, SplitType, api};
use gpx_engine::{CleanType, FileId, MergeType, Selection, SplitType, api};
use tauri::State;
use uuid::Uuid;
use crate::state::AppState;
use crate::state::{AppState, Core};
/// Names and describes the selected files or tracks. The files on the disk keep their name: see
/// `disk::rename_file`.
/// Names and describes the selected files or tracks. A file on the disk is renamed with it (and back
/// when it is undone): its name is one that a file can have, and not the one of another file.
#[tauri::command(async)]
pub fn metadata(state: State<AppState>, name: String, desc: String) -> api::Outcome {
state.run(move |e| api::metadata(e, &name, &desc))
state.core(move |core| rename_selection(core, name, desc))
}
/// See `metadata`.
pub fn rename_selection(core: &mut Core, name: String, desc: String) -> api::Outcome {
let mut name = name;
if let Selection::File { file_ids } = core.engine.selection() {
for FileId(id) in file_ids.clone() {
match core.workspace.name_for(id, &name) {
Ok(valid) => name = valid,
Err(error) => return api::Outcome::failed(error),
}
}
}
core.edit(move |e| api::metadata(e, &name, &desc))
}
#[tauri::command(async)]
+2 -2
View File
@@ -115,10 +115,10 @@ pub fn move_elements(
#[tauri::command(async)]
pub fn undo(state: State<AppState>) -> api::Outcome {
state.run(api::undo)
state.edit(api::undo)
}
#[tauri::command(async)]
pub fn redo(state: State<AppState>) -> api::Outcome {
state.run(api::redo)
state.edit(api::redo)
}
+10
View File
@@ -57,6 +57,16 @@ pub fn waypoint(
state.read(move |e| api::waypoint(e, file_id, waypoint_id))
}
#[tauri::command(async)]
pub fn trackpoint(
state: State<AppState>,
file_id: Uuid,
segment_id: Uuid,
index: usize,
) -> Option<api::TrackpointDetails> {
state.read(move |e| api::trackpoint(e, file_id, segment_id, index))
}
/// A file as GPX (UTF-8 bytes), the first byte telling whether the file exists.
#[tauri::command(async)]
#[allow(clippy::too_many_arguments)]
+10 -13
View File
@@ -3,20 +3,20 @@
mod bytes;
mod commands;
pub mod state;
pub mod store;
pub mod workspace;
mod state;
mod store;
mod workspace;
use commands::*;
use tauri::{Emitter, Manager};
/// The engine of the app: each file has its own history, so that undoing only concerns the
/// selected files, and opening or closing a file is not something to undo.
pub type Engine = gpx_engine::Engine<gpx_engine::PerFileHistory>;
pub(crate) type Engine = gpx_engine::Engine<gpx_engine::PerFileHistory>;
/// The GPX files among what the system gave to the app (the arguments of the command line, when a
/// file is opened with it).
pub fn gpx_paths(arguments: impl IntoIterator<Item = String>) -> Vec<std::path::PathBuf> {
fn gpx_paths(arguments: impl IntoIterator<Item = String>) -> Vec<std::path::PathBuf> {
arguments
.into_iter()
.map(std::path::PathBuf::from)
@@ -55,12 +55,6 @@ pub fn run() {
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_opener::init())
.setup(|app| {
#[cfg(desktop)]
{
app.handle()
.plugin(tauri_plugin_updater::Builder::new().build())?;
app.handle().plugin(tauri_plugin_process::init())?;
}
let handle = app.handle().clone();
let emit: state::Emit = std::sync::Arc::new(move |event, payload| {
let _ = handle.emit(event, payload);
@@ -114,7 +108,7 @@ fn menu<R: tauri::Runtime>(app: &tauri::AppHandle<R>) -> tauri::Result<tauri::me
}
/// Gives the builder the commands that reach the engine (which it has to be given as `AppState`).
pub fn register_commands<R: tauri::Runtime>(builder: tauri::Builder<R>) -> tauri::Builder<R> {
fn register_commands<R: tauri::Runtime>(builder: tauri::Builder<R>) -> tauri::Builder<R> {
builder.invoke_handler(tauri::generate_handler![
// selection
selection::select,
@@ -173,6 +167,7 @@ pub fn register_commands<R: tauri::Runtime>(builder: tauri::Builder<R>) -> tauri
queries::can_redo,
queries::can_paste,
queries::waypoint,
queries::trackpoint,
queries::export_file,
queries::exportable_data,
queries::reduction_distances,
@@ -231,7 +226,6 @@ pub fn register_commands<R: tauri::Runtime>(builder: tauri::Builder<R>) -> tauri
disk::list_folder,
disk::create_folder,
disk::rename_path,
disk::rename_file,
disk::move_paths,
disk::delete_paths,
// the system
@@ -239,3 +233,6 @@ pub fn register_commands<R: tauri::Runtime>(builder: tauri::Builder<R>) -> tauri
system::reveal_path,
])
}
#[cfg(test)]
mod tests;
+45 -7
View File
@@ -94,8 +94,11 @@ impl Core {
self.commit(None);
}
/// Runs `f` on the engine, which can change: what changed is kept.
fn editing<T>(&mut self, f: impl FnOnce(&mut Engine) -> T) -> T {
/// Runs `f` on the engine, which can change: what changed is kept, and the files on the disk are
/// renamed like the files of the engine were (an edit of the name, or its undo). Gives what
/// could not be renamed.
fn editing<T>(&mut self, f: impl FnOnce(&mut Engine) -> T) -> (T, Vec<String>) {
let names = self.workspace.names(&self.engine);
let preview = self.workspace.preview;
let preview_before = preview.and_then(|id| signature(&self.engine, id));
let result = f(&mut self.engine);
@@ -104,18 +107,32 @@ impl Core {
if let Some(id) = preview.filter(|_| kept) {
self.workspace.keep(&[id]);
}
let (renamed, errors) = self.workspace.follow_names(&mut self.engine, &names);
// and it goes when something else is selected
let dropped = self.workspace.drop_preview(&mut self.engine);
if kept || dropped.is_some() {
if kept || renamed || dropped.is_some() {
self.commit(dropped.as_ref());
} else {
self.persist();
}
result
(result, errors)
}
/// After files were written (`result`): what changed in the engine is kept and told, with where
/// the files are. Says whether they were written.
/// Like `editing`, for an edit that can rename files: the outcome tells the first thing that
/// could not be renamed (a key of the dictionaries of the frontend, which shows it).
pub fn edit(&mut self, f: impl FnOnce(&mut Engine) -> api::Outcome) -> api::Outcome {
let (outcome, errors) = self.editing(f);
match errors.first() {
Some(error) if !outcome.has_error() => {
outcome.merge(api::Outcome::failed(error.clone()))
}
_ => outcome,
}
}
/// After files were written (`result`): what changed in the engine (the files are called like
/// the files they were written to) is kept and told, with where the files are. Says whether
/// they were written.
pub fn wrote(&mut self, result: Result<api::Outcome, String>) -> Result<bool, String> {
self.commit(result.as_ref().ok().filter(|outcome| outcome.changed));
result.map(|_| true)
@@ -280,6 +297,13 @@ impl AppState {
})
}
/// An engine that keeps its data in a directory of its own, and has nobody to tell.
#[cfg(test)]
pub fn temporary() -> Self {
let directory = std::env::temp_dir().join(format!("gpx-studio-{}", uuid::Uuid::new_v4()));
Self::open(directory, Arc::new(|_, _| {})).expect("the storage can be opened")
}
/// Opens files that the system gave to the app, see `Core::open_external`.
pub fn open_external(&self, paths: Vec<PathBuf>) {
self.core(move |core| core.open_external(&paths));
@@ -301,7 +325,21 @@ impl AppState {
/// Runs `f` on the engine, which can change: what changed is kept (see `Core::editing`).
pub fn run<T: Send + 'static>(&self, f: impl FnOnce(&mut Engine) -> T + Send + 'static) -> T {
self.core(move |core| core.editing(f))
self.core(move |core| {
let (result, errors) = core.editing(f);
for error in errors {
eprintln!("{error}");
}
result
})
}
/// Like `run`, for an edit that can rename files: the outcome tells what could not be renamed.
pub fn edit(
&self,
f: impl FnOnce(&mut Engine) -> api::Outcome + Send + 'static,
) -> api::Outcome {
self.core(move |core| core.edit(f))
}
/// Reads from the engine.
+66
View File
@@ -217,3 +217,69 @@ impl Storage for FileStorage {
Ok(())
}
}
#[cfg(test)]
mod tests {
use crate::Engine;
use gpx_engine::{Action, Command, Load, LoadFiles, Persister};
use super::*;
fn directory() -> PathBuf {
std::env::temp_dir().join(format!("gpx-studio-store-{}", Uuid::new_v4()))
}
fn engine_with_a_file() -> Engine {
let mut engine = Engine::default();
let data = std::fs::read("../gpx-rs/data/simple.gpx").unwrap();
engine
.execute(Action::Edit(Command::LoadFiles(LoadFiles {
files: vec![Load {
data: &data,
name: "simple",
}],
})))
.unwrap();
engine
}
#[test]
fn keeps_the_files_and_the_settings_between_sessions() {
let root = directory();
let engine = engine_with_a_file();
let order = engine.order().to_vec();
let storage = FileStorage::open(&root).unwrap();
pollster::block_on(Persister::default().save(&storage, engine.snapshot())).unwrap();
pollster::block_on(storage.put_setting("units", "\"metric\"")).unwrap();
// another session
let storage = FileStorage::open(&root).unwrap();
let restored = pollster::block_on(Persister::default().restore(&storage)).unwrap();
let mut other = Engine::default();
other.restore(restored);
assert_eq!(other.order(), order);
assert_eq!(
other.file_statistics(&order[0]).unwrap().total_distance,
engine.file_statistics(&order[0]).unwrap().total_distance
);
assert_eq!(storage.settings()["units"], "\"metric\"");
fs::remove_dir_all(root).unwrap();
}
#[test]
fn refuses_a_commit_that_is_not_based_on_the_head() {
let root = directory();
let storage = FileStorage::open(&root).unwrap();
let batch = Batch {
order: Some(vec![]),
..Default::default()
};
assert_eq!(pollster::block_on(storage.commit(&batch)), Ok(Revision(1)));
assert_eq!(
pollster::block_on(storage.commit(&batch)),
Err(CommitError::Stale { head: Revision(1) })
);
fs::remove_dir_all(root).unwrap();
}
}
@@ -6,23 +6,14 @@ use tauri::test::{INVOKE_KEY, get_ipc_response, mock_builder, mock_context, noop
use tauri::webview::InvokeRequest;
use tauri::{WebviewWindow, ipc::CallbackFn, ipc::InvokeBody, ipc::InvokeResponseBody};
/// The origin of the pages of the app, the one Tauri allows the commands from: Windows has no
/// custom protocols, the pages come from `http://tauri.localhost` there.
const ORIGIN: &str = if cfg!(windows) {
"http://tauri.localhost"
} else {
"tauri://localhost"
};
struct App(WebviewWindow<tauri::test::MockRuntime>);
impl App {
fn new() -> Self {
let app = gpx_studio_desktop_lib::register_commands(
mock_builder().manage(crate::temporary_state()),
)
.build(mock_context(noop_assets()))
.unwrap();
let app =
crate::register_commands(mock_builder().manage(crate::state::AppState::temporary()))
.build(mock_context(noop_assets()))
.unwrap();
let window = tauri::WebviewWindowBuilder::new(&app, "main", Default::default())
.build()
.unwrap();
@@ -43,7 +34,7 @@ impl App {
cmd: cmd.into(),
callback: CallbackFn(0),
error: CallbackFn(1),
url: ORIGIN.parse().unwrap(),
url: "tauri://localhost".parse().unwrap(),
body,
headers,
invoke_key: INVOKE_KEY.to_string(),
@@ -59,20 +50,6 @@ impl App {
}
}
/// The error of a command that fails.
fn error(&self, cmd: &str, args: Value) -> Value {
let request = InvokeRequest {
cmd: cmd.into(),
callback: CallbackFn(0),
error: CallbackFn(1),
url: ORIGIN.parse().unwrap(),
body: InvokeBody::Json(args),
headers: Default::default(),
invoke_key: INVOKE_KEY.to_string(),
};
get_ipc_response(&self.0, request).expect_err(&format!("{cmd} did not fail"))
}
fn bytes(&self, cmd: &str, args: Value) -> Vec<u8> {
match self.request(cmd, InvokeBody::Json(args), Default::default()) {
InvokeResponseBody::Raw(bytes) => bytes,
@@ -320,8 +297,8 @@ fn keeps_settings_for_the_session() {
#[test]
fn the_files_are_still_there_in_the_next_session() {
use crate::state::AppState;
use gpx_engine::api;
use gpx_studio_desktop_lib::state::AppState;
let directory =
std::env::temp_dir().join(format!("gpx-studio-session-{}", uuid::Uuid::new_v4()));
@@ -356,14 +333,14 @@ fn only_gpx_files_that_exist_are_taken_from_what_the_system_gives() {
text.to_string_lossy().into_owned(),
directory.join("missing.gpx").to_string_lossy().into_owned(),
];
assert_eq!(gpx_studio_desktop_lib::gpx_paths(arguments), [track]);
assert_eq!(crate::gpx_paths(arguments), [track]);
std::fs::remove_dir_all(directory).unwrap();
}
#[test]
fn a_file_opened_with_the_app_is_opened_selected_and_announced() {
use crate::state::AppState;
use gpx_engine::api;
use gpx_studio_desktop_lib::state::AppState;
use std::sync::{Arc, Mutex};
let directory = std::env::temp_dir().join(format!("gpx-studio-open-{}", uuid::Uuid::new_v4()));
@@ -450,7 +427,7 @@ fn a_file_outside_the_open_folder_is_read_again_when_the_disk_changes() {
let (events, received) = mpsc::channel();
let directory = std::env::temp_dir().join(format!("gpx-store-{}", uuid::Uuid::new_v4()));
let state = gpx_studio_desktop_lib::state::AppState::open(
let state = crate::state::AppState::open(
directory.clone(),
std::sync::Arc::new(move |name, _| {
let _ = events.send(name.to_string());
@@ -470,8 +447,8 @@ fn a_file_outside_the_open_folder_is_read_again_when_the_disk_changes() {
});
let id = uuid::Uuid::parse_str(&id).unwrap();
// the name comes from the path, which does not change: the content does
let signature = |state: &gpx_studio_desktop_lib::state::AppState| {
state.core(move |core| gpx_studio_desktop_lib::workspace::signature(&core.engine, id))
let signature = |state: &crate::state::AppState| {
state.core(move |core| crate::workspace::signature(&core.engine, id))
};
let before = signature(&state);
@@ -492,7 +469,7 @@ fn a_file_outside_the_open_folder_is_read_again_when_the_disk_changes() {
#[test]
fn files_made_from_a_file_of_the_open_folder_are_written_next_to_it_at_once() {
let state = crate::temporary_state();
let state = crate::state::AppState::temporary();
let folder = std::env::temp_dir().join(format!("gpx-tests-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(folder.join("sub")).unwrap();
std::fs::copy("../gpx-rs/data/simple.gpx", folder.join("sub/track.gpx")).unwrap();
@@ -523,25 +500,21 @@ fn files_made_from_a_file_of_the_open_folder_are_written_next_to_it_at_once() {
.values()
.map(|file| file.path.clone().unwrap())
.collect();
// the copy is in the subfolder, named after its name (the one in the file, not of the file)
// the copy is in the subfolder, named after the file
assert!(
paths
.iter()
.any(|path| std::path::Path::new(path).ends_with("sub/simple.gpx")),
paths.iter().any(|path| path.ends_with("sub/track (2).gpx")),
"{paths:?}"
);
// the new file went where the selected file is
assert!(
paths
.iter()
.any(|path| std::path::Path::new(path).ends_with("sub/fresh.gpx")),
paths.iter().any(|path| path.ends_with("sub/fresh.gpx")),
"{paths:?}"
);
}
#[test]
fn the_parts_of_a_split_are_numbered_from_one() {
let state = crate::temporary_state();
let state = crate::state::AppState::temporary();
let folder = std::env::temp_dir().join(format!("gpx-tests-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&folder).unwrap();
std::fs::copy("../gpx-rs/data/simple.gpx", folder.join("track.gpx")).unwrap();
@@ -563,8 +536,8 @@ fn the_parts_of_a_split_are_numbered_from_one() {
.map(|entry| entry.file_name().to_string_lossy().into_owned())
.collect();
names.sort();
// the file stays, its two parts are numbered from 1, under their name (the one in the file)
assert_eq!(names, ["simple (1).gpx", "simple (2).gpx", "track.gpx"]);
// the file stays, its two parts are numbered from 1
assert_eq!(names, ["track (1).gpx", "track (2).gpx", "track.gpx"]);
std::fs::remove_dir_all(folder).unwrap();
}
@@ -608,18 +581,8 @@ fn name_of(app: &App, id: &str) -> String {
.to_string()
}
/// The name of the file on the disk of an open file, without its extension.
fn file_stem_of(app: &App, id: &str) -> String {
let path = app.call("workspace_state", json!({}))["files"][id]["path"].clone();
std::path::Path::new(path.as_str().unwrap())
.file_stem()
.unwrap()
.to_string_lossy()
.into_owned()
}
#[test]
fn a_file_keeps_its_name_and_its_file_is_renamed_apart() {
fn a_file_is_called_like_its_file_and_renaming_it_renames_the_file() {
let app = App::new();
let folder = folder_with(&["outside", "taken"]);
let outcome = app.call(
@@ -627,62 +590,76 @@ fn a_file_keeps_its_name_and_its_file_is_renamed_apart() {
json!({ "paths": [folder.join("outside.gpx")] }),
);
let id = outcome["added"][0].as_str().unwrap().to_string();
let dirty = |app: &App| app.call("workspace_state", json!({}))["files"][&id]["dirty"].clone();
let inside = |name: &str| std::fs::read_to_string(folder.join(format!("{name}.gpx"))).unwrap();
// the name in the file is its name, not the one of the file
assert_eq!(name_of(&app, &id), "Inside");
assert_eq!(file_stem_of(&app, &id), "outside");
assert_eq!(dirty(&app), false);
// the name in the file is not the name of the file: the file wins, and nothing is unsaved
assert_eq!(name_of(&app, &id), "outside");
assert_eq!(
app.call("workspace_state", json!({}))["files"][&id]["dirty"],
false
);
// renaming it is an edit of the file only, which is undone
// renaming renames the file on the disk
app.call("select", json!({ "fileIds": [id], "mode": "replace" }));
let outcome = app.call("metadata", json!({ "name": "renamed", "desc": "" }));
assert!(outcome.get("error").is_none());
assert_eq!(name_of(&app, &id), "renamed");
assert_eq!(file_stem_of(&app, &id), "outside");
assert_eq!(dirty(&app), true);
assert!(folder.join("renamed.gpx").exists());
assert!(!folder.join("outside.gpx").exists());
let path = app.call("workspace_state", json!({}))["files"][&id]["path"].clone();
assert!(path.as_str().unwrap().ends_with("renamed.gpx"));
// the file had nothing unsaved: it is written with its new name, and still has nothing unsaved
let dirty = |app: &App| app.call("workspace_state", json!({}))["files"][&id]["dirty"].clone();
let inside = |name: &str| std::fs::read_to_string(folder.join(format!("{name}.gpx"))).unwrap();
assert_eq!(dirty(&app), false);
assert!(inside("renamed").contains("<name>renamed</name>"));
// undone and redone, on the disk too, still with nothing unsaved
app.call("undo", json!({}));
assert_eq!(name_of(&app, &id), "Inside");
assert_eq!(name_of(&app, &id), "outside");
assert!(folder.join("outside.gpx").exists() && !folder.join("renamed.gpx").exists());
assert_eq!(dirty(&app), false);
assert!(inside("outside").contains("<name>outside</name>"));
app.call("redo", json!({}));
assert_eq!(name_of(&app, &id), "renamed");
assert!(folder.join("renamed.gpx").exists() && !folder.join("outside.gpx").exists());
assert_eq!(dirty(&app), false);
// the file on the disk is renamed apart: not an edit, the file is as saved as it was
let renamed = app.call("rename_file", json!({ "fileId": id, "name": "moved" }));
assert_eq!(renamed, true);
assert!(folder.join("moved.gpx").exists() && !folder.join("outside.gpx").exists());
assert_eq!(file_stem_of(&app, &id), "moved");
assert_eq!(name_of(&app, &id), "Inside");
assert_eq!(dirty(&app), false);
assert_eq!(app.call("can_undo", json!({})), false);
// saving writes to the new place, under the name of the file
app.call("metadata", json!({ "name": "saved", "desc": "" }));
app.call("save_files", json!({ "fileIds": [id] }));
assert!(inside("moved").contains("<name>saved</name>"));
assert_eq!(name_of(&app, &id), "saved");
// the name of another file is not taken
let error = app.error("rename_file", json!({ "fileId": id, "name": "taken" }));
assert_eq!(error, gpx_studio_desktop_lib::workspace::NAME_TAKEN);
assert!(folder.join("moved.gpx").exists());
// the name of another file is not taken, nothing changes
let outcome = app.call("metadata", json!({ "name": "taken", "desc": "" }));
assert_eq!(outcome["error"], crate::workspace::NAME_TAKEN);
assert_eq!(name_of(&app, &id), "renamed");
assert!(folder.join("renamed.gpx").exists());
// a name is one that a file can have
app.call("rename_file", json!({ "fileId": id, "name": "a/b" }));
app.call("metadata", json!({ "name": "a/b", "desc": "" }));
assert_eq!(name_of(&app, &id), "a_b");
assert!(folder.join("a_b.gpx").exists());
// a file with edits is renamed, but not written: its edits are not saved for it
app.call("style", json!({ "color": "#ff0000" }));
assert_eq!(dirty(&app), true);
app.call("metadata", json!({ "name": "edited", "desc": "" }));
assert!(folder.join("edited.gpx").exists());
assert_eq!(dirty(&app), true);
assert!(!inside("edited").contains("ff0000"));
app.call("undo", json!({}));
app.call("undo", json!({}));
assert_eq!(name_of(&app, &id), "a_b");
assert_eq!(dirty(&app), false);
// only the case changes: the same file
app.call("rename_file", json!({ "fileId": id, "name": "A_B" }));
app.call("metadata", json!({ "name": "A_B", "desc": "" }));
assert_eq!(name_of(&app, &id), "A_B");
let names: Vec<String> = std::fs::read_dir(&folder)
.unwrap()
.map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
.collect();
assert!(names.contains(&"A_B.gpx".to_string()));
assert_eq!(names.len(), 2);
assert_eq!(name_of(&app, &id), "saved");
std::fs::remove_dir_all(folder).unwrap();
}
#[test]
fn a_new_file_written_under_another_name_keeps_its_own() {
fn a_new_file_written_under_another_name_takes_it() {
let app = App::new();
let folder = folder_with(&["route"]);
// a new file made in the folder is written there at once: route.gpx is taken
@@ -692,8 +669,7 @@ fn a_new_file_written_under_another_name_keeps_its_own() {
);
let id = created["added"][0].as_str().unwrap().to_string();
assert!(folder.join("route (2).gpx").exists());
// the file keeps its name, whatever the name of the file it was written to
assert_eq!(name_of(&app, &id), "route");
assert_eq!(name_of(&app, &id), "route (2)");
assert_eq!(
app.call("workspace_state", json!({}))["files"][&id]["dirty"],
false
@@ -722,7 +698,7 @@ fn a_file_open_as_a_preview_is_replaced_until_it_is_kept_or_edited() {
.as_array()
.unwrap()
.iter()
.map(|id| file_stem_of(app, id.as_str().unwrap()))
.map(|id| name_of(app, id.as_str().unwrap()))
.collect()
};
+898 -29
View File
@@ -148,7 +148,7 @@ pub struct Entry {
pub is_dir: bool,
}
pub fn is_gpx(path: &Path) -> bool {
fn is_gpx(path: &Path) -> bool {
path.extension()
.and_then(|extension| extension.to_str())
.is_some_and(|extension| extension.eq_ignore_ascii_case("gpx"))
@@ -156,7 +156,7 @@ pub fn is_gpx(path: &Path) -> bool {
/// Compares names the way people read them: the numbers in them by their value ("track 2" before
/// "track 10"), the rest regardless of case.
pub fn natural_cmp(a: &str, b: &str) -> Ordering {
fn natural_cmp(a: &str, b: &str) -> Ordering {
let (mut a, mut b) = (a.chars().peekable(), b.chars().peekable());
loop {
let order = match (a.peek().copied(), b.peek().copied()) {
@@ -695,8 +695,8 @@ impl Workspace {
/// Writes files to the disk, replacing what is there: they are the same as their file from
/// then on. A file that is not on the disk goes in its folder, or at its path in `paths`, or in
/// `folder`, under its name (changed if that is the one of something else). Stops at the first
/// error, the files that were written stay written.
/// `folder`, under its name (changed if that is the one of something else), which the file then
/// has (see `write_file`). Stops at the first error, the files that were written stay written.
pub fn save(
&mut self,
engine: &mut Engine,
@@ -725,7 +725,8 @@ impl Workspace {
/// Writes the new files among `ids` in their folder, under their name. A name that is the one of
/// something else is changed (`name (2)`). Files that would be called the same, like the parts
/// of a split, are numbered from 1 (`name (1)`, `name (2)`). The files keep their name.
/// of a split, are numbered from 1 (`name (1)`, `name (2)`). The files are called like the file
/// they are written to.
pub fn save_new(&mut self, engine: &mut Engine, ids: &[Uuid]) -> Result<api::Outcome, String> {
let names: Vec<Option<(Uuid, PathBuf, String)>> = ids
.iter()
@@ -759,6 +760,30 @@ impl Workspace {
Ok(outcome)
}
/// The names of the files that are on the disk, and whether they are the files on the disk, to
/// tell which ones were renamed by an edit (see `follow_names`).
pub fn names(&self, engine: &Engine) -> BTreeMap<Uuid, (String, bool)> {
self.links
.keys()
.filter_map(|id| {
let name = engine.file_structure(&FileId(*id))?.name.clone();
Some((*id, (name, !self.is_dirty(engine, *id))))
})
.collect()
}
/// The name that a file can be given. A file on the disk is called like its file: the name is
/// one that a file can have (see `file_name`), and not the one of another file next to it
/// (`NAME_TAKEN`). The other files get theirs when they are written.
pub fn name_for(&self, id: Uuid, name: &str) -> Result<String, String> {
if !self.links.contains_key(&id) {
return Ok(name.to_owned());
}
let name = file_name(name);
self.renamed_path(id, &name)?;
Ok(name)
}
/// Where a file on the disk goes when it is called `name`: next to where it is, with the same
/// extension. `None` if it is there already, an error if something else is.
fn renamed_path(&self, id: Uuid, name: &str) -> Result<Option<PathBuf>, String> {
@@ -788,24 +813,49 @@ impl Workspace {
Ok(Some(path))
}
/// Renames the file on the disk of an open file, next to where it is: the name is one that a
/// file can have (see `file_name`), and not the one of another file (`NAME_TAKEN`). It is not
/// an edit, nothing is undone; the file has the same content, so it is as saved as it was.
/// Nothing happens to a file that is not on the disk. Says whether it was renamed.
pub fn rename_file(&mut self, id: Uuid, name: &str) -> Result<bool, String> {
let Some(path) = self.renamed_path(id, name)? else {
return Ok(false);
};
let link = self.links.get_mut(&id).expect("the file is on the disk");
// a file that is gone is written at its new place when it is saved
if !link.missing {
fs::rename(&link.path, &path).map_err(|error| {
/// Renames the files on the disk whose name changed in the engine since it had `before` (see
/// `names`): an edit of the name, or its undo, renames the file. A file that was the one on the
/// disk is written too, so that it still is: the rename is not something to save. A file with
/// edits is not, its edits are not saved for it. A file that cannot be renamed keeps its place,
/// with the reason in the errors. Says whether a file was renamed.
pub fn follow_names(
&mut self,
engine: &mut Engine,
before: &BTreeMap<Uuid, (String, bool)>,
) -> (bool, Vec<String>) {
let mut renamed = false;
let mut errors = vec![];
for (id, (old, clean)) in before {
let Some(structure) = engine.file_structure(&FileId(*id)) else {
continue;
};
if structure.name == *old {
continue;
}
let path = match self.renamed_path(*id, &structure.name) {
Ok(Some(path)) => path,
Ok(None) => continue,
Err(error) => {
errors.push(error);
continue;
}
};
let link = self.links.get_mut(id).expect("the file is on the disk");
// a file that is gone is written at its new place when it is saved
if !link.missing
&& let Err(error) = fs::rename(&link.path, &path)
{
eprintln!("{} cannot be renamed: {error}", link.path.display());
RENAME_FAILED.to_owned()
})?;
errors.push(RENAME_FAILED.to_owned());
continue;
}
link.path = path.clone();
renamed = true;
if *clean && let Err(error) = self.write_file(engine, *id, &path) {
errors.push(error);
}
}
link.path = path;
Ok(true)
(renamed, errors)
}
/// Writes a file to a path of the user's choice, which is the place of the file from then on.
@@ -823,21 +873,30 @@ impl Workspace {
self.write_file(engine, id, path)
}
/// Writes a file to `path`, which it is linked to from then on. Says what changed in the engine
/// (nothing: its name is its own, whatever the name of the file it is written to).
/// Writes a file to `path`, which it is linked to from then on. It is called like the file it is
/// written to (a file has a single name), as if it always had been: that is not an edit to
/// undo. Says what changed in the engine.
fn write_file(
&mut self,
engine: &mut Engine,
id: Uuid,
path: &Path,
) -> Result<api::Outcome, String> {
let unchanged = api::Outcome::failed_none();
let Some(structure) = engine.file_structure(&FileId(id)) else {
return Ok(api::Outcome::failed_none());
};
let name = stem(path);
let renamed = if structure.name != name {
api::rename_file(engine, id, &name)
} else {
api::Outcome::failed_none()
};
let Some(bytes) = api::export_file(engine, id, ExportOptions::ALL) else {
return Ok(unchanged);
return Ok(renamed);
};
write_atomically(path, &bytes).map_err(|error| format!("{}: {error}", path.display()))?;
let Some(signature) = signature(engine, id) else {
return Ok(unchanged);
return Ok(renamed);
};
// the folder, if there is one, may watch what was just written: the hash tells it is known
self.links.insert(
@@ -852,7 +911,7 @@ impl Workspace {
},
);
self.dirs.remove(&id);
Ok(unchanged)
Ok(renamed)
}
/// The folders and the GPX files that are in a folder of the open folder (or in it), the
@@ -967,8 +1026,8 @@ impl Workspace {
Ok(path)
}
/// Renames a file or a folder of the tree. A file keeps its extension, and an open file keeps its
/// name (see `rename_file`). Gives the new path.
/// Renames a file or a folder of the tree that is not an open file (which is renamed in the
/// engine, see `follow_names`). A file keeps its extension. Gives the new path.
pub fn rename_path(&mut self, path: &Path, name: &str) -> Result<PathBuf, String> {
let path = self.tree_item(path)?;
let name = file_name(name);
@@ -1040,3 +1099,813 @@ impl Workspace {
})
}
}
#[cfg(test)]
mod tests {
use gpx_engine::SelectMode;
use super::*;
fn gpx(name: &str) -> String {
format!(
r#"<?xml version="1.0"?><gpx version="1.1" creator="test" xmlns="http://www.topografix.com/GPX/1/1"><metadata><name>{name}</name></metadata><trk><name>{name}</name><trkseg><trkpt lat="50.0" lon="4.0"><ele>10</ele></trkpt><trkpt lat="50.1" lon="4.1"><ele>20</ele></trkpt></trkseg></trk></gpx>"#
)
}
/// The GPX files of a folder and of the folders in it.
pub(super) fn gpx_files(folder: &Path) -> Vec<PathBuf> {
let mut found = vec![];
for entry in fs::read_dir(folder).unwrap().flatten() {
let path = entry.path();
if path.is_dir() {
found.extend(gpx_files(&path));
} else if is_gpx(&path) {
found.push(path);
}
}
found.sort();
found
}
struct Fixture {
folder: PathBuf,
engine: Engine,
workspace: Workspace,
}
impl Fixture {
fn new() -> Self {
let folder =
canonical(&std::env::temp_dir()).join(format!("gpx-ws-{}", Uuid::new_v4()));
fs::create_dir_all(&folder).unwrap();
Self {
folder,
engine: Engine::default(),
workspace: Workspace::default(),
}
}
fn write(&self, name: &str, title: &str) -> PathBuf {
let path = self.folder.join(name);
fs::write(&path, gpx(title)).unwrap();
path
}
/// Opens the folder, and all the files that are in it.
fn open_folder(&mut self) {
let folder = self.folder.clone();
self.workspace.open_folder(&mut self.engine, &folder, false);
let files = gpx_files(&folder);
self.workspace.open_files(&mut self.engine, &files, false);
}
fn reconcile(&mut self, changed: Option<&[PathBuf]>) -> Option<api::Outcome> {
self.workspace.reconcile(&mut self.engine, changed)
}
fn save(&mut self, ids: &[Uuid]) {
self.workspace
.save(&mut self.engine, ids, &BTreeMap::new(), None)
.unwrap();
}
fn ids(&self) -> Vec<Uuid> {
self.engine.order().iter().map(|id| id.0).collect()
}
fn id_named(&self, name: &str) -> Uuid {
self.ids()
.into_iter()
.find(|id| self.name(*id) == name)
.unwrap()
}
fn name(&self, id: Uuid) -> String {
self.engine
.file_structure(&FileId(id))
.unwrap()
.name
.clone()
}
/// What the file holds: the name of its track (its own name is the one of the file).
fn content(&self, id: Uuid) -> String {
self.engine.file_structure(&FileId(id)).unwrap().tracks[0]
.info
.name
.clone()
.unwrap_or_default()
}
fn rename(&mut self, id: Uuid, name: &str) {
api::select(&mut self.engine, &[id], SelectMode::Replace);
assert!(!api::metadata(&mut self.engine, name, "").has_error());
}
fn status(&self, id: Uuid) -> FileStatus {
self.workspace
.state(&self.engine)
.files
.remove(&id.to_string())
.unwrap()
}
}
impl Drop for Fixture {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.folder);
}
}
#[test]
fn an_opened_file_is_clean_until_it_is_edited_and_clean_again_once_saved() {
let mut fx = Fixture::new();
let path = fx.write("a.gpx", "a");
fx.workspace
.open_files(&mut fx.engine, std::slice::from_ref(&path), true);
let id = fx.ids()[0];
assert!(!fx.workspace.is_dirty(&fx.engine, id));
assert_eq!(fx.status(id).path.as_deref(), path.to_str());
fx.rename(id, "renamed");
assert!(fx.workspace.is_dirty(&fx.engine, id));
// nothing is written before it is saved
assert!(fs::read_to_string(&path).unwrap().contains(">a<"));
fx.save(&[id]);
assert!(!fx.workspace.is_dirty(&fx.engine, id));
assert!(fs::read_to_string(&path).unwrap().contains(">renamed<"));
// going back before the save is an edit again
api::select(&mut fx.engine, &[id], SelectMode::Replace);
api::undo(&mut fx.engine);
assert!(fx.workspace.is_dirty(&fx.engine, id));
api::redo(&mut fx.engine);
assert!(!fx.workspace.is_dirty(&fx.engine, id));
}
#[test]
fn a_file_that_is_not_on_the_disk_is_unsaved_until_it_is_given_a_place() {
let mut fx = Fixture::new();
api::new_file(&mut fx.engine, "fresh", None, None, None, false);
let id = fx.ids()[0];
assert!(fx.workspace.is_dirty(&fx.engine, id));
assert_eq!(
fx.workspace.unlinked(&fx.engine, &[id]),
[(id, "fresh".to_string())]
);
// nowhere to put it without being told
fx.save(&[id]);
assert!(fx.workspace.is_dirty(&fx.engine, id));
let path = fx.folder.join("fresh.gpx");
let paths = BTreeMap::from([(id, path.clone())]);
fx.workspace
.save(&mut fx.engine, &[id], &paths, None)
.unwrap();
assert!(path.exists());
assert!(!fx.workspace.is_dirty(&fx.engine, id));
assert!(fx.workspace.unlinked(&fx.engine, &[id]).is_empty());
}
#[test]
fn several_files_without_a_place_go_in_a_folder_with_names_that_are_free() {
let mut fx = Fixture::new();
fx.write("fresh.gpx", "already there");
api::new_file(&mut fx.engine, "fresh", None, None, None, false);
api::new_file(&mut fx.engine, "a/b: c", None, None, None, false);
api::new_file(&mut fx.engine, "fresh", None, None, None, false);
let ids = fx.ids();
let folder = fx.folder.clone();
fx.workspace
.save(&mut fx.engine, &ids, &BTreeMap::new(), Some(&folder))
.unwrap();
for name in ["fresh (2).gpx", "fresh (3).gpx", "a_b_ c.gpx"] {
assert!(fx.folder.join(name).exists(), "{name}");
}
assert!(ids.iter().all(|id| !fx.workspace.is_dirty(&fx.engine, *id)));
}
#[test]
fn what_this_app_writes_is_not_a_change_of_the_disk() {
let mut fx = Fixture::new();
let path = fx.write("a.gpx", "a");
fx.open_folder();
let id = fx.ids()[0];
api::select(&mut fx.engine, &[id], SelectMode::Replace);
assert!(!api::style(&mut fx.engine, Some("#ff0000"), None, None).has_error());
fx.save(&[id]);
assert!(fx.reconcile(Some(&[path])).is_none());
assert!(!fx.status(id).replaced && !fx.status(id).dirty);
}
#[test]
fn the_folders_of_the_files_outside_the_open_folder_are_watched_too() {
let mut fx = Fixture::new();
let inside = fx.write("in.gpx", "in");
let elsewhere = canonical(&std::env::temp_dir()).join(format!("gpx-ws-{}", Uuid::new_v4()));
fs::create_dir_all(&elsewhere).unwrap();
let (one, two) = (elsewhere.join("one.gpx"), elsewhere.join("two.gpx"));
fs::write(&one, gpx("one")).unwrap();
fs::write(&two, gpx("two")).unwrap();
let folder = fx.folder.clone();
// no folder: only the folder of the files
fx.workspace.open_files(&mut fx.engine, &[one, two], false);
assert_eq!(fx.workspace.watched(), [(elsewhere.clone(), false)]);
// the open folder as a whole, and the file in it needs nothing more
fx.workspace.open_folder(&mut fx.engine, &folder, false);
fx.workspace.open_files(&mut fx.engine, &[inside], false);
assert_eq!(
fx.workspace.watched(),
[(folder, true), (elsewhere.clone(), false)]
);
// closing the files stops it
let ids = fx.ids();
fx.workspace.close_files(&mut fx.engine, &ids, true);
assert_eq!(fx.workspace.watched(), [(fx.folder.clone(), true)]);
fs::remove_dir_all(elsewhere).unwrap();
}
#[test]
fn opening_a_folder_does_not_open_its_files() {
let mut fx = Fixture::new();
fx.write("a.gpx", "a");
let folder = fx.folder.clone();
let outcome = fx.workspace.open_folder(&mut fx.engine, &folder, false);
assert!(!outcome.changed);
assert!(fx.ids().is_empty());
assert_eq!(fx.workspace.folder.as_deref(), Some(folder.as_path()));
}
#[test]
fn folders_are_made_renamed_and_moved_and_the_open_files_follow() {
let mut fx = Fixture::new();
let a = fx.write("a.gpx", "a");
fx.open_folder();
let id = fx.ids()[0];
let root = fx.folder.clone();
let path_of = |fx: &Fixture| PathBuf::from(fx.status(id).path.unwrap());
let first = fx.workspace.create_folder(&root, "New folder").unwrap();
let second = fx.workspace.create_folder(&root, "New folder").unwrap();
assert_eq!(first, root.join("New folder"));
assert_eq!(second, root.join("New folder 2"));
fx.workspace.move_paths(&[a], &first).unwrap();
assert_eq!(path_of(&fx), first.join("a.gpx"));
assert!(first.join("a.gpx").exists() && !fx.status(id).dirty);
let trips = fx.workspace.rename_path(&first, "Trips").unwrap();
assert_eq!(path_of(&fx), root.join("Trips/a.gpx"));
// a folder does not go into itself, nor onto something else
assert!(
fx.workspace
.move_paths(std::slice::from_ref(&trips), &trips)
.is_err()
);
assert_eq!(
fx.workspace.rename_path(&trips, "New folder 2"),
Err(NAME_TAKEN.to_owned())
);
fx.workspace.move_paths(&[trips], &second).unwrap();
assert_eq!(path_of(&fx), second.join("Trips/a.gpx"));
// a file keeps its extension
let closed = fx.write("c.gpx", "c");
assert_eq!(
fx.workspace.rename_path(&closed, "d").unwrap(),
root.join("d.gpx")
);
// the open folder and what is not in it are left alone
assert!(fx.workspace.rename_path(&root, "x").is_err());
let elsewhere = canonical(&std::env::temp_dir());
assert!(fx.workspace.rename_path(&elsewhere, "x").is_err());
assert!(fx.workspace.create_folder(&elsewhere, "x").is_err());
}
#[test]
fn deleted_files_are_closed_unless_they_have_edits() {
let mut fx = Fixture::new();
let a = fx.write("a.gpx", "a");
let b = fx.write("b.gpx", "b");
fx.open_folder();
let (id_a, id_b) = (fx.id_named("a"), fx.id_named("b"));
api::select(&mut fx.engine, &[id_b], SelectMode::Replace);
assert!(!api::style(&mut fx.engine, Some("#ff0000"), None, None).has_error());
let outcome = fx
.workspace
.delete_paths(&mut fx.engine, &[a.clone(), b.clone()], |paths| {
paths.iter().for_each(|path| fs::remove_file(path).unwrap());
Ok(())
})
.unwrap();
assert!(outcome.changed);
assert_eq!(fx.ids(), [id_b]);
assert!(!fx.ids().contains(&id_a));
let status = fx.status(id_b);
assert!(status.dirty && status.missing);
assert!(!a.exists() && !b.exists());
}
#[test]
fn the_tree_of_the_folder_shows_folders_first_and_only_gpx_files() {
let mut fx = Fixture::new();
fx.write("b.gpx", "b");
fx.write("A.GPX", "a");
fx.write("b 10.gpx", "b 10");
fx.write("b 2.gpx", "b 2");
fx.write("notes.txt", "not a track");
fx.write(".hidden.gpx", "hidden");
fs::create_dir(fx.folder.join("zoo")).unwrap();
fs::create_dir(fx.folder.join("Alps")).unwrap();
fs::create_dir(fx.folder.join(".git")).unwrap();
fx.write("zoo/c.gpx", "c");
let folder = fx.folder.clone();
fx.workspace.open_folder(&mut fx.engine, &folder, false);
let names = |entries: Vec<Entry>| -> Vec<(String, bool)> {
entries.into_iter().map(|e| (e.name, e.is_dir)).collect()
};
assert_eq!(
names(fx.workspace.list_folder(&folder).unwrap()),
[
("Alps".to_string(), true),
("zoo".to_string(), true),
("A.GPX".to_string(), false),
("b.gpx".to_string(), false),
("b 2.gpx".to_string(), false),
("b 10.gpx".to_string(), false),
]
);
assert_eq!(
names(fx.workspace.list_folder(&folder.join("zoo")).unwrap()),
[("c.gpx".to_string(), false)]
);
// only what is in the open folder can be listed
let elsewhere = canonical(&std::env::temp_dir());
assert!(fx.workspace.list_folder(&elsewhere).is_err());
}
#[test]
fn names_are_sorted_by_the_numbers_they_hold() {
let mut names = vec![
"track 10",
"track 2",
"Track 1",
"track",
"track 02b",
"track 2a",
"b",
"A",
];
names.sort_by(|a, b| natural_cmp(a, b).then_with(|| a.cmp(b)));
assert_eq!(
names,
[
"A",
"b",
"track",
"Track 1",
"track 2",
"track 2a",
"track 02b",
"track 10",
]
);
}
#[test]
fn a_file_without_edits_is_read_again_when_the_disk_changes() {
let mut fx = Fixture::new();
let a = fx.write("a.gpx", "a");
fx.open_folder();
let id = fx.ids()[0];
fx.write("a.gpx", "theirs");
let outcome = fx.reconcile(Some(std::slice::from_ref(&a))).unwrap();
assert!(outcome.changed);
// the same file, now the one on the disk
assert_eq!(fx.ids(), [id]);
assert_eq!(fx.content(id), "theirs");
let status = fx.status(id);
assert!(!status.dirty && !status.replaced);
// looking again changes nothing
assert!(fx.reconcile(Some(std::slice::from_ref(&a))).is_none());
}
#[test]
fn a_file_with_edits_is_flagged_when_the_disk_changes_and_not_read_again() {
let mut fx = Fixture::new();
let a = fx.write("a.gpx", "a");
fx.open_folder();
let id = fx.ids()[0];
fx.rename(id, "mine");
fx.write("a.gpx", "theirs");
let outcome = fx.reconcile(Some(std::slice::from_ref(&a))).unwrap();
assert!(!outcome.changed);
assert_eq!(fx.name(id), "mine");
let status = fx.status(id);
assert!(status.dirty && status.replaced && !status.missing);
// looking again changes nothing
assert!(fx.reconcile(Some(std::slice::from_ref(&a))).is_none());
// the disk goes back to what was read: only the edits are left
fx.write("a.gpx", "a");
assert!(fx.reconcile(Some(std::slice::from_ref(&a))).is_some());
let status = fx.status(id);
assert!(status.dirty && !status.replaced);
}
#[test]
fn the_user_can_take_the_disk_instead_of_the_edits() {
let mut fx = Fixture::new();
fx.write("a.gpx", "a");
fx.open_folder();
let id = fx.ids()[0];
fx.rename(id, "mine");
fx.write("a.gpx", "theirs");
fx.reconcile(None);
assert!(fx.status(id).replaced);
fx.workspace.reload(&mut fx.engine, &[id]).unwrap();
assert_eq!(fx.content(id), "theirs");
let status = fx.status(id);
assert!(!status.dirty && !status.replaced);
// and it is one undo step
api::select(&mut fx.engine, &[id], SelectMode::Replace);
api::undo(&mut fx.engine);
assert_eq!(fx.content(id), "mine");
}
#[test]
fn saving_overwrites_what_replaced_the_file() {
let mut fx = Fixture::new();
let a = fx.write("a.gpx", "a");
fx.open_folder();
let id = fx.ids()[0];
fx.rename(id, "mine");
fx.write("a.gpx", "theirs");
fx.reconcile(None);
assert!(fx.status(id).replaced);
fx.save(&[id]);
assert!(fs::read_to_string(a).unwrap().contains(">mine<"));
assert!(!fx.status(id).replaced && !fx.status(id).dirty);
}
#[test]
fn a_file_that_is_gone_from_the_disk_stays_open_and_dirty_until_it_is_saved_again() {
let mut fx = Fixture::new();
let a = fx.write("a.gpx", "a");
fx.open_folder();
let id = fx.ids()[0];
fs::remove_file(&a).unwrap();
assert!(fx.reconcile(Some(std::slice::from_ref(&a))).is_some());
assert_eq!(fx.ids(), [id]);
let status = fx.status(id);
assert!(status.dirty && status.missing && status.path.is_some());
// saving puts it back
fx.save(&[id]);
assert!(a.exists());
let status = fx.status(id);
assert!(!status.dirty && !status.missing);
}
#[test]
fn a_file_that_comes_back_different_is_read_again() {
let mut fx = Fixture::new();
let a = fx.write("a.gpx", "a");
fx.open_folder();
let id = fx.ids()[0];
fs::remove_file(&a).unwrap();
fx.reconcile(None);
assert!(fx.status(id).missing);
fx.write("a.gpx", "back");
fx.reconcile(None);
assert_eq!(fx.content(id), "back");
let status = fx.status(id);
assert!(!status.dirty && !status.missing);
}
#[test]
fn what_changed_while_the_app_was_closed_is_found_when_it_starts() {
let mut fx = Fixture::new();
let a = fx.write("a.gpx", "a");
fx.open_folder();
let id = fx.ids()[0];
fx.write("a.gpx", "changed");
assert!(fx.reconcile(None).is_some());
assert_eq!(fx.content(id), "changed");
fs::remove_file(a).unwrap();
assert!(fx.reconcile(None).is_some());
assert!(fx.status(id).missing);
}
#[test]
fn new_files_made_from_a_file_of_the_folder_are_saved_next_to_it() {
let mut fx = Fixture::new();
fs::create_dir(fx.folder.join("sub")).unwrap();
fx.write("sub/b.gpx", "b");
fx.write("a.gpx", "a");
fx.open_folder();
let b = fx.id_named("b");
let sub = fx.folder.join("sub");
assert_eq!(fx.workspace.source_dir(&[b]), Some(canonical(&sub)));
let before = fx.ids();
api::select(&mut fx.engine, &[b], SelectMode::Replace);
let outcome = api::duplicate(&mut fx.engine);
let copy = fx
.ids()
.into_iter()
.find(|id| !before.contains(id))
.unwrap();
fx.workspace.inherit(outcome.added(), &canonical(&sub));
assert_eq!(fx.status(copy).folder.as_deref(), canonical(&sub).to_str());
assert!(fx.status(copy).path.is_none() && fx.status(copy).dirty);
// nobody needs to be asked where it goes
assert!(fx.workspace.unlinked(&fx.engine, &[copy]).is_empty());
fx.save(&[copy]);
assert!(sub.join("b (2).gpx").exists());
let status = fx.status(copy);
assert!(!status.dirty && status.folder.is_none());
assert_eq!(
status.path.as_deref(),
canonical(&sub.join("b (2).gpx")).to_str()
);
// the copy of the copy is next to it as well
assert_eq!(fx.workspace.source_dir(&[copy]), Some(canonical(&sub)));
}
#[test]
fn a_file_outside_the_open_folder_hands_nothing_down() {
let mut fx = Fixture::new();
let elsewhere = canonical(&std::env::temp_dir()).join(format!("gpx-ws-{}", Uuid::new_v4()));
fs::create_dir_all(&elsewhere).unwrap();
let outside = elsewhere.join("o.gpx");
fs::write(&outside, gpx("o")).unwrap();
let folder = fx.folder.clone();
fx.workspace.open_folder(&mut fx.engine, &folder, false);
fx.workspace
.open_files(&mut fx.engine, std::slice::from_ref(&outside), true);
let id = fx.ids()[0];
assert_eq!(fx.workspace.source_dir(&[id]), None);
// a new file with no source is not linked to a folder by `source_dir`: the caller falls back
fs::remove_dir_all(elsewhere).unwrap();
}
#[test]
fn closing_files_asks_what_to_do_with_the_unsaved_ones() {
let mut fx = Fixture::new();
fx.write("a.gpx", "a");
fx.write("b.gpx", "b");
fx.open_folder();
let (a, b) = (fx.id_named("a"), fx.id_named("b"));
fx.rename(a, "edited");
assert_eq!(fx.workspace.unsaved(&fx.engine, &[a, b]), [a]);
// without a choice what has edits stays
let outcome = fx.workspace.close_files(&mut fx.engine, &[a, b], false);
assert!(outcome.changed);
assert_eq!(fx.ids(), [a]);
// saved first
fx.save(&[a]);
fx.workspace.close_files(&mut fx.engine, &[a], false);
assert!(fx.ids().is_empty());
assert!(
fs::read_to_string(fx.folder.join("a.gpx"))
.unwrap()
.contains("edited")
);
assert!(fx.workspace.links.is_empty());
}
#[test]
fn closing_files_can_discard_their_edits() {
let mut fx = Fixture::new();
fx.write("a.gpx", "a");
fx.open_folder();
let a = fx.ids()[0];
fx.rename(a, "edited");
api::new_file(&mut fx.engine, "fresh", None, None, None, false);
let fresh = fx.id_named("fresh");
fx.workspace.close_files(&mut fx.engine, &[a, fresh], true);
assert!(fx.ids().is_empty());
assert!(
fs::read_to_string(fx.folder.join("a.gpx"))
.unwrap()
.contains(">a<")
);
}
#[test]
fn closing_the_folder_closes_every_file() {
let mut fx = Fixture::new();
fx.write("a.gpx", "a");
fx.open_folder();
api::new_file(&mut fx.engine, "fresh", None, None, None, false);
assert_eq!(fx.ids().len(), 2);
// the new file has nowhere to go: it has to be discarded
let outcome = fx.workspace.close_folder(&mut fx.engine, false);
assert!(outcome.changed);
assert_eq!(fx.ids().len(), 1);
assert!(fx.workspace.folder.is_none());
let outcome = fx.workspace.close_folder(&mut fx.engine, true);
assert!(outcome.changed);
assert!(fx.ids().is_empty());
}
#[test]
fn opening_another_folder_closes_the_first_with_all_its_files() {
let mut fx = Fixture::new();
fx.write("a.gpx", "a");
fx.open_folder();
let a = fx.ids()[0];
fx.rename(a, "edited");
let other = canonical(&std::env::temp_dir()).join(format!("gpx-ws-{}", Uuid::new_v4()));
fs::create_dir_all(&other).unwrap();
// the edits stay, nothing is lost without a choice
fx.workspace.open_folder(&mut fx.engine, &other, false);
assert_eq!(fx.ids(), [a]);
assert_eq!(fx.workspace.folder.as_deref(), Some(other.as_path()));
let first = fx.folder.clone();
fx.workspace.open_folder(&mut fx.engine, &first, true);
assert!(fx.ids().is_empty());
assert!(
fs::read_to_string(fx.folder.join("a.gpx"))
.unwrap()
.contains(">a<")
);
fs::remove_dir_all(other).unwrap();
}
#[test]
fn opening_the_same_folder_again_changes_nothing() {
let mut fx = Fixture::new();
fx.write("a.gpx", "a");
fx.open_folder();
let folder = fx.folder.clone();
let outcome = fx.workspace.open_folder(&mut fx.engine, &folder, true);
assert!(!outcome.changed);
assert_eq!(fx.ids().len(), 1);
}
#[test]
fn a_failed_save_stops_at_the_file_and_leaves_it_dirty() {
let mut fx = Fixture::new();
fx.write("a.gpx", "a");
fx.open_folder();
let id = fx.ids()[0];
fx.rename(id, "edited");
// the place of the file is taken by a folder
fs::remove_file(fx.folder.join("a.gpx")).unwrap();
fs::create_dir(fx.folder.join("a.gpx")).unwrap();
let result = fx
.workspace
.save(&mut fx.engine, &[id], &BTreeMap::new(), None);
assert!(result.is_err());
assert!(fx.workspace.is_dirty(&fx.engine, id));
}
#[test]
fn saving_as_gives_the_file_another_place() {
let mut fx = Fixture::new();
let a = fx.write("a.gpx", "a");
fx.write("b.gpx", "b");
fx.open_folder();
let id = fx.id_named("a");
let other = fx.id_named("b");
fx.rename(id, "edited");
let target = fx.folder.join("copy.gpx");
fx.workspace.save_as(&mut fx.engine, id, &target).unwrap();
assert!(fs::read_to_string(&target).unwrap().contains("edited"));
assert!(fs::read_to_string(a).unwrap().contains(">a<"));
let status = fx.status(id);
assert!(!status.dirty);
assert_eq!(status.path.as_deref(), canonical(&target).to_str());
// the place of another open file is not available
let taken = fx.folder.join("b.gpx");
assert!(fx.workspace.save_as(&mut fx.engine, id, &taken).is_err());
assert!(!fx.workspace.is_dirty(&fx.engine, other));
}
}
#[cfg(test)]
mod restart_tests {
use gpx_engine::Persister;
use super::*;
use crate::store::FileStorage;
/// What the app does when it starts again: the engine and the links are read from what was
/// kept.
fn restart(engine: &Engine, workspace: &Workspace, root: &Path) -> (Engine, Workspace) {
let storage = FileStorage::open(root).unwrap();
pollster::block_on(Persister::default().save(&storage, engine.snapshot())).unwrap();
let mut restarted = Engine::default();
let restored = pollster::block_on(Persister::default().restore(&storage)).unwrap();
restarted.restore(restored);
let links = serde_json::to_string(workspace).unwrap();
(restarted, serde_json::from_str(&links).unwrap())
}
fn setup() -> (PathBuf, Engine, Workspace, Vec<Uuid>) {
let root = std::env::temp_dir().join(format!("gpx-restart-{}", Uuid::new_v4()));
let folder = root.join("tracks");
fs::create_dir_all(&folder).unwrap();
for name in ["with_tracks", "with_time", "with_waypoint"] {
let _ = fs::copy(
format!("../gpx-rs/data/{name}.gpx"),
folder.join(format!("{name}.gpx")),
);
}
let mut engine = Engine::default();
let mut workspace = Workspace::default();
workspace.open_folder(&mut engine, &folder, false);
workspace.open_files(&mut engine, &tests::gpx_files(&folder), false);
let ids = engine.order().iter().map(|id| id.0).collect();
(root, engine, workspace, ids)
}
#[test]
fn files_that_were_not_edited_are_not_unsaved_after_a_restart() {
let (root, engine, workspace, ids) = setup();
assert!(ids.len() >= 2);
let (restarted, mut workspace) = restart(&engine, &workspace, &root.join("store"));
// the files are the same, but the engine knows their contents by new identities
assert!(ids.iter().any(|id| workspace.is_dirty(&restarted, *id)));
workspace.verify(&restarted);
assert!(ids.iter().all(|id| !workspace.is_dirty(&restarted, *id)));
fs::remove_dir_all(root).unwrap();
}
#[test]
fn files_that_were_edited_are_still_unsaved_after_a_restart() {
let (root, mut engine, workspace, ids) = setup();
api::select(&mut engine, &[ids[0]], gpx_engine::SelectMode::Replace);
api::metadata(&mut engine, "edited", "");
assert!(workspace.is_dirty(&engine, ids[0]));
let (restarted, mut workspace) = restart(&engine, &workspace, &root.join("store"));
workspace.verify(&restarted);
assert!(workspace.is_dirty(&restarted, ids[0]));
assert!(
ids[1..]
.iter()
.all(|id| !workspace.is_dirty(&restarted, *id))
);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn links_made_before_the_content_was_kept_are_checked_against_the_disk() {
let (root, mut engine, mut workspace, ids) = setup();
api::select(&mut engine, &[ids[0]], gpx_engine::SelectMode::Replace);
api::metadata(&mut engine, "edited", "");
for link in workspace.links.values_mut() {
link.export_hash = 0;
}
let (restarted, mut workspace) = restart(&engine, &workspace, &root.join("store"));
workspace.verify(&restarted);
assert!(workspace.is_dirty(&restarted, ids[0]));
assert!(
ids[1..]
.iter()
.all(|id| !workspace.is_dirty(&restarted, *id))
);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn the_folders_of_new_files_and_the_old_flag_name_survive_a_restart() {
let (root, engine, mut workspace, ids) = setup();
let folder = workspace.folder.clone().unwrap();
let fresh = Uuid::new_v4();
workspace.inherit(&[fresh.to_string()], &folder);
workspace.links.get_mut(&ids[0]).unwrap().replaced = true;
let json = serde_json::to_string(&workspace).unwrap();
// links written by the previous version had `conflict`, which is the same thing
let json = json.replace("\"replaced\"", "\"conflict\"");
assert!(json.contains("\"conflict\":true"));
let read: Workspace = serde_json::from_str(&json).unwrap();
assert!(read.links[&ids[0]].replaced);
assert_eq!(read.dirs.get(&fresh), Some(&folder));
let _ = engine;
fs::remove_dir_all(root).unwrap();
}
}
+1 -10
View File
@@ -27,8 +27,7 @@
},
"bundle": {
"active": true,
"targets": ["app", "dmg", "appimage", "deb", "rpm", "nsis"],
"macOS": { "signingIdentity": "-" },
"targets": "all",
"fileAssociations": [
{
"ext": ["gpx"],
@@ -45,13 +44,5 @@
"icons/icon.icns",
"icons/icon.ico"
]
},
"plugins": {
"updater": {
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDE5NTFDQzVDOUYwNEMyNEMKUldSTXdnU2ZYTXhSR1ZXRDV6aVErc3dUWXBaK0VGSitYRnFFR21hZ2s5UEJTT01aYkE5Unp5c0cKdW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEFFNTU3Q0Y1NzhFODkyMTEKUldRUmt1aDQ5WHhWcmdXQmx0UG83V29TenRxSVJjdkc4ckN1Zi93ajc3ZUhVUVp3eFlCOXphb1IK",
"endpoints": [
"https://github.com/gpxstudio/gpx.studio/releases/latest/download/latest.json"
]
}
}
}
-15
View File
@@ -1,15 +0,0 @@
//! The tests of the desktop app. They are integration tests, in a single binary, rather than unit
//! tests: on Windows, only test binaries can be given the manifest that the app needs to start
//! (see `build.rs`).
mod commands;
mod store;
mod workspace;
use gpx_studio_desktop_lib::state::AppState;
/// An engine that keeps its data in a directory of its own, and has nobody to tell.
fn temporary_state() -> AppState {
let directory = std::env::temp_dir().join(format!("gpx-studio-{}", uuid::Uuid::new_v4()));
AppState::open(directory, std::sync::Arc::new(|_, _| {})).expect("the storage can be opened")
}
-69
View File
@@ -1,69 +0,0 @@
//! The storage of the engine on the file system (`store`).
use std::fs;
use std::path::PathBuf;
use gpx_engine::{
Action, Batch, Command, CommitError, Load, LoadFiles, Persister, Revision, Storage,
};
use gpx_studio_desktop_lib::Engine;
use gpx_studio_desktop_lib::store::FileStorage;
use uuid::Uuid;
fn directory() -> PathBuf {
std::env::temp_dir().join(format!("gpx-studio-store-{}", Uuid::new_v4()))
}
fn engine_with_a_file() -> Engine {
let mut engine = Engine::default();
let data = std::fs::read("../gpx-rs/data/simple.gpx").unwrap();
engine
.execute(Action::Edit(Command::LoadFiles(LoadFiles {
files: vec![Load {
data: &data,
name: "simple",
}],
})))
.unwrap();
engine
}
#[test]
fn keeps_the_files_and_the_settings_between_sessions() {
let root = directory();
let engine = engine_with_a_file();
let order = engine.order().to_vec();
let storage = FileStorage::open(&root).unwrap();
pollster::block_on(Persister::default().save(&storage, engine.snapshot())).unwrap();
pollster::block_on(storage.put_setting("units", "\"metric\"")).unwrap();
// another session
let storage = FileStorage::open(&root).unwrap();
let restored = pollster::block_on(Persister::default().restore(&storage)).unwrap();
let mut other = Engine::default();
other.restore(restored);
assert_eq!(other.order(), order);
assert_eq!(
other.file_statistics(&order[0]).unwrap().total_distance,
engine.file_statistics(&order[0]).unwrap().total_distance
);
assert_eq!(storage.settings()["units"], "\"metric\"");
fs::remove_dir_all(root).unwrap();
}
#[test]
fn refuses_a_commit_that_is_not_based_on_the_head() {
let root = directory();
let storage = FileStorage::open(&root).unwrap();
let batch = Batch {
order: Some(vec![]),
..Default::default()
};
assert_eq!(pollster::block_on(storage.commit(&batch)), Ok(Revision(1)));
assert_eq!(
pollster::block_on(storage.commit(&batch)),
Err(CommitError::Stale { head: Revision(1) })
);
fs::remove_dir_all(root).unwrap();
}
-811
View File
@@ -1,811 +0,0 @@
//! The places of the files of the engine on the disk (`workspace`).
use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
use gpx_engine::{FileId, SelectMode, api};
use gpx_studio_desktop_lib::Engine;
use gpx_studio_desktop_lib::workspace::*;
use uuid::Uuid;
fn gpx(name: &str) -> String {
format!(
r#"<?xml version="1.0"?><gpx version="1.1" creator="test" xmlns="http://www.topografix.com/GPX/1/1"><metadata><name>{name}</name></metadata><trk><name>{name}</name><trkseg><trkpt lat="50.0" lon="4.0"><ele>10</ele></trkpt><trkpt lat="50.1" lon="4.1"><ele>20</ele></trkpt></trkseg></trk></gpx>"#
)
}
/// The GPX files of a folder and of the folders in it.
pub fn gpx_files(folder: &Path) -> Vec<PathBuf> {
let mut found = vec![];
for entry in fs::read_dir(folder).unwrap().flatten() {
let path = entry.path();
if path.is_dir() {
found.extend(gpx_files(&path));
} else if is_gpx(&path) {
found.push(path);
}
}
found.sort();
found
}
struct Fixture {
folder: PathBuf,
engine: Engine,
workspace: Workspace,
}
impl Fixture {
fn new() -> Self {
let folder = canonical(&std::env::temp_dir()).join(format!("gpx-ws-{}", Uuid::new_v4()));
fs::create_dir_all(&folder).unwrap();
Self {
folder,
engine: Engine::default(),
workspace: Workspace::default(),
}
}
fn write(&self, name: &str, title: &str) -> PathBuf {
let path = self.folder.join(name);
fs::write(&path, gpx(title)).unwrap();
path
}
/// Opens the folder, and all the files that are in it.
fn open_folder(&mut self) {
let folder = self.folder.clone();
self.workspace.open_folder(&mut self.engine, &folder, false);
let files = gpx_files(&folder);
self.workspace.open_files(&mut self.engine, &files, false);
}
fn reconcile(&mut self, changed: Option<&[PathBuf]>) -> Option<api::Outcome> {
self.workspace.reconcile(&mut self.engine, changed)
}
fn save(&mut self, ids: &[Uuid]) {
self.workspace
.save(&mut self.engine, ids, &BTreeMap::new(), None)
.unwrap();
}
fn ids(&self) -> Vec<Uuid> {
self.engine.order().iter().map(|id| id.0).collect()
}
fn id_named(&self, name: &str) -> Uuid {
self.ids()
.into_iter()
.find(|id| self.name(*id) == name)
.unwrap()
}
fn name(&self, id: Uuid) -> String {
self.engine
.file_structure(&FileId(id))
.unwrap()
.name
.clone()
}
/// What the file holds: the name of its track (its own name is the one of the file).
fn content(&self, id: Uuid) -> String {
self.engine.file_structure(&FileId(id)).unwrap().tracks[0]
.info
.name
.clone()
.unwrap_or_default()
}
fn rename(&mut self, id: Uuid, name: &str) {
api::select(&mut self.engine, &[id], SelectMode::Replace);
assert!(!api::metadata(&mut self.engine, name, "").has_error());
}
fn status(&self, id: Uuid) -> FileStatus {
self.workspace
.state(&self.engine)
.files
.remove(&id.to_string())
.unwrap()
}
}
impl Drop for Fixture {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.folder);
}
}
#[test]
fn an_opened_file_is_clean_until_it_is_edited_and_clean_again_once_saved() {
let mut fx = Fixture::new();
let path = fx.write("a.gpx", "a");
fx.workspace
.open_files(&mut fx.engine, std::slice::from_ref(&path), true);
let id = fx.ids()[0];
assert!(!fx.workspace.is_dirty(&fx.engine, id));
assert_eq!(fx.status(id).path.as_deref(), path.to_str());
fx.rename(id, "renamed");
assert!(fx.workspace.is_dirty(&fx.engine, id));
// nothing is written before it is saved
assert!(fs::read_to_string(&path).unwrap().contains(">a<"));
fx.save(&[id]);
assert!(!fx.workspace.is_dirty(&fx.engine, id));
assert!(fs::read_to_string(&path).unwrap().contains(">renamed<"));
// going back before the save is an edit again
api::select(&mut fx.engine, &[id], SelectMode::Replace);
api::undo(&mut fx.engine);
assert!(fx.workspace.is_dirty(&fx.engine, id));
api::redo(&mut fx.engine);
assert!(!fx.workspace.is_dirty(&fx.engine, id));
}
#[test]
fn a_file_that_is_not_on_the_disk_is_unsaved_until_it_is_given_a_place() {
let mut fx = Fixture::new();
api::new_file(&mut fx.engine, "fresh", None, None, None, false);
let id = fx.ids()[0];
assert!(fx.workspace.is_dirty(&fx.engine, id));
assert_eq!(
fx.workspace.unlinked(&fx.engine, &[id]),
[(id, "fresh".to_string())]
);
// nowhere to put it without being told
fx.save(&[id]);
assert!(fx.workspace.is_dirty(&fx.engine, id));
let path = fx.folder.join("fresh.gpx");
let paths = BTreeMap::from([(id, path.clone())]);
fx.workspace
.save(&mut fx.engine, &[id], &paths, None)
.unwrap();
assert!(path.exists());
assert!(!fx.workspace.is_dirty(&fx.engine, id));
assert!(fx.workspace.unlinked(&fx.engine, &[id]).is_empty());
}
#[test]
fn several_files_without_a_place_go_in_a_folder_with_names_that_are_free() {
let mut fx = Fixture::new();
fx.write("fresh.gpx", "already there");
api::new_file(&mut fx.engine, "fresh", None, None, None, false);
api::new_file(&mut fx.engine, "a/b: c", None, None, None, false);
api::new_file(&mut fx.engine, "fresh", None, None, None, false);
let ids = fx.ids();
let folder = fx.folder.clone();
fx.workspace
.save(&mut fx.engine, &ids, &BTreeMap::new(), Some(&folder))
.unwrap();
for name in ["fresh (2).gpx", "fresh (3).gpx", "a_b_ c.gpx"] {
assert!(fx.folder.join(name).exists(), "{name}");
}
assert!(ids.iter().all(|id| !fx.workspace.is_dirty(&fx.engine, *id)));
}
#[test]
fn what_this_app_writes_is_not_a_change_of_the_disk() {
let mut fx = Fixture::new();
let path = fx.write("a.gpx", "a");
fx.open_folder();
let id = fx.ids()[0];
api::select(&mut fx.engine, &[id], SelectMode::Replace);
assert!(!api::style(&mut fx.engine, Some("#ff0000"), None, None).has_error());
fx.save(&[id]);
assert!(fx.reconcile(Some(&[path])).is_none());
assert!(!fx.status(id).replaced && !fx.status(id).dirty);
}
#[test]
fn the_folders_of_the_files_outside_the_open_folder_are_watched_too() {
let mut fx = Fixture::new();
let inside = fx.write("in.gpx", "in");
let elsewhere = canonical(&std::env::temp_dir()).join(format!("gpx-ws-{}", Uuid::new_v4()));
fs::create_dir_all(&elsewhere).unwrap();
let (one, two) = (elsewhere.join("one.gpx"), elsewhere.join("two.gpx"));
fs::write(&one, gpx("one")).unwrap();
fs::write(&two, gpx("two")).unwrap();
let folder = fx.folder.clone();
// no folder: only the folder of the files
fx.workspace.open_files(&mut fx.engine, &[one, two], false);
assert_eq!(fx.workspace.watched(), [(elsewhere.clone(), false)]);
// the open folder as a whole, and the file in it needs nothing more
fx.workspace.open_folder(&mut fx.engine, &folder, false);
fx.workspace.open_files(&mut fx.engine, &[inside], false);
assert_eq!(
fx.workspace.watched(),
[(folder, true), (elsewhere.clone(), false)]
);
// closing the files stops it
let ids = fx.ids();
fx.workspace.close_files(&mut fx.engine, &ids, true);
assert_eq!(fx.workspace.watched(), [(fx.folder.clone(), true)]);
fs::remove_dir_all(elsewhere).unwrap();
}
#[test]
fn opening_a_folder_does_not_open_its_files() {
let mut fx = Fixture::new();
fx.write("a.gpx", "a");
let folder = fx.folder.clone();
let outcome = fx.workspace.open_folder(&mut fx.engine, &folder, false);
assert!(!outcome.changed);
assert!(fx.ids().is_empty());
assert_eq!(fx.workspace.folder.as_deref(), Some(folder.as_path()));
}
#[test]
fn folders_are_made_renamed_and_moved_and_the_open_files_follow() {
let mut fx = Fixture::new();
let a = fx.write("a.gpx", "a");
fx.open_folder();
let id = fx.ids()[0];
let root = fx.folder.clone();
let path_of = |fx: &Fixture| PathBuf::from(fx.status(id).path.unwrap());
let first = fx.workspace.create_folder(&root, "New folder").unwrap();
let second = fx.workspace.create_folder(&root, "New folder").unwrap();
assert_eq!(first, root.join("New folder"));
assert_eq!(second, root.join("New folder 2"));
fx.workspace.move_paths(&[a], &first).unwrap();
assert_eq!(path_of(&fx), first.join("a.gpx"));
assert!(first.join("a.gpx").exists() && !fx.status(id).dirty);
let trips = fx.workspace.rename_path(&first, "Trips").unwrap();
assert_eq!(path_of(&fx), root.join("Trips/a.gpx"));
// a folder does not go into itself, nor onto something else
assert!(
fx.workspace
.move_paths(std::slice::from_ref(&trips), &trips)
.is_err()
);
assert_eq!(
fx.workspace.rename_path(&trips, "New folder 2"),
Err(NAME_TAKEN.to_owned())
);
fx.workspace.move_paths(&[trips], &second).unwrap();
assert_eq!(path_of(&fx), second.join("Trips/a.gpx"));
// a file keeps its extension
let closed = fx.write("c.gpx", "c");
assert_eq!(
fx.workspace.rename_path(&closed, "d").unwrap(),
root.join("d.gpx")
);
// the open folder and what is not in it are left alone
assert!(fx.workspace.rename_path(&root, "x").is_err());
let elsewhere = canonical(&std::env::temp_dir());
assert!(fx.workspace.rename_path(&elsewhere, "x").is_err());
assert!(fx.workspace.create_folder(&elsewhere, "x").is_err());
}
#[test]
fn deleted_files_are_closed_unless_they_have_edits() {
let mut fx = Fixture::new();
let a = fx.write("a.gpx", "a");
let b = fx.write("b.gpx", "b");
fx.open_folder();
let (id_a, id_b) = (fx.id_named("a"), fx.id_named("b"));
api::select(&mut fx.engine, &[id_b], SelectMode::Replace);
assert!(!api::style(&mut fx.engine, Some("#ff0000"), None, None).has_error());
let outcome = fx
.workspace
.delete_paths(&mut fx.engine, &[a.clone(), b.clone()], |paths| {
paths.iter().for_each(|path| fs::remove_file(path).unwrap());
Ok(())
})
.unwrap();
assert!(outcome.changed);
assert_eq!(fx.ids(), [id_b]);
assert!(!fx.ids().contains(&id_a));
let status = fx.status(id_b);
assert!(status.dirty && status.missing);
assert!(!a.exists() && !b.exists());
}
#[test]
fn the_tree_of_the_folder_shows_folders_first_and_only_gpx_files() {
let mut fx = Fixture::new();
fx.write("b.gpx", "b");
fx.write("A.GPX", "a");
fx.write("b 10.gpx", "b 10");
fx.write("b 2.gpx", "b 2");
fx.write("notes.txt", "not a track");
fx.write(".hidden.gpx", "hidden");
fs::create_dir(fx.folder.join("zoo")).unwrap();
fs::create_dir(fx.folder.join("Alps")).unwrap();
fs::create_dir(fx.folder.join(".git")).unwrap();
fx.write("zoo/c.gpx", "c");
let folder = fx.folder.clone();
fx.workspace.open_folder(&mut fx.engine, &folder, false);
let names = |entries: Vec<Entry>| -> Vec<(String, bool)> {
entries.into_iter().map(|e| (e.name, e.is_dir)).collect()
};
assert_eq!(
names(fx.workspace.list_folder(&folder).unwrap()),
[
("Alps".to_string(), true),
("zoo".to_string(), true),
("A.GPX".to_string(), false),
("b.gpx".to_string(), false),
("b 2.gpx".to_string(), false),
("b 10.gpx".to_string(), false),
]
);
assert_eq!(
names(fx.workspace.list_folder(&folder.join("zoo")).unwrap()),
[("c.gpx".to_string(), false)]
);
// only what is in the open folder can be listed
let elsewhere = canonical(&std::env::temp_dir());
assert!(fx.workspace.list_folder(&elsewhere).is_err());
}
#[test]
fn names_are_sorted_by_the_numbers_they_hold() {
let mut names = vec![
"track 10",
"track 2",
"Track 1",
"track",
"track 02b",
"track 2a",
"b",
"A",
];
names.sort_by(|a, b| natural_cmp(a, b).then_with(|| a.cmp(b)));
assert_eq!(
names,
[
"A",
"b",
"track",
"Track 1",
"track 2",
"track 2a",
"track 02b",
"track 10",
]
);
}
#[test]
fn a_file_without_edits_is_read_again_when_the_disk_changes() {
let mut fx = Fixture::new();
let a = fx.write("a.gpx", "a");
fx.open_folder();
let id = fx.ids()[0];
fx.write("a.gpx", "theirs");
let outcome = fx.reconcile(Some(std::slice::from_ref(&a))).unwrap();
assert!(outcome.changed);
// the same file, now the one on the disk
assert_eq!(fx.ids(), [id]);
assert_eq!(fx.content(id), "theirs");
let status = fx.status(id);
assert!(!status.dirty && !status.replaced);
// looking again changes nothing
assert!(fx.reconcile(Some(std::slice::from_ref(&a))).is_none());
}
#[test]
fn a_file_with_edits_is_flagged_when_the_disk_changes_and_not_read_again() {
let mut fx = Fixture::new();
let a = fx.write("a.gpx", "a");
fx.open_folder();
let id = fx.ids()[0];
fx.rename(id, "mine");
fx.write("a.gpx", "theirs");
let outcome = fx.reconcile(Some(std::slice::from_ref(&a))).unwrap();
assert!(!outcome.changed);
assert_eq!(fx.name(id), "mine");
let status = fx.status(id);
assert!(status.dirty && status.replaced && !status.missing);
// looking again changes nothing
assert!(fx.reconcile(Some(std::slice::from_ref(&a))).is_none());
// the disk goes back to what was read: only the edits are left
fx.write("a.gpx", "a");
assert!(fx.reconcile(Some(std::slice::from_ref(&a))).is_some());
let status = fx.status(id);
assert!(status.dirty && !status.replaced);
}
#[test]
fn the_user_can_take_the_disk_instead_of_the_edits() {
let mut fx = Fixture::new();
fx.write("a.gpx", "a");
fx.open_folder();
let id = fx.ids()[0];
fx.rename(id, "mine");
fx.write("a.gpx", "theirs");
fx.reconcile(None);
assert!(fx.status(id).replaced);
fx.workspace.reload(&mut fx.engine, &[id]).unwrap();
assert_eq!(fx.content(id), "theirs");
let status = fx.status(id);
assert!(!status.dirty && !status.replaced);
// and it is one undo step
api::select(&mut fx.engine, &[id], SelectMode::Replace);
api::undo(&mut fx.engine);
assert_eq!(fx.content(id), "mine");
}
#[test]
fn saving_overwrites_what_replaced_the_file() {
let mut fx = Fixture::new();
let a = fx.write("a.gpx", "a");
fx.open_folder();
let id = fx.ids()[0];
fx.rename(id, "mine");
fx.write("a.gpx", "theirs");
fx.reconcile(None);
assert!(fx.status(id).replaced);
fx.save(&[id]);
assert!(fs::read_to_string(a).unwrap().contains(">mine<"));
assert!(!fx.status(id).replaced && !fx.status(id).dirty);
}
#[test]
fn a_file_that_is_gone_from_the_disk_stays_open_and_dirty_until_it_is_saved_again() {
let mut fx = Fixture::new();
let a = fx.write("a.gpx", "a");
fx.open_folder();
let id = fx.ids()[0];
fs::remove_file(&a).unwrap();
assert!(fx.reconcile(Some(std::slice::from_ref(&a))).is_some());
assert_eq!(fx.ids(), [id]);
let status = fx.status(id);
assert!(status.dirty && status.missing && status.path.is_some());
// saving puts it back
fx.save(&[id]);
assert!(a.exists());
let status = fx.status(id);
assert!(!status.dirty && !status.missing);
}
#[test]
fn a_file_that_comes_back_different_is_read_again() {
let mut fx = Fixture::new();
let a = fx.write("a.gpx", "a");
fx.open_folder();
let id = fx.ids()[0];
fs::remove_file(&a).unwrap();
fx.reconcile(None);
assert!(fx.status(id).missing);
fx.write("a.gpx", "back");
fx.reconcile(None);
assert_eq!(fx.content(id), "back");
let status = fx.status(id);
assert!(!status.dirty && !status.missing);
}
#[test]
fn what_changed_while_the_app_was_closed_is_found_when_it_starts() {
let mut fx = Fixture::new();
let a = fx.write("a.gpx", "a");
fx.open_folder();
let id = fx.ids()[0];
fx.write("a.gpx", "changed");
assert!(fx.reconcile(None).is_some());
assert_eq!(fx.content(id), "changed");
fs::remove_file(a).unwrap();
assert!(fx.reconcile(None).is_some());
assert!(fx.status(id).missing);
}
#[test]
fn new_files_made_from_a_file_of_the_folder_are_saved_next_to_it() {
let mut fx = Fixture::new();
fs::create_dir(fx.folder.join("sub")).unwrap();
fx.write("sub/b.gpx", "b");
fx.write("a.gpx", "a");
fx.open_folder();
let b = fx.id_named("b");
let sub = fx.folder.join("sub");
assert_eq!(fx.workspace.source_dir(&[b]), Some(canonical(&sub)));
let before = fx.ids();
api::select(&mut fx.engine, &[b], SelectMode::Replace);
let outcome = api::duplicate(&mut fx.engine);
let copy = fx
.ids()
.into_iter()
.find(|id| !before.contains(id))
.unwrap();
fx.workspace.inherit(outcome.added(), &canonical(&sub));
assert_eq!(fx.status(copy).folder.as_deref(), canonical(&sub).to_str());
assert!(fx.status(copy).path.is_none() && fx.status(copy).dirty);
// nobody needs to be asked where it goes
assert!(fx.workspace.unlinked(&fx.engine, &[copy]).is_empty());
fx.save(&[copy]);
assert!(sub.join("b (2).gpx").exists());
let status = fx.status(copy);
assert!(!status.dirty && status.folder.is_none());
assert_eq!(
status.path.as_deref(),
canonical(&sub.join("b (2).gpx")).to_str()
);
// the copy of the copy is next to it as well
assert_eq!(fx.workspace.source_dir(&[copy]), Some(canonical(&sub)));
}
#[test]
fn a_file_outside_the_open_folder_hands_nothing_down() {
let mut fx = Fixture::new();
let elsewhere = canonical(&std::env::temp_dir()).join(format!("gpx-ws-{}", Uuid::new_v4()));
fs::create_dir_all(&elsewhere).unwrap();
let outside = elsewhere.join("o.gpx");
fs::write(&outside, gpx("o")).unwrap();
let folder = fx.folder.clone();
fx.workspace.open_folder(&mut fx.engine, &folder, false);
fx.workspace
.open_files(&mut fx.engine, std::slice::from_ref(&outside), true);
let id = fx.ids()[0];
assert_eq!(fx.workspace.source_dir(&[id]), None);
// a new file with no source is not linked to a folder by `source_dir`: the caller falls back
fs::remove_dir_all(elsewhere).unwrap();
}
#[test]
fn closing_files_asks_what_to_do_with_the_unsaved_ones() {
let mut fx = Fixture::new();
fx.write("a.gpx", "a");
fx.write("b.gpx", "b");
fx.open_folder();
let (a, b) = (fx.id_named("a"), fx.id_named("b"));
fx.rename(a, "edited");
assert_eq!(fx.workspace.unsaved(&fx.engine, &[a, b]), [a]);
// without a choice what has edits stays
let outcome = fx.workspace.close_files(&mut fx.engine, &[a, b], false);
assert!(outcome.changed);
assert_eq!(fx.ids(), [a]);
// saved first
fx.save(&[a]);
fx.workspace.close_files(&mut fx.engine, &[a], false);
assert!(fx.ids().is_empty());
assert!(
fs::read_to_string(fx.folder.join("a.gpx"))
.unwrap()
.contains("edited")
);
assert!(fx.workspace.links.is_empty());
}
#[test]
fn closing_files_can_discard_their_edits() {
let mut fx = Fixture::new();
fx.write("a.gpx", "a");
fx.open_folder();
let a = fx.ids()[0];
fx.rename(a, "edited");
api::new_file(&mut fx.engine, "fresh", None, None, None, false);
let fresh = fx.id_named("fresh");
fx.workspace.close_files(&mut fx.engine, &[a, fresh], true);
assert!(fx.ids().is_empty());
assert!(
fs::read_to_string(fx.folder.join("a.gpx"))
.unwrap()
.contains(">a<")
);
}
#[test]
fn closing_the_folder_closes_every_file() {
let mut fx = Fixture::new();
fx.write("a.gpx", "a");
fx.open_folder();
api::new_file(&mut fx.engine, "fresh", None, None, None, false);
assert_eq!(fx.ids().len(), 2);
// the new file has nowhere to go: it has to be discarded
let outcome = fx.workspace.close_folder(&mut fx.engine, false);
assert!(outcome.changed);
assert_eq!(fx.ids().len(), 1);
assert!(fx.workspace.folder.is_none());
let outcome = fx.workspace.close_folder(&mut fx.engine, true);
assert!(outcome.changed);
assert!(fx.ids().is_empty());
}
#[test]
fn opening_another_folder_closes_the_first_with_all_its_files() {
let mut fx = Fixture::new();
fx.write("a.gpx", "a");
fx.open_folder();
let a = fx.ids()[0];
fx.rename(a, "edited");
let other = canonical(&std::env::temp_dir()).join(format!("gpx-ws-{}", Uuid::new_v4()));
fs::create_dir_all(&other).unwrap();
// the edits stay, nothing is lost without a choice
fx.workspace.open_folder(&mut fx.engine, &other, false);
assert_eq!(fx.ids(), [a]);
assert_eq!(fx.workspace.folder.as_deref(), Some(other.as_path()));
let first = fx.folder.clone();
fx.workspace.open_folder(&mut fx.engine, &first, true);
assert!(fx.ids().is_empty());
assert!(
fs::read_to_string(fx.folder.join("a.gpx"))
.unwrap()
.contains(">a<")
);
fs::remove_dir_all(other).unwrap();
}
#[test]
fn opening_the_same_folder_again_changes_nothing() {
let mut fx = Fixture::new();
fx.write("a.gpx", "a");
fx.open_folder();
let folder = fx.folder.clone();
let outcome = fx.workspace.open_folder(&mut fx.engine, &folder, true);
assert!(!outcome.changed);
assert_eq!(fx.ids().len(), 1);
}
#[test]
fn a_failed_save_stops_at_the_file_and_leaves_it_dirty() {
let mut fx = Fixture::new();
fx.write("a.gpx", "a");
fx.open_folder();
let id = fx.ids()[0];
fx.rename(id, "edited");
// the place of the file is taken by a folder
fs::remove_file(fx.folder.join("a.gpx")).unwrap();
fs::create_dir(fx.folder.join("a.gpx")).unwrap();
let result = fx
.workspace
.save(&mut fx.engine, &[id], &BTreeMap::new(), None);
assert!(result.is_err());
assert!(fx.workspace.is_dirty(&fx.engine, id));
}
#[test]
fn saving_as_gives_the_file_another_place() {
let mut fx = Fixture::new();
let a = fx.write("a.gpx", "a");
fx.write("b.gpx", "b");
fx.open_folder();
let id = fx.id_named("a");
let other = fx.id_named("b");
fx.rename(id, "edited");
let target = fx.folder.join("copy.gpx");
fx.workspace.save_as(&mut fx.engine, id, &target).unwrap();
assert!(fs::read_to_string(&target).unwrap().contains("edited"));
assert!(fs::read_to_string(a).unwrap().contains(">a<"));
let status = fx.status(id);
assert!(!status.dirty);
assert_eq!(status.path.as_deref(), canonical(&target).to_str());
// the place of another open file is not available
let taken = fx.folder.join("b.gpx");
assert!(fx.workspace.save_as(&mut fx.engine, id, &taken).is_err());
assert!(!fx.workspace.is_dirty(&fx.engine, other));
}
mod restart {
use gpx_engine::Persister;
use super::*;
use gpx_studio_desktop_lib::store::FileStorage;
/// What the app does when it starts again: the engine and the links are read from what was
/// kept.
fn restart(engine: &Engine, workspace: &Workspace, root: &Path) -> (Engine, Workspace) {
let storage = FileStorage::open(root).unwrap();
pollster::block_on(Persister::default().save(&storage, engine.snapshot())).unwrap();
let mut restarted = Engine::default();
let restored = pollster::block_on(Persister::default().restore(&storage)).unwrap();
restarted.restore(restored);
let links = serde_json::to_string(workspace).unwrap();
(restarted, serde_json::from_str(&links).unwrap())
}
fn setup() -> (PathBuf, Engine, Workspace, Vec<Uuid>) {
let root = std::env::temp_dir().join(format!("gpx-restart-{}", Uuid::new_v4()));
let folder = root.join("tracks");
fs::create_dir_all(&folder).unwrap();
for name in ["with_tracks", "with_time", "with_waypoint"] {
let _ = fs::copy(
format!("../gpx-rs/data/{name}.gpx"),
folder.join(format!("{name}.gpx")),
);
}
let mut engine = Engine::default();
let mut workspace = Workspace::default();
workspace.open_folder(&mut engine, &folder, false);
workspace.open_files(&mut engine, &gpx_files(&folder), false);
let ids = engine.order().iter().map(|id| id.0).collect();
(root, engine, workspace, ids)
}
#[test]
fn files_that_were_not_edited_are_not_unsaved_after_a_restart() {
let (root, engine, workspace, ids) = setup();
assert!(ids.len() >= 2);
let (restarted, mut workspace) = restart(&engine, &workspace, &root.join("store"));
// the files are the same, but the engine knows their contents by new identities
assert!(ids.iter().any(|id| workspace.is_dirty(&restarted, *id)));
workspace.verify(&restarted);
assert!(ids.iter().all(|id| !workspace.is_dirty(&restarted, *id)));
fs::remove_dir_all(root).unwrap();
}
#[test]
fn files_that_were_edited_are_still_unsaved_after_a_restart() {
let (root, mut engine, workspace, ids) = setup();
api::select(&mut engine, &[ids[0]], gpx_engine::SelectMode::Replace);
api::metadata(&mut engine, "edited", "");
assert!(workspace.is_dirty(&engine, ids[0]));
let (restarted, mut workspace) = restart(&engine, &workspace, &root.join("store"));
workspace.verify(&restarted);
assert!(workspace.is_dirty(&restarted, ids[0]));
assert!(
ids[1..]
.iter()
.all(|id| !workspace.is_dirty(&restarted, *id))
);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn links_made_before_the_content_was_kept_are_checked_against_the_disk() {
let (root, mut engine, mut workspace, ids) = setup();
api::select(&mut engine, &[ids[0]], gpx_engine::SelectMode::Replace);
api::metadata(&mut engine, "edited", "");
for link in workspace.links.values_mut() {
link.export_hash = 0;
}
let (restarted, mut workspace) = restart(&engine, &workspace, &root.join("store"));
workspace.verify(&restarted);
assert!(workspace.is_dirty(&restarted, ids[0]));
assert!(
ids[1..]
.iter()
.all(|id| !workspace.is_dirty(&restarted, *id))
);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn the_folders_of_new_files_and_the_old_flag_name_survive_a_restart() {
let (root, engine, mut workspace, ids) = setup();
let folder = workspace.folder.clone().unwrap();
let fresh = Uuid::new_v4();
workspace.inherit(&[fresh.to_string()], &folder);
workspace.links.get_mut(&ids[0]).unwrap().replaced = true;
let json = serde_json::to_string(&workspace).unwrap();
// links written by the previous version had `conflict`, which is the same thing
let json = json.replace("\"replaced\"", "\"conflict\"");
assert!(json.contains("\"conflict\":true"));
let read: Workspace = serde_json::from_str(&json).unwrap();
assert!(read.links[&ids[0]].replaced);
assert_eq!(read.dirs.get(&fresh), Some(&folder));
let _ = engine;
fs::remove_dir_all(root).unwrap();
}
}
-14
View File
@@ -1,14 +0,0 @@
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<dependency>
<dependentAssembly>
<assemblyIdentity
type="win32"
name="Microsoft.Windows.Common-Controls"
version="6.0.0.0"
processorArchitecture="*"
publicKeyToken="6595b64144ccf1df"
language="*"
/>
</dependentAssembly>
</dependency>
</assembly>
+6 -18
View File
@@ -26,9 +26,6 @@ thread_local! {
static PERSISTER: RefCell<Option<Persister>> = const { RefCell::new(None) };
static SAVING: Cell<bool> = const { Cell::new(false) };
static DIRTY: Cell<bool> = const { Cell::new(false) };
/// Whether the last write failed, or was not done because a newer version wrote the storage:
/// what the engine holds is then not all stored.
static NOT_WRITTEN: Cell<bool> = const { Cell::new(false) };
/// Resolve functions of the promises of `flush_storage`.
/// Called after the files were written, and when a write was refused because they were
/// written by someone else since: see `open_storage`.
@@ -76,28 +73,20 @@ pub(crate) fn schedule_save() {
let result = persister.save(&*storage, snapshot).await;
PERSISTER.with(|slot| *slot.borrow_mut() = Some(persister));
match result {
Ok(()) => {
NOT_WRITTEN.set(false);
saved = true;
}
Ok(()) => saved = true,
// nothing was written, so that the files of the other tab are not damaged: this
// tab has to read them, which replaces what it did
Err(engine::CommitError::Stale { .. }) => {
NOT_WRITTEN.set(false);
DIRTY.set(false);
behind = true;
}
// nothing is written, so that the newer version finds its data again
Err(engine::CommitError::Failed(engine::StorageError::Newer)) => {
NOT_WRITTEN.set(true);
DIRTY.set(false);
newer = true;
}
// what failed is written with the next change
Err(error) => {
NOT_WRITTEN.set(true);
console_error(&error.to_string());
}
Err(error) => console_error(&error.to_string()),
}
}
SAVING.set(false);
@@ -199,18 +188,17 @@ pub(crate) fn to_js_error(error: engine::StorageError) -> JsValue {
JsValue::from_str(&error.to_string())
}
/// Resolves when the writes of what was changed are done, to whether they went well. A write that
/// was refused because another tab wrote since is fine: this tab then reads what that tab wrote.
/// Resolves when what was changed has been written to the storage.
#[wasm_bindgen]
pub async fn flush_storage() -> Result<bool, JsValue> {
pub async fn flush_storage() -> Result<(), JsValue> {
if !SAVING.get() {
return Ok(!NOT_WRITTEN.get());
return Ok(());
}
let promise = js_sys::Promise::new(&mut |resolve, _| {
WAITERS.with(|waiters| waiters.borrow_mut().push(resolve));
});
wasm_bindgen_futures::JsFuture::from(promise).await?;
Ok(!NOT_WRITTEN.get())
Ok(())
}
/// If another tab wrote the files since this one last did, reads them again and overwrites the
+12
View File
@@ -101,6 +101,18 @@ pub fn waypoint(file_id: &str, waypoint_id: &str) -> WaypointDetails {
optional_js(details).unchecked_into()
}
/// A trackpoint of a segment of a file, `undefined` if it does not exist.
#[wasm_bindgen]
pub fn trackpoint(file_id: &str, segment_id: &str, index: usize) -> TrackpointDetails {
let details =
parse_uuid(file_id)
.zip(parse_uuid(segment_id))
.and_then(|(file_id, segment_id)| {
with_engine(|e| api::trackpoint(e, file_id, segment_id, index)).flatten()
});
optional_js(details).unchecked_into()
}
/// What was copied or cut and is waiting to be pasted, `undefined` if nothing: the kind of the
/// elements and their ids (UUID strings).
#[wasm_bindgen]
+10
View File
@@ -59,6 +59,14 @@ export interface WaypointDetails {
links?: { href: string; text?: string }[];
sym?: string;
}
/** The position, elevation and time of a trackpoint. */
export interface TrackpointDetails {
lng: number;
lat: number;
ele: number;
/** ms since epoch */
time?: number;
}
/**
* A trackpoint of the selection: what the statistics buffers do not hold for each trackpoint.
* Absent fields are unknown.
@@ -181,6 +189,8 @@ extern "C" {
pub type Selection;
#[wasm_bindgen(typescript_type = "WaypointDetails | undefined")]
pub type WaypointDetails;
#[wasm_bindgen(typescript_type = "TrackpointDetails | undefined")]
pub type TrackpointDetails;
#[wasm_bindgen(typescript_type = "SelectionPoint | undefined")]
pub type SelectionPoint;
#[wasm_bindgen(typescript_type = "MoveTarget")]
+13
View File
@@ -0,0 +1,13 @@
.DS_Store
node_modules
/build
/.svelte-kit
/package
.env
.env.*
!.env.example
# Ignore files for PNPM, NPM and YARN
pnpm-lock.yaml
package-lock.json
yarn.lock
+31
View File
@@ -0,0 +1,31 @@
/** @type { import("eslint").Linter.Config } */
module.exports = {
root: true,
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:svelte/recommended',
'prettier',
],
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint'],
parserOptions: {
sourceType: 'module',
ecmaVersion: 2020,
extraFileExtensions: ['.svelte'],
},
env: {
browser: true,
es2017: true,
node: true,
},
overrides: [
{
files: ['*.svelte'],
parser: 'svelte-eslint-parser',
parserOptions: {
parser: '@typescript-eslint/parser',
},
},
],
};
+18 -18
View File
@@ -1,20 +1,20 @@
{
"$schema": "https://shadcn-svelte.com/schema.json",
"tailwind": {
"css": "src/app.css",
"baseColor": "neutral"
},
"aliases": {
"components": "$lib/components",
"utils": "$lib/utils",
"ui": "$lib/components/ui",
"hooks": "$lib/hooks",
"lib": "$lib"
},
"typescript": true,
"registry": "https://shadcn-svelte.com/registry",
"style": "nova",
"iconLibrary": "lucide",
"menuColor": "default",
"menuAccent": "subtle"
"$schema": "https://shadcn-svelte.com/schema.json",
"tailwind": {
"css": "src/app.css",
"baseColor": "neutral"
},
"aliases": {
"components": "$lib/components",
"utils": "$lib/utils",
"ui": "$lib/components/ui",
"hooks": "$lib/hooks",
"lib": "$lib"
},
"typescript": true,
"registry": "https://shadcn-svelte.com/registry",
"style": "nova",
"iconLibrary": "lucide",
"menuColor": "default",
"menuAccent": "subtle"
}
-47
View File
@@ -1,47 +0,0 @@
import js from '@eslint/js';
import ts from '@typescript-eslint/eslint-plugin';
import tsParser from '@typescript-eslint/parser';
import svelte from 'eslint-plugin-svelte';
import prettier from 'eslint-config-prettier';
import globals from 'globals';
/** @type {import('eslint').Linter.Config[]} */
export default [
{
ignores: ['build/', '.svelte-kit/', 'package/'],
},
js.configs.recommended,
...ts.configs['flat/recommended'],
...svelte.configs['flat/recommended'],
prettier,
...svelte.configs['flat/prettier'],
{
languageOptions: {
globals: { ...globals.browser, ...globals.node },
},
},
{
rules: {
// TypeScript already reports undefined names
'no-undef': 'off',
'no-empty': ['error', { allowEmptyCatch: true }],
'@typescript-eslint/no-unused-vars': [
'error',
{ argsIgnorePattern: '^_', varsIgnorePattern: '^_' },
],
},
},
{
files: ['**/*.svelte', '**/*.svelte.ts', '**/*.svelte.js'],
languageOptions: {
parserOptions: {
parser: tsParser,
extraFileExtensions: ['.svelte'],
},
},
rules: {
// $effect dependencies are tracked by reading them
'@typescript-eslint/no-unused-expressions': 'off',
},
},
];
+55 -93
View File
@@ -18,23 +18,20 @@
"gpx-wasm": "file:../wasm/pkg",
"jszip": "^3.10.1",
"mapillary-js": "^4.1.2",
"maplibre-gl": "^6.18.0",
"maplibre-gl": "^6.15.0",
"sanitize-html": "^2.17.0",
"sortablejs": "^1.15.7"
"sortablejs": "^1.15.6"
},
"devDependencies": {
"@fontsource-variable/inter": "^5.2.8",
"@internationalized/date": "^3.12.0",
"@lucide/svelte": "^1.7.0",
"@mapbox/vector-tile": "^3.0.0",
"@sveltejs/adapter-static": "^3.0.8",
"@sveltejs/enhanced-img": "^0.6.0",
"@sveltejs/kit": "^2.21.2",
"@sveltejs/vite-plugin-svelte": "^6.2.4",
"@tailwindcss/vite": "^4.1.8",
"@tauri-apps/api": "^2.12.3",
"@tauri-apps/plugin-process": "^2.4.0",
"@tauri-apps/plugin-updater": "^2.14.1",
"@types/eslint": "^9.6.1",
"@types/events": "^3.0.3",
"@types/file-saver": "^2.0.7",
@@ -42,12 +39,11 @@
"@types/mapbox__tilebelt": "^1.0.4",
"@types/node": "^22.15.30",
"@types/sanitize-html": "^2.16.0",
"@types/sortablejs": "^1.15.9",
"@types/sortablejs": "^1.15.8",
"@typescript-eslint/eslint-plugin": "^8.33.1",
"@typescript-eslint/parser": "^8.33.1",
"bits-ui": "^2.17.2",
"clsx": "^2.1.1",
"cross-env": "^10.1.0",
"eslint": "^9.28.0",
"eslint-config-prettier": "^10.1.5",
"eslint-plugin-svelte": "^3.9.1",
@@ -57,7 +53,6 @@
"mdsvex": "^0.12.6",
"mode-watcher": "^1.1.0",
"paneforge": "^1.0.0-next.5",
"pbf": "^5.2.1",
"postcss": "^8.4.47",
"prettier": "^3.5.3",
"prettier-plugin-svelte": "^3.4.0",
@@ -359,13 +354,6 @@
"tslib": "^2.4.0"
}
},
"node_modules/@epic-web/invariant": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@epic-web/invariant/-/invariant-1.0.0.tgz",
"integrity": "sha512-lrTPqgvfFQtR/eY/qkIzp98OGdNJu0m5ji3q/nJI8v3SXkRKEnWiOxMmbvcSoAIzv/cGiuvRy57k4suKQSAdwA==",
"dev": true,
"license": "MIT"
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.27.7",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.7.tgz",
@@ -1751,6 +1739,18 @@
"pbf": "^5.0.0"
}
},
"node_modules/@mapbox/vector-tile/node_modules/pbf": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/pbf/-/pbf-5.1.2.tgz",
"integrity": "sha512-mnvGdvOrIvJOBGUEdGkrVXjN8E/VkIJCkf2eS1DH2yv82ORUlLttmDt0rWY38yYZmVwciZwBUvHM20qxBZf40w==",
"license": "BSD-3-Clause",
"dependencies": {
"resolve-protobuf-schema": "^2.1.0"
},
"bin": {
"pbf": "bin/pbf"
}
},
"node_modules/@maplibre/geojson-vt": {
"version": "6.3.0",
"resolved": "https://registry.npmjs.org/@maplibre/geojson-vt/-/geojson-vt-6.3.0.tgz",
@@ -1778,9 +1778,9 @@
}
},
"node_modules/@maplibre/maplibre-gl-style-spec": {
"version": "26.7.0",
"resolved": "https://registry.npmjs.org/@maplibre/maplibre-gl-style-spec/-/maplibre-gl-style-spec-26.7.0.tgz",
"integrity": "sha512-9d7hK1zk1WRx/AFvq7NtmlTlaOGPXS2r+FZXsrMv8453Xy14bnXBpVCPJDBupCfQs/p8FL0/kb0ygbEWTufN0g==",
"version": "26.4.4",
"resolved": "https://registry.npmjs.org/@maplibre/maplibre-gl-style-spec/-/maplibre-gl-style-spec-26.4.4.tgz",
"integrity": "sha512-hG4RZR4PBd/+6A3ODdZ3AnQRF106ZQk1y3bhwDg8bH/A4Oz2tnRUJVVWs9BZa6gXZ1d3UKe89C+Mm+olGBELvA==",
"license": "ISC",
"dependencies": {
"@mapbox/jsonlint-lines-primitives": "^2.0.3",
@@ -1806,14 +1806,26 @@
}
},
"node_modules/@maplibre/vt-pbf": {
"version": "4.3.3",
"resolved": "https://registry.npmjs.org/@maplibre/vt-pbf/-/vt-pbf-4.3.3.tgz",
"integrity": "sha512-dEe5XUd64RQbxNxy2OzIkJnwNDWjVmSXjCd0A7zLirm7QJ/WWbmtDFIkfsiM4yt1cplqzG6oSivRYeWx1SM1yg==",
"version": "4.3.2",
"resolved": "https://registry.npmjs.org/@maplibre/vt-pbf/-/vt-pbf-4.3.2.tgz",
"integrity": "sha512-j6p0AdjvAR19Z3XaCysle7A4ZSo08tYOzxD0Y9NQylwPAkwJJeYub5b2eVucdeDh7erhv69DahoLOevDRERRUw==",
"license": "MIT",
"dependencies": {
"@mapbox/point-geometry": "^1.1.0",
"@types/geojson": "^7946.0.16",
"pbf": "^5.1.2"
"pbf": "^5.1.0"
}
},
"node_modules/@maplibre/vt-pbf/node_modules/pbf": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/pbf/-/pbf-5.1.2.tgz",
"integrity": "sha512-mnvGdvOrIvJOBGUEdGkrVXjN8E/VkIJCkf2eS1DH2yv82ORUlLttmDt0rWY38yYZmVwciZwBUvHM20qxBZf40w==",
"license": "BSD-3-Clause",
"dependencies": {
"resolve-protobuf-schema": "^2.1.0"
},
"bin": {
"pbf": "bin/pbf"
}
},
"node_modules/@polka/url": {
@@ -2647,26 +2659,6 @@
"url": "https://opencollective.com/tauri"
}
},
"node_modules/@tauri-apps/plugin-process": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/@tauri-apps/plugin-process/-/plugin-process-2.4.0.tgz",
"integrity": "sha512-GddrmsSLAYrLa/yTXlXK/YRDzUgYeeOnUXTbiyvJWkmI424RmDPD3FVLeqcon7rv6O6ZfhBilcrHWnSo7o6hIQ==",
"dev": true,
"license": "MIT OR Apache-2.0",
"dependencies": {
"@tauri-apps/api": "^2.12.0"
}
},
"node_modules/@tauri-apps/plugin-updater": {
"version": "2.14.1",
"resolved": "https://registry.npmjs.org/@tauri-apps/plugin-updater/-/plugin-updater-2.14.1.tgz",
"integrity": "sha512-Hr7nlBm1wT6xbwzjZ/S36YULazu8MNlj5vvOwMl47fXI7HTa5Bjl1PbDEwVHaZTAKzE1VZsUy35UqnbrQxmYQw==",
"dev": true,
"license": "MIT OR Apache-2.0",
"dependencies": {
"@tauri-apps/api": "^2.12.0"
}
},
"node_modules/@types/cookie": {
"version": "0.6.0",
"dev": true,
@@ -2770,8 +2762,6 @@
},
"node_modules/@types/sortablejs": {
"version": "1.15.9",
"resolved": "https://registry.npmjs.org/@types/sortablejs/-/sortablejs-1.15.9.tgz",
"integrity": "sha512-7HP+rZGE2p886PKV9c9OJzLBI6BBJu1O7lJGYnPyG3fS4/duUCcngkNCjsLwIMV+WMqANe3tt4irrXHSIe68OQ==",
"dev": true,
"license": "MIT"
},
@@ -3283,24 +3273,6 @@
"version": "1.0.3",
"license": "MIT"
},
"node_modules/cross-env": {
"version": "10.1.0",
"resolved": "https://registry.npmjs.org/cross-env/-/cross-env-10.1.0.tgz",
"integrity": "sha512-GsYosgnACZTADcmEyJctkJIoqAhHjttw7RsFrVoJNXbsWWqaq6Ym+7kZjq6mS45O0jij6vtiReppKQEtqWy6Dw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@epic-web/invariant": "^1.0.0",
"cross-spawn": "^7.0.6"
},
"bin": {
"cross-env": "dist/bin/cross-env.js",
"cross-env-shell": "dist/bin/cross-env-shell.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/cross-spawn": {
"version": "7.0.6",
"dev": true,
@@ -4035,8 +4007,6 @@
},
"node_modules/ieee754": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
"integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
"funding": [
{
"type": "github",
@@ -4653,23 +4623,10 @@
"version": "2.1.0",
"license": "(MIT AND Zlib)"
},
"node_modules/mapillary-js/node_modules/pbf": {
"version": "3.3.0",
"resolved": "https://registry.npmjs.org/pbf/-/pbf-3.3.0.tgz",
"integrity": "sha512-XDF38WCH3z5OV/OVa8GKUNtLAyneuzbCisx7QUCF8Q6Nutx0WnJrQe5O+kOtBlLfRNUws98Y58Lblp+NJG5T4Q==",
"license": "BSD-3-Clause",
"dependencies": {
"ieee754": "^1.1.12",
"resolve-protobuf-schema": "^2.1.0"
},
"bin": {
"pbf": "bin/pbf"
}
},
"node_modules/maplibre-gl": {
"version": "6.18.0",
"resolved": "https://registry.npmjs.org/maplibre-gl/-/maplibre-gl-6.18.0.tgz",
"integrity": "sha512-8ucT+RhJtEZGFvWGPioVQwvOPMAIuUehEgxl2dELw9aJmX4SpUi+OCHHAD33B9EuohNC7kC/gccJacUgTMQfQQ==",
"version": "6.15.0",
"resolved": "https://registry.npmjs.org/maplibre-gl/-/maplibre-gl-6.15.0.tgz",
"integrity": "sha512-kxFetbvUHDOVaAP1CYb226Mdk2QhzIPddqM0xJTFD35wu78Mpd6NM7+H68ALjc6Oa0kAOX5EAdMKyvD2u3qfcg==",
"license": "BSD-3-Clause",
"dependencies": {
"@mapbox/point-geometry": "^1.1.0",
@@ -4677,9 +4634,9 @@
"@mapbox/unitbezier": "^1.0.0",
"@mapbox/vector-tile": "^3.0.0",
"@maplibre/geojson-vt": "^6.3.0",
"@maplibre/maplibre-gl-style-spec": "^26.6.0",
"@maplibre/maplibre-gl-style-spec": "^26.4.4",
"@maplibre/mlt": "^1.3.0",
"@maplibre/vt-pbf": "^4.3.3",
"@maplibre/vt-pbf": "^4.3.2",
"@types/geojson": "^7946.0.16",
"bidi-js": "^1.1.0",
"earcut": "^3.2.4",
@@ -4705,6 +4662,18 @@
"integrity": "sha512-FHc6yNpnTORB0tM5kmZ03iD2mDuNakDE2lvf4Hw1XkfxtEHIGVi01B/GqUSwx+NcC1WGjidAfpTXzeALtPtfpg==",
"license": "ISC"
},
"node_modules/maplibre-gl/node_modules/pbf": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/pbf/-/pbf-5.1.2.tgz",
"integrity": "sha512-mnvGdvOrIvJOBGUEdGkrVXjN8E/VkIJCkf2eS1DH2yv82ORUlLttmDt0rWY38yYZmVwciZwBUvHM20qxBZf40w==",
"license": "BSD-3-Clause",
"dependencies": {
"resolve-protobuf-schema": "^2.1.0"
},
"bin": {
"pbf": "bin/pbf"
}
},
"node_modules/martinez-polygon-clipping": {
"version": "0.7.4",
"license": "MIT",
@@ -5066,12 +5035,11 @@
}
},
"node_modules/pbf": {
"version": "5.2.1",
"resolved": "https://registry.npmjs.org/pbf/-/pbf-5.2.1.tgz",
"integrity": "sha512-5s6y6g3akGMF98eemb+3QZAWTCUHyox40TJOwcY4M1w40RvoXrfbRUVmY02RlRiEPyE6KVaM0xxfF4+4vjSJTQ==",
"version": "3.3.0",
"license": "BSD-3-Clause",
"dependencies": {
"protocol-buffers-schema": "^3.6.1"
"ieee754": "^1.1.12",
"resolve-protobuf-schema": "^2.1.0"
},
"bin": {
"pbf": "bin/pbf"
@@ -5295,9 +5263,7 @@
"license": "MIT"
},
"node_modules/protocol-buffers-schema": {
"version": "3.6.1",
"resolved": "https://registry.npmjs.org/protocol-buffers-schema/-/protocol-buffers-schema-3.6.1.tgz",
"integrity": "sha512-VG2K63Igkiv9p76tk1lilczEK1cT+kCjKtkdhw1dQZV3k3IXJbd3o6Ho8b9zJZaHSnT2hKe4I+ObmX9w6m5SmQ==",
"version": "3.6.0",
"license": "MIT"
},
"node_modules/punycode": {
@@ -5379,8 +5345,6 @@
},
"node_modules/resolve-protobuf-schema": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/resolve-protobuf-schema/-/resolve-protobuf-schema-2.1.0.tgz",
"integrity": "sha512-kI5ffTiZWmJaS/huM8wZfEMer1eRd7oJQhDuxeCLe3t7N7mX3z94CN0xPxBQxFYQTSNz9T0i+v6inKqSdK8xrQ==",
"license": "MIT",
"dependencies": {
"protocol-buffers-schema": "^3.3.1"
@@ -5635,8 +5599,6 @@
},
"node_modules/sortablejs": {
"version": "1.15.7",
"resolved": "https://registry.npmjs.org/sortablejs/-/sortablejs-1.15.7.tgz",
"integrity": "sha512-Kk8wLQPlS+yi1ZEf48a4+fzHa4yxjC30M/Sr2AnQu+f/MPwvvX9XjZ6OWejiz8crBsLwSq8GHqaxaET7u6ux0A==",
"license": "MIT"
},
"node_modules/source-map-js": {
+4 -10
View File
@@ -5,12 +5,11 @@
"scripts": {
"dev": "vite dev",
"build": "vite build",
"build:desktop": "cross-env BUILD_TARGET=desktop BASE_PATH= vite build",
"build:desktop": "BUILD_TARGET=desktop BASE_PATH='' vite build",
"prebuild": "npx tsx src/lib/scripts/pwa-manifest.ts",
"postbuild": "npx tsx src/lib/scripts/sitemap.ts",
"preview": "vite preview",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"pretest": "svelte-kit sync",
"test": "node --import tsx --import ./src/test/register.mjs --experimental-wasm-modules --disable-warning=ExperimentalWarning --test \"src/**/*.test.ts\"",
"generate:example": "node --import tsx src/lib/scripts/example-statistics.ts",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
@@ -21,15 +20,12 @@
"@fontsource-variable/inter": "^5.2.8",
"@internationalized/date": "^3.12.0",
"@lucide/svelte": "^1.7.0",
"@mapbox/vector-tile": "^3.0.0",
"@sveltejs/adapter-static": "^3.0.8",
"@sveltejs/enhanced-img": "^0.6.0",
"@sveltejs/kit": "^2.21.2",
"@sveltejs/vite-plugin-svelte": "^6.2.4",
"@tailwindcss/vite": "^4.1.8",
"@tauri-apps/api": "^2.12.3",
"@tauri-apps/plugin-process": "^2.4.0",
"@tauri-apps/plugin-updater": "^2.14.1",
"@types/eslint": "^9.6.1",
"@types/events": "^3.0.3",
"@types/file-saver": "^2.0.7",
@@ -37,12 +33,11 @@
"@types/mapbox__tilebelt": "^1.0.4",
"@types/node": "^22.15.30",
"@types/sanitize-html": "^2.16.0",
"@types/sortablejs": "^1.15.9",
"@types/sortablejs": "^1.15.8",
"@typescript-eslint/eslint-plugin": "^8.33.1",
"@typescript-eslint/parser": "^8.33.1",
"bits-ui": "^2.17.2",
"clsx": "^2.1.1",
"cross-env": "^10.1.0",
"eslint": "^9.28.0",
"eslint-config-prettier": "^10.1.5",
"eslint-plugin-svelte": "^3.9.1",
@@ -52,7 +47,6 @@
"mdsvex": "^0.12.6",
"mode-watcher": "^1.1.0",
"paneforge": "^1.0.0-next.5",
"pbf": "^5.2.1",
"postcss": "^8.4.47",
"prettier": "^3.5.3",
"prettier-plugin-svelte": "^3.4.0",
@@ -84,8 +78,8 @@
"gpx-wasm": "file:../wasm/pkg",
"jszip": "^3.10.1",
"mapillary-js": "^4.1.2",
"maplibre-gl": "^6.18.0",
"maplibre-gl": "^6.15.0",
"sanitize-html": "^2.17.0",
"sortablejs": "^1.15.7"
"sortablejs": "^1.15.6"
}
}
+4 -4
View File
@@ -1,7 +1,7 @@
@import 'tailwindcss';
@import 'tw-animate-css';
@import 'shadcn-svelte/tailwind.css';
@import '@fontsource-variable/inter';
@import "shadcn-svelte/tailwind.css";
@import "@fontsource-variable/inter";
@custom-variant dark (&:is(.dark *));
@@ -158,7 +158,7 @@
body {
@apply bg-background text-foreground;
}
html {
@apply font-sans;
html {
@apply font-sans;
}
}
-5
View File
@@ -8,11 +8,6 @@ declare global {
// interface PageState {}
// interface Platform {}
}
interface Window {
/** The map, for extensions (set once it has loaded). */
_map?: import('maplibre-gl').Map;
}
}
export {};
+5 -5
View File
@@ -1,4 +1,4 @@
import { asset, resolve as resolvePath } from '$app/paths';
import { base } from '$app/paths';
import { languages } from '$lib/i18n/languages';
import { getURLForLanguage } from '$lib/utils';
@@ -37,16 +37,16 @@ export async function handle({ event, resolve }) {
<meta property="og:description" content="${description}" />
<meta name="twitter:title" content="gpx.studio — ${title}" />
<meta name="twitter:description" content="${description}" />
<meta property="og:image" content="https://gpx.studio${asset('/og_logo.png')}" />
<meta property="og:image" content="https://gpx.studio${base}/og_logo.png" />
<meta property="og:url" content="https://gpx.studio/" />
<meta property="og:type" content="website" />
<meta property="og:site_name" content="gpx.studio" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:image" content="https://gpx.studio${asset('/og_logo.png')}" />
<meta name="twitter:image" content="https://gpx.studio${base}/og_logo.png" />
<meta name="twitter:url" content="https://gpx.studio/" />
<meta name="twitter:site" content="@gpxstudio" />
<meta name="twitter:creator" content="@gpxstudio" />
<link rel="alternate" hreflang="x-default" href="https://gpx.studio${resolvePath(getURLForLanguage('en', path))}" />`;
<link rel="alternate" hreflang="x-default" href="https://gpx.studio${getURLForLanguage('en', path)}" />`;
// the manifests are made for the website, not for the desktop app (`npm run build:desktop`)
if (process.env.BUILD_TARGET !== 'desktop') {
@@ -56,7 +56,7 @@ export async function handle({ event, resolve }) {
if (page !== '404') {
for (let lang of Object.keys(languages)) {
headTag += ` <link rel="alternate" hreflang="${lang}" href="https://gpx.studio${resolvePath(getURLForLanguage(lang, path))}" />
headTag += ` <link rel="alternate" hreflang="${lang}" href="https://gpx.studio${getURLForLanguage(lang, path)}" />
`;
}
}
@@ -60,7 +60,7 @@
</script>
<svelte:head>
<link rel="preconnect" href="https://21XLD94PE3-dsn.algolia.net" crossorigin="anonymous" />
<link rel="preconnect" href="https://21XLD94PE3-dsn.algolia.net" crossorigin />
</svelte:head>
<div id="docsearch" class={props.class ?? ''}></div>
@@ -26,7 +26,7 @@
<Tooltip.Root>
<Tooltip.Trigger>
{#snippet child({ props })}
<Button {...props} {variant} {disabled} class="bg-inherit {className}" {onclick}>
<Button {...props} {variant} class="bg-inherit {className}" {onclick}>
{@render children()}
</Button>
{/snippet}
+3 -4
View File
@@ -1,5 +1,4 @@
<script lang="ts">
import { resolve } from '$app/paths';
import { Button } from '$lib/components/ui/button';
import LanguageSelect from '$lib/components/LanguageSelect.svelte';
import ModeSwitch from '$lib/components/ModeSwitch.svelte';
@@ -32,7 +31,7 @@
<Button
variant="link"
class="h-6 px-0 has-[>svg]:px-0 text-muted-foreground"
href={resolve(getURLForLanguage(i18n.lang, '/'))}
href={getURLForLanguage(i18n.lang, '/')}
>
<House size="16" />
{i18n._('homepage.home')}
@@ -41,7 +40,7 @@
data-sveltekit-reload
variant="link"
class="h-6 px-0 has-[>svg]:px-0 text-muted-foreground"
href={resolve(getURLForLanguage(i18n.lang, '/app'))}
href={getURLForLanguage(i18n.lang, '/app')}
>
<Map size="16" />
{i18n._('homepage.app')}
@@ -49,7 +48,7 @@
<Button
variant="link"
class="h-6 px-0 has-[>svg]:px-0 text-muted-foreground"
href={resolve(getURLForLanguage(i18n.lang, '/help'))}
href={getURLForLanguage(i18n.lang, '/help')}
>
<BookOpenText size="16" />
{i18n._('menu.help')}
+1 -2
View File
@@ -2,7 +2,6 @@
import { CircleQuestionMark } from '@lucide/svelte';
import { i18n } from '$lib/i18n/i18n.svelte';
import type { Snippet } from 'svelte';
import { resolve } from '$app/paths';
let {
link,
@@ -20,7 +19,7 @@
<div>
{@render children()}
{#if link}
<a href={resolve(link)} target="_blank" class="text-[13px] text-link hover:underline">
<a href={link} target="_blank" class="text-[13px] text-link hover:underline">
{i18n._('menu.more')}
</a>
{/if}
@@ -1,5 +1,4 @@
<script lang="ts">
import { resolve } from '$app/paths';
import { page } from '$app/state';
import * as Select from '$lib/components/ui/select';
import { languages } from '$lib/i18n/languages';
@@ -16,13 +15,13 @@
</span>
</Select.Trigger>
<Select.Content>
{#each Object.entries(languages) as [lang, label] (lang)}
{#each Object.entries(languages) as [lang, label]}
{#if page.url.pathname.includes('404')}
<a href={resolve(getURLForLanguage(lang, '/'))}>
<a href={getURLForLanguage(lang, '/')}>
<Select.Item value={lang}>{label}</Select.Item>
</a>
{:else}
<a href={resolve(getURLForLanguage(lang, page.url.pathname))}>
<a href={getURLForLanguage(lang, page.url.pathname)}>
<Select.Item value={lang}>{label}</Select.Item>
</a>
{/if}
+3 -3
View File
@@ -1,6 +1,6 @@
<script lang="ts">
import { mode } from 'mode-watcher';
import { asset } from '$app/paths';
import { base } from '$app/paths';
let {
iconOnly = false,
@@ -9,13 +9,13 @@
}: {
iconOnly?: boolean;
company?: 'gpx.studio' | 'github' | 'crowdin' | 'facebook' | 'reddit';
[key: string]: unknown;
[key: string]: any;
} = $props();
</script>
{#if company === 'gpx.studio'}
<img
src={asset(`/${iconOnly ? 'icon' : 'logo'}${mode.current === 'dark' ? '-dark' : ''}.svg`)}
src="{base}/{iconOnly ? 'icon' : 'logo'}{mode.current === 'dark' ? '-dark' : ''}.svg"
alt="Logo of gpx.studio."
{...others}
/>
+29 -46
View File
@@ -1,5 +1,4 @@
<script lang="ts">
import { resolve } from '$app/paths';
import * as Menubar from '$lib/components/ui/menubar/index.js';
import { Button } from '$lib/components/ui/button';
import Logo from '$lib/components/Logo.svelte';
@@ -79,7 +78,7 @@
} from '$lib/actions/file-actions';
import UnsavedDialog from '$lib/components/file-list/UnsavedDialog.svelte';
import { engine } from '$lib/engine';
import { allHidden, selectedFilesConversion } from '$lib/engine/selection-stores';
import { allHidden } from '$lib/engine/all-hidden';
import { selectedFileIds, selectionSize } from '$lib/engine/selection-helpers';
import { boundsManager } from '$lib/state/bounds';
import { onMount } from 'svelte';
@@ -149,7 +148,7 @@
<div
class="w-fit flex flex-row items-center justify-center p-1 bg-background rounded-b-md md:rounded-md pointer-events-auto shadow-md"
>
<a href={resolve(getURLForLanguage(i18n.lang, '/'))} target="_blank" class="shrink-0">
<a href={getURLForLanguage(i18n.lang, '/')} target="_blank" class="shrink-0">
<Logo class="h-5 mt-0.5 mx-2 md:hidden" iconOnly={true} width="16" />
<Logo class="h-5 mt-0.5 mx-2 hidden md:block" width="96" />
</a>
@@ -294,6 +293,19 @@
<PaintBucket size="16" />
{i18n._('menu.style.button')}
</Menubar.Item>
<Menubar.Item
onclick={() => engine.setSelectionHidden(!$allHidden)}
disabled={selectionCount == 0}
>
{#if $allHidden}
<Eye size="16" />
{i18n._('menu.unhide')}
{:else}
<EyeOff size="16" />
{i18n._('menu.hide')}
{/if}
<Shortcut key="H" ctrl={true} />
</Menubar.Item>
{#if $treeFileView}
{#if $selection.type === 'file'}
<Menubar.Separator />
@@ -335,25 +347,24 @@
</Menubar.Item>
{/if}
{/if}
{#if $selectedFilesConversion}
{#if !$treeFileView}
<Menubar.Separator />
{/if}
<Menubar.Item onclick={() => engine.convert()}>
<ArrowRightLeft size="16" />
{i18n._(
$selectedFilesConversion === 'route'
? 'menu.convert_to_routes'
: 'menu.convert_to_tracks'
)}
</Menubar.Item>
{/if}
<Menubar.Separator />
<Menubar.Item onclick={() => engine.selectAll()} disabled={noFiles}>
<FileStack size="16" />
{i18n._('menu.select_all')}
<Shortcut key="A" ctrl={true} />
</Menubar.Item>
<Menubar.Item
onclick={() => {
if (selectionCount > 0) {
boundsManager.centerMapOnSelection();
}
}}
disabled={selectionCount == 0}
>
<Maximize size="16" />
{i18n._('menu.center')}
<Shortcut key="⏎" ctrl={true} />
</Menubar.Item>
{#if $treeFileView}
<Menubar.Separator />
<Menubar.Item onclick={() => engine.copy()} disabled={selectionCount === 0}>
@@ -418,34 +429,6 @@
/>
</Menubar.CheckboxItem>
<Menubar.Separator />
<Menubar.Item
inset
onclick={() => engine.setSelectionHidden(!$allHidden)}
disabled={selectionCount == 0}
>
{#if $allHidden}
<Eye size="16" />
{i18n._('menu.unhide')}
{:else}
<EyeOff size="16" />
{i18n._('menu.hide')}
{/if}
<Shortcut key="H" ctrl={true} />
</Menubar.Item>
<Menubar.Item
inset
onclick={() => {
if (selectionCount > 0) {
boundsManager.centerMapOnSelection();
}
}}
disabled={selectionCount == 0}
>
<Maximize size="16" />
{i18n._('menu.center')}
<Shortcut key="⏎" ctrl={true} />
</Menubar.Item>
<Menubar.Separator />
<Menubar.Item inset onclick={() => map.toggle3D()}>
<Box size="16" />
{i18n._('menu.toggle_3d')}
@@ -527,8 +510,8 @@
</Menubar.SubTrigger>
<Menubar.SubContent>
<Menubar.RadioGroup value={i18n.lang}>
{#each Object.entries(languages) as [lang, label] (lang)}
<a href={resolve(getURLForLanguage(lang, '/app'))}>
{#each Object.entries(languages) as [lang, label]}
<a href={getURLForLanguage(lang, '/app')}>
<Menubar.RadioItem value={lang}>{label}</Menubar.RadioItem>
</a>
{/each}
+4 -5
View File
@@ -1,5 +1,4 @@
<script lang="ts">
import { resolve } from '$app/paths';
import Logo from '$lib/components/Logo.svelte';
import { Button } from '$lib/components/ui/button';
import { BookOpenText, House, Map } from '@lucide/svelte';
@@ -10,7 +9,7 @@
<nav class="sticky top-0 w-full px-12 py-2 bg-background z-50 flex flex-col items-center border-b">
<div class="w-full max-w-5xl flex flex-row items-center gap-4 sm:gap-8">
<a
href={resolve(getURLForLanguage(i18n.lang, '/'))}
href={getURLForLanguage(i18n.lang, '/')}
class="shrink-0 translate-y-0.25 justify-self-start"
>
<Logo class="h-8 xs:hidden" iconOnly={true} width="26" />
@@ -19,7 +18,7 @@
<Button
variant="link"
class="text-base px-0 has-[>svg]:px-0 ml-auto"
href={resolve(getURLForLanguage(i18n.lang, '/'))}
href={getURLForLanguage(i18n.lang, '/')}
>
<House size="18" />
{i18n._('homepage.home')}
@@ -28,7 +27,7 @@
data-sveltekit-reload
variant="link"
class="text-base px-0 has-[>svg]:px-0"
href={resolve(getURLForLanguage(i18n.lang, '/app'))}
href={getURLForLanguage(i18n.lang, '/app')}
>
<Map size="18" />
{i18n._('homepage.app')}
@@ -36,7 +35,7 @@
<Button
variant="link"
class="text-base px-0 has-[>svg]:px-0"
href={resolve(getURLForLanguage(i18n.lang, '/help'))}
href={getURLForLanguage(i18n.lang, '/help')}
>
<BookOpenText size="18" />
{i18n._('menu.help')}
+3 -3
View File
@@ -39,7 +39,7 @@ export function getPreviousGuide(currentGuide: string): string | undefined {
return `${previousGuide}/${guides[previousGuide][guides[previousGuide].length - 1]}`;
}
} else {
if (Object.hasOwn(guides, subguides[0])) {
if (guides.hasOwnProperty(subguides[0])) {
const subguideIndex = guides[subguides[0]].indexOf(subguides[1]);
if (subguideIndex > 0) {
return `${subguides[0]}/${guides[subguides[0]][subguideIndex - 1]}`;
@@ -56,7 +56,7 @@ export function getNextGuide(currentGuide: string): string | undefined {
const subguides = currentGuide.split('/');
if (subguides.length === 1) {
if (Object.hasOwn(guides, currentGuide)) {
if (guides.hasOwnProperty(currentGuide)) {
if (guides[currentGuide].length === 0) {
const keys = Object.keys(guides);
const index = keys.indexOf(currentGuide);
@@ -68,7 +68,7 @@ export function getNextGuide(currentGuide: string): string | undefined {
return undefined;
}
} else {
if (Object.hasOwn(guides, subguides[0])) {
if (guides.hasOwnProperty(subguides[0])) {
const subguideIndex = guides[subguides[0]].indexOf(subguides[1]);
if (subguideIndex < guides[subguides[0]].length - 1) {
return `${subguides[0]}/${guides[subguides[0]][subguideIndex + 1]}`;
@@ -31,7 +31,6 @@
statistics,
slicedStatistics,
hoveredPoint,
hoveredTrackpoint,
additionalDatasets,
elevationFill,
showControls = true,
@@ -39,7 +38,6 @@
statistics: Readable<SelectionStatistics>;
slicedStatistics: Writable<SlicedStatistics | undefined>;
hoveredPoint: Writable<Coordinates | null>;
hoveredTrackpoint?: Readable<number | null>;
additionalDatasets: Writable<string[]>;
elevationFill: Writable<'slope' | 'surface' | 'highway' | undefined>;
showControls?: boolean;
@@ -57,8 +55,7 @@
additionalDatasets,
elevationFill,
canvas,
overlay,
hoveredTrackpoint
overlay
);
});
@@ -15,15 +15,10 @@ import {
getVelocityWithUnits,
} from '$lib/units/units';
import Chart, {
Tooltip,
type ActiveDataPoint,
type ChartEvent,
type ChartOptions,
type ChartType,
type Point,
type ScriptableLineSegmentContext,
type TooltipItem,
type TooltipPositionerFunction,
} from 'chart.js/auto';
import { get, type Readable, type Writable } from 'svelte/store';
import type { Coordinates } from '$lib/geo/coordinates';
@@ -45,25 +40,6 @@ const { distanceUnits, velocityUnits, temperatureUnits } = settings;
Chart.defaults.font.family =
'ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"'; // Tailwind CSS font
declare module 'chart.js' {
interface TooltipPositionerMap {
trackpoint: TooltipPositionerFunction<ChartType>;
}
}
/** Marks the positions of the trackpoints shown without an event of the chart. */
const trackpointPosition = Symbol('trackpointPosition');
/**
* Like the default for the events of the chart. A trackpoint that is shown without one is given by
* its position, as it can be between the points of the chart (see `activateTrackpoint`).
*/
Tooltip.positioners.trackpoint = function (items, position) {
return trackpointPosition in position
? position
: Tooltip.positioners.average.call(this, items, position);
};
/** `undefined` for a missing measure (NaN), so that Chart.js leaves a gap instead of a value. */
function optional(value: number, convert: (value: number) => number = (v) => v) {
return Number.isNaN(value) ? undefined : convert(value);
@@ -79,21 +55,6 @@ interface ElevationProfilePoint {
index: number;
}
/** The index of the point the closest to `x`, in points sorted by `x`. */
function nearestPointIndex(points: { x: number }[], x: number): number {
let low = 0;
let high = points.length - 1;
while (low < high) {
const middle = (low + high) >> 1;
if (points[middle].x < x) {
low = middle + 1;
} else {
high = middle;
}
}
return low > 0 && x - points[low - 1].x < points[low].x - x ? low - 1 : low;
}
export class ElevationProfile {
private _chart: Chart | null = null;
private _canvas: HTMLCanvasElement;
@@ -110,14 +71,10 @@ export class ElevationProfile {
*/
private _hovered: { index: number; loaded: boolean; point?: SelectionPoint } | null = null;
private _loadingHovered = false;
/** The last move over the chart, held until the data of its trackpoint is read. */
private _heldMove: MouseEvent | null = null;
private _slicedStatistics: Writable<SlicedStatistics | undefined>;
private _hoveredPoint: Writable<Coordinates | null>;
/** All the points of each dataset, including the ones that the chart decimated. */
private _points: ElevationProfilePoint[][] = [];
/** The trackpoint hovered somewhere else, that the tooltip shows instead of its elements. */
private _shownTrackpoint: number | null = null;
private _hoveredTrackpoint: Readable<number | null> | undefined;
private _unsubscribeHoveredTrackpoint: (() => void) | undefined;
private _additionalDatasets: Readable<string[]>;
private _elevationFill: Readable<'slope' | 'surface' | 'highway' | undefined>;
/** The statistics that are only read from the engine while the profile shows them. */
@@ -130,8 +87,7 @@ export class ElevationProfile {
additionalDatasets: Readable<string[]>,
elevationFill: Readable<'slope' | 'surface' | 'highway' | undefined>,
canvas: HTMLCanvasElement,
overlay: HTMLCanvasElement,
hoveredTrackpoint?: Readable<number | null>
overlay: HTMLCanvasElement
) {
this._statistics = statistics;
this._slicedStatistics = slicedStatistics;
@@ -140,7 +96,6 @@ export class ElevationProfile {
this._elevationFill = elevationFill;
this._canvas = canvas;
this._overlay = overlay;
this._hoveredTrackpoint = hoveredTrackpoint;
this._request = engine.requestStatistics();
this.updateRequest();
@@ -172,9 +127,6 @@ export class ElevationProfile {
this.updateRequest();
this.updateFill();
});
this._unsubscribeHoveredTrackpoint = this._hoveredTrackpoint?.subscribe((index) => {
this.showTrackpoint(index);
});
});
}
@@ -196,7 +148,7 @@ export class ElevationProfile {
}
initialize() {
const options: ChartOptions<'line'> = {
let options: ChartOptions<'line'> = {
animation: false,
parsing: false,
maintainAspectRatio: false,
@@ -226,7 +178,6 @@ export class ElevationProfile {
tension: 0.4,
borderWidth: 2,
cubicInterpolationMode: 'monotone',
spanGaps: true,
},
},
interaction: {
@@ -243,16 +194,20 @@ export class ElevationProfile {
},
tooltip: {
enabled: () => !this._dragging && !this._panning,
position: 'trackpoint',
callbacks: {
title: () => {
return '';
},
label: (context: TooltipItem<'line'>) => {
const point = this.pointOf(context);
let point = context.raw as ElevationProfilePoint;
if (context.datasetIndex === 0) {
this._hoveredPoint.set(
this._dragging ? null : this.coordinatesOf(point.index)
this._dragging
? null
: {
lat: this._data.lat[point.index],
lng: this._data.lng[point.index],
}
);
return `${i18n._('quantities.elevation')}: ${getElevationWithUnits(point.y, false)}`;
} else if (context.datasetIndex === 1) {
@@ -268,18 +223,16 @@ export class ElevationProfile {
}
},
afterBody: (contexts: TooltipItem<'line'>[]) => {
const context = contexts.filter(
(context) => context.datasetIndex === 0
);
let context = contexts.filter((context) => context.datasetIndex === 0);
if (context.length === 0) return;
const point = this.pointOf(context[0]);
let point = context[0].raw as ElevationProfilePoint;
// the rest of the data is there once it is read (see `hover`)
const hovered = this._hovered;
const details =
hovered?.index === point.index ? hovered.point : undefined;
const elevationFill = get(this._elevationFill);
const labels = [
let labels = [
` ${i18n._('quantities.distance')}: ${getDistanceWithUnits(point.x, false)}`,
];
@@ -297,10 +250,10 @@ export class ElevationProfile {
}
labels.push(` ${i18n._('quantities.slope')}: ${slope}`);
}
const surface = details.surface ?? 'unknown';
const highway = details.highway ?? 'unknown';
const sacScale = details.sacScale;
const mtbScale = details.mtbScale;
let surface = details.surface ?? 'unknown';
let highway = details.highway ?? 'unknown';
let sacScale = details.sacScale;
let mtbScale = details.mtbScale;
if (elevationFill === 'surface') {
labels.push(
@@ -352,7 +305,7 @@ export class ElevationProfile {
enabled: true,
},
mode: 'x',
onZoomStart: ({ event }: { event: any }) => {
onZoomStart: ({ chart, event }: { chart: Chart; event: any }) => {
if (!this._chart) {
return false;
}
@@ -382,7 +335,7 @@ export class ElevationProfile {
},
};
const datasets: string[] = ['speed', 'hr', 'cad', 'atemp', 'power'];
let datasets: string[] = ['speed', 'hr', 'cad', 'atemp', 'power'];
datasets.forEach((id) => {
options.scales![`y${id}`] = {
type: 'linear',
@@ -390,8 +343,7 @@ export class ElevationProfile {
grid: {
display: false,
},
// the pace axis is reversed: set with the data, which the units change
reverse: false,
reverse: () => id === 'speed' && get(velocityUnits) === 'pace',
display: false,
};
});
@@ -409,21 +361,29 @@ export class ElevationProfile {
afterEvent: (chart: Chart, args: { event: ChartEvent }) => {
if (args.event.type === 'mouseout') {
this._hovered = null;
this._heldMove = null;
this._hoveredPoint.set(null);
}
},
},
{
// The tooltip follows the pointer at once with what the chart knows of the
// trackpoint, and shows the rest of its data once it is read (see
// `loadHovered`).
id: 'loadTrackpoint',
// The tooltip only shows a trackpoint once all its data is read: a move to
// another one is held until then, and replayed (see `loadHovered`).
id: 'waitForTrackpoint',
events: ['mousemove'],
beforeEvent: (chart: Chart, args: { event: ChartEvent }) => {
const index = this.indexAt(args.event);
if (index !== undefined) {
this.hover(index);
if (index === undefined) {
return;
}
const hovered = this._hovered;
if (hovered?.index === index && hovered.loaded) {
this._heldMove = null;
return;
}
this._heldMove = args.event.native as MouseEvent;
this.hover(index);
return false;
},
},
],
@@ -514,7 +474,6 @@ export class ElevationProfile {
}
const data = get(this._statistics);
this._data = data;
const shownTrackpoint = this._shownTrackpoint;
// the indices of the trackpoints are the ones of other statistics
this._hovered = null;
const units = {
@@ -561,7 +520,6 @@ export class ElevationProfile {
}
}
this._points = datasets;
this._chart.data.datasets[0] = {
label: i18n._('quantities.elevation'),
data: datasets[0],
@@ -601,17 +559,11 @@ export class ElevationProfile {
global.totalDistance,
units.distance
);
// a faster pace is a lower value, it goes up like a higher speed
this._chart.options.scales!.yspeed!.reverse = units.velocity === 'pace';
this.setVisibility();
this.setFill();
this._chart.update();
if (shownTrackpoint !== null) {
this.showTrackpoint(shownTrackpoint);
}
}
updateDataVisibility() {
@@ -628,11 +580,11 @@ export class ElevationProfile {
}
const additionalDatasets = get(this._additionalDatasets);
const includeSpeed = additionalDatasets.includes('speed');
const includeHeartRate = additionalDatasets.includes('hr');
const includeCadence = additionalDatasets.includes('cad');
const includeTemperature = additionalDatasets.includes('atemp');
const includePower = additionalDatasets.includes('power');
let includeSpeed = additionalDatasets.includes('speed');
let includeHeartRate = additionalDatasets.includes('hr');
let includeCadence = additionalDatasets.includes('cad');
let includeTemperature = additionalDatasets.includes('atemp');
let includePower = additionalDatasets.includes('power');
if (this._chart.data.datasets.length == 6) {
this._chart.data.datasets[1].hidden = !includeSpeed;
this._chart.data.datasets[2].hidden = !includeHeartRate;
@@ -687,21 +639,21 @@ export class ElevationProfile {
const slicedStatistics = get(this._slicedStatistics);
if (slicedStatistics) {
const startIndex = slicedStatistics.start;
const endIndex = slicedStatistics.end;
let startIndex = slicedStatistics.start;
let endIndex = slicedStatistics.end;
// Draw selection rectangle
const selectionContext = this._overlay.getContext('2d');
let selectionContext = this._overlay.getContext('2d');
if (selectionContext) {
selectionContext.fillStyle = mode.current === 'dark' ? 'white' : 'black';
selectionContext.globalAlpha = mode.current === 'dark' ? 0.2 : 0.1;
selectionContext.clearRect(0, 0, this._overlay.width, this._overlay.height);
const statistics = get(this._statistics);
const startPixel = this._chart.scales.x.getPixelForValue(
let startPixel = this._chart.scales.x.getPixelForValue(
getConvertedDistance(statistics.totalDistance[startIndex] ?? 0)
);
const endPixel = this._chart.scales.x.getPixelForValue(
let endPixel = this._chart.scales.x.getPixelForValue(
getConvertedDistance(statistics.totalDistance[endIndex] ?? 0)
);
@@ -713,81 +665,13 @@ export class ElevationProfile {
);
}
} else if (this._overlay) {
const selectionContext = this._overlay.getContext('2d');
let selectionContext = this._overlay.getContext('2d');
if (selectionContext) {
selectionContext.clearRect(0, 0, this._overlay.width, this._overlay.height);
}
}
}
/** The point that a line of the tooltip is about. */
private pointOf(context: TooltipItem<'line'>): ElevationProfilePoint {
return this._shownTrackpoint === null
? (context.raw as ElevationProfilePoint)
: this._points[context.datasetIndex][this._shownTrackpoint];
}
private coordinatesOf(index: number): Coordinates {
return { lat: this._data.lat[index], lng: this._data.lng[index] };
}
/** Shows a trackpoint in the tooltip like when hovering it, or nothing anymore with `null`. */
private showTrackpoint(index: number | null) {
const shown = this._shownTrackpoint;
this._shownTrackpoint = index;
if (index !== null) {
this.hover(index);
if (this._hovered?.loaded) {
this.activateTrackpoint(index);
}
} else if (shown !== null) {
this._hovered = null;
this.setActiveElements([], { x: 0, y: 0 });
this._hoveredPoint.set(null);
}
}
/**
* Opens the tooltip on a trackpoint, once its data is read. The chart can only activate the
* points that it kept after decimating its data, which are different for each dataset and might
* not include the trackpoint: it activates the nearest ones, within a pixel of it, and the
* tooltip reads the values of the trackpoint (see `pointOf`).
*/
private activateTrackpoint(index: number) {
const point = this._points[0]?.[index];
if (!this._chart || !point) {
return;
}
const { x: xScale, y: yScale } = this._chart.scales;
const elements: ActiveDataPoint[] = [];
// when the chart is zoomed, the trackpoint can be outside of it
if (xScale.min <= point.x && point.x <= xScale.max) {
for (const { index: datasetIndex } of this._chart.getSortedVisibleDatasetMetas()) {
if (this._points[datasetIndex]?.[index]?.y !== undefined) {
const data = this._chart.data.datasets[datasetIndex].data as { x: number }[];
elements.push({ datasetIndex, index: nearestPointIndex(data, point.x) });
}
}
}
if (elements.length === 0) {
// no tooltip to tell the map about the point
this._hoveredPoint.set(this.coordinatesOf(index));
}
this.setActiveElements(elements, {
x: xScale.getPixelForValue(point.x),
y: yScale.getPixelForValue(point.y),
[trackpointPosition]: true,
} as Point);
}
private setActiveElements(elements: ActiveDataPoint[], position: Point) {
if (this._chart) {
this._chart.tooltip?.setActiveElements(elements, position);
this._chart.setActiveElements(elements);
this._chart.render();
}
}
/** The trackpoint that the tooltip shows for an event, `undefined` outside of the chart. */
private indexAt(event: ChartEvent): number | undefined {
const elements = this._chart?.getElementsAtEventForMode(
@@ -828,10 +712,11 @@ export class ElevationProfile {
}
hovered.loaded = true;
hovered.point = point;
if (this._shownTrackpoint === hovered.index) {
this.activateTrackpoint(hovered.index);
} else {
this.refreshTooltip();
// the move that was held can now show the tooltip
const move = this._heldMove;
this._heldMove = null;
if (move) {
this._canvas.dispatchEvent(new MouseEvent(move.type, move));
}
}
} finally {
@@ -839,18 +724,6 @@ export class ElevationProfile {
}
}
/** Writes the tooltip again, on the same trackpoint, for the data that was read since. */
private refreshTooltip() {
// the plugin of the tooltip, whose type only has its model
const tooltip = this._chart?.tooltip as
| (Chart['tooltip'] & { update(changed: boolean): void })
| undefined;
if (tooltip && tooltip.getActiveElements().length > 0) {
tooltip.update(true);
this._chart!.render();
}
}
/** The trackpoint that a segment of the chart starts at. */
private static segmentStart(context: ScriptableLineSegmentContext & { p0: { raw: any } }) {
return (context.p0.raw as ElevationProfilePoint).index;
@@ -879,7 +752,6 @@ export class ElevationProfile {
destroy() {
this._request.release();
this._unsubscribeHoveredTrackpoint?.();
if (this._chart) {
this._chart.destroy();
this._chart = null;
@@ -18,11 +18,7 @@
import { untrack } from 'svelte';
import { isSelected, toggle } from '$lib/components/map/layer-control/utils';
import { engine } from '$lib/engine';
import {
hoveredPoint,
hoveredTrackpoint,
slicedStatistics,
} from '$lib/state/selection-statistics';
import { hoveredPoint, slicedStatistics } from '$lib/state/selection-statistics';
let {
useHash = true,
@@ -123,7 +119,6 @@
{statistics}
{slicedStatistics}
{hoveredPoint}
{hoveredTrackpoint}
{additionalDatasets}
{elevationFill}
showControls={options.elevation.controls}
@@ -25,10 +25,9 @@
import { PUBLIC_MAPTILER_KEY } from '$env/static/public';
import Embedding from './Embedding.svelte';
import { onDestroy } from 'svelte';
import { resolve } from '$app/paths';
import { base } from '$app/paths';
import { map } from '$lib/components/map/map';
import { mode } from 'mode-watcher';
import { getURLForLanguage } from '$lib/utils';
let options = $state(
getMergedEmbeddingOptions(
@@ -115,7 +114,7 @@
{i18n._(`layers.label.${options.basemap}`)}
</Select.Trigger>
<Select.Content class="max-h-60 overflow-y-scroll">
{#each allowedEmbeddingBasemaps as basemap (basemap)}
{#each allowedEmbeddingBasemaps as basemap}
<Select.Item value={basemap}
>{i18n._(`layers.label.${basemap}`)}</Select.Item
>
@@ -322,7 +321,7 @@
<pre
class="bg-primary text-primary-foreground p-3 rounded-md whitespace-normal break-all">
<code class="language-html">
{`<iframe src="https://gpx.studio${resolve(getURLForLanguage(i18n.lang, '/embed'))}?options=${encodeURIComponent(JSON.stringify(getCleanedEmbeddingOptions(iframeOptions)))}${hash}" width="100%" height="600px" frameborder="0" style="outline: none;"/>`}
{`<iframe src="https://gpx.studio${base}/embed?options=${encodeURIComponent(JSON.stringify(getCleanedEmbeddingOptions(iframeOptions)))}${hash}" width="100%" height="600px" frameborder="0" style="outline: none;"/>`}
</code>
</pre>
</fieldset>
@@ -1,5 +1,4 @@
<script lang="ts">
import { resolve } from '$app/paths';
import { Button } from '$lib/components/ui/button';
import Logo from '$lib/components/Logo.svelte';
import { getURLForLanguage } from '$lib/utils';
@@ -17,7 +16,7 @@
<Button
variant="ghost"
class="absolute top-0 flex-wrap h-fit bg-background font-semibold rounded-md py-1 px-2 gap-1.5 xs:text-base mt-2.5 ml-2.5 mr-12"
href="{resolve(getURLForLanguage(i18n.lang, '/app'))}?{files.length > 0
href="{getURLForLanguage(i18n.lang, '/app')}?{files.length > 0
? `files=${encodeURIComponent(JSON.stringify(files))}`
: ''}{files.length > 0 && ids.length > 0 ? '&' : ''}{ids.length > 0
? `ids=${encodeURIComponent(JSON.stringify(ids))}`
@@ -109,7 +109,7 @@ export function getURLForGoogleDriveFile(fileId: string): string {
}
export function convertOldEmbeddingOptions(options: URLSearchParams): any {
const newOptions: any = {
let newOptions: any = {
key: PUBLIC_MAPTILER_KEY,
files: [],
ids: [],
@@ -128,7 +128,7 @@ export function convertOldEmbeddingOptions(options: URLSearchParams): any {
}
}
if (options.has('source')) {
const basemap = options.get('source')!;
let basemap = options.get('source')!;
if (basemap === 'satellite') {
newOptions.basemap = 'libertySatellite';
} else if (basemap === 'otm') {
@@ -132,6 +132,7 @@
<div class="flex flex-col h-full">
<div class="px-2 py-1 text-sm font-semibold shrink-0">{i18n._('menu.explorer')}</div>
<ScrollArea class="grow min-h-0">
<!-- svelte-ignore a11y_no_noninteractive_tabindex -->
<div
bind:this={container}
data-explorer
@@ -29,7 +29,7 @@
import { editStyle } from '$lib/components/file-list/style/utils.svelte';
import { getSymbolKey, symbols } from '$lib/data/symbols';
import { engine, type FileState } from '$lib/engine';
import { allHidden, selectedFilesConversion } from '$lib/engine/selection-stores';
import { allHidden } from '$lib/engine/all-hidden';
import { normalizeColor } from '$lib/engine/file-colors';
import { isHidden } from '$lib/engine/file-visibility';
import {
@@ -121,6 +121,7 @@
let isCut = $derived($clipboard?.cut === true && isInClipboard($clipboard, node));
</script>
<!-- svelte-ignore a11y_click_events_have_key_events -->
<!-- svelte-ignore a11y_no_static_element_interactions -->
<ContextMenu.Root
onOpenChange={(open) => {
@@ -258,8 +259,18 @@
<PaintBucket size="16" />
{i18n._('menu.style.button')}
</ContextMenu.Item>
<ContextMenu.Separator />
{/if}
<ContextMenu.Item onclick={() => engine.setSelectionHidden(!$allHidden)}>
{#if $allHidden}
<Eye size="16" />
{i18n._('menu.unhide')}
{:else}
<EyeOff size="16" />
{i18n._('menu.hide')}
{/if}
<Shortcut key="H" ctrl={true} />
</ContextMenu.Item>
<ContextMenu.Separator />
{#if orientation === 'vertical'}
{#if node.type === 'file'}
<ContextMenu.Item disabled={!singleSelection} onclick={() => engine.newTrack()}>
@@ -270,6 +281,7 @@
<Plus size="16" />
{i18n._('menu.new_route')}
</ContextMenu.Item>
<ContextMenu.Separator />
{:else if node.type === 'track'}
<ContextMenu.Item
disabled={!singleSelection}
@@ -289,44 +301,18 @@
<ContextMenu.Separator />
{/if}
{/if}
{#if node.type === 'file'}
{#if $selectedFilesConversion}
<ContextMenu.Item onclick={() => engine.convert()}>
<ArrowRightLeft size="16" />
{i18n._(
$selectedFilesConversion === 'route'
? 'menu.convert_to_routes'
: 'menu.convert_to_tracks'
)}
</ContextMenu.Item>
{/if}
{#if orientation === 'vertical' || $selectedFilesConversion}
<ContextMenu.Separator />
{/if}
{/if}
<ContextMenu.Item onclick={() => engine.setSelectionHidden(!$allHidden)}>
{#if $allHidden}
<Eye size="16" />
{i18n._('menu.unhide')}
{:else}
<EyeOff size="16" />
{i18n._('menu.hide')}
{/if}
<Shortcut key="H" ctrl={true} />
</ContextMenu.Item>
<ContextMenu.Item onclick={() => boundsManager.centerMapOnSelection()}>
<Maximize size="16" />
{i18n._('menu.center')}
<Shortcut key="⏎" ctrl={true} />
</ContextMenu.Item>
{#if level !== 'waypoints'}
<ContextMenu.Separator />
<ContextMenu.Item onclick={() => engine.selectAll()}>
<FileStack size="16" />
{i18n._('menu.select_all')}
<Shortcut key="A" ctrl={true} />
</ContextMenu.Item>
{/if}
<ContextMenu.Item onclick={() => boundsManager.centerMapOnSelection()}>
<Maximize size="16" />
{i18n._('menu.center')}
<Shortcut key="⏎" ctrl={true} />
</ContextMenu.Item>
<ContextMenu.Separator />
<ContextMenu.Item onclick={() => engine.duplicate()}>
<Copy size="16" />
@@ -43,7 +43,7 @@
</AlertDialog.Description>
</AlertDialog.Header>
<ul class="list-disc pl-6 text-sm max-h-40 overflow-y-auto">
{#each prompt.names as name, i (i)}
{#each prompt.names as name}
<li>{name}</li>
{/each}
</ul>
@@ -3,7 +3,6 @@
import { Input } from '$lib/components/ui/input';
import { Textarea } from '$lib/components/ui/textarea';
import { Label } from '$lib/components/ui/label/index.js';
import { Checkbox } from '$lib/components/ui/checkbox';
import * as Popover from '$lib/components/ui/popover';
import { Save } from '@lucide/svelte';
import { i18n } from '$lib/i18n/i18n.svelte';
@@ -31,48 +30,9 @@
node.type === 'file' ? (fileState.structure.desc ?? '') : (path?.desc ?? '')
);
const { workspace } = engine;
// the name of the file on the disk, without its extension (the desktop app), which is not the
// name of the file: it can be renamed with it, which is not undone
let fileName = $derived.by(() => {
if (node.type !== 'file') return undefined;
const path = $workspace?.files[node.fileId]?.path;
return path
?.split(/[\\/]/)
.pop()
?.replace(/\.[^.]*$/, '');
});
// asked only when the name is changed, and proposed then
let renamed = $derived(node.type === 'file' && name !== fileState.structure.name);
let renameFile = $state(true);
async function save() {
// closes the dialog now: `open` follows `editMetadata`, and the change of the file would
// open the dialog again before the effect below has reset it
editMetadata.current = false;
open = false;
// the file on the disk first: nothing is changed if it cannot be renamed (the name of
// another file, for instance)
if (
renamed &&
renameFile &&
fileName !== undefined &&
fileName !== name &&
node.type === 'file'
) {
if (!(await engine.renameFile(node.fileId, name))) {
showEngineError();
return;
}
}
engine.metadata(name, description);
}
$effect(() => {
if (!open) {
editMetadata.current = false;
renameFile = true;
}
});
</script>
@@ -84,13 +44,22 @@
<Input bind:value={name} id="name" class="font-semibold h-8" />
<Label for="description">{i18n._('menu.metadata.description')}</Label>
<Textarea bind:value={description} id="description" />
{#if fileName !== undefined && renamed}
<div class="flex flex-row items-center gap-2">
<Checkbox id="rename-file" bind:checked={renameFile} class="scale-90" />
<Label for="rename-file">{i18n._('menu.metadata.rename_file')}</Label>
</div>
{/if}
<Button variant="outline" onclick={save}>
<Button
variant="outline"
onclick={() => {
// closes the dialog now: `open` follows `editMetadata`, and the change of the file
// would open the dialog again before the effect below has reset it
editMetadata.current = false;
open = false;
// the metadata of the selected elements are changed. In the desktop app, a file on
// the disk is renamed with it, which is refused if the name is the one of another
engine.metadata(name, description).then((changed) => {
if (!changed) {
showEngineError();
}
});
}}
>
<Save size="16" />
{i18n._('menu.metadata.save')}
</Button>
@@ -1,6 +1,5 @@
import { isMac } from '$lib/utils';
import Sortable from './sortable';
import type { Direction } from 'sortablejs';
import Sortable, { type Direction } from 'sortablejs/Sortable';
import { get, writable } from 'svelte/store';
import { tick } from 'svelte';
import { engine, type MoveTarget, type Selection } from '$lib/engine';
@@ -79,13 +78,9 @@ export class SortableFileList {
setTimeout(() => this.updateToSelection(e), 50),
onDeselect: (e: Sortable.SortableEvent) =>
setTimeout(() => this.updateToSelection(e), 50),
onChoose: () => {
// all the nodes, not only the elements: the comments are the anchors of the Svelte
// blocks. Taken before the drag starts, when MultiDrag removes the other selected
// elements from the list.
this._snapshot = Array.from(container.childNodes);
},
onStart: (e: Sortable.SortableEvent) => {
// all the nodes, not only the elements: the comments are the anchors of the Svelte blocks
this._snapshot = Array.from(container.childNodes);
dragging.set(sortableLevel);
// the files that are dragged (or whose elements are) are open for good
engine.keepPreview(this.draggedFiles(e));
@@ -246,9 +241,9 @@ export class SortableFileList {
return;
}
const selection_ = get(engine.selection);
for (const id of changed) {
const element = this._elements[id];
const node = this.childNode(id);
for (let id of changed) {
let element = this._elements[id];
let node = this.childNode(id);
if (element && node) {
if (isSelected(selection_, node)) {
Sortable.utils.select(element);
@@ -263,7 +258,7 @@ export class SortableFileList {
}
}
updateToSelection(e: Sortable.SortableEvent & { originalEvent?: MouseEvent }) {
updateToSelection(e: Sortable.SortableEvent) {
if (!this._sortable) return;
if (this._updatingSelection || this._applying) return;
this._updatingSelection = true;
@@ -349,7 +344,7 @@ export class SortableFileList {
const files = get(engine.files);
this._container.childNodes.forEach((element) => {
if (element instanceof HTMLElement) {
const attr = element.getAttribute('data-id');
let attr = element.getAttribute('data-id');
if (attr) {
if (this._sortableLevel === 'file' && !files.has(attr)) {
this.forget(element);
@@ -397,12 +392,12 @@ export class SortableFileList {
}
getChangedIds() {
const changed: string[] = [];
let changed: string[] = [];
const selection_ = get(engine.selection);
Object.entries(this._elements).forEach(([id, element]) => {
const node = this.childNode(id);
const inSelection = node !== undefined && isSelected(selection_, node);
const isSelectedInList = element.classList.contains('sortable-selected');
let inSelection = node !== undefined && isSelected(selection_, node);
let isSelectedInList = element.classList.contains('sortable-selected');
if (inSelection !== isSelectedInList) {
changed.push(id);
}
@@ -1,7 +0,0 @@
import Sortable, { MultiDrag } from 'sortablejs';
// The ESM build leaves out the MultiDrag plugin. Mounting it twice throws, so it is done here
// rather than in a module that hot reloading runs again.
Sortable.mount(new MultiDrag());
export default Sortable;
@@ -5,7 +5,6 @@
import { StartEndMarkers } from '$lib/components/map/gpx-layer/start-end-markers';
import { createPopups, removePopups } from '$lib/components/map/gpx-layer/gpx-layer-popup';
import { map } from '$lib/components/map/map';
import { hoveredTrackpoint } from '$lib/state/selection-statistics';
let distanceMarkers: DistanceMarkers;
let startEndMarkers: StartEndMarkers;
@@ -15,11 +14,6 @@
startEndMarkers = new StartEndMarkers();
distanceMarkers = new DistanceMarkers();
createPopups(map_);
// the layers do not see the pointer when it leaves the map or when it drags something
const stopHovering = () => hoveredTrackpoint.set(null);
map_.on('mouseout', stopHovering);
map_.on('mousedown', stopHovering);
map_.on('movestart', stopHovering);
});
onDestroy(() => {
@@ -2,15 +2,17 @@
import { Button } from '$lib/components/ui/button';
import CopyCoordinates from '$lib/components/map/gpx-layer/CopyCoordinates.svelte';
import * as Card from '$lib/components/ui/card';
import { Compass, Earth } from '@lucide/svelte';
import WithUnits from '$lib/components/WithUnits.svelte';
import { Compass, Earth, Mountain, Timer } from '@lucide/svelte';
import { i18n } from '$lib/i18n/i18n.svelte';
import type { PopupItem } from '$lib/components/map/map-popup';
import type { TrackpointDetails } from '$lib/engine';
import { map } from '$lib/components/map/map';
let {
trackpoint,
}: {
trackpoint: PopupItem<{ lng: number; lat: number }>;
trackpoint: PopupItem<Pick<TrackpointDetails, 'lng' | 'lat'> & Partial<TrackpointDetails>>;
} = $props();
</script>
@@ -20,19 +22,33 @@
<Compass size="14" />
{trackpoint.item.lat.toFixed(6)}&deg; {trackpoint.item.lng.toFixed(6)}&deg;
</div>
{#if trackpoint.item.ele !== undefined}
<div class="flex flex-row items-center gap-1">
<Mountain size="14" />
<WithUnits value={trackpoint.item.ele} type="elevation" />
</div>
{/if}
{#if trackpoint.item.time !== undefined}
<div class="flex flex-row items-center gap-1">
<Timer size="14" />
{i18n.df.format(new Date(trackpoint.item.time))}
</div>
{/if}
<CopyCoordinates
coordinates={trackpoint.item}
onCopy={() => trackpoint.hide?.()}
class="mt-0.5"
/>
<Button
variant="outline"
class="justify-start"
href={`https://www.openstreetmap.org/edit?#map=${(($map?.getZoom() ?? 17) + 1).toFixed(0)}/${trackpoint.item.lat.toFixed(5)}/${trackpoint.item.lng.toFixed(5)}`}
target="_blank"
>
<Earth size="14" />
{i18n._('menu.edit_osm')}
</Button>
{#if trackpoint.fileId === undefined}
<Button
variant="outline"
class="justify-start"
href={`https://www.openstreetmap.org/edit?#map=${(($map?.getZoom() ?? 17) + 1).toFixed(0)}/${trackpoint.item.lat.toFixed(5)}/${trackpoint.item.lng.toFixed(5)}`}
target="_blank"
>
<Earth size="14" />
{i18n._('menu.edit_osm')}
</Button>
{/if}
</Card.Content>
</Card.Root>
@@ -48,7 +48,7 @@
<Card.Title class="text-md">
{@const link = waypoint.item.links?.[0]}
{#if link?.href}
<a href={link.href} target="_blank" rel="external">
<a href={link.href} target="_blank">
{waypoint.item.name ?? link.href}
<ExternalLink size="12" class="inline-block mb-1.5" />
</a>
@@ -77,11 +77,9 @@
</div>
<ScrollArea class="flex flex-col max-h-[30dvh]">
{#if waypoint.item.desc}
<!-- eslint-disable-next-line svelte/no-at-html-tags -- sanitized -->
<span class="whitespace-pre-wrap">{@html sanitize(waypoint.item.desc)}</span>
{/if}
{#if waypoint.item.cmt && waypoint.item.cmt !== waypoint.item.desc}
<!-- eslint-disable-next-line svelte/no-at-html-tags -- sanitized -->
<span class="whitespace-pre-wrap">{@html sanitize(waypoint.item.cmt)}</span>
{/if}
</ScrollArea>
@@ -3,7 +3,7 @@ import { engine } from '$lib/engine';
import { getConvertedDistanceToKilometers } from '$lib/units/units';
import { get } from 'svelte/store';
import { map } from '$lib/components/map/map';
import { allHidden } from '$lib/engine/selection-stores';
import { allHidden } from '$lib/engine/all-hidden';
import type { GeoJSONSource } from 'maplibre-gl';
import { ANCHOR_LAYER_KEY } from '$lib/components/map/style';
@@ -35,8 +35,7 @@ export class DistanceMarkers {
try {
if (get(distanceMarkers) && !get(allHidden)) {
const distanceSource: GeoJSONSource | undefined =
map_.getSource('distance-markers');
let distanceSource: GeoJSONSource | undefined = map_.getSource('distance-markers');
if (distanceSource) {
distanceSource.setData(this.getDistanceMarkersGeoJSON());
} else {
@@ -91,7 +90,7 @@ export class DistanceMarkers {
map_.removeLayer('distance-markers');
}
}
} catch {
} catch (e) {
// No reliable way to check if the map is ready to add sources and layers
return;
}
@@ -105,12 +104,12 @@ export class DistanceMarkers {
// the distance from the start of the selection, and the position, of each trackpoint
const { length, totalDistance, lng, lat } = get(engine.statistics);
const features: GeoJSON.Feature[] = [];
let features: GeoJSON.Feature[] = [];
let currentTargetDistance = 1;
for (let i = 0; i < length; i++) {
if (totalDistance[i] >= getConvertedDistanceToKilometers(currentTargetDistance)) {
const distance = currentTargetDistance.toFixed(0);
const level = levels.find((level) => currentTargetDistance % level === 0) || 1;
let distance = currentTargetDistance.toFixed(0);
let level = levels.find((level) => currentTargetDistance % level === 0) || 1;
features.push({
type: 'Feature',
geometry: {
@@ -7,8 +7,8 @@ import {
Point,
} from 'maplibre-gl';
import { map } from '$lib/components/map/map';
import { waypointPopup } from './gpx-layer-popup';
import { closestPointIndexIn } from '$lib/geo/closest-point';
import { waypointPopup, trackpointPopup } from './gpx-layer-popup';
import { closestPointIndex } from '$lib/geo/closest-point';
import { getElevation, loadSVGIcon } from '$lib/utils';
import { selectedWaypoint } from '$lib/components/toolbar/tools/waypoint/waypoint';
import { MapPin, Square } from 'lucide-static';
@@ -21,10 +21,9 @@ import { currentTool, Tool } from '$lib/components/toolbar/tools';
import { splitAtPoint } from '$lib/components/toolbar/tools/scissors/scissors';
import { mapCursor, MapCursorState } from '$lib/state/map-cursor';
import { ANCHOR_LAYER_KEY } from '$lib/components/map/style';
import { hoveredTrackpoint } from '$lib/state/selection-statistics';
export function getSvgForSymbol(symbol?: string | undefined, layerColor?: string | undefined) {
const symbolSvg = symbol ? symbols[symbol]?.iconSvg : undefined;
let symbolSvg = symbol ? symbols[symbol]?.iconSvg : undefined;
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
${
layerColor
@@ -64,13 +63,12 @@ export class GPXLayer {
currentWaypointData: GeoJSON.FeatureCollection | null = null;
draggedWaypointIndex: number | null = null;
draggingStartingPosition: Point = new Point(0, 0);
hoversTrackpoint: boolean = false;
unsubscribe: (() => void)[] = [];
unsubscribe: Function[] = [];
updateBinded: () => void = this.update.bind(this);
layerOnMouseEnterBinded: (e: MapLayerMouseEvent) => void = this.layerOnMouseEnter.bind(this);
layerOnMouseEnterBinded: (e: any) => void = this.layerOnMouseEnter.bind(this);
layerOnMouseLeaveBinded: () => void = this.layerOnMouseLeave.bind(this);
layerOnMouseMoveBinded: (e: MapLayerMouseEvent) => void = this.layerOnMouseMove.bind(this);
layerOnMouseMoveBinded: (e: any) => void = this.layerOnMouseMove.bind(this);
layerOnClickBinded: (e: MapLayerMouseEvent) => void = this.layerOnClick.bind(this);
layerOnContextMenuBinded: (e: MapLayerMouseEvent) => void = this.layerOnContextMenu.bind(this);
waypointLayerOnMouseEnterBinded: (e: MapLayerMouseEvent) => void =
@@ -103,7 +101,7 @@ export class GPXLayer {
this.unsubscribe.push(
engine.selection.subscribe(($selection) => {
this.selectionState = $selection;
const newSelected = hasSelectionWithin($selection, this.fileNode());
let newSelected = hasSelectionWithin($selection, this.fileNode());
if (this.selected || newSelected) {
this.selected = newSelected;
this.update();
@@ -148,7 +146,7 @@ export class GPXLayer {
this.loadIcons();
try {
const source = _map.getSource(this.fileId) as GeoJSONSource | undefined;
let source = _map.getSource(this.fileId) as GeoJSONSource | undefined;
if (source) {
source.setData(this.getGeoJSON());
} else {
@@ -236,7 +234,7 @@ export class GPXLayer {
}
}
const waypointSource = _map.getSource(this.fileId + '-waypoints') as
let waypointSource = _map.getSource(this.fileId + '-waypoints') as
| GeoJSONSource
| undefined;
this.currentWaypointData = this.getWaypointsGeoJSON();
@@ -303,7 +301,7 @@ export class GPXLayer {
['in', ['get', 'waypointIndex'], ['literal', visibleWaypoints]],
{ validate: false }
);
} catch {
} catch (e) {
// No reliable way to check if the map is ready to add sources and layers
return;
}
@@ -388,10 +386,10 @@ export class GPXLayer {
}
}
layerOnMouseEnter(e: MapLayerMouseEvent) {
layerOnMouseEnter(e: any) {
if (
get(currentTool) === Tool.SCISSORS &&
isCovered(this.selectionState, this.segmentNode(e.features![0].properties))
isCovered(this.selectionState, this.segmentNode(e.features[0].properties))
) {
mapCursor.notify(MapCursorState.SCISSORS, true);
} else {
@@ -402,55 +400,25 @@ export class GPXLayer {
layerOnMouseLeave() {
mapCursor.notify(MapCursorState.SCISSORS, false);
mapCursor.notify(MapCursorState.LAYER_HOVER, false);
this.stopHoveringTrackpoint();
}
layerOnMouseMove(e: MapLayerMouseEvent) {
// these tools act on the track under the pointer, and show it themselves
const tool = get(currentTool);
const index =
tool === Tool.ROUTING || tool === Tool.SCISSORS
? undefined
: this.selectedTrackpointAt(e);
if (index === undefined) {
this.stopHoveringTrackpoint();
} else {
this.hoversTrackpoint = true;
hoveredTrackpoint.set(index);
}
}
stopHoveringTrackpoint() {
if (this.hoversTrackpoint) {
this.hoversTrackpoint = false;
hoveredTrackpoint.set(null);
}
}
/**
* The trackpoint of the statistics of the selection that is the closest to the pointer, in the
* first segment under it that is part of the selection.
*/
selectedTrackpointAt(e: MapLayerMouseEvent): number | undefined {
const statistics = get(engine.statistics);
if (!statistics.segments) {
return undefined;
}
const { starts, ids } = statistics.segments;
for (const { properties } of e.features!) {
const segment = ids.indexOf(properties.segmentId);
if (segment >= 0) {
const end = segment + 1 < starts.length ? starts[segment + 1] : statistics.length;
return closestPointIndexIn(
statistics.lng,
statistics.lat,
starts[segment],
end,
e.lngLat
);
async layerOnMouseMove(e: any) {
if (e.originalEvent.shiftKey) {
const { segmentId } = e.features[0].properties;
const lngLat = { lng: e.lngLat.lng, lat: e.lngLat.lat };
const index = closestPointIndex(await engine.segmentCoordinates(segmentId), lngLat);
const trackpoint =
index === undefined
? undefined
: await engine.trackpoint(this.fileId, segmentId, index);
if (trackpoint) {
trackpointPopup?.setItem({
item: trackpoint,
kind: 'trackpoint',
fileId: this.fileId,
});
}
}
return undefined;
}
layerOnClick(e: MapLayerMouseEvent) {
@@ -501,7 +469,7 @@ export class GPXLayer {
}
}
layerOnContextMenu(e: MapLayerMouseEvent) {
layerOnContextMenu(e: any) {
if (e.originalEvent.ctrlKey) {
this.layerOnClick(e);
}
@@ -616,7 +584,7 @@ export class GPXLayer {
this.currentWaypointData!.features[this.draggedWaypointIndex].geometry as GeoJSON.Point
).coordinates = [e.lngLat.lng, e.lngLat.lat];
const waypointSource = get(map)?.getSource(this.fileId + '-waypoints') as
let waypointSource = get(map)?.getSource(this.fileId + '-waypoints') as
| GeoJSONSource
| undefined;
if (waypointSource) {
@@ -730,7 +698,7 @@ export class GPXLayer {
return;
}
const symbols = new Set<string | undefined>();
let symbols = new Set<string | undefined>();
get(this.file).waypoints.features.forEach((feature) => {
symbols.add(getSymbolKey(feature.properties.sym));
});
@@ -1,4 +1,4 @@
import { engine, FileStateCollectionObserver } from '$lib/engine';
import { FileStateCollectionObserver } from '$lib/engine';
import { writable } from 'svelte/store';
import { GPXLayer } from './gpx-layer';
@@ -14,7 +14,6 @@ export class GPXLayerCollection {
if (this._fileStateCollectionObserver) {
return;
}
engine.requestStatistics().set(['segments']);
this._fileStateCollectionObserver = new FileStateCollectionObserver(
(newFiles) => {
newFiles.forEach((fileStore, fileId) => {
@@ -2,7 +2,7 @@ import { currentTool, Tool } from '$lib/components/toolbar/tools';
import type { GeoJSONSource } from 'maplibre-gl';
import { get } from 'svelte/store';
import { map } from '$lib/components/map/map';
import { allHidden } from '$lib/engine/selection-stores';
import { allHidden } from '$lib/engine/all-hidden';
import { ANCHOR_LAYER_KEY } from '$lib/components/map/style';
import { loadSVGIcon } from '$lib/utils';
import { hoveredPoint, slicedStatistics } from '$lib/state/selection-statistics';
@@ -100,7 +100,7 @@ export class StartEndMarkers {
});
}
const source = map_.getSource('start-end-markers') as GeoJSONSource | undefined;
let source = map_.getSource('start-end-markers') as GeoJSONSource | undefined;
if (source) {
source.setData(data);
} else {
@@ -18,7 +18,7 @@
Layers2,
} from '@lucide/svelte';
import { i18n } from '$lib/i18n/i18n.svelte';
import { defaultBasemap, layerGroup, type CustomLayer } from '$lib/data/layers';
import { defaultBasemap, type CustomLayer } from '$lib/data/layers';
import { onMount } from 'svelte';
import { remove } from './utils';
import { settings } from '$lib/state/settings';
@@ -128,16 +128,15 @@
],
};
}
$customLayers[layerId] = layer;
addLayer(layerId);
$customLayers[layerId] = layer;
selectedLayerId = undefined;
setDataFromSelectedLayer();
}
function getLayerId() {
for (let id = 0; ; id++) {
if (!Object.hasOwn($customLayers, `custom-${id}`)) {
if (!$customLayers.hasOwnProperty(`custom-${id}`)) {
return `custom-${id}`;
}
}
@@ -146,7 +145,7 @@
function addLayer(layerId: string) {
if (layerType === 'basemap') {
selectedBasemapTree.update(($tree) => {
if (!Object.hasOwn($tree.basemaps, 'custom')) {
if (!$tree.basemaps.hasOwnProperty('custom')) {
$tree.basemaps['custom'] = {};
}
$tree.basemaps['custom'][layerId] = true;
@@ -162,7 +161,7 @@
}
} else {
selectedOverlayTree.update(($tree) => {
if (!Object.hasOwn($tree.overlays, 'custom')) {
if (!$tree.overlays.hasOwnProperty('custom')) {
$tree.overlays['custom'] = {};
}
$tree.overlays['custom'][layerId] = true;
@@ -170,7 +169,7 @@
});
currentOverlays.update(($overlays) => {
if (!Object.hasOwn($overlays.overlays, 'custom')) {
if (!$overlays.overlays.hasOwnProperty('custom')) {
$overlays.overlays['custom'] = {};
}
$overlays.overlays['custom'][layerId] = true;
@@ -183,8 +182,8 @@
}
}
function tryDeleteLayer<T>(node: Record<string, T>, id: string): Record<string, T> {
if (Object.hasOwn(node, id)) {
function tryDeleteLayer(node: any, id: string): any {
if (node.hasOwnProperty(id)) {
delete node[id];
}
return node;
@@ -256,12 +255,13 @@
onfinalize={(e) => {
customBasemapItems = e.detail.items;
$customBasemapOrder = customBasemapItems.map((item) => item.id);
selectedBasemapTree.update(($tree) => {
layerGroup($tree.basemaps)['custom'] = Object.fromEntries(
customBasemapItems.map((item) => [item.id, true])
);
return $tree;
});
$selectedBasemapTree.basemaps['custom'] = customBasemapItems.reduce(
(acc, item) => {
acc[item.id] = true;
return acc;
},
{}
);
}}
>
{#each customBasemapItems as item (item.id)}
@@ -315,12 +315,13 @@
onfinalize={(e) => {
customOverlayItems = e.detail.items;
$customOverlayOrder = customOverlayItems.map((item) => item.id);
selectedOverlayTree.update(($tree) => {
layerGroup($tree.overlays)['custom'] = Object.fromEntries(
customOverlayItems.map((item) => [item.id, true])
);
return $tree;
});
$selectedOverlayTree.overlays['custom'] = customOverlayItems.reduce(
(acc, item) => {
acc[item.id] = true;
return acc;
},
{}
);
}}
>
{#each customOverlayItems as item (item.id)}
@@ -364,7 +365,7 @@
<Label for="name">{i18n._('menu.metadata.name')}</Label>
<Input bind:value={name} id="name" class="h-8" />
<Label for="url">{i18n._('layers.custom_layers.urls')}</Label>
{#each tileUrls as _, i (i)}
{#each tileUrls as url, i}
<div class="flex flex-row gap-2">
<Input
bind:value={tileUrls[i]}
@@ -17,6 +17,7 @@
} from '$lib/data/layers';
import { getLayers, isSelected, toggle } from '$lib/components/map/layer-control/utils';
import { i18n } from '$lib/i18n/i18n.svelte';
import { map } from '$lib/components/map/map';
import CustomLayers from './CustomLayers.svelte';
import { settings } from '$lib/state/settings';
import { untrack } from 'svelte';
@@ -44,7 +45,7 @@
function setOpacityFromSelection() {
if (selectedOverlay) {
if (Object.hasOwn($opacities, selectedOverlay)) {
if ($opacities.hasOwnProperty(selectedOverlay)) {
overlayOpacity = $opacities[selectedOverlay];
} else {
overlayOpacity = 1;
@@ -168,7 +169,7 @@
{#if isSelected($selectedOverlayTree, selectedOverlay)}
{#if $isLayerFromExtension(selectedOverlay)}
{$getLayerName(selectedOverlay)}
{:else if Object.hasOwn($customLayers, selectedOverlay)}
{:else if $customLayers.hasOwnProperty(selectedOverlay)}
{$customLayers[selectedOverlay].name}
{:else}
{i18n._(`layers.label.${selectedOverlay}`)}
@@ -177,7 +178,7 @@
{/if}
</Select.Trigger>
<Select.Content class="h-fit max-h-[40dvh] overflow-y-auto">
{#each Object.keys(overlays) as id (id)}
{#each Object.keys(overlays) as id}
{#if isSelected($selectedOverlayTree, id)}
<Select.Item value={id}>
{#if $isLayerFromExtension(id)}
@@ -188,7 +189,7 @@
</Select.Item>
{/if}
{/each}
{#each Object.entries($customLayers) as [id, layer] (id)}
{#each Object.entries($customLayers) as [id, layer]}
{#if layer.layerType === 'overlay'}
<Select.Item value={id}>{layer.name}</Select.Item>
{/if}
@@ -208,6 +209,19 @@
disabled={selectedOverlay === undefined}
onValueChange={(value) => {
if (selectedOverlay) {
if (
$map &&
$currentOverlays &&
isSelected($currentOverlays, selectedOverlay)
) {
try {
if ($map.getLayer(selectedOverlay)) {
$map.removeLayer(selectedOverlay);
}
} catch (e) {
// No reliable way to check if the map is ready to remove sources and layers
}
}
$opacities[selectedOverlay] = value;
}
}}
@@ -233,7 +247,7 @@
{i18n._(`layers.label.${$terrainSource}`)}
</Select.Trigger>
<Select.Content class="h-fit max-h-[40dvh] overflow-y-auto">
{#each Object.keys(terrainSources) as id (id)}
{#each Object.keys(terrainSources) as id}
<Select.Item value={id}>
{i18n._(`layers.label.${id}`)}
</Select.Item>
@@ -12,7 +12,6 @@
let {
name,
node,
parent = '',
selected = '',
onselect = () => {},
multiple = false,
@@ -20,34 +19,19 @@
}: {
name: string;
node: LayerTreeType;
parent?: string;
selected?: string;
onselect?: (value: string) => void;
multiple: boolean;
checked?: LayerTreeType;
checked: LayerTreeType;
} = $props();
const { customLayers } = settings;
const { isLayerFromExtension, getLayerName, isExtensionGroup } = extensionAPI;
/** The groups of extensions are right below the overlays, with the name they were given. */
function getGroupLabel(id: string) {
return parent === 'overlays' && $isExtensionGroup(id)
? id
: i18n._(`layers.label.${id}`, id);
}
function getLabel(id: string) {
if (Object.hasOwn($customLayers, id)) {
return $customLayers[id].name;
}
return $isLayerFromExtension(id) ? $getLayerName(id) : i18n._(`layers.label.${id}`);
}
const { isLayerFromExtension, getLayerName } = extensionAPI;
$effect.pre(() => {
if (checked !== undefined) {
Object.keys(node).forEach((id) => {
if (!Object.hasOwn(checked, id)) {
if (!checked.hasOwnProperty(id)) {
if (typeof node[id] == 'boolean') {
checked[id] = false;
} else {
@@ -60,7 +44,7 @@
</script>
<div class="flex flex-col gap-[3px]">
{#each Object.keys(node) as id (id)}
{#each Object.keys(node) as id}
{#if typeof node[id] == 'boolean'}
{#if node[id]}
<div class="flex flex-row items-center gap-2 first:mt-0.5 h-4">
@@ -69,11 +53,9 @@
id="{name}-{id}"
{name}
value={id}
bind:checked={
() => checked[id] === true, (value) => (checked[id] = value)
}
bind:checked={checked[id]}
class="scale-90"
aria-label={getLabel(id)}
aria-label={i18n._(`layers.label.${id}`)}
/>
{:else}
<input
@@ -90,31 +72,30 @@
/>
{/if}
<Label for="{name}-{id}" class="flex flex-row items-center gap-1">
{getLabel(id)}
{#if $customLayers.hasOwnProperty(id)}
{$customLayers[id].name}
{:else if $isLayerFromExtension(id)}
{$getLayerName(id)}
{:else}
{i18n._(`layers.label.${id}`)}
{/if}
</Label>
</div>
{/if}
{:else if anySelectedLayer(node[id])}
<CollapsibleTreeNode {id}>
{#snippet trigger()}
<span>{getGroupLabel(id)}</span>
<span>{i18n._(`layers.label.${id}`, id)}</span>
{/snippet}
{#snippet content()}
<div class="ml-2">
<Self
node={node[id] as LayerTreeType}
parent={id}
node={node[id]}
{name}
{selected}
{onselect}
{multiple}
bind:checked={
() => {
const group = checked[id];
return typeof group === 'object' ? group : undefined;
},
(value) => (checked[id] = value ?? {})
}
bind:checked={checked[id]}
/>
</div>
{/snippet}
@@ -79,16 +79,11 @@
</div>
{/if}
<div class="grid grid-cols-[auto_auto] gap-x-3">
{#each Object.entries(tags) as [key, value] (key)}
{#each Object.entries(tags) as [key, value]}
{#if key !== 'name' && !key.includes('image')}
<span class="font-mono">{key}</span>
{#if key === 'website' || key.startsWith('website:') || key.endsWith(':website') || key === 'contact:facebook' || key === 'contact:instagram' || key === 'contact:twitter'}
<a
href={value}
target="_blank"
rel="external"
class="text-link underline">{value}</a
>
<a href={value} target="_blank" class="text-link underline">{value}</a>
{:else if key === 'wikipedia' || key.startsWith('wikipedia:') || key.endsWith(':wikipedia')}
<a
href="https://wikipedia.org/wiki/{value}"
@@ -5,16 +5,20 @@ import { get } from 'svelte/store';
import { overlays, overlayTree, type LayerTreeType } from '$lib/data/layers';
import { engine } from '$lib/engine';
import { settings } from '$lib/state/settings';
import { map } from '$lib/components/map/map';
import type { StyleSpecification } from 'maplibre-gl';
import { ExtensionAPI, type ExtensionOverlay } from './extension-api';
import { isSelected, prefixStyle } from './utils';
import { ExtensionAPI, type CustomOverlay } from './extension-api';
import { isSelected } from './utils';
const original = { set: engine.setSetting, delete: engine.deleteSetting };
const overlayTreeBefore = JSON.stringify(overlayTree);
const overlayIdsBefore = Object.keys(overlays).sort();
const overlay = (id: string, extensionName = 'My extension'): CustomOverlay => ({
extensionName,
id,
name: `Overlay ${id}`,
tileUrls: [`https://tiles.example.com/${id}/{z}/{x}/{y}.png`],
});
let api: ExtensionAPI;
beforeEach(() => {
@@ -27,335 +31,119 @@ beforeEach(() => {
afterEach(() => {
// the layers are shared by the whole app: leave them as they were
api.setOverlays('Heatmaps', []);
api.setOverlays('Other', []);
api.filterOverlays([]);
for (const extension of ['My extension', 'Other extension']) {
delete (overlayTree.overlays as LayerTreeType)[extension];
}
engine.setSetting = original.set;
engine.deleteSetting = original.delete;
assert.equal(JSON.stringify(overlayTree), overlayTreeBefore);
assert.deepEqual(Object.keys(overlays).sort(), overlayIdsBefore);
});
const rasterStyle = (url = 'https://tiles.example.com/{z}/{x}/{y}.png'): StyleSpecification => ({
version: 8,
sources: { tiles: { type: 'raster', tiles: [url], tileSize: 256 } },
layers: [{ id: 'tiles', type: 'raster', source: 'tiles' }],
});
const v2 = (id: string, extra: Partial<ExtensionOverlay> = {}): ExtensionOverlay => ({
id,
name: `Overlay ${id}`,
style: rasterStyle(),
...extra,
});
const id = (overlayId: string, extension = 'Heatmaps') =>
`extension-${encodeURIComponent(extension)}/${encodeURIComponent(overlayId)}`;
/** The overlays of an extension in a tree, with their state. */
const group = (tree: LayerTreeType | undefined, extension = 'Heatmaps') =>
(tree!.overlays as LayerTreeType)[extension] as LayerTreeType | undefined;
/** What the user does in the layer menu. */
function setShown(overlayId: string, shown: boolean) {
settings.currentOverlays.update((tree) => {
group(tree)![overlayId] = shown;
return tree;
});
}
describe('prefixStyle', () => {
it('prefixes the sources, the layers, and the source of the layers', () => {
const prefixed = prefixStyle('overlay', {
version: 8,
sources: { dem: { type: 'raster-dem', tiles: ['https://dem/{z}/{x}/{y}.png'] } },
layers: [
{ id: 'relief', type: 'color-relief', source: 'dem' },
{ id: 'background', type: 'background' },
],
});
assert.deepEqual(Object.keys(prefixed.sources), ['overlay/dem']);
assert.deepEqual(
prefixed.layers.map((layer) => layer.id),
['overlay/relief', 'overlay/background']
);
assert.equal((prefixed.layers[0] as { source: string }).source, 'overlay/dem');
assert.equal('source' in prefixed.layers[1], false);
});
it('refuses a style whose layers cannot work', () => {
const style = (layers: unknown) =>
({ version: 8, sources: {}, layers }) as StyleSpecification;
assert.throws(() => prefixStyle('o', style(undefined)), /list of layers/);
assert.throws(
() => prefixStyle('o', style([{ id: 'a', type: 'raster', source: 'none' }])),
/unknown source/
);
assert.throws(
() =>
prefixStyle(
'o',
style([
{ id: 'a', type: 'background' },
{ id: 'a', type: 'background' },
])
),
/repeated layer id/
);
});
});
describe('ExtensionAPI', () => {
it('adds the overlays of an extension, in the order of the list, hidden by default', () => {
api.setOverlays('Heatmaps', [v2('b'), v2('a', { name: 'A' }), v2('c', { visible: true })]);
it('adds an overlay as a layer, in the tree of its extension', () => {
api.addOrUpdateOverlay(overlay('one'));
const expected = [id('b'), id('a'), id('c')];
assert.deepEqual(Object.keys(group(overlayTree)!), expected);
assert.deepEqual(Object.keys(group(get(settings.selectedOverlayTree))!), expected);
assert.deepEqual(group(get(settings.currentOverlays)), {
[id('b')]: false,
[id('a')]: false,
[id('c')]: true,
const layer = overlays['extension-one'];
assert.ok(layer && typeof layer === 'object');
const source = (layer as any).sources['extension-one'];
assert.equal(source.type, 'raster');
assert.deepEqual(source.tiles, ['https://tiles.example.com/one/{z}/{x}/{y}.png']);
assert.equal(source.tileSize, 256);
assert.equal(source.maxzoom, 22);
assert.ok((overlayTree.overlays as LayerTreeType)['My extension']);
assert.equal(isSelected(overlayTree, 'extension-one'), true);
assert.equal(isSelected(get(settings.selectedOverlayTree), 'extension-one'), true);
// not shown until the user chooses to
assert.equal(isSelected(get(settings.currentOverlays)!, 'extension-one'), false);
assert.ok(get(api.isLayerFromExtension)('extension-one'));
assert.equal(get(api.getLayerName)('extension-one'), 'Overlay one');
assert.equal(get(api.getLayerName)('other'), '');
});
it('uses big tiles when the urls say so, and the max zoom it is given', () => {
api.addOrUpdateOverlay({
...overlay('big'),
tileUrls: ['https://tiles.example.com/512/{z}/{x}/{y}.png'],
maxZoom: 15,
});
assert.ok(get(api.isLayerFromExtension)(id('a')));
assert.equal(get(api.getLayerName)(id('a')), 'A');
assert.equal(api.version, 2);
const source = (overlays['extension-big'] as any).sources['extension-big'];
assert.equal(source.tileSize, 512);
assert.equal(source.maxzoom, 15);
});
it('uses the style as is, with prefixed ids', () => {
api.setOverlays('Heatmaps', [v2('a')]);
const style = overlays[id('a')] as StyleSpecification;
assert.deepEqual(Object.keys(style.sources), [`${id('a')}/tiles`]);
assert.equal(style.layers[0].id, `${id('a')}/tiles`);
assert.equal((style.layers[0] as { source: string }).source, `${id('a')}/tiles`);
});
it('names its overlays after the extension', () => {
api.setOverlays('My heatmap', [v2('all')]);
assert.ok(isSelected(overlayTree, 'extension-My%20heatmap/all'));
api.setOverlays('My heatmap', []);
});
it('keeps two extensions with the same overlay ids, or similar names, apart', () => {
api.setOverlays('Heatmaps', [v2('a')]);
api.setOverlays('Other', [v2('a')]);
assert.deepEqual(Object.keys(group(overlayTree)!), [id('a')]);
assert.deepEqual(Object.keys(group(overlayTree, 'Other')!), [id('a', 'Other')]);
api.setOverlays('Heatmaps/a', [v2('b')]);
api.setOverlays('Heatmaps', [v2('a'), v2('a/b')]);
assert.notEqual(id('a/b'), id('b', 'Heatmaps/a'));
assert.ok(get(api.isLayerFromExtension)(id('a/b')));
assert.ok(get(api.isLayerFromExtension)(id('b', 'Heatmaps/a')));
api.setOverlays('Other', []);
assert.deepEqual(Object.keys(group(overlayTree)!).length, 2);
api.setOverlays('Heatmaps/a', []);
});
it('knows the groups of the extensions', () => {
api.setOverlays('Heatmaps', [v2('a')]);
assert.equal(get(api.isExtensionGroup)('Heatmaps'), true);
assert.equal(get(api.isExtensionGroup)('france'), false);
api.setOverlays('Heatmaps', []);
assert.equal(get(api.isExtensionGroup)('Heatmaps'), false);
});
it('removes what is not in the list anymore, with its group when it is empty', () => {
api.setOverlays('Heatmaps', [v2('a', { visible: true }), v2('b')]);
api.setOverlays('Heatmaps', [v2('b')]);
assert.ok(!(id('a') in overlays));
assert.equal(get(api.isLayerFromExtension)(id('a')), false);
assert.equal(isSelected(get(settings.currentOverlays)!, id('a')), false);
assert.deepEqual(Object.keys(group(overlayTree)!), [id('b')]);
api.setOverlays('Heatmaps', []);
assert.equal(group(overlayTree), undefined);
assert.equal(group(get(settings.selectedOverlayTree)), undefined);
assert.equal(group(get(settings.currentOverlays)), undefined);
});
it('keeps the state of an overlay unless told otherwise, and the opacity and menu choices', () => {
api.setOverlays('Heatmaps', [v2('a'), v2('b')]);
setShown(id('a'), true);
settings.opacities.update((opacities) => ({ ...opacities, [id('a')]: 0.3 }));
settings.selectedOverlayTree.update((tree) => {
group(tree)![id('b')] = false;
return tree;
});
api.setOverlays('Heatmaps', [v2('b'), v2('a')]);
assert.equal(isSelected(get(settings.currentOverlays)!, id('a')), true);
assert.equal(isSelected(get(settings.selectedOverlayTree), id('b')), false);
assert.equal(get(settings.opacities)[id('a')], 0.3);
assert.deepEqual(Object.keys(group(get(settings.selectedOverlayTree))!), [
id('b'),
id('a'),
]);
api.setOverlays('Heatmaps', [v2('a', { visible: false }), v2('b', { visible: true })]);
assert.equal(isSelected(get(settings.currentOverlays)!, id('a')), false);
// the user took it out of the menu, where it could not be hidden again
assert.equal(isSelected(get(settings.currentOverlays)!, id('b')), false);
});
it('changes nothing when the list is not valid', () => {
api.setOverlays('Heatmaps', [v2('a')]);
const invalid: unknown[] = [
[v2('b'), v2('b')],
[v2('b'), { id: 'c', name: 'C' }],
[v2('b'), { ...v2('c'), style: { version: 8, sources: {} } }],
'not a list',
];
for (const list of invalid) {
assert.throws(() => api.setOverlays('Heatmaps', list as ExtensionOverlay[]));
}
assert.deepEqual(Object.keys(group(overlayTree)!), [id('a')]);
assert.ok(!(id('b') in overlays));
});
it('refuses the names that cannot be the group of an extension', () => {
for (const name of ['', 'world', 'countries', '__proto__']) {
assert.throws(() => api.setOverlays(name, [v2('a')]));
}
});
it('waits for the settings', () => {
const current = get(settings.currentOverlays);
(settings.currentOverlays as unknown as { _value: { set(v: unknown): void } })._value.set(
undefined
);
assert.throws(() => api.setOverlays('Heatmaps', [v2('a')]), /gpxstudio\.ready/);
settings.currentOverlays.set(current!);
});
it('tells the extension about the actions of the user only', () => {
const calls: Record<string, boolean>[] = [];
const stop = api.onVisibilityChange('Heatmaps', (visible) => calls.push(visible));
const others: unknown[] = [];
api.onVisibilityChange('Other', (visible) => others.push(visible));
api.setOverlays('Other', [v2('x')]);
api.setOverlays('Heatmaps', [v2('a'), v2('b', { visible: true })]);
api.setOverlays('Heatmaps', [v2('a', { visible: true }), v2('b', { visible: false })]);
assert.deepEqual(calls, []);
setShown(id('b'), true);
assert.deepEqual(calls, [{ a: true, b: true }]);
// nothing changed
setShown(id('b'), true);
assert.equal(calls.length, 1);
assert.deepEqual(others, []);
stop();
setShown(id('b'), false);
assert.equal(calls.length, 1);
});
it('tells the extension when the overlays are all hidden from the menu', () => {
const calls: Record<string, boolean>[] = [];
api.onVisibilityChange('Heatmaps', (visible) => calls.push(visible));
api.setOverlays('Heatmaps', [v2('a', { visible: true })]);
settings.currentOverlays.set({ overlays: {} });
assert.deepEqual(calls, [{ a: false }]);
});
it('survives a callback that throws, or that sets the overlays', () => {
const error = console.error;
console.error = () => {};
const calls: unknown[] = [];
api.onVisibilityChange('Heatmaps', () => {
throw new Error('from the extension');
});
api.onVisibilityChange('Heatmaps', (visible) => {
calls.push(visible);
api.setOverlays('Heatmaps', [v2('a', { visible: visible.a })]);
});
api.setOverlays('Heatmaps', [v2('a')]);
setShown(id('a'), true);
console.error = error;
assert.deepEqual(calls, [{ a: true }]);
});
it('forgets the state of the overlays with the next session', () => {
const saved = () => ({
currentOverlays: JSON.stringify(get(settings.currentOverlays)),
previousOverlays: JSON.stringify(get(settings.previousOverlays)),
selectedOverlayTree: JSON.stringify(get(settings.selectedOverlayTree)),
opacities: JSON.stringify(get(settings.opacities)),
});
// what was saved, not the default trees, which are the ones that are allowed
settings.connect(saved());
api.setOverlays('Heatmaps', [v2('a', { visible: true }), v2('b')]);
settings.selectedOverlayTree.update((tree) => {
group(tree)![id('b')] = false;
return tree;
});
settings.opacities.update((opacities) => ({ ...opacities, [id('a')]: 0.3 }));
const stored = saved();
assert.ok(stored.currentOverlays.includes(id('a')));
settings.connect(stored);
for (const tree of [
get(settings.currentOverlays),
get(settings.previousOverlays),
get(settings.selectedOverlayTree),
it('refuses an overlay that is not complete', () => {
for (const bad of [
{ ...overlay('a'), extensionName: '' },
{ ...overlay('a'), id: '' },
{ ...overlay('a'), name: '' },
{ ...overlay('a'), tileUrls: [] },
{ ...overlay('a'), tileUrls: undefined as unknown as string[] },
]) {
assert.ok(!JSON.stringify(tree).includes('extension-'));
assert.throws(() => api.addOrUpdateOverlay(bad), /must have/);
}
assert.equal(get(settings.opacities)[id('a')], 0.3);
// an extension that is still there starts again, as the source of what it remembers
const next = new ExtensionAPI();
next.setOverlays('Heatmaps', [v2('a'), v2('b', { visible: true })]);
assert.equal(isSelected(get(settings.currentOverlays)!, id('a')), false);
assert.equal(isSelected(get(settings.currentOverlays)!, id('b')), true);
assert.equal(isSelected(get(settings.selectedOverlayTree), id('b')), true);
next.setOverlays('Heatmaps', []);
assert.ok(!('extension-a' in overlays));
});
it('leaves a style URL for the map to fetch', () => {
const fetchBefore = globalThis.fetch;
globalThis.fetch = (() => assert.fail('fetched')) as typeof fetch;
try {
const url = 'https://example.com/style.json';
api.setOverlays('Heatmaps', [v2('a', { style: url })]);
assert.equal(overlays[id('a')], url);
} finally {
globalThis.fetch = fetchBefore;
}
it('updates an overlay that is added again, keeping it shown', () => {
api.addOrUpdateOverlay(overlay('one'));
settings.currentOverlays.update((current) => {
(current.overlays as LayerTreeType)['My extension'] = { 'extension-one': true };
return current;
});
api.addOrUpdateOverlay({
...overlay('one'),
name: 'Renamed',
tileUrls: ['https://other/{z}'],
});
assert.equal(get(api.getLayerName)('extension-one'), 'Renamed');
assert.deepEqual((overlays['extension-one'] as any).sources['extension-one'].tiles, [
'https://other/{z}',
]);
assert.equal(isSelected(get(settings.currentOverlays)!, 'extension-one'), true);
});
it('removes a style that changes from the map, layers first, but not one that stays', () => {
const calls: string[] = [];
const prefix = id('a');
const fakeMap = {
getStyle: () => ({
sources: { [`${prefix}/tiles`]: {}, [`${prefix}2/tiles`]: {}, core: {} },
layers: [{ id: `${prefix}/tiles` }, { id: `${prefix}2/tiles` }, { id: 'core' }],
}),
removeLayer: (layer: string) => calls.push(`layer ${layer}`),
removeSource: (source: string) => calls.push(`source ${source}`),
};
const store = (map as unknown as { _mapStore: { set(value: unknown): void } })._mapStore;
store.set(fakeMap);
try {
api.setOverlays('Heatmaps', [v2('a', { visible: true })]);
api.setOverlays('Heatmaps', [v2('a', { name: 'Renamed' })]);
assert.deepEqual(calls, []);
it('removes the overlays that are not in the list anymore, everywhere', () => {
api.addOrUpdateOverlay(overlay('one'));
api.addOrUpdateOverlay(overlay('two', 'Other extension'));
api.setOverlays('Heatmaps', [v2('a', { style: rasterStyle('https://other/{z}') })]);
assert.deepEqual(calls, [`layer ${prefix}/tiles`, `source ${prefix}/tiles`]);
calls.length = 0;
api.setOverlays('Heatmaps', [v2('a', { style: 'https://example.com/style.json' })]);
assert.equal(calls.length, 2);
calls.length = 0;
api.setOverlays('Heatmaps', []);
assert.equal(calls.length, 2);
} finally {
store.set(null);
api.filterOverlays(['two']);
assert.ok(!('extension-one' in overlays));
assert.ok('extension-two' in overlays);
assert.equal(get(api.isLayerFromExtension)('extension-one'), false);
assert.equal(get(api.isLayerFromExtension)('extension-two'), true);
for (const tree of [
overlayTree,
get(settings.selectedOverlayTree),
get(settings.currentOverlays)!,
]) {
assert.equal(isSelected(tree, 'extension-one'), false);
}
assert.equal(isSelected(overlayTree, 'extension-two'), true);
api.filterOverlays([]);
assert.ok(!('extension-two' in overlays));
});
it('puts the overlays in the order it is given', () => {
api.addOrUpdateOverlay(overlay('one'));
api.addOrUpdateOverlay(overlay('two'));
api.addOrUpdateOverlay(overlay('three'));
api.updateOverlaysOrder(['three', 'one', 'two']);
const extension = (get(settings.selectedOverlayTree).overlays as LayerTreeType)[
'My extension'
];
assert.deepEqual(Object.keys(extension as LayerTreeType), [
'extension-three',
'extension-one',
'extension-two',
]);
// ids it does not know are ignored
api.updateOverlaysOrder(['unknown', 'two']);
assert.equal(Object.keys(extension as LayerTreeType).at(-1), 'extension-two');
});
});
@@ -1,87 +1,35 @@
import { settings } from '$lib/state/settings';
import type { StyleSpecification } from 'maplibre-gl';
import { derived, get, writable, type Writable } from 'svelte/store';
import { isSelected, prefixStyle, removeAll } from './utils';
import { layerGroup, overlays, overlayTree, type LayerTreeType } from '$lib/data/layers';
import { isSelected, remove, removeAll } from './utils';
import { overlays, overlayTree } from '$lib/data/layers';
import { browser } from '$app/environment';
import { map } from '$lib/components/map/map';
const { currentOverlays, previousOverlays, selectedOverlayTree } = settings;
/** An overlay given by an extension. */
export type ExtensionOverlay = {
/** Unique within the extension. Keep it stable: the opacity and menu choices are tied to it. */
export type CustomOverlay = {
extensionName: string;
id: string;
name: string;
/**
* The sources and layers of the overlay, or the URL of a style JSON (which must allow
* cross-origin requests). It is used as is, with MapLibre's defaults: a `raster` source has
* tiles of 512 pixels unless its `tileSize` says otherwise. Layers can only use the sources of
* this style, and the rest of a style (`sprite`, `glyphs`, `terrain`...) is ignored.
*/
style: StyleSpecification | string;
/** Applied if given, otherwise the current state is kept (hidden for a new overlay). */
visible?: boolean;
tileUrls: string[];
maxZoom?: number;
};
/** What the API knows of an overlay. */
type RegisteredOverlay = {
extensionName: string;
name: string;
/** The style given by the extension, to tell when it changes. */
signature: string;
};
type VisibilityCallback = (visible: Record<string, boolean>) => void;
/** The groups of the overlay tree that an extension cannot put its overlays in. */
const reservedGroups = new Set(['__proto__', ...Object.keys(layerGroup(overlayTree.overlays))]);
/** The id of an overlay. It is encoded so that two extensions cannot clash. */
function getExtensionOverlayId(extensionName: string, id: string): string {
return `extension-${encodeURIComponent(extensionName)}/${encodeURIComponent(id)}`;
}
/**
* Sets the overlays of an extension in a tree, in order, dropping its other entries. An extension
* that has nothing left has no group anymore.
*/
function setGroup(tree: LayerTreeType, extensionName: string, entries: Record<string, boolean>) {
const groups = layerGroup(tree.overlays);
if (Object.keys(entries).length > 0) {
groups[extensionName] = { ...entries };
} else {
delete groups[extensionName];
}
return tree;
}
export class ExtensionAPI {
/** The version of the API. */
readonly version = 2;
/**
* Resolved once overlays can be set. `gpxstudio:extension-api-ready` is sent on `window` at that
* moment.
*/
ready!: Promise<void>;
private _overlays: Writable<Map<string, RegisteredOverlay>> = writable(new Map());
/** What each extension knows of the visibility of its overlays, by its own overlay ids. */
private _visibility: Map<string, Record<string, boolean>> = new Map();
private _visibilityCallbacks: Map<string, Set<VisibilityCallback>> = new Map();
private _watchingVisibility = false;
private _overlays: Writable<Map<string, CustomOverlay>> = writable(new Map());
init() {
if (browser && !Object.hasOwn(window, 'gpxstudio')) {
this.ready = this.whenLoaded();
this.ready.then(() => window.dispatchEvent(new Event('gpxstudio:extension-api-ready')));
if (browser && !window.hasOwnProperty('gpxstudio')) {
Object.defineProperty(window, 'gpxstudio', {
value: this,
});
addEventListener('beforeunload', () => {
this.destroy();
});
}
}
private whenLoaded(): Promise<void> {
ensureLoaded(): Promise<void> {
let unsubscribe: () => void;
const promise = new Promise<void>((resolve) => {
map.onLoad(() => {
@@ -98,160 +46,133 @@ export class ExtensionAPI {
return promise;
}
/**
* Replaces the overlays of an extension: the order of the list is the order in the layer menu,
* and the overlays that are not in the list are removed. The opacity and the choices of the
* layer menu are kept for the ones that stay. Throws, changing nothing, if the list is invalid;
* a style URL is only fetched when the overlay is shown, and a failure is then only logged.
*/
setOverlays(extensionName: string, newOverlays: ExtensionOverlay[]) {
if (typeof extensionName !== 'string' || !extensionName) {
throw new Error('An extension must have a name.');
}
if (reservedGroups.has(extensionName)) {
throw new Error(`The extension name ${extensionName} is reserved.`);
}
if (!Array.isArray(newOverlays)) {
throw new Error('The overlays must be a list.');
}
const current = get(currentOverlays);
if (!current) {
throw new Error('Overlays cannot be set yet: wait for `gpxstudio.ready`.');
}
const previous = this.getOverlaysOf(extensionName);
const next = new Map<string, RegisteredOverlay>();
const styles = new Map<string, StyleSpecification | string>();
for (const overlay of newOverlays) {
if (!overlay?.id || !overlay.name || !overlay.style) {
throw new Error('Overlay must have an id, a name and a style.');
}
const id = getExtensionOverlayId(extensionName, overlay.id);
if (next.has(id)) {
throw new Error(`Overlay ${overlay.id} is in the list twice.`);
}
const signature = JSON.stringify(overlay.style);
// the ids of the style at a URL are prefixed when the map fetches it
styles.set(
id,
typeof overlay.style === 'string'
? overlay.style
: prefixStyle(id, JSON.parse(signature))
addOrUpdateOverlay(overlay: CustomOverlay) {
if (
!overlay.extensionName ||
!overlay.id ||
!overlay.name ||
!overlay.tileUrls ||
overlay.tileUrls.length === 0
) {
throw new Error(
'Overlay must have an extensionName, id, name, and at least one tile URL.'
);
next.set(id, { extensionName, name: overlay.name, signature });
}
overlay.id = this.getOverlayId(overlay.id);
// Nothing can fail from here. The map does not replace a source that it already has, so
// what has changed has to be removed first; it is then added back with the new style.
const removedIds: string[] = [];
previous.forEach((overlay, id) => {
if (next.get(id)?.signature !== overlay.signature) {
this.removeFromMap(id);
}
if (!next.has(id)) {
removedIds.push(id);
delete overlays[id];
}
});
styles.forEach((style, id) => {
overlays[id] = style;
});
this._overlays.update(($overlays) => {
removedIds.forEach((id) => $overlays.delete(id));
next.forEach((overlay, id) => $overlays.set(id, overlay));
$overlays.set(overlay.id, overlay);
return $overlays;
});
const available: Record<string, boolean> = {};
const selected: Record<string, boolean> = {};
const shown: Record<string, boolean> = {};
const visibility: Record<string, boolean> = {};
const selectedGroup = layerGroup(get(selectedOverlayTree).overlays)[extensionName];
newOverlays.forEach((overlay) => {
const id = getExtensionOverlayId(extensionName, overlay.id);
available[id] = true;
// an overlay that the user took out of the layer menu could not be hidden again
selected[id] =
typeof selectedGroup !== 'object' ||
!Object.hasOwn(selectedGroup, id) ||
selectedGroup[id] === true;
shown[id] = selected[id] && Boolean(overlay.visible ?? isSelected(current, id));
visibility[overlay.id] = shown[id];
overlays[overlay.id] = {
version: 8,
sources: {
[overlay.id]: {
type: 'raster',
tiles: overlay.tileUrls,
tileSize: overlay.tileUrls.some((url) => url.includes('512')) ? 512 : 256,
maxzoom: overlay.maxZoom ?? 22,
},
},
layers: [
{
id: overlay.id,
type: 'raster',
source: overlay.id,
},
],
};
if (!overlayTree.overlays.hasOwnProperty(overlay.extensionName)) {
overlayTree.overlays[overlay.extensionName] = {};
}
overlayTree.overlays[overlay.extensionName][overlay.id] = true;
selectedOverlayTree.update((selected) => {
if (!selected.overlays.hasOwnProperty(overlay.extensionName)) {
selected.overlays[overlay.extensionName] = {};
}
selected.overlays[overlay.extensionName][overlay.id] = true;
return selected;
});
setGroup(overlayTree, extensionName, available);
selectedOverlayTree.update((tree) => setGroup(tree, extensionName, selected));
previousOverlays.update((tree) => removeAll(tree, removedIds));
// this is not an action of the user: there must be nothing to tell the extension about
this._visibility.set(extensionName, visibility);
currentOverlays.update((tree) => setGroup(tree, extensionName, shown));
}
/**
* Calls `callback` with the visibility of all the overlays of the extension, by id, when the
* user shows or hides one of them (not when `setOverlays` does). Returns how to stop.
*/
onVisibilityChange(extensionName: string, callback: VisibilityCallback): () => void {
const callbacks = this._visibilityCallbacks.get(extensionName) ?? new Set();
this._visibilityCallbacks.set(extensionName, callbacks);
callbacks.add(callback);
if (!this._watchingVisibility) {
this._watchingVisibility = true;
currentOverlays.subscribe(() => this.notifyVisibility());
}
return () => {
callbacks.delete(callback);
};
}
private notifyVisibility() {
const current = get(currentOverlays);
if (!current) return;
this._visibilityCallbacks.forEach((callbacks, extensionName) => {
const known = this._visibility.get(extensionName);
if (!known) return;
const visibility = Object.fromEntries(
Object.keys(known).map((id) => [
id,
isSelected(current, getExtensionOverlayId(extensionName, id)),
])
);
if (Object.keys(known).every((id) => known[id] === visibility[id])) return;
this._visibility.set(extensionName, visibility);
callbacks.forEach((callback) => {
try {
callback({ ...visibility });
} catch (e) {
// an extension must not break the updates of the store for the others
console.error(e);
let show = false;
if (current && isSelected(current, overlay.id)) {
show = true;
try {
get(map)?.removeLayer(overlay.id);
} catch (e) {
// No reliable way to check if the map is ready to remove sources and layers
}
}
currentOverlays.update((current) => {
if (!current.overlays.hasOwnProperty(overlay.extensionName)) {
current.overlays[overlay.extensionName] = {};
}
current.overlays[overlay.extensionName][overlay.id] = show;
return current;
});
}
filterOverlays(ids: string[]) {
ids = ids.map((id) => this.getOverlayId(id));
const idsToRemove = Array.from(get(this._overlays).keys()).filter(
(id) => !ids.includes(id)
);
currentOverlays.update((current) => {
removeAll(current, idsToRemove);
return current;
});
previousOverlays.update((previous) => {
removeAll(previous, idsToRemove);
return previous;
});
selectedOverlayTree.update((selected) => {
removeAll(selected, idsToRemove);
return selected;
});
Object.keys(overlays).forEach((id) => {
if (idsToRemove.includes(id)) {
delete overlays[id];
}
});
removeAll(overlayTree, idsToRemove);
this._overlays.update(($overlays) => {
$overlays.forEach((_, id) => {
if (idsToRemove.includes(id)) {
$overlays.delete(id);
}
});
return $overlays;
});
}
private getOverlaysOf(extensionName: string): Map<string, RegisteredOverlay> {
return new Map(
Array.from(get(this._overlays)).filter(
([, overlay]) => overlay.extensionName === extensionName
)
);
}
/** Removes the layers and sources of an overlay: their ids start with the one of the overlay. */
private removeFromMap(overlayId: string) {
const map_ = get(map);
if (!map_) return;
try {
const style = map_.getStyle();
style.layers
.filter((layer) => layer.id.startsWith(`${overlayId}/`))
.forEach((layer) => map_.removeLayer(layer.id));
Object.keys(style.sources)
.filter((source) => source.startsWith(`${overlayId}/`))
.forEach((source) => map_.removeSource(source));
} catch {
// No reliable way to check if the map is ready to remove sources and layers
}
updateOverlaysOrder(ids: string[]) {
ids = ids.map((id) => this.getOverlayId(id));
selectedOverlayTree.update((selected) => {
let isSelected: Record<string, boolean> = {};
ids.forEach((id) => {
const overlay = get(this._overlays).get(id);
if (
overlay &&
selected.overlays.hasOwnProperty(overlay.extensionName) &&
selected.overlays[overlay.extensionName].hasOwnProperty(id)
) {
isSelected[id] = selected.overlays[overlay.extensionName][id];
delete selected.overlays[overlay.extensionName][id];
}
});
Object.entries(isSelected).forEach(([id, value]) => {
const overlay = get(this._overlays).get(id)!;
selected.overlays[overlay.extensionName][id] = value;
});
return selected;
});
}
isLayerFromExtension = derived(this._overlays, ($overlays) => {
@@ -262,11 +183,31 @@ export class ExtensionAPI {
return (id: string) => $overlays.get(id)?.name || '';
});
/** Whether a group of the layer trees is an extension, whose name is shown as it was given. */
isExtensionGroup = derived(this._overlays, ($overlays) => {
const names = new Set(Array.from($overlays.values(), (overlay) => overlay.extensionName));
return (id: string) => names.has(id);
});
private getOverlayId(id: string): string {
return `extension-${id}`;
}
private destroy() {
const ids = Array.from(get(this._overlays).keys());
currentOverlays.update((current) => {
ids.forEach((id) => {
remove(current, id);
});
return current;
});
previousOverlays.update((previous) => {
ids.forEach((id) => {
remove(previous, id);
});
return previous;
});
selectedOverlayTree.update((selected) => {
ids.forEach((id) => {
remove(selected, id);
});
return selected;
});
}
}
export const extensionAPI = new ExtensionAPI();
@@ -4,7 +4,7 @@ import { get, writable } from 'svelte/store';
import { overpassQueryData } from '$lib/data/layers';
import { MapPopup } from '$lib/components/map/map-popup';
import { settings } from '$lib/state/settings';
import type { GeoJSONSource, MapLayerMouseEvent, Map as MapLibreMap } from 'maplibre-gl';
import type { GeoJSONSource, Map as MapLibreMap } from 'maplibre-gl';
import { ANCHOR_LAYER_KEY } from '$lib/components/map/style';
import type { MapLayerEventManager } from '$lib/components/map/map-layer-event-manager';
import { loadSVGIcon } from '$lib/utils';
@@ -86,7 +86,7 @@ export class OverpassLayer {
};
try {
const source = this.map.getSource('overpass') as GeoJSONSource | undefined;
let source = this.map.getSource('overpass') as GeoJSONSource | undefined;
if (source) {
source.setData(d);
} else {
@@ -115,7 +115,7 @@ export class OverpassLayer {
this.layerEventManager.on('mouseenter', 'overpass', this.onHoverBinded);
this.layerEventManager.on('click', 'overpass', this.onHoverBinded);
}
} catch {
} catch (e) {
// No reliable way to check if the map is ready to add sources and layers
}
}
@@ -135,28 +135,28 @@ export class OverpassLayer {
if (this.map.getSource('overpass')) {
this.map.removeSource('overpass');
}
} catch {
} catch (e) {
// No reliable way to check if the map is ready to remove sources and layers
}
}
onHover(e: MapLayerMouseEvent) {
onHover(e: any) {
this.popup.setItem({
kind: 'overpass',
item: {
...e.features![0].properties,
sym: overpassQueryData[e.features![0].properties.query].symbol ?? '',
...e.features[0].properties,
sym: overpassQueryData[e.features[0].properties.query].symbol ?? '',
},
});
}
query(bbox: [number, number, number, number]) {
const queries = getCurrentQueries();
let queries = getCurrentQueries();
if (queries.length === 0) {
return;
}
const tileLimits = mercator.xyz(bbox, this.queryZoom);
let tileLimits = mercator.xyz(bbox, this.queryZoom);
for (let x = tileLimits.minX; x <= tileLimits.maxX; x++) {
for (let y = tileLimits.minY; y <= tileLimits.maxY; y++) {
@@ -189,8 +189,8 @@ export class OverpassLayer {
}
this.data.update((updatedData) => {
for (const element of data.elements) {
for (const query of queries) {
for (let element of data.elements) {
for (let query of queries) {
if (belongsToQuery(element, query)) {
updatedData.features.push({
type: 'Feature',
@@ -224,7 +224,7 @@ export class OverpassLayer {
}
loadIcons() {
const currentQueries = getCurrentQueries();
let currentQueries = getCurrentQueries();
currentQueries.forEach((query) => {
loadSVGIcon(
this.map,
@@ -257,7 +257,7 @@ function getQuery(query: string) {
}
function getQueryItem(tags: Record<string, string | string[]>) {
const arrayEntry = Object.entries(tags).find((entry): entry is [string, string[]] =>
let arrayEntry = Object.entries(tags).find((entry): entry is [string, string[]] =>
Array.isArray(entry[1])
);
if (arrayEntry !== undefined) {
@@ -291,12 +291,12 @@ function belongsToQueryItem(element: any, tags: Record<string, string | string[]
}
function getCurrentQueries() {
const currentQueries = get(currentOverpassQueries);
let currentQueries = get(currentOverpassQueries);
if (currentQueries === undefined) {
return [];
}
return Object.entries(getLayers(currentQueries))
.filter(([, selected]) => selected)
.map(([query]) => query);
.filter(([_, selected]) => selected)
.map(([query, _]) => query);
}
@@ -1,16 +1,7 @@
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import type { LayerTreeType } from '$lib/data/layers';
import type { LayerSpecification } from 'maplibre-gl';
import {
anySelectedLayer,
getLayers,
getOpacityPaint,
isSelected,
remove,
removeAll,
toggle,
} from './utils';
import { anySelectedLayer, getLayers, isSelected, remove, removeAll, toggle } from './utils';
// roads: bike (selected), foot
// satellite: esri, ign: fr (selected)
@@ -81,39 +72,3 @@ describe('layer trees', () => {
assert.deepEqual(removeAll(tree(), []), tree());
});
});
describe('getOpacityPaint', () => {
const layer = (type: string, paint?: Record<string, unknown>) =>
({ id: 'layer', type, source: 'source', paint }) as LayerSpecification;
it('uses the opacity properties of each type of layer', () => {
assert.deepEqual(getOpacityPaint(layer('raster'), 0.5), { 'raster-opacity': 0.5 });
assert.deepEqual(getOpacityPaint(layer('color-relief'), 0.5), {
'color-relief-opacity': 0.5,
});
assert.deepEqual(getOpacityPaint(layer('symbol'), 0.5), {
'icon-opacity': 0.5,
'text-opacity': 0.5,
});
assert.deepEqual(getOpacityPaint(layer('circle'), 0.5), {
'circle-opacity': 0.5,
'circle-stroke-opacity': 0.5,
});
assert.deepEqual(getOpacityPaint(layer('hillshade'), 0.5), {
'hillshade-exaggeration': 0.25,
});
});
it('scales the opacity that the layer already has', () => {
assert.deepEqual(getOpacityPaint(layer('line', { 'line-opacity': 0.5 }), 0.5), {
'line-opacity': 0.25,
});
});
it('replaces an expression, unless the opacity is left at 1', () => {
const expression = ['interpolate', ['linear'], ['zoom'], 5, 0, 10, 1];
const paint = { 'fill-opacity': expression };
assert.deepEqual(getOpacityPaint(layer('fill', paint), 0.5), { 'fill-opacity': 0.5 });
assert.deepEqual(getOpacityPaint(layer('fill', paint), 1), { 'fill-opacity': expression });
});
});
@@ -1,89 +1,4 @@
import type { LayerTreeType } from '$lib/data/layers';
import type { LayerSpecification, StyleSpecification } from 'maplibre-gl';
/** Parts of a style that apply to a whole map, not to an overlay. */
const ignoredStyleProperties = ['sprite', 'glyphs', 'terrain', 'sky', 'light', 'projection'];
/** The overlays that were warned about those: a style at a URL is read again and again. */
const warnedOverlays = new Set<string>();
/**
* A copy of the style of an overlay whose sources and layers have ids of their own, so that they
* cannot clash with the ones of gpx.studio or of another overlay.
*/
export function prefixStyle(overlayId: string, style: StyleSpecification): StyleSpecification {
if (typeof style !== 'object' || style === null || !Array.isArray(style.layers)) {
throw new Error(`The style of overlay ${overlayId} must have a list of layers.`);
}
const ignored = ignoredStyleProperties.filter((property) => Object.hasOwn(style, property));
if (ignored.length > 0 && !warnedOverlays.has(overlayId)) {
warnedOverlays.add(overlayId);
console.warn(`Overlay ${overlayId} ignores these style properties: ${ignored.join(', ')}.`);
}
const prefixed = (id: string) => `${overlayId}/${id}`;
const sources = style.sources ?? {};
const layerIds = new Set<string>();
const layers = style.layers.map((layer) => {
if (!layer.id || layerIds.has(layer.id)) {
throw new Error(`Overlay ${overlayId} has a missing or repeated layer id.`);
}
layerIds.add(layer.id);
if ('source' in layer) {
if (!Object.hasOwn(sources, layer.source)) {
throw new Error(
`Layer ${layer.id} of overlay ${overlayId} uses unknown source ${layer.source}.`
);
}
return { ...layer, id: prefixed(layer.id), source: prefixed(layer.source) };
}
return { ...layer, id: prefixed(layer.id) };
}) as LayerSpecification[];
return {
...style,
sources: Object.fromEntries(
Object.entries(sources).map(([id, source]) => [prefixed(id), source])
),
layers,
};
}
/** The paint properties that make a layer transparent, by type of layer. */
const opacityProperties: Partial<Record<LayerSpecification['type'], string[]>> = {
background: ['background-opacity'],
circle: ['circle-opacity', 'circle-stroke-opacity'],
'color-relief': ['color-relief-opacity'],
fill: ['fill-opacity'],
'fill-extrusion': ['fill-extrusion-opacity'],
heatmap: ['heatmap-opacity'],
line: ['line-opacity'],
raster: ['raster-opacity'],
symbol: ['icon-opacity', 'text-opacity'],
};
/**
* The paint properties that give a layer an opacity. The opacity of an overlay applies on top of
* those of its layers, so that they stay different from one another. A value that is computed
* (an expression) cannot always be scaled: the opacity replaces it, unless it is left at 1.
*/
export function getOpacityPaint(
layer: LayerSpecification,
opacity: number
): Record<string, unknown> {
if (layer.type === 'hillshade') {
return { 'hillshade-exaggeration': opacity / 2 };
}
const paint = (layer.paint ?? {}) as Record<string, unknown>;
return Object.fromEntries(
(opacityProperties[layer.type] ?? []).map((property) => {
const value = paint[property];
if (typeof value === 'number') {
return [property, value * opacity];
}
return [property, value !== undefined && opacity === 1 ? value : opacity];
})
);
}
export function anySelectedLayer(node: LayerTreeType) {
return (
@@ -235,7 +235,7 @@ export class MapLayerEventManager {
private _filterLayersIntersectingBounds(layerIds: string[], bounds: LngLatBounds): string[] {
const files = get(engine.files);
const result = layerIds.filter((layerId) => {
let result = layerIds.filter((layerId) => {
if (!this._map.getLayer(layerId)) return false;
const fileId = layerId.replace('-waypoints', '');
if (fileId === layerId) {
+1 -1
View File
@@ -6,7 +6,7 @@ import MapPopupComponent from '$lib/components/map/MapPopup.svelte';
export type PopupItem<T = any> = {
/** Has a position (`lng` and `lat`). */
item: T;
/** What the item is: a `WaypointDetails`, the coordinates of a point or an Overpass element. */
/** What the item is: a `WaypointDetails`, a `TrackpointDetails` or an Overpass element. */
kind: 'waypoint' | 'trackpoint' | 'overpass';
fileId?: string;
hide?: () => void;
+6 -16
View File
@@ -10,11 +10,10 @@ import { settings } from '$lib/state/settings';
import { tick } from 'svelte';
import { ANCHOR_LAYER_KEY, StyleManager } from '$lib/components/map/style';
import { MapLayerEventManager } from '$lib/components/map/map-layer-event-manager';
import { registerOpenSatelliteProtocol } from '$lib/components/map/open-satellite';
const { treeFileView, elevationProfile, bottomPanelSize, rightPanelSize, distanceUnits } = settings;
const fitBoundsOptions: maplibregl.MapOptions['fitBoundsOptions'] = {
let fitBoundsOptions: maplibregl.MapOptions['fitBoundsOptions'] = {
maxZoom: 15,
linear: true,
easing: () => 1,
@@ -42,7 +41,6 @@ export class MapLibreGLMap {
geolocate: boolean
) {
maplibregl.setWorkerUrl(workerUrl);
registerOpenSatelliteProtocol(maptilerKey);
this._maptilerKey = maptilerKey;
this._styleManager = new StyleManager(this._mapStore, this._maptilerKey);
// MapLibre gives Safari more workers, but only recognizes it by its user agent: not
@@ -77,7 +75,7 @@ export class MapLibreGLMap {
})
);
if (geocoder) {
const geocoder = new MaplibreGeocoder(
let geocoder = new MaplibreGeocoder(
{
forwardGeocode: async (config) => {
const results: MaplibreGeocoderFeatureResults = {
@@ -87,26 +85,18 @@ export class MapLibreGLMap {
try {
const request = `https://nominatim.openstreetmap.org/search?format=json&q=${config.query}&limit=5&accept-language=${language}`;
const response = await fetch(request);
const places: {
lat: string;
lon: string;
type: string;
display_name: string;
}[] = await response.json();
results.features = places.map((result) => {
const geojson = await response.json();
results.features = geojson.map((result: any) => {
return {
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [Number(result.lon), Number(result.lat)],
coordinates: [result.lon, result.lat],
},
properties: {},
text: result.display_name,
place_name: result.display_name,
place_type: [result.type],
};
});
} catch {}
} catch (e) {}
return results;
},
},
@@ -1,98 +0,0 @@
// Which imagery each tile of the open satellite basemap is made of, from saved tiles of the
// tileset of the countries.
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { describe, it } from 'node:test';
import { planTile, type CountryTiles } from './open-satellite';
const fixtures = new URL('../../../test/fixtures/satellite-countries/', import.meta.url);
/** The saved tiles, none where there is no file, and the ones that were asked for. */
function savedTiles() {
const asked: string[] = [];
const tiles: CountryTiles = async (z, x, y) => {
asked.push(`${z}/${x}/${y}`);
try {
return new Uint8Array(readFileSync(new URL(`${z}-${x}-${y}.mvt`, fixtures))).buffer;
} catch {
return null;
}
};
return { asked, tiles };
}
function tile(lon: number, lat: number, z: number): [number, number, number] {
const n = 2 ** z;
const sin = Math.sin((lat * Math.PI) / 180);
return [
z,
Math.floor(((lon + 180) / 360) * n),
Math.floor((0.5 - Math.log((1 + sin) / (1 - sin)) / (4 * Math.PI)) * n),
];
}
async function plan([z, x, y]: [number, number, number], tiles: CountryTiles) {
const { parts, fallback } = await planTile(z, x, y, tiles);
return { parts: parts.map((p) => `${p.source.id}:${p.relation}`).sort(), fallback };
}
describe('planTile', () => {
it('takes every tile up to zoom 12 from the imagery of the whole world', async () => {
const { asked, tiles } = savedTiles();
assert.deepEqual(await plan(tile(2.35, 48.85, 12), tiles), { parts: [], fallback: true });
assert.deepEqual(asked, []);
});
it('takes a tile far from every country from the fallback, without asking for countries', async () => {
const { asked, tiles } = savedTiles();
// London, and the Atlantic
assert.deepEqual(await plan(tile(-0.12, 51.5, 14), tiles), { parts: [], fallback: true });
assert.deepEqual(await plan(tile(-30, 40, 13), tiles), { parts: [], fallback: true });
assert.deepEqual(asked, []);
});
it('takes a tile inside a country from its agency alone', async () => {
const { tiles } = savedTiles();
assert.deepEqual(await plan(tile(2.35, 48.85, 15), tiles), {
parts: ['FR:full'],
fallback: false,
});
});
it('puts the countries of a border tile together, over the fallback where none is', async () => {
const { tiles } = savedTiles();
// Basel: France, Switzerland and Germany, which is not in the patchwork
assert.deepEqual(await plan([13, 4268, 2861], tiles), {
parts: ['CH:partial', 'FR:partial'],
fallback: true,
});
// only Germany
assert.deepEqual(await plan([13, 4269, 2860], tiles), { parts: [], fallback: true });
});
it('needs no fallback where the countries cover the tile between them', async () => {
const { tiles } = savedTiles();
// Wattrelos: France and Belgium
assert.deepEqual(await plan([13, 4166, 2750], tiles), {
parts: ['BE:partial', 'FR:partial'],
fallback: false,
});
// Baarle, with its enclaves of Belgium and the Netherlands
assert.deepEqual(await plan([13, 4208, 2726], tiles), {
parts: ['BE:partial', 'NL:partial'],
fallback: false,
});
});
it('asks for a tile of the countries once for all the tiles of imagery inside it', async () => {
const { asked, tiles } = savedTiles();
// around Lausanne, which no other test asks for
const [, x, y] = tile(6.63, 46.52, 12);
for (let dx = 0; dx < 4; dx++) {
for (let dy = 0; dy < 4; dy++) {
await planTile(14, x * 4 + dx, y * 4 + dy, tiles);
}
}
assert.deepEqual(asked, [`12/${x}/${y}`]);
});
});
@@ -1,422 +0,0 @@
import * as maplibregl from 'maplibre-gl';
import { VectorTile } from '@mapbox/vector-tile';
import { PbfReader } from 'pbf';
/**
* A satellite basemap made of the open imagery of national mapping agencies, drawn through a
* custom protocol: each tile is taken from the agency whose country covers it, the tiles on a
* border are put together on a canvas clipped to the border of each country, and only the parts
* no open source covers are taken from the commercial fallback.
*/
export const OPEN_SATELLITE_PROTOCOL = 'opensat';
type TileUrl = (z: number, x: number, y: number) => string;
type ImagerySource = {
/** ISO code of the country, in the tileset of the countries */
id: string;
url: TileUrl;
/** Above it, the tile of this zoom level is scaled up. */
maxzoom: number;
};
const xyz =
(template: string): TileUrl =>
(z, x, y) =>
template.replace('{z}', String(z)).replace('{x}', String(x)).replace('{y}', String(y));
const ignOrthophotos = xyz(
'https://data.geopf.fr/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=ORTHOIMAGERY.ORTHOPHOTOS&STYLE=normal&FORMAT=image/jpeg&TILEMATRIXSET=PM&TILEMATRIX={z}&TILECOL={x}&TILEROW={y}'
);
/**
* Up to zoom 12, IGN's orthophotos cover the whole world with a mosaic of satellite images: all
* tiles come from it there, and the national sources and the commercial fallback only above.
*/
const world: ImagerySource = { id: 'world', url: ignOrthophotos, maxzoom: 12 };
/** In order of priority, the first one covering a point is used. */
const sources: ImagerySource[] = [
{
id: 'CH',
url: xyz(
'https://wmts.geo.admin.ch/1.0.0/ch.swisstopo.swissimage/default/current/3857/{z}/{x}/{y}.jpeg'
),
maxzoom: 20,
},
{
id: 'FR',
url: ignOrthophotos,
maxzoom: 19,
},
{
id: 'ES',
url: xyz(
'https://www.ign.es/wmts/pnoa-ma?layer=OI.OrthoimageCoverage&style=default&tilematrixset=GoogleMapsCompatible&Service=WMTS&Request=GetTile&Version=1.0.0&Format=image/jpeg&TileMatrix={z}&TileCol={x}&TileRow={y}'
),
maxzoom: 19,
},
{
id: 'AT',
url: xyz(
'https://mapsneu.wien.gv.at/basemap/bmaporthofoto30cm/normal/google3857/{z}/{y}/{x}.jpeg'
),
maxzoom: 19,
},
{
id: 'NL',
url: xyz(
'https://service.pdok.nl/hwh/luchtfotorgb/wmts/v1_0/Actueel_orthoHR/EPSG:3857/{z}/{x}/{y}.jpeg'
),
maxzoom: 19,
},
{
id: 'LU',
url: xyz(
'https://wmts1.geoportail.lu/opendata/wmts/ortho_latest/GLOBAL_WEBMERCATOR_4_V3/{z}/{x}/{y}.jpeg'
),
maxzoom: 19,
},
{
id: 'CZ',
url: xyz(
'https://ags.cuzk.gov.cz/arcgis1/rest/services/ORTOFOTO_WM/MapServer/tile/{z}/{y}/{x}'
),
maxzoom: 19,
},
{
id: 'BE',
url: xyz(
'https://wmts.ngi.be/inspire/ortho/1.0.0/orthoimage_coverage/default/3857/latest/{z}/{y}/{x}.png'
),
maxzoom: 19,
},
{
id: 'PL',
url: xyz(
'https://mapy.geoportal.gov.pl/wss/service/PZGIK/ORTO/WMTS/StandardResolution?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=ORTOFOTOMAPA&STYLE=default&FORMAT=image/jpeg&TILEMATRIXSET=EPSG:3857&TILEMATRIX=EPSG:3857:{z}&TILEROW={y}&TILECOL={x}'
),
maxzoom: 19,
},
];
export const openSatelliteAttribution = [
'<a href="https://www.swisstopo.admin.ch/" target="_blank">swisstopo</a>',
'<a href="https://geoservices.ign.fr/" target="_blank">IGN-F/Géoplateforme</a>',
'PNOA © <a href="https://www.ign.es/" target="_blank">IGN España</a>',
'<a href="https://basemap.at/" target="_blank">basemap.at</a>',
'<a href="https://www.pdok.nl/" target="_blank">PDOK</a>',
'<a href="https://geoportail.lu/" target="_blank">geoportail.lu</a>',
'<a href="https://cuzk.gov.cz/" target="_blank">ČÚZK</a>',
'<a href="https://www.ngi.be/" target="_blank">NGI/IGN</a>',
'<a href="https://www.geoportal.gov.pl/" target="_blank">GUGiK</a>',
'<a href="https://www.maptiler.com/copyright/" target="_blank">© MapTiler</a>',
].join(', ');
// Countries, from the tileset of their polygons, built from the borders of OpenStreetMap
const COUNTRIES_URL = xyz('https://tiles.gpx.studio/satellite-countries/{z}/{x}/{y}.mvt');
/** The only zoom level of the tileset. */
const COUNTRIES_ZOOM = 12;
const sourceByCountry = new Map(sources.map((source) => [source.id, source]));
/** The tiles of the countries, from their tileset: null where there is none. */
export type CountryTiles = (z: number, x: number, y: number) => Promise<ArrayBuffer | null>;
async function fetchCountryTile(z: number, x: number, y: number): Promise<ArrayBuffer | null> {
try {
const response = await fetch(COUNTRIES_URL(z, x, y));
if (!response.ok) return null;
const bytes = await response.arrayBuffer();
return bytes.byteLength > 0 ? bytes : null;
} catch {
return null;
}
}
/** A tile of the countries is shared by the 4^(z - 12) tiles of imagery inside it. */
const countryTiles = new Map<string, Promise<ArrayBuffer | null>>();
function getCountryTile(x: number, y: number, tiles: CountryTiles) {
const key = `${x}/${y}`;
let tile = countryTiles.get(key);
if (tile) {
// the last used, at the end of the map
countryTiles.delete(key);
} else {
tile = tiles(COUNTRIES_ZOOM, x, y);
if (countryTiles.size >= 256) countryTiles.delete(countryTiles.keys().next().value!);
}
countryTiles.set(key, tile);
return tile;
}
/** The tiles of zoom `zoom` where there is a country, as y * 2^zoom + x. */
let areas: Promise<{ zoom: number; tiles: Set<number> }> | null = null;
function getAreas() {
areas ??= import('$lib/data/satellite-countries.json').then((module) => ({
zoom: module.default.zoom,
tiles: new Set(module.default.tiles),
}));
return areas;
}
// Geometry, in pixels of the tile of imagery
const TILE_SIZE = 256;
const TILE_AREA = TILE_SIZE * TILE_SIZE;
type Ring = [number, number][];
/** The ring cut to the tile (Sutherland–Hodgman), which keeps its orientation. */
function clipRing(ring: Ring): Ring {
let points = ring;
const edges: [(p: [number, number]) => number, number][] = [
[(p) => p[0], 0],
[(p) => -p[0], -TILE_SIZE],
[(p) => p[1], 0],
[(p) => -p[1], -TILE_SIZE],
];
for (const [value, min] of edges) {
if (points.length === 0) break;
const clipped: Ring = [];
for (let i = 0; i < points.length; i++) {
const current = points[i];
const previous = points[(i + points.length - 1) % points.length];
const inCurrent = value(current) >= min;
const inPrevious = value(previous) >= min;
if (inCurrent !== inPrevious) {
const t = (min - value(previous)) / (value(current) - value(previous));
clipped.push([
previous[0] + t * (current[0] - previous[0]),
previous[1] + t * (current[1] - previous[1]),
]);
}
if (inCurrent) clipped.push(current);
}
points = clipped;
}
return points;
}
/** Positive for an outer ring of a vector tile, negative for a hole. */
function signedArea(ring: Ring) {
let area = 0;
for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
area += ring[j][0] * ring[i][1] - ring[i][0] * ring[j][1];
}
return area / 2;
}
/** The polygons of the countries with imagery in the tile, cut to it, with their area. */
function countriesInTile(
bytes: ArrayBuffer,
z: number,
x: number,
y: number
): { source: ImagerySource; rings: Ring[]; area: number }[] {
const layer = new VectorTile(new PbfReader(bytes)).layers.countries;
if (!layer) return [];
const d = z - COUNTRIES_ZOOM;
const scale = (TILE_SIZE * 2 ** d) / layer.extent;
const offsetX = (x - ((x >> d) << d)) * TILE_SIZE;
const offsetY = (y - ((y >> d) << d)) * TILE_SIZE;
const countries = [];
for (let i = 0; i < layer.length; i++) {
const feature = layer.feature(i);
const source = sourceByCountry.get(String(feature.properties.country));
if (!source) continue;
const rings = feature
.loadGeometry()
.map((ring) =>
clipRing(ring.map((p) => [p.x * scale - offsetX, p.y * scale - offsetY]))
)
.filter((ring) => ring.length >= 3);
const area = rings.reduce((sum, ring) => sum + signedArea(ring), 0);
// less than a pixel: a polygon of the tile of the countries outside this one
if (area >= 1) countries.push({ source, rings, area });
}
return countries;
}
// Imagery
async function fetchBytes(url: string, signal: AbortSignal): Promise<ArrayBuffer | null> {
try {
const response = await fetch(url, { signal });
if (!response.ok) return null;
const contentType = response.headers.get('content-type') ?? '';
if (!contentType.startsWith('image/')) return null;
const bytes = await response.arrayBuffer();
return (await isBlank(bytes)) ? null : bytes;
} catch (e) {
if (signal.aborted) throw e;
return null;
}
}
/**
* Whether the image is all white or transparent: what some agencies give where they have no
* imagery, such as IGN on the French part of Lake Geneva. Such an image is small, the others
* are not even decoded.
*/
async function isBlank(bytes: ArrayBuffer) {
if (bytes.byteLength > 4096) return false;
try {
const image = await createImageBitmap(new Blob([bytes]));
const canvas = new OffscreenCanvas(16, 16);
const context = canvas.getContext('2d')!;
context.drawImage(image, 0, 0, 16, 16);
image.close();
const pixels = context.getImageData(0, 0, 16, 16).data;
for (let i = 0; i < pixels.length; i += 4) {
const transparent = pixels[i + 3] < 8;
const white = pixels[i] >= 250 && pixels[i + 1] >= 250 && pixels[i + 2] >= 250;
if (!transparent && !white) return false;
}
return true;
} catch {
return false;
}
}
/** The image of the tile, or of the part of its ancestor at the max zoom of the source. */
async function fetchImage(
url: TileUrl,
maxzoom: number,
z: number,
x: number,
y: number,
signal: AbortSignal
): Promise<{ image: ImageBitmap; sx: number; sy: number; size: number } | null> {
const d = Math.max(0, z - maxzoom);
const bytes = await fetchBytes(url(z - d, x >> d, y >> d), signal);
if (!bytes) return null;
try {
const image = await createImageBitmap(new Blob([bytes]));
const size = image.width / 2 ** d;
return {
image,
sx: (x - ((x >> d) << d)) * size,
sy: (y - ((y >> d) << d)) * size,
size,
};
} catch {
return null;
}
}
function clipTo(context: OffscreenCanvasRenderingContext2D, rings: Ring[]) {
context.beginPath();
for (const ring of rings) {
ring.forEach(([px, py], i) => (i === 0 ? context.moveTo(px, py) : context.lineTo(px, py)));
context.closePath();
}
context.clip('evenodd');
}
type TilePart = { source: ImagerySource; relation: 'full' | 'partial'; rings: Ring[] };
/**
* The sources of the tile, in drawing order: the one covering the whole tile, or those
* covering part of it, and whether the fallback is needed below them.
*/
export async function planTile(
z: number,
x: number,
y: number,
tiles: CountryTiles = fetchCountryTile
): Promise<{ parts: TilePart[]; fallback: boolean }> {
const none = { parts: [], fallback: true };
if (z <= world.maxzoom) return none;
const { zoom, tiles: withCountries } = await getAreas();
const d = z - zoom;
if (!withCountries.has((y >> d) * 2 ** zoom + (x >> d))) return none;
const bytes = await getCountryTile(x >> (z - COUNTRIES_ZOOM), y >> (z - COUNTRIES_ZOOM), tiles);
if (!bytes) return none;
const countries = countriesInTile(bytes, z, x, y);
// a pixel of margin, for the rounding of the coordinates of the tiles
const whole = countries.find((country) => country.area >= TILE_AREA - TILE_SIZE);
if (whole) {
return { parts: [{ source: whole.source, relation: 'full', rings: [] }], fallback: false };
}
const covered = countries.reduce((sum, country) => sum + country.area, 0);
return {
parts: countries.map(({ source, rings }) => ({ source, relation: 'partial', rings })),
fallback: covered < TILE_AREA - TILE_SIZE,
};
}
export function maptilerSource(maptilerKey: string): ImagerySource {
return {
id: 'fallback',
url: xyz(`https://api.maptiler.com/tiles/satellite-v2/{z}/{x}/{y}.jpg?key=${maptilerKey}`),
maxzoom: 18,
};
}
export async function loadTile(
z: number,
x: number,
y: number,
commercialFallback: ImagerySource,
signal: AbortSignal
): Promise<ArrayBuffer | ImageBitmap> {
const fallback = z <= world.maxzoom ? world : commercialFallback;
const plan = await planTile(z, x, y);
const { parts } = plan;
// a single tile as it is, without drawing it again
const single =
parts.length === 0
? fallback
: parts.length === 1 && !plan.fallback && parts[0].relation === 'full'
? parts[0].source
: null;
if (single && z <= single.maxzoom) {
const bytes = await fetchBytes(single.url(z, x, y), signal);
if (bytes) return bytes;
if (single === fallback) throw new Error(`No imagery for tile ${z}/${x}/${y}`);
}
const images = await Promise.all(
parts.map((p) => fetchImage(p.source.url, p.source.maxzoom, z, x, y, signal))
);
const fallbackImage =
plan.fallback || images.some((image) => image === null)
? await fetchImage(fallback.url, fallback.maxzoom, z, x, y, signal)
: null;
const canvas = new OffscreenCanvas(TILE_SIZE, TILE_SIZE);
const context = canvas.getContext('2d')!;
if (fallbackImage) {
const { image, sx, sy, size } = fallbackImage;
context.drawImage(image, sx, sy, size, size, 0, 0, TILE_SIZE, TILE_SIZE);
image.close();
}
parts.forEach((p, i) => {
const result = images[i];
if (!result) return;
context.save();
if (p.relation === 'partial') clipTo(context, p.rings);
const { image, sx, sy, size } = result;
context.drawImage(image, sx, sy, size, size, 0, 0, TILE_SIZE, TILE_SIZE);
context.restore();
image.close();
});
return canvas.transferToImageBitmap();
}
export function registerOpenSatelliteProtocol(maptilerKey: string) {
const fallback = maptilerSource(maptilerKey);
maplibregl.addProtocol(OPEN_SATELLITE_PROTOCOL, async (params, abortController) => {
const match = params.url.match(/(\d+)\/(\d+)\/(\d+)$/);
if (!match) throw new Error(`Invalid tile URL: ${params.url}`);
const [z, x, y] = match.slice(1).map(Number);
return { data: await loadTile(z, x, y, fallback, abortController.signal) };
});
}
@@ -5,7 +5,7 @@ import {
type MapLayerMouseEvent,
type VectorSourceSpecification,
} from 'maplibre-gl';
import { Viewer, type ViewerBearingEvent } from 'mapillary-js';
import { Viewer, type ViewerBearingEvent } from 'mapillary-js/dist/mapillary.module';
import 'mapillary-js/dist/mapillary.css';
import { mapCursor, MapCursorState } from '$lib/state/map-cursor';
import { ANCHOR_LAYER_KEY } from '$lib/components/map/style';
@@ -89,7 +89,7 @@ export class MapillaryLayer {
this.viewer.on('position', async () => {
if (this.active) {
popupOpen.value = true;
const latLng = await this.viewer.getPosition();
let latLng = await this.viewer.getPosition();
this.marker.setLngLat(latLng).addTo(this.map);
if (!this.map.getBounds()?.contains(latLng)) {
this.map.panTo(latLng);
@@ -1,220 +0,0 @@
// How the map shows the overlays: here, those of extensions that give the URL of their style.
import assert from 'node:assert/strict';
import { afterEach, beforeEach, describe, it } from 'node:test';
import type { Map as MapLibreMap, StyleSpecification } from 'maplibre-gl';
import { writable } from 'svelte/store';
import { overlays, type LayerTreeType } from '$lib/data/layers';
import { engine } from '$lib/engine';
import { settings } from '$lib/state/settings';
import { StyleManager } from './style';
const URL_A = 'https://example.com/a.json';
const URL_B = 'https://example.com/b.json';
const ID = 'extension-Heatmaps/a';
const style = (tiles: string): StyleSpecification => ({
version: 8,
sources: { tiles: { type: 'raster', tiles: [tiles], tileSize: 256 } },
layers: [{ id: 'tiles', type: 'raster', source: 'tiles' }],
});
const original = {
set: engine.setSetting,
delete: engine.deleteSetting,
fetch: globalThis.fetch,
error: console.error,
};
/** A map that only knows of its overlays. */
function fakeMap() {
const sources = new Map<string, { tiles: string[] }>([['empty-source', { tiles: [] }]]);
const layers = new Map<string, { source: string; paint: Record<string, unknown> }>();
return {
sources,
layers,
on: () => {},
setStyle: () => {},
getPitch: () => 0,
getTerrain: () => null,
setTerrain: () => {},
getSource: (id: string) => sources.get(id),
addSource: (id: string, source: { tiles: string[] }) => sources.set(id, source),
getLayer: (id: string) => layers.get(id),
addLayer: (layer: { id: string; source: string; paint: Record<string, unknown> }) =>
layers.set(layer.id, layer),
removeLayer: (id: string) => layers.delete(id),
setPaintProperty: (id: string, name: string, value: unknown) => {
layers.get(id)!.paint[name] = value;
},
};
}
/** Shows the overlay, and gives the manager of the map. */
function setUp(fake: ReturnType<typeof fakeMap>) {
settings.currentOverlays.update((tree) => {
(tree.overlays as LayerTreeType).Heatmaps = { [ID]: true };
return tree;
});
const store = writable<MapLibreMap | null>(null);
const manager = new StyleManager(store, '');
store.set(fake as unknown as MapLibreMap);
return manager;
}
beforeEach(() => {
engine.setSetting = () => {};
engine.deleteSetting = () => {};
settings.connect({});
settings.initialize();
});
afterEach(() => {
delete overlays[ID];
delete overlays.plainUrl;
settings.currentOverlays.update((tree) => {
delete (tree.overlays as LayerTreeType).Heatmaps;
delete (tree.overlays as LayerTreeType).plainUrl;
return tree;
});
engine.setSetting = original.set;
engine.deleteSetting = original.delete;
globalThis.fetch = original.fetch;
console.error = original.error;
});
/** Answers the style requests with the styles of `responses`, by URL. */
function answerWith(responses: Record<string, StyleSpecification>) {
globalThis.fetch = (async (url: string) =>
Object.hasOwn(responses, url)
? new Response(JSON.stringify(responses[url]))
: new Response(JSON.stringify(style('https://basemap/{z}')))) as typeof fetch;
}
describe('StyleManager, with the style URL of an extension', () => {
it('fetches it, and prefixes the ids of its sources and layers', async () => {
answerWith({ [URL_A]: style('https://a/{z}') });
overlays[ID] = URL_A;
const fake = fakeMap();
await setUp(fake).updateOverlays();
assert.deepEqual(fake.sources.get(`${ID}/tiles`)?.tiles, ['https://a/{z}']);
assert.equal(fake.layers.get(`${ID}/tiles`)?.source, `${ID}/tiles`);
assert.ok(!fake.sources.has('tiles'));
});
it('uses the opacity of the overlay', async () => {
answerWith({ [URL_A]: style('https://a/{z}') });
overlays[ID] = URL_A;
settings.opacities.update((opacities) => ({ ...opacities, [ID]: 0.3 }));
const fake = fakeMap();
await setUp(fake).updateOverlays();
assert.equal(fake.layers.get(`${ID}/tiles`)?.paint['raster-opacity'], 0.3);
});
it('removes its layers when it is hidden', async () => {
answerWith({ [URL_A]: style('https://a/{z}') });
overlays[ID] = URL_A;
const fake = fakeMap();
const manager = setUp(fake);
await manager.updateOverlays();
assert.ok(fake.layers.has(`${ID}/tiles`));
settings.currentOverlays.update((tree) => {
(tree.overlays as LayerTreeType).Heatmaps = { [ID]: false };
return tree;
});
await manager.updateOverlays();
assert.ok(!fake.layers.has(`${ID}/tiles`));
});
it('does not fetch it while the overlay is hidden', async () => {
const urls: string[] = [];
answerWith({});
const answer = globalThis.fetch;
globalThis.fetch = ((url: string) => {
urls.push(url);
return answer(url);
}) as typeof fetch;
overlays[ID] = URL_A;
settings.currentOverlays.update((tree) => {
(tree.overlays as LayerTreeType).Heatmaps = { [ID]: false };
return tree;
});
const store = writable<MapLibreMap | null>(null);
const manager = new StyleManager(store, '');
store.set(fakeMap() as unknown as MapLibreMap);
await manager.updateOverlays();
assert.ok(!urls.includes(URL_A));
});
it('ignores a style that was replaced or removed while it was fetched', async () => {
for (const next of [URL_B, undefined]) {
let respond: (response: Response) => void = () => {};
const answers: Record<string, StyleSpecification> = {
[URL_B]: style('https://b/{z}'),
};
answerWith(answers);
const answer = globalThis.fetch;
globalThis.fetch = ((url: string) =>
url === URL_A
? new Promise((resolve) => (respond = resolve))
: answer(url)) as typeof fetch;
overlays[ID] = URL_A;
const fake = fakeMap();
const manager = setUp(fake);
const pending = manager.updateOverlays();
await new Promise((resolve) => setTimeout(resolve));
if (next) {
overlays[ID] = next;
} else {
delete overlays[ID];
}
respond(new Response(JSON.stringify(style('https://a/{z}'))));
await pending;
assert.ok(!fake.sources.has(`${ID}/tiles`));
await manager.updateOverlays();
assert.deepEqual(
fake.sources.get(`${ID}/tiles`)?.tiles,
next ? ['https://b/{z}'] : undefined
);
}
});
it('logs a style that cannot be used, which leaves the others alone', async () => {
const logged: unknown[] = [];
console.error = (...args) => logged.push(args);
for (const answer of [
new Response('', { status: 404 }),
new Response(JSON.stringify({ version: 8, sources: {} })),
]) {
answerWith({});
const basemap = globalThis.fetch;
globalThis.fetch = ((url: string) =>
url === URL_A ? Promise.resolve(answer.clone()) : basemap(url)) as typeof fetch;
overlays[ID] = URL_A;
const fake = fakeMap();
logged.length = 0;
await setUp(fake).updateOverlays();
assert.ok(logged.length > 0);
assert.equal(fake.layers.size, 0);
}
});
it('does not prefix the style URL of anything else', async () => {
answerWith({ [URL_A]: style('https://a/{z}') });
overlays.plainUrl = URL_A;
settings.currentOverlays.update((tree) => {
(tree.overlays as LayerTreeType).plainUrl = { plainUrl: true };
return tree;
});
const fake = fakeMap();
const store = writable<MapLibreMap | null>(null);
const manager = new StyleManager(store, '');
store.set(fake as unknown as MapLibreMap);
await manager.updateOverlays();
assert.ok(fake.sources.has('tiles'));
assert.ok(fake.layers.has('tiles'));
});
});
+31 -51
View File
@@ -14,7 +14,7 @@ import {
overlays,
terrainSources,
} from '$lib/data/layers';
import { getLayers, getOpacityPaint, prefixStyle } from '$lib/components/map/layer-control/utils';
import { getLayers } from '$lib/components/map/layer-control/utils';
import { i18n } from '$lib/i18n/i18n.svelte';
const { currentBasemap, currentOverlays, customLayers, opacities, terrainSource, distanceUnits } =
@@ -87,7 +87,7 @@ export class StyleManager {
updateBasemap() {
const map_ = get(this._map);
if (!map_) return;
const basemap = get(currentBasemap);
let basemap = get(currentBasemap);
this.buildStyle(basemap).then((style) => {
if (get(currentBasemap) === basemap) map_.setStyle(style);
});
@@ -125,7 +125,7 @@ export class StyleManager {
}
}
} catch (e) {
console.error(e instanceof Error ? e.message : e);
console.error(e.message);
}
this.merge(style, basemapStyle);
style.sky ??= sky;
@@ -147,69 +147,60 @@ export class StyleManager {
const custom = get(customLayers);
const overlayOpacities = get(opacities);
try {
// an overlay on the map can be gone from the tree, which has been replaced as a whole
const layers = getLayers(get(currentOverlays) ?? {});
this._pastOverlays.forEach((id) => (layers[id] ??= false));
for (const overlay in layers) {
const overlayInfo = custom[overlay]?.value ?? overlays[overlay];
if (!overlayInfo) {
// removed, together with what it had on the map
this._pastOverlays.delete(overlay);
} else if (!layers[overlay]) {
for (let overlay in layers) {
if (!layers[overlay]) {
if (this._pastOverlays.has(overlay)) {
const overlayInfo = custom[overlay]?.value ?? overlays[overlay];
try {
const overlayStyle = await this.getOverlayStyle(overlay, overlayInfo);
for (const layer of overlayStyle.layers ?? []) {
const overlayStyle = await this.get(overlayInfo);
for (let layer of overlayStyle.layers ?? []) {
if (map_.getLayer(layer.id)) {
map_.removeLayer(layer.id);
}
}
} catch {
} catch (e) {
// Should not happen
}
this._pastOverlays.delete(overlay);
}
} else {
const overlayInfo = custom[overlay]?.value ?? overlays[overlay];
try {
const overlayStyle = await this.getOverlayStyle(overlay, overlayInfo);
// replaced or removed while it was fetched: its new style has its own turn
if (!custom[overlay] && overlays[overlay] !== overlayInfo) continue;
const overlayStyle = await this.get(overlayInfo);
const opacity = overlayOpacities[overlay];
for (const sourceId in overlayStyle.sources) {
for (let sourceId in overlayStyle.sources) {
if (!map_.getSource(sourceId)) {
map_.addSource(sourceId, overlayStyle.sources[sourceId]);
}
}
for (const layer of overlayStyle.layers ?? []) {
const paint =
opacity === undefined ? {} : getOpacityPaint(layer, opacity);
if (map_.getLayer(layer.id)) {
for (const property in paint) {
map_.setPaintProperty(
layer.id,
property as never,
paint[property] as never
);
for (let layer of overlayStyle.layers ?? []) {
if (!map_.getLayer(layer.id)) {
if (opacity !== undefined) {
if (layer.type === 'raster') {
if (!layer.paint) {
layer.paint = {};
}
layer.paint['raster-opacity'] = opacity;
} else if (layer.type === 'hillshade') {
if (!layer.paint) {
layer.paint = {};
}
layer.paint['hillshade-exaggeration'] = opacity / 2;
}
}
} else {
map_.addLayer(
{
...layer,
paint: { ...layer.paint, ...paint },
} as LayerSpecification,
ANCHOR_LAYER_KEY.overlays
);
map_.addLayer(layer, ANCHOR_LAYER_KEY.overlays);
}
}
this._pastOverlays.add(overlay);
} catch (e) {
console.error(e instanceof Error ? e.message : e);
console.error(e.message);
}
}
}
} catch {}
} catch (e) {}
}
updateTerrain() {
@@ -230,20 +221,9 @@ export class StyleManager {
}
}
/** The style of an overlay. The ids of one from an extension's URL still have to be prefixed. */
private async getOverlayStyle(
overlay: string,
styleInfo: StyleSpecification | string
): Promise<StyleSpecification> {
const style = await this.get(styleInfo);
return typeof styleInfo === 'string' && overlay.startsWith('extension-')
? prefixStyle(overlay, style)
: style;
}
async get(styleInfo: StyleSpecification | string): Promise<StyleSpecification> {
if (typeof styleInfo === 'string') {
const styleUrl = styleInfo as string;
let styleUrl = styleInfo as string;
const response = await fetch(styleUrl, { cache: 'force-cache' });
if (!response.ok) {
throw new Error(`HTTP error fetching style "${styleInfo}": ${response.status}`);
@@ -258,7 +238,7 @@ export class StyleManager {
merge(style: StyleSpecification, other: StyleSpecification) {
style.sources = { ...style.sources, ...other.sources };
const units = get(distanceUnits);
for (const layer of other.layers ?? []) {
for (let layer of other.layers ?? []) {
if ('source' in layer) {
if (layer.source == 'contours_m' && units === 'imperial') continue;
if (layer.source == 'contours_ft' && units !== 'imperial') continue;
@@ -16,7 +16,7 @@
import { getURLForLanguage } from '$lib/utils';
import { Trash2 } from '@lucide/svelte';
import { map } from '$lib/components/map/map';
import type { GeoJSONSource, LngLat, MapMouseEvent, MapTouchEvent } from 'maplibre-gl';
import type { GeoJSONSource, LngLat } from 'maplibre-gl';
import { engine } from '$lib/engine';
import { mapCursor, MapCursorState } from '$lib/state/map-cursor';
import { ANCHOR_LAYER_KEY } from '$lib/components/map/style';
@@ -81,18 +81,18 @@
});
let mousedown = false;
function onMouseDown(e: MapMouseEvent | MapTouchEvent) {
function onMouseDown(e: any) {
mousedown = true;
rectangleCoordinates = [e.lngLat, e.lngLat];
}
function onMouseMove(e: MapMouseEvent | MapTouchEvent) {
function onMouseMove(e: any) {
if (mousedown) {
rectangleCoordinates[1] = e.lngLat;
}
}
function onMouseUp() {
function onMouseUp(e: any) {
mousedown = false;
}
@@ -218,7 +218,6 @@
</span>
{:else}
<TimePicker
id="speed"
bind:value={speed}
showHours={false}
disabled={!canUpdate}
@@ -244,7 +243,6 @@
{i18n._('toolbar.time.total_time')}
</Label>
<TimePicker
id="duration"
bind:value={movingTime}
disabled={!canUpdate}
onChange={() => {
@@ -1,5 +1,5 @@
<script lang="ts">
import type { MapMouseEvent, Popup } from 'maplibre-gl';
import type { Popup } from 'maplibre-gl';
import * as Select from '$lib/components/ui/select';
import { Switch } from '$lib/components/ui/switch';
import { Label } from '$lib/components/ui/label/index.js';
@@ -58,7 +58,7 @@
// the tool works on files, routes, tracks and segments, not on waypoints
let validSelection = $derived(coversSegments($selection));
function createFileWithPoint(e: MapMouseEvent) {
function createFileWithPoint(e: any) {
if ($selection.type === 'empty') {
// the engine selects the new file, which starts with the trackpoint: one undo step
engine.newFile(newFileName(), { lng: e.lngLat.lng, lat: e.lngLat.lat });
@@ -130,7 +130,7 @@
{i18n._(`toolbar.routing.activities.${$routingProfile}`)}
</Select.Trigger>
<Select.Content>
{#each Object.keys(routingProfiles) as profile (profile)}
{#each Object.keys(routingProfiles) as profile}
<Select.Item value={profile}
>{i18n._(
`toolbar.routing.activities.${profile}`
@@ -74,7 +74,7 @@ export class RoutingControls {
listenedFileIds: string[] = [];
popup: Popup;
popupElement: HTMLElement;
unsubscribes: (() => void)[] = [];
unsubscribes: Function[] = [];
updateBinded: () => void = this.update.bind(this);
appendAnchorBinded: (e: MapMouseEvent) => void = this.appendAnchor.bind(this);
@@ -270,7 +270,7 @@ export class RoutingControls {
layerEventManager.on('mousedown', LAYER_ID, this.onMouseDownBinded);
layerEventManager.on('touchstart', LAYER_ID, this.onTouchStartBinded);
}
} catch {
} catch (e) {
// No reliable way to check if the map is ready to add sources and layers
}
}
@@ -303,7 +303,7 @@ export class RoutingControls {
if (map_?.getSource(LAYER_ID)) {
map_?.removeSource(LAYER_ID);
}
} catch {
} catch (e) {
// No reliable way to check if the map is ready to remove sources and layers
}
@@ -556,9 +556,8 @@ export class RoutingControls {
let response;
try {
response = await route(targets);
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
toast.error(i18n._(message, message));
} catch (e: any) {
toast.error(i18n._(e.message, e.message));
return false;
}
@@ -633,11 +632,6 @@ export class RoutingControls {
const anchor = this.anchors[e.features![0].properties.anchorIndex];
if (!anchor) {
// The temporary anchor on the line is not one of the anchors (nor is a feature
// still rendered from before they were rebuilt), a click on it adds it
if (e.type === 'click') {
this.addIntermediateAnchor(e);
}
return;
}
if (e.originalEvent.shiftKey) {
@@ -808,7 +802,7 @@ export class RoutingControls {
this.moveAnchorFeature(this.anchorWithId(this.anchors.length)!, position);
}
temporaryAnchorCloseToOtherAnchor(e: MapMouseEvent) {
temporaryAnchorCloseToOtherAnchor(e: any) {
const map_ = get(map);
if (!map_) {
return false;
@@ -137,7 +137,7 @@ async function getGraphHopperRoute(
graphHopperProfile: string,
privateRoads: boolean
): Promise<RoutedPoints> {
const response = await fetch('https://graphhopper.gpx.studio/route', {
let response = await fetch('https://graphhopper.gpx.studio/route', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
@@ -222,9 +222,9 @@ async function getBRouterRoute(
points: Coordinates[],
brouterProfile: string
): Promise<RoutedPoints> {
const url = `https://brouter.de/brouter?lonlats=${points.map((point) => `${point.lng.toFixed(8)},${point.lat.toFixed(8)}`).join('|')}&profile=${brouterProfile}&format=geojson&alternativeidx=0`;
let url = `https://brouter.de/brouter?lonlats=${points.map((point) => `${point.lng.toFixed(8)},${point.lat.toFixed(8)}`).join('|')}&profile=${brouterProfile}&format=geojson&alternativeidx=0`;
const response = await fetch(url);
let response = await fetch(url);
if (!response.ok) {
throw brouterError(await response.text());
@@ -289,10 +289,11 @@ export function parseBRouterRoute(geojson: any): RoutedPoints {
/** The tags of a way, `key=value` separated by spaces, with the `:` of the keys as `_`. */
export function getTags(message: string): { [key: string]: string } {
const fields = message.split(' ');
const tags: { [key: string]: string } = {};
let tags: { [key: string]: string } = {};
for (let i = 0; i < fields.length; i++) {
const [key, value] = fields[i].split('=');
tags[key.replace(/:/g, '_')] = value;
let [key, value] = fields[i].split('=');
key = key.replace(/:/g, '_');
tags[key] = value;
}
return tags;
}
@@ -131,7 +131,7 @@
{i18n._('gpx.' + $splitAs)}
</Select.Trigger>
<Select.Content>
{#each splitTypes as splitType (splitType)}
{#each splitTypes as splitType}
<Select.Item value={splitType}>{i18n._('gpx.' + splitType)}</Select.Item>
{/each}
</Select.Content>
Loaded 100 of 490 files, more files were not shown because too many files have changed in this diff. Show more