102 Commits
Author SHA1 Message Date
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
604 changed files with 33071 additions and 17933 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 -594
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]]
@@ -1469,11 +1430,7 @@ dependencies = [
"tauri",
"tauri-build",
"tauri-plugin-dialog",
"tauri-plugin-opener",
"tauri-plugin-process",
"tauri-plugin-single-instance",
"tauri-plugin-updater",
"trash",
"uuid",
]
@@ -1672,21 +1629,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 +1648,9 @@ dependencies = [
"percent-encoding",
"pin-project-lite",
"socket2",
"system-configuration",
"tokio",
"tower-service",
"tracing",
"windows-registry",
]
[[package]]
@@ -1930,25 +1870,6 @@ version = "2.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"
[[package]]
name = "is-docker"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "928bae27f42bc99b60d9ac7334e3a21d10ad8f1835a4e12ec3ec0464765ed1b3"
dependencies = [
"once_cell",
]
[[package]]
name = "is-wsl"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "173609498df190136aa7dea1a91db051746d339e18476eed5ca40521f02d7aa5"
dependencies = [
"is-docker",
"once_cell",
]
[[package]]
name = "itoa"
version = "1.0.18"
@@ -2048,36 +1969,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 +2193,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 +2282,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 +2508,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"
@@ -2716,23 +2577,6 @@ version = "11.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e"
[[package]]
name = "open"
version = "5.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa576c76302b7b808eecc68061e67336c47833ef9d22caa74dda10fa9675eebc"
dependencies = [
"dunce",
"is-wsl",
"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 +2593,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 +3017,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 +3061,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 +3089,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 +3104,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 +3161,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 +3393,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 +3514,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 +3577,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 +3598,7 @@ checksum = "f37f381f4e048e6cdf038b5705f8cf14ad108279d46eb968140a7b291aba9400"
dependencies = [
"bitflags 2.13.2",
"block2",
"core-foundation 0.10.1",
"core-foundation",
"core-graphics",
"crossbeam-channel",
"dbus",
@@ -3945,7 +3608,7 @@ dependencies = [
"gdkwayland-sys",
"gdkx11-sys",
"gtk",
"jni 0.21.1",
"jni",
"libc",
"log",
"ndk",
@@ -3978,17 +3641,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 +3664,7 @@ dependencies = [
"gtk",
"heck 0.5.0",
"http",
"jni 0.21.1",
"jni",
"libc",
"log",
"mime",
@@ -4166,38 +3818,6 @@ dependencies = [
"url",
]
[[package]]
name = "tauri-plugin-opener"
version = "2.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "53810be1b4fed22bb6ac3f4cab5a2b80d9391d1af436bda145607532bc0bb219"
dependencies = [
"dunce",
"glob",
"objc2-app-kit",
"objc2-foundation",
"open",
"schemars 0.8.22",
"serde",
"serde_json",
"tauri",
"tauri-plugin",
"thiserror 2.0.21",
"url",
"windows",
"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 +3834,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 +3844,7 @@ dependencies = [
"dpi",
"gtk",
"http",
"jni 0.21.1",
"jni",
"objc2",
"objc2-ui-kit",
"objc2-web-kit",
@@ -4281,7 +3867,7 @@ checksum = "7f9e7e0c9f80a5130773cfabb6df4dc924518fb1b2c923726966804634b57d22"
dependencies = [
"gtk",
"http",
"jni 0.21.1",
"jni",
"log",
"objc2",
"objc2-app-kit",
@@ -4470,16 +4056,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"
@@ -4665,24 +4241,6 @@ dependencies = [
"once_cell",
]
[[package]]
name = "trash"
version = "5.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be89b3fe156965d29ac4f8522f3a640c655affdd9f21cb4f36857f0c92c00317"
dependencies = [
"chrono",
"libc",
"log",
"objc2",
"objc2-foundation",
"once_cell",
"percent-encoding",
"scopeguard",
"urlencoding",
"windows",
]
[[package]]
name = "tray-icon"
version = "0.25.1"
@@ -4711,12 +4269,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 +4304,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"
@@ -4771,12 +4317,6 @@ dependencies = [
"serde_derive",
]
[[package]]
name = "urlencoding"
version = "2.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da"
[[package]]
name = "urlpattern"
version = "0.6.0"
@@ -5057,15 +4597,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 +4761,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 +4788,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 +4821,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 +4831,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 +4862,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 +4874,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 +4886,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 +4904,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 +4916,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 +4928,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 +4940,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 +5004,7 @@ dependencies = [
"gtk",
"http",
"javascriptcore-rs",
"jni 0.21.1",
"jni",
"libc",
"ndk",
"objc2",
@@ -5604,16 +5051,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 +5165,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 +5198,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>
+8 -51
View File
@@ -49,7 +49,7 @@ pub fn select_elements<H: History>(
}
/// Selects all the elements of the same kind as the selected ones, in the same place: all the
/// files, the routes or the tracks of the file, the segments of the track, the waypoints of the file. All the
/// files, the tracks of the file, the segments of the track, the waypoints of the file. All the
/// files when nothing is selected.
pub fn select_all<H: History>(engine: &mut Engine<H>) -> Outcome {
execute(engine, Action::SelectAll)
@@ -62,19 +62,6 @@ pub fn arrow_select<H: History>(engine: &mut Engine<H>, down: bool, add: bool) -
execute(engine, Action::ArrowSelect { down, add })
}
pub fn select_routes<H: History>(
engine: &mut Engine<H>,
file_id: Uuid,
route_ids: &[Uuid],
mode: engine::SelectMode,
) -> Outcome {
let selection = engine::Selection::Route {
file_id: engine::FileId(file_id),
rte_ids: route_ids.iter().copied().map(engine::RouteId).collect(),
};
select_elements(engine, selection, mode)
}
pub fn select_tracks<H: History>(
engine: &mut Engine<H>,
file_id: Uuid,
@@ -148,30 +135,21 @@ pub fn redo<H: History>(engine: &mut Engine<H>) -> Outcome {
// Files
/// Creates a file and selects it. With `route`, it starts with a route. With `lng` and `lat`, it
/// starts with a segment that holds that trackpoint (at `ele`, 0 by default): the one of its route
/// with `route`, of a track otherwise.
/// Creates a file and selects it. With `lng` and `lat`, it starts with a track and a segment that
/// hold that trackpoint (at `ele`, 0 by default).
pub fn new_file<H: History>(
engine: &mut Engine<H>,
name: &str,
lng: Option<f64>,
lat: Option<f64>,
ele: Option<f64>,
route: bool,
) -> Outcome {
let trackpoint = lng.zip(lat).map(|(lng, lat)| engine::NewTrackpoint {
lng,
lat,
ele: ele.unwrap_or_default(),
});
edit(
engine,
Command::New(engine::New {
name,
trackpoint,
route,
}),
)
edit(engine, Command::New(engine::New { name, trackpoint }))
}
/// Loads files as a single command (one undo step). The files are in `data`, one after the other,
@@ -205,8 +183,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. 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)],
@@ -254,18 +232,6 @@ pub fn reorder<H: History>(engine: &mut Engine<H>, file_ids_: &[Uuid], index: us
)
}
/// Names a file in all its states, as if it had always been called so (not undoable): for a file
/// that is written to a file of another name, whose name it takes.
pub fn rename_file<H: History>(engine: &mut Engine<H>, file_id: Uuid, name: &str) -> Outcome {
execute(
engine,
Action::Rename {
file_id: engine::FileId(file_id),
name: name.to_owned(),
},
)
}
/// Puts the selected elements in the clipboard. Nothing happens when nothing is selected.
pub fn copy<H: History>(engine: &mut Engine<H>) -> Outcome {
execute(engine, Action::Copy)
@@ -326,15 +292,6 @@ pub fn style<H: History>(
)
}
/// Converts the selected routes to tracks, or the selected tracks or segments to routes.
pub fn convert<H: History>(engine: &mut Engine<H>) -> Outcome {
edit(engine, Command::Convert(engine::Convert))
}
pub fn new_route<H: History>(engine: &mut Engine<H>) -> Outcome {
edit(engine, Command::NewRoute(engine::NewRoute))
}
pub fn new_track<H: History>(engine: &mut Engine<H>) -> Outcome {
edit(engine, Command::NewTrack(engine::NewTrack))
}
@@ -606,7 +563,7 @@ pub fn route<H: History>(
at_revision(engine, revision, |engine| {
edit(
engine,
Command::Reroute(engine::Reroute {
Command::Route(engine::Route {
start,
end,
lng,
@@ -649,7 +606,7 @@ pub fn change_loop_start<H: History>(engine: &mut Engine<H>, revision: u32, inde
})
}
/// Cuts the file, the route, the track or the segment (see `SplitType`) of the trackpoint `at` of the
/// Cuts the file, the track or the segment (see `SplitType`) of the trackpoint `at` of the
/// selection in two, there: the trackpoint ends the first part and starts the second one. A file that
/// is cut is kept (and its two parts are new files) if the history needs it, see
/// [`History::KEEPS_ORIGINALS`].
+32 -101
View File
@@ -68,11 +68,6 @@ impl Outcome {
Self::new(&engine::Outcome::default(), None)
}
/// The ids of the files that the call added.
pub fn added(&self) -> &[String] {
&self.added
}
/// Whether the call did nothing and says why.
pub fn has_error(&self) -> bool {
self.error.is_some()
@@ -131,10 +126,6 @@ pub enum Selection {
File {
file_ids: Vec<Uuid>,
},
Route {
file_id: Uuid,
route_ids: Vec<Uuid>,
},
Track {
file_id: Uuid,
track_ids: Vec<Uuid>,
@@ -161,10 +152,6 @@ impl From<&engine::Selection> for Selection {
S::File { file_ids } => Self::File {
file_ids: file_ids.iter().map(|id| id.0).collect(),
},
S::Route { file_id, rte_ids } => Self::Route {
file_id: file_id.0,
route_ids: rte_ids.iter().map(|id| id.0).collect(),
},
S::Track { file_id, trk_ids } => Self::Track {
file_id: file_id.0,
track_ids: trk_ids.iter().map(|id| id.0).collect(),
@@ -195,10 +182,6 @@ impl From<Selection> for engine::Selection {
Selection::File { file_ids } => S::File {
file_ids: file_ids.into_iter().map(FileId).collect(),
},
Selection::Route { file_id, route_ids } => S::Route {
file_id: FileId(file_id),
rte_ids: route_ids.into_iter().map(engine::RouteId).collect(),
},
Selection::Track { file_id, track_ids } => S::Track {
file_id: FileId(file_id),
trk_ids: track_ids.into_iter().map(engine::TrackId).collect(),
@@ -241,10 +224,6 @@ pub enum MoveTarget {
Files {
index: f64,
},
Routes {
file_id: Uuid,
index: f64,
},
Tracks {
file_id: Uuid,
index: f64,
@@ -266,10 +245,6 @@ impl From<MoveTarget> for engine::MoveTarget {
let index = |index: f64| index.max(0.0) as usize;
match target {
MoveTarget::Files { index: i } => T::Files { index: index(i) },
MoveTarget::Routes { file_id, index: i } => T::Routes {
file_id: FileId(file_id),
index: index(i),
},
MoveTarget::Tracks { file_id, index: i } => T::Tracks {
file_id: FileId(file_id),
index: index(i),
@@ -306,9 +281,6 @@ impl Clipboard {
engine::ClipboardIds::Files(ids) => {
("files", strings(ids.into_iter().map(|id| id.0).collect()))
}
engine::ClipboardIds::Routes(ids) => {
("routes", strings(ids.into_iter().map(|id| id.0).collect()))
}
engine::ClipboardIds::Tracks(ids) => {
("tracks", strings(ids.into_iter().map(|id| id.0).collect()))
}
@@ -338,15 +310,14 @@ pub struct FileStructure {
name: String,
#[serde(skip_serializing_if = "Option::is_none")]
desc: Option<String>,
routes: Vec<RouteNode>,
tracks: Vec<TrackNode>,
waypoints: Vec<WaypointNode>,
waypoints_rev: String,
}
/// The name, description and style of a route or a track.
#[derive(Serialize)]
struct PathInfo {
struct TrackNode {
id: String,
#[serde(skip_serializing_if = "Option::is_none")]
name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
@@ -357,33 +328,6 @@ struct PathInfo {
opacity: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
width: Option<f64>,
}
impl From<&engine::PathInfo> for PathInfo {
fn from(info: &engine::PathInfo) -> Self {
Self {
name: info.name.clone(),
desc: info.desc.clone(),
color: info.color.clone(),
opacity: info.opacity,
width: info.width,
}
}
}
#[derive(Serialize)]
struct RouteNode {
id: String,
#[serde(flatten)]
info: PathInfo,
segment: SegmentNode,
}
#[derive(Serialize)]
struct TrackNode {
id: String,
#[serde(flatten)]
info: PathInfo,
segments: Vec<SegmentNode>,
}
@@ -394,16 +338,6 @@ struct SegmentNode {
length: f64,
}
impl From<&engine::SegmentNode> for SegmentNode {
fn from(seg: &engine::SegmentNode) -> Self {
Self {
id: seg.id.0.to_string(),
rev: seg.rev_id.0.to_string(),
length: seg.len as f64,
}
}
}
#[derive(Serialize)]
struct WaypointNode {
id: String,
@@ -419,22 +353,25 @@ impl FileStructure {
id: file.id.0.to_string(),
name: file.name.clone(),
desc: file.desc.clone(),
routes: file
.routes
.iter()
.map(|rte| RouteNode {
id: rte.id.0.to_string(),
info: (&rte.info).into(),
segment: (&rte.segment).into(),
})
.collect(),
tracks: file
.tracks
.iter()
.map(|trk| TrackNode {
id: trk.id.0.to_string(),
info: (&trk.info).into(),
segments: trk.segments.iter().map(Into::into).collect(),
name: trk.name.clone(),
desc: trk.desc.clone(),
color: trk.color.clone(),
opacity: trk.opacity,
width: trk.width,
segments: trk
.segments
.iter()
.map(|seg| SegmentNode {
id: seg.id.0.to_string(),
rev: seg.rev_id.0.to_string(),
length: seg.len as f64,
})
.collect(),
})
.collect(),
waypoints: file
@@ -560,30 +497,24 @@ impl WaypointDetails {
}
}
/// A trackpoint of the selection: what the statistics buffers do not hold for each trackpoint.
/// Absent fields are unknown.
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SelectionPoint {
/// Slope (%) at the trackpoint.
pub struct TrackpointDetails {
lng: f64,
lat: f64,
ele: f64,
#[serde(skip_serializing_if = "Option::is_none")]
pub slope: Option<f64>,
/// ms since the epoch.
#[serde(skip_serializing_if = "Option::is_none")]
pub time: Option<f64>,
/// Slope (%) and length (km) of the smoothed elevation segment of the trackpoint.
#[serde(skip_serializing_if = "Option::is_none")]
pub slope_segment_slope: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub slope_segment_distance: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub surface: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub highway: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub sac_scale: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub mtb_scale: Option<String>,
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),
}
}
}
// Routing
+21 -44
View File
@@ -63,8 +63,22 @@ 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.
/// trackpoints to keep, and with `as_route` that the segments are written as routes (`rte`)
/// instead of tracks: the anchors are the route points, and the trackpoints between them the
/// points of their path.
pub fn export_file<H: History>(
engine: &Engine<H>,
file_id: Uuid,
@@ -139,6 +153,9 @@ buffers!(
total_distance,
elevation_gain,
elevation_loss,
slope,
slope_segment_slope,
slope_segment_distance,
lng,
lat,
ele
@@ -158,49 +175,9 @@ macro_rules! optional_buffers {
optional_buffers!(moving_distance: f64, speed: f64, hr: f64, cad: f64, atemp: f64, power: f64);
optional_buffers!(total_time: i64, moving_time: i64);
// The smoothed elevation segments of the selection, over which the slope is averaged, as
// intervals of trackpoints: `slope_segment_starts` holds the index of the first trackpoint of each
// segment, and `slope_segment_slopes` its slope (%). Their length is in `selection_point`.
pub fn slope_segment_starts<H: History>(engine: &Engine<H>) -> &[u32] {
&engine.statistics().slope_segments.starts
}
pub fn slope_segment_slopes<H: History>(engine: &Engine<H>) -> &[f64] {
&engine.statistics().slope_segments.slopes
}
/// What the buffers do not hold for each trackpoint of the selection, for the one at `index`
/// (numbered as in the buffers), `None` if there is none: for example the one that is hovered on
/// the elevation profile.
pub fn selection_point<H: History>(engine: &Engine<H>, index: usize) -> Option<SelectionPoint> {
let stats = engine.statistics();
if index >= stats.len() {
return None;
}
let categories = engine.categories();
let name = |intervals: &engine::Intervals, categories: &engine::Categories| {
let value = intervals.value_at(index);
let code = value.checked_sub(1)?;
categories.name(code).map(str::to_owned)
};
let segment = stats.slope_segments.at(index);
let finite = |value: f64| value.is_finite().then_some(value);
Some(SelectionPoint {
slope: finite(stats.slope[index]),
time: stats
.time
.as_ref()
.map(|time| time[index])
.filter(|time| *time != engine::NO_TIME)
.map(|time| time as f64),
slope_segment_slope: segment.and_then(|i| finite(stats.slope_segments.slopes[i])),
slope_segment_distance: segment.and_then(|i| finite(stats.slope_segments.distances[i])),
surface: name(&stats.surface, &categories.surface),
highway: name(&stats.highway, &categories.highway),
sac_scale: name(&stats.sac_scale, &categories.sac_scale),
mtb_scale: name(&stats.mtb_scale, &categories.mtb_scale),
})
/// Timestamps in milliseconds since the epoch (`NO_TIME` when missing), see `optional_buffers`.
pub fn timestamps<H: History>(engine: &Engine<H>) -> Option<&[i64]> {
engine.statistics().time.as_deref()
}
// Surface, highway, SAC scale and MTB scale of the trackpoints, as intervals of trackpoints that
+1 -14
View File
@@ -6,7 +6,7 @@
//! between them are kept: every part comes after the previous one in the new order, as late as the
//! original one came after the part that followed it.
use crate::{Route, Track, TrackSegment, Trackpoint};
use crate::{Track, TrackSegment, Trackpoint};
/// The time of the first trackpoint of a segment.
pub fn start_time(segment: &TrackSegment) -> Option<i64> {
@@ -94,19 +94,6 @@ pub fn reverse_segments(
}
}
/// Reverses the routes of a file, and their trackpoints, like the segments of a track (see
/// [`reverse_segments`]).
pub fn reverse_routes(routes: &mut [Route], original_next: Option<i64>, new_previous: Option<i64>) {
routes.reverse();
let (mut next, mut previous) = (original_next, new_previous);
for route in routes.iter_mut() {
let original_start = start_time(&route.seg);
reverse_segment(&mut route.seg, next, previous);
next = original_start;
previous = end_time(&route.seg);
}
}
/// Reverses the tracks of a file, and their segments and trackpoints.
pub fn reverse_tracks(tracks: &mut [Track], original_next: Option<i64>, new_previous: Option<i64>) {
tracks.reverse();
+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());
+1 -51
View File
@@ -1,4 +1,4 @@
use crate::{Link, Route, Track, TrackSegment, Waypoints};
use crate::{Link, Track, Waypoints};
use super::common::uuid_id;
@@ -8,9 +8,6 @@ uuid_id!(FileId);
pub struct File {
pub id: FileId,
pub info: FileInfo,
/// The routes come before the tracks, as in GPX: everything that goes through the segments
/// of a file (statistics, the elevation profile...) takes the ones of the routes first.
pub rte: Vec<Route>,
pub trk: Vec<Track>,
pub wpt: Waypoints,
}
@@ -32,50 +29,3 @@ pub struct Author {
/// The author has a single link, unlike the other elements.
pub link: Option<Link>,
}
/// Where a segment is in its file: the one of a route, or one of a track.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SegmentIndex {
Route(usize),
Track { trk: usize, seg: usize },
}
impl File {
/// The segments of the routes, then the ones of the tracks.
pub fn segments(&self) -> impl Iterator<Item = &TrackSegment> {
self.rte
.iter()
.map(|rte| &rte.seg)
.chain(self.trk.iter().flat_map(|trk| &trk.trkseg))
}
/// Where the segments are, in the order of [`File::segments`].
pub fn segment_indices(&self) -> impl Iterator<Item = SegmentIndex> + '_ {
(0..self.rte.len())
.map(SegmentIndex::Route)
.chain(self.trk.iter().enumerate().flat_map(|(trk, track)| {
(0..track.trkseg.len()).map(move |seg| SegmentIndex::Track { trk, seg })
}))
}
/// The segment at `index`. Panics if there is none.
pub fn segment(&self, index: SegmentIndex) -> &TrackSegment {
match index {
SegmentIndex::Route(rte) => &self.rte[rte].seg,
SegmentIndex::Track { trk, seg } => &self.trk[trk].trkseg[seg],
}
}
/// The segment at `index`. Panics if there is none.
pub fn segment_mut(&mut self, index: SegmentIndex) -> &mut TrackSegment {
match index {
SegmentIndex::Route(rte) => &mut self.rte[rte].seg,
SegmentIndex::Track { trk, seg } => &mut self.trk[trk].trkseg[seg],
}
}
/// Whether the file has no route nor track.
pub fn has_no_path(&self) -> bool {
self.rte.is_empty() && self.trk.is_empty()
}
}
-2
View File
@@ -3,7 +3,6 @@ mod chunk;
mod chunked;
mod common;
mod file;
mod route;
mod segment;
mod track;
mod trackpoint;
@@ -15,7 +14,6 @@ pub use chunk::*;
pub use chunked::*;
pub use common::*;
pub use file::*;
pub use route::*;
pub use segment::*;
pub use track::*;
pub use trackpoint::*;
-15
View File
@@ -1,15 +0,0 @@
use crate::{TrackInfo, TrackSegment};
use super::common::uuid_id;
uuid_id!(RouteId);
/// A route of the file (`rte`): like a track, but with a single segment, its points.
///
/// It has the information of a track: GPX gives the same to both.
#[derive(Debug, Default, Clone)]
pub struct Route {
pub id: RouteId,
pub info: TrackInfo,
pub seg: TrackSegment,
}
+55 -271
View File
@@ -1,13 +1,13 @@
use crate::{
Author, Chunk, File, Link, LngLat, Route, Track, TrackSegment, Trackpoint,
TrackpointCategories, TrackpointChunk, Waypoint, WaypointChunk, distance,
Author, Chunk, File, Link, LngLat, Track, TrackSegment, Trackpoint, 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,
@@ -18,7 +18,6 @@ enum GPXElement {
Author(Author),
Link(Link),
Text,
/// A track, or a route, whose information is read the same way.
Track(Track),
Segment(TrackSegment),
Trackpoint(Trackpoint),
@@ -37,8 +36,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 +57,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 +80,6 @@ fn holds_text(element: Option<&GPXElement>) -> bool {
| GPXElement::Symbol
| GPXElement::Type
| GPXElement::Color
| GPXElement::DisplayColor
| GPXElement::Opacity
| GPXElement::Width
)
@@ -213,21 +165,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 +240,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 +259,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 +267,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 +282,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
@@ -470,7 +396,7 @@ pub fn parse(data: &[u8], categories: &mut TrackpointCategories) -> Result<File,
let mut stack: Vec<GPXElement> = vec![];
let mut trkpt_chunk = TrackpointChunk::default();
let mut wpt_chunk = WaypointChunk::default();
// The segment of a route is read by `RouteReader`. The points of the detailed
// Routes are read as tracks of a single segment, see `RouteReader`. The points of the detailed
// path that a route point comes with (`gpxx:rpt`) are collected until the route point is read.
let mut route = RouteReader::default();
let mut rpt_points: Vec<Trackpoint> = vec![];
@@ -521,7 +447,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),
_ => (),
@@ -605,12 +530,12 @@ pub fn parse(data: &[u8], categories: &mut TrackpointCategories) -> Result<File,
}
}
"rte" => {
if let Some(GPXElement::Track(trk)) = stack.pop() {
gpx.rte.push(Route {
info: trk.info,
seg: std::mem::take(&mut route).finish(),
..Default::default()
});
if let Some(GPXElement::Track(mut trk)) = stack.pop() {
let trkseg = std::mem::take(&mut route).finish();
if !trkseg.is_empty() {
trk.trkseg.push(trkseg);
}
gpx.trk.push(trk);
}
}
"rtept" => {
@@ -700,14 +625,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>
@@ -823,37 +740,38 @@ mod tests {
}
#[test]
fn test_parse_routes() {
fn test_parse_routes_as_tracks() {
let gpx = parse_data("with_routes");
assert!(gpx.trk.is_empty());
assert_eq!(gpx.rte.len(), 2);
let rte = &gpx.rte[0];
assert_eq!(rte.info.name.as_deref(), Some("route 1"));
assert_eq!(rte.info.type_.as_deref(), Some("Cycling"));
assert_eq!(rte.seg.len(), 49);
let trkpt = &rte.seg[0];
assert_eq!(gpx.trk.len(), 2);
let trk = &gpx.trk[0];
assert_eq!(trk.info.name.as_deref(), Some("route 1"));
assert_eq!(trk.info.type_.as_deref(), Some("Cycling"));
assert_eq!(trk.trkseg.len(), 1);
let trkseg = &trk.trkseg[0];
assert_eq!(trkseg.len(), 49);
let trkpt = &trkseg[0];
assert_eq!(trkpt.coordinates.lat, 50.790867);
assert_eq!(trkpt.coordinates.lng, 4.404968);
assert_eq!(trkpt.ele, 109.0);
let rte = &gpx.rte[1];
assert_eq!(rte.info.name.as_deref(), Some("route 2"));
assert_eq!(rte.seg.len(), 28);
assert_ne!(gpx.rte[0].id, rte.id);
let trk = &gpx.trk[1];
assert_eq!(trk.info.name.as_deref(), Some("route 2"));
assert_eq!(trk.trkseg[0].len(), 28);
}
#[test]
fn test_parse_route_point_extensions() {
let gpx = parse_data("with_route_extensions");
// a route without points has an empty segment
assert_eq!(gpx.rte.len(), 2);
assert!(gpx.rte[1].seg.is_empty());
// a route without points has no segment
assert_eq!(gpx.trk.len(), 2);
assert!(gpx.trk[1].trkseg.is_empty());
let rte = &gpx.rte[0];
assert_eq!(rte.info.name.as_deref(), Some("with extensions"));
let points: Vec<_> = rte.seg.iter().collect();
let trk = &gpx.trk[0];
assert_eq!(trk.info.name.as_deref(), Some("with extensions"));
assert_eq!(trk.trkseg.len(), 1);
let points: Vec<_> = trk.trkseg[0].iter().collect();
// the route points are kept, the points of the detailed path follow the one they come with
let coordinates: Vec<_> = points
.iter()
@@ -870,13 +788,14 @@ mod tests {
#[test]
fn test_route_points_are_the_anchors_and_nothing_else_is() {
let gpx = parse_data("with_route_extensions");
let anchors: Vec<_> = gpx.rte[0].seg.iter().map(|p| p.anchor).collect();
let anchors: Vec<_> = gpx.trk[0].trkseg[0].iter().map(|p| p.anchor).collect();
assert_eq!(anchors, [Some(0), None, None, Some(0), Some(0)]);
// no anchor is computed for the points of a route that has none in between
let gpx = parse_data("with_routes");
for rte in &gpx.rte {
assert!(rte.seg.iter().all(|p| p.anchor == Some(0)));
for trk in &gpx.trk {
let segment = &trk.trkseg[0];
assert!(segment.iter().all(|p| p.anchor == Some(0)));
}
// while a track gets the anchors that its shape needs
let track = parse_data("with_tracks");
@@ -888,14 +807,14 @@ mod tests {
#[test]
fn test_parse_the_points_of_the_detailed_path_of_a_route() {
let gpx = parse_data("with_route_points");
assert_eq!(gpx.rte.len(), 1);
let rte = &gpx.rte[0];
assert_eq!(rte.info.name.as_deref(), Some("Lausanne"));
assert_eq!(rte.info.cmt.as_deref(), Some("comment"));
assert_eq!(rte.info.desc.as_deref(), Some("description"));
assert_eq!(rte.info.type_.as_deref(), Some("Cycling"));
assert_eq!(gpx.trk.len(), 1);
let trk = &gpx.trk[0];
assert_eq!(trk.info.name.as_deref(), Some("Lausanne"));
assert_eq!(trk.info.cmt.as_deref(), Some("comment"));
assert_eq!(trk.info.desc.as_deref(), Some("description"));
assert_eq!(trk.info.type_.as_deref(), Some("Cycling"));
let points: Vec<_> = rte.seg.iter().cloned().collect();
let points: Vec<_> = trk.trkseg[0].iter().cloned().collect();
// 3 route points and 4 points between them, the repeated one being kept
assert_eq!(points.len(), 7);
let kinds: Vec<_> = points.iter().map(|p| p.anchor.is_some()).collect();
@@ -927,7 +846,7 @@ mod tests {
</rtept>
</rte></gpx>"#;
let gpx = parse(data.as_bytes(), &mut Default::default()).unwrap();
let points: Vec<_> = gpx.rte[0].seg.iter().cloned().collect();
let points: Vec<_> = gpx.trk[0].trkseg[0].iter().cloned().collect();
let coordinates: Vec<_> = points.iter().map(|p| p.coordinates.lat).collect();
assert_eq!(coordinates, [1.0, 2.0, 2.1, 2.2]);
// the route point is an anchor, and so is the end of the path
@@ -942,7 +861,7 @@ mod tests {
<gpxx:RoutePointExtension><gpxx:rpt lat="1.5" lon="1.5"/></gpxx:RoutePointExtension>
</extensions></rtept></rte></gpx>"#;
let gpx = parse(data.as_bytes(), &mut Default::default()).unwrap();
let anchors: Vec<_> = gpx.rte[0].seg.iter().map(|p| p.anchor).collect();
let anchors: Vec<_> = gpx.trk[0].trkseg[0].iter().map(|p| p.anchor).collect();
assert_eq!(anchors, [Some(0), Some(0)]);
}
@@ -1011,14 +930,14 @@ mod tests {
assert_eq!(waypoints[0].links[2].text.as_deref(), Some("three"));
assert!(waypoints[1].links.is_empty());
// tracks, and routes
assert_eq!((gpx.trk.len(), gpx.rte.len()), (1, 1));
// tracks, and routes which are read as tracks
assert_eq!(gpx.trk.len(), 2);
assert_eq!(
hrefs(&gpx.trk[0].info.links),
["https://example.com/trk-1", "https://example.com/trk-2"]
);
assert_eq!(
hrefs(&gpx.rte[0].info.links),
hrefs(&gpx.trk[1].info.links),
["https://example.com/rte-1", "https://example.com/rte-2"]
);
}
@@ -1147,20 +1066,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 +1223,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 +1236,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 +1247,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));
}
}
+124 -161
View File
@@ -8,6 +8,9 @@ use crate::{File, Link, Track, Trackpoint, TrackpointCategories, Waypoint};
/// What the written file contains: the data of the trackpoints that are `false` are left out.
/// The same type tells which data a file has, see [`File::exportable_data`].
///
/// With `as_route`, the file is written with routes instead of tracks, see [`write`]. It is not
/// data: it is off in `ALL` and `NONE`, and in what [`File::exportable_data`] gives.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ExportOptions {
pub time: bool,
@@ -17,6 +20,8 @@ pub struct ExportOptions {
pub power: bool,
/// The OpenStreetMap data: surface, highway, SAC scale and MTB scale.
pub osm: bool,
/// Writes every segment as a route (`rte`) instead of a track.
pub as_route: bool,
}
impl ExportOptions {
@@ -31,6 +36,7 @@ impl ExportOptions {
atemp: value,
power: value,
osm: value,
as_route: false,
}
}
@@ -43,6 +49,7 @@ impl ExportOptions {
atemp: self.atemp || other.atemp,
power: self.power || other.power,
osm: self.osm || other.osm,
as_route: self.as_route || other.as_route,
}
}
}
@@ -52,7 +59,12 @@ impl File {
/// options of [`write`] can leave out.
pub fn exportable_data(&self) -> ExportOptions {
let mut data = ExportOptions::NONE;
for point in self.segments().flat_map(|seg| seg.iter()) {
for point in self
.trk
.iter()
.flat_map(|trk| &trk.trkseg)
.flat_map(|seg| seg.iter())
{
data.time |= point.time.is_some();
data.hr |= point.hr.is_some();
data.cad |= point.cad.is_some();
@@ -70,10 +82,6 @@ impl File {
}
}
/// The highest zoom level from which an anchor is shown that makes it a route point, see [`write`]:
/// the anchors that only appear when zooming in further are details of the path.
pub const ROUTE_POINT_MAX_ZOOM: u8 = 12;
const SCHEMA_LOCATION: &str = "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.garmin.com/xmlschemas/PowerExtension/v1 http://www.garmin.com/xmlschemas/PowerExtensionv1.xsd http://www.topografix.com/GPX/gpx_style/0/2 http://www.topografix.com/GPX/gpx_style/0/2/gpx_style.xsd";
type XmlWriter = Writer<Vec<u8>>;
@@ -81,10 +89,10 @@ type XmlWriter = Writer<Vec<u8>>;
/// Writes a file as GPX 1.1, in UTF-8. The surface, highway, SAC scale and MTB scale of the trackpoints are
/// the names of their codes in `categories`.
///
/// The routes are written as routes (`rte`): the anchors of their segment that are shown from the
/// zoom level [`ROUTE_POINT_MAX_ZOOM`] or a lower one are the `rtept`, and the trackpoints between
/// two of them are the `gpxx:rpt` of the `rtept` before them (which only have a position, unlike
/// the `rtept`). The first and last trackpoints always are `rtept`.
/// The segments are written as tracks, or with `options.as_route` as routes: a segment becomes a
/// `rte` that has the information of its track, its anchors are the `rtept` and the trackpoints
/// between two anchors are the `gpxx:rpt` of the `rtept` before them (which only have a
/// position, unlike the `rtept`). The first and last trackpoints always are `rtept`.
pub fn write(file: &File, categories: &TrackpointCategories, options: ExportOptions) -> Vec<u8> {
let mut writer = Writer::new_with_indent(Vec::new(), b' ', 4);
// writing to memory does not fail
@@ -92,9 +100,9 @@ pub fn write(file: &File, categories: &TrackpointCategories, options: ExportOpti
writer.into_inner()
}
fn write_file<'a>(
fn write_file(
w: &mut XmlWriter,
file: &'a File,
file: &File,
categories: &TrackpointCategories,
options: ExportOptions,
) -> io::Result<()> {
@@ -128,18 +136,20 @@ fn write_file<'a>(
for wpt in file.wpt.iter() {
write_waypoint(w, wpt, options)?;
}
// a single unnamed route or track is named like the file
let alone = file.rte.len() + file.trk.len() == 1;
let name = |info: &'a crate::TrackInfo| match &info.name {
Some(name) if !name.is_empty() => Some(name.as_str()),
_ if alone => Some(file.info.name.as_str()),
_ => None,
};
for rte in &file.rte {
write_route(w, &rte.info, &rte.seg, name(&rte.info), categories, options)?;
}
for trk in &file.trk {
write_track(w, trk, name(&trk.info), categories, options)?;
// a single unnamed track is named like the file
let name = match (&trk.info.name, file.trk.len()) {
(Some(name), _) if !name.is_empty() => Some(name.as_str()),
(_, 1) => Some(file.info.name.as_str()),
_ => None,
};
if options.as_route {
for segment in trk.trkseg.iter().filter(|segment| !segment.is_empty()) {
write_route(w, trk, segment, name, categories, options)?;
}
} else {
write_track(w, trk, name, categories, options)?;
}
}
Ok(())
})?;
@@ -301,28 +311,22 @@ fn write_track(
fn write_route(
w: &mut XmlWriter,
info: &crate::TrackInfo,
trk: &Track,
segment: &crate::TrackSegment,
name: Option<&str>,
categories: &TrackpointCategories,
options: ExportOptions,
) -> io::Result<()> {
w.create_element("rte").write_inner_content(|w| {
write_track_info(w, name, info)?;
write_track_info(w, name, &trk.info)?;
let points: Vec<&Trackpoint> = segment.iter().collect();
let last = points.len().saturating_sub(1);
let is_route_point = |i: usize| {
i == 0
|| i == last
|| points[i]
.anchor
.is_some_and(|zoom| zoom <= ROUTE_POINT_MAX_ZOOM)
};
let last = points.len() - 1;
let is_anchor = |i: usize| i == 0 || i == last || points[i].anchor.is_some();
let mut i = 0;
while i < points.len() {
// the trackpoints up to the next route point
// the trackpoints up to the next anchor
let mut next = i + 1;
while next < points.len() && !is_route_point(next) {
while next < points.len() && !is_anchor(next) {
next += 1;
}
write_point(
@@ -402,10 +406,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")
@@ -452,7 +455,9 @@ mod tests {
}
fn points(file: &File) -> Vec<Trackpoint> {
file.segments()
file.trk
.iter()
.flat_map(|trk| &trk.trkseg)
.flat_map(|seg| seg.iter().cloned())
.collect()
}
@@ -512,7 +517,6 @@ mod tests {
"with_temp",
"with_power_1",
"with_power_2",
"with_power_3",
"with_surface",
"with_highway",
"with_style",
@@ -580,16 +584,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");
@@ -601,20 +595,11 @@ mod tests {
assert!(file.exportable_data().power);
}
/// The file with each segment of its tracks as a route, which has the information of its
/// track.
fn as_routes(mut file: File) -> File {
file.rte = std::mem::take(&mut file.trk)
.into_iter()
.flat_map(|trk| {
trk.trkseg.into_iter().map(move |seg| crate::Route {
info: trk.info.clone(),
seg,
..Default::default()
})
})
.collect();
file
fn as_route() -> ExportOptions {
ExportOptions {
as_route: true,
..ExportOptions::ALL
}
}
fn count(text: &str, pattern: &str) -> usize {
@@ -622,17 +607,19 @@ mod tests {
}
#[test]
fn test_routes_are_written_with_their_route_points_and_their_path() {
fn test_export_as_route_writes_routes_instead_of_tracks() {
let (file, categories) = read("with_route_points");
let text = written_text(&file, &categories, ExportOptions::ALL);
let text = written_text(&file, &categories, as_route());
assert_eq!(count(&text, "<rte>"), 1);
assert_eq!(count(&text, "<trk>"), 0);
assert_eq!(count(&text, "<trkseg>"), 0);
assert_eq!(count(&text, "<trkpt"), 0);
// the anchors are the route points, the trackpoints between them the points of their path
assert_eq!(count(&text, "<rtept"), 3);
assert_eq!(count(&text, "<gpxx:rpt"), 4);
assert_eq!(count(&text, "<gpxx:RoutePointExtension>"), 2);
// a route has the information of its track
assert!(text.contains("<name>Lausanne</name>"));
assert!(text.contains("<cmt>comment</cmt>"));
assert!(text.contains("<desc>description</desc>"));
@@ -647,14 +634,14 @@ mod tests {
}
#[test]
fn test_a_route_survives_being_written() {
fn test_a_route_survives_being_exported_as_a_route() {
let (file, mut categories) = read("with_route_points");
let written = write(&file, &categories, ExportOptions::ALL);
let written = write(&file, &categories, as_route());
let again = parse(&written, &mut categories).unwrap();
assert_eq!(again.rte.len(), 1);
assert_eq!(again.rte[0].info, file.rte[0].info);
let (a, b) = (&file.rte[0].seg, &again.rte[0].seg);
assert_eq!(again.trk.len(), 1);
assert_eq!(again.trk[0].info, file.trk[0].info);
let (a, b) = (&file.trk[0].trkseg[0], &again.trk[0].trkseg[0]);
assert_eq!(a.len(), b.len());
for (a, b) in a.iter().zip(b.iter()) {
assert_eq!(a.coordinates.lat, b.coordinates.lat);
@@ -672,121 +659,85 @@ mod tests {
}
#[test]
fn test_the_anchors_shown_up_to_zoom_12_are_the_route_points() {
fn test_tracks_become_one_route_per_segment_with_the_information_of_the_track() {
let (file, mut categories) = read("with_tracks_and_segments");
let file = as_routes(file);
assert!(file.rte.len() > 2);
let written = write(&file, &categories, ExportOptions::ALL);
let segments: usize = file.trk.iter().map(|t| t.trkseg.len()).sum();
assert!(segments > 2);
let written = write(&file, &categories, as_route());
let text = String::from_utf8(written.clone()).unwrap();
assert_eq!(count(&text, "<rte>"), segments);
assert_eq!(count(&text, "<trk>"), 0);
// every route starts and ends with a route point
assert_eq!(count(&text, "</rte>"), segments);
let again = parse(&written, &mut categories).unwrap();
assert_eq!(again.rte.len(), file.rte.len());
let anchors = |s: &crate::TrackSegment, max_zoom: u8| {
s.iter()
.enumerate()
.filter(|(_, p)| p.anchor.is_some_and(|zoom| zoom <= max_zoom))
.map(|(i, _)| i)
.collect::<Vec<_>>()
};
for (a, b) in file.rte.iter().zip(&again.rte) {
assert_eq!(a.info.name, b.info.name);
assert_eq!(a.seg.len(), b.seg.len());
// the route points come back as anchors, the other anchors as points of the path
assert_eq!(
anchors(&a.seg, ROUTE_POINT_MAX_ZOOM),
anchors(&b.seg, u8::MAX)
);
assert_eq!(again.trk.len(), segments);
let mut routes = again.trk.iter();
for track in &file.trk {
for segment in &track.trkseg {
let route = routes.next().unwrap();
// the information of the track, repeated for each of its segments
assert_eq!(route.info.name, track.info.name);
assert_eq!(route.info.type_, track.info.type_);
let (a, b) = (segment, &route.trkseg[0]);
assert_eq!(a.len(), b.len());
for (a, b) in a.iter().zip(b.iter()) {
assert_eq!(
(a.coordinates.lat, a.coordinates.lng),
(b.coordinates.lat, b.coordinates.lng)
);
}
// the anchors of the segment are the ones of its route
let anchors = |s: &crate::TrackSegment| {
s.iter()
.enumerate()
.filter(|(_, p)| p.anchor.is_some())
.map(|(i, _)| i)
.collect::<Vec<_>>()
};
assert_eq!(anchors(a), anchors(b));
}
}
}
#[test]
fn test_anchors_shown_from_a_higher_zoom_are_points_of_the_path() {
let (file, categories) = read("simple");
let mut file = as_routes(file);
let segment = &mut file.rte[0].seg;
segment.update_all(|_, point| point.anchor = None);
let len = segment.len();
segment.set_anchor(5, ROUTE_POINT_MAX_ZOOM);
segment.set_anchor(10, ROUTE_POINT_MAX_ZOOM + 1);
let text = written_text(&file, &categories, ExportOptions::ALL);
// the ends, and the anchor shown from zoom 12
assert_eq!(count(&text, "<rtept"), 3);
assert_eq!(count(&text, "<gpxx:rpt"), len - 3);
}
#[test]
fn test_the_ends_of_a_route_are_route_points_even_without_anchors() {
let (file, categories) = read("simple");
let mut file = as_routes(file);
file.rte[0].seg.update_all(|_, point| point.anchor = None);
let len = file.rte[0].seg.len();
let text = written_text(&file, &categories, ExportOptions::ALL);
let (mut file, categories) = read("simple");
file.trk[0].trkseg[0].update_all(|_, point| point.anchor = None);
let len = file.trk[0].trkseg[0].len();
let text = written_text(&file, &categories, as_route());
assert_eq!(count(&text, "<rtept"), 2);
assert_eq!(count(&text, "<gpxx:rpt"), len - 2);
// and a single trackpoint is a route of one point
file.rte[0].seg.splice(1, len, vec![]);
let text = written_text(&file, &categories, ExportOptions::ALL);
file.trk[0].trkseg[0].splice(1, len, vec![]);
let text = written_text(&file, &categories, as_route());
assert_eq!(count(&text, "<rtept"), 1);
assert_eq!(count(&text, "<gpxx:rpt"), 0);
}
#[test]
fn test_routes_keep_their_style() {
fn test_empty_segments_are_not_routes() {
let (mut file, categories) = read("simple");
file.trk[0].trkseg.push(crate::TrackSegment::default());
let text = written_text(&file, &categories, as_route());
assert_eq!(count(&text, "<rte>"), 1);
}
#[test]
fn test_routes_have_the_style_of_their_track() {
let (file, categories) = read("with_style");
let file = as_routes(file);
let text = written_text(&file, &categories, ExportOptions::ALL);
let text = written_text(&file, &categories, as_route());
assert!(count(&text, "<gpx_style:line>") >= 1);
assert_eq!(count(&text, "<gpx_style:line>"), count(&text, "<rte>"));
let again = parse(text.as_bytes(), &mut Default::default()).unwrap();
assert_eq!(again.rte[0].info.color, file.rte[0].info.color);
assert_eq!(again.rte[0].info.width, file.rte[0].info.width);
}
#[test]
fn test_routes_are_written_as_routes_before_the_tracks() {
let (mut file, categories) = read("with_tracks");
let (routes, _) = read("with_routes");
file.rte = routes.rte.clone();
let text = written_text(&file, &categories, ExportOptions::ALL);
assert_eq!(count(&text, "<rte>"), routes.rte.len());
assert_eq!(count(&text, "<trk>"), file.trk.len());
assert!(text.rfind("</rte>").unwrap() < text.find("<trk>").unwrap());
let again = parse(text.as_bytes(), &mut categories.clone()).unwrap();
assert_eq!(again.rte.len(), file.rte.len());
assert_eq!(again.trk.len(), file.trk.len());
for (a, b) in file.rte.iter().zip(&again.rte) {
assert_eq!(a.info, b.info);
same_points(
&a.seg.iter().cloned().collect::<Vec<_>>(),
&b.seg.iter().cloned().collect::<Vec<_>>(),
);
}
same_points(&points(&file), &points(&again));
}
#[test]
fn test_an_empty_route_is_written_and_a_single_route_is_named_like_the_file() {
let mut file = File::default();
file.info.name = "file".into();
file.rte.push(crate::Route::default());
let text = written_text(&file, &Default::default(), ExportOptions::ALL);
assert_eq!(count(&text, "<rte>"), 1);
assert_eq!(count(&text, "<rtept"), 0);
let again = parse(text.as_bytes(), &mut Default::default()).unwrap();
assert_eq!(again.rte.len(), 1);
assert_eq!(again.rte[0].info.name.as_deref(), Some("file"));
// not when there are others
file.trk.push(Track::default());
let text = written_text(&file, &Default::default(), ExportOptions::ALL);
// the metadata only
assert_eq!(count(&text, "<name>file</name>"), 1);
assert_eq!(again.trk[0].info.color, file.trk[0].info.color);
assert_eq!(again.trk[0].info.width, file.trk[0].info.width);
}
#[test]
fn test_route_points_keep_their_data_and_the_options_apply_to_them() {
let (file, categories) = read("with_hr");
let file = as_routes(file);
let with_all = written_text(&file, &categories, ExportOptions::ALL);
let with_all = written_text(&file, &categories, as_route());
assert!(with_all.contains("<gpxtpx:hr>"));
let without = written_text(
&file,
@@ -794,10 +745,22 @@ mod tests {
ExportOptions {
hr: false,
time: false,
as_route: true,
..ExportOptions::ALL
},
);
assert!(!without.contains("<gpxtpx:hr>"));
assert!(!without.contains("<time>"));
}
#[test]
fn test_the_route_option_is_not_data() {
let (file, _) = read("with_route_points");
assert!(!file.exportable_data().as_route);
// it is a way to write the data, never part of them
let all = std::hint::black_box(ExportOptions::ALL);
assert!(!all.as_route && !ExportOptions::NONE.as_route);
assert!(as_route().union(ExportOptions::NONE).as_route);
assert!(!ExportOptions::ALL.union(ExportOptions::NONE).as_route);
}
}
+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() {
-7
View File
@@ -36,11 +36,4 @@ pub enum Action<'a> {
file_ids: Vec<FileId>,
index: usize,
},
/// Names a file in all the states of the history, as if it had always been called so (see
/// [`crate::History::rename`]). Not undoable: for a file that is given a name from the outside,
/// like the name of the file it is written to.
Rename {
file_id: FileId,
name: String,
},
}
-163
View File
@@ -1,163 +0,0 @@
use std::{collections::HashSet, rc::Rc};
use crate::{Apply, CommandError, FileId, Route, Selection, State, Track};
/// Converts the selected routes to tracks, or the selected tracks or segments to routes, in their
/// file:
///
/// - a route becomes a track with its segment. The new tracks go before the other tracks, right
/// 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.
///
/// 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.
#[derive(Debug)]
pub struct Convert;
impl Apply for Convert {
fn apply(self, state: &mut State) -> Result<(), CommandError> {
let selection = state.selection.clone();
let next = match &selection {
Selection::Route { file_id, rte_ids } => {
let file = Rc::make_mut(
state
.files
.get_mut(file_id)
.ok_or(CommandError::NothingToDo)?,
);
let (converted, kept) = std::mem::take(&mut file.rte)
.into_iter()
.partition::<Vec<_>, _>(|rte| rte_ids.contains(&rte.id));
file.rte = kept;
let tracks = to_tracks(converted);
let trk_ids: HashSet<_> = tracks.iter().map(|trk| trk.id).collect();
file.trk.splice(0..0, tracks);
Selection::Track {
file_id: *file_id,
trk_ids,
}
}
Selection::Track { file_id, trk_ids } => {
let file = Rc::make_mut(
state
.files
.get_mut(file_id)
.ok_or(CommandError::NothingToDo)?,
);
let (converted, kept) = std::mem::take(&mut file.trk)
.into_iter()
.partition::<Vec<_>, _>(|trk| trk_ids.contains(&trk.id));
file.trk = kept;
add_routes(&mut file.rte, *file_id, to_routes(converted))
}
Selection::TrackSegment {
file_id,
trk_id,
trkseg_ids,
} => {
let file = Rc::make_mut(
state
.files
.get_mut(file_id)
.ok_or(CommandError::NothingToDo)?,
);
let trk = file
.trk
.iter_mut()
.find(|trk| trk.id == *trk_id)
.ok_or(CommandError::NothingToDo)?;
let (converted, kept) = std::mem::take(&mut trk.trkseg)
.into_iter()
.partition::<Vec<_>, _>(|seg| trkseg_ids.contains(&seg.id));
trk.trkseg = kept;
let info = trk.info.clone();
let routes = converted.into_iter().map(|seg| Route {
id: Default::default(),
info: info.clone(),
seg,
});
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);
}
};
let empty = match &next {
Selection::Route { rte_ids, .. } => rte_ids.is_empty(),
Selection::Track { trk_ids, .. } => trk_ids.is_empty(),
_ => true,
};
if empty {
// nothing was converted (the changed copy of the file is dropped)
return Err(CommandError::NothingToDo);
}
*state.selection = next;
Ok(())
}
}
/// 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>,
file_id: FileId,
routes: impl Iterator<Item = Route>,
) -> Selection {
let start = rte.len();
rte.extend(routes);
Selection::Route {
file_id,
rte_ids: rte[start..].iter().map(|rte| rte.id).collect(),
}
}
+7 -24
View File
@@ -1,6 +1,4 @@
use crate::{
Apply, CommandError, Edit, Editor, File, Route, State, Track, TrackInfo, update_selected,
};
use crate::{Apply, CommandError, Edit, Editor, File, State, Track, update_selected};
#[derive(Debug)]
pub struct Metadata<'a> {
@@ -15,33 +13,21 @@ impl Apply for Metadata<'_> {
}
}
impl Metadata<'_> {
fn set(&self, info: &mut TrackInfo) -> Edit {
info.name = Some(self.name.to_owned());
info.desc = Some(self.desc.to_owned());
Edit::Changed
}
}
impl Editor for Metadata<'_> {
fn file(&mut self, file: &mut File) -> Edit {
file.info.name = self.name.to_owned();
file.info.desc = Some(self.desc.to_owned());
// a single route or track is named like the file
match (file.rte.as_mut_slice(), file.trk.as_mut_slice()) {
([route], []) => route.info.name = Some(self.name.to_owned()),
([], [track]) => track.info.name = Some(self.name.to_owned()),
_ => {}
// a single track is named like the file
if let [track] = file.trk.as_mut_slice() {
track.info.name = Some(self.name.to_owned());
}
Edit::Changed
}
fn route(&mut self, route: &mut Route) -> Edit {
self.set(&mut route.info)
}
fn track(&mut self, track: &mut Track) -> Edit {
self.set(&mut track.info)
track.info.name = Some(self.name.to_owned());
track.info.desc = Some(self.desc.to_owned());
Edit::Changed
}
}
@@ -59,14 +45,12 @@ mod tests {
New {
name: "first",
trackpoint: None,
route: false,
}
.apply(&mut fx.state())
.unwrap();
New {
name: "second",
trackpoint: None,
route: false,
}
.apply(&mut fx.state())
.unwrap(); // now selected
@@ -124,7 +108,6 @@ mod tests {
New {
name: "file",
trackpoint: None,
route: false,
}
.apply(&mut fx.state())
.unwrap();
-4
View File
@@ -1,13 +1,9 @@
mod convert;
mod metadata;
mod new_route;
mod new_track;
mod new_track_segment;
mod style;
pub use convert::*;
pub use metadata::*;
pub use new_route::*;
pub use new_track::*;
pub use new_track_segment::*;
pub use style::*;
@@ -1,55 +0,0 @@
use crate::{Apply, CommandError, Edit, Editor, File, Route, State, update_selected};
use super::new_track::common_style;
/// Adds an empty route to the selected files, with the style that their routes and tracks agree
/// on (see [`crate::NewTrack`]).
#[derive(Debug)]
pub struct NewRoute;
impl Apply for NewRoute {
fn apply(mut self, state: &mut State) -> Result<(), CommandError> {
update_selected(state, &mut self);
Ok(())
}
}
impl Editor for NewRoute {
fn file(&mut self, file: &mut File) -> Edit {
file.rte.push(Route {
info: common_style(file),
..Default::default()
});
Edit::Changed
}
}
#[cfg(test)]
mod tests {
use crate::{New, engine::command::fixture::Fixture};
use super::*;
#[test]
fn test_new_route_has_the_style_of_the_tracks_and_an_empty_segment() {
let mut fx = Fixture::default();
New {
name: "file",
trackpoint: None,
route: false,
}
.apply(&mut fx.state())
.unwrap();
crate::NewTrack.apply(&mut fx.state()).unwrap();
let file = std::rc::Rc::make_mut(fx.files.values_mut().next().unwrap());
file.trk[0].info.color = Some("ff0000".into());
NewRoute.apply(&mut fx.state()).unwrap();
NewRoute.apply(&mut fx.state()).unwrap();
let file = fx.files.values().next().unwrap();
assert_eq!(file.rte.len(), 2);
assert_ne!(file.rte[0].id, file.rte[1].id);
assert!(file.rte[0].seg.is_empty());
assert_eq!(file.rte[1].info.color.as_deref(), Some("ff0000"));
}
}
+11 -34
View File
@@ -1,4 +1,4 @@
use crate::{Apply, CommandError, Edit, Editor, File, State, Track, TrackInfo, update_selected};
use crate::{Apply, CommandError, Edit, Editor, File, State, Track, update_selected};
#[derive(Debug)]
pub struct NewTrack;
@@ -12,41 +12,20 @@ impl Apply for NewTrack {
impl Editor for NewTrack {
fn file(&mut self, file: &mut File) -> Edit {
file.trk.push(Track {
info: common_style(file),
..Default::default()
});
let mut track = Track::default();
track.info.color = common(file, |t| &t.info.color);
track.info.opacity = common(file, |t| &t.info.opacity);
track.info.width = common(file, |t| &t.info.width);
file.trk.push(track);
Edit::Changed
}
}
/// The style that all the routes and tracks of the file agree on: each attribute is set if they
/// all have the same value for it.
pub(super) fn common_style(file: &File) -> TrackInfo {
let infos: Vec<&TrackInfo> = file
.rte
.iter()
.map(|rte| &rte.info)
.chain(file.trk.iter().map(|trk| &trk.info))
.collect();
TrackInfo {
color: common(&infos, |info| &info.color),
opacity: common(&infos, |info| &info.opacity),
width: common(&infos, |info| &info.width),
..Default::default()
}
}
/// Returns the value of a style attribute if all the infos agree on it.
fn common<T: Clone + PartialEq>(
infos: &[&TrackInfo],
get: impl Fn(&TrackInfo) -> &Option<T>,
) -> Option<T> {
let mut infos = infos.iter();
let first = get(infos.next()?);
infos
.all(|info| get(info) == first)
.then(|| first.clone())?
/// Returns the value of a style attribute if all existing tracks agree on it.
fn common<T: Clone + PartialEq>(file: &File, get: impl Fn(&Track) -> &Option<T>) -> Option<T> {
let mut tracks = file.trk.iter();
let first = get(tracks.next()?);
tracks.all(|t| get(t) == first).then(|| first.clone())?
}
#[cfg(test)]
@@ -61,7 +40,6 @@ mod tests {
New {
name: "file",
trackpoint: None,
route: false,
}
.apply(&mut fx.state())
.unwrap();
@@ -78,7 +56,6 @@ mod tests {
New {
name: "file",
trackpoint: None,
route: false,
}
.apply(&mut fx.state())
.unwrap();
@@ -29,7 +29,6 @@ mod tests {
New {
name: "file",
trackpoint: None,
route: false,
}
.apply(&mut fx.state())
.unwrap();
+6 -16
View File
@@ -1,4 +1,4 @@
use crate::{Apply, CommandError, Edit, Editor, Route, State, Track, TrackInfo, update_selected};
use crate::{Apply, CommandError, Edit, Editor, State, Track, update_selected};
#[derive(Debug)]
pub struct Style<'a> {
@@ -14,31 +14,21 @@ impl Apply for Style<'_> {
}
}
impl Style<'_> {
fn set(&self, info: &mut TrackInfo) -> Edit {
impl Editor for Style<'_> {
fn track(&mut self, track: &mut Track) -> Edit {
if let Some(color) = self.color {
info.color = Some(color.to_owned());
track.info.color = Some(color.to_owned());
}
if self.opacity.is_some() {
info.opacity = self.opacity;
track.info.opacity = self.opacity;
}
if self.width.is_some() {
info.width = self.width;
track.info.width = self.width;
}
Edit::Changed
}
}
impl Editor for Style<'_> {
fn route(&mut self, route: &mut Route) -> Edit {
self.set(&mut route.info)
}
fn track(&mut self, track: &mut Track) -> Edit {
self.set(&mut track.info)
}
}
#[cfg(test)]
mod tests {
use std::collections::HashSet;
+1 -18
View File
@@ -3,7 +3,7 @@ use std::rc::Rc;
use crate::{Apply, CommandError, FileId, Files, Selection, State, Waypoint};
/// Deletes the selected elements. With `whole_files`, the files holding the selected elements
/// are deleted instead, even if only a route, a track or a waypoint is selected.
/// are deleted instead, even if only a track or a waypoint is selected.
#[derive(Debug)]
pub struct Delete {
pub whole_files: bool,
@@ -23,21 +23,6 @@ impl Apply for Delete {
state.order.0.retain(|id| !file_ids.contains(id));
Selection::Empty
}
Selection::Route { file_id, rte_ids } => {
let file = state
.files
.get_mut(file_id)
.ok_or(CommandError::NothingToDo)?;
let file = Rc::make_mut(file);
let len = file.rte.len();
file.rte.retain(|rte| !rte_ids.contains(&rte.id));
if file.rte.len() == len {
return Err(CommandError::NothingToDo);
}
Selection::File {
file_ids: [*file_id].into(),
}
}
Selection::Track { file_id, trk_ids } => {
let file = state
.files
@@ -146,7 +131,6 @@ mod tests {
crate::New {
name: "keep",
trackpoint: None,
route: false,
}
.apply(&mut fx.state())
.unwrap();
@@ -281,7 +265,6 @@ mod tests {
crate::New {
name: "keep",
trackpoint: None,
route: false,
}
.apply(&mut fx.state())
.unwrap();
@@ -31,14 +31,12 @@ mod tests {
crate::New {
name: "a",
trackpoint: None,
route: false,
}
.apply(&mut fx.state())
.unwrap();
crate::New {
name: "b",
trackpoint: None,
route: false,
}
.apply(&mut fx.state())
.unwrap();
+2 -27
View File
@@ -1,8 +1,8 @@
use std::{collections::HashSet, rc::Rc};
use crate::{
Apply, CommandError, FileId, Files, Selection, State, Waypoint, copy_file, copy_route,
copy_segment, copy_track, copy_waypoint,
Apply, CommandError, FileId, Files, Selection, State, Waypoint, copy_file, copy_segment,
copy_track, copy_waypoint,
};
#[derive(Debug)]
@@ -35,30 +35,6 @@ impl Apply for Duplicate {
state.order.0.splice(at..at, order);
Selection::File { file_ids: copies }
}
Selection::Route { file_id, rte_ids } => {
let file = state
.files
.get_mut(file_id)
.ok_or(CommandError::NothingToDo)?;
let file = Rc::make_mut(file);
let mut copies = HashSet::new();
append_copies(
&mut file.rte,
|rte| rte_ids.contains(&rte.id),
|rte| {
let copy = copy_route(rte);
copies.insert(copy.id);
copy
},
);
if copies.is_empty() {
return Err(CommandError::NothingToDo);
}
Selection::Route {
file_id: *file_id,
rte_ids: copies,
}
}
Selection::Track { file_id, trk_ids } => {
let file = state
.files
@@ -217,7 +193,6 @@ mod tests {
crate::New {
name,
trackpoint: None,
route: false,
}
.apply(&mut fx.state())
.unwrap();
-3
View File
@@ -85,7 +85,6 @@ mod tests {
crate::New {
name: "keep",
trackpoint: None,
route: false,
}
.apply(&mut fx.state())
.unwrap();
@@ -141,7 +140,6 @@ mod tests {
crate::New {
name: "before",
trackpoint: None,
route: false,
}
.apply(&mut fx.state())
.unwrap();
@@ -191,7 +189,6 @@ mod tests {
crate::New {
name: "keep",
trackpoint: None,
route: false,
}
.apply(&mut fx.state())
.unwrap();
@@ -9,8 +9,6 @@ use crate::{
pub enum MoveTarget {
/// The list of files.
Files { index: usize },
/// The routes of a file.
Routes { file_id: FileId, index: usize },
/// The tracks of a file.
Tracks { file_id: FileId, index: usize },
/// The segments of a track.
@@ -28,10 +26,9 @@ pub enum MoveTarget {
///
/// What can go where:
/// - files: among the files;
/// - routes and tracks: among the files (each one becomes a file), or among the routes or the
/// tracks of a file, where they keep their kind (see [`Destination`]);
/// - segments: among the files (each segment becomes a file), among the routes or the tracks of a
/// file (each segment becomes a route or a track), or among the segments of a track;
/// - tracks: among the files (each track becomes a file), or among the tracks of a file;
/// - segments: among the files (each segment becomes a file), among the tracks of a file (each
/// segment becomes a track), or among the segments of a track;
/// - waypoints, or all the waypoints of a file (the waypoints node): among the waypoints of a
/// file.
#[derive(Debug)]
@@ -44,9 +41,6 @@ impl From<MoveTarget> for Destination {
fn from(target: MoveTarget) -> Self {
match target {
MoveTarget::Files { index } => Destination::Files(Place::Index(index)),
MoveTarget::Routes { file_id, index } => {
Destination::Routes(file_id, Place::Index(index))
}
MoveTarget::Tracks { file_id, index } => {
Destination::Tracks(file_id, Place::Index(index))
}
+6 -53
View File
@@ -1,16 +1,12 @@
use crate::{
Apply, CommandError, File, LngLat, Route, State, Track, TrackSegment, Trackpoint, produce,
};
use crate::{Apply, CommandError, File, LngLat, State, Track, TrackSegment, Trackpoint, produce};
/// Creates an empty file and selects it. With `route`, the file starts with a route, which is
/// empty. With a `trackpoint`, the file starts with a segment that holds it, the one of its route
/// with `route` or of a track otherwise: it is how the routing tool starts a route on an empty map,
/// in a single undo step.
/// Creates an empty file and selects it. With a `trackpoint`, the file starts with a track and a
/// segment that hold it: it is how the routing tool starts a route on an empty map, in a single
/// undo step.
#[derive(Debug)]
pub struct New<'a> {
pub name: &'a str,
pub trackpoint: Option<NewTrackpoint>,
pub route: bool,
}
#[derive(Debug, Clone, Copy)]
@@ -25,8 +21,8 @@ impl Apply for New<'_> {
produce(state, |_| {
let mut file = File::default();
file.info.name = self.name.to_owned();
let mut segment = TrackSegment::default();
if let Some(point) = self.trackpoint {
let mut segment = TrackSegment::default();
// the ends of a segment are anchors of the routing tool
segment.splice(
0,
@@ -40,13 +36,6 @@ impl Apply for New<'_> {
..Default::default()
}],
);
}
if self.route {
file.rte.push(Route {
seg: segment,
..Default::default()
});
} else if self.trackpoint.is_some() {
file.trk.push(Track {
trkseg: vec![segment],
..Default::default()
@@ -70,8 +59,7 @@ mod tests {
assert!(
New {
name: "new",
trackpoint: None,
route: false,
trackpoint: None
}
.apply(&mut fx.state())
.is_ok()
@@ -95,7 +83,6 @@ mod tests {
New {
name: "new",
trackpoint: Some(point),
route: false,
}
.apply(&mut fx.state())
.unwrap();
@@ -111,38 +98,4 @@ mod tests {
assert_eq!(segment[0].anchor, Some(0));
assert_eq!(fx.selected_files(), [file.id].into());
}
#[test]
fn test_new_with_a_route() {
let mut fx = Fixture::default();
New {
name: "new",
trackpoint: None,
route: true,
}
.apply(&mut fx.state())
.unwrap();
let file = fx.files.values().next().unwrap();
assert_eq!((file.rte.len(), file.trk.len()), (1, 0));
assert!(file.rte[0].seg.is_empty());
assert_eq!(fx.selected_files(), [file.id].into());
// the trackpoint goes to the route
let mut fx = Fixture::default();
New {
name: "new",
trackpoint: Some(NewTrackpoint {
lng: 1.0,
lat: 2.0,
ele: 3.0,
}),
route: true,
}
.apply(&mut fx.state())
.unwrap();
let file = fx.files.values().next().unwrap();
assert_eq!((file.rte.len(), file.trk.len()), (1, 0));
assert_eq!(file.rte[0].seg.len(), 1);
assert_eq!(file.rte[0].seg[0].anchor, Some(0));
}
}
+10 -41
View File
@@ -1,21 +1,18 @@
use std::{collections::HashSet, hash::Hash};
use crate::{
Apply, ClipboardContent, CommandError, Destination, FileId, Place, RouteId, Selection, State,
TrackId, TrackSegmentId, WaypointId, transfer, waypoint_ids,
Apply, ClipboardContent, CommandError, Destination, FileId, Place, Selection, State, TrackId,
TrackSegmentId, WaypointId, transfer, waypoint_ids,
};
/// Pastes what was copied or cut (see [`crate::Clipboard`]).
///
/// Where it goes depends on the selection, see [`crate::Clipboard::can_paste`]:
/// - nothing selected: the files are copied, and routes, tracks and segments become new files
/// (named like their route or track, or like the file they come from);
/// - a file: the routes and tracks are added to it, segments become new tracks in it, and the
/// waypoints are added to its own;
/// - a route: routes, and segments as new routes, go after it in its file, tracks go before the
/// other tracks (right after the routes);
/// - a track: the segments are added to it, tracks go after it in its file, and routes after the
/// other routes;
/// - nothing selected: the files are copied, and tracks and segments become new files (named
/// like their track, or like the file they come from);
/// - a file: the tracks are added to it, segments become new tracks in it, and the waypoints are
/// added to its own;
/// - a track: the segments are added to it, tracks go after it in its file;
/// - a segment: the segments go after it in its track;
/// - the waypoints or a waypoint: the waypoints are added to their file, after the waypoint.
///
@@ -49,14 +46,6 @@ impl Apply for Paste {
}
}
fn route_ids_of(state: &State, file_id: FileId) -> Vec<RouteId> {
state
.files
.get(&file_id)
.map(|file| file.rte.iter().map(|rte| rte.id).collect())
.unwrap_or_default()
}
fn track_ids_of(state: &State, file_id: FileId) -> Vec<TrackId> {
state
.files
@@ -90,34 +79,14 @@ fn destination(state: &State, content: &ClipboardContent) -> Result<Destination,
};
Ok(match (content, &*state.selection) {
(ClipboardContent::Files(_), _) => Destination::Files(Place::End),
(
ClipboardContent::Routes(_)
| ClipboardContent::Tracks(_)
| ClipboardContent::Segments(_),
Selection::Empty,
) => Destination::Files(Place::End),
(ClipboardContent::Routes(_), Selection::File { file_ids }) => {
Destination::Routes(last_file(file_ids)?, Place::End)
}
// routes and tracks keep their kind (see `Destination`)
(
ClipboardContent::Routes(_)
| ClipboardContent::Tracks(_)
| ClipboardContent::Segments(_),
Selection::Route { file_id, rte_ids },
) => {
let last =
last_selected(route_ids_of(state, *file_id).into_iter(), rte_ids).ok_or(nothing)?;
Destination::Routes(*file_id, Place::After(last))
(ClipboardContent::Tracks(_) | ClipboardContent::Segments(_), Selection::Empty) => {
Destination::Files(Place::End)
}
(
ClipboardContent::Tracks(_) | ClipboardContent::Segments(_),
Selection::File { file_ids },
) => Destination::Tracks(last_file(file_ids)?, Place::End),
(
ClipboardContent::Routes(_) | ClipboardContent::Tracks(_),
Selection::Track { file_id, trk_ids },
) => {
(ClipboardContent::Tracks(_), Selection::Track { file_id, trk_ids }) => {
let last =
last_selected(track_ids_of(state, *file_id).into_iter(), trk_ids).ok_or(nothing)?;
Destination::Tracks(*file_id, Place::After(last))
+1 -4
View File
@@ -7,8 +7,7 @@ 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 when the data has none (see [`Load`]).
pub name: &'a str,
}
@@ -76,7 +75,6 @@ mod tests {
New {
name,
trackpoint: None,
route: false,
}
.apply(&mut fx.state())
.unwrap();
@@ -103,7 +101,6 @@ 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");
assert_eq!(fx.files[&first].id, first);
// the selection is not changed
+30 -131
View File
@@ -5,9 +5,9 @@
use std::{collections::HashSet, rc::Rc};
use crate::{
ClipboardContent, ClipboardRoute, ClipboardSegment, ClipboardTrack, CommandError, File, FileId,
Route, RouteId, Selection, State, Track, TrackId, TrackSegment, TrackSegmentId, Waypoint,
WaypointId, copy_file, copy_route, copy_segment, copy_track, copy_waypoint,
ClipboardContent, ClipboardSegment, ClipboardTrack, CommandError, File, FileId, Selection,
State, Track, TrackId, TrackSegment, TrackSegmentId, Waypoint, WaypointId, copy_file,
copy_segment, copy_track, copy_waypoint,
};
/// Where elements are put, among the others of the same list.
@@ -37,20 +37,15 @@ impl<T: Copy + PartialEq> Place<T> {
/// Where elements go. What can go where:
/// - files: among the files;
/// - routes: among the files (each route becomes a file, named like the route, or like the file
/// it comes from), or among the routes of a file. Among the tracks of a file, they stay routes,
/// which come before the tracks: they go after the other routes;
/// - tracks: among the files (each track becomes a file, named like the track, or like the file
/// it comes from), or among the tracks of a file. Among the routes of a file, they stay tracks,
/// which come after the routes: they go before the other tracks;
/// it comes from), or among the tracks of a file;
/// - segments: among the files (each segment becomes a file with a track, named like its track,
/// or like its file), among the routes or the tracks of a file (each segment becomes a route or
/// a track), or among the segments of a track;
/// or like its file), among the tracks of a file (each segment becomes a track), or among the
/// segments of a track;
/// - waypoints: among the waypoints of a file.
#[derive(Debug, Clone, Copy)]
pub enum Destination {
Files(Place<FileId>),
Routes(FileId, Place<RouteId>),
Tracks(FileId, Place<TrackId>),
Segments(FileId, TrackId, Place<TrackSegmentId>),
Waypoints(FileId, Place<WaypointId>),
@@ -98,14 +93,6 @@ pub fn remove_elements(state: &mut State, content: &ClipboardContent) {
state.files.retain(|id, _| !ids.contains(id));
state.order.0.retain(|id| !ids.contains(id));
}
ClipboardContent::Routes(routes) => {
let ids: HashSet<RouteId> = routes.iter().map(|rte| rte.route.id).collect();
for file in state.files.values_mut() {
if file.rte.iter().any(|rte| ids.contains(&rte.id)) {
Rc::make_mut(file).rte.retain(|rte| !ids.contains(&rte.id));
}
}
}
ClipboardContent::Tracks(tracks) => {
let ids: HashSet<TrackId> = tracks.iter().map(|trk| trk.track.id).collect();
for file in state.files.values_mut() {
@@ -154,9 +141,7 @@ pub fn transfer(
// the destination has to be there, before anything is changed
let exists = match to {
Destination::Files(_) => true,
Destination::Routes(file_id, _) | Destination::Tracks(file_id, _) => {
state.files.contains_key(&file_id)
}
Destination::Tracks(file_id, _) => state.files.contains_key(&file_id),
Destination::Segments(file_id, trk_id, _) => state
.files
.get(&file_id)
@@ -167,21 +152,17 @@ pub fn transfer(
(content, to),
(ClipboardContent::Files(_), Destination::Files(_))
| (
ClipboardContent::Routes(_) | ClipboardContent::Tracks(_),
Destination::Files(_) | Destination::Routes(..) | Destination::Tracks(..)
ClipboardContent::Tracks(_),
Destination::Files(_) | Destination::Tracks(..)
)
| (
ClipboardContent::Segments(_),
Destination::Files(_)
| Destination::Routes(..)
| Destination::Tracks(..)
| Destination::Segments(..),
Destination::Files(_) | Destination::Tracks(..) | Destination::Segments(..),
)
| (ClipboardContent::Waypoints(_), Destination::Waypoints(..))
);
let empty = match content {
ClipboardContent::Files(files) => files.is_empty(),
ClipboardContent::Routes(routes) => routes.is_empty(),
ClipboardContent::Tracks(tracks) => tracks.is_empty(),
ClipboardContent::Segments(segments) => segments.is_empty(),
ClipboardContent::Waypoints(waypoints) => waypoints.is_empty(),
@@ -208,7 +189,6 @@ pub fn transfer(
.collect();
Ok(add_files(state, files, place))
}
(ClipboardContent::Routes(routes), to) => transfer_routes(state, routes, copy, to),
(ClipboardContent::Tracks(tracks), to) => transfer_tracks(state, tracks, copy, to),
(ClipboardContent::Segments(segments), to) => transfer_segments(state, segments, copy, to),
(ClipboardContent::Waypoints(waypoints), Destination::Waypoints(file_id, place)) => {
@@ -218,89 +198,6 @@ pub fn transfer(
}
}
/// Puts the routes among the routes of a file, at `place`, and gives the selection of them.
fn insert_routes(
state: &mut State,
file_id: FileId,
place: Place<RouteId>,
routes: Vec<Route>,
) -> Result<Selection, CommandError> {
let ids: HashSet<RouteId> = routes.iter().map(|rte| rte.id).collect();
let file = file_mut(state, file_id)?;
let existing: Vec<RouteId> = file.rte.iter().map(|rte| rte.id).collect();
let at = place.position(&existing);
file.rte.splice(at..at, routes);
Ok(Selection::Route {
file_id,
rte_ids: ids,
})
}
fn transfer_routes(
state: &mut State,
routes: &[ClipboardRoute],
copy: bool,
to: Destination,
) -> Result<Selection, CommandError> {
let routes: Vec<(Route, &str)> = routes
.iter()
.map(|clip| {
let route = if copy {
copy_route(&clip.route)
} else {
clip.route.clone()
};
(route, clip.file_name.as_str())
})
.collect();
match to {
Destination::Files(place) => {
let files = routes
.into_iter()
.map(|(route, file_name)| {
let name = route
.info
.name
.clone()
.unwrap_or_else(|| file_name.to_owned());
Rc::new(File {
rte: vec![route],
..new_file(&name, vec![])
})
})
.collect();
Ok(add_files(state, files, place))
}
Destination::Routes(file_id, place) => {
let routes = routes.into_iter().map(|(route, _)| route).collect();
insert_routes(state, file_id, place, routes)
}
Destination::Tracks(file_id, _) => {
let routes = routes.into_iter().map(|(route, _)| route).collect();
insert_routes(state, file_id, Place::End, routes)
}
_ => Err(CommandError::NothingToDo),
}
}
/// Puts the tracks among the tracks of a file, at `place`, and gives the selection of them.
fn insert_tracks(
state: &mut State,
file_id: FileId,
place: Place<TrackId>,
tracks: Vec<Track>,
) -> Result<Selection, CommandError> {
let ids: HashSet<TrackId> = tracks.iter().map(|trk| trk.id).collect();
let file = file_mut(state, file_id)?;
let existing: Vec<TrackId> = file.trk.iter().map(|trk| trk.id).collect();
let at = place.position(&existing);
file.trk.splice(at..at, tracks);
Ok(Selection::Track {
file_id,
trk_ids: ids,
})
}
fn transfer_tracks(
state: &mut State,
tracks: &[ClipboardTrack],
@@ -334,12 +231,16 @@ fn transfer_tracks(
Ok(add_files(state, files, place))
}
Destination::Tracks(file_id, place) => {
let tracks = tracks.into_iter().map(|(track, _)| track).collect();
insert_tracks(state, file_id, place, tracks)
}
Destination::Routes(file_id, _) => {
let tracks = tracks.into_iter().map(|(track, _)| track).collect();
insert_tracks(state, file_id, Place::Index(0), tracks)
let tracks: Vec<Track> = tracks.into_iter().map(|(track, _)| track).collect();
let ids: HashSet<TrackId> = tracks.iter().map(|trk| trk.id).collect();
let file = file_mut(state, file_id)?;
let existing: Vec<TrackId> = file.trk.iter().map(|trk| trk.id).collect();
let at = place.position(&existing);
file.trk.splice(at..at, tracks);
Ok(Selection::Track {
file_id,
trk_ids: ids,
})
}
_ => Err(CommandError::NothingToDo),
}
@@ -375,22 +276,20 @@ fn transfer_segments(
.collect();
Ok(add_files(state, files, place))
}
Destination::Routes(file_id, place) => {
let routes = segments
.into_iter()
.map(|(seg, _)| Route {
seg,
..Default::default()
})
.collect();
insert_routes(state, file_id, place, routes)
}
Destination::Tracks(file_id, place) => {
let tracks = segments
let tracks: Vec<Track> = segments
.into_iter()
.map(|(segment, _)| own_track(segment))
.collect();
insert_tracks(state, file_id, place, tracks)
let ids = tracks.iter().map(|trk| trk.id).collect();
let file = file_mut(state, file_id)?;
let existing: Vec<TrackId> = file.trk.iter().map(|trk| trk.id).collect();
let at = place.position(&existing);
file.trk.splice(at..at, tracks);
Ok(Selection::Track {
file_id,
trk_ids: ids,
})
}
Destination::Segments(file_id, trk_id, place) => {
let segments: Vec<TrackSegment> =
+2 -8
View File
@@ -4,8 +4,6 @@ mod file;
#[cfg(test)]
pub(crate) mod fixture;
mod pattern;
#[cfg(test)]
mod routes_tests;
mod tools;
pub use apply::*;
@@ -33,15 +31,13 @@ pub enum Command<'a> {
Move(Move),
DeleteAll(DeleteAll),
DeleteWaypoint(DeleteWaypoint),
Convert(Convert),
Metadata(Metadata<'a>),
Style(Style<'a>),
NewRoute(NewRoute),
NewTrack(NewTrack),
NewTrackSegment(NewTrackSegment),
Reverse(Reverse),
RoundTrip(RoundTrip),
Reroute(Reroute<'a>),
Route(Route<'a>),
NewWaypoint(NewWaypoint<'a>),
EditWaypoint(EditWaypoint<'a>),
MoveWaypoint(MoveWaypoint),
@@ -70,15 +66,13 @@ impl Apply for Command<'_> {
Command::Move(c) => c.apply(state),
Command::DeleteAll(c) => c.apply(state),
Command::DeleteWaypoint(c) => c.apply(state),
Command::Convert(c) => c.apply(state),
Command::Metadata(c) => c.apply(state),
Command::Style(c) => c.apply(state),
Command::NewRoute(c) => c.apply(state),
Command::NewTrack(c) => c.apply(state),
Command::NewTrackSegment(c) => c.apply(state),
Command::Reverse(c) => c.apply(state),
Command::RoundTrip(c) => c.apply(state),
Command::Reroute(c) => c.apply(state),
Command::Route(c) => c.apply(state),
Command::NewWaypoint(c) => c.apply(state),
Command::EditWaypoint(c) => c.apply(state),
Command::MoveWaypoint(c) => c.apply(state),
+2 -12
View File
@@ -1,4 +1,4 @@
use crate::{File, Route, Track, TrackSegment, Waypoint};
use crate::{File, Track, TrackSegment, Waypoint};
// The trackpoints of a segment are shared chunks, so copying elements is cheap.
@@ -18,20 +18,10 @@ pub fn copy_track(track: &Track) -> Track {
}
}
/// A copy of the route and of its segment, with new ids.
pub fn copy_route(route: &Route) -> Route {
Route {
id: Default::default(),
seg: copy_segment(&route.seg),
..route.clone()
}
}
/// A copy of the file and of its routes, tracks and segments, with new ids.
/// A copy of the file and of its tracks and segments, with new ids.
pub fn copy_file(file: &File) -> File {
File {
id: Default::default(),
rte: file.rte.iter().map(copy_route).collect(),
trk: file.trk.iter().map(copy_track).collect(),
..file.clone()
}
@@ -18,7 +18,7 @@ pub fn update_segments(
let file = files
.entry(location.file_id)
.or_insert_with(|| (*state.files[&location.file_id]).clone());
f(i, file.segment_mut(location.index));
f(i, &mut file.trk[location.trk].trkseg[location.seg]);
}
for (file_id, file) in files {
state.files.insert(file_id, Rc::new(file));
@@ -31,8 +31,6 @@ mod tests {
use crate::engine::command::fixture::Fixture;
use crate::SegmentIndex;
use super::*;
fn fixture() -> (Fixture, FileId) {
@@ -51,11 +49,13 @@ mod tests {
let locations = [
SegmentLocation {
file_id: id,
index: SegmentIndex::Track { trk: 1, seg: 0 },
trk: 1,
seg: 0,
},
SegmentLocation {
file_id: id,
index: SegmentIndex::Track { trk: 0, seg: 0 },
trk: 0,
seg: 0,
},
];
let mut calls = vec![];
@@ -1,6 +1,6 @@
use std::rc::Rc;
use crate::{File, FileId, Files, Route, Selection, State, Track, TrackSegment, Waypoint};
use crate::{File, FileId, Files, Selection, State, Track, TrackSegment, Waypoint};
/// What an [`Editor`] hook did to the element it was given.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -21,19 +21,13 @@ impl Edit {
/// Independent edit of each selected element, without needing the rest of the state.
///
/// A selected file, route, track or segment is passed to the hook of its own level. By default
/// a file is forwarded to its routes and tracks, and a route or a track to its segments, so an
/// editor only overrides the level(s) it cares about (metadata: file, route and track, style:
/// route and track, reverse: segment). Waypoints are only edited when selected, never through
/// their file.
/// A selected file, track or segment is passed to the hook of its own level. By default a
/// file is forwarded to its tracks and a track to its segments, so an editor only overrides
/// the level(s) it cares about (metadata: file and track, style: track, reverse: segment).
/// Waypoints are only edited when selected, never through their file.
pub trait Editor {
fn file(&mut self, file: &mut File) -> Edit {
let routes = edit_each(&mut file.rte, |rte| self.route(rte));
routes.merge(edit_each(&mut file.trk, |trk| self.track(trk)))
}
fn route(&mut self, route: &mut Route) -> Edit {
edit_segment(self, &mut route.seg)
edit_each(&mut file.trk, |trk| self.track(trk))
}
fn track(&mut self, track: &mut Track) -> Edit {
@@ -101,7 +95,7 @@ fn edit_waypoints<E: Editor + ?Sized>(
}
}
/// Applies the editor to every selected file, route, track or segment.
/// Applies the editor to every selected file, track or segment.
pub fn update_selected<E: Editor>(state: &mut State, editor: &mut E) {
match &*state.selection {
Selection::File { file_ids } => {
@@ -109,15 +103,6 @@ pub fn update_selected<E: Editor>(state: &mut State, editor: &mut E) {
update_file(state.files, *id, |file| editor.file(file));
}
}
Selection::Route { file_id, rte_ids } => {
update_file(state.files, *file_id, |file| {
edit_where(
&mut file.rte,
|rte| rte_ids.contains(&rte.id),
|rte| editor.route(rte),
)
});
}
Selection::Track { file_id, trk_ids } => {
update_file(state.files, *file_id, |file| {
edit_where(
-724
View File
@@ -1,724 +0,0 @@
//! The commands on routes: they work as on tracks, a route being a track of a single segment.
use std::rc::Rc;
use crate::{
Apply, Clean, CleanType, Clipboard, ClipboardContent, CommandError, Convert, Crop, Delete,
Duplicate, Extract, File, FileId, LngLat, LngLatBounds, Merge, MergeType, Metadata, Move,
MoveTarget, Paste, Reverse, RouteId, SegmentIndex, Selection, Split, SplitType, Style,
engine::command::fixture::Fixture, parse,
};
/// A file with the 2 routes of `with_routes` and the 2 tracks (of 2 segments) of
/// `with_tracks_and_segments`, which is the only file and is in the order.
fn fixture() -> (Fixture, FileId) {
let read = |name: &str| {
let data = std::fs::read(format!("data/{name}.gpx")).unwrap();
parse(&data, &mut Default::default()).unwrap()
};
let mut file = read("with_tracks_and_segments");
file.rte = read("with_routes").rte;
assert_eq!((file.rte.len(), file.trk.len()), (2, 2));
let mut fx = Fixture::default();
let id = file.id;
fx.files.insert(id, Rc::new(file));
fx.order.0.push(id);
(fx, id)
}
fn file(fx: &Fixture, id: FileId) -> &File {
&fx.files[&id]
}
fn routes(fx: &Fixture, id: FileId, indices: &[usize]) -> Selection {
Selection::Route {
file_id: id,
rte_ids: indices.iter().map(|i| file(fx, id).rte[*i].id).collect(),
}
}
fn whole(id: FileId) -> Selection {
Selection::File {
file_ids: [id].into(),
}
}
fn lengths(file: &File) -> Vec<usize> {
file.segments().map(|segment| segment.len()).collect()
}
#[test]
fn test_the_segments_of_a_file_are_the_ones_of_its_routes_then_its_tracks() {
let (fx, id) = fixture();
let file = file(&fx, id);
let locations = whole(id).segment_locations(&fx.files, &fx.order.0);
let indices: Vec<SegmentIndex> = locations.iter().map(|l| l.index).collect();
assert_eq!(
indices,
[
SegmentIndex::Route(0),
SegmentIndex::Route(1),
SegmentIndex::Track { trk: 0, seg: 0 },
SegmentIndex::Track { trk: 0, seg: 1 },
SegmentIndex::Track { trk: 1, seg: 0 },
SegmentIndex::Track { trk: 1, seg: 1 },
]
);
// a selection of routes covers their segments only
let selected = routes(&fx, id, &[1]).segment_locations(&fx.files, &fx.order.0);
assert_eq!(selected.len(), 1);
assert_eq!(selected[0].segment(&fx.files).id, file.rte[1].seg.id);
}
#[test]
fn test_routes_are_selected_like_tracks() {
let (fx, id) = fixture();
let ids: Vec<RouteId> = file(&fx, id).rte.iter().map(|r| r.id).collect();
let mut selection = routes(&fx, id, &[0]);
selection.extend(routes(&fx, id, &[1]));
assert_eq!(selection, routes(&fx, id, &[0, 1]));
selection.toggle(routes(&fx, id, &[0]));
assert_eq!(selection, routes(&fx, id, &[1]));
// routes and tracks are not selected together
let track = Selection::Track {
file_id: id,
trk_ids: [file(&fx, id).trk[0].id].into(),
};
selection.extend(track.clone());
assert_eq!(selection, track);
assert_eq!(
routes(&fx, id, &[0]).all_at_level(&fx.files, &fx.order.0),
Some(routes(&fx, id, &[0, 1]))
);
assert_eq!(
routes(&fx, id, &[0]).neighbour(&fx.files, &fx.order.0, true),
Some(routes(&fx, id, &[1]))
);
assert_eq!(
routes(&fx, id, &[1]).neighbour(&fx.files, &fx.order.0, true),
None
);
assert_eq!(routes(&fx, id, &[1]).to_files(), whole(id));
let mut gone = Selection::Route {
file_id: id,
rte_ids: [ids[0], RouteId::default()].into(),
};
gone.retain_existing(&fx.files);
assert_eq!(gone, routes(&fx, id, &[0]));
}
#[test]
fn test_delete_and_duplicate_routes() {
let (mut fx, id) = fixture();
let kept = file(&fx, id).rte[1].id;
fx.selection = routes(&fx, id, &[0]);
Delete { whole_files: false }
.apply(&mut fx.state())
.unwrap();
assert_eq!(file(&fx, id).rte.len(), 1);
assert_eq!(file(&fx, id).rte[0].id, kept);
assert_eq!(file(&fx, id).trk.len(), 2);
assert_eq!(fx.selection, whole(id));
fx.selection = routes(&fx, id, &[0]);
Duplicate.apply(&mut fx.state()).unwrap();
let file = file(&fx, id);
assert_eq!(file.rte.len(), 2);
assert_ne!(file.rte[1].id, kept);
assert_ne!(file.rte[1].seg.id, file.rte[0].seg.id);
assert_eq!(file.rte[1].info, file.rte[0].info);
assert_eq!(
fx.selection,
Selection::Route {
file_id: id,
rte_ids: [file.rte[1].id].into()
}
);
}
#[test]
fn test_metadata_and_style_of_routes() {
let (mut fx, id) = fixture();
fx.selection = routes(&fx, id, &[1]);
Metadata {
name: "renamed",
desc: "about",
}
.apply(&mut fx.state())
.unwrap();
Style {
color: Some("00ff00"),
opacity: None,
width: Some(3.0),
}
.apply(&mut fx.state())
.unwrap();
let file = file(&fx, id);
let info = &file.rte[1].info;
assert_eq!(info.name.as_deref(), Some("renamed"));
assert_eq!(info.desc.as_deref(), Some("about"));
assert_eq!(info.color.as_deref(), Some("00ff00"));
assert_eq!(info.width, Some(3.0));
assert_ne!(file.rte[0].info.name.as_deref(), Some("renamed"));
// the style of a file is the one of its routes and tracks
fx.selection = whole(id);
Style {
color: Some("ff0000"),
opacity: None,
width: None,
}
.apply(&mut fx.state())
.unwrap();
let file = &fx.files[&id];
assert!(
file.rte
.iter()
.map(|r| &r.info)
.chain(file.trk.iter().map(|t| &t.info))
.all(|info| info.color.as_deref() == Some("ff0000"))
);
}
#[test]
fn test_copy_and_paste_routes() {
let (mut fx, id) = fixture();
let copied = file(&fx, id).rte[0].clone();
fx.clipboard = Clipboard::new(&routes(&fx, id, &[0]), &fx.files, &fx.order.0, false);
assert!(matches!(
fx.clipboard.as_ref().unwrap().content,
ClipboardContent::Routes(_)
));
// after the selected route
fx.selection = routes(&fx, id, &[1]);
Paste.apply(&mut fx.state()).unwrap();
let file = file(&fx, id);
assert_eq!(file.rte.len(), 3);
assert_ne!(file.rte[2].id, copied.id);
assert_eq!(file.rte[2].seg.len(), copied.seg.len());
assert!(
matches!(&fx.selection, Selection::Route { rte_ids, .. } if rte_ids.contains(&file.rte[2].id))
);
// nothing selected: a new file, named like the route
fx.selection = Selection::Empty;
Paste.apply(&mut fx.state()).unwrap();
assert_eq!(fx.order.0.len(), 2);
let new = &fx.files[&fx.order.0[1]];
assert_eq!(new.rte.len(), 1);
assert!(new.trk.is_empty());
assert_eq!(Some(&new.info.name), copied.info.name.as_ref());
// a track selected: among the routes of its file
fx.selection = Selection::Track {
file_id: id,
trk_ids: [fx.files[&id].trk[0].id].into(),
};
Paste.apply(&mut fx.state()).unwrap();
assert_eq!(fx.files[&id].rte.len(), 4);
// segments do not go in a route, but become routes next to it
let file = &fx.files[&id];
let track = &file.trk[0];
fx.clipboard = Clipboard::new(
&Selection::TrackSegment {
file_id: id,
trk_id: track.id,
trkseg_ids: [track.trkseg[1].id].into(),
},
&fx.files,
&fx.order.0,
false,
);
fx.selection = routes(&fx, id, &[0]);
Paste.apply(&mut fx.state()).unwrap();
let file = &fx.files[&id];
assert_eq!(file.rte.len(), 5);
assert_eq!(file.rte[1].seg.len(), file.trk[0].trkseg[1].len());
}
#[test]
fn test_cut_tracks_pasted_on_a_route_go_first_among_the_tracks() {
let (mut fx, id) = fixture();
let moved = file(&fx, id).trk[1].id;
fx.clipboard = Clipboard::new(
&Selection::Track {
file_id: id,
trk_ids: [moved].into(),
},
&fx.files,
&fx.order.0,
true,
);
fx.selection = routes(&fx, id, &[0]);
Paste.apply(&mut fx.state()).unwrap();
let file = file(&fx, id);
assert_eq!(file.trk.len(), 2);
assert_eq!(file.trk[0].id, moved);
assert_eq!(file.rte.len(), 2);
}
#[test]
fn test_move_routes() {
let (mut fx, id) = fixture();
let ids: Vec<RouteId> = file(&fx, id).rte.iter().map(|r| r.id).collect();
Move {
what: routes(&fx, id, &[1]),
to: MoveTarget::Routes {
file_id: id,
index: 0,
},
}
.apply(&mut fx.state())
.unwrap();
let order: Vec<RouteId> = file(&fx, id).rte.iter().map(|r| r.id).collect();
assert_eq!(order, [ids[1], ids[0]]);
// to the files: a file of its own
Move {
what: routes(&fx, id, &[0]),
to: MoveTarget::Files { index: 1 },
}
.apply(&mut fx.state())
.unwrap();
assert_eq!(file(&fx, id).rte.len(), 1);
let new = &fx.files[&fx.order.0[1]];
assert_eq!(new.rte[0].id, ids[1]);
// a segment moved among the routes becomes one
let track = &file(&fx, id).trk[0];
let segment = track.trkseg[0].id;
Move {
what: Selection::TrackSegment {
file_id: id,
trk_id: track.id,
trkseg_ids: [segment].into(),
},
to: MoveTarget::Routes {
file_id: id,
index: 1,
},
}
.apply(&mut fx.state())
.unwrap();
let file = file(&fx, id);
assert_eq!(file.rte[1].seg.id, segment);
assert_eq!(file.trk[0].trkseg.len(), 1);
}
#[test]
fn test_routes_and_tracks_moved_among_each_other_keep_their_kind() {
let (mut fx, id) = fixture();
let route = file(&fx, id).rte[0].id;
let track = file(&fx, id).trk[1].id;
// a route among the tracks: after the other routes, which come first
Move {
what: routes(&fx, id, &[0]),
to: MoveTarget::Tracks {
file_id: id,
index: 1,
},
}
.apply(&mut fx.state())
.unwrap();
let moved = file(&fx, id);
assert_eq!((moved.rte.len(), moved.trk.len()), (2, 2));
assert_eq!(moved.rte[1].id, route);
assert_eq!(
fx.selection,
Selection::Route {
file_id: id,
rte_ids: [route].into()
}
);
// a track among the routes: before the other tracks, which come after the routes
Move {
what: Selection::Track {
file_id: id,
trk_ids: [track].into(),
},
to: MoveTarget::Routes {
file_id: id,
index: 0,
},
}
.apply(&mut fx.state())
.unwrap();
let moved = file(&fx, id);
assert_eq!((moved.rte.len(), moved.trk.len()), (2, 2));
assert_eq!(moved.trk[0].id, track);
// and copied routes pasted on a track stay routes
fx.clipboard = Clipboard::new(&routes(&fx, id, &[0]), &fx.files, &fx.order.0, false);
fx.selection = Selection::Track {
file_id: id,
trk_ids: [track].into(),
};
Paste.apply(&mut fx.state()).unwrap();
let pasted = file(&fx, id);
assert_eq!((pasted.rte.len(), pasted.trk.len()), (3, 2));
}
#[test]
fn test_merge_routes() {
let (mut fx, id) = fixture();
let before = lengths(file(&fx, id));
let first = file(&fx, id).rte[0].id;
fx.selection = routes(&fx, id, &[0, 1]);
let merge = |type_| Merge {
type_,
remove_gaps: false,
keep_originals: false,
};
assert_eq!(
merge(MergeType::Group).apply(&mut fx.state()),
Err(CommandError::NothingToDo)
);
merge(MergeType::Connect).apply(&mut fx.state()).unwrap();
let file = file(&fx, id);
assert_eq!(file.rte.len(), 1);
assert_eq!(file.rte[0].id, first);
assert_eq!(file.rte[0].seg.len(), before[0] + before[1]);
assert_eq!(file.trk.len(), 2);
}
#[test]
fn test_merge_files_with_routes() {
let (mut fx, id) = fixture();
let other = File {
rte: file(&fx, id).rte.iter().map(crate::copy_route).collect(),
..File::default()
};
let other_id = other.id;
fx.files.insert(other_id, Rc::new(other));
fx.order.0.push(other_id);
let total: usize = lengths(file(&fx, id)).iter().sum::<usize>()
+ lengths(&fx.files[&other_id]).iter().sum::<usize>();
let mut grouped = Fixture {
files: fx.files.clone(),
order: fx.order.clone(),
selection: Selection::File {
file_ids: [id, other_id].into(),
},
..Default::default()
};
Merge {
type_: MergeType::Group,
remove_gaps: false,
keep_originals: false,
}
.apply(&mut grouped.state())
.unwrap();
let merged = &grouped.files[&id];
assert_eq!((merged.rte.len(), merged.trk.len()), (4, 2));
assert!(!grouped.files.contains_key(&other_id));
// connected in the first route, which comes first
fx.selection = Selection::File {
file_ids: [id, other_id].into(),
};
Merge {
type_: MergeType::Connect,
remove_gaps: false,
keep_originals: false,
}
.apply(&mut fx.state())
.unwrap();
let merged = &fx.files[&id];
assert_eq!((merged.rte.len(), merged.trk.len()), (1, 0));
assert_eq!(merged.rte[0].seg.len(), total);
}
#[test]
fn test_extract_a_file_with_routes() {
let (mut fx, id) = fixture();
let names: Vec<_> = file(&fx, id)
.rte
.iter()
.map(|r| r.info.name.clone().unwrap())
.collect();
fx.selection = whole(id);
Extract {
keep_originals: false,
}
.apply(&mut fx.state())
.unwrap();
// one file per route and one per track
assert_eq!(fx.order.0.len(), 4);
let files: Vec<&File> = fx.order.0.iter().map(|id| &*fx.files[id]).collect();
for (file, name) in files.iter().zip(&names) {
assert_eq!((file.rte.len(), file.trk.len()), (1, 0));
assert_eq!(&file.info.name, name);
}
for file in &files[2..] {
assert_eq!((file.rte.len(), file.trk.len()), (0, 2));
}
// a route has nothing to extract
let (mut fx, id) = fixture();
fx.selection = routes(&fx, id, &[0]);
assert_eq!(
Extract {
keep_originals: false
}
.apply(&mut fx.state()),
Err(CommandError::NothingToDo)
);
}
#[test]
fn test_split_a_route() {
let (mut fx, id) = fixture();
let before = file(&fx, id).rte[1].clone();
fx.selection = routes(&fx, id, &[1]);
Split {
at: 10,
split_type: SplitType::Routes,
keep_originals: false,
}
.apply(&mut fx.state())
.unwrap();
// two routes, which share the trackpoint
let split = file(&fx, id);
assert_eq!(split.rte.len(), 3);
assert_eq!(split.rte[1].id, before.id);
assert_ne!(split.rte[2].id, before.id);
assert_eq!(split.rte[1].seg.len(), 11);
assert_eq!(split.rte[2].seg.len(), before.seg.len() - 10);
assert_eq!(split.rte[2].info, before.info);
// a route is not a track nor a segment, and the other way around
let (mut fx, id) = fixture();
fx.selection = whole(id);
let segment_start = lengths(file(&fx, id))[..2].iter().sum::<usize>() as u32;
for (at, split_type) in [
(10, SplitType::Tracks),
(10, SplitType::Segments),
(segment_start + 10, SplitType::Routes),
] {
assert_eq!(
Split {
at,
split_type,
keep_originals: false,
}
.apply(&mut fx.state()),
Err(CommandError::NothingToDo)
);
}
assert_eq!(file(&fx, id).rte.len(), 2);
// into two files: the following routes and the tracks go to the second one
let (mut fx, id) = fixture();
let first_len = file(&fx, id).rte[0].seg.len();
fx.selection = whole(id);
Split {
at: 5,
split_type: SplitType::Files,
keep_originals: false,
}
.apply(&mut fx.state())
.unwrap();
assert_eq!(fx.order.0.len(), 2);
let (a, b) = (&fx.files[&fx.order.0[0]], &fx.files[&fx.order.0[1]]);
assert_eq!(a.id, id);
assert_eq!((a.rte.len(), a.trk.len()), (1, 0));
assert_eq!(a.rte[0].seg.len(), 6);
assert_eq!((b.rte.len(), b.trk.len()), (2, 2));
assert_eq!(b.rte[0].seg.len(), first_len - 5);
}
#[test]
fn test_crop_removes_the_routes_left_without_trackpoints() {
let (mut fx, id) = fixture();
let len = lengths(file(&fx, id));
fx.selection = whole(id);
// the second route only
let start = len[0] as u32;
Crop {
start,
end: start + len[1] as u32 - 1,
}
.apply(&mut fx.state())
.unwrap();
let file = file(&fx, id);
assert_eq!((file.rte.len(), file.trk.len()), (1, 0));
assert_eq!(file.rte[0].seg.len(), len[1]);
}
#[test]
fn test_clean_removes_the_routes_left_without_trackpoints() {
let (mut fx, id) = fixture();
fx.selection = routes(&fx, id, &[0]);
let everywhere = LngLatBounds {
sw: LngLat {
lng: -180.0,
lat: -90.0,
},
ne: LngLat {
lng: 180.0,
lat: 90.0,
},
};
Clean {
bounds: everywhere,
type_: CleanType::Inside,
trkpt: true,
wpt: false,
}
.apply(&mut fx.state())
.unwrap();
assert_eq!(file(&fx, id).rte.len(), 1);
assert_eq!(fx.selection, whole(id));
}
#[test]
fn test_reverse_a_route_and_the_routes_of_a_file() {
let (mut fx, id) = fixture();
let before = file(&fx, id).clone();
fx.selection = routes(&fx, id, &[0]);
Reverse.apply(&mut fx.state()).unwrap();
let route = &file(&fx, id).rte[0].seg;
let original = &before.rte[0].seg;
assert_eq!(
route[0].coordinates.lat,
original[original.len() - 1].coordinates.lat
);
assert_eq!(file(&fx, id).rte[1].seg.rev_id, before.rte[1].seg.rev_id);
let (mut fx, id) = fixture();
let before = file(&fx, id).clone();
fx.selection = whole(id);
Reverse.apply(&mut fx.state()).unwrap();
let file = file(&fx, id);
// the routes are in the opposite order, and still before the tracks
assert_eq!(file.rte[0].id, before.rte[1].id);
assert_eq!(file.trk[0].id, before.trk[1].id);
}
#[test]
fn test_convert_routes_to_tracks_and_back() {
let (mut fx, id) = fixture();
let before = file(&fx, id).clone();
// a route becomes a track, first among the tracks, with its segment and its information
fx.selection = routes(&fx, id, &[1]);
Convert.apply(&mut fx.state()).unwrap();
let converted = file(&fx, id);
assert_eq!((converted.rte.len(), converted.trk.len()), (1, 3));
assert_eq!(converted.trk[0].info, before.rte[1].info);
assert_eq!(converted.trk[0].trkseg.len(), 1);
assert_eq!(converted.trk[0].trkseg[0].id, before.rte[1].seg.id);
assert_eq!(
fx.selection,
Selection::Track {
file_id: id,
trk_ids: [converted.trk[0].id].into()
}
);
// and back: a route again, after the other routes
Convert.apply(&mut fx.state()).unwrap();
let back = file(&fx, id);
assert_eq!((back.rte.len(), back.trk.len()), (2, 2));
assert_eq!(back.rte[1].seg.id, before.rte[1].seg.id);
assert_eq!(back.rte[1].info, before.rte[1].info);
assert!(
matches!(&fx.selection, Selection::Route { rte_ids, .. } if rte_ids.contains(&back.rte[1].id))
);
}
#[test]
fn test_convert_a_track_to_one_route_per_segment() {
let (mut fx, id) = fixture();
let track = file(&fx, id).trk[0].clone();
assert_eq!(track.trkseg.len(), 2);
fx.selection = Selection::Track {
file_id: id,
trk_ids: [track.id].into(),
};
Convert.apply(&mut fx.state()).unwrap();
let converted = file(&fx, id);
assert_eq!((converted.rte.len(), converted.trk.len()), (4, 1));
for (route, segment) in converted.rte[2..].iter().zip(&track.trkseg) {
assert_eq!(route.seg.id, segment.id);
assert_eq!(route.info, track.info);
}
assert!(matches!(&fx.selection, Selection::Route { rte_ids, .. } if rte_ids.len() == 2));
}
#[test]
fn test_convert_segments_to_routes_keeps_their_track() {
let (mut fx, id) = fixture();
let track = file(&fx, id).trk[1].clone();
fx.selection = Selection::TrackSegment {
file_id: id,
trk_id: track.id,
trkseg_ids: [track.trkseg[0].id, track.trkseg[1].id].into(),
};
Convert.apply(&mut fx.state()).unwrap();
let converted = file(&fx, id);
assert_eq!((converted.rte.len(), converted.trk.len()), (4, 2));
assert!(converted.trk[1].trkseg.is_empty());
assert_eq!(converted.rte[2].seg.id, track.trkseg[0].id);
// nothing to convert otherwise
for selection in [
whole(id),
Selection::Empty,
Selection::Waypoints { file_id: id },
] {
fx.selection = selection;
assert_eq!(
Convert.apply(&mut fx.state()),
Err(CommandError::NothingToDo)
);
}
}
#[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)
);
}
@@ -24,7 +24,7 @@ impl Apply for ChangeLoopStart {
let index = self.index as usize;
let target = find_target(state, index, index)?.ok_or(CommandError::NothingToDo)?;
let mut file = (*state.files[&target.location.file_id]).clone();
let segment = file.segment_mut(target.location.index);
let segment = &mut file.trk[target.location.trk].trkseg[target.location.seg];
let (start, len) = (target.start, segment.len());
if start == 0 || start >= len {
// it already is the start, or it is not a trackpoint
+21 -44
View File
@@ -13,8 +13,8 @@ pub enum CleanType {
}
/// Removes the trackpoints and/or waypoints of the selection lying inside (or outside) a
/// rectangle. A selected file cleans its routes, its tracks and its waypoints, a selected route,
/// track or segment only trackpoints, selected waypoints only waypoints.
/// rectangle. A selected file cleans its tracks and its waypoints, a selected track or segment
/// only trackpoints, selected waypoints only waypoints.
#[derive(Debug)]
pub struct Clean {
pub bounds: LngLatBounds,
@@ -85,11 +85,6 @@ struct Cleaner<'a> {
impl Editor for Cleaner<'_> {
fn file(&mut self, file: &mut File) -> Edit {
let mut edit = Edit::Unchanged;
for rte in &mut file.rte {
if self.route(rte) == Edit::Changed {
edit = Edit::Changed;
}
}
for trk in &mut file.trk {
if self.track(trk) == Edit::Changed {
edit = Edit::Changed;
@@ -129,27 +124,36 @@ impl Editor for Cleaner<'_> {
}
}
/// Removes what the clean left empty: the emptied segments, the routes of these segments and the
/// tracks that lost all their segments. A file is never removed, even if nothing is left in it: it stays, empty. The
/// selection falls back to the closest element still existing.
/// Removes what the clean left empty: the emptied segments, the tracks that lost all their
/// segments and the files that lost something and have nothing left. The selection falls back
/// to the closest element still existing.
fn prune(state: &mut State, emptied: &HashSet<TrackSegmentId>, wpt_files: &HashSet<FileId>) {
let ids: Vec<FileId> = state
.files
.iter()
.filter(|(id, file)| {
wpt_files.contains(id) || file.segments().any(|seg| emptied.contains(&seg.id))
wpt_files.contains(id)
|| file
.trk
.iter()
.any(|trk| trk.trkseg.iter().any(|seg| emptied.contains(&seg.id)))
})
.map(|(id, _)| *id)
.collect();
for id in ids {
let mut file = (*state.files[&id]).clone();
file.rte.retain(|rte| !emptied.contains(&rte.seg.id));
let lost_something = !emptied.is_empty() || wpt_files.contains(&id);
file.trk.retain_mut(|trk| {
let len = trk.trkseg.len();
trk.trkseg.retain(|seg| !emptied.contains(&seg.id));
trk.trkseg.len() == len || !trk.trkseg.is_empty()
});
state.files.insert(id, Rc::new(file));
if lost_something && file.trk.is_empty() && file.wpt.is_empty() {
state.files.remove(&id);
state.order.0.retain(|f| *f != id);
} else {
state.files.insert(id, Rc::new(file));
}
}
*state.selection = fixed_selection(state);
}
@@ -169,27 +173,6 @@ fn fixed_selection(state: &State) -> Selection {
Selection::File { file_ids }
}
}
Selection::Route { file_id, rte_ids } => {
let Some(file) = files.get(file_id) else {
return Selection::Empty;
};
let rte_ids: HashSet<_> = file
.rte
.iter()
.map(|rte| rte.id)
.filter(|id| rte_ids.contains(id))
.collect();
if rte_ids.is_empty() {
Selection::File {
file_ids: [*file_id].into(),
}
} else {
Selection::Route {
file_id: *file_id,
rte_ids,
}
}
}
Selection::Track { file_id, trk_ids } => {
let Some(file) = files.get(file_id) else {
return Selection::Empty;
@@ -314,16 +297,10 @@ mod tests {
.apply(&mut fx.state())
.unwrap();
assert_eq!(count(&fx, id), 0);
// nothing is left in the file, which stays and is still selected
let file = &fx.files[&id];
assert!(file.trk.is_empty() && file.wpt.is_empty());
assert_eq!(fx.order.0, [id]);
assert_eq!(
fx.selection,
Selection::File {
file_ids: HashSet::from([id])
}
);
// nothing is left of the file
assert!(!fx.files.contains_key(&id));
assert!(fx.order.0.is_empty());
assert_eq!(fx.selection, Selection::Empty);
}
#[test]
+8 -9
View File
@@ -11,9 +11,9 @@ use crate::{
/// Keeps the trackpoints `start` to `end` (both included) of the selection, which are counted
/// over its segments one after the other (as in the `RoutingBuffer`), and removes the others.
///
/// The segments that have no trackpoint left are removed, and so are the routes of these segments.
/// So are the tracks that have no segment left, if tracks or files are selected (not if only
/// segments are), and the files that have no trackpoint left, if files are selected. A range that goes past the last trackpoint stops at it.
/// The segments that have no trackpoint left are removed. So are the tracks that have no segment
/// left, if tracks or files are selected (not if only segments are), and the files that have no
/// trackpoint left, if files are selected. A range that goes past the last trackpoint stops at it.
#[derive(Debug)]
pub struct Crop {
pub start: u32,
@@ -43,7 +43,8 @@ impl Apply for Crop {
.segment_locations(state.files, &state.order.0)
.into_iter()
.map(|location| {
let len = location.segment(state.files).len();
let len =
state.files[&location.file_id].trk[location.trk].trkseg[location.seg].len();
let keep = (len > 0 && start < offset + len && end >= offset)
.then(|| (start.saturating_sub(offset), (end - offset).min(len - 1)));
offset += len;
@@ -72,14 +73,14 @@ impl Apply for Crop {
let mut removed: HashSet<TrackSegmentId> = HashSet::new();
let mut had_points: HashSet<FileId> = HashSet::new();
for plan in &plans {
let SegmentLocation { file_id, index } = plan.location;
let SegmentLocation { file_id, trk, seg } = plan.location;
let file = files
.entry(file_id)
.or_insert_with(|| (*state.files[&file_id]).clone());
if plan.len > 0 {
had_points.insert(file_id);
}
let segment = file.segment_mut(index);
let segment = &mut file.trk[trk].trkseg[seg];
match plan.keep {
None => {
removed.insert(segment.id);
@@ -90,8 +91,6 @@ impl Apply for Crop {
let mut gone: Vec<FileId> = vec![];
for (file_id, file) in files.iter_mut() {
// a route has its segment, or is not there
file.rte.retain(|route| !removed.contains(&route.seg.id));
// the tracks that lost segments
let touched: Vec<bool> = file
.trk
@@ -109,7 +108,7 @@ impl Apply for Crop {
file.trk
.retain(|track| !(touched.next().unwrap() && track.trkseg.is_empty()));
}
if prune_files && file.has_no_path() && had_points.contains(file_id) {
if prune_files && file.trk.is_empty() && had_points.contains(file_id) {
gone.push(*file_id);
}
}
+3 -1
View File
@@ -14,7 +14,9 @@ impl Apply for Elevation<'_> {
.segment_locations(state.files, &state.order.0);
let count: usize = locations
.iter()
.map(|location| location.segment(state.files).len())
.map(|location| {
state.files[&location.file_id].trk[location.trk].trkseg[location.seg].len()
})
.sum();
if count == 0 {
return Err(CommandError::NothingToDo);
+56 -62
View File
@@ -1,23 +1,22 @@
use std::{collections::HashSet, rc::Rc};
use crate::{
Apply, CommandError, File, FileId, LngLat, LngLatBounds, Route, Selection, State, Track,
TrackId, TrackSegment, Waypoint, Waypoints, copy_file, copy_waypoint, crossarc_lnglat,
distance,
Apply, CommandError, File, FileId, LngLat, LngLatBounds, Selection, State, Track, TrackId,
TrackSegment, Waypoint, Waypoints, copy_file, copy_waypoint, crossarc_lnglat, distance,
};
/// Splits the selected elements that are made of several segments into elements that have one
/// each:
///
/// - files: a file with several routes and tracks becomes one file per route and per track, in
/// which the track is split into one track per segment. A file with a single track becomes one
/// file per segment. The new files are in the place of the file, which goes, and are selected.
/// They are named after the route or track, or the file, and numbered. The waypoints go to the files that have the segments
/// - files: a file with several tracks becomes one file per track, in which the track is split
/// into one track per segment. A file with a single track becomes one file per segment. The new
/// files are in the place of the file, which goes, and are selected. They are named after the
/// track, or the file, and numbered. The waypoints go to the files that have the segments
/// closest to them (to the first file if the file has no trackpoint).
/// - tracks: each selected track is replaced by one track per segment, which are selected. They
/// are named after the track and numbered.
///
/// What has a single segment is left as it is, which routes always are. There is nothing to do if nothing was changed.
/// What has a single segment is left as it is. There is nothing to do if nothing was changed.
///
/// With `keep_originals`, the files that are extracted stay where they are, and the new files come
/// right after each of them, and only the new files are selected. Extracting
@@ -47,7 +46,8 @@ fn extract_files(
let mut extracted: Vec<(FileId, Vec<File>)> = vec![];
for id in state.order.0.iter().filter(|id| file_ids.contains(id)) {
let file = &state.files[id];
if file.segments().count() > 1 {
let segments: usize = file.trk.iter().map(|track| track.trkseg.len()).sum();
if segments > 1 {
let mut files = extract_file(file);
if keep_originals {
// the tracks and segments are the ones of the file, which stays: they need new ids
@@ -95,65 +95,60 @@ fn extract_files(
/// The files that a file with several segments becomes.
fn extract_file(file: &File) -> Vec<File> {
// for each new file: its routes, its tracks and its name, and the segments that go with it
// for each new file: its tracks and its name, and the segments that go with it
struct Part {
routes: Vec<Route>,
tracks: Vec<Track>,
name: String,
}
let name = |name: &Option<String>, i: usize| {
name.clone()
.unwrap_or_else(|| format!("{} ({})", file.info.name, i + 1))
};
let (parts, owner): (Vec<Part>, Vec<usize>) =
if file.rte.len() + file.trk.len() > 1 {
// one file per route and per track, the segments of a track follow it
let routes = file.rte.iter().enumerate().map(|(i, route)| Part {
routes: vec![route.clone()],
tracks: vec![],
name: name(&route.info.name, i),
});
let tracks = file.trk.iter().enumerate().map(|(i, track)| Part {
routes: vec![],
let (parts, owner): (Vec<Part>, Vec<usize>) = if file.trk.len() > 1 {
// one file per track, the segments of a track follow it
let parts = file
.trk
.iter()
.enumerate()
.map(|(i, track)| Part {
tracks: split_track(track),
name: name(&track.info.name, file.rte.len() + i),
});
let parts = routes.chain(tracks).collect();
let owner =
(0..file.rte.len())
.chain(file.trk.iter().enumerate().flat_map(|(i, track)| {
track.trkseg.iter().map(move |_| file.rte.len() + i)
}))
.collect();
(parts, owner)
} else {
// one file per segment
let track = &file.trk[0];
let base = track
.info
.name
.clone()
.unwrap_or_else(|| file.info.name.clone());
let parts = track
.trkseg
.iter()
.enumerate()
.map(|(i, segment)| Part {
routes: vec![],
tracks: vec![Track {
id: if i == 0 { track.id } else { Default::default() },
trkseg: vec![segment.clone()],
..track.clone()
}],
name: format!("{base} ({})", i + 1),
})
.collect();
let owner = (0..track.trkseg.len()).collect();
(parts, owner)
};
name: track
.info
.name
.clone()
.unwrap_or_else(|| format!("{} ({})", file.info.name, i + 1)),
})
.collect();
let owner = file
.trk
.iter()
.enumerate()
.flat_map(|(i, track)| track.trkseg.iter().map(move |_| i))
.collect();
(parts, owner)
} else {
// one file per segment
let track = &file.trk[0];
let base = track
.info
.name
.clone()
.unwrap_or_else(|| file.info.name.clone());
let parts = track
.trkseg
.iter()
.enumerate()
.map(|(i, segment)| Part {
tracks: vec![Track {
id: if i == 0 { track.id } else { Default::default() },
trkseg: vec![segment.clone()],
..track.clone()
}],
name: format!("{base} ({})", i + 1),
})
.collect();
let owner = (0..track.trkseg.len()).collect();
(parts, owner)
};
// the waypoints go with the segments that are the closest to them
let segments: Vec<&TrackSegment> = file.segments().collect();
let segments: Vec<&TrackSegment> = file.trk.iter().flat_map(|track| &track.trkseg).collect();
let mut waypoints: Vec<Vec<Waypoint>> = vec![vec![]; parts.len()];
for waypoint in file.wpt.iter() {
let mut owners: Vec<usize> = closest_segments(&segments, waypoint.coordinates)
@@ -181,7 +176,6 @@ fn extract_file(file: &File) -> Vec<File> {
.map(|(part, waypoints)| {
let mut extracted = File {
id: Default::default(),
rte: part.routes,
trk: part.tracks,
wpt: Waypoints::default(),
..file.clone()
@@ -39,7 +39,7 @@ impl Apply for InsertAnchor {
.selection
.segment_locations(state.files, &state.order.0)
{
let segment = location.segment(state.files);
let segment = &state.files[&location.file_id].trk[location.trk].trkseg[location.seg];
let mut points = segment.iter();
let Some(mut previous) = points.next() else {
continue;
@@ -81,7 +81,7 @@ impl Apply for InsertAnchor {
let closest = closest.ok_or(CommandError::NothingToDo)?;
let mut file = (*state.files[&closest.location.file_id]).clone();
let segment = file.segment_mut(closest.location.index);
let segment = &mut file.trk[closest.location.trk].trkseg[closest.location.seg];
let before = closest.before;
// on a trackpoint already, if it is closer than `SNAP_DISTANCE`
let snapped = if segment.len() == 1 {
+15 -63
View File
@@ -1,9 +1,8 @@
use std::{collections::HashSet, rc::Rc};
use crate::{
Apply, CommandError, FileId, GlobalStatistics, Route, RouteId, Selection, State, Statistics,
Track, TrackId, TrackSegment, TrackSegmentId, Waypoint, Waypoints, copy_route, copy_track,
replace_trackpoints,
Apply, CommandError, FileId, GlobalStatistics, Selection, State, Statistics, Track, TrackId,
TrackSegment, TrackSegmentId, Waypoint, Waypoints, copy_track, replace_trackpoints,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)]
@@ -17,16 +16,13 @@ pub enum MergeType {
/// Merges the selected elements into the first of them:
///
/// - files: the other files are deleted. The routes and tracks of all of them are in the first
/// file, as they are with `Group`, or all connected in the first of them (a route or a track,
/// the routes of a file coming before its tracks) with `Connect`. The waypoints of
/// - files: the other files are deleted. The tracks of all of them are in the first file, as
/// they are with `Group`, or all connected in the first track with `Connect`. The waypoints of
/// all of them are in the first file too, except the ones that are the same. With
/// `keep_originals`, no file is deleted nor changed: the result is a new file (with the info of
/// the first one and new ids), which comes right after the last of the files and is selected.
/// - tracks of a file: the first track gets their segments, as they are with `Group`, or all
/// connected in one segment with `Connect`. The other tracks are removed.
/// - routes of a file: the first route gets their trackpoints, all connected with `Connect`, and
/// the other routes are removed. A route has a single segment, so there is nothing to `Group`.
/// - segments of a track: they are all connected in a segment at the position of the first one
/// with `Connect`. With `Group` they are put one after the other, at that position.
///
@@ -48,7 +44,6 @@ impl Apply for Merge {
let selection = state.selection.clone();
match &selection {
Selection::File { file_ids } => self.merge_files(state, file_ids),
Selection::Route { file_id, rte_ids } => self.merge_routes(state, *file_id, rte_ids),
Selection::Track { file_id, trk_ids } => self.merge_tracks(state, *file_id, trk_ids),
Selection::TrackSegment {
file_id,
@@ -82,26 +77,21 @@ impl Merge {
return Err(CommandError::NothingToDo);
};
let mut routes: Vec<Route> = vec![];
let mut tracks: Vec<Track> = vec![];
let mut segments: Vec<TrackSegment> = vec![];
let mut waypoints: Vec<Waypoint> = vec![];
for id in &ordered {
let file = &state.files[id];
routes.extend(file.rte.iter().cloned());
tracks.extend(file.trk.iter().cloned());
segments.extend(file.segments().cloned());
for waypoint in file.wpt.iter() {
if !waypoints.iter().any(|kept| kept.same_content(waypoint)) {
waypoints.push(waypoint.clone());
}
}
}
// the first route or track, which holds the connected segment
let first_is_route = ordered.iter().find_map(|id| {
let file = &state.files[id];
(!file.has_no_path()).then(|| !file.rte.is_empty())
});
let segments: Vec<TrackSegment> = tracks
.iter()
.flat_map(|track| track.trkseg.iter().cloned())
.collect();
match self.type_ {
MergeType::Group if ordered.len() == 1 => return Err(CommandError::NothingToDo),
@@ -109,35 +99,24 @@ impl Merge {
return Err(CommandError::NothingToDo);
}
MergeType::Connect if !segments.is_empty() => {
// a single route or track, which is the first one, with the connected segment
// a single track, which is the first one, with the connected segment
let merged = connect(&segments, segments[0].id, self.remove_gaps);
if first_is_route == Some(true) {
let first = Route {
seg: merged,
..routes[0].clone()
};
(routes, tracks) = (vec![first], vec![]);
} else {
let first = Track {
trkseg: vec![merged],
..tracks[0].clone()
};
(routes, tracks) = (vec![], vec![first]);
}
let first = Track {
trkseg: vec![merged],
..tracks[0].clone()
};
tracks = vec![first];
}
_ => {}
}
let mut target = (*state.files[&target_id]).clone();
target.rte = routes;
target.trk = tracks;
target.wpt = Waypoints::default();
target.wpt.insert_at(0, waypoints);
if self.keep_originals {
// a new file, whose routes, tracks and segments do not share their ids with the
// originals
// a new file, whose tracks and segments do not share their ids with the originals
target.id = Default::default();
target.rte = target.rte.iter().map(copy_route).collect();
target.trk = target.trk.iter().map(copy_track).collect();
let at = state
.order
@@ -160,33 +139,6 @@ impl Merge {
Ok(())
}
fn merge_routes(
&self,
state: &mut State,
file_id: FileId,
rte_ids: &HashSet<RouteId>,
) -> Result<(), CommandError> {
let file = state.files.get(&file_id).ok_or(CommandError::NothingToDo)?;
let selected: Vec<usize> = (0..file.rte.len())
.filter(|i| rte_ids.contains(&file.rte[*i].id))
.collect();
if selected.len() < 2 || self.type_ == MergeType::Group {
return Err(CommandError::NothingToDo);
}
let first = selected[0];
let segments: Vec<TrackSegment> =
selected.iter().map(|i| file.rte[*i].seg.clone()).collect();
let mut file = (**file).clone();
file.rte[first].seg = connect(&segments, segments[0].id, self.remove_gaps);
let mut index = 0;
file.rte.retain(|_| {
index += 1;
!selected[1..].contains(&(index - 1))
});
state.files.insert(file_id, Rc::new(file));
Ok(())
}
fn merge_tracks(
&self,
state: &mut State,
@@ -58,8 +58,7 @@ impl Apply for NewWaypoint<'_> {
.filter(|id| file_ids.contains(id))
.copied()
.collect(),
Selection::Route { file_id, .. }
| Selection::Track { file_id, .. }
Selection::Track { file_id, .. }
| Selection::TrackSegment { file_id, .. }
| Selection::Waypoints { file_id }
| Selection::Waypoint { file_id, .. } => vec![*file_id],
@@ -119,14 +118,12 @@ mod tests {
New {
name: "a",
trackpoint: None,
route: false,
}
.apply(&mut fx.state())
.unwrap();
New {
name: "b",
trackpoint: None,
route: false,
}
.apply(&mut fx.state())
.unwrap();
@@ -172,7 +169,6 @@ mod tests {
New {
name: "a",
trackpoint: None,
route: false,
}
.apply(&mut fx.state())
.unwrap();
@@ -200,7 +196,6 @@ mod tests {
New {
name,
trackpoint: None,
route: false,
}
.apply(&mut fx.state())
.unwrap();
@@ -239,7 +234,6 @@ mod tests {
New {
name: "a",
trackpoint: None,
route: false,
}
.apply(&mut fx.state())
.unwrap();
@@ -256,7 +250,6 @@ mod tests {
New {
name: "a",
trackpoint: None,
route: false,
}
.apply(&mut fx.state())
.unwrap();
+1 -1
View File
@@ -23,7 +23,7 @@ impl Apply for Reduce {
let mut changed = vec![];
let mut kept_points = vec![];
for location in &locations {
let segment = location.segment(state.files);
let segment = &state.files[&location.file_id].trk[location.trk].trkseg[location.seg];
let kept = reduce_indices(segment, self.tolerance);
if kept.len() == segment.len() {
continue;
+9 -21
View File
@@ -1,15 +1,14 @@
use std::rc::Rc;
use crate::{
Apply, CommandError, File, FileId, RouteId, Selection, State, TrackId, TrackSegmentId,
end_time, reverse_routes, reverse_segment, reverse_segments, reverse_tracks, start_time,
track_end_time, track_start_time,
Apply, CommandError, File, FileId, Selection, State, TrackId, TrackSegmentId, end_time,
reverse_segment, reverse_segments, reverse_tracks, start_time, track_end_time,
track_start_time,
};
/// Reverses the direction of the selected elements: the whole of each selected file (its routes,
/// its tracks, the segments of its tracks and their trackpoints are in the opposite order; the
/// routes and the tracks are two wholes, as the routes stay before the tracks), of each selected
/// track (its segments and their trackpoints), or each selected route or segment on its own (its
/// Reverses the direction of the selected elements: the whole of each selected file (its tracks,
/// the segments of its tracks and their trackpoints are in the opposite order), of each selected
/// track (its segments and their trackpoints), or each selected segment on its own (its
/// trackpoints). The timestamps are mirrored, see [`reverse_segment`].
#[derive(Debug)]
pub struct Reverse;
@@ -21,7 +20,9 @@ impl Apply for Reverse {
.segment_locations(state.files, &state.order.0);
let points: usize = locations
.iter()
.map(|location| location.segment(state.files).len())
.map(|location| {
state.files[&location.file_id].trk[location.trk].trkseg[location.seg].len()
})
.sum();
if points <= 1 {
return Err(CommandError::NothingToDo);
@@ -39,18 +40,12 @@ impl Apply for Reverse {
Selection::File { file_ids } => {
for file_id in file_ids {
edit(file_id, &|file| {
let end = file.rte.last().and_then(|rte| end_time(&rte.seg));
let start = file.rte.first().and_then(|rte| start_time(&rte.seg));
reverse_routes(&mut file.rte, end, start);
let end = file.trk.last().and_then(track_end_time);
let start = file.trk.first().and_then(track_start_time);
reverse_tracks(&mut file.trk, end, start);
});
}
}
Selection::Route { file_id, rte_ids } => edit(file_id, &|file| {
reverse_selected_routes(file, rte_ids);
}),
Selection::Track { file_id, trk_ids } => edit(file_id, &|file| {
reverse_selected_tracks(file, trk_ids);
}),
@@ -71,13 +66,6 @@ impl Apply for Reverse {
}
}
fn reverse_selected_routes(file: &mut File, ids: &std::collections::HashSet<RouteId>) {
for route in file.rte.iter_mut().filter(|route| ids.contains(&route.id)) {
let (end, start) = (end_time(&route.seg), start_time(&route.seg));
reverse_segment(&mut route.seg, end, start);
}
}
fn reverse_selected_tracks(file: &mut File, ids: &std::collections::HashSet<TrackId>) {
for track in file.trk.iter_mut().filter(|track| ids.contains(&track.id)) {
let end = track.trkseg.last().and_then(end_time);
@@ -14,7 +14,7 @@ impl Apply for RoundTrip {
.selection
.segment_locations(state.files, &state.order.0)
.into_iter()
.filter(|l| l.segment(state.files).len() >= 2)
.filter(|l| state.files[&l.file_id].trk[l.trk].trkseg[l.seg].len() >= 2)
.collect();
if locations.is_empty() {
return Err(CommandError::NothingToDo);
+14 -17
View File
@@ -1,11 +1,11 @@
use std::rc::Rc;
use crate::{
Apply, Categories, CommandError, FileId, SegmentIndex, SegmentLocation, Selection, State,
Statistics, Track, TrackSegment, Trackpoint, distance, replace_trackpoints,
Apply, Categories, CommandError, FileId, SegmentLocation, Selection, State, Statistics, Track,
TrackSegment, Trackpoint, distance, replace_trackpoints,
};
/// The values of an OSM attribute (surface, highway...) of the new trackpoints of a [`Reroute`], as
/// The values of an OSM attribute (surface, highway...) of the new trackpoints of a [`Route`], as
/// the intervals of consecutive trackpoints that share one: `starts[i]` is the index of the first
/// trackpoint of the interval `i`, and `values[i]` its value, 0 when unknown, else 1 + the index
/// of its name in `names`. No intervals means that the attribute is unknown everywhere.
@@ -64,7 +64,7 @@ impl RouteCategory<'_> {
/// anchors anyway. The ones right before and after the range, between which the route goes, become
/// shown at every zoom level as well.
#[derive(Debug)]
pub struct Reroute<'a> {
pub struct Route<'a> {
pub start: u32,
pub end: u32,
pub lng: &'a [f64],
@@ -89,7 +89,7 @@ pub(super) struct Target {
pub end: usize,
}
impl Apply for Reroute<'_> {
impl Apply for Route<'_> {
fn apply(self, state: &mut State) -> Result<(), CommandError> {
let (start, end) = (self.start as usize, self.end as usize);
let len = self.lng.len();
@@ -152,17 +152,14 @@ impl Apply for Reroute<'_> {
}
let seg = file.trk[trk].trkseg.len() - 1;
Target {
location: SegmentLocation {
file_id,
index: SegmentIndex::Track { trk, seg },
},
location: SegmentLocation { file_id, trk, seg },
start: 0,
end: 0,
}
}
};
let segment = file.segment_mut(target.location.index);
let segment = &mut file.trk[target.location.trk].trkseg[target.location.seg];
let new_len = points.len();
let (speed, start_time) = speed_and_start_time(segment, &target, &points);
let has_times = !segment.is_empty() && segment[0].time.is_some();
@@ -211,7 +208,7 @@ pub(super) fn find_target(
let segments: Vec<(SegmentLocation, usize)> = locations
.into_iter()
.map(|location| {
let segment = location.segment(state.files);
let segment = &state.files[&location.file_id].trk[location.trk].trkseg[location.seg];
(location, segment.len())
})
.collect();
@@ -385,8 +382,8 @@ mod tests {
lng: &'a [f64],
lat: &'a [f64],
ele: &'a [f64],
) -> Reroute<'a> {
Reroute {
) -> Route<'a> {
Route {
start,
end,
lng,
@@ -462,7 +459,7 @@ mod tests {
route(0, 0, &[1.0], &[], &[]).apply(&mut fx.state()),
route(0, len + 1, &[], &[], &[]).apply(&mut fx.state()),
route(len + 1, len + 1, &[1.0], &[1.0], &[1.0]).apply(&mut fx.state()),
Reroute {
Route {
anchors: &[1],
..route(0, 0, &[1.0], &[1.0], &[1.0])
}
@@ -592,7 +589,7 @@ mod tests {
// 5 new points replacing the 2 in the middle, two of them are anchors
let (lng, lat, ele) = ([1.0; 5], [2.0; 5], [3.0; 5]);
Reroute {
Route {
anchors: &[1, 3],
..route(1, 3, &lng, &lat, &ele)
}
@@ -642,7 +639,7 @@ mod tests {
let names = ["asphalt".to_string(), "gravel".to_string()];
let (lng, lat, ele) = ([1.0; 4], [2.0; 4], [3.0; 4]);
// asphalt, asphalt, unknown, gravel
Reroute {
Route {
surface: RouteCategory {
starts: &[0, 2, 3],
values: &[1, 0, 2],
@@ -686,7 +683,7 @@ mod tests {
},
];
for surface in broken {
let result = Reroute {
let result = Route {
surface,
..route(0, 0, &lng, &lat, &ele)
}
+94 -108
View File
@@ -1,8 +1,8 @@
use std::rc::Rc;
use crate::{
Apply, CommandError, File, Route, SegmentIndex, Selection, State, Track, TrackSegment,
Waypoints, copy_file, copy_route, copy_segment, copy_track, copy_waypoint,
Apply, CommandError, File, Selection, State, Track, TrackSegment, Waypoints, copy_file,
copy_segment, copy_track, copy_waypoint,
};
use super::route::find_target;
@@ -13,27 +13,24 @@ use super::route::find_target;
pub enum SplitType {
/// The file becomes two files, which both have the waypoints (copies, in the second one).
Files,
/// The route becomes two routes.
Routes,
/// The track becomes two tracks.
Tracks,
/// The segment of a track becomes two segments.
/// The segment becomes two segments.
Segments,
}
/// Cuts the file, the route, the track or the segment of the trackpoint `at` of the selection (see
/// Cuts the file, the track or the segment of the trackpoint `at` of the selection (see
/// `RoutingBuffer`) in two, there: the trackpoint is the last one of the first part and the first
/// one of the second part. Cutting a route needs the trackpoint to be in a route, and cutting a
/// track or a segment needs it to be in a track: there is nothing to do otherwise.
/// one of the second part.
///
/// The first part keeps the ids of what is cut, the second one has new ids, as the elements that
/// come after the trackpoint (the following segments of the track, the following routes and
/// tracks of the file, the routes coming before the tracks), which are moved to it. When the file
/// is cut, the new file comes right after it. The selection does not change.
/// come after the trackpoint (the following segments of the track, the following tracks of the
/// file), which are moved to it. When the file is cut, the new file comes right after it. The
/// selection does not change.
///
/// With `keep_originals`, a file that is cut (`SplitType::Files`) is left as it is: its two parts
/// are two new files, with new ids, which come right after it and are selected. Cutting a route, a
/// track or a segment changes the file in place anyway, so the flag has no effect on them.
/// are two new files, with new ids, which come right after it and are selected. Cutting a track
/// or a segment changes the file in place anyway, so the flag has no effect on them.
#[derive(Debug)]
pub struct Split {
pub at: u32,
@@ -46,115 +43,104 @@ impl Apply for Split {
let at = self.at as usize;
let target = find_target(state, at, at)?.ok_or(CommandError::NothingToDo)?;
let location = target.location;
let (file_id, index) = (location.file_id, target.start);
let in_route = matches!(location.index, SegmentIndex::Route(_));
let fits = match self.split_type {
SplitType::Files => true,
SplitType::Routes => in_route,
SplitType::Tracks | SplitType::Segments => !in_route,
};
if !fits {
return Err(CommandError::NothingToDo);
}
let (file_id, trk, seg, index) =
(location.file_id, location.trk, location.seg, target.start);
let mut file = (*state.files[&file_id]).clone();
if index >= file.segment(location.index).len() {
if index >= file.trk[trk].trkseg[seg].len() {
return Err(CommandError::InvalidData(
"trackpoint out of the segment".into(),
));
}
// with `SplitType::Files`, what goes to the second file: what comes after the trackpoint
let mut second_file = File {
id: Default::default(),
rte: vec![],
trk: vec![],
wpt: Waypoints::default(),
..file.clone()
let track = file.trk[trk].clone();
let segment = &track.trkseg[seg];
let (first, second) = (keep_up_to(segment, index), keep_from(segment, index));
// the track is cut: what is before the segment, and its first part, then the second part
// and what is after it
let split_track = || {
let mut first_track = track.clone();
first_track.trkseg.truncate(seg);
first_track.trkseg.push(first.clone());
let mut second_track = Track {
id: Default::default(),
trkseg: vec![second.clone()],
..track.clone()
};
second_track
.trkseg
.extend(track.trkseg[seg + 1..].iter().map(copy_segment));
(first_track, second_track)
};
match location.index {
SegmentIndex::Route(rte) => {
let route = file.rte[rte].clone();
let first = Route {
seg: keep_up_to(&route.seg, index),
..route.clone()
};
let second = Route {
id: Default::default(),
seg: keep_from(&route.seg, index),
..route.clone()
};
if self.split_type == SplitType::Routes {
file.rte.splice(rte..=rte, [first, second]);
state.files.insert(file_id, Rc::new(file));
return Ok(());
}
// the following routes, and the tracks, which come after the routes
second_file.rte = [second]
.into_iter()
.chain(file.rte[rte + 1..].iter().map(copy_route))
.collect();
second_file.trk = file.trk.iter().map(copy_track).collect();
file.rte.truncate(rte);
file.rte.push(first);
file.trk.clear();
match self.split_type {
SplitType::Segments => {
file.trk[trk].trkseg.splice(seg..=seg, [first, second]);
}
SegmentIndex::Track { trk, seg } => {
let track = file.trk[trk].clone();
let segment = &track.trkseg[seg];
let (first, second) = (keep_up_to(segment, index), keep_from(segment, index));
if self.split_type == SplitType::Segments {
file.trk[trk].trkseg.splice(seg..=seg, [first, second]);
state.files.insert(file_id, Rc::new(file));
return Ok(());
}
// the track is cut: what is before the segment, and its first part, then the
// second part and what is after it
let mut first_track = track.clone();
first_track.trkseg.truncate(seg);
first_track.trkseg.push(first);
let mut second_track = Track {
SplitType::Tracks => {
let (first_track, second_track) = split_track();
file.trk.splice(trk..=trk, [first_track, second_track]);
}
SplitType::Files if self.keep_originals => {
let (first_track, second_track) = split_track();
// the parts are new files: nothing is shared by id with the file, nor between them
let first_file = copy_file(&File {
trk: file.trk[..trk]
.iter()
.cloned()
.chain([first_track])
.collect(),
..file.clone()
});
let mut second_file = File {
id: Default::default(),
trkseg: vec![second],
..track.clone()
trk: vec![second_track],
wpt: Waypoints::default(),
..file.clone()
};
second_track
.trkseg
.extend(track.trkseg[seg + 1..].iter().map(copy_segment));
if self.split_type == SplitType::Tracks {
file.trk.splice(trk..=trk, [first_track, second_track]);
state.files.insert(file_id, Rc::new(file));
return Ok(());
}
second_file.trk = [second_track]
.into_iter()
.chain(file.trk[trk + 1..].iter().map(copy_track))
.collect();
second_file
.trk
.extend(file.trk[trk + 1..].iter().map(copy_track));
second_file
.wpt
.insert_at(0, file.wpt.iter().map(copy_waypoint).collect());
let ids = [first_file.id, second_file.id];
let position = state.order.0.iter().position(|id| *id == file_id);
let at = position.map_or(state.order.0.len(), |p| p + 1);
state.order.0.splice(at..at, ids);
state.files.insert(first_file.id, Rc::new(first_file));
state.files.insert(second_file.id, Rc::new(second_file));
*state.selection = Selection::File {
file_ids: ids.into(),
};
return Ok(());
}
SplitType::Files => {
let (first_track, second_track) = split_track();
let mut second_file = File {
id: Default::default(),
trk: vec![second_track],
wpt: Waypoints::default(),
..file.clone()
};
second_file
.trk
.extend(file.trk[trk + 1..].iter().map(copy_track));
second_file
.wpt
.insert_at(0, file.wpt.iter().map(copy_waypoint).collect());
file.trk.truncate(trk);
file.trk.push(first_track);
let position = state.order.0.iter().position(|id| *id == file_id);
state.order.0.insert(
position.map_or(state.order.0.len(), |p| p + 1),
second_file.id,
);
state.files.insert(second_file.id, Rc::new(second_file));
}
}
// the file is cut: both parts have the waypoints
second_file
.wpt
.insert_at(0, file.wpt.iter().map(copy_waypoint).collect());
let position = state.order.0.iter().position(|id| *id == file_id);
let at = position.map_or(state.order.0.len(), |p| p + 1);
if self.keep_originals {
// the parts are new files: nothing is shared by id with the file, nor between them
let first_file = copy_file(&file);
let ids = [first_file.id, second_file.id];
state.order.0.splice(at..at, ids);
state.files.insert(first_file.id, Rc::new(first_file));
state.files.insert(second_file.id, Rc::new(second_file));
*state.selection = Selection::File {
file_ids: ids.into(),
};
} else {
state.order.0.insert(at, second_file.id);
state.files.insert(second_file.id, Rc::new(second_file));
state.files.insert(file_id, Rc::new(file));
}
state.files.insert(file_id, Rc::new(file));
Ok(())
}
}
+4 -2
View File
@@ -45,8 +45,10 @@ impl Apply for Time {
let locations = state
.selection
.segment_locations(state.files, &state.order.0);
let segments: Vec<&TrackSegment> =
locations.iter().map(|l| l.segment(state.files)).collect();
let segments: Vec<&TrackSegment> = locations
.iter()
.map(|l| &state.files[&l.file_id].trk[l.trk].trkseg[l.seg])
.collect();
if segments.iter().all(|segment| segment.is_empty()) {
return Err(CommandError::NothingToDo);
}
@@ -3,7 +3,7 @@ use std::collections::{HashMap, HashSet};
use crate::{FileId, FileWaypointsRevisionId, Files, TrackSegmentId, TrackSegmentRevisionId};
/// Coordinates buffers, as flat `[lng, lat, lng, lat, ...]` arrays so that they can be handed
/// to the UI without per-point calls: one per segment of a route or track (its trackpoints) and one per file
/// to the UI without per-point calls: one per track segment (its trackpoints) and one per file
/// (its waypoints). A buffer is only rebuilt when the revision of its segment (or the waypoints
/// of its file) changes, so editing a segment does not touch the buffers of the others.
#[derive(Debug, Default)]
@@ -30,7 +30,7 @@ impl CoordinatesCache {
self.waypoints
.insert(file.id, (file.wpt.rev_id, coordinates));
}
for seg in file.segments() {
for seg in file.trk.iter().flat_map(|trk| &trk.trkseg) {
segments.insert(seg.id);
if self
.segments
+28 -59
View File
@@ -1,10 +1,9 @@
use crate::{
File, FileId, FileWaypointsRevisionId, RouteId, TrackId, TrackInfo, TrackSegment,
TrackSegmentId, TrackSegmentRevisionId, WaypointId,
File, FileId, FileWaypointsRevisionId, TrackId, TrackSegmentId, TrackSegmentRevisionId,
WaypointId,
};
/// What the UI needs to display a file: its name and the structure of its routes, tracks and
/// waypoints,
/// What the UI needs to display a file: its name and the structure of its tracks and waypoints,
/// with the ids that reference every element. Coordinates are not part of it, they are read
/// from the buffers of the [`CoordinatesCache`](crate::CoordinatesCache) (the `i`-th waypoint
/// of a file is the `i`-th coordinates pair of its waypoint buffer, same for the trackpoints of
@@ -14,47 +13,21 @@ pub struct FileStructure {
pub id: FileId,
pub name: String,
pub desc: Option<String>,
pub routes: Vec<RouteNode>,
pub tracks: Vec<TrackNode>,
pub waypoints: Vec<WaypointNode>,
/// Changes whenever the waypoints of the file (hence their buffer) change.
pub wpt_rev_id: FileWaypointsRevisionId,
}
/// The name, description and style of a route or a track (the style only when the file defines
/// it).
#[derive(Debug, Clone, PartialEq)]
pub struct PathInfo {
pub name: Option<String>,
pub desc: Option<String>,
pub color: Option<String>,
pub opacity: Option<f64>,
pub width: Option<f64>,
}
impl From<&TrackInfo> for PathInfo {
fn from(info: &TrackInfo) -> Self {
Self {
name: info.name.clone(),
desc: info.desc.clone(),
color: info.color.clone(),
opacity: info.opacity,
width: info.width,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct RouteNode {
pub id: RouteId,
pub info: PathInfo,
pub segment: SegmentNode,
}
#[derive(Debug, Clone, PartialEq)]
pub struct TrackNode {
pub id: TrackId,
pub info: PathInfo,
pub name: Option<String>,
pub desc: Option<String>,
/// Style of the track, only when the file defines it.
pub color: Option<String>,
pub opacity: Option<f64>,
pub width: Option<f64>,
pub segments: Vec<SegmentNode>,
}
@@ -73,38 +46,31 @@ pub struct WaypointNode {
pub sym: Option<String>,
}
impl From<&TrackSegment> for SegmentNode {
fn from(seg: &TrackSegment) -> Self {
Self {
id: seg.id,
rev_id: seg.rev_id,
len: seg.len(),
}
}
}
impl FileStructure {
pub fn new(file: &File) -> Self {
Self {
id: file.id,
name: file.info.name.clone(),
desc: file.info.desc.clone(),
routes: file
.rte
.iter()
.map(|rte| RouteNode {
id: rte.id,
info: (&rte.info).into(),
segment: (&rte.seg).into(),
})
.collect(),
tracks: file
.trk
.iter()
.map(|trk| TrackNode {
id: trk.id,
info: (&trk.info).into(),
segments: trk.trkseg.iter().map(Into::into).collect(),
name: trk.info.name.clone(),
desc: trk.info.desc.clone(),
color: trk.info.color.clone(),
opacity: trk.info.opacity,
width: trk.info.width,
segments: trk
.trkseg
.iter()
.map(|seg| SegmentNode {
id: seg.id,
rev_id: seg.rev_id,
len: seg.len(),
})
.collect(),
})
.collect(),
waypoints: file
@@ -146,8 +112,11 @@ mod tests {
);
assert_eq!(node.tracks.len(), file.trk.len());
for (n, t) in node.tracks.iter().zip(&file.trk) {
assert_eq!(n.id, t.id);
assert_eq!(n.info, PathInfo::from(&t.info));
assert_eq!((n.id, &n.name, &n.desc), (t.id, &t.info.name, &t.info.desc));
assert_eq!(
(&n.color, n.opacity, n.width),
(&t.info.color, t.info.opacity, t.info.width)
);
assert_eq!(n.segments.len(), t.trkseg.len());
for (n, s) in n.segments.iter().zip(&t.trkseg) {
assert_eq!((n.id, n.rev_id, n.len), (s.id, s.rev_id, s.len()));
+1 -1
View File
@@ -39,7 +39,7 @@ impl RoutingBuffer {
.map(|files| selection.segment_locations(files, order))
.unwrap_or_default()
{
let segment = location.segment(files.unwrap());
let segment = &files.unwrap()[&location.file_id].trk[location.trk].trkseg[location.seg];
signature.push((segment.id, segment.rev_id));
if segment.is_empty() {
continue;
+28 -81
View File
@@ -1,4 +1,4 @@
use crate::{GlobalStatistics, SlopeSegment, Statistics, TrackSegment, sum_options};
use crate::{GlobalStatistics, Statistics, TrackSegment, sum_options};
/// Value of the timestamps of the trackpoints that have none.
pub const NO_TIME: i64 = i64::MIN;
@@ -27,8 +27,8 @@ pub struct StatisticsBuffer {
pub elevation_gain: Vec<f64>,
pub elevation_loss: Vec<f64>,
pub slope: Vec<f64>,
/// The smoothed elevation segments that the trackpoints belong to, see [`SlopeSegments`].
pub slope_segments: SlopeSegments,
pub slope_segment_slope: Vec<f64>,
pub slope_segment_distance: Vec<f64>,
pub lng: Vec<f64>,
pub lat: Vec<f64>,
pub ele: Vec<f64>,
@@ -62,18 +62,6 @@ pub struct Intervals {
}
impl Intervals {
/// The value of the trackpoint at `index` (the one of the last interval past the trackpoints),
/// 0 (unknown) when there are no trackpoints.
pub fn value_at(&self, index: usize) -> u8 {
match self
.starts
.partition_point(|start| *start as usize <= index)
{
0 => 0,
next => self.values[next - 1],
}
}
fn clear(&mut self) {
self.starts.clear();
self.values.clear();
@@ -88,50 +76,6 @@ impl Intervals {
}
}
/// The smoothed elevation segments of the selection, over which the slope is averaged, as the
/// intervals of trackpoints that belong to the same one: segment `i` starts at the trackpoint
/// `starts[i]` and ends where the next one starts, or at the last trackpoint. It has a `slope` (%)
/// and a length (`distance`, km). A segment never spans two segments of the selection. All are
/// empty when there are no trackpoints.
#[derive(Debug, Default, PartialEq)]
pub struct SlopeSegments {
pub starts: Vec<u32>,
pub slopes: Vec<f64>,
pub distances: Vec<f64>,
}
impl SlopeSegments {
/// The index of the segment of the trackpoint at `index` (the last one past the trackpoints),
/// `None` when there are no trackpoints.
pub fn at(&self, index: usize) -> Option<usize> {
let next = self
.starts
.partition_point(|start| *start as usize <= index);
next.checked_sub(1)
}
fn clear(&mut self) {
self.starts.clear();
self.slopes.clear();
self.distances.clear();
}
/// Adds the trackpoint at `index`, the indices being pushed in order: it starts a segment if
/// it is the first of a segment of the selection (`first`), or if its segment is not the one
/// of the previous trackpoint.
fn push(&mut self, index: usize, segment: &SlopeSegment, first: bool) {
// compared as bits, so that a NaN slope (no distance) is the same as the previous one
let same = |values: &[f64], value: f64| {
values.last().map(|last| last.to_bits()) == Some(value.to_bits())
};
if first || !same(&self.slopes, segment.slope) || !same(&self.distances, segment.distance) {
self.starts.push(index as u32);
self.slopes.push(segment.slope);
self.distances.push(segment.distance);
}
}
}
/// 0 for an unknown value, else the code plus one. The categories hold at most 255 values, so it
/// fits.
fn unknown_or_next(code: Option<u8>) -> u8 {
@@ -173,7 +117,8 @@ impl StatisticsBuffer {
self.elevation_gain.clear();
self.elevation_loss.clear();
self.slope.clear();
self.slope_segments.clear();
self.slope_segment_slope.clear();
self.slope_segment_distance.clear();
self.lng.clear();
self.lat.clear();
self.ele.clear();
@@ -188,7 +133,6 @@ impl StatisticsBuffer {
self.mtb_scale.clear();
for (segment, stats) in selected {
let segment_start = self.total_distance.len();
for (trkpt, trkpt_stats) in segment.iter().zip(stats.local.iter()) {
let index = self.total_distance.len();
let cumul_stats = &self.global;
@@ -218,8 +162,10 @@ impl StatisticsBuffer {
self.elevation_loss
.push(cumul_stats.elevation_loss + trkpt_stats.elevation_loss);
self.slope.push(trkpt_stats.slope);
self.slope_segments
.push(index, &trkpt_stats.slope_segment, index == segment_start);
self.slope_segment_slope
.push(trkpt_stats.slope_segment.slope);
self.slope_segment_distance
.push(trkpt_stats.slope_segment.distance);
self.lng.push(trkpt.coordinates.lng);
self.lat.push(trkpt.coordinates.lat);
self.ele.push(trkpt.ele);
@@ -283,12 +229,25 @@ mod tests {
(segment, stats)
}
/// The value of the trackpoint at `index`, 0 before the first interval.
fn value_at(intervals: &Intervals, index: usize) -> u8 {
match intervals
.starts
.partition_point(|start| *start as usize <= index)
{
0 => 0,
next => intervals.values[next - 1],
}
}
fn all_lengths(buffer: &StatisticsBuffer) -> Vec<usize> {
vec![
buffer.total_distance.len(),
buffer.elevation_gain.len(),
buffer.elevation_loss.len(),
buffer.slope.len(),
buffer.slope_segment_slope.len(),
buffer.slope_segment_distance.len(),
buffer.lng.len(),
buffer.lat.len(),
buffer.ele.len(),
@@ -317,19 +276,7 @@ mod tests {
for (i, local) in s.local.iter().enumerate() {
assert_eq!(buffer.total_distance[i], local.total_distance);
assert_eq!(buffer.slope[i], local.slope);
let segment = buffer.slope_segments.at(i).unwrap();
assert_eq!(
buffer.slope_segments.slopes[segment].to_bits(),
local.slope_segment.slope.to_bits()
);
assert_eq!(
buffer.slope_segments.distances[segment],
local.slope_segment.distance
);
}
// a segment per smoothed elevation segment, not per trackpoint
assert!(buffer.slope_segments.starts.len() < n);
assert_eq!(buffer.slope_segments.starts[0], 0);
// the trackpoints
for (i, trkpt) in segment.iter().enumerate() {
assert_eq!(buffer.lng[i], trkpt.coordinates.lng);
@@ -507,7 +454,7 @@ mod tests {
assert!(all_lengths(&buffer).iter().all(|len| *len == 5));
// and they can be looked up
let values: Vec<u8> = (0..6).map(|i| buffer.surface.value_at(i)).collect();
let values: Vec<u8> = (0..6).map(|i| value_at(&buffer.surface, i)).collect();
assert_eq!(values, [1, 1, 0, 2, 2, 2]);
}
@@ -547,10 +494,10 @@ mod tests {
buffer.update(&[(&segment, &s)]);
let at = |i: usize| {
(
buffer.surface.value_at(i),
buffer.highway.value_at(i),
buffer.sac_scale.value_at(i),
buffer.mtb_scale.value_at(i),
value_at(&buffer.surface, i),
value_at(&buffer.highway, i),
value_at(&buffer.sac_scale, i),
value_at(&buffer.mtb_scale, i),
)
};
assert_eq!(at(0), (8, 255, 1, 4));
@@ -575,7 +522,7 @@ mod tests {
assert_eq!(buffer.highway, Intervals::default());
assert_eq!(buffer.sac_scale, Intervals::default());
assert_eq!(buffer.mtb_scale, Intervals::default());
assert_eq!(buffer.surface.value_at(0), 0);
assert_eq!(value_at(&buffer.surface, 0), 0);
}
#[test]
+11 -19
View File
@@ -18,13 +18,15 @@ impl StatisticsCache {
let mut stale: HashSet<TrackSegmentRevisionId> = self.map.keys().copied().collect();
if let Some(state) = state {
for file in state.values() {
for trkseg in file.segments() {
match self.map.entry(trkseg.rev_id) {
Entry::Occupied(_) => {
stale.remove(&trkseg.rev_id);
}
Entry::Vacant(e) => {
e.insert(Statistics::compute(trkseg));
for trk in file.trk.iter() {
for trkseg in trk.trkseg.iter() {
match self.map.entry(trkseg.rev_id) {
Entry::Occupied(_) => {
stale.remove(&trkseg.rev_id);
}
Entry::Vacant(e) => {
e.insert(Statistics::compute(trkseg));
}
}
}
}
@@ -36,7 +38,6 @@ impl StatisticsCache {
}
/// Statistics of the segments of the selection.
#[cfg(test)]
pub fn get<'a>(
&'a self,
state: Option<&'a Files>,
@@ -71,15 +72,6 @@ impl StatisticsCache {
}
}
}
Selection::Route { file_id, rte_ids } => {
if let Some(file) = state.get(file_id) {
for rte in file.rte.iter() {
if rte_ids.contains(&rte.id) {
self.add_segment_stats(&rte.seg, &mut selected);
}
}
}
}
Selection::Track { file_id, trk_ids } => {
if let Some(file) = state.get(file_id) {
for trk in file.trk.iter() {
@@ -137,8 +129,8 @@ impl StatisticsCache {
}
fn add_file_stats<'a>(&'a self, file: &'a File, selected: &mut Vec<SelectedSegment<'a>>) {
for trkseg in file.segments() {
self.add_segment_stats(trkseg, selected);
for trk in file.trk.iter() {
self.add_track_stats(trk, selected);
}
}
+24 -3
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,24 @@ impl<H: History> Engine<H> {
.find(|wpt| wpt.id == *id)
}
/// A trackpoint of a segment 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)?
.trk
.iter()
.flat_map(|trk| &trk.trkseg)
.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> {
@@ -91,7 +109,11 @@ impl<H: History> Engine<H> {
self.selection
.segment_locations(files, &self.order.0)
.iter()
.flat_map(|location| reduction_distances(location.segment(files)))
.flat_map(|location| {
reduction_distances(
&files[&location.file_id].trk[location.trk].trkseg[location.seg],
)
})
.collect()
}
@@ -226,7 +248,6 @@ impl<H: History> Engine<H> {
self.order.move_files(&file_ids, index);
None
}
Action::Rename { file_id, name } => self.history.rename(file_id, &name),
};
let changed = diff.is_some()
|| self.selection != selection_before
+13 -44
View File
@@ -3,18 +3,10 @@ use std::rc::Rc;
use uuid::Uuid;
use crate::{
File, FileId, Files, Route, RouteId, Selection, Track, TrackId, TrackSegment, TrackSegmentId,
Waypoint, WaypointId,
File, FileId, Files, Selection, Track, TrackId, TrackSegment, TrackSegmentId, Waypoint,
WaypointId,
};
/// A route in the clipboard, with the name of the file it comes from (the name of the new file
/// when it is pasted on its own).
#[derive(Debug, Clone)]
pub struct ClipboardRoute {
pub route: Route,
pub file_name: String,
}
/// A track in the clipboard, with the name of the file it comes from (the name of the new file
/// when it is pasted on its own).
#[derive(Debug, Clone)]
@@ -39,7 +31,6 @@ pub struct ClipboardSegment {
#[derive(Debug, Clone)]
pub enum ClipboardContent {
Files(Vec<Rc<File>>),
Routes(Vec<ClipboardRoute>),
Tracks(Vec<ClipboardTrack>),
Segments(Vec<ClipboardSegment>),
Waypoints(Vec<Waypoint>),
@@ -93,19 +84,6 @@ impl Clipboard {
.filter_map(|id| files.get(id).cloned())
.collect(),
),
Selection::Route { file_id, rte_ids } => {
let file = files.get(file_id)?;
ClipboardContent::Routes(
file.rte
.iter()
.filter(|rte| rte_ids.contains(&rte.id))
.map(|rte| ClipboardRoute {
route: rte.clone(),
file_name: file.info.name.clone(),
})
.collect(),
)
}
Selection::Track { file_id, trk_ids } => {
let file = files.get(file_id)?;
ClipboardContent::Tracks(
@@ -166,37 +144,32 @@ impl Clipboard {
pub fn is_empty(&self) -> bool {
match &self.content {
ClipboardContent::Files(files) => files.is_empty(),
ClipboardContent::Routes(routes) => routes.is_empty(),
ClipboardContent::Tracks(tracks) => tracks.is_empty(),
ClipboardContent::Segments(segments) => segments.is_empty(),
ClipboardContent::Waypoints(waypoints) => waypoints.is_empty(),
}
}
/// Whether the content can be pasted when `target` is selected: files, routes and tracks can
/// be pasted anywhere above them in the file tree (routes and tracks are at the same level),
/// and nothing selected stands for the list of files.
/// Whether the content can be pasted when `target` is selected: files and tracks can be
/// pasted anywhere above them in the file tree, and nothing selected stands for the list of
/// files.
///
/// | copied | pasted when selected |
/// |-----------|-----------------------------------------------|
/// | files | nothing, a file |
/// | routes | nothing, a file, a route, a track |
/// | tracks | nothing, a file, a route, a track |
/// | segments | nothing, a file, a route, a track, a segment |
/// | waypoints | a file, the waypoints, a waypoint |
/// | copied | pasted when selected |
/// |-----------|------------------------------------------|
/// | files | nothing, a file |
/// | tracks | nothing, a file, a track |
/// | segments | nothing, a file, a track, a segment |
/// | waypoints | a file, the waypoints, a waypoint |
pub fn can_paste(&self, target: &Selection) -> bool {
use ClipboardContent as C;
use Selection::*;
matches!(
(&self.content, target),
(C::Files(_), Empty | File { .. })
| (
C::Routes(_) | C::Tracks(_),
Empty | File { .. } | Route { .. } | Track { .. }
)
| (C::Tracks(_), Empty | File { .. } | Track { .. })
| (
C::Segments(_),
Empty | File { .. } | Route { .. } | Track { .. } | TrackSegment { .. }
Empty | File { .. } | Track { .. } | TrackSegment { .. }
)
| (
C::Waypoints(_),
@@ -210,7 +183,6 @@ impl Clipboard {
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ClipboardIds {
Files(Vec<FileId>),
Routes(Vec<RouteId>),
Tracks(Vec<TrackId>),
Segments(Vec<TrackSegmentId>),
Waypoints(Vec<WaypointId>),
@@ -222,9 +194,6 @@ impl ClipboardContent {
ClipboardContent::Files(files) => {
ClipboardIds::Files(files.iter().map(|file| file.id).collect())
}
ClipboardContent::Routes(routes) => {
ClipboardIds::Routes(routes.iter().map(|rte| rte.route.id).collect())
}
ClipboardContent::Tracks(tracks) => {
ClipboardIds::Tracks(tracks.iter().map(|trk| trk.track.id).collect())
}
+1 -17
View File
@@ -1,6 +1,6 @@
use std::rc::Rc;
use super::{Diff, Files, History, Renamer, diff_between};
use super::{Diff, Files, History, diff_between};
use crate::{CommandError, FileId};
/// One history for the whole workspace: each entry is a state of all the files.
@@ -123,22 +123,6 @@ impl History for GlobalHistory {
None => !self.entries.is_empty(),
}
}
fn rename(&mut self, id: FileId, name: &str) -> Option<Diff> {
let before = self.current()?.get(&id)?.clone();
let mut renamer = Renamer::new(name);
for entry in self.entries.iter_mut() {
if let Some(file) = entry.get(&id) {
let renamed = renamer.rename(file);
entry.insert(id, renamed);
}
}
let after = self.current()?.get(&id)?;
(!Rc::ptr_eq(&before, after)).then(|| Diff {
modified: vec![id],
..Default::default()
})
}
}
#[cfg(test)]
-35
View File
@@ -57,41 +57,6 @@ pub trait History: Default + Debug {
/// Whether [`History::redo`] would do something for these `files`.
fn can_redo(&self, files: &[FileId]) -> bool;
/// Names a file `name` in all its states, as if it had always been called so: there is nothing
/// to undo. Says that the file changed, `None` if there is no such file or it is called so.
fn rename(&mut self, id: FileId, name: &str) -> Option<Diff>;
}
/// Names the states of a file: the ones that were shared stay shared (a state that several
/// entries have is renamed once), and the ones that are called so already are kept.
pub(super) struct Renamer<'a> {
name: &'a str,
renamed: HashMap<*const File, Rc<File>>,
}
impl<'a> Renamer<'a> {
pub(super) fn new(name: &'a str) -> Self {
Self {
name,
renamed: HashMap::new(),
}
}
pub(super) fn rename(&mut self, file: &Rc<File>) -> Rc<File> {
if file.info.name == self.name {
return file.clone();
}
let name = self.name;
self.renamed
.entry(Rc::as_ptr(file))
.or_insert_with(|| {
let mut renamed = (**file).clone();
renamed.info.name = name.to_owned();
Rc::new(renamed)
})
.clone()
}
}
/// Which files were added, removed or modified by a change of the current files.
+1 -15
View File
@@ -1,6 +1,6 @@
use std::rc::Rc;
use super::{Diff, Files, History, Renamer, diff_between};
use super::{Diff, Files, History, diff_between};
use crate::{CommandError, File, FileId};
use std::collections::HashMap;
@@ -139,20 +139,6 @@ impl History for PerFileHistory {
self.any(files, FileHistory::can_undo)
}
fn rename(&mut self, id: FileId, name: &str) -> Option<Diff> {
let history = self.stacks.get_mut(&id)?;
let mut renamer = Renamer::new(name);
for entry in history.entries.iter_mut() {
*entry = renamer.rename(entry);
}
let current = history.current().clone();
let before = self.current.insert(id, current.clone());
(!before.is_some_and(|before| Rc::ptr_eq(&before, &current))).then(|| Diff {
modified: vec![id],
..Default::default()
})
}
fn can_redo(&self, files: &[FileId]) -> bool {
self.any(files, FileHistory::can_redo)
}
+27 -81
View File
@@ -1,8 +1,6 @@
use std::collections::HashSet;
use crate::{
File, FileId, Files, RouteId, SegmentIndex, TrackId, TrackSegment, TrackSegmentId, WaypointId,
};
use crate::{FileId, Files, TrackId, TrackSegmentId, WaypointId};
/// How a new selection combines with the current one.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)]
@@ -25,10 +23,6 @@ pub enum Selection {
File {
file_ids: HashSet<FileId>,
},
Route {
file_id: FileId,
rte_ids: HashSet<RouteId>,
},
Track {
file_id: FileId,
trk_ids: HashSet<TrackId>,
@@ -47,19 +41,12 @@ pub enum Selection {
},
}
/// Where a segment is: its file, then its place in it (its route, or its track and its own
/// position in it).
/// Where a track segment is: its file, then its track and its own position in it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SegmentLocation {
pub file_id: FileId,
pub index: SegmentIndex,
}
impl SegmentLocation {
/// The segment, in `files`. Panics if it is not there.
pub fn segment<'a>(&self, files: &'a Files) -> &'a TrackSegment {
files[&self.file_id].segment(self.index)
}
pub trk: usize,
pub seg: usize,
}
impl Selection {
@@ -102,18 +89,23 @@ impl Selection {
}
impl Selection {
/// The segments covered by the selection, in order: the segments of several selected files
/// follow `order` (the files missing from it come last), then the routes, tracks and segments
/// follow the file (see [`File::segments`]). Waypoints are not segments: selecting only
/// waypoints covers none.
/// The track segments covered by the selection, in order: the segments of several selected
/// files follow `order` (the files missing from it come last), then the tracks and segments
/// follow the file. Waypoints are not segments: selecting only waypoints covers none.
pub fn segment_locations(&self, files: &Files, order: &[FileId]) -> Vec<SegmentLocation> {
let mut locations = vec![];
let mut add = |file_id: FileId, filter: &dyn Fn(&File, SegmentIndex) -> bool| {
let mut add = |file_id: FileId,
trk_filter: &dyn Fn(&crate::Track) -> bool,
seg_filter: &dyn Fn(&crate::TrackSegment) -> bool| {
let Some(file) = files.get(&file_id) else {
return;
};
for index in file.segment_indices().filter(|index| filter(file, *index)) {
locations.push(SegmentLocation { file_id, index });
for (trk, track) in file.trk.iter().enumerate().filter(|(_, t)| trk_filter(t)) {
for (seg, segment) in track.trkseg.iter().enumerate() {
if seg_filter(segment) {
locations.push(SegmentLocation { file_id, trk, seg });
}
}
}
};
match self {
@@ -124,35 +116,25 @@ impl Selection {
.filter(|id| file_ids.contains(id))
.chain(file_ids.iter().filter(|id| !order.contains(id)));
for id in ordered {
add(*id, &|_, _| true);
add(*id, &|_| true, &|_| true);
}
}
Selection::Route { file_id, rte_ids } => add(*file_id, &|file, index| match index {
SegmentIndex::Route(rte) => rte_ids.contains(&file.rte[rte].id),
SegmentIndex::Track { .. } => false,
}),
Selection::Track { file_id, trk_ids } => add(*file_id, &|file, index| match index {
SegmentIndex::Track { trk, .. } => trk_ids.contains(&file.trk[trk].id),
SegmentIndex::Route(_) => false,
}),
Selection::Track { file_id, trk_ids } => {
add(*file_id, &|trk| trk_ids.contains(&trk.id), &|_| true)
}
Selection::TrackSegment {
file_id,
trk_id,
trkseg_ids,
} => add(*file_id, &|file, index| match index {
SegmentIndex::Track { trk, seg } => {
let track = &file.trk[trk];
track.id == *trk_id && trkseg_ids.contains(&track.trkseg[seg].id)
}
SegmentIndex::Route(_) => false,
} => add(*file_id, &|trk| trk.id == *trk_id, &|seg| {
trkseg_ids.contains(&seg.id)
}),
}
locations
}
/// Drops what does not exist anymore (e.g. after an undo): files, and the routes, tracks,
/// segments and waypoints of the files that remain. A selection left with nothing becomes
/// empty.
/// Drops what does not exist anymore (e.g. after an undo): files, and the tracks, segments
/// and waypoints of the files that remain. A selection left with nothing becomes empty.
pub fn retain_existing(&mut self, files: &Files) {
let empty = match self {
Selection::Empty => false,
@@ -160,13 +142,6 @@ impl Selection {
file_ids.retain(|id| files.contains_key(id));
file_ids.is_empty()
}
Selection::Route { file_id, rte_ids } => match files.get(file_id) {
Some(file) => {
rte_ids.retain(|id| file.rte.iter().any(|rte| rte.id == *id));
rte_ids.is_empty()
}
None => true,
},
Selection::Track { file_id, trk_ids } => match files.get(file_id) {
Some(file) => {
trk_ids.retain(|id| file.trk.iter().any(|trk| trk.id == *id));
@@ -210,13 +185,6 @@ impl Selection {
(Selection::File { file_ids }, Selection::File { file_ids: other }) => {
file_ids.extend(other)
}
(
Selection::Route { file_id, rte_ids },
Selection::Route {
file_id: other_file,
rte_ids: other,
},
) if *file_id == other_file => rte_ids.extend(other),
(
Selection::Track { file_id, trk_ids },
Selection::Track {
@@ -264,16 +232,6 @@ impl Selection {
toggle_ids(file_ids, other);
file_ids.is_empty()
}
(
Selection::Route { file_id, rte_ids },
Selection::Route {
file_id: other_file,
rte_ids: other,
},
) if *file_id == other_file => {
toggle_ids(rte_ids, other);
rte_ids.is_empty()
}
(
Selection::Track { file_id, trk_ids },
Selection::Track {
@@ -367,8 +325,7 @@ impl Selection {
match self {
Selection::Empty => Selection::Empty,
Selection::File { .. } => self.clone(),
Selection::Route { file_id, .. }
| Selection::Track { file_id, .. }
Selection::Track { file_id, .. }
| Selection::TrackSegment { file_id, .. }
| Selection::Waypoints { file_id }
| Selection::Waypoint { file_id, .. } => Selection::File {
@@ -378,7 +335,7 @@ impl Selection {
}
/// Selects all the elements of the same kind as the selected ones, in the same place: all
/// the files, all the routes (or tracks) of the file, all the segments of the track, all the waypoints
/// the files, all the tracks of the file, all the segments of the track, all the waypoints
/// of the file. All the files when nothing is selected. `None` when there is nothing to
/// select (the waypoints node, or a file that does not exist).
pub fn all_at_level(&self, files: &Files, order: &[FileId]) -> Option<Selection> {
@@ -386,10 +343,6 @@ impl Selection {
Selection::Empty | Selection::File { .. } => Some(Selection::File {
file_ids: order.iter().copied().collect(),
}),
Selection::Route { file_id, .. } => Some(Selection::Route {
file_id: *file_id,
rte_ids: files.get(file_id)?.rte.iter().map(|rte| rte.id).collect(),
}),
Selection::Track { file_id, .. } => Some(Selection::Track {
file_id: *file_id,
trk_ids: files.get(file_id)?.trk.iter().map(|trk| trk.id).collect(),
@@ -418,7 +371,7 @@ impl Selection {
/// The element next to the selected ones, as a selection of that one element: the next one
/// (`down`) or the previous one among the elements of the same kind, in the same place.
/// The routes, tracks, segments and waypoints stop at their ends, the files wrap around and skip
/// The tracks, segments and waypoints stop at their ends, the files wrap around and skip
/// the ones that are already selected. `None` when there is no such element.
pub fn neighbour(&self, files: &Files, order: &[FileId], down: bool) -> Option<Selection> {
match self {
@@ -440,13 +393,6 @@ impl Selection {
}
}
}
Selection::Route { file_id, rte_ids } => {
let ids: Vec<RouteId> = files.get(file_id)?.rte.iter().map(|r| r.id).collect();
Some(Selection::Route {
file_id: *file_id,
rte_ids: [neighbour(&ids, rte_ids, down)?].into(),
})
}
Selection::Track { file_id, trk_ids } => {
let ids: Vec<TrackId> = files.get(file_id)?.trk.iter().map(|t| t.id).collect();
Some(Selection::Track {
+18 -73
View File
@@ -87,7 +87,6 @@ fn new(engine: &mut TestEngine, name: &str) -> bool {
Command::New(New {
name,
trackpoint: None,
route: false,
}),
)
}
@@ -183,52 +182,6 @@ fn test_metadata_renames_selected_file() {
assert_eq!(file.info.desc.as_deref(), Some("about"));
}
#[test]
fn test_rename_names_every_state_of_the_file_and_is_not_undoable() {
let mut engine = TestEngine::default();
new(&mut engine, "first");
new(&mut engine, "other");
let id = engine.order()[0];
let other = engine.order()[1];
let other_file = engine.history.current().unwrap()[&other].clone();
engine.run(Action::Select {
selection: Selection::File {
file_ids: [id].into(),
},
mode: SelectMode::Replace,
});
assert!(edit(
&mut engine,
Command::Metadata(Metadata {
name: "edited",
desc: "",
})
));
assert!(engine.run(Action::Rename {
file_id: id,
name: "written".to_owned(),
}));
assert_eq!(engine.last_diff().unwrap().modified, vec![id]);
assert_eq!(engine.file_structure(&id).unwrap().name, "written");
// nothing to undo for it: the edits before are undone, and the file keeps its name
engine.run(Action::Undo);
engine.run(Action::Undo);
assert_eq!(engine.file_structure(&id).unwrap().name, "written");
engine.run(Action::Redo);
engine.run(Action::Redo);
assert_eq!(engine.file_structure(&id).unwrap().name, "written");
// the other file is still the same object, in every state
assert!(Rc::ptr_eq(
&engine.history.current().unwrap()[&other],
&other_file
));
// naming it as it is already called changes nothing
assert!(!engine.run(Action::Rename {
file_id: id,
name: "written".to_owned(),
}));
}
#[test]
fn test_metadata_without_selection_does_not_modify_files() {
let mut engine = TestEngine::default();
@@ -1169,6 +1122,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();
@@ -1472,7 +1443,6 @@ mod per_file_history {
.execute(Action::Edit(Command::New(New {
name,
trackpoint: None,
route: false,
})))
.unwrap();
*engine.order().last().unwrap()
@@ -1499,31 +1469,6 @@ mod per_file_history {
engine.file_structure(&id).unwrap().name.clone()
}
#[test]
fn test_rename_names_every_state_of_the_file() {
let mut engine = Engine::<PerFileHistory>::default();
let id = new_file(&mut engine, "a");
select(&mut engine, &[id]);
rename(&mut engine, "b");
rename(&mut engine, "c");
let outcome = engine
.execute(Action::Rename {
file_id: id,
name: "written".to_owned(),
})
.unwrap();
assert_eq!(outcome.diff.unwrap().modified, vec![id]);
assert_eq!(name_of(&engine, id), "written");
// the edits are still there to undo, the name stays
engine.execute(Action::Undo).unwrap();
assert!(engine.can_undo());
engine.execute(Action::Undo).unwrap();
assert!(!engine.can_undo());
assert_eq!(name_of(&engine, id), "written");
engine.execute(Action::Redo).unwrap();
assert_eq!(name_of(&engine, id), "written");
}
#[test]
fn test_creating_a_file_is_not_undoable() {
let mut engine = Engine::<PerFileHistory>::default();
+36 -88
View File
@@ -18,9 +18,9 @@ use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::{
File, FileId, FileInfo, Route, RouteId, Track, TrackId, TrackInfo, TrackSegment,
TrackSegmentId, TrackpointCategories, TrackpointChunk, TrackpointChunkId, Waypoint,
WaypointChunk, WaypointChunkId, Waypoints,
File, FileId, FileInfo, Track, TrackId, TrackInfo, TrackSegment, TrackSegmentId,
TrackpointCategories, TrackpointChunk, TrackpointChunkId, Waypoint, WaypointChunk,
WaypointChunkId, Waypoints,
};
/// The version that is written.
@@ -54,17 +54,10 @@ fn parse<'a, T: Deserialize<'a>>(data: &'a [u8]) -> Result<T, DecodeError> {
/// A file without its trackpoints and waypoints, which are in chunks.
pub struct FileRecord {
info: FileInfo,
routes: Vec<RouteRecord>,
tracks: Vec<TrackRecord>,
waypoints: Vec<WaypointChunkId>,
}
struct RouteRecord {
id: RouteId,
info: TrackInfo,
segment: SegmentRecord,
}
struct TrackRecord {
id: TrackId,
info: TrackInfo,
@@ -76,35 +69,24 @@ struct SegmentRecord {
chunks: Vec<TrackpointChunkId>,
}
impl From<v1::SegmentRecord1> for SegmentRecord {
fn from(segment: v1::SegmentRecord1) -> Self {
Self {
id: TrackSegmentId(segment.id),
chunks: segment.chunks.into_iter().map(TrackpointChunkId).collect(),
}
}
}
impl From<v1::FileRecord1> for FileRecord {
fn from(record: v1::FileRecord1) -> Self {
Self {
info: record.info.into(),
routes: record
.routes
.into_iter()
.map(|route| RouteRecord {
id: RouteId(route.id),
info: route.info.into(),
segment: route.segment.into(),
})
.collect(),
tracks: record
.tracks
.into_iter()
.map(|track| TrackRecord {
id: TrackId(track.id),
info: track.info.into(),
segments: track.segments.into_iter().map(Into::into).collect(),
segments: track
.segments
.into_iter()
.map(|segment| SegmentRecord {
id: TrackSegmentId(segment.id),
chunks: segment.chunks.into_iter().map(TrackpointChunkId).collect(),
})
.collect(),
})
.collect(),
waypoints: record.waypoints.into_iter().map(WaypointChunkId).collect(),
@@ -126,27 +108,16 @@ impl FileRecord {
info: self.info,
..Default::default()
};
let segment = |record: SegmentRecord| {
let mut built = TrackSegment::default();
built.id = record.id;
for chunk in &record.chunks {
built.push_shared(trackpoint_chunks(chunk)?);
}
Some(built)
};
for route in self.routes {
file.rte.push(Route {
id: route.id,
info: route.info,
seg: segment(route.segment)?,
});
}
for track in self.tracks {
let trkseg = track
.segments
.into_iter()
.map(segment)
.collect::<Option<Vec<_>>>()?;
let mut trkseg = Vec::with_capacity(track.segments.len());
for segment in track.segments {
let mut built = TrackSegment::default();
built.id = segment.id;
for chunk in &segment.chunks {
built.push_shared(trackpoint_chunks(chunk)?);
}
trkseg.push(built);
}
file.trk.push(Track {
id: track.id,
info: track.info,
@@ -321,20 +292,6 @@ mod tests {
});
let mut empty = TrackSegment::default();
empty.id = TrackSegmentId(id(6));
// a route, whose segment shares the chunk of the track
let mut route_segment = TrackSegment::default();
route_segment.id = TrackSegmentId(id(10));
route_segment.push_shared(segment.chunks()[0].clone());
file.rte.push(Route {
id: RouteId(id(9)),
info: TrackInfo {
name: Some("route".into()),
type_: Some("Hiking".into()),
color: Some("00ff00".into()),
..Default::default()
},
seg: route_segment,
});
file.trk.push(Track {
id: TrackId(id(2)),
info: TrackInfo {
@@ -395,7 +352,9 @@ mod tests {
HashMap<WaypointChunkId, Rc<WaypointChunk>>,
) {
let trackpoints = file
.segments()
.trk
.iter()
.flat_map(|track| &track.trkseg)
.flat_map(|segment| segment.chunks().iter().map(|c| (c.id, c.clone())))
.collect();
let waypoints = file
@@ -414,28 +373,19 @@ mod tests {
})
}
fn assert_same_segment(a: &TrackSegment, b: &TrackSegment) {
assert_eq!(a.id, b.id);
assert_eq!(a.len(), b.len());
for (a, b) in a.chunks().iter().zip(b.chunks()) {
assert!(Rc::ptr_eq(a, b), "the chunks are the ones that were given");
}
}
fn assert_same_file(a: &File, b: &File) {
assert_eq!(a.id, b.id);
assert_eq!(a.info, b.info);
assert_eq!(a.rte.len(), b.rte.len());
for (a, b) in a.rte.iter().zip(&b.rte) {
assert_eq!((a.id, &a.info), (b.id, &b.info));
assert_same_segment(&a.seg, &b.seg);
}
assert_eq!(a.trk.len(), b.trk.len());
for (a, b) in a.trk.iter().zip(&b.trk) {
assert_eq!((a.id, &a.info), (b.id, &b.info));
assert_eq!(a.trkseg.len(), b.trkseg.len());
for (a, b) in a.trkseg.iter().zip(&b.trkseg) {
assert_same_segment(a, b);
assert_eq!(a.id, b.id);
assert_eq!(a.len(), b.len());
for (a, b) in a.chunks().iter().zip(b.chunks()) {
assert!(Rc::ptr_eq(a, b), "the chunks are the ones that were given");
}
}
}
assert_eq!(a.wpt.len(), b.wpt.len());
@@ -475,7 +425,7 @@ mod tests {
.unwrap()
.build(file.id, &|_| None, &|_| None)
.unwrap();
assert!(built.rte.is_empty() && built.trk.is_empty() && built.wpt.is_empty());
assert!(built.trk.is_empty() && built.wpt.is_empty());
}
/// The names of the categories of a trackpoint.
@@ -661,15 +611,13 @@ mod tests {
"70733a2f2f6578616d706c652e636f6d2f736f6d656f6e65021868747470733a2f2f6578616d706c652e636f",
"6d2f66696c65012074657874206f662068747470733a2f2f6578616d706c652e636f6d2f66696c651a687474",
"70733a2f2f6578616d706c652e636f6d2f66696c652d32012274657874206f662068747470733a2f2f657861",
"6d706c652e636f6d2f66696c652d320180a0abfef9620110000000000000000000000000000000090105726f",
"75746500000000010648696b696e6701063030666630300000100000000000000000000000000000000a0110",
"000000000000000000000000000000040110000000000000000000000000000000020105747261636b010363",
"6d740104646573630103737263021968747470733a2f2f6578616d706c652e636f6d2f747261636b01217465",
"7874206f662068747470733a2f2f6578616d706c652e636f6d2f747261636b1b68747470733a2f2f6578616d",
"706c652e636f6d2f747261636b2d32012374657874206f662068747470733a2f2f6578616d706c652e636f6d",
"2f747261636b2d3201074379636c696e67010666663030303001000000000000e03f01000000000000184002",
"1000000000000000000000000000000003011000000000000000000000000000000004100000000000000000",
"000000000000000600011000000000000000000000000000000005",
"6d706c652e636f6d2f66696c652d320180a0abfef96201100000000000000000000000000000000201057472",
"61636b0103636d740104646573630103737263021968747470733a2f2f6578616d706c652e636f6d2f747261",
"636b012174657874206f662068747470733a2f2f6578616d706c652e636f6d2f747261636b1b68747470733a",
"2f2f6578616d706c652e636f6d2f747261636b2d32012374657874206f662068747470733a2f2f6578616d70",
"6c652e636f6d2f747261636b2d3201074379636c696e67010666663030303001000000000000e03f01000000",
"0000001840021000000000000000000000000000000003011000000000000000000000000000000004100000",
"000000000000000000000000000600011000000000000000000000000000000005",
);
const TRACKPOINTS_V1: &str = concat!(
"01020667726176656c0761737068616c74010470617468010668696b696e6701046d74623003000000000000",
+10 -29
View File
@@ -8,8 +8,8 @@ use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::{
Author, Categories, File, FileInfo, Link, LngLat, TrackInfo, TrackSegment, Trackpoint,
TrackpointCategories, Waypoint, WaypointId,
Author, Categories, File, FileInfo, Link, LngLat, TrackInfo, Trackpoint, TrackpointCategories,
Waypoint, WaypointId,
};
#[derive(Serialize, Deserialize)]
@@ -133,18 +133,10 @@ impl From<TrackInfo1> for TrackInfo {
#[derive(Serialize, Deserialize)]
pub struct FileRecord1 {
pub info: FileInfo1,
pub routes: Vec<RouteRecord1>,
pub tracks: Vec<TrackRecord1>,
pub waypoints: Vec<Uuid>,
}
#[derive(Serialize, Deserialize)]
pub struct RouteRecord1 {
pub id: Uuid,
pub info: TrackInfo1,
pub segment: SegmentRecord1,
}
#[derive(Serialize, Deserialize)]
pub struct TrackRecord1 {
pub id: Uuid,
@@ -158,35 +150,24 @@ pub struct SegmentRecord1 {
pub chunks: Vec<Uuid>,
}
impl SegmentRecord1 {
fn new(segment: &TrackSegment) -> Self {
Self {
id: segment.id.0,
chunks: segment.chunks().iter().map(|chunk| chunk.id.0).collect(),
}
}
}
impl FileRecord1 {
pub fn new(file: &File) -> Self {
Self {
info: (&file.info).into(),
routes: file
.rte
.iter()
.map(|route| RouteRecord1 {
id: route.id.0,
info: (&route.info).into(),
segment: SegmentRecord1::new(&route.seg),
})
.collect(),
tracks: file
.trk
.iter()
.map(|track| TrackRecord1 {
id: track.id.0,
info: (&track.info).into(),
segments: track.trkseg.iter().map(SegmentRecord1::new).collect(),
segments: track
.trkseg
.iter()
.map(|segment| SegmentRecord1 {
id: segment.id.0,
chunks: segment.chunks().iter().map(|chunk| chunk.id.0).collect(),
})
.collect(),
})
.collect(),
waypoints: file.wpt.chunks().iter().map(|chunk| chunk.id.0).collect(),
+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 {
+2 -1
View File
@@ -217,7 +217,8 @@ impl Persister {
.files
.get(id)
.is_none_or(|saved| !Rc::ptr_eq(saved, file));
for chunk in file.segments().flat_map(|segment| segment.chunks()) {
let segments = file.trk.iter().flat_map(|track| &track.trkseg);
for chunk in segments.flat_map(|segment| segment.chunks()) {
let key = ChunkKey::trackpoints(chunk.id.0);
if chunks.insert(key) && changed && !self.chunks.contains(&key) {
batch
-15
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"] }
@@ -34,10 +25,4 @@ notify = "8.2.0"
notify-debouncer-mini = "0.7.0"
tauri-plugin-dialog = "2.8.2"
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"]
}
+4
View File
@@ -34,3 +34,7 @@ pub fn optional(array: Option<Vec<u8>>) -> Bytes {
pub fn f64_bytes(values: &[f64]) -> Vec<u8> {
values.iter().flat_map(|v| v.to_le_bytes()).collect()
}
pub fn i64_bytes(values: &[i64]) -> Vec<u8> {
values.iter().flat_map(|v| v.to_le_bytes()).collect()
}
+65 -380
View File
@@ -1,21 +1,16 @@
//! The files of the engine and the file system: picking files and folders, saving, closing, and
//! what the frontend shows of it (see `workspace`).
//!
//! The commands that can lose the edits of a file (closing, opening another folder) take what to do
//! with the files that have some: the frontend asks the user, and the files that have edits stay
//! open if it does not say.
//! The files of the engine and the file system: picking files and folders, saving, and what the
//! frontend shows of it (see `workspace`).
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::path::PathBuf;
use gpx_engine::{ExportOptions, FileId, api};
use serde::Deserialize;
use gpx_engine::api;
use tauri::{AppHandle, Runtime, State};
use tauri_plugin_dialog::{DialogExt, FilePath};
use uuid::Uuid;
use crate::state::AppState;
use crate::workspace::{Entry, Unsaved, WorkspaceState, free_path};
use crate::workspace::{Unsaved, WorkspaceState};
fn paths(picked: Vec<FilePath>) -> Vec<PathBuf> {
picked
@@ -24,32 +19,6 @@ fn paths(picked: Vec<FilePath>) -> Vec<PathBuf> {
.collect()
}
/// Asks where to write a GPX file, proposing `file_name` in `folder`. `None` if the user cancelled.
fn ask_save_path<R: Runtime>(
app: &AppHandle<R>,
file_name: &str,
folder: Option<&Path>,
) -> Option<PathBuf> {
let mut dialog = app
.dialog()
.file()
.add_filter("GPX", &["gpx"])
.set_file_name(file_name);
if let Some(folder) = folder {
dialog = dialog.set_directory(folder);
}
dialog.blocking_save_file()?.into_path().ok()
}
/// Asks for a folder, starting in `folder`. `None` if the user cancelled.
fn ask_folder<R: Runtime>(app: &AppHandle<R>, folder: Option<&Path>) -> Option<PathBuf> {
let mut dialog = app.dialog().file();
if let Some(folder) = folder {
dialog = dialog.set_directory(folder);
}
dialog.blocking_pick_folder()?.into_path().ok()
}
#[tauri::command(async)]
pub fn workspace_state(state: State<AppState>) -> WorkspaceState {
state.core(|core| core.workspace_state())
@@ -66,160 +35,17 @@ pub fn open_files<R: Runtime>(app: AppHandle<R>, state: State<AppState>) -> api:
let Some(picked) = picked else {
return api::Outcome::failed_none();
};
open_paths(state, paths(picked), None)
}
/// Opens files that are on the disk, like the ones of the tree of the open folder. They get selected.
/// With `preview`, a single file is open as a preview (a single click in the tree, see
/// `Workspace::open`); otherwise they are open for good, even the preview.
#[tauri::command(async)]
pub fn open_paths(
state: State<AppState>,
paths: Vec<PathBuf>,
preview: Option<bool>,
) -> api::Outcome {
let files = paths(picked);
state.core(move |core| {
let outcome = core
.workspace
.open(&mut core.engine, &paths, preview.unwrap_or_default());
core.commit(None);
let outcome = core.workspace.open_files(&mut core.engine, &files, true);
core.keep_workspace();
core.persist();
outcome
})
}
/// The files are open for good: the preview among them is not a preview anymore (the user did
/// something to it that the engine does not see, like hiding it).
#[tauri::command(async)]
pub fn keep_files(state: State<AppState>, file_ids: Vec<Uuid>) {
state.core(move |core| {
core.workspace.keep(&file_ids);
core.commit(None);
})
}
/// Writes the files among `ids` that are not the ones on the disk, asking where to put the ones
/// that have no place: the file dialog for a single one, a folder for several of them. Says whether
/// they were written, which is not the case if the user cancelled.
///
/// The files whose file on the disk was replaced are overwritten: the frontend asks before.
fn write_unsaved<R: Runtime>(
app: &AppHandle<R>,
state: &AppState,
ids: Vec<Uuid>,
) -> Result<bool, String> {
let (unlinked, start) = {
let ids = ids.clone();
state.core(move |core| {
(
core.workspace.unlinked(&core.engine, &ids),
core.workspace.folder.clone(),
)
})
};
let mut chosen = BTreeMap::new();
let mut folder = None;
match unlinked.as_slice() {
[] => {}
[(id, name)] => match ask_save_path(app, &format!("{name}.gpx"), start.as_deref()) {
Some(path) => {
chosen.insert(*id, path);
}
None => return Ok(false),
},
_ => match ask_folder(app, start.as_deref()) {
Some(path) => folder = Some(path),
None => return Ok(false),
},
}
state.core(move |core| {
let result = core
.workspace
.save(&mut core.engine, &ids, &chosen, folder.as_deref());
core.wrote(result)
})
}
/// Writes files to the disk, replacing what is there. The ones that are not on the disk yet go in
/// their folder, or where the user says. Says whether they were written (`false` if the user
/// cancelled).
#[tauri::command(async)]
pub fn save_files<R: Runtime>(
app: AppHandle<R>,
state: State<AppState>,
file_ids: Vec<Uuid>,
) -> Result<bool, String> {
write_unsaved(&app, &state, file_ids)
}
/// Writes a file where the user says, which is where the file is from then on. Says whether it was
/// written (`false` if the user cancelled).
#[tauri::command(async)]
pub fn save_file_as<R: Runtime>(
app: AppHandle<R>,
state: State<AppState>,
file_id: Uuid,
) -> Result<bool, String> {
let (name, current, folder) = state.core(move |core| {
let name = core
.engine
.file_structure(&FileId(file_id))
.map(|structure| structure.name.clone());
let status = core.workspace_state();
let file = status.files.get(&file_id.to_string());
let current = file.and_then(|file| file.path.clone().map(PathBuf::from));
let folder = file
.and_then(|file| file.folder.clone().map(PathBuf::from))
.or(status.folder.map(PathBuf::from));
(name, current, folder)
});
let Some(name) = name else {
return Ok(false);
};
// where the file is, or else where it would be written
let folder = current
.as_ref()
.and_then(|path| path.parent().map(Path::to_path_buf))
.or(folder);
let Some(path) = ask_save_path(&app, &format!("{name}.gpx"), folder.as_deref()) else {
return Ok(false);
};
state.core(move |core| {
let result = core.workspace.save_as(&mut core.engine, file_id, &path);
core.wrote(result)
})
}
/// Reads files again from the disk: the edits they have are lost (they are one undo step).
#[tauri::command(async)]
pub fn reload_files(state: State<AppState>, file_ids: Vec<Uuid>) -> Result<api::Outcome, String> {
state.core(move |core| {
let outcome = core.workspace.reload(&mut core.engine, &file_ids);
core.commit(None);
outcome
})
}
/// The files among `ids` that are not the ones on the disk, saved first if `unsaved` says so.
/// Says whether to go on, which is not the case if the user cancelled saving them.
fn settle<R: Runtime>(
app: &AppHandle<R>,
state: &AppState,
ids: Vec<Uuid>,
unsaved: Option<Unsaved>,
) -> Result<bool, String> {
if unsaved != Some(Unsaved::Save) {
return Ok(true);
}
let unsaved_ids = state.core(move |core| core.workspace.unsaved(&core.engine, &ids));
if unsaved_ids.is_empty() {
return Ok(true);
}
write_unsaved(app, state, unsaved_ids)
}
/// Opens the folder that the user picks, which is watched. Its files are not opened. The folder
/// that was open is closed with its files: `unsaved` says what to do with the ones that have
/// unsaved edits.
/// Opens the folder that the user picks: its GPX files are opened and it is watched. The folder
/// that was open is closed, `unsaved` says what to do with its files that have unsaved edits.
#[tauri::command(async)]
pub fn open_folder<R: Runtime>(
app: AppHandle<R>,
@@ -234,221 +60,80 @@ pub fn open_folder<R: Runtime>(
else {
return Ok(api::Outcome::failed_none());
};
let all = state.core(|core| core.workspace.all(&core.engine));
if !settle(&app, &state, all, unsaved)? {
return Ok(api::Outcome::failed_none());
}
state.core(move |core| {
let discard = unsaved.is_some();
let outcome = core
.workspace
.open_folder(&mut core.engine, &folder, discard);
core.commit(None);
Ok(outcome)
.open_folder(&mut core.engine, &folder, unsaved);
core.keep_workspace();
core.persist();
core.watch();
core.announce(None);
outcome
})
}
/// Closes the folder: it is not watched anymore, and the files are closed with it. `unsaved` says
/// what to do with the ones that have unsaved edits (they stay open without it).
/// Closes the folder: it is not watched anymore, and its files are closed. `unsaved` says what to
/// do with the ones that have unsaved edits (they stay without it).
#[tauri::command(async)]
pub fn close_folder<R: Runtime>(
app: AppHandle<R>,
pub fn close_folder(
state: State<AppState>,
unsaved: Option<Unsaved>,
) -> Result<api::Outcome, String> {
let all = state.core(|core| core.workspace.all(&core.engine));
if !settle(&app, &state, all, unsaved)? {
return Ok(api::Outcome::failed_none());
}
state.core(move |core| {
let outcome = core
.workspace
.close_folder(&mut core.engine, unsaved.is_some());
core.commit(None);
Ok(outcome)
let outcome = core.workspace.close_folder(&mut core.engine, unsaved);
core.keep_workspace();
core.persist();
core.watch();
core.announce(None);
outcome
})
}
/// Closes files. `unsaved` says what to do with the ones that have unsaved edits: they are saved
/// first, or the edits are lost (they stay open without it).
/// Writes files to the disk, replacing what is there. The ones that are not on the disk yet go in
/// the open folder, or where the user says if there is none.
#[tauri::command(async)]
pub fn close_files<R: Runtime>(
pub fn save_files<R: Runtime>(
app: AppHandle<R>,
state: State<AppState>,
file_ids: Vec<Uuid>,
unsaved: Option<Unsaved>,
) -> Result<api::Outcome, String> {
if !settle(&app, &state, file_ids.clone(), unsaved)? {
return Ok(api::Outcome::failed_none());
}
state.core(move |core| {
let outcome = core
.workspace
.close_files(&mut core.engine, &file_ids, unsaved.is_some());
core.commit(None);
Ok(outcome)
})
}
/// The folders and GPX files that are in a folder of the open folder, or in it (the root of the
/// tree when no path is given).
#[tauri::command(async)]
pub fn list_folder(state: State<AppState>, path: Option<PathBuf>) -> Result<Vec<Entry>, String> {
state.core(move |core| {
let Some(path) = path.or_else(|| core.workspace.folder.clone()) else {
return Ok(vec![]);
};
core.workspace.list_folder(&path)
})
}
/// What the files are exported with, see `ExportOptions`.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExportArguments {
time: bool,
hr: bool,
cad: bool,
atemp: bool,
power: bool,
osm: bool,
}
impl From<ExportArguments> for ExportOptions {
fn from(arguments: ExportArguments) -> Self {
Self {
time: arguments.time,
hr: arguments.hr,
cad: arguments.cad,
atemp: arguments.atemp,
power: arguments.power,
osm: arguments.osm,
}
}
}
/// Writes copies of files where the user says: a file dialog for a single one, a folder for
/// several. The files stay as they are. Says whether they were written (`false` if the user
/// cancelled).
#[tauri::command(async)]
pub fn export_files<R: Runtime>(
app: AppHandle<R>,
state: State<AppState>,
file_ids: Vec<Uuid>,
options: ExportArguments,
) -> Result<bool, String> {
let options = ExportOptions::from(options);
let files: Vec<(String, Vec<u8>)> = state.core(move |core| {
file_ids
.iter()
.filter_map(|id| {
let name = core.engine.file_structure(&FileId(*id))?.name.clone();
Some((name, api::export_file(&core.engine, *id, options)?))
})
.collect()
});
let write = |path: PathBuf, bytes: &[u8]| {
crate::store::write_atomically(&path, bytes)
.map_err(|error| format!("{}: {error}", path.display()))
};
match files.as_slice() {
[] => Ok(false),
[(name, bytes)] => {
let Some(path) = ask_save_path(&app, &format!("{name}.gpx"), None) else {
return Ok(false);
};
write(path, bytes).map(|()| true)
}
_ => {
let Some(folder) = ask_folder(&app, None) else {
return Ok(false);
};
let mut written: Vec<PathBuf> = vec![];
for (name, bytes) in &files {
let path = free_path(&folder, name, |path| written.iter().any(|w| w == path));
write(path.clone(), bytes)?;
written.push(path);
}
Ok(true)
}
}
}
/// Makes a folder in a folder of the open folder, called `name` (numbered if that is taken). Gives
/// its path.
#[tauri::command(async)]
pub fn create_folder(
state: State<AppState>,
parent: PathBuf,
name: String,
) -> Result<PathBuf, String> {
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.
#[tauri::command(async)]
pub fn rename_path(state: State<AppState>, path: PathBuf, name: String) -> Result<(), String> {
state.core(move |core| {
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)
})
}
/// Moves files and folders of the open folder into a folder of it. The open files follow.
#[tauri::command(async)]
pub fn move_paths(
state: State<AppState>,
paths: Vec<PathBuf>,
folder: PathBuf,
) -> Result<(), String> {
let (ids, unlinked, folder) = {
let ids = file_ids.clone();
state.core(move |core| {
(
ids.clone(),
core.workspace.unlinked(&core.engine, &ids),
core.workspace.folder.clone(),
)
})
};
let mut chosen = BTreeMap::new();
// with a folder open, a new file goes in it: nobody is asked
let to_ask = if folder.is_some() { vec![] } else { unlinked };
for (id, name) in to_ask {
let mut dialog = app
.dialog()
.file()
.add_filter("GPX", &["gpx"])
.set_file_name(format!("{name}.gpx"));
if let Some(folder) = &folder {
dialog = dialog.set_directory(folder);
}
match dialog
.blocking_save_file()
.and_then(|path| path.into_path().ok())
{
Some(path) => {
chosen.insert(id, path);
}
// cancelled: the others are not saved either
None => return Ok(()),
}
}
state.core(move |core| {
let result = core.workspace.move_paths(&paths, &folder);
core.commit(None);
let result = core.workspace.save(&core.engine, &ids, &chosen);
core.keep_workspace();
core.announce(None);
result
})
}
/// Moves files and folders of the open folder to the trash. The open files that were among them
/// are closed, unless they have edits: they stay open, as gone from the disk.
#[tauri::command(async)]
pub fn delete_paths(state: State<AppState>, paths: Vec<PathBuf>) -> Result<api::Outcome, String> {
state.core(move |core| {
let outcome = core
.workspace
.delete_paths(&mut core.engine, &paths, to_trash)?;
core.commit(None);
Ok(outcome)
})
}
/// Moves files and folders to the trash of the system.
fn to_trash(paths: &[PathBuf]) -> Result<(), String> {
#[allow(unused_mut)]
let mut trash = trash::TrashContext::default();
// without asking the Finder, which needs a permission
#[cfg(target_os = "macos")]
{
use trash::macos::{DeleteMethod, TrashContextExtMacos};
trash.set_delete_method(DeleteMethod::NsFileManager);
}
trash.delete_all(paths).map_err(|error| {
eprintln!("the files cannot be deleted: {error}");
crate::workspace::DELETE_FAILED.to_owned()
})
}
+3 -15
View File
@@ -7,8 +7,6 @@ use uuid::Uuid;
use crate::state::AppState;
/// Names and describes the selected files or tracks. The files on the disk keep their name: see
/// `disk::rename_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))
@@ -24,16 +22,6 @@ pub fn style(
state.run(move |e| api::style(e, color.as_deref(), opacity, width))
}
#[tauri::command(async)]
pub fn convert(state: State<AppState>) -> api::Outcome {
state.run(api::convert)
}
#[tauri::command(async)]
pub fn new_route(state: State<AppState>) -> api::Outcome {
state.run(api::new_route)
}
#[tauri::command(async)]
pub fn new_track(state: State<AppState>) -> api::Outcome {
state.run(api::new_track)
@@ -151,12 +139,12 @@ pub fn create_artificial_timestamps(
#[tauri::command(async)]
pub fn merge(state: State<AppState>, merge_type: MergeType, remove_gaps: bool) -> api::Outcome {
state.core(move |core| core.creating(None, false, |e| api::merge(e, merge_type, remove_gaps)))
state.run(move |e| api::merge(e, merge_type, remove_gaps))
}
#[tauri::command(async)]
pub fn extract(state: State<AppState>) -> api::Outcome {
state.core(|core| core.creating(None, false, api::extract))
state.run(api::extract)
}
#[tauri::command(async)]
@@ -226,5 +214,5 @@ pub fn split(
at: u32,
split_type: SplitType,
) -> api::Outcome {
state.core(move |core| core.creating(None, false, |e| api::split(e, revision, at, split_type)))
state.run(move |e| api::split(e, revision, at, split_type))
}
+2 -12
View File
@@ -1,7 +1,5 @@
//! Creating, loading, deleting, moving, copying and pasting files and their elements, and undoing.
use std::path::PathBuf;
use gpx_engine::api;
use tauri::State;
use tauri::ipc::{InvokeBody, Request};
@@ -16,16 +14,8 @@ pub fn new_file(
lng: Option<f64>,
lat: Option<f64>,
ele: Option<f64>,
route: Option<bool>,
folder: Option<PathBuf>,
) -> api::Outcome {
let route = route.unwrap_or_default();
// in `folder` if it is given, otherwise like the selected file, otherwise in the open folder
state.core(move |core| {
core.creating(folder, true, |e| {
api::new_file(e, &name, lng, lat, ele, route)
})
})
state.run(move |e| api::new_file(e, &name, lng, lat, ele))
}
/// The files are in the body, one after the other, the headers `lengths` and `names` (JSON,
@@ -71,7 +61,7 @@ fn percent_decode(value: &str) -> Option<String> {
#[tauri::command(async)]
pub fn duplicate(state: State<AppState>) -> api::Outcome {
state.core(|core| core.creating(None, false, api::duplicate))
state.run(api::duplicate)
}
#[tauri::command(async)]
-1
View File
@@ -12,4 +12,3 @@ pub mod queries;
pub mod selection;
pub mod statistics;
pub mod storage;
pub mod system;
+12
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)]
@@ -69,6 +79,7 @@ pub fn export_file(
atemp: bool,
power: bool,
osm: bool,
as_route: bool,
) -> Bytes {
let options = ExportOptions {
time,
@@ -77,6 +88,7 @@ pub fn export_file(
atemp,
power,
osm,
as_route,
};
optional(state.read(move |e| api::export_file(e, file_id, options)))
}
-10
View File
@@ -21,16 +21,6 @@ pub fn arrow_select(state: State<AppState>, down: bool, add: bool) -> api::Outco
state.run(move |e| api::arrow_select(e, down, add))
}
#[tauri::command(async)]
pub fn select_routes(
state: State<AppState>,
file_id: Uuid,
route_ids: Vec<Uuid>,
mode: SelectMode,
) -> api::Outcome {
state.run(move |e| api::select_routes(e, file_id, &route_ids, mode))
}
#[tauri::command(async)]
pub fn select_tracks(
state: State<AppState>,
+12 -10
View File
@@ -17,7 +17,15 @@ macro_rules! f64_getters {
)*};
}
f64_getters!(total_distance, slope_segment_slopes, lng, lat, ele);
f64_getters!(
total_distance,
slope,
slope_segment_slope,
slope_segment_distance,
lng,
lat,
ele
);
macro_rules! optional_f64_getters {
($($name:ident),*) => {$(
@@ -30,16 +38,10 @@ macro_rules! optional_f64_getters {
optional_f64_getters!(speed, hr, cad, atemp, power);
/// The index of the first trackpoint of each smoothed elevation segment of the selection.
/// Timestamps in milliseconds since the epoch (`NO_TIME` when missing), as `i64`.
#[tauri::command(async)]
pub fn slope_segment_starts(state: State<AppState>) -> Bytes {
u32s(&state.read(|e| api::slope_segment_starts(e).to_vec()))
}
/// What the buffers do not hold for each trackpoint of the selection, for the one at `index`.
#[tauri::command(async)]
pub fn selection_point(state: State<AppState>, index: usize) -> Option<api::SelectionPoint> {
state.read(move |e| api::selection_point(e, index))
pub fn timestamps(state: State<AppState>) -> Bytes {
optional(state.read(|e| api::timestamps(e).map(i64_bytes)))
}
#[tauri::command(async)]
-28
View File
@@ -1,28 +0,0 @@
//! What the app asks of the system, outside of the files.
use std::path::PathBuf;
use tauri::{AppHandle, Runtime};
use tauri_plugin_opener::OpenerExt;
/// Opens a web page (or an email to write) with the app of the system for it: the links of the
/// page are not followed in the window of the app. Only `http`, `https` and `mailto` addresses are
/// opened.
#[tauri::command(async)]
pub fn open_url<R: Runtime>(app: AppHandle<R>, url: String) -> Result<(), String> {
let allowed = ["http://", "https://", "mailto:"];
if !allowed.iter().any(|scheme| url.starts_with(scheme)) {
return Err(format!("{url} is not a web address"));
}
app.opener()
.open_url(url, None::<&str>)
.map_err(|error| error.to_string())
}
/// Shows a file or a folder in the file manager of the system (the Finder...).
#[tauri::command(async)]
pub fn reveal_path<R: Runtime>(app: AppHandle<R>, path: PathBuf) -> Result<(), String> {
app.opener()
.reveal_item_in_dir(path)
.map_err(|error| error.to_string())
}
+14 -61
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)
@@ -48,19 +48,9 @@ pub fn run() {
}
},
));
// on macOS, the app has a menu bar of its own (Windows and Linux have none by default)
#[cfg(target_os = "macos")]
let builder = builder.menu(menu);
register_commands(builder)
.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);
@@ -89,38 +79,13 @@ pub fn run() {
});
}
#[cfg(target_os = "macos")]
fn menu<R: tauri::Runtime>(app: &tauri::AppHandle<R>) -> tauri::Result<tauri::menu::Menu<R>> {
use tauri::menu::{AboutMetadata, Menu, PredefinedMenuItem, Submenu};
// the name of the product, as macOS would otherwise name the items after the binary
let name = app.package_info().name.clone();
let about = AboutMetadata {
name: Some(name.clone()),
..Default::default()
};
Menu::with_items(
app,
&[&Submenu::with_items(
app,
&name,
true,
&[
&PredefinedMenuItem::about(app, Some(&format!("About {name}")), Some(about))?,
&PredefinedMenuItem::separator(app)?,
&PredefinedMenuItem::quit(app, Some(&format!("Quit {name}")))?,
],
)?],
)
}
/// 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,
selection::select_all,
selection::arrow_select,
selection::select_routes,
selection::select_tracks,
selection::select_segments,
selection::select_waypoint_group,
@@ -141,8 +106,6 @@ pub fn register_commands<R: tauri::Runtime>(builder: tauri::Builder<R>) -> tauri
// edits and tools
edit::metadata,
edit::style,
edit::convert,
edit::new_route,
edit::new_track,
edit::new_track_segment,
edit::new_waypoint,
@@ -173,6 +136,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,
@@ -180,8 +144,9 @@ pub fn register_commands<R: tauri::Runtime>(builder: tauri::Builder<R>) -> tauri
queries::waypoint_coordinates,
// statistics
statistics::total_distance,
statistics::slope_segment_starts,
statistics::slope_segment_slopes,
statistics::slope,
statistics::slope_segment_slope,
statistics::slope_segment_distance,
statistics::lng,
statistics::lat,
statistics::ele,
@@ -190,7 +155,7 @@ pub fn register_commands<R: tauri::Runtime>(builder: tauri::Builder<R>) -> tauri
statistics::cad,
statistics::atemp,
statistics::power,
statistics::selection_point,
statistics::timestamps,
statistics::selection_statistics,
statistics::slice_statistics,
statistics::surface_starts,
@@ -219,23 +184,11 @@ pub fn register_commands<R: tauri::Runtime>(builder: tauri::Builder<R>) -> tauri
// the file system
disk::workspace_state,
disk::open_files,
disk::open_paths,
disk::keep_files,
disk::open_folder,
disk::close_folder,
disk::close_files,
disk::save_files,
disk::save_file_as,
disk::reload_files,
disk::export_files,
disk::list_folder,
disk::create_folder,
disk::rename_path,
disk::rename_file,
disk::move_paths,
disk::delete_paths,
// the system
system::open_url,
system::reveal_path,
])
}
#[cfg(test)]
mod tests;
+33 -127
View File
@@ -5,7 +5,7 @@
//! watcher of the open folder), and the commands send that thread jobs: they are done one after the
//! other, in the order they were sent.
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use std::sync::mpsc::{self, Sender};
use std::sync::{Arc, Mutex};
use std::thread;
@@ -18,7 +18,7 @@ use notify_debouncer_mini::{DebounceEventResult, Debouncer, new_debouncer};
use serde::Serialize;
use crate::store::FileStorage;
use crate::workspace::{Workspace, WorkspaceState, signature};
use crate::workspace::{Workspace, WorkspaceState};
/// Tells the frontend that something happened that it did not ask for: a name and a JSON value.
pub type Emit = Arc<dyn Fn(&str, serde_json::Value) + Send + Sync>;
@@ -32,8 +32,6 @@ pub struct Core {
storage: Arc<FileStorage>,
persister: Persister,
watcher: Option<Debouncer<notify::RecommendedWatcher>>,
/// What the watcher watches, see `Workspace::watched`.
watching: Vec<(PathBuf, bool)>,
jobs: Sender<Job>,
emit: Emit,
}
@@ -52,7 +50,6 @@ impl Core {
persister: Persister::default(),
storage,
watcher: None,
watching: vec![],
jobs,
emit,
};
@@ -89,50 +86,15 @@ impl Core {
if paths.is_empty() {
return;
}
let outcome = self.workspace.open(&mut self.engine, paths, false);
(self.emit)("files-opened", to_json(&outcome));
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 {
let preview = self.workspace.preview;
let preview_before = preview.and_then(|id| signature(&self.engine, id));
let result = f(&mut self.engine);
// the preview is open for good once something is done to it
let kept = preview.is_some_and(|id| signature(&self.engine, id) != preview_before);
if let Some(id) = preview.filter(|_| kept) {
self.workspace.keep(&[id]);
}
// and it goes when something else is selected
let dropped = self.workspace.drop_preview(&mut self.engine);
if kept || dropped.is_some() {
self.commit(dropped.as_ref());
} else {
self.persist();
}
result
}
/// After files were written (`result`): what changed in the engine 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)
}
/// After a change of the files or of where they are: the workspace and the engine are kept, and
/// the frontend is told (`outcome` is what changed in the engine, if it did not ask for it).
pub fn commit(&mut self, outcome: Option<&api::Outcome>) {
let outcome = self.workspace.open_files(&mut self.engine, paths, true);
self.keep_workspace();
self.persist();
self.announce(outcome);
(self.emit)("files-opened", to_json(&outcome));
self.announce(None);
}
/// Writes the workspace, and watches what it holds (a file may have been opened or closed).
pub fn keep_workspace(&mut self) {
pub fn keep_workspace(&self) {
self.workspace.write(self.storage.root());
self.watch();
}
pub fn workspace_state(&self) -> WorkspaceState {
@@ -147,16 +109,13 @@ impl Core {
(self.emit)("workspace-changed", to_json(&self.workspace_state()));
}
/// Watches the open folder, and the folders of the files that are linked outside of it. Does
/// nothing if that is what is watched already.
/// Watches the open folder (and only it).
pub fn watch(&mut self) {
let wanted = self.workspace.watched();
if wanted == self.watching && (self.watcher.is_some() || wanted.is_empty()) {
return;
}
self.watcher = None;
self.watching = wanted.clone();
if wanted.is_empty() {
let Some(folder) = self.workspace.folder.clone() else {
return;
};
if !Path::new(&folder).is_dir() {
return;
}
let jobs = self.jobs.clone();
@@ -172,86 +131,22 @@ impl Core {
);
match debouncer {
Ok(mut debouncer) => {
for (path, recursive) in &wanted {
let mode = if *recursive {
RecursiveMode::Recursive
} else {
RecursiveMode::NonRecursive
};
if let Err(error) = debouncer.watcher().watch(path, mode) {
eprintln!("{} cannot be watched: {error}", path.display());
}
match debouncer.watcher().watch(&folder, RecursiveMode::Recursive) {
Ok(()) => self.watcher = Some(debouncer),
Err(error) => eprintln!("the folder cannot be watched: {error}"),
}
self.watcher = Some(debouncer);
}
Err(error) => eprintln!("the files cannot be watched: {error}"),
Err(error) => eprintln!("the folder cannot be watched: {error}"),
}
}
fn on_disk_changed(&mut self, paths: &[PathBuf]) {
// the tree of the folder shows the disk
let in_folder: Vec<&PathBuf> = paths
.iter()
.filter(|path| {
self.workspace
.folder
.as_ref()
.is_some_and(|f| path.starts_with(f))
})
.collect();
if !in_folder.is_empty() {
(self.emit)("folder-changed", to_json(&in_folder));
let outcome = self.workspace.reconcile(&mut self.engine, Some(paths));
if let Some(outcome) = outcome {
self.workspace.write(self.storage.root());
self.persist();
self.announce(Some(&outcome));
}
if let Some(outcome) = self.workspace.reconcile(&mut self.engine, Some(paths)) {
self.commit(Some(&outcome));
}
}
/// Runs `f`, which creates files (a new file, a copy, the result of a split...). Where they go
/// when they are saved is the folder of the files they come from (the selected ones, before
/// `f`), if it is in the open folder. `default_folder` says whether a file with nothing to
/// come from goes in the open folder: a new file does.
pub fn creating(
&mut self,
folder: Option<PathBuf>,
default_folder: bool,
f: impl FnOnce(&mut Engine) -> api::Outcome,
) -> api::Outcome {
let selected: Vec<uuid::Uuid> = self
.engine
.selection()
.file_ids()
.into_iter()
.map(|gpx_engine::FileId(id)| id)
.collect();
let dir = folder
.map(|folder| crate::workspace::canonical(&folder))
.or_else(|| self.workspace.source_dir(&selected))
.or_else(|| {
default_folder
.then(|| self.workspace.folder.clone())
.flatten()
});
let mut outcome = f(&mut self.engine);
if let Some(dir) = dir {
self.workspace.inherit(outcome.added(), &dir);
// what is made in a folder is written there at once, so that the tree shows it
let made: Vec<uuid::Uuid> = outcome
.added()
.iter()
.filter_map(|id| uuid::Uuid::parse_str(id).ok())
.filter(|id| self.workspace.dirs.contains_key(id))
.collect();
match self.workspace.save_new(&mut self.engine, &made) {
Ok(renamed) => outcome = outcome.merge(renamed),
Err(error) if !outcome.has_error() => {
outcome = outcome.merge(api::Outcome::failed(error));
}
Err(_) => {}
}
}
self.commit(None);
outcome
}
}
@@ -280,6 +175,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));
@@ -299,9 +201,13 @@ impl AppState {
result.recv().expect("the engine thread stopped")
}
/// Runs `f` on the engine, which can change: what changed is kept (see `Core::editing`).
/// Runs `f` on the engine, which can change: what changed is kept.
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 = f(&mut core.engine);
core.persist();
result
})
}
/// 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();
}
}
+365
View File
@@ -0,0 +1,365 @@
//! The commands, called the way the frontend calls them (through the IPC of Tauri), on the sample
//! files of the engine.
use serde_json::{Value, json};
use tauri::test::{INVOKE_KEY, get_ipc_response, mock_builder, mock_context, noop_assets};
use tauri::webview::InvokeRequest;
use tauri::{WebviewWindow, ipc::CallbackFn, ipc::InvokeBody, ipc::InvokeResponseBody};
struct App(WebviewWindow<tauri::test::MockRuntime>);
impl App {
fn new() -> Self {
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();
// the app has to outlive its window
std::mem::forget(app);
Self(window)
}
fn request(
&self,
cmd: &str,
body: InvokeBody,
headers: tauri::http::HeaderMap,
) -> InvokeResponseBody {
get_ipc_response(
&self.0,
InvokeRequest {
cmd: cmd.into(),
callback: CallbackFn(0),
error: CallbackFn(1),
url: "tauri://localhost".parse().unwrap(),
body,
headers,
invoke_key: INVOKE_KEY.to_string(),
},
)
.unwrap_or_else(|error| panic!("{cmd} failed: {error}"))
}
fn call(&self, cmd: &str, args: Value) -> Value {
match self.request(cmd, InvokeBody::Json(args), Default::default()) {
InvokeResponseBody::Json(json) => serde_json::from_str(&json).unwrap(),
InvokeResponseBody::Raw(_) => panic!("{cmd} returned bytes"),
}
}
fn bytes(&self, cmd: &str, args: Value) -> Vec<u8> {
match self.request(cmd, InvokeBody::Json(args), Default::default()) {
InvokeResponseBody::Raw(bytes) => bytes,
InvokeResponseBody::Json(_) => panic!("{cmd} returned JSON"),
}
}
fn load(&self, names: &[&str]) -> Value {
let mut data = vec![];
let mut lengths = vec![];
for name in names {
let file = std::fs::read(format!("../gpx-rs/data/{name}.gpx")).unwrap();
lengths.push(file.len());
data.extend(file);
}
let header = |value: Value| value.to_string().replace('"', "%22").parse().unwrap();
let mut headers = tauri::http::HeaderMap::new();
headers.insert("lengths", header(json!(lengths)));
headers.insert("names", header(json!(names)));
match self.request("load_files", InvokeBody::Raw(data), headers) {
InvokeResponseBody::Json(json) => serde_json::from_str(&json).unwrap(),
InvokeResponseBody::Raw(_) => panic!("load_files returned bytes"),
}
}
}
fn f64s(bytes: &[u8]) -> Vec<f64> {
bytes
.as_chunks::<8>()
.0
.iter()
.map(|chunk| f64::from_le_bytes(*chunk))
.collect()
}
#[test]
fn loads_files_and_describes_them() {
let app = App::new();
let outcome = app.load(&["simple", "with_tracks"]);
assert_eq!(outcome["changed"], true);
assert_eq!(outcome["added"].as_array().unwrap().len(), 2);
assert!(outcome.get("error").is_none());
let order = app.call("file_order", json!({}));
let first = order[0].as_str().unwrap();
assert_eq!(
app.call("selection", json!({})),
json!({ "type": "file", "fileIds": [first] })
);
let structure = app.call("file_structure", json!({ "fileId": first }));
assert_eq!(structure["name"], "simple");
let segment = &structure["tracks"][0]["segments"][0];
let length = segment["length"].as_f64().unwrap() as usize;
assert!(length > 0);
// coordinates are little-endian doubles, lng and lat for each trackpoint
let coordinates =
f64s(&app.bytes("segment_coordinates", json!({ "segmentId": segment["id"] })));
assert_eq!(coordinates.len(), 2 * length);
let statistics = app.call("file_statistics", json!({ "fileId": first }));
assert!(statistics["totalDistance"].as_f64().unwrap() > 0.0);
assert!(
statistics["bounds"]["west"].as_f64().unwrap()
<= statistics["bounds"]["east"].as_f64().unwrap()
);
assert_eq!(
app.call(
"file_structure",
json!({ "fileId": "00000000-0000-0000-0000-000000000000" })
),
Value::Null
);
}
#[test]
fn reads_the_statistics_of_the_selection() {
let app = App::new();
app.load(&["simple"]);
let distance = f64s(&app.bytes("total_distance", json!({})));
assert!(distance.len() > 1);
assert_eq!(f64s(&app.bytes("lng", json!({}))).len(), distance.len());
assert!(
app.call("selection_statistics", json!({}))["totalDistance"]
.as_f64()
.unwrap()
> 0.0
);
// optional arrays start with a byte telling whether they are there
let hr = app.bytes("hr", json!({}));
assert_eq!(hr[0], 0);
assert!(
app.call("slice_statistics", json!({ "start": 1, "end": 3 }))["totalDistance"].is_number()
);
assert_eq!(
app.call("slice_statistics", json!({ "start": 0, "end": 100000 })),
Value::Null
);
app.load(&["with_hr"]);
app.call("select_all", json!({}));
let hr = app.bytes("hr", json!({}));
assert_eq!(hr[0], 1);
assert_eq!((hr.len() - 1) % 8, 0);
}
#[test]
fn edits_undoes_and_selects() {
let app = App::new();
let outcome = app.call(
"new_file",
json!({ "name": "route", "lng": 4.4, "lat": 50.8 }),
);
assert_eq!(outcome["changed"], true);
// each file has its own history, which starts when it appears
assert_eq!(app.call("can_undo", json!({})), false);
let id = app.call("file_order", json!({}))[0].clone();
let outcome = app.call("metadata", json!({ "name": "renamed", "desc": "" }));
assert_eq!(outcome["modified"], json!([id]));
assert_eq!(
app.call("file_structure", json!({ "fileId": id }))["name"],
"renamed"
);
let outcome = app.call("select", json!({ "fileIds": [], "mode": "replace" }));
assert_eq!(outcome["selectionChanged"], true);
assert_eq!(app.call("selection", json!({})), json!({ "type": "empty" }));
app.call("select", json!({ "fileIds": [id], "mode": "toggle" }));
assert_eq!(app.call("can_undo", json!({})), true);
app.call("undo", json!({}));
assert_eq!(
app.call("file_structure", json!({ "fileId": id }))["name"],
"route"
);
assert_eq!(app.call("can_redo", json!({})), true);
// creating the file is not something to undo
assert_eq!(app.call("can_undo", json!({})), false);
let outcome = app.call("undo", json!({}));
assert_eq!(outcome["changed"], false);
assert_eq!(app.call("file_order", json!({})), json!([id]));
// what cannot be done says why
let outcome = app.call("reverse", json!({}));
assert_eq!(outcome["changed"], false);
assert!(outcome["error"].is_string());
}
#[test]
fn moves_and_clipboard() {
let app = App::new();
app.load(&["simple", "with_tracks"]);
let ids = app.call("file_order", json!({}));
app.call("select", json!({ "fileIds": [ids[0]], "mode": "replace" }));
app.call("copy", json!({}));
assert_eq!(
app.call("clipboard", json!({})),
json!({ "type": "files", "ids": [ids[0]], "cut": false })
);
let outcome = app.call(
"move_elements",
json!({
"what": { "type": "file", "fileIds": [ids[0]] },
"to": { "type": "files", "index": 9007199254740991u64 },
}),
);
assert_eq!(outcome["orderChanged"], true);
assert_eq!(app.call("file_order", json!({})), json!([ids[1], ids[0]]));
}
#[test]
fn waypoints_exports_and_routing_revisions() {
let app = App::new();
app.call("new_file", json!({ "name": "file" }));
let outcome = app.call(
"new_waypoint",
json!({ "lng": 4.4, "lat": 50.8, "ele": 100, "name": "summit", "desc": "", "icon": "Summit", "link": "https://example.com" }),
);
assert_eq!(outcome["changed"], true);
let file = app.call("file_order", json!({}))[0].clone();
let waypoint =
app.call("file_structure", json!({ "fileId": file }))["waypoints"][0]["id"].clone();
let details = app.call(
"waypoint",
json!({ "fileId": file, "waypointId": waypoint }),
);
assert_eq!(details["name"], "summit");
assert_eq!(details["sym"], "Summit");
assert_eq!(details["links"][0]["href"], "https://example.com");
let exported = app.bytes(
"export_file",
json!({ "fileId": file, "time": true, "hr": true, "cad": true, "atemp": true, "power": true, "osm": true, "asRoute": false }),
);
assert_eq!(exported[0], 1);
assert!(
String::from_utf8(exported[1..].to_vec())
.unwrap()
.contains("<wpt")
);
assert_eq!(app.call("exportable_data", json!({ "fileIds": [file] })), 0);
let stale = app.call(
"route",
json!({
"revision": 12345, "start": 0, "end": 0,
"lng": [4.4], "lat": [50.8], "ele": [0],
"attributes": { "surface": { "starts": [0], "values": [0], "names": [] } },
"anchors": [],
}),
);
assert_eq!(stale["changed"], false);
assert!(stale["error"].as_str().unwrap().contains("routing buffers"));
}
#[test]
fn keeps_settings_for_the_session() {
let app = App::new();
app.call(
"set_setting",
json!({ "key": "units", "value": "\"metric\"" }),
);
assert_eq!(
app.call("open_storage", json!({}))["settings"]["units"],
"\"metric\""
);
app.call("delete_setting", json!({ "key": "units" }));
assert_eq!(app.call("open_storage", json!({}))["settings"], json!({}));
}
#[test]
fn the_files_are_still_there_in_the_next_session() {
use crate::state::AppState;
use gpx_engine::api;
let directory =
std::env::temp_dir().join(format!("gpx-studio-session-{}", uuid::Uuid::new_v4()));
let data = std::fs::read("../gpx-rs/data/simple.gpx").unwrap();
let first = AppState::open(&directory, std::sync::Arc::new(|_, _| {})).unwrap();
let lengths = [data.len()];
let names = ["simple".to_string()];
first.run(move |e| api::load_files(e, &data, &lengths, &names));
let order = first.read(api::file_order);
let second = AppState::open(&directory, std::sync::Arc::new(|_, _| {})).unwrap();
assert_eq!(second.read(api::file_order), order);
let outcome = second.read(api::Outcome::everything);
assert_eq!(
serde_json::to_value(&outcome).unwrap()["added"],
serde_json::json!(order)
);
std::fs::remove_dir_all(directory).unwrap();
}
#[test]
fn only_gpx_files_that_exist_are_taken_from_what_the_system_gives() {
let directory = std::env::temp_dir().join(format!("gpx-studio-args-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&directory).unwrap();
let track = directory.join("track.GPX");
std::fs::copy("../gpx-rs/data/simple.gpx", &track).unwrap();
let text = directory.join("notes.txt");
std::fs::write(&text, "x").unwrap();
let arguments = [
"--flag".to_string(),
track.to_string_lossy().into_owned(),
text.to_string_lossy().into_owned(),
directory.join("missing.gpx").to_string_lossy().into_owned(),
];
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 std::sync::{Arc, Mutex};
let directory = std::env::temp_dir().join(format!("gpx-studio-open-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&directory).unwrap();
let track = directory.join("track.gpx");
std::fs::copy("../gpx-rs/data/simple.gpx", &track).unwrap();
let events = Arc::new(Mutex::new(vec![]));
let sink = events.clone();
let state = AppState::open(
directory.join("store"),
Arc::new(move |name, payload| sink.lock().unwrap().push((name.to_string(), payload))),
)
.unwrap();
state.open_external(vec![track.clone()]);
// opening it again is a selection, not another file
state.open_external(vec![track]);
assert_eq!(state.read(api::file_order).len(), 1);
assert!(matches!(
state.read(api::selection),
api::Selection::File { .. }
));
let events = events.lock().unwrap();
let opened: Vec<_> = events
.iter()
.filter(|(name, _)| name == "files-opened")
.collect();
assert_eq!(opened.len(), 2);
assert_eq!(opened[0].1["added"].as_array().unwrap().len(), 1);
assert!(opened[1].1["added"].as_array().unwrap().is_empty());
assert!(events.iter().any(|(name, _)| name == "workspace-changed"));
std::fs::remove_dir_all(directory).unwrap();
}
+767 -688
View File
File diff suppressed because it is too large. Load diff
+3 -14
View File
@@ -6,7 +6,7 @@
"build": {
"beforeDevCommand": "npm --prefix ../website run dev -- --port 4283",
"devUrl": "http://localhost:4283",
"beforeBuildCommand": "npm --prefix ../website run build:desktop",
"beforeBuildCommand": "BASE_PATH='' npm --prefix ../website run build",
"frontendDist": "../website/build"
},
"app": {
@@ -18,17 +18,14 @@
"width": 1400,
"height": 900,
"minWidth": 800,
"minHeight": 600,
"maximized": true,
"dragDropEnabled": false
"minHeight": 600
}
],
"security": { "csp": null }
},
"bundle": {
"active": true,
"targets": ["app", "dmg", "appimage", "deb", "rpm", "nsis"],
"macOS": { "signingIdentity": "-" },
"targets": "all",
"fileAssociations": [
{
"ext": ["gpx"],
@@ -45,13 +42,5 @@
"icons/icon.icns",
"icons/icon.ico"
]
},
"plugins": {
"updater": {
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDE5NTFDQzVDOUYwNEMyNEMKUldSTXdnU2ZYTXhSR1ZXRDV6aVErc3dUWXBaK0VGSitYRnFFR21hZ2s5UEJTT01aYkE5Unp5c0cKdW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEFFNTU3Q0Y1NzhFODkyMTEKUldRUmt1aDQ5WHhWcmdXQmx0UG83V29TenRxSVJjdkc4ckN1Zi93ajc3ZUhVUVp3eFlCOXphb1IK",
"endpoints": [
"https://github.com/gpxstudio/gpx.studio/releases/latest/download/latest.json"
]
}
}
}
-800
View File
@@ -1,800 +0,0 @@
//! The commands, called the way the frontend calls them (through the IPC of Tauri), on the sample
//! files of the engine.
use serde_json::{Value, json};
use tauri::test::{INVOKE_KEY, get_ipc_response, mock_builder, mock_context, noop_assets};
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 window = tauri::WebviewWindowBuilder::new(&app, "main", Default::default())
.build()
.unwrap();
// the app has to outlive its window
std::mem::forget(app);
Self(window)
}
fn request(
&self,
cmd: &str,
body: InvokeBody,
headers: tauri::http::HeaderMap,
) -> InvokeResponseBody {
get_ipc_response(
&self.0,
InvokeRequest {
cmd: cmd.into(),
callback: CallbackFn(0),
error: CallbackFn(1),
url: ORIGIN.parse().unwrap(),
body,
headers,
invoke_key: INVOKE_KEY.to_string(),
},
)
.unwrap_or_else(|error| panic!("{cmd} failed: {error}"))
}
fn call(&self, cmd: &str, args: Value) -> Value {
match self.request(cmd, InvokeBody::Json(args), Default::default()) {
InvokeResponseBody::Json(json) => serde_json::from_str(&json).unwrap(),
InvokeResponseBody::Raw(_) => panic!("{cmd} returned bytes"),
}
}
/// 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,
InvokeResponseBody::Json(_) => panic!("{cmd} returned JSON"),
}
}
fn load(&self, names: &[&str]) -> Value {
let mut data = vec![];
let mut lengths = vec![];
for name in names {
let file = std::fs::read(format!("../gpx-rs/data/{name}.gpx")).unwrap();
lengths.push(file.len());
data.extend(file);
}
let header = |value: Value| value.to_string().replace('"', "%22").parse().unwrap();
let mut headers = tauri::http::HeaderMap::new();
headers.insert("lengths", header(json!(lengths)));
headers.insert("names", header(json!(names)));
match self.request("load_files", InvokeBody::Raw(data), headers) {
InvokeResponseBody::Json(json) => serde_json::from_str(&json).unwrap(),
InvokeResponseBody::Raw(_) => panic!("load_files returned bytes"),
}
}
}
fn f64s(bytes: &[u8]) -> Vec<f64> {
bytes
.as_chunks::<8>()
.0
.iter()
.map(|chunk| f64::from_le_bytes(*chunk))
.collect()
}
#[test]
fn loads_files_and_describes_them() {
let app = App::new();
let outcome = app.load(&["simple", "with_tracks"]);
assert_eq!(outcome["changed"], true);
assert_eq!(outcome["added"].as_array().unwrap().len(), 2);
assert!(outcome.get("error").is_none());
let order = app.call("file_order", json!({}));
let first = order[0].as_str().unwrap();
assert_eq!(
app.call("selection", json!({})),
json!({ "type": "file", "fileIds": [first] })
);
let structure = app.call("file_structure", json!({ "fileId": first }));
assert_eq!(structure["name"], "simple");
let segment = &structure["tracks"][0]["segments"][0];
let length = segment["length"].as_f64().unwrap() as usize;
assert!(length > 0);
// coordinates are little-endian doubles, lng and lat for each trackpoint
let coordinates =
f64s(&app.bytes("segment_coordinates", json!({ "segmentId": segment["id"] })));
assert_eq!(coordinates.len(), 2 * length);
let statistics = app.call("file_statistics", json!({ "fileId": first }));
assert!(statistics["totalDistance"].as_f64().unwrap() > 0.0);
assert!(
statistics["bounds"]["west"].as_f64().unwrap()
<= statistics["bounds"]["east"].as_f64().unwrap()
);
assert_eq!(
app.call(
"file_structure",
json!({ "fileId": "00000000-0000-0000-0000-000000000000" })
),
Value::Null
);
}
#[test]
fn reads_the_statistics_of_the_selection() {
let app = App::new();
app.load(&["simple"]);
let distance = f64s(&app.bytes("total_distance", json!({})));
assert!(distance.len() > 1);
assert_eq!(f64s(&app.bytes("lng", json!({}))).len(), distance.len());
assert!(
app.call("selection_statistics", json!({}))["totalDistance"]
.as_f64()
.unwrap()
> 0.0
);
// optional arrays start with a byte telling whether they are there
let hr = app.bytes("hr", json!({}));
assert_eq!(hr[0], 0);
// the slope segments are intervals of trackpoints
let starts = app.bytes("slope_segment_starts", json!({}));
let slopes = f64s(&app.bytes("slope_segment_slopes", json!({})));
assert_eq!(starts.len() / 4, slopes.len());
assert!(!slopes.is_empty() && slopes.len() < distance.len());
let point = app.call("selection_point", json!({ "index": 1 }));
assert!(point["slopeSegmentDistance"].is_number());
assert!(point.get("time").is_none());
assert_eq!(
app.call("selection_point", json!({ "index": distance.len() })),
Value::Null
);
assert!(
app.call("slice_statistics", json!({ "start": 1, "end": 3 }))["totalDistance"].is_number()
);
assert_eq!(
app.call("slice_statistics", json!({ "start": 0, "end": 100000 })),
Value::Null
);
app.load(&["with_hr"]);
app.call("select_all", json!({}));
let hr = app.bytes("hr", json!({}));
assert_eq!(hr[0], 1);
assert_eq!((hr.len() - 1) % 8, 0);
}
#[test]
fn edits_undoes_and_selects() {
let app = App::new();
let outcome = app.call(
"new_file",
json!({ "name": "route", "lng": 4.4, "lat": 50.8 }),
);
assert_eq!(outcome["changed"], true);
// each file has its own history, which starts when it appears
assert_eq!(app.call("can_undo", json!({})), false);
let id = app.call("file_order", json!({}))[0].clone();
let outcome = app.call("metadata", json!({ "name": "renamed", "desc": "" }));
assert_eq!(outcome["modified"], json!([id]));
assert_eq!(
app.call("file_structure", json!({ "fileId": id }))["name"],
"renamed"
);
let outcome = app.call("select", json!({ "fileIds": [], "mode": "replace" }));
assert_eq!(outcome["selectionChanged"], true);
assert_eq!(app.call("selection", json!({})), json!({ "type": "empty" }));
app.call("select", json!({ "fileIds": [id], "mode": "toggle" }));
assert_eq!(app.call("can_undo", json!({})), true);
app.call("undo", json!({}));
assert_eq!(
app.call("file_structure", json!({ "fileId": id }))["name"],
"route"
);
assert_eq!(app.call("can_redo", json!({})), true);
// creating the file is not something to undo
assert_eq!(app.call("can_undo", json!({})), false);
let outcome = app.call("undo", json!({}));
assert_eq!(outcome["changed"], false);
assert_eq!(app.call("file_order", json!({})), json!([id]));
// what cannot be done says why
let outcome = app.call("reverse", json!({}));
assert_eq!(outcome["changed"], false);
assert!(outcome["error"].is_string());
}
#[test]
fn moves_and_clipboard() {
let app = App::new();
app.load(&["simple", "with_tracks"]);
let ids = app.call("file_order", json!({}));
app.call("select", json!({ "fileIds": [ids[0]], "mode": "replace" }));
app.call("copy", json!({}));
assert_eq!(
app.call("clipboard", json!({})),
json!({ "type": "files", "ids": [ids[0]], "cut": false })
);
let outcome = app.call(
"move_elements",
json!({
"what": { "type": "file", "fileIds": [ids[0]] },
"to": { "type": "files", "index": 9007199254740991u64 },
}),
);
assert_eq!(outcome["orderChanged"], true);
assert_eq!(app.call("file_order", json!({})), json!([ids[1], ids[0]]));
}
#[test]
fn waypoints_exports_and_routing_revisions() {
let app = App::new();
app.call("new_file", json!({ "name": "file" }));
let outcome = app.call(
"new_waypoint",
json!({ "lng": 4.4, "lat": 50.8, "ele": 100, "name": "summit", "desc": "", "icon": "Summit", "link": "https://example.com" }),
);
assert_eq!(outcome["changed"], true);
let file = app.call("file_order", json!({}))[0].clone();
let waypoint =
app.call("file_structure", json!({ "fileId": file }))["waypoints"][0]["id"].clone();
let details = app.call(
"waypoint",
json!({ "fileId": file, "waypointId": waypoint }),
);
assert_eq!(details["name"], "summit");
assert_eq!(details["sym"], "Summit");
assert_eq!(details["links"][0]["href"], "https://example.com");
let exported = app.bytes(
"export_file",
json!({ "fileId": file, "time": true, "hr": true, "cad": true, "atemp": true, "power": true, "osm": true }),
);
assert_eq!(exported[0], 1);
assert!(
String::from_utf8(exported[1..].to_vec())
.unwrap()
.contains("<wpt")
);
assert_eq!(app.call("exportable_data", json!({ "fileIds": [file] })), 0);
let stale = app.call(
"route",
json!({
"revision": 12345, "start": 0, "end": 0,
"lng": [4.4], "lat": [50.8], "ele": [0],
"attributes": { "surface": { "starts": [0], "values": [0], "names": [] } },
"anchors": [],
}),
);
assert_eq!(stale["changed"], false);
assert!(stale["error"].as_str().unwrap().contains("routing buffers"));
}
#[test]
fn keeps_settings_for_the_session() {
let app = App::new();
app.call(
"set_setting",
json!({ "key": "units", "value": "\"metric\"" }),
);
assert_eq!(
app.call("open_storage", json!({}))["settings"]["units"],
"\"metric\""
);
app.call("delete_setting", json!({ "key": "units" }));
assert_eq!(app.call("open_storage", json!({}))["settings"], json!({}));
}
#[test]
fn the_files_are_still_there_in_the_next_session() {
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()));
let data = std::fs::read("../gpx-rs/data/simple.gpx").unwrap();
let first = AppState::open(&directory, std::sync::Arc::new(|_, _| {})).unwrap();
let lengths = [data.len()];
let names = ["simple".to_string()];
first.run(move |e| api::load_files(e, &data, &lengths, &names));
let order = first.read(api::file_order);
let second = AppState::open(&directory, std::sync::Arc::new(|_, _| {})).unwrap();
assert_eq!(second.read(api::file_order), order);
let outcome = second.read(api::Outcome::everything);
assert_eq!(
serde_json::to_value(&outcome).unwrap()["added"],
serde_json::json!(order)
);
std::fs::remove_dir_all(directory).unwrap();
}
#[test]
fn only_gpx_files_that_exist_are_taken_from_what_the_system_gives() {
let directory = std::env::temp_dir().join(format!("gpx-studio-args-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&directory).unwrap();
let track = directory.join("track.GPX");
std::fs::copy("../gpx-rs/data/simple.gpx", &track).unwrap();
let text = directory.join("notes.txt");
std::fs::write(&text, "x").unwrap();
let arguments = [
"--flag".to_string(),
track.to_string_lossy().into_owned(),
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]);
std::fs::remove_dir_all(directory).unwrap();
}
#[test]
fn a_file_opened_with_the_app_is_opened_selected_and_announced() {
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()));
std::fs::create_dir_all(&directory).unwrap();
let track = directory.join("track.gpx");
std::fs::copy("../gpx-rs/data/simple.gpx", &track).unwrap();
let events = Arc::new(Mutex::new(vec![]));
let sink = events.clone();
let state = AppState::open(
directory.join("store"),
Arc::new(move |name, payload| sink.lock().unwrap().push((name.to_string(), payload))),
)
.unwrap();
state.open_external(vec![track.clone()]);
// opening it again is a selection, not another file
state.open_external(vec![track]);
assert_eq!(state.read(api::file_order).len(), 1);
assert!(matches!(
state.read(api::selection),
api::Selection::File { .. }
));
let events = events.lock().unwrap();
let opened: Vec<_> = events
.iter()
.filter(|(name, _)| name == "files-opened")
.collect();
assert_eq!(opened.len(), 2);
assert_eq!(opened[0].1["added"].as_array().unwrap().len(), 1);
assert!(opened[1].1["added"].as_array().unwrap().is_empty());
assert!(events.iter().any(|(name, _)| name == "workspace-changed"));
std::fs::remove_dir_all(directory).unwrap();
}
#[test]
fn files_are_opened_closed_and_made_in_a_folder() {
let app = App::new();
let folder = std::env::temp_dir().join(format!("gpx-tests-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&folder).unwrap();
let path = folder.join("track.gpx");
std::fs::copy("../gpx-rs/data/simple.gpx", &path).unwrap();
// opened from the disk, clean
let outcome = app.call("open_paths", json!({ "paths": [path] }));
assert_eq!(outcome["added"].as_array().unwrap().len(), 1);
let id = outcome["added"][0].as_str().unwrap().to_string();
let state = app.call("workspace_state", json!({}));
assert_eq!(state["files"][&id]["dirty"], false);
assert!(state["files"][&id]["path"].is_string());
// a new file made in a folder is written there at once, so that the tree shows it
let created = app.call(
"new_file",
json!({ "name": "route", "lng": 4.4, "lat": 50.8, "folder": folder }),
);
let new_id = created["added"][0].as_str().unwrap().to_string();
let state = app.call("workspace_state", json!({}));
assert_eq!(state["files"][&new_id]["dirty"], false);
assert!(state["files"][&new_id]["path"].is_string());
assert!(folder.join("route.gpx").exists());
// the tree needs an open folder
assert_eq!(app.call("list_folder", json!({})), json!([]));
// closing: what is saved goes, what has edits stays unless it is discarded
app.call("select", json!({ "fileIds": [new_id], "mode": "replace" }));
app.call("style", json!({ "color": "#ff0000" }));
app.call("close_files", json!({ "fileIds": [id, new_id] }));
assert_eq!(app.call("file_order", json!({})), json!([new_id]));
app.call(
"close_files",
json!({ "fileIds": [new_id], "unsaved": "discard" }),
);
assert_eq!(app.call("file_order", json!({})), json!([]));
std::fs::remove_dir_all(folder).unwrap();
}
/// A file that is open from outside of any folder follows the disk too.
#[test]
fn a_file_outside_the_open_folder_is_read_again_when_the_disk_changes() {
use std::sync::mpsc;
use std::time::Duration;
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(
directory.clone(),
std::sync::Arc::new(move |name, _| {
let _ = events.send(name.to_string());
}),
)
.unwrap();
let folder = std::env::temp_dir().join(format!("gpx-tests-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&folder).unwrap();
let path = folder.join("track.gpx");
std::fs::copy("../gpx-rs/data/simple.gpx", &path).unwrap();
let opened = path.clone();
let id = state.core(move |core| {
let outcome = core.workspace.open_files(&mut core.engine, &[opened], true);
core.keep_workspace();
outcome.added()[0].clone()
});
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 before = signature(&state);
std::fs::copy("../gpx-rs/data/with_time.gpx", &path).unwrap();
// the debounced watcher tells the frontend that the engine changed
let mut changed = false;
while let Ok(event) = received.recv_timeout(Duration::from_secs(10)) {
if event == "engine-changed" {
changed = true;
break;
}
}
assert!(changed, "the file was not read again");
assert_ne!(signature(&state), before);
std::fs::remove_dir_all(folder).unwrap();
std::fs::remove_dir_all(directory).unwrap();
}
#[test]
fn files_made_from_a_file_of_the_open_folder_are_written_next_to_it_at_once() {
let state = crate::temporary_state();
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();
let sub = folder.join("sub");
let (copied, new_file) = state.core(move |core| {
core.workspace.open_folder(&mut core.engine, &folder, false);
let opened = core
.workspace
.open_files(&mut core.engine, &[sub.join("track.gpx")], true);
core.keep_workspace();
assert_eq!(opened.added().len(), 1);
let copy = core.creating(None, false, gpx_engine::api::duplicate);
let fresh = core.creating(None, true, |e| {
gpx_engine::api::new_file(e, "fresh", None, None, None, false)
});
// a copy of the file goes next to it, a new file with nothing selected in the selection
// of the file that was just made
(copy, fresh)
});
let sub = std::env::temp_dir();
let _ = sub;
assert_eq!(copied.added().len(), 1);
assert_eq!(new_file.added().len(), 1);
let status = state.core(|core| core.workspace_state());
assert!(status.files.values().all(|file| !file.dirty));
let paths: Vec<String> = status
.files
.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)
assert!(
paths
.iter()
.any(|path| std::path::Path::new(path).ends_with("sub/simple.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:?}"
);
}
#[test]
fn the_parts_of_a_split_are_numbered_from_one() {
let state = crate::temporary_state();
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();
let root = folder.clone();
let outcome = state.core(move |core| {
core.workspace.open_folder(&mut core.engine, &root, false);
core.workspace
.open_files(&mut core.engine, &[root.join("track.gpx")], true);
core.keep_workspace();
let revision = core.engine.routing().revision;
core.creating(None, false, |e| {
gpx_engine::api::split(e, revision, 2, gpx_engine::SplitType::Files)
})
});
assert_eq!(outcome.added().len(), 2, "{:?}", outcome.added());
let mut names: Vec<String> = std::fs::read_dir(&folder)
.unwrap()
.flatten()
.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"]);
std::fs::remove_dir_all(folder).unwrap();
}
#[test]
fn files_can_be_reordered() {
let app = App::new();
let mut ids = vec![];
for name in ["a", "b", "c"] {
let outcome = app.call("new_file", json!({ "name": name }));
ids.push(outcome["added"][0].as_str().unwrap().to_string());
}
assert_eq!(app.call("file_order", json!({})), json!(ids));
let outcome = app.call("reorder", json!({ "fileIds": [ids[2]], "index": 0 }));
assert_eq!(outcome["changed"], true);
assert_eq!(outcome["orderChanged"], true);
assert_eq!(
app.call("file_order", json!({})),
json!([ids[2], ids[0], ids[1]])
);
}
/// A folder of its own, with GPX files whose name inside is not the name of the file.
fn folder_with(files: &[&str]) -> std::path::PathBuf {
let folder = std::env::temp_dir().join(format!("gpx-names-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&folder).unwrap();
for name in files {
std::fs::write(
folder.join(format!("{name}.gpx")),
r#"<?xml version="1.0"?><gpx version="1.1" creator="test"><metadata><name>Inside</name></metadata><trk><trkseg><trkpt lat="50.0" lon="4.0"></trkpt><trkpt lat="50.1" lon="4.1"></trkpt></trkseg></trk></gpx>"#,
)
.unwrap();
}
folder
}
fn name_of(app: &App, id: &str) -> String {
app.call("file_structure", json!({ "fileId": id }))["name"]
.as_str()
.unwrap()
.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() {
let app = App::new();
let folder = folder_with(&["outside", "taken"]);
let outcome = app.call(
"open_paths",
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);
// renaming it is an edit of the file only, which is undone
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);
app.call("undo", json!({}));
assert_eq!(name_of(&app, &id), "Inside");
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());
// a name is one that a file can have
app.call("rename_file", json!({ "fileId": id, "name": "a/b" }));
assert!(folder.join("a_b.gpx").exists());
// only the case changes: the same file
app.call("rename_file", json!({ "fileId": id, "name": "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() {
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
let created = app.call(
"new_file",
json!({ "name": "route", "lng": 4.4, "lat": 50.8, "folder": folder }),
);
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!(
app.call("workspace_state", json!({}))["files"][&id]["dirty"],
false
);
// which is not an edit to undo
app.call("select", json!({ "fileIds": [id], "mode": "replace" }));
assert_eq!(app.call("can_undo", json!({})), false);
std::fs::remove_dir_all(folder).unwrap();
}
#[test]
fn a_file_open_as_a_preview_is_replaced_until_it_is_kept_or_edited() {
let app = App::new();
let folder = folder_with(&["a", "b", "c", "d"]);
let path = |name: &str| folder.join(format!("{name}.gpx"));
let open = |name: &str, preview: bool| {
app.call(
"open_paths",
json!({ "paths": [path(name)], "preview": preview }),
)
};
let state = |app: &App| app.call("workspace_state", json!({}))["files"].clone();
let names = |app: &App| -> Vec<String> {
let order = app.call("file_order", json!({}));
order
.as_array()
.unwrap()
.iter()
.map(|id| file_stem_of(app, id.as_str().unwrap()))
.collect()
};
let a = open("a", true)["added"][0].as_str().unwrap().to_string();
assert_eq!(state(&app)[&a]["preview"], true);
// the next preview replaces it
let b = open("b", true)["added"][0].as_str().unwrap().to_string();
assert_eq!(names(&app), ["b"]);
assert_eq!(state(&app)[&b]["preview"], true);
// opened for good (a double click), it stays when another one is previewed
open("b", false);
assert_eq!(state(&app)[&b]["preview"], false);
let c = open("c", true)["added"][0].as_str().unwrap().to_string();
assert_eq!(names(&app), ["b", "c"]);
// something done to the preview keeps it too
app.call("style", json!({ "color": "#ff0000" }));
assert_eq!(state(&app)[&c]["preview"], false);
open("d", true);
assert_eq!(names(&app), ["b", "c", "d"]);
// several files at once are open for good
app.call(
"open_paths",
json!({ "paths": [path("a"), path("d")], "preview": true }),
);
assert_eq!(names(&app), ["b", "c", "d", "a"]);
let files = state(&app);
assert!(
files
.as_object()
.unwrap()
.values()
.all(|file| file["preview"] == false)
);
std::fs::remove_dir_all(folder).unwrap();
}
#[test]
fn the_preview_goes_when_something_else_is_selected_unless_it_was_kept() {
let app = App::new();
let folder = folder_with(&["a", "b", "c"]);
let open = |name: &str, preview: bool| {
app.call(
"open_paths",
json!({ "paths": [folder.join(format!("{name}.gpx"))], "preview": preview }),
)["added"][0]
.as_str()
.map(str::to_string)
};
let order = |app: &App| app.call("file_order", json!({})).as_array().unwrap().len();
let a = open("a", false).unwrap();
// looked at, then something else is selected: it goes
let b = open("b", true).unwrap();
assert_eq!(order(&app), 2);
app.call("select", json!({ "fileIds": [a], "mode": "replace" }));
assert_eq!(order(&app), 1);
// nothing selected: it stays
open("b", true);
app.call("select", json!({ "fileIds": [], "mode": "replace" }));
assert_eq!(order(&app), 2);
// kept (hidden, its menu opened...): it stays when something else is selected
let c = open("c", true).unwrap();
assert_eq!(order(&app), 2, "c replaces b");
app.call("keep_files", json!({ "fileIds": [c] }));
assert_eq!(
app.call("workspace_state", json!({}))["files"][&c]["preview"],
false
);
app.call("select", json!({ "fileIds": [a], "mode": "replace" }));
assert_eq!(order(&app), 2);
let _ = b;
std::fs::remove_dir_all(folder).unwrap();
}
-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>
-11
View File
@@ -18,17 +18,6 @@ pub fn style(color: Option<String>, opacity: Option<f64>, width: Option<f64>) ->
run(|e| api::style(e, color.as_deref(), opacity, width))
}
/// Converts the selected routes to tracks, or the selected tracks or segments to routes.
#[wasm_bindgen]
pub fn convert() -> Outcome {
run(api::convert)
}
#[wasm_bindgen]
pub fn new_route() -> Outcome {
run(api::new_route)
}
#[wasm_bindgen]
pub fn new_track() -> Outcome {
run(api::new_track)
+4 -11
View File
@@ -10,18 +10,11 @@ use crate::ts::*;
// File commands
/// Creates a file and selects it. With `route`, it starts with a route. With `lng` and `lat`, it
/// starts with a segment that holds that trackpoint (at `ele`, 0 by default): the one of its route
/// with `route`, of a track otherwise.
/// Creates a file and selects it. With `lng` and `lat`, it starts with a track and a segment that
/// hold that trackpoint (at `ele`, 0 by default).
#[wasm_bindgen]
pub fn new_file(
name: &str,
lng: Option<f64>,
lat: Option<f64>,
ele: Option<f64>,
route: bool,
) -> Outcome {
run(|e| api::new_file(e, name, lng, lat, ele, route))
pub fn new_file(name: &str, lng: Option<f64>, lat: Option<f64>, ele: Option<f64>) -> Outcome {
run(|e| api::new_file(e, name, lng, lat, ele))
}
/// Loads files as a single command (one undo step). The files are in `data`, one after the
+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
+17 -1
View File
@@ -45,8 +45,10 @@ pub fn selection_statistics() -> GlobalStatistics {
}
/// A file as GPX (UTF-8 bytes), `undefined` if it does not exist. The options say which data of the trackpoints
/// to keep.
/// to keep, and with `as_route` that the segments are written as routes (`rte`) instead of tracks:
/// the anchors are the route points, and the trackpoints between them the points of their path.
#[wasm_bindgen]
#[allow(clippy::too_many_arguments)]
pub fn export_file(
file_id: &str,
time: bool,
@@ -55,6 +57,7 @@ pub fn export_file(
atemp: bool,
power: bool,
osm: bool,
as_route: bool,
) -> Option<Vec<u8>> {
let id = parse_uuid(file_id)?;
let options = ExportOptions {
@@ -64,6 +67,7 @@ pub fn export_file(
atemp,
power,
osm,
as_route,
};
with_engine(|e| api::export_file(e, id, options)).flatten()
}
@@ -101,6 +105,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]
+11 -13
View File
@@ -25,6 +25,9 @@ macro_rules! stats_getter {
stats_getter!(total_distance, Float64Array);
stats_getter!(elevation_gain, Float64Array);
stats_getter!(elevation_loss, Float64Array);
stats_getter!(slope, Float64Array);
stats_getter!(slope_segment_slope, Float64Array);
stats_getter!(slope_segment_distance, Float64Array);
stats_getter!(lng, Float64Array);
stats_getter!(lat, Float64Array);
stats_getter!(ele, Float64Array);
@@ -46,6 +49,14 @@ optional_stats_getter!(moving_distance, Float64Array);
optional_stats_getter!(total_time, BigInt64Array);
optional_stats_getter!(moving_time, BigInt64Array);
optional_stats_getter!(speed, Float64Array);
// Timestamps in milliseconds since the epoch (`NO_TIME`, the smallest i64, when missing).
optional_stats_getter!(timestamps, BigInt64Array);
/// Value of the timestamps of the trackpoints that have none.
#[wasm_bindgen]
pub fn no_time() -> i64 {
gpx_engine::NO_TIME
}
optional_stats_getter!(hr, Float64Array);
optional_stats_getter!(cad, Float64Array);
@@ -85,19 +96,6 @@ categories_getters!(highway_starts, highway_values, highways);
categories_getters!(sac_scale_starts, sac_scale_values, sac_scales);
categories_getters!(mtb_scale_starts, mtb_scale_values, mtb_scales);
// The smoothed elevation segments of the selection, over which the slope is averaged, as
// intervals of trackpoints: `slope_segment_starts` holds the index of the first trackpoint of each
// segment, and `slope_segment_slopes` its slope (%). Their length is in `selection_point`.
stats_getter!(slope_segment_starts, Uint32Array);
stats_getter!(slope_segment_slopes, Float64Array);
/// What the buffers do not hold for each trackpoint of the selection, for the one at `index`
/// (numbered as in the buffers), `undefined` if there is none.
#[wasm_bindgen]
pub fn selection_point(index: usize) -> SelectionPoint {
optional_js(with_engine(|e| api::selection_point(e, index)).flatten()).unchecked_into()
}
/// For each trackpoint of the selection (numbered as in the statistics), the highest tolerance
/// (m) of `reduce` that keeps it: infinite for the ends of the segments.
#[wasm_bindgen]
-8
View File
@@ -41,14 +41,6 @@ pub fn arrow_select(down: bool, add: bool) -> Outcome {
// with the selection when it holds elements of the same kind in the same place (same file, same
// track for segments), otherwise they replace it.
#[wasm_bindgen]
pub fn select_routes(file_id: &str, route_ids_bytes: &[u8], mode: SelectMode) -> Outcome {
match parse_uuid(file_id).zip(uuid_list(route_ids_bytes)) {
Some((file_id, ids)) => run(|e| api::select_routes(e, file_id, &ids, mode.into())),
None => fail("the ids are not UUIDs"),
}
}
#[wasm_bindgen]
pub fn select_tracks(file_id: &str, track_ids_bytes: &[u8], mode: SelectMode) -> Outcome {
match parse_uuid(file_id).zip(uuid_list(track_ids_bytes)) {
+25 -42
View File
@@ -4,7 +4,7 @@
#![allow(clippy::needless_borrows_for_generic_args)]
use js_sys::{Array, Float64Array, Object, Reflect};
use js_sys::{Array, BigInt64Array, Float64Array, Object, Reflect};
use wasm_bindgen::prelude::*;
use wasm_bindgen_test::*;
@@ -16,7 +16,6 @@ use crate::types::*;
const SIMPLE: &[u8] = include_bytes!("../../gpx-rs/data/simple.gpx");
const WITH_TIME: &[u8] = include_bytes!("../../gpx-rs/data/with_time.gpx");
const WITH_SURFACE: &[u8] = include_bytes!("../../gpx-rs/data/with_surface.gpx");
const WITH_ROUTES: &[u8] = include_bytes!("../../gpx-rs/data/with_routes.gpx");
thread_local! {
static LAST: std::cell::RefCell<JsValue> = const { std::cell::RefCell::new(JsValue::UNDEFINED) };
@@ -84,7 +83,7 @@ fn uuid_bytes(ids: &[String]) -> Vec<u8> {
fn test_new_file_is_listed_and_selected() {
start();
assert!(run(crate::command::files::new_file(
"route", None, None, None, false
"route", None, None, None
)));
assert_eq!(last_error(), None);
@@ -113,7 +112,10 @@ fn test_unknown_file_has_no_structure() {
assert!(crate::queries::files::file_structure(&id).is_undefined());
assert!(crate::queries::files::file_structure("not an id").is_undefined());
assert!(crate::queries::files::file_statistics(&id).is_undefined());
assert!(crate::queries::files::export_file(&id, true, true, true, true, true, true).is_none());
assert!(
crate::queries::files::export_file(&id, true, true, true, true, true, true, false)
.is_none()
);
assert_eq!(
crate::queries::coordinates::segment_coordinates(&id).length(),
0
@@ -142,10 +144,7 @@ fn test_loaded_file_has_statistics_and_coordinates() {
assert_eq!(crate::queries::statistics::lng().length(), n);
assert_eq!(crate::queries::statistics::ele().length(), n);
// no timestamps in this file
let point = crate::queries::statistics::selection_point(0);
assert!(get(&point, "slopeSegmentDistance").as_f64().is_some());
assert!(get(&point, "time").is_undefined());
assert!(crate::queries::statistics::selection_point(n as usize).is_undefined());
assert!(crate::queries::statistics::timestamps().is_none());
let structure = crate::queries::files::file_structure(&id);
let segment = get(
@@ -166,8 +165,8 @@ fn test_loaded_file_has_statistics_and_coordinates() {
#[wasm_bindgen_test]
fn test_timestamps_and_categories() {
started_with(&[(WITH_TIME, "time")]);
let point = crate::queries::statistics::selection_point(0);
assert!(get(&point, "time").as_f64().unwrap() > 0.0);
let times: BigInt64Array = crate::queries::statistics::timestamps().unwrap();
assert!(times.length() > 0);
assert!(crate::queries::statistics::total_time().is_some());
started_with(&[(WITH_SURFACE, "surface")]);
@@ -180,14 +179,6 @@ fn test_timestamps_and_categories() {
crate::queries::statistics::surface_starts().length(),
values.len() as u32
);
// the name of the surface of a trackpoint that has one
let starts = crate::queries::statistics::surface_starts().to_vec();
let known = values.iter().position(|v| *v > 0).unwrap();
let point = crate::queries::statistics::selection_point(starts[known] as usize);
assert_eq!(
get(&point, "surface").as_string(),
Some(surfaces[values[known] as usize - 1].clone())
);
}
#[wasm_bindgen_test]
@@ -198,9 +189,7 @@ fn test_the_reason_of_a_failure_can_be_read() {
assert!(!run(crate::command::tools::reverse()));
assert_eq!(last_error().as_deref(), Some("nothing to do"));
// the next call starts afresh
assert!(run(crate::command::files::new_file(
"a", None, None, None, false
)));
assert!(run(crate::command::files::new_file("a", None, None, None)));
assert_eq!(last_error(), None);
// invalid data
@@ -253,9 +242,7 @@ fn test_the_reason_of_a_failure_can_be_read() {
assert!(last_error().is_some());
// answers are not failures
assert!(run(crate::command::files::new_file(
"b", None, None, None, false
)));
assert!(run(crate::command::files::new_file("b", None, None, None)));
assert!(!crate::command::files::can_paste());
assert_eq!(last_error(), None);
}
@@ -264,9 +251,7 @@ fn test_the_reason_of_a_failure_can_be_read() {
fn test_undo_and_redo() {
started_with(&[]);
assert!(!can_undo() && !can_redo());
assert!(run(crate::command::files::new_file(
"a", None, None, None, false
)));
assert!(run(crate::command::files::new_file("a", None, None, None)));
assert!(can_undo() && !can_redo());
assert!(run(undo()));
assert!(order().is_empty());
@@ -283,7 +268,8 @@ fn test_export_and_exportable_data() {
let ids = order();
let bytes =
crate::queries::files::export_file(&ids[0], true, true, true, true, true, true).unwrap();
crate::queries::files::export_file(&ids[0], true, true, true, true, true, true, false)
.unwrap();
assert!(String::from_utf8(bytes).unwrap().contains("<gpx"));
// the time is the first bit
@@ -303,17 +289,18 @@ fn test_export_and_exportable_data() {
}
#[wasm_bindgen_test]
fn test_export_tracks_and_routes() {
started_with(&[(SIMPLE, "track"), (WITH_ROUTES, "routes")]);
let text = |id: &str| {
fn test_export_as_route() {
started_with(&[(SIMPLE, "plain")]);
let id = order().remove(0);
let text = |as_route| {
let bytes =
crate::queries::files::export_file(id, true, true, true, true, true, true).unwrap();
crate::queries::files::export_file(&id, true, true, true, true, true, true, as_route)
.unwrap();
String::from_utf8(bytes).unwrap()
};
let ids = order();
let tracks = text(&ids[0]);
let tracks = text(false);
assert!(tracks.contains("<trk>") && !tracks.contains("<rte>"));
let routes = text(&ids[1]);
let routes = text(true);
assert!(routes.contains("<rte>") && !routes.contains("<trk>"));
assert!(routes.contains("<rtept"));
}
@@ -392,7 +379,7 @@ fn test_move_elements_takes_js_objects() {
fn test_waypoints() {
started_with(&[]);
assert!(run(crate::command::files::new_file(
"file", None, None, None, false
"file", None, None, None
)));
let file = order().remove(0);
assert!(run(crate::command::waypoints::new_waypoint(
@@ -496,9 +483,7 @@ fn test_editing_tools_change_the_statistics() {
#[wasm_bindgen_test]
fn test_last_update_describes_the_last_call_only() {
started_with(&[]);
assert!(run(crate::command::files::new_file(
"a", None, None, None, false
)));
assert!(run(crate::command::files::new_file("a", None, None, None)));
let update = last_outcome();
assert_eq!(array(get(&update, "added")).length(), 1);
assert_eq!(get(&update, "orderChanged").as_bool(), Some(true));
@@ -510,9 +495,7 @@ fn test_last_update_describes_the_last_call_only() {
assert_eq!(get(&update, "orderChanged").as_bool(), Some(false));
assert_eq!(get(&update, "selectionChanged").as_bool(), Some(false));
assert!(run(crate::command::files::new_file(
"b", None, None, None, false
)));
assert!(run(crate::command::files::new_file("b", None, None, None)));
assert!(!run(crate::command::tools::crop(3, 1)));
let update = last_outcome();
assert_eq!(array(get(&update, "added")).length(), 0);
+12 -34
View File
@@ -28,19 +28,16 @@ const FILE_STRUCTURE_TS: &str = r#"
export type Selection =
| { type: 'empty' }
| { type: 'file'; fileIds: string[] }
| { type: 'route'; fileId: string; routeIds: string[] }
| { type: 'track'; fileId: string; trackIds: string[] }
| { type: 'segment'; fileId: string; trackId: string; segmentIds: string[] }
| { type: 'waypoints'; fileId: string }
| { type: 'waypoint'; fileId: string; waypointIds: string[] };
/**
* Where moved elements go: a list of the file tree and the position in it, counted among the
* elements of the list that are not moved. Routes and tracks keep their kind: moved among the
* other kind, routes go after the routes, tracks before the tracks.
* elements of the list that are not moved.
*/
export type MoveTarget =
| { type: 'files'; index: number }
| { type: 'routes'; fileId: string; index: number }
| { type: 'tracks'; fileId: string; index: number }
| { type: 'segments'; fileId: string; trackId: string; index: number }
| { type: 'waypoints'; fileId: string; index: number };
@@ -59,26 +56,17 @@ export interface WaypointDetails {
links?: { href: string; text?: string }[];
sym?: string;
}
/**
* A trackpoint of the selection: what the statistics buffers do not hold for each trackpoint.
* Absent fields are unknown.
*/
export interface SelectionPoint {
/** Slope (%) at the trackpoint. */
slope?: number;
/** The position, elevation and time of a trackpoint. */
export interface TrackpointDetails {
lng: number;
lat: number;
ele: number;
/** ms since epoch */
time?: number;
/** Slope (%) and length (km) of the smoothed elevation segment of the trackpoint. */
slopeSegmentSlope?: number;
slopeSegmentDistance?: number;
surface?: string;
highway?: string;
sacScale?: string;
mtbScale?: string;
}
/** What was copied or cut, to be pasted: the kind of the elements and their ids. */
export interface Clipboard {
type: 'files' | 'routes' | 'tracks' | 'segments' | 'waypoints';
type: 'files' | 'tracks' | 'segments' | 'waypoints';
ids: string[];
cut: boolean;
}
@@ -114,8 +102,6 @@ export interface FileStructure {
id: string;
name: string;
desc?: string;
/** The routes come before the tracks, in the file and in the statistics. */
routes: RouteNode[];
tracks: TrackNode[];
waypoints: WaypointNode[];
/** Changes when the waypoints of the file change: refetch their coordinates. */
@@ -143,22 +129,14 @@ export interface GlobalStatistics {
/** Absent when there are no trackpoints. */
bounds?: { west: number; south: number; east: number; north: number };
}
/** The name, description and style of a route or a track. */
export interface PathInfo {
export interface TrackNode {
id: string;
name?: string;
desc?: string;
/** Style, only present when the file defines it. */
/** Style of the track, only present when the file defines it. */
color?: string;
opacity?: number;
width?: number;
}
/** A route: like a track, with a single segment. */
export interface RouteNode extends PathInfo {
id: string;
segment: SegmentNode;
}
export interface TrackNode extends PathInfo {
id: string;
segments: SegmentNode[];
}
export interface SegmentNode {
@@ -181,8 +159,8 @@ extern "C" {
pub type Selection;
#[wasm_bindgen(typescript_type = "WaypointDetails | undefined")]
pub type WaypointDetails;
#[wasm_bindgen(typescript_type = "SelectionPoint | undefined")]
pub type SelectionPoint;
#[wasm_bindgen(typescript_type = "TrackpointDetails | undefined")]
pub type TrackpointDetails;
#[wasm_bindgen(typescript_type = "MoveTarget")]
pub type MoveTarget;
Loaded 100 of 604 files, more files were not shown because too many files have changed in this diff. Show more