mirror of
https://github.com/gpxstudio/gpx.studio.git
synced 2026-11-18 07:27:43 +00:00
Compare commits
31
Commits
main
..
f1904bc12f
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f1904bc12f | ||
|
|
9afba53e5d | ||
|
|
fd76e0fa46 | ||
|
|
438a87f06f | ||
|
|
a994e16f51 | ||
|
|
639e7491eb | ||
|
|
891a08a3cc | ||
|
|
0c07164dec | ||
|
|
f133d55889 | ||
|
|
fbb636cb06 | ||
|
|
bddceb28aa | ||
|
|
bff84fa24c | ||
|
|
64914f9aa0 | ||
|
|
2abf46c747 | ||
|
|
888f41e979 | ||
|
|
17533586ef | ||
|
|
c6ad088947 | ||
|
|
87d6d5f30e | ||
|
|
dbe894b3a3 | ||
|
|
a921d4b9cd | ||
|
|
b7db73cf77 | ||
|
|
5868595a6c | ||
|
|
eb8e09b835 | ||
|
|
41dc853f65 | ||
|
|
27c0a57cc1 | ||
|
|
497ac120ec | ||
|
|
a486016d96 | ||
|
|
cc5f5653ef | ||
|
|
20222c450d | ||
|
|
69049e1345 | ||
|
|
ed6264444f |
No files matched your search
@@ -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
|
||||
@@ -25,43 +15,49 @@ jobs:
|
||||
with:
|
||||
node-version: 24
|
||||
cache: npm
|
||||
cache-dependency-path: website/package-lock.json
|
||||
cache-dependency-path: |
|
||||
gpx/package-lock.json
|
||||
website/package-lock.json
|
||||
|
||||
- name: Install Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: wasm32-unknown-unknown
|
||||
- name: Install dependencies for gpx
|
||||
run: npm install --prefix gpx
|
||||
|
||||
- name: Install wasm-pack
|
||||
uses: taiki-e/install-action@v2
|
||||
with:
|
||||
tool: wasm-pack
|
||||
|
||||
- name: Test gpx-rs
|
||||
run: cargo test
|
||||
|
||||
- name: Build wasm
|
||||
run: wasm-pack build --target bundler
|
||||
working-directory: wasm
|
||||
- name: Build gpx
|
||||
run: npm run build --prefix gpx
|
||||
|
||||
- name: Install dependencies for website
|
||||
run: npm install --prefix website
|
||||
|
||||
- name: Test website
|
||||
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
|
||||
@@ -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
|
||||
+1
-2
@@ -1,2 +1 @@
|
||||
.DS_Store
|
||||
target/
|
||||
.DS_Store
|
||||
Generated
-5837
File diff suppressed because it is too large.
Load diff
@@ -1,5 +0,0 @@
|
||||
[workspace]
|
||||
members = ["gpx-rs", "wasm", "tauri"]
|
||||
# `cargo test` at the root only tests the engine: the others need their own tooling
|
||||
default-members = ["gpx-rs"]
|
||||
resolver = "3"
|
||||
@@ -25,20 +25,19 @@ Any help is greatly appreciated!
|
||||
|
||||
## Development
|
||||
|
||||
The code is split into four parts:
|
||||
The code is split into two parts:
|
||||
|
||||
- `gpx-rs`: a Rust library for parsing and manipulating GPX files (the engine), and the interface to it that the next two share (`gpx_engine::api`),
|
||||
- `wasm`: the engine for the browser, compiled to WebAssembly,
|
||||
- `tauri`: the desktop app, which runs the engine natively,
|
||||
- `website`: the website itself, which is a [SvelteKit](https://kit.svelte.dev/) application. It also is the UI of the desktop app.
|
||||
- `gpx`: a Typescript library for parsing and manipulating GPX files,
|
||||
- `website`: the website itself, which is a [SvelteKit](https://kit.svelte.dev/) application.
|
||||
|
||||
You will need [Node.js](https://nodejs.org/), [Rust](https://rustup.rs/) and [wasm-pack](https://rustwasm.github.io/wasm-pack/) to build and run the website. See [`tauri`](tauri/README.md) for the desktop app.
|
||||
You will need [Node.js](https://nodejs.org/) to build and run these two parts.
|
||||
|
||||
### Building the WebAssembly engine
|
||||
### Building the `gpx` library
|
||||
|
||||
```bash
|
||||
cd wasm
|
||||
wasm-pack build --target bundler
|
||||
cd gpx
|
||||
npm install
|
||||
npm run build
|
||||
```
|
||||
|
||||
### Running the website
|
||||
@@ -52,18 +51,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,13 +58,15 @@ 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
|
||||
- [tailwindcss](https://github.com/tailwindlabs/tailwindcss) — easy styling
|
||||
- [Chart.js](https://github.com/chartjs/Chart.js) — beautiful and fast charts
|
||||
- Logic:
|
||||
- [immer](https://github.com/immerjs/immer) — complex state management
|
||||
- [Dexie.js](https://github.com/dexie/Dexie.js) — IndexedDB wrapper
|
||||
- [fast-xml-parser](https://github.com/NaturalIntelligence/fast-xml-parser) — fast GPX file parsing
|
||||
- [SortableJS](https://github.com/SortableJS/Sortable) — creating a sortable file tree
|
||||
- Mapping:
|
||||
- [MapLibre GL JS](https://github.com/maplibre/maplibre-gl-js) — beautiful and fast interactive map rendering
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
target/
|
||||
pkg/
|
||||
Generated
+398
@@ -0,0 +1,398 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "android_system_properties"
|
||||
version = "0.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "autocfg"
|
||||
version = "1.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||
|
||||
[[package]]
|
||||
name = "bumpalo"
|
||||
version = "3.20.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.4.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a3eb0f42d6c360dc3f8a821f6bf2fdea7f72bfd36b3076eb0e6d1e9e0752fff4"
|
||||
dependencies = [
|
||||
"find-msvc-tools",
|
||||
"shlex",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
|
||||
|
||||
[[package]]
|
||||
name = "chrono"
|
||||
version = "0.4.45"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"
|
||||
dependencies = [
|
||||
"iana-time-zone",
|
||||
"js-sys",
|
||||
"num-traits",
|
||||
"wasm-bindgen",
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "console_error_panic_hook"
|
||||
version = "0.1.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "core-foundation-sys"
|
||||
version = "0.8.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
|
||||
|
||||
[[package]]
|
||||
name = "find-msvc-tools"
|
||||
version = "0.1.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3e0f1c7c3a72c66fd80abe965175f7523475c0489a87d3ff9d6e8c87d87a9d2d"
|
||||
|
||||
[[package]]
|
||||
name = "futures-core"
|
||||
version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
|
||||
|
||||
[[package]]
|
||||
name = "futures-task"
|
||||
version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
|
||||
|
||||
[[package]]
|
||||
name = "futures-util"
|
||||
version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"futures-task",
|
||||
"pin-project-lite",
|
||||
"slab",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"r-efi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gpx-engine"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"quick-xml",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gpx-rs"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"console_error_panic_hook",
|
||||
"gpx-engine",
|
||||
"js-sys",
|
||||
"uuid",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "iana-time-zone"
|
||||
version = "0.1.65"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"
|
||||
dependencies = [
|
||||
"android_system_properties",
|
||||
"core-foundation-sys",
|
||||
"iana-time-zone-haiku",
|
||||
"js-sys",
|
||||
"log",
|
||||
"wasm-bindgen",
|
||||
"windows-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "iana-time-zone-haiku"
|
||||
version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
|
||||
dependencies = [
|
||||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "js-sys"
|
||||
version = "0.3.106"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"futures-util",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.189"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
|
||||
|
||||
[[package]]
|
||||
name = "log"
|
||||
version = "0.4.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.21.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||
|
||||
[[package]]
|
||||
name = "pin-project-lite"
|
||||
version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.106"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quick-xml"
|
||||
version = "0.42.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.46"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "r-efi"
|
||||
version = "6.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
|
||||
|
||||
[[package]]
|
||||
name = "rustversion"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
|
||||
|
||||
[[package]]
|
||||
name = "shlex"
|
||||
version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
|
||||
|
||||
[[package]]
|
||||
name = "slab"
|
||||
version = "0.4.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.118"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.24"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "uuid"
|
||||
version = "1.26.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce"
|
||||
dependencies = [
|
||||
"getrandom",
|
||||
"js-sys",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen"
|
||||
version = "0.2.129"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"once_cell",
|
||||
"rustversion",
|
||||
"wasm-bindgen-macro",
|
||||
"wasm-bindgen-shared",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-macro"
|
||||
version = "0.2.129"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535"
|
||||
dependencies = [
|
||||
"quote",
|
||||
"wasm-bindgen-macro-support",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-macro-support"
|
||||
version = "0.2.129"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7"
|
||||
dependencies = [
|
||||
"bumpalo",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.6",
|
||||
"wasm-bindgen-shared",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-shared"
|
||||
version = "0.2.129"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-core"
|
||||
version = "0.62.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
|
||||
dependencies = [
|
||||
"windows-implement",
|
||||
"windows-interface",
|
||||
"windows-link",
|
||||
"windows-result",
|
||||
"windows-strings",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-implement"
|
||||
version = "0.60.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-interface"
|
||||
version = "0.59.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-link"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
||||
|
||||
[[package]]
|
||||
name = "windows-result"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-strings"
|
||||
version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
+5
-10
@@ -1,11 +1,6 @@
|
||||
[package]
|
||||
name = "gpx-engine"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
[workspace]
|
||||
members = ["engine", "wasm"]
|
||||
resolver = "3"
|
||||
|
||||
[dependencies]
|
||||
chrono = "0.4.45"
|
||||
postcard = { version = "1.1.3", features = ["use-std"] }
|
||||
quick-xml = "0.42.0"
|
||||
serde = { version = "1.0.229", features = ["derive"] }
|
||||
uuid = { version = "1.26.1", features = ["serde", "v4"] }
|
||||
[profile.release]
|
||||
debug = true
|
||||
+3
-10
@@ -1,10 +1,3 @@
|
||||
# gpx-rs
|
||||
|
||||
The GPX engine: plain Rust, no knowledge of who uses it. Tested natively with `cargo test` (from
|
||||
here or from the root).
|
||||
|
||||
- `src/core`, `src/engine`, `src/storage`: the engine itself.
|
||||
- `src/api`: the interface to the engine that the frontends (`../wasm`, `../tauri`) share. Each
|
||||
function takes the engine and typed arguments, and gives plain data (`api::dto`, serde types, or
|
||||
slices for the numeric buffers). A frontend only converts what crosses: ids from strings or
|
||||
bytes, results to JS objects or JSON, slices to typed arrays or raw bytes.
|
||||
```
|
||||
wasm-pack build wasm --target bundler --out-dir ../pkg
|
||||
```
|
||||
@@ -1,26 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<gpx version="1.1" creator="gpx.studio" xmlns="http://www.topografix.com/GPX/1/1"
|
||||
xmlns:ext="https://example.com/ext/0.1">
|
||||
<metadata>
|
||||
<name>self closing points</name>
|
||||
<desc>Points without children are self-closing elements.</desc>
|
||||
<extensions>
|
||||
<ext:version>2.0</ext:version>
|
||||
<ext:paths/>
|
||||
</extensions>
|
||||
</metadata>
|
||||
<wpt lat="50.0" lon="4.0"/>
|
||||
<wpt lat="50.1" lon="4.1"><name>with children</name></wpt>
|
||||
<wpt lat="50.2" lon="4.2"/>
|
||||
<trk>
|
||||
<name>track</name>
|
||||
<trkseg>
|
||||
<trkpt lat="50.00" lon="4.00"/>
|
||||
<trkpt lat="50.01" lon="4.01"><ele>12.5</ele></trkpt>
|
||||
<trkpt lat="50.02" lon="4.02"/>
|
||||
</trkseg>
|
||||
<trkseg>
|
||||
<trkpt lat="51.00" lon="5.00"/>
|
||||
</trkseg>
|
||||
</trk>
|
||||
</gpx>
|
||||
@@ -1,62 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<gpx xmlns="http://www.topografix.com/GPX/1/1"
|
||||
xmlns:gpxtpx="http://www.garmin.com/xmlschemas/TrackPointExtension/v1" version="1.1" creator="https://gpx.studio">
|
||||
<metadata>
|
||||
<name>with_highway</name>
|
||||
</metadata>
|
||||
<trk>
|
||||
<name>with_highway</name>
|
||||
<trkseg>
|
||||
<trkpt lat="50.790867" lon="4.404968">
|
||||
<ele>109.0</ele>
|
||||
<extensions>
|
||||
<gpxtpx:TrackPointExtension>
|
||||
<gpxtpx:Extensions>
|
||||
<surface>asphalt</surface>
|
||||
<highway>residential</highway>
|
||||
</gpxtpx:Extensions>
|
||||
</gpxtpx:TrackPointExtension>
|
||||
</extensions>
|
||||
</trkpt>
|
||||
<trkpt lat="50.791000" lon="4.405100">
|
||||
<ele>110.0</ele>
|
||||
<extensions>
|
||||
<gpxtpx:TrackPointExtension>
|
||||
<gpxtpx:Extensions>
|
||||
<surface>asphalt</surface>
|
||||
<highway>residential</highway>
|
||||
</gpxtpx:Extensions>
|
||||
</gpxtpx:TrackPointExtension>
|
||||
</extensions>
|
||||
</trkpt>
|
||||
<trkpt lat="50.791200" lon="4.405300">
|
||||
<ele>111.0</ele>
|
||||
</trkpt>
|
||||
<trkpt lat="50.791400" lon="4.405500">
|
||||
<ele>112.0</ele>
|
||||
<extensions>
|
||||
<gpxtpx:TrackPointExtension>
|
||||
<gpxtpx:Extensions>
|
||||
<surface>gravel</surface>
|
||||
<highway>track</highway>
|
||||
<sac_scale>mountain_hiking</sac_scale>
|
||||
<mtb_scale>1</mtb_scale>
|
||||
</gpxtpx:Extensions>
|
||||
</gpxtpx:TrackPointExtension>
|
||||
</extensions>
|
||||
</trkpt>
|
||||
<trkpt lat="50.791600" lon="4.405700">
|
||||
<ele>113.0</ele>
|
||||
<extensions>
|
||||
<gpxtpx:TrackPointExtension>
|
||||
<gpxtpx:Extensions>
|
||||
<surface>gravel</surface>
|
||||
<sac_scale>hiking</sac_scale>
|
||||
<mtb_scale>1</mtb_scale>
|
||||
</gpxtpx:Extensions>
|
||||
</gpxtpx:TrackPointExtension>
|
||||
</extensions>
|
||||
</trkpt>
|
||||
</trkseg>
|
||||
</trk>
|
||||
</gpx>
|
||||
@@ -1,38 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<gpx xmlns="http://www.topografix.com/GPX/1/1" version="1.1" creator="test">
|
||||
<metadata>
|
||||
<name>with links</name>
|
||||
<author>
|
||||
<name>someone</name>
|
||||
<email id="someone" domain="example.com"/>
|
||||
<link href="https://example.com/author"><text>author</text></link>
|
||||
</author>
|
||||
<link href="https://example.com/file-1"><text>first</text></link>
|
||||
<link href="https://example.com/file-2"/>
|
||||
</metadata>
|
||||
<wpt lat="50" lon="4">
|
||||
<name>summit</name>
|
||||
<link href="https://example.com/wpt-1"><text>one</text></link>
|
||||
<link href="https://example.com/wpt-2"/>
|
||||
<link href="https://example.com/wpt-3"><text>three</text></link>
|
||||
</wpt>
|
||||
<trk>
|
||||
<name>track</name>
|
||||
<link href="https://example.com/trk-1"/>
|
||||
<link href="https://example.com/trk-2"><text>two</text></link>
|
||||
<trkseg>
|
||||
<trkpt lat="50" lon="4"/>
|
||||
<trkpt lat="50.1" lon="4.1"/>
|
||||
</trkseg>
|
||||
</trk>
|
||||
<rte>
|
||||
<name>route</name>
|
||||
<link href="https://example.com/rte-1"/>
|
||||
<link href="https://example.com/rte-2"/>
|
||||
<rtept lat="51" lon="5"/>
|
||||
<rtept lat="51.1" lon="5.1"/>
|
||||
</rte>
|
||||
<wpt lat="51" lon="5">
|
||||
<name>email variants</name>
|
||||
</wpt>
|
||||
</gpx>
|
||||
@@ -1,23 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<gpx xmlns="http://www.topografix.com/GPX/1/1" xmlns:gpxx="http://www.garmin.com/xmlschemas/GpxExtensions/v3" version="1.1" creator="test">
|
||||
<rte>
|
||||
<name>with extensions</name>
|
||||
<rtept lat="1" lon="1">
|
||||
<ele>10</ele>
|
||||
<extensions>
|
||||
<gpxx:RoutePointExtension>
|
||||
<gpxx:rpt lat="1.1" lon="1.1"/>
|
||||
<gpxx:rpt lat="1.2" lon="1.2"></gpxx:rpt>
|
||||
</gpxx:RoutePointExtension>
|
||||
</extensions>
|
||||
</rtept>
|
||||
<rtept lat="2" lon="2">
|
||||
<ele>20</ele>
|
||||
<time>2024-01-01T00:00:00Z</time>
|
||||
</rtept>
|
||||
<rtept lat="3" lon="3"/>
|
||||
</rte>
|
||||
<rte>
|
||||
<name>empty</name>
|
||||
</rte>
|
||||
</gpx>
|
||||
@@ -1,30 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<gpx xmlns="http://www.topografix.com/GPX/1/1" xmlns:gpxx="http://www.garmin.com/xmlschemas/GpxExtensions/v3" version="1.1" creator="test">
|
||||
<rte>
|
||||
<name>Lausanne</name>
|
||||
<cmt>comment</cmt>
|
||||
<desc>description</desc>
|
||||
<type>Cycling</type>
|
||||
<rtept lat="46.544628096744418" lon="6.658079791814089">
|
||||
<ele>500</ele>
|
||||
<extensions>
|
||||
<gpxx:RoutePointExtension>
|
||||
<gpxx:rpt lat="46.544483928009868" lon="6.658018603920937"/>
|
||||
<gpxx:rpt lat="46.544415950775146" lon="6.658358573913574"/>
|
||||
<gpxx:rpt lat="46.544415950775146" lon="6.658358573913574"/>
|
||||
</gpxx:RoutePointExtension>
|
||||
</extensions>
|
||||
</rtept>
|
||||
<rtept lat="46.544100000000000" lon="6.659000000000000">
|
||||
<ele>510</ele>
|
||||
<extensions>
|
||||
<gpxx:RoutePointExtension>
|
||||
<gpxx:rpt lat="46.543900000000000" lon="6.659500000000000"/>
|
||||
</gpxx:RoutePointExtension>
|
||||
</extensions>
|
||||
</rtept>
|
||||
<rtept lat="46.543000000000000" lon="6.660000000000000">
|
||||
<ele>505</ele>
|
||||
</rtept>
|
||||
</rte>
|
||||
</gpx>
|
||||
@@ -0,0 +1,9 @@
|
||||
[package]
|
||||
name = "gpx-engine"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
chrono = "0.4.45"
|
||||
quick-xml = "0.42.0"
|
||||
uuid = { version = "1.26.1", features = ["v4"] }
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,4 @@
|
||||
mod simplify;
|
||||
mod smooth;
|
||||
|
||||
pub use simplify::*;
|
||||
@@ -0,0 +1,133 @@
|
||||
use crate::{
|
||||
core::gpx::{TrackSegment, TrackSegmentIndex},
|
||||
core::utils::crossarc,
|
||||
};
|
||||
|
||||
pub fn ramer_douglas_peucker<F>(
|
||||
trkseg: &TrackSegment,
|
||||
mapping: &F,
|
||||
epsilon: f64,
|
||||
) -> Vec<TrackSegmentIndex>
|
||||
where
|
||||
F: Fn(TrackSegmentIndex) -> (f64, f64),
|
||||
{
|
||||
match trkseg.len() {
|
||||
0 => vec![],
|
||||
1 => vec![trkseg.first_index().unwrap()],
|
||||
2 => vec![trkseg.first_index().unwrap(), trkseg.last_index().unwrap()],
|
||||
_ => {
|
||||
let first = trkseg.first_index().unwrap();
|
||||
let last = trkseg.last_index().unwrap();
|
||||
|
||||
let mut indices = vec![first];
|
||||
ramer_douglas_peucker_helper(trkseg, first, last, mapping, epsilon, &mut indices);
|
||||
indices.push(last);
|
||||
indices
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn ramer_douglas_peucker_helper<F>(
|
||||
trkseg: &TrackSegment,
|
||||
start: TrackSegmentIndex,
|
||||
end: TrackSegmentIndex,
|
||||
mapping: &F,
|
||||
epsilon: f64,
|
||||
indices: &mut Vec<TrackSegmentIndex>,
|
||||
) where
|
||||
F: Fn(TrackSegmentIndex) -> (f64, f64),
|
||||
{
|
||||
let mut max_idx = None;
|
||||
let mut max_dist = 0.0;
|
||||
|
||||
let start_pt = mapping(start);
|
||||
let end_pt = mapping(end);
|
||||
|
||||
let mut cur = trkseg.next_index(Some(start));
|
||||
while let Some(idx) = cur {
|
||||
if idx == end {
|
||||
break;
|
||||
}
|
||||
|
||||
let pt = mapping(idx);
|
||||
let dist = crossarc(start_pt.0, start_pt.1, end_pt.0, end_pt.1, pt.0, pt.1);
|
||||
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, mapping, epsilon, indices);
|
||||
indices.push(idx);
|
||||
ramer_douglas_peucker_helper(trkseg, idx, end, mapping, epsilon, indices);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{Trackpoint, TrackpointChunk};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn segment(eles: &[f64]) -> TrackSegment {
|
||||
let mut trkseg = TrackSegment::default();
|
||||
// several small chunks, to also exercise the chunk boundaries
|
||||
for part in eles.chunks(3) {
|
||||
let mut chunk = TrackpointChunk::default();
|
||||
for ele in part {
|
||||
chunk.trkpt.push(Trackpoint {
|
||||
ele: *ele,
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
trkseg.push(chunk);
|
||||
}
|
||||
trkseg
|
||||
}
|
||||
|
||||
fn simplify(eles: &[f64], epsilon: f64) -> Vec<usize> {
|
||||
let trkseg = segment(eles);
|
||||
ramer_douglas_peucker(&trkseg, &|idx| (idx.flat as f64, trkseg[idx].ele), epsilon)
|
||||
.iter()
|
||||
.map(|idx| idx.flat)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_empty_and_single_point() {
|
||||
assert!(simplify(&[], 1.0).is_empty());
|
||||
assert_eq!(simplify(&[5.0], 1.0), vec![0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_collinear_points_are_removed() {
|
||||
let eles: Vec<f64> = (0..20).map(|i| i as f64 * 2.0).collect();
|
||||
assert_eq!(simplify(&eles, 0.1), vec![0, 19]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_peak_is_kept_when_above_epsilon() {
|
||||
let eles = [0.0, 0.0, 0.0, 10.0, 0.0, 0.0, 0.0];
|
||||
assert_eq!(simplify(&eles, 5.0), vec![0, 3, 6]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_peak_is_dropped_when_below_epsilon() {
|
||||
let eles = [0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0];
|
||||
assert_eq!(simplify(&eles, 1.0), vec![0, 6]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_indices_are_sorted_and_keep_extremities() {
|
||||
let eles = [0.0, 5.0, -3.0, 8.0, 1.0, 9.0, -4.0, 2.0, 7.0, 0.0];
|
||||
let kept = simplify(&eles, 0.5);
|
||||
assert_eq!(kept.first(), Some(&0));
|
||||
assert_eq!(kept.last(), Some(&9));
|
||||
assert!(kept.windows(2).all(|w| w[0] < w[1]));
|
||||
// a larger epsilon never keeps more points
|
||||
assert!(simplify(&eles, 5.0).len() <= kept.len());
|
||||
}
|
||||
}
|
||||
File renamed without changes.
@@ -0,0 +1,100 @@
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{Trackpoint, Waypoint};
|
||||
|
||||
const MAX_TRKPT_CHUNK_SIZE: usize = 4096;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct TrackpointChunkId(Uuid);
|
||||
|
||||
impl Default for TrackpointChunkId {
|
||||
fn default() -> Self {
|
||||
Self(Uuid::new_v4())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct TrackpointChunk {
|
||||
pub id: TrackpointChunkId,
|
||||
pub trkpt: Vec<Trackpoint>,
|
||||
}
|
||||
|
||||
impl PartialEq for TrackpointChunk {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.id == other.id
|
||||
}
|
||||
}
|
||||
|
||||
impl TrackpointChunk {
|
||||
pub fn is_full(&self) -> bool {
|
||||
self.trkpt.len() == MAX_TRKPT_CHUNK_SIZE
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct WaypointChunkId(Uuid);
|
||||
|
||||
impl Default for WaypointChunkId {
|
||||
fn default() -> Self {
|
||||
Self(Uuid::new_v4())
|
||||
}
|
||||
}
|
||||
|
||||
const MAX_WPT_CHUNK_SIZE: usize = 128;
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct WaypointChunk {
|
||||
pub id: WaypointChunkId,
|
||||
pub wpt: Vec<Waypoint>,
|
||||
}
|
||||
|
||||
impl PartialEq for WaypointChunk {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.id == other.id
|
||||
}
|
||||
}
|
||||
|
||||
impl WaypointChunk {
|
||||
pub fn is_full(&self) -> bool {
|
||||
self.wpt.len() == MAX_WPT_CHUNK_SIZE
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_trackpoint_chunk_full() {
|
||||
let mut chunk = TrackpointChunk::default();
|
||||
assert!(!chunk.is_full());
|
||||
for _ in 0..MAX_TRKPT_CHUNK_SIZE - 1 {
|
||||
chunk.trkpt.push(Trackpoint::default());
|
||||
}
|
||||
assert!(!chunk.is_full());
|
||||
chunk.trkpt.push(Trackpoint::default());
|
||||
assert!(chunk.is_full());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_waypoint_chunk_full() {
|
||||
let mut chunk = WaypointChunk::default();
|
||||
assert!(!chunk.is_full());
|
||||
for _ in 0..MAX_WPT_CHUNK_SIZE {
|
||||
chunk.wpt.push(Waypoint::default());
|
||||
}
|
||||
assert!(chunk.is_full());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_chunk_equality_is_by_id() {
|
||||
let a = TrackpointChunk::default();
|
||||
let b = TrackpointChunk::default();
|
||||
assert_ne!(a, b);
|
||||
let c = TrackpointChunk {
|
||||
id: TrackpointChunkId(a.id.0),
|
||||
trkpt: vec![Trackpoint::default()],
|
||||
};
|
||||
assert_eq!(a, c);
|
||||
}
|
||||
}
|
||||
@@ -1,20 +1,3 @@
|
||||
/// Defines an identifier made of a UUID, which is a new one by default.
|
||||
macro_rules! uuid_id {
|
||||
($(#[$meta:meta])* $name:ident) => {
|
||||
$(#[$meta])*
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct $name(pub uuid::Uuid);
|
||||
|
||||
impl Default for $name {
|
||||
fn default() -> Self {
|
||||
Self(uuid::Uuid::new_v4())
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
pub(crate) use uuid_id;
|
||||
|
||||
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
||||
pub struct Link {
|
||||
pub href: String,
|
||||
@@ -27,7 +10,7 @@ pub struct LngLat {
|
||||
pub lat: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
#[derive(Debug)]
|
||||
pub struct LngLatBounds {
|
||||
pub sw: LngLat,
|
||||
pub ne: LngLat,
|
||||
@@ -0,0 +1,49 @@
|
||||
use std::rc::Rc;
|
||||
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{Link, Track, WaypointChunk};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct FileId(pub Uuid);
|
||||
|
||||
impl Default for FileId {
|
||||
fn default() -> Self {
|
||||
Self(Uuid::new_v4())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct FileWaypointsRevisionId(pub Uuid);
|
||||
|
||||
impl Default for FileWaypointsRevisionId {
|
||||
fn default() -> Self {
|
||||
Self(Uuid::new_v4())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, PartialEq)]
|
||||
pub struct File {
|
||||
pub id: FileId,
|
||||
pub info: FileInfo,
|
||||
pub trk: Vec<Track>,
|
||||
pub wpt: Vec<Rc<WaypointChunk>>,
|
||||
pub wpt_rev_id: FileWaypointsRevisionId,
|
||||
// TODO routes
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, PartialEq)]
|
||||
pub struct FileInfo {
|
||||
pub name: String,
|
||||
pub desc: Option<String>,
|
||||
pub author: Option<Author>,
|
||||
pub link: Option<Link>,
|
||||
pub time: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, PartialEq)]
|
||||
pub struct Author {
|
||||
pub name: Option<String>,
|
||||
pub email: Option<String>,
|
||||
pub link: Option<Link>,
|
||||
}
|
||||
@@ -1,23 +1,15 @@
|
||||
mod categories;
|
||||
mod chunk;
|
||||
mod chunked;
|
||||
mod common;
|
||||
mod file;
|
||||
mod route;
|
||||
mod segment;
|
||||
mod track;
|
||||
mod trackpoint;
|
||||
mod waypoint;
|
||||
mod waypoints;
|
||||
|
||||
pub use categories::*;
|
||||
pub use chunk::*;
|
||||
pub use chunked::*;
|
||||
pub use common::*;
|
||||
pub use file::*;
|
||||
pub use route::*;
|
||||
pub use segment::*;
|
||||
pub use track::*;
|
||||
pub use trackpoint::*;
|
||||
pub use waypoint::*;
|
||||
pub use waypoints::*;
|
||||
@@ -0,0 +1,454 @@
|
||||
use std::{ops::Index, rc::Rc};
|
||||
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{Trackpoint, TrackpointChunk};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct TrackSegmentId(pub Uuid);
|
||||
|
||||
impl Default for TrackSegmentId {
|
||||
fn default() -> Self {
|
||||
Self(Uuid::new_v4())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct TrackSegmentRevisionId(pub Uuid);
|
||||
|
||||
impl Default for TrackSegmentRevisionId {
|
||||
fn default() -> Self {
|
||||
Self(Uuid::new_v4())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, PartialEq)]
|
||||
pub struct TrackSegment {
|
||||
pub id: TrackSegmentId,
|
||||
pub rev_id: TrackSegmentRevisionId,
|
||||
chunks: Vec<Rc<TrackpointChunk>>,
|
||||
cumul_length: Vec<usize>,
|
||||
}
|
||||
|
||||
impl TrackSegment {
|
||||
pub fn push(&mut self, chunk: TrackpointChunk) {
|
||||
self.push_shared(Rc::new(chunk));
|
||||
}
|
||||
|
||||
fn push_shared(&mut self, chunk: Rc<TrackpointChunk>) {
|
||||
if chunk.trkpt.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.cumul_length
|
||||
.push(self.cumul_length.last().copied().unwrap_or_default() + chunk.trkpt.len());
|
||||
self.chunks.push(chunk);
|
||||
}
|
||||
|
||||
/// Replaces the points in `start..end` by `points`. Panics if the range is out of bounds.
|
||||
///
|
||||
/// Chunks that are not concerned are kept as they are (shared), only the chunks around the
|
||||
/// range are copied and refilled.
|
||||
pub fn splice(&mut self, start: usize, end: usize, points: Vec<Trackpoint>) {
|
||||
assert!(
|
||||
start <= end && end <= self.len(),
|
||||
"splice range out of bounds"
|
||||
);
|
||||
let old = std::mem::take(&mut self.chunks);
|
||||
self.cumul_length.clear();
|
||||
|
||||
let mut pending = TrackpointChunk::default();
|
||||
let mut inserted = false;
|
||||
let mut offset = 0;
|
||||
for chunk in old {
|
||||
let (lo, hi) = (offset, offset + chunk.trkpt.len());
|
||||
offset = hi;
|
||||
// a chunk ending at `start` is extended unless it is full, to avoid tiny chunks
|
||||
if hi < start || (hi == start && chunk.is_full()) {
|
||||
self.push_shared(chunk);
|
||||
continue;
|
||||
}
|
||||
if !inserted {
|
||||
self.fill(&mut pending, chunk.trkpt[..start - lo].iter().cloned());
|
||||
self.fill(&mut pending, points.iter().cloned());
|
||||
inserted = true;
|
||||
}
|
||||
if hi <= end {
|
||||
continue;
|
||||
}
|
||||
if lo >= end {
|
||||
self.flush(&mut pending);
|
||||
self.push_shared(chunk);
|
||||
} else {
|
||||
self.fill(&mut pending, chunk.trkpt[end - lo..].iter().cloned());
|
||||
}
|
||||
}
|
||||
if !inserted {
|
||||
self.fill(&mut pending, points);
|
||||
}
|
||||
self.flush(&mut pending);
|
||||
}
|
||||
|
||||
fn fill(
|
||||
&mut self,
|
||||
pending: &mut TrackpointChunk,
|
||||
points: impl IntoIterator<Item = Trackpoint>,
|
||||
) {
|
||||
for trkpt in points {
|
||||
pending.trkpt.push(trkpt);
|
||||
if pending.is_full() {
|
||||
self.flush(pending);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn flush(&mut self, pending: &mut TrackpointChunk) {
|
||||
self.push(std::mem::take(pending));
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.cumul_length.last().copied().unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.chunks.is_empty()
|
||||
}
|
||||
|
||||
pub fn iter(&self) -> TrackSegmentIterator<'_> {
|
||||
TrackSegmentIterator::new(self)
|
||||
}
|
||||
|
||||
pub fn first_index(&self) -> Option<TrackSegmentIndex> {
|
||||
self.next_index(None)
|
||||
}
|
||||
|
||||
pub fn last_index(&self) -> Option<TrackSegmentIndex> {
|
||||
self.prev_index(None)
|
||||
}
|
||||
|
||||
pub fn next_index(&self, cur: Option<TrackSegmentIndex>) -> Option<TrackSegmentIndex> {
|
||||
let mut next = cur.map_or_default(|idx| TrackSegmentIndex {
|
||||
chunk: idx.chunk,
|
||||
pos: idx.pos + 1,
|
||||
flat: idx.flat + 1,
|
||||
});
|
||||
loop {
|
||||
if next.chunk >= self.chunks.len() {
|
||||
return None;
|
||||
}
|
||||
if next.pos == self.chunks[next.chunk].trkpt.len() {
|
||||
next.chunk += 1;
|
||||
next.pos = 0;
|
||||
} else {
|
||||
return Some(next);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn prev_index(&self, cur: Option<TrackSegmentIndex>) -> Option<TrackSegmentIndex> {
|
||||
let mut prev = cur.unwrap_or(TrackSegmentIndex {
|
||||
chunk: self.chunks.len(),
|
||||
pos: 0,
|
||||
flat: self.cumul_length.last().copied().unwrap_or_default(),
|
||||
});
|
||||
if prev.pos == 0 {
|
||||
while prev.chunk > 0 {
|
||||
prev.chunk -= 1;
|
||||
if !self.chunks[prev.chunk].trkpt.is_empty() {
|
||||
prev.pos = self.chunks[prev.chunk].trkpt.len() - 1;
|
||||
prev.flat -= 1;
|
||||
return Some(prev);
|
||||
}
|
||||
}
|
||||
None
|
||||
} else {
|
||||
prev.pos -= 1;
|
||||
prev.flat -= 1;
|
||||
Some(prev)
|
||||
}
|
||||
}
|
||||
|
||||
fn locate(&self, idx: usize) -> Option<TrackSegmentIndex> {
|
||||
let chunk = self.cumul_length.partition_point(|l| idx >= *l);
|
||||
if chunk >= self.chunks.len() {
|
||||
return None;
|
||||
}
|
||||
let pos = if chunk > 0 {
|
||||
idx - self.cumul_length[chunk - 1]
|
||||
} else {
|
||||
idx
|
||||
};
|
||||
if pos >= self.chunks[chunk].trkpt.len() {
|
||||
None
|
||||
} else {
|
||||
Some(TrackSegmentIndex {
|
||||
chunk,
|
||||
pos,
|
||||
flat: idx,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Index<TrackSegmentIndex> for TrackSegment {
|
||||
type Output = Trackpoint;
|
||||
|
||||
fn index(&self, idx: TrackSegmentIndex) -> &Self::Output {
|
||||
&self.chunks[idx.chunk].trkpt[idx.pos]
|
||||
}
|
||||
}
|
||||
|
||||
impl Index<usize> for TrackSegment {
|
||||
type Output = Trackpoint;
|
||||
|
||||
fn index(&self, idx: usize) -> &Self::Output {
|
||||
&self[self.locate(idx).unwrap()]
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PartialOrd, Ord)]
|
||||
pub struct TrackSegmentIndex {
|
||||
pub chunk: usize,
|
||||
pub pos: usize,
|
||||
pub flat: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct TrackSegmentIterator<'a> {
|
||||
trkseg: &'a TrackSegment,
|
||||
idx: Option<TrackSegmentIndex>,
|
||||
}
|
||||
|
||||
impl<'a> TrackSegmentIterator<'a> {
|
||||
pub fn new(trkseg: &'a TrackSegment) -> Self {
|
||||
Self {
|
||||
trkseg,
|
||||
idx: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Iterator for TrackSegmentIterator<'a> {
|
||||
type Item = &'a Trackpoint;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
self.idx = self.trkseg.next_index(self.idx);
|
||||
self.idx.map(|idx| &self.trkseg[idx])
|
||||
}
|
||||
|
||||
fn nth(&mut self, n: usize) -> Option<Self::Item> {
|
||||
let idx = self.idx.map_or_default(|idx| idx.flat) + n;
|
||||
self.idx = self.trkseg.locate(idx);
|
||||
self.idx.map(|idx| &self.trkseg[idx])
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn create_track_segment(nb_chunks: usize) -> TrackSegment {
|
||||
let mut trkseg = TrackSegment::default();
|
||||
let mut count = 0;
|
||||
for n in 1..=nb_chunks {
|
||||
let mut chunk = TrackpointChunk::default();
|
||||
for _ in 0..n {
|
||||
chunk.trkpt.push(Trackpoint {
|
||||
ele: count as f64,
|
||||
..Default::default()
|
||||
});
|
||||
count += 1;
|
||||
}
|
||||
trkseg.push(chunk);
|
||||
}
|
||||
trkseg
|
||||
}
|
||||
|
||||
fn eles(trkseg: &TrackSegment) -> Vec<f64> {
|
||||
trkseg.iter().map(|p| p.ele).collect()
|
||||
}
|
||||
|
||||
fn points(eles: &[f64]) -> Vec<Trackpoint> {
|
||||
eles.iter()
|
||||
.map(|&ele| Trackpoint {
|
||||
ele,
|
||||
..Default::default()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_splice_replace_insert_delete_append() {
|
||||
// chunks of 1..=5 points: [0] [1 2] [3 4 5] [6 7 8 9] [10..=14]
|
||||
let mut trkseg = create_track_segment(5);
|
||||
trkseg.splice(4, 8, points(&[-1.0, -2.0]));
|
||||
let mut expected: Vec<f64> = (0..4).map(f64::from).collect();
|
||||
expected.extend([-1.0, -2.0]);
|
||||
expected.extend((8..15).map(f64::from));
|
||||
assert_eq!(eles(&trkseg), expected);
|
||||
assert_eq!(trkseg.len(), expected.len());
|
||||
for i in 0..trkseg.len() {
|
||||
assert_eq!(trkseg[i].ele, expected[i]);
|
||||
}
|
||||
|
||||
trkseg.splice(2, 2, points(&[100.0]));
|
||||
expected.insert(2, 100.0);
|
||||
assert_eq!(eles(&trkseg), expected);
|
||||
|
||||
trkseg.splice(0, 3, vec![]);
|
||||
expected.drain(..3);
|
||||
assert_eq!(eles(&trkseg), expected);
|
||||
|
||||
let len = trkseg.len();
|
||||
trkseg.splice(len, len, points(&[7.0, 8.0]));
|
||||
expected.extend([7.0, 8.0]);
|
||||
assert_eq!(eles(&trkseg), expected);
|
||||
|
||||
let len = trkseg.len();
|
||||
trkseg.splice(0, len, vec![]);
|
||||
assert_eq!(trkseg.len(), 0);
|
||||
assert!(trkseg.first_index().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_splice_keeps_untouched_chunks_shared() {
|
||||
let mut trkseg = create_track_segment(5);
|
||||
let before = trkseg.chunks.clone();
|
||||
// inside the third chunk only
|
||||
trkseg.splice(4, 5, points(&[-1.0]));
|
||||
assert!(Rc::ptr_eq(&trkseg.chunks[0], &before[0]));
|
||||
assert!(Rc::ptr_eq(&trkseg.chunks[1], &before[1]));
|
||||
assert!(Rc::ptr_eq(trkseg.chunks.last().unwrap(), &before[4]));
|
||||
assert!(Rc::ptr_eq(
|
||||
&trkseg.chunks[trkseg.chunks.len() - 2],
|
||||
&before[3]
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_splice_append_extends_last_chunk_and_respects_max_size() {
|
||||
let mut trkseg = TrackSegment::default();
|
||||
for i in 0..10_000 {
|
||||
let len = trkseg.len();
|
||||
trkseg.splice(len, len, points(&[i as f64]));
|
||||
}
|
||||
assert_eq!(trkseg.len(), 10_000);
|
||||
assert!(trkseg.chunks.len() <= 3);
|
||||
assert!(trkseg.chunks.iter().all(|c| c.trkpt.len() <= 4096));
|
||||
assert_eq!(trkseg[9_999].ele, 9_999.0);
|
||||
assert_eq!(*trkseg.cumul_length.last().unwrap(), 10_000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_len() {
|
||||
let nb_chunks = 10;
|
||||
let trkseg = create_track_segment(nb_chunks);
|
||||
assert_eq!(trkseg.len(), nb_chunks * (nb_chunks + 1) / 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_locate() {
|
||||
let nb_chunks = 10;
|
||||
let trkseg = create_track_segment(nb_chunks);
|
||||
for i in 0..trkseg.len() {
|
||||
let idx = trkseg.locate(i);
|
||||
assert!(idx.is_some());
|
||||
assert_eq!(trkseg[idx.unwrap()].ele, i as f64);
|
||||
}
|
||||
|
||||
assert!(trkseg.locate(trkseg.len()).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_index() {
|
||||
let nb_chunks = 10;
|
||||
let trkseg = create_track_segment(nb_chunks);
|
||||
for i in 0..trkseg.len() {
|
||||
assert_eq!(trkseg[i].ele, i as f64);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn test_index_out_of_bounds_1() {
|
||||
let nb_chunks = 10;
|
||||
let trkseg = create_track_segment(nb_chunks);
|
||||
let _ = trkseg[trkseg.len()];
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn test_index_out_of_bounds_2() {
|
||||
let nb_chunks = 10;
|
||||
let trkseg = create_track_segment(nb_chunks);
|
||||
let _ = trkseg[TrackSegmentIndex {
|
||||
chunk: trkseg.chunks.len(),
|
||||
pos: 0,
|
||||
flat: 0,
|
||||
}];
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_iter() {
|
||||
let nb_chunks = 10;
|
||||
let trkseg = create_track_segment(nb_chunks);
|
||||
for (i, trkpt) in trkseg.iter().enumerate() {
|
||||
assert!(std::ptr::eq(&trkseg[i], trkpt));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_iter_nth() {
|
||||
let nb_chunks = 10;
|
||||
let trkseg = create_track_segment(nb_chunks);
|
||||
let tenth = trkseg.iter().nth(10);
|
||||
assert!(tenth.is_some());
|
||||
assert!(std::ptr::eq(&trkseg[10], tenth.unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_iter_skip() {
|
||||
let nb_chunks = 10;
|
||||
let trkseg = create_track_segment(nb_chunks);
|
||||
for (i, trkpt) in trkseg.iter().enumerate().skip(5) {
|
||||
assert!(std::ptr::eq(&trkseg[i], trkpt));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_first_last_index() {
|
||||
assert!(TrackSegment::default().first_index().is_none());
|
||||
assert!(TrackSegment::default().last_index().is_none());
|
||||
|
||||
let trkseg = create_track_segment(5); // 15 points in chunks of 1..=5
|
||||
let first = trkseg.first_index().unwrap();
|
||||
let last = trkseg.last_index().unwrap();
|
||||
assert_eq!((first.chunk, first.pos, first.flat), (0, 0, 0));
|
||||
assert_eq!((last.chunk, last.pos, last.flat), (4, 4, 14));
|
||||
assert_eq!(trkseg[last].ele, 14.0);
|
||||
assert_eq!(trkseg.locate(14), Some(last));
|
||||
assert!(trkseg.next_index(Some(last)).is_none());
|
||||
assert!(trkseg.prev_index(Some(first)).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_prev_next_are_inverse() {
|
||||
let trkseg = create_track_segment(6);
|
||||
let mut idx = trkseg.last_index();
|
||||
let mut visited = vec![];
|
||||
while let Some(i) = idx {
|
||||
assert_eq!(trkseg.locate(i.flat), Some(i));
|
||||
visited.push(i.flat);
|
||||
idx = trkseg.prev_index(Some(i));
|
||||
}
|
||||
assert_eq!(visited, (0..trkseg.len()).rev().collect::<Vec<_>>());
|
||||
|
||||
let mut idx = trkseg.first_index();
|
||||
while let Some(i) = idx {
|
||||
let next = trkseg.next_index(Some(i));
|
||||
if let Some(n) = next {
|
||||
assert_eq!(trkseg.prev_index(Some(n)), Some(i));
|
||||
}
|
||||
idx = next;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,17 @@
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{Link, TrackSegment};
|
||||
|
||||
use super::common::uuid_id;
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct TrackId(pub Uuid);
|
||||
|
||||
uuid_id!(TrackId);
|
||||
impl Default for TrackId {
|
||||
fn default() -> Self {
|
||||
Self(Uuid::new_v4())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone)]
|
||||
#[derive(Debug, Default, Clone, PartialEq)]
|
||||
pub struct Track {
|
||||
pub id: TrackId,
|
||||
pub info: TrackInfo,
|
||||
@@ -17,7 +24,7 @@ pub struct TrackInfo {
|
||||
pub cmt: Option<String>,
|
||||
pub desc: Option<String>,
|
||||
pub src: Option<String>,
|
||||
pub links: Vec<Link>,
|
||||
pub link: Option<Link>,
|
||||
pub type_: Option<String>,
|
||||
pub color: Option<String>,
|
||||
pub opacity: Option<f64>,
|
||||
@@ -0,0 +1,13 @@
|
||||
use crate::LngLat;
|
||||
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct Trackpoint {
|
||||
pub coordinates: LngLat,
|
||||
pub ele: f64,
|
||||
pub time: Option<i64>,
|
||||
pub atemp: Option<i16>,
|
||||
pub hr: Option<u16>,
|
||||
pub cad: Option<u16>,
|
||||
pub power: Option<u16>,
|
||||
// TODO OSM data? or store intervals at a higher level?
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{Link, LngLat};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct WaypointId(pub Uuid);
|
||||
|
||||
impl Default for WaypointId {
|
||||
fn default() -> Self {
|
||||
Self(Uuid::new_v4())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct Waypoint {
|
||||
pub id: WaypointId,
|
||||
pub coordinates: LngLat,
|
||||
pub ele: f64,
|
||||
pub time: Option<i64>,
|
||||
pub name: Option<String>,
|
||||
pub cmt: Option<String>,
|
||||
pub desc: Option<String>,
|
||||
pub link: Option<Link>,
|
||||
pub sym: Option<String>,
|
||||
pub type_: Option<String>,
|
||||
}
|
||||
@@ -1,5 +1,3 @@
|
||||
mod parse;
|
||||
mod write;
|
||||
|
||||
pub use parse::*;
|
||||
pub use write::*;
|
||||
@@ -0,0 +1,579 @@
|
||||
use std::rc::Rc;
|
||||
|
||||
use crate::{
|
||||
Author, File, Link, LngLat, Track, TrackSegment, Trackpoint, TrackpointChunk, Waypoint,
|
||||
WaypointChunk,
|
||||
};
|
||||
use chrono::DateTime;
|
||||
use quick_xml::Error;
|
||||
use quick_xml::events::Event;
|
||||
use quick_xml::events::attributes::Attributes;
|
||||
use quick_xml::reader::Reader;
|
||||
|
||||
enum GPXElement {
|
||||
Metadata,
|
||||
Name,
|
||||
Comment,
|
||||
Description,
|
||||
Source,
|
||||
Author(Author),
|
||||
Link(Link),
|
||||
Text,
|
||||
Track(Track),
|
||||
Segment(TrackSegment),
|
||||
Trackpoint(Trackpoint),
|
||||
Waypoint(Waypoint),
|
||||
Elevation,
|
||||
Time,
|
||||
Temperature,
|
||||
Heartrate,
|
||||
Cadence,
|
||||
Power,
|
||||
Symbol,
|
||||
Type,
|
||||
Color,
|
||||
Opacity,
|
||||
Width,
|
||||
}
|
||||
|
||||
fn parse_coordinates(attributes: Attributes<'_>) -> LngLat {
|
||||
let mut coordinates = LngLat::default();
|
||||
for attr in attributes.flatten() {
|
||||
match attr.key.as_ref() {
|
||||
"lat" => coordinates.lat = attr.value.parse().unwrap_or_default(),
|
||||
"lon" => coordinates.lng = attr.value.parse().unwrap_or_default(),
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
coordinates
|
||||
}
|
||||
|
||||
pub fn parse(data: &[u8]) -> Result<File, Error> {
|
||||
let mut reader = Reader::from_reader(data);
|
||||
let mut buf = vec![];
|
||||
let mut gpx = File::default();
|
||||
let mut stack: Vec<GPXElement> = vec![];
|
||||
let mut trkpt_chunk = TrackpointChunk::default();
|
||||
let mut wpt_chunk = WaypointChunk::default();
|
||||
loop {
|
||||
match reader.read_event_into(&mut buf) {
|
||||
Ok(Event::Start(e)) => match e.name().as_ref() {
|
||||
"metadata" => stack.push(GPXElement::Metadata),
|
||||
"name" => stack.push(GPXElement::Name),
|
||||
"cmt" => stack.push(GPXElement::Comment),
|
||||
"desc" => stack.push(GPXElement::Description),
|
||||
"src" => stack.push(GPXElement::Source),
|
||||
"author" => stack.push(GPXElement::Author(Author::default())),
|
||||
"link" => {
|
||||
let mut link = Link::default();
|
||||
for attr in e.attributes().flatten() {
|
||||
if attr.key.as_ref() == "href" {
|
||||
link.href = attr.value.to_string();
|
||||
}
|
||||
}
|
||||
stack.push(GPXElement::Link(link));
|
||||
}
|
||||
"text" => stack.push(GPXElement::Text),
|
||||
"trk" => stack.push(GPXElement::Track(Track::default())),
|
||||
"trkseg" => {
|
||||
stack.push(GPXElement::Segment(TrackSegment::default()));
|
||||
}
|
||||
"trkpt" => {
|
||||
stack.push(GPXElement::Trackpoint(Trackpoint {
|
||||
coordinates: parse_coordinates(e.attributes()),
|
||||
..Default::default()
|
||||
}));
|
||||
}
|
||||
"wpt" => {
|
||||
stack.push(GPXElement::Waypoint(Waypoint {
|
||||
coordinates: parse_coordinates(e.attributes()),
|
||||
..Default::default()
|
||||
}));
|
||||
}
|
||||
"ele" => stack.push(GPXElement::Elevation),
|
||||
"time" => stack.push(GPXElement::Time),
|
||||
e if e.ends_with("atemp") => stack.push(GPXElement::Temperature),
|
||||
e if e.ends_with("hr") => stack.push(GPXElement::Heartrate),
|
||||
e if e.ends_with("cad") => stack.push(GPXElement::Cadence),
|
||||
"power" => stack.push(GPXElement::Power),
|
||||
e if e.ends_with("PowerInWatts") => stack.push(GPXElement::Power),
|
||||
"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("opacity") => stack.push(GPXElement::Opacity),
|
||||
e if e.ends_with("width") => stack.push(GPXElement::Width),
|
||||
_ => (),
|
||||
},
|
||||
Ok(Event::End(e)) => match e.name().as_ref() {
|
||||
"gpx" => {
|
||||
if !wpt_chunk.wpt.is_empty() {
|
||||
gpx.wpt.push(Rc::new(std::mem::take(&mut wpt_chunk)));
|
||||
}
|
||||
}
|
||||
"metadata" => {
|
||||
stack.pop();
|
||||
}
|
||||
"author" => {
|
||||
if let Some(GPXElement::Author(author)) = stack.pop() {
|
||||
gpx.info.author = Some(author);
|
||||
}
|
||||
}
|
||||
"link" => {
|
||||
if let Some(GPXElement::Link(link)) = stack.pop() {
|
||||
match stack.last_mut() {
|
||||
Some(GPXElement::Author(author)) => {
|
||||
author.link = Some(link);
|
||||
}
|
||||
Some(GPXElement::Track(trk)) => {
|
||||
trk.info.link = Some(link);
|
||||
}
|
||||
Some(GPXElement::Waypoint(wpt)) => {
|
||||
wpt.link = Some(link);
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
}
|
||||
"trk" => {
|
||||
if let Some(GPXElement::Track(trk)) = stack.pop() {
|
||||
gpx.trk.push(trk);
|
||||
}
|
||||
}
|
||||
"trkseg" => {
|
||||
if let Some(GPXElement::Segment(mut trkseg)) = stack.pop()
|
||||
&& let Some(GPXElement::Track(trk)) = stack.last_mut()
|
||||
{
|
||||
// `push` ignores the chunk if it is empty
|
||||
trkseg.push(std::mem::take(&mut trkpt_chunk));
|
||||
trk.trkseg.push(trkseg);
|
||||
}
|
||||
}
|
||||
"trkpt" => {
|
||||
if let Some(GPXElement::Trackpoint(trkpt)) = stack.pop()
|
||||
&& let Some(GPXElement::Segment(trkseg)) = stack.last_mut()
|
||||
{
|
||||
trkpt_chunk.trkpt.push(trkpt);
|
||||
if trkpt_chunk.is_full() {
|
||||
trkseg.push(std::mem::take(&mut trkpt_chunk));
|
||||
}
|
||||
}
|
||||
}
|
||||
"wpt" => {
|
||||
if let Some(GPXElement::Waypoint(wpt)) = stack.pop() {
|
||||
wpt_chunk.wpt.push(wpt);
|
||||
if wpt_chunk.is_full() {
|
||||
gpx.wpt.push(Rc::new(std::mem::take(&mut wpt_chunk)));
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => (),
|
||||
},
|
||||
Ok(Event::Text(e)) => match stack.last_mut() {
|
||||
Some(GPXElement::Name) => {
|
||||
stack.pop();
|
||||
match stack.last_mut() {
|
||||
Some(GPXElement::Metadata) => {
|
||||
gpx.info.name = e.to_string();
|
||||
}
|
||||
Some(GPXElement::Author(author)) => {
|
||||
author.name = Some(e.to_string());
|
||||
}
|
||||
Some(GPXElement::Track(trk)) => {
|
||||
trk.info.name = Some(e.to_string());
|
||||
}
|
||||
Some(GPXElement::Waypoint(wpt)) => {
|
||||
wpt.name = Some(e.to_string());
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
Some(GPXElement::Comment) => {
|
||||
stack.pop();
|
||||
match stack.last_mut() {
|
||||
Some(GPXElement::Track(trk)) => {
|
||||
trk.info.cmt = Some(e.to_string());
|
||||
}
|
||||
Some(GPXElement::Waypoint(wpt)) => {
|
||||
wpt.cmt = Some(e.to_string());
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
Some(GPXElement::Description) => {
|
||||
stack.pop();
|
||||
match stack.last_mut() {
|
||||
Some(GPXElement::Metadata) => {
|
||||
gpx.info.desc = Some(e.to_string());
|
||||
}
|
||||
Some(GPXElement::Track(trk)) => {
|
||||
trk.info.desc = Some(e.to_string());
|
||||
}
|
||||
Some(GPXElement::Waypoint(wpt)) => {
|
||||
wpt.desc = Some(e.to_string());
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
Some(GPXElement::Source) => {
|
||||
stack.pop();
|
||||
if let Some(GPXElement::Track(trk)) = stack.last_mut() {
|
||||
trk.info.src = Some(e.to_string());
|
||||
}
|
||||
}
|
||||
Some(GPXElement::Text) => {
|
||||
stack.pop();
|
||||
if let Some(GPXElement::Link(link)) = stack.last_mut() {
|
||||
link.text = Some(e.to_string());
|
||||
}
|
||||
}
|
||||
Some(GPXElement::Elevation) => {
|
||||
stack.pop();
|
||||
match stack.last_mut() {
|
||||
Some(GPXElement::Trackpoint(trkpt)) => {
|
||||
trkpt.ele = e.parse().unwrap_or_default();
|
||||
}
|
||||
Some(GPXElement::Waypoint(wpt)) => {
|
||||
wpt.ele = e.parse().unwrap_or_default();
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
Some(GPXElement::Time) => {
|
||||
stack.pop();
|
||||
if let Some(GPXElement::Trackpoint(trkpt)) = stack.last_mut() {
|
||||
trkpt.time = DateTime::parse_from_rfc3339(e.as_ref())
|
||||
.ok()
|
||||
.map(|time| time.timestamp_millis());
|
||||
}
|
||||
}
|
||||
Some(GPXElement::Temperature) => {
|
||||
stack.pop();
|
||||
if let Some(GPXElement::Trackpoint(trkpt)) = stack.last_mut() {
|
||||
trkpt.atemp = e.parse().ok();
|
||||
}
|
||||
}
|
||||
Some(GPXElement::Heartrate) => {
|
||||
stack.pop();
|
||||
if let Some(GPXElement::Trackpoint(trkpt)) = stack.last_mut() {
|
||||
trkpt.hr = e.parse().ok();
|
||||
}
|
||||
}
|
||||
Some(GPXElement::Cadence) => {
|
||||
stack.pop();
|
||||
if let Some(GPXElement::Trackpoint(trkpt)) = stack.last_mut() {
|
||||
trkpt.cad = e.parse().ok();
|
||||
}
|
||||
}
|
||||
Some(GPXElement::Power) => {
|
||||
stack.pop();
|
||||
if let Some(GPXElement::Trackpoint(trkpt)) = stack.last_mut() {
|
||||
trkpt.power = e.parse().ok();
|
||||
}
|
||||
}
|
||||
Some(GPXElement::Symbol) => {
|
||||
stack.pop();
|
||||
if let Some(GPXElement::Waypoint(wpt)) = stack.last_mut() {
|
||||
wpt.sym = Some(e.to_string());
|
||||
}
|
||||
}
|
||||
Some(GPXElement::Type) => {
|
||||
stack.pop();
|
||||
match stack.last_mut() {
|
||||
Some(GPXElement::Track(trk)) => {
|
||||
trk.info.type_ = Some(e.to_string());
|
||||
}
|
||||
Some(GPXElement::Waypoint(wpt)) => {
|
||||
wpt.type_ = Some(e.to_string());
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
Some(GPXElement::Color) => {
|
||||
stack.pop();
|
||||
if let Some(GPXElement::Track(trk)) = stack.last_mut() {
|
||||
trk.info.color = Some(format!("#{}", &*e));
|
||||
}
|
||||
}
|
||||
Some(GPXElement::Opacity) => {
|
||||
stack.pop();
|
||||
if let Some(GPXElement::Track(trk)) = stack.last_mut() {
|
||||
trk.info.opacity = e.parse().ok();
|
||||
}
|
||||
}
|
||||
Some(GPXElement::Width) => {
|
||||
stack.pop();
|
||||
if let Some(GPXElement::Track(trk)) = stack.last_mut() {
|
||||
trk.info.width = e.parse().ok();
|
||||
}
|
||||
}
|
||||
_ => (),
|
||||
},
|
||||
Ok(Event::Eof) => break,
|
||||
Err(e) => return Err(e),
|
||||
_ => (),
|
||||
}
|
||||
buf.clear();
|
||||
}
|
||||
Ok(gpx)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn parse_data(name: &str) -> File {
|
||||
parse(&std::fs::read(format!("data/{name}.gpx")).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_simple() {
|
||||
let gpx = parse_data("simple");
|
||||
|
||||
assert_eq!(gpx.info.name, "simple");
|
||||
assert!(gpx.info.desc.is_some_and(|d| d == "description"));
|
||||
assert!(gpx.info.author.is_some());
|
||||
let author = gpx.info.author.as_ref().unwrap();
|
||||
assert!(author.name.as_ref().is_some_and(|n| n == "gpx.studio"));
|
||||
assert!(author.link.is_some());
|
||||
let link = author.link.as_ref().unwrap();
|
||||
assert_eq!(link.href, "https://gpx.studio");
|
||||
assert!(link.text.as_ref().is_some_and(|t| t == "link text"));
|
||||
|
||||
assert_eq!(gpx.trk.len(), 1);
|
||||
let trk = &gpx.trk[0];
|
||||
assert!(trk.info.name.as_ref().is_some_and(|n| n == "track name"));
|
||||
assert!(trk.info.cmt.as_ref().is_some_and(|c| c == "track comment"));
|
||||
assert!(
|
||||
trk.info
|
||||
.desc
|
||||
.as_ref()
|
||||
.is_some_and(|d| d == "track description")
|
||||
);
|
||||
assert!(trk.info.src.as_ref().is_some_and(|s| s == "track source"));
|
||||
assert!(trk.info.link.is_some());
|
||||
let link = trk.info.link.as_ref().unwrap();
|
||||
assert_eq!(link.href, "https://gpx.studio");
|
||||
assert!(link.text.as_ref().is_some_and(|t| t == "track link text"));
|
||||
assert!(trk.info.type_.as_ref().is_some_and(|c| c == "Cycling"));
|
||||
|
||||
assert_eq!(trk.trkseg.len(), 1);
|
||||
let trkseg = &trk.trkseg[0];
|
||||
assert_eq!(trkseg.len(), 80);
|
||||
let trkpt = &trkseg[0];
|
||||
assert_eq!(trkpt.coordinates.lat, 50.790867);
|
||||
assert_eq!(trkpt.coordinates.lng, 4.404968);
|
||||
assert_eq!(trkpt.ele, 109.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_tracks() {
|
||||
let gpx = parse_data("with_tracks");
|
||||
|
||||
assert_eq!(gpx.trk.len(), 2);
|
||||
let trk = &gpx.trk[0];
|
||||
assert!(trk.info.name.as_ref().is_some_and(|n| n == "track 1"));
|
||||
assert!(trk.info.type_.as_ref().is_some_and(|c| c == "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 trk = &gpx.trk[1];
|
||||
assert!(trk.info.name.as_ref().is_some_and(|n| n == "track 2"));
|
||||
assert!(trk.info.type_.as_ref().is_some_and(|c| c == "Cycling"));
|
||||
|
||||
assert_eq!(trk.trkseg.len(), 1);
|
||||
let trkseg = &trk.trkseg[0];
|
||||
assert_eq!(trkseg.len(), 28);
|
||||
let trkpt = &trkseg[0];
|
||||
assert_eq!(trkpt.coordinates.lat, 50.782212);
|
||||
assert_eq!(trkpt.coordinates.lng, 4.406377);
|
||||
assert_eq!(trkpt.ele, 115.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_segments() {
|
||||
let gpx = parse_data("with_segments");
|
||||
|
||||
assert_eq!(gpx.trk.len(), 1);
|
||||
let trk = &gpx.trk[0];
|
||||
|
||||
assert_eq!(trk.trkseg.len(), 2);
|
||||
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 trkseg = &trk.trkseg[1];
|
||||
assert_eq!(trkseg.len(), 28);
|
||||
let trkpt = &trkseg[0];
|
||||
assert_eq!(trkpt.coordinates.lat, 50.782212);
|
||||
assert_eq!(trkpt.coordinates.lng, 4.406377);
|
||||
assert_eq!(trkpt.ele, 115.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_tracks_and_segments() {
|
||||
let gpx = parse_data("with_tracks_and_segments");
|
||||
|
||||
assert_eq!(gpx.trk.len(), 2);
|
||||
let trk = &gpx.trk[0];
|
||||
|
||||
assert_eq!(trk.trkseg.len(), 2);
|
||||
let trkseg = &trk.trkseg[0];
|
||||
assert_eq!(trkseg.len(), 16);
|
||||
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 trkseg = &trk.trkseg[1];
|
||||
assert_eq!(trkseg.len(), 34);
|
||||
let trkpt = &trkseg[0];
|
||||
assert_eq!(trkpt.coordinates.lat, 50.78727108169855);
|
||||
assert_eq!(trkpt.coordinates.lng, 4.406133681127736);
|
||||
assert_eq!(trkpt.ele, 115.0);
|
||||
|
||||
let trk = &gpx.trk[1];
|
||||
|
||||
assert_eq!(trk.trkseg.len(), 2);
|
||||
let trkseg = &trk.trkseg[0];
|
||||
assert_eq!(trkseg.len(), 19);
|
||||
let trkpt = &trkseg[0];
|
||||
assert_eq!(trkpt.coordinates.lat, 50.782212);
|
||||
assert_eq!(trkpt.coordinates.lng, 4.406377);
|
||||
assert_eq!(trkpt.ele, 115.5);
|
||||
|
||||
let trkseg = &trk.trkseg[1];
|
||||
assert_eq!(trkseg.len(), 10);
|
||||
let trkpt = &trkseg[0];
|
||||
assert_eq!(trkpt.coordinates.lat, 50.77906316558724);
|
||||
assert_eq!(trkpt.coordinates.lng, 4.412547477922485);
|
||||
assert_eq!(trkpt.ele, 133.3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_waypoint() {
|
||||
let gpx = parse_data("with_waypoint");
|
||||
|
||||
assert_eq!(gpx.wpt.len(), 1);
|
||||
let chunk = &gpx.wpt[0];
|
||||
assert_eq!(chunk.wpt.len(), 1);
|
||||
let wpt = &chunk.wpt[0];
|
||||
assert_eq!(wpt.coordinates.lat, 50.7836710064975);
|
||||
assert_eq!(wpt.coordinates.lng, 4.410764082658738);
|
||||
assert!(wpt.name.as_ref().is_some_and(|n| n == "waypoint name"));
|
||||
assert!(wpt.cmt.as_ref().is_some_and(|c| c == "waypoint comment"));
|
||||
assert!(
|
||||
wpt.desc
|
||||
.as_ref()
|
||||
.is_some_and(|d| d == "waypoint description")
|
||||
);
|
||||
assert!(wpt.link.is_some());
|
||||
let link = wpt.link.as_ref().unwrap();
|
||||
assert_eq!(link.href, "https://gpx.studio");
|
||||
assert!(
|
||||
link.text
|
||||
.as_ref()
|
||||
.is_some_and(|t| t == "waypoint link text")
|
||||
);
|
||||
assert!(wpt.sym.as_ref().is_some_and(|s| s == "Bike Trail"));
|
||||
assert!(wpt.type_.as_ref().is_some_and(|t| t == "Bike Trail"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_trackpoint_time() {
|
||||
let gpx = parse_data("with_time");
|
||||
|
||||
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.time.is_some_and(|t| t == 1704063600000));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_trackpoint_hr() {
|
||||
let gpx = parse_data("with_hr");
|
||||
|
||||
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.hr.is_some_and(|h| h == 150));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_trackpoint_cad() {
|
||||
let gpx = parse_data("with_cad");
|
||||
|
||||
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.cad.is_some_and(|c| c == 80));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_trackpoint_power_1() {
|
||||
let gpx = parse_data("with_power_1");
|
||||
|
||||
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_power_2() {
|
||||
let gpx = parse_data("with_power_2");
|
||||
|
||||
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");
|
||||
|
||||
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.atemp.is_some_and(|t| t == 21));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_track_style() {
|
||||
let gpx = parse_data("with_style");
|
||||
|
||||
assert_eq!(gpx.trk.len(), 1);
|
||||
let trk = &gpx.trk[0];
|
||||
assert_eq!(trk.trkseg.len(), 1);
|
||||
assert!(trk.info.color.as_ref().is_some_and(|c| c == "#2d3ee9"));
|
||||
assert!(trk.info.opacity.is_some_and(|o| o == 0.5));
|
||||
assert!(trk.info.width.is_some_and(|w| w == 6.0));
|
||||
}
|
||||
}
|
||||
File renamed without changes.
@@ -0,0 +1,5 @@
|
||||
mod statistics;
|
||||
mod utils;
|
||||
|
||||
pub use statistics::*;
|
||||
pub use utils::*;
|
||||
+38
-137
@@ -3,20 +3,6 @@ use crate::{
|
||||
max_options, min_options, ramer_douglas_peucker, slope, speed, sum_options, time_diff,
|
||||
};
|
||||
|
||||
/// Time between two trackpoints, to size the windows of a smoothing. It is unknown when one of
|
||||
/// them has no time, which is longer than any known time span: the window does not go there.
|
||||
#[derive(Clone, Copy, PartialEq, PartialOrd)]
|
||||
enum TimeSpan {
|
||||
Known(i64),
|
||||
Unknown,
|
||||
}
|
||||
|
||||
impl TimeSpan {
|
||||
fn between(end: Option<i64>, start: Option<i64>) -> Self {
|
||||
time_diff(end, start).map_or(Self::Unknown, Self::Known)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Debug)]
|
||||
pub struct Statistics {
|
||||
pub global: GlobalStatistics,
|
||||
@@ -24,6 +10,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() {
|
||||
@@ -57,18 +51,18 @@ impl Statistics {
|
||||
|
||||
self.global.total_distance += dist;
|
||||
|
||||
let moving = time
|
||||
.zip(time.and_then(|time| speed(dist, time)))
|
||||
.filter(|(_, speed)| (0.5..=1500.0).contains(speed));
|
||||
if let Some((time, _)) = moving {
|
||||
self.global.moving_distance = self
|
||||
.global
|
||||
.moving_distance
|
||||
.map_or(Some(dist), |d| Some(d + dist));
|
||||
self.global.moving_time = self
|
||||
.global
|
||||
.moving_time
|
||||
.map_or(Some(time), |t| Some(t + time));
|
||||
if let Some(time) = time {
|
||||
let speed = speed(dist, time);
|
||||
if (0.5..=1500.0).contains(&speed) {
|
||||
self.global.moving_distance = self
|
||||
.global
|
||||
.moving_distance
|
||||
.map_or(Some(dist), |d| Some(d + dist));
|
||||
self.global.moving_time = self
|
||||
.global
|
||||
.moving_time
|
||||
.map_or(Some(time), |t| Some(t + time));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,35 +80,22 @@ impl Statistics {
|
||||
self.global.bounds.extend(coordinates);
|
||||
}
|
||||
|
||||
/// Speed over a window of 10 seconds on each side of the trackpoints that have a time (the
|
||||
/// others have no speed). The windows do not extend to the trackpoints without time: if the
|
||||
/// previous or next trackpoint has none, the window ends at the trackpoint itself on that side.
|
||||
fn compute_smoothed_speed(&mut self, trkseg: &TrackSegment) {
|
||||
for_each_window!(
|
||||
trkseg,
|
||||
trkseg.first_index(),
|
||||
trkseg.last_index(),
|
||||
TimeSpan::Known(10_000),
|
||||
|i, j| TimeSpan::between(trkseg[j].time, trkseg[i].time),
|
||||
Some(10000),
|
||||
|i, j| time_diff(trkseg[i].time, trkseg[j].time),
|
||||
|i, left, right| {
|
||||
if trkseg[i].time.is_some() {
|
||||
let timed = |index: TrackSegmentIndex| {
|
||||
if trkseg[index].time.is_some() {
|
||||
index
|
||||
} else {
|
||||
i
|
||||
}
|
||||
};
|
||||
let (left, right) = (timed(left), timed(right));
|
||||
self.local[i.flat].speed = time_diff(trkseg[right].time, trkseg[left].time)
|
||||
.and_then(|time| {
|
||||
speed(
|
||||
self.local[right.flat].total_distance
|
||||
- self.local[left.flat].total_distance,
|
||||
time,
|
||||
)
|
||||
});
|
||||
}
|
||||
self.local[i.flat].speed =
|
||||
time_diff(trkseg[right].time, trkseg[left].time).map(|t| {
|
||||
speed(
|
||||
self.local[right.flat].total_distance
|
||||
- self.local[left.flat].total_distance,
|
||||
t,
|
||||
)
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -230,8 +211,8 @@ impl Statistics {
|
||||
pub struct GlobalStatistics {
|
||||
pub total_distance: f64,
|
||||
pub moving_distance: Option<f64>,
|
||||
pub total_time: Option<i64>,
|
||||
pub moving_time: Option<i64>,
|
||||
pub total_time: Option<i32>,
|
||||
pub moving_time: Option<i32>,
|
||||
pub elevation_gain: f64,
|
||||
pub elevation_loss: f64,
|
||||
pub start_time: Option<i64>,
|
||||
@@ -240,17 +221,14 @@ pub struct GlobalStatistics {
|
||||
}
|
||||
|
||||
impl GlobalStatistics {
|
||||
/// Average speed over the total time, unknown if that is not a positive duration (for
|
||||
/// example a range with a single timestamp, or timestamps going backwards).
|
||||
pub fn total_speed(&self) -> Option<f64> {
|
||||
self.total_time.and_then(|t| speed(self.total_distance, t))
|
||||
self.total_time.map(|t| speed(self.total_distance, t))
|
||||
}
|
||||
|
||||
/// Average speed over the moving time, unknown if there is no moving time.
|
||||
pub fn moving_speed(&self) -> Option<f64> {
|
||||
self.moving_distance
|
||||
.zip(self.moving_time)
|
||||
.and_then(|(d, t)| speed(d, t))
|
||||
.map(|(d, t)| speed(d, t))
|
||||
}
|
||||
|
||||
pub fn merge(&mut self, other: &GlobalStatistics) {
|
||||
@@ -270,8 +248,8 @@ impl GlobalStatistics {
|
||||
pub struct TrackpointStatistics {
|
||||
pub total_distance: f64,
|
||||
pub moving_distance: Option<f64>,
|
||||
pub total_time: Option<i64>,
|
||||
pub moving_time: Option<i64>,
|
||||
pub total_time: Option<i32>,
|
||||
pub moving_time: Option<i32>,
|
||||
pub speed: Option<f64>,
|
||||
pub elevation_gain: f64,
|
||||
pub elevation_loss: f64,
|
||||
@@ -315,7 +293,7 @@ mod tests {
|
||||
let mut f = File::open("data/with_time.gpx").unwrap();
|
||||
let mut data = String::new();
|
||||
let _ = f.read_to_string(&mut data);
|
||||
let gpx = parse(data.as_bytes(), &mut Default::default()).unwrap();
|
||||
let gpx = parse(data.as_bytes()).unwrap();
|
||||
|
||||
let trkseg = &gpx.trk[0].trkseg[0];
|
||||
let stats = Statistics::compute(trkseg);
|
||||
@@ -328,88 +306,11 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The speeds of the segment of `data/with_time.gpx` (80 trackpoints at 20 km/h) once the
|
||||
/// trackpoints at `holes` have lost their time.
|
||||
fn speeds_with_holes(holes: &[usize]) -> Vec<Option<f64>> {
|
||||
let gpx = load("data/with_time.gpx");
|
||||
let mut segment = gpx.trk[0].trkseg[0].clone();
|
||||
let points: Vec<_> = segment
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, trkpt)| {
|
||||
let mut trkpt = trkpt.clone();
|
||||
if holes.contains(&i) {
|
||||
trkpt.time = None;
|
||||
}
|
||||
trkpt
|
||||
})
|
||||
.collect();
|
||||
segment.splice(0, points.len(), points);
|
||||
Statistics::compute(&segment)
|
||||
.local
|
||||
.iter()
|
||||
.map(|local| local.speed)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Without time, there is no speed. With one, the speed is the one of the trackpoints around.
|
||||
fn assert_speeds_with_holes(holes: &[usize]) {
|
||||
let speeds = speeds_with_holes(holes);
|
||||
assert_eq!(speeds.len(), 80);
|
||||
for (i, speed) in speeds.iter().enumerate() {
|
||||
if holes.contains(&i) {
|
||||
assert_eq!(*speed, None, "trackpoint {i}");
|
||||
} else {
|
||||
let speed = speed.unwrap_or_else(|| panic!("no speed for trackpoint {i}"));
|
||||
assert!((speed - 20.0).abs() < 0.1, "trackpoint {i}: {speed}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_speed_without_holes() {
|
||||
assert_speeds_with_holes(&[]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_speed_with_holes_at_the_beginning() {
|
||||
assert_speeds_with_holes(&[0, 1, 2, 3, 4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_speed_with_holes_at_the_end() {
|
||||
assert_speeds_with_holes(&[75, 76, 77, 78, 79]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_speed_with_holes_at_both_ends() {
|
||||
assert_speeds_with_holes(&[0, 1, 2, 77, 78, 79]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_speed_with_holes_in_the_middle() {
|
||||
assert_speeds_with_holes(&[40]);
|
||||
assert_speeds_with_holes(&[30, 31, 32, 33, 34]);
|
||||
assert_speeds_with_holes(&(20..60).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_speed_with_scattered_holes() {
|
||||
let holes: Vec<_> = (0..80).step_by(7).collect();
|
||||
assert_speeds_with_holes(&holes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_speed_without_any_time() {
|
||||
let holes: Vec<_> = (0..80).collect();
|
||||
assert!(speeds_with_holes(&holes).iter().all(Option::is_none));
|
||||
}
|
||||
|
||||
fn load(path: &str) -> crate::File {
|
||||
let mut f = File::open(path).unwrap();
|
||||
let mut data = String::new();
|
||||
let _ = f.read_to_string(&mut data);
|
||||
parse(data.as_bytes(), &mut Default::default()).unwrap()
|
||||
parse(data.as_bytes()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
File renamed without changes.
@@ -18,14 +18,13 @@ pub fn distance(p1: LngLat, p2: LngLat) -> f64 {
|
||||
EARTH_RADIUS * c
|
||||
}
|
||||
|
||||
pub fn time_diff(a: Option<i64>, b: Option<i64>) -> Option<i64> {
|
||||
Some(a? - b?)
|
||||
pub fn time_diff(a: Option<i64>, b: Option<i64>) -> Option<i32> {
|
||||
Some((a? - b?) as i32)
|
||||
}
|
||||
|
||||
/// Computes the speed in km/h for a given distance in kilometers and a time in milliseconds.
|
||||
/// Unknown if the time is not a positive duration.
|
||||
pub fn speed(distance: f64, time: i64) -> Option<f64> {
|
||||
(time > 0).then(|| distance / (time as f64 / 3_600_000.0))
|
||||
/// Computes the speed for a given distance in kilometers and a time in milliseconds
|
||||
pub fn speed(distance: f64, time: i32) -> f64 {
|
||||
distance / (time as f64 / 3_600_000.0)
|
||||
}
|
||||
|
||||
pub fn slope(ele: f64, distance: f64) -> f64 {
|
||||
@@ -116,19 +115,6 @@ mod tests {
|
||||
LngLat { lng, lat }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_time_diff_and_speed_with_long_durations() {
|
||||
// 40 days in milliseconds, more than an i32 can hold
|
||||
let forty_days = 40 * 24 * 3_600_000_i64;
|
||||
assert!(forty_days > i64::from(i32::MAX));
|
||||
assert_eq!(time_diff(Some(forty_days), Some(0)), Some(forty_days));
|
||||
assert_eq!(time_diff(Some(0), Some(forty_days)), Some(-forty_days));
|
||||
assert_eq!(time_diff(None, Some(1)), None);
|
||||
assert_eq!(time_diff(Some(1), None), None);
|
||||
// 1 km in one hour
|
||||
assert!((speed(1.0, 3_600_000).unwrap() - 1.0).abs() < 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_distance() {
|
||||
assert_eq!(distance(p(4.0, 50.0), p(4.0, 50.0)), 0.0);
|
||||
@@ -155,13 +141,9 @@ mod tests {
|
||||
#[test]
|
||||
fn test_speed() {
|
||||
// 1 km in 1 h
|
||||
assert!((speed(1.0, 3_600_000).unwrap() - 1.0).abs() < 1e-12);
|
||||
assert!((speed(1.0, 3_600_000) - 1.0).abs() < 1e-12);
|
||||
// 10 km in 30 min
|
||||
assert!((speed(10.0, 1_800_000).unwrap() - 20.0).abs() < 1e-12);
|
||||
// no duration, no speed
|
||||
assert_eq!(speed(1.0, 0), None);
|
||||
assert_eq!(speed(0.0, 0), None);
|
||||
assert_eq!(speed(1.0, -1000), None);
|
||||
assert!((speed(10.0, 1_800_000) - 20.0).abs() < 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -0,0 +1,24 @@
|
||||
use crate::{Command, FileId};
|
||||
|
||||
/// Everything the frontend can ask the engine to do.
|
||||
///
|
||||
/// Only [`Action::Edit`] changes the files (and records an undo step); the others act on the
|
||||
/// history, on the selection or on the file order.
|
||||
#[derive(Debug)]
|
||||
pub enum Action<'a> {
|
||||
Edit(Command<'a>),
|
||||
Undo,
|
||||
Redo,
|
||||
Select {
|
||||
file_ids: Vec<FileId>,
|
||||
},
|
||||
AddSelect {
|
||||
file_ids: Vec<FileId>,
|
||||
},
|
||||
SelectAll,
|
||||
/// Moves the files to `index` among the other files, in the given order. Not undoable.
|
||||
Reorder {
|
||||
file_ids: Vec<FileId>,
|
||||
index: usize,
|
||||
},
|
||||
}
|
||||
@@ -12,6 +12,8 @@ pub trait Apply {
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum CommandError {
|
||||
/// The command is not implemented yet.
|
||||
NotImplemented(&'static str),
|
||||
/// The command would not change anything.
|
||||
NothingToDo,
|
||||
/// The input data could not be parsed.
|
||||
@@ -21,6 +23,7 @@ pub enum CommandError {
|
||||
impl fmt::Display for CommandError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::NotImplemented(name) => write!(f, "{name} is not implemented yet"),
|
||||
Self::NothingToDo => write!(f, "nothing to do"),
|
||||
Self::InvalidData(err) => write!(f, "invalid data: {err}"),
|
||||
}
|
||||
@@ -1,20 +1,9 @@
|
||||
mod apply;
|
||||
mod edit;
|
||||
mod file;
|
||||
#[cfg(test)]
|
||||
pub(crate) mod fixture;
|
||||
mod pattern;
|
||||
#[cfg(test)]
|
||||
mod routes_tests;
|
||||
mod tools;
|
||||
|
||||
pub use apply::*;
|
||||
pub use edit::*;
|
||||
pub use file::*;
|
||||
pub use pattern::*;
|
||||
pub use tools::*;
|
||||
|
||||
use crate::State;
|
||||
use crate::{Apply, CommandError, State};
|
||||
use crate::{
|
||||
Clean, Crop, Delete, DeleteAll, Duplicate, Elevation, Extract, Load, Merge, Metadata,
|
||||
MoveWaypoint, New, NewTrack, NewTrackSegment, NewWaypoint, Reverse, SpliceTrackpoints, Split,
|
||||
Style, Time,
|
||||
};
|
||||
|
||||
/// A user action that edits the files. Each variant wraps the command's own struct, whose
|
||||
/// effect is implemented in its own file (see `Apply`).
|
||||
@@ -25,36 +14,24 @@ use crate::State;
|
||||
pub enum Command<'a> {
|
||||
New(New<'a>),
|
||||
Load(Load<'a>),
|
||||
LoadFiles(LoadFiles<'a>),
|
||||
SyncFiles(SyncFiles<'a>),
|
||||
Duplicate(Duplicate),
|
||||
Delete(Delete),
|
||||
Paste(Paste),
|
||||
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>),
|
||||
SpliceTrackpoints(SpliceTrackpoints<'a>),
|
||||
NewWaypoint(NewWaypoint<'a>),
|
||||
EditWaypoint(EditWaypoint<'a>),
|
||||
MoveWaypoint(MoveWaypoint),
|
||||
Crop(Crop),
|
||||
Reduce(Reduce),
|
||||
Split(Split),
|
||||
Time(Time),
|
||||
Merge(Merge),
|
||||
Extract(Extract),
|
||||
InsertAnchor(InsertAnchor),
|
||||
Elevation(Elevation<'a>),
|
||||
Clean(Clean),
|
||||
ChangeLoopStart(ChangeLoopStart),
|
||||
}
|
||||
|
||||
impl Apply for Command<'_> {
|
||||
@@ -62,36 +39,24 @@ impl Apply for Command<'_> {
|
||||
match self {
|
||||
Command::New(c) => c.apply(state),
|
||||
Command::Load(c) => c.apply(state),
|
||||
Command::LoadFiles(c) => c.apply(state),
|
||||
Command::SyncFiles(c) => c.apply(state),
|
||||
Command::Duplicate(c) => c.apply(state),
|
||||
Command::Delete(c) => c.apply(state),
|
||||
Command::Paste(c) => c.apply(state),
|
||||
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::SpliceTrackpoints(c) => c.apply(state),
|
||||
Command::NewWaypoint(c) => c.apply(state),
|
||||
Command::EditWaypoint(c) => c.apply(state),
|
||||
Command::MoveWaypoint(c) => c.apply(state),
|
||||
Command::Crop(c) => c.apply(state),
|
||||
Command::Reduce(c) => c.apply(state),
|
||||
Command::Split(c) => c.apply(state),
|
||||
Command::Time(c) => c.apply(state),
|
||||
Command::Merge(c) => c.apply(state),
|
||||
Command::Extract(c) => c.apply(state),
|
||||
Command::InsertAnchor(c) => c.apply(state),
|
||||
Command::Elevation(c) => c.apply(state),
|
||||
Command::Clean(c) => c.apply(state),
|
||||
Command::ChangeLoopStart(c) => c.apply(state),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
use crate::{Apply, CommandError, Edit, Editor, File, State, Track, update_selected};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Metadata<'a> {
|
||||
pub name: &'a str,
|
||||
pub desc: &'a str,
|
||||
}
|
||||
|
||||
impl Apply for Metadata<'_> {
|
||||
fn apply(mut self, state: &mut State) -> Result<(), CommandError> {
|
||||
update_selected(state, &mut self);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
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());
|
||||
Edit::Changed
|
||||
}
|
||||
|
||||
fn track(&mut self, track: &mut Track) -> Edit {
|
||||
track.info.name = Some(self.name.to_owned());
|
||||
track.info.desc = Some(self.desc.to_owned());
|
||||
Edit::Changed
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::HashSet;
|
||||
|
||||
use crate::{New, Selection, engine::command::fixture::Fixture};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_metadata_applies_to_selected_file() {
|
||||
let mut fx = Fixture::default();
|
||||
New { name: "first" }.apply(&mut fx.state()).unwrap();
|
||||
New { name: "second" }.apply(&mut fx.state()).unwrap(); // now selected
|
||||
let selected = *fx.selected_files().iter().next().unwrap();
|
||||
|
||||
Metadata {
|
||||
name: "renamed",
|
||||
desc: "description",
|
||||
}
|
||||
.apply(&mut fx.state())
|
||||
.unwrap();
|
||||
|
||||
for (id, file) in fx.files.iter() {
|
||||
if *id == selected {
|
||||
assert_eq!(file.info.name, "renamed");
|
||||
assert_eq!(file.info.desc.as_deref(), Some("description"));
|
||||
} else {
|
||||
assert_eq!(file.info.name, "first");
|
||||
assert_eq!(file.info.desc, None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_metadata_applies_to_selected_track() {
|
||||
let mut fx = Fixture::default();
|
||||
let data = std::fs::read("data/with_tracks.gpx").unwrap();
|
||||
crate::Load { data: &data }.apply(&mut fx.state()).unwrap();
|
||||
let file = fx.files.values().next().unwrap().clone();
|
||||
fx.selection = Selection::Track {
|
||||
file_id: file.id,
|
||||
trk_ids: HashSet::from([file.trk[0].id]),
|
||||
};
|
||||
|
||||
Metadata {
|
||||
name: "renamed",
|
||||
desc: "",
|
||||
}
|
||||
.apply(&mut fx.state())
|
||||
.unwrap();
|
||||
|
||||
let after = &fx.files[&file.id];
|
||||
assert_eq!(after.info.name, file.info.name);
|
||||
assert_eq!(after.trk[0].info.name.as_deref(), Some("renamed"));
|
||||
assert_eq!(after.trk[1].info, file.trk[1].info);
|
||||
}
|
||||
}
|
||||
@@ -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::*;
|
||||
+13
-46
@@ -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)]
|
||||
@@ -58,13 +37,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_new_track() {
|
||||
let mut fx = Fixture::default();
|
||||
New {
|
||||
name: "file",
|
||||
trackpoint: None,
|
||||
route: false,
|
||||
}
|
||||
.apply(&mut fx.state())
|
||||
.unwrap();
|
||||
New { name: "file" }.apply(&mut fx.state()).unwrap();
|
||||
NewTrack.apply(&mut fx.state()).unwrap();
|
||||
NewTrack.apply(&mut fx.state()).unwrap();
|
||||
let file = fx.files.values().next().unwrap();
|
||||
@@ -75,13 +48,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_new_track_inherits_agreeing_style_only() {
|
||||
let mut fx = Fixture::default();
|
||||
New {
|
||||
name: "file",
|
||||
trackpoint: None,
|
||||
route: false,
|
||||
}
|
||||
.apply(&mut fx.state())
|
||||
.unwrap();
|
||||
New { name: "file" }.apply(&mut fx.state()).unwrap();
|
||||
NewTrack.apply(&mut fx.state()).unwrap();
|
||||
NewTrack.apply(&mut fx.state()).unwrap();
|
||||
let file = std::rc::Rc::make_mut(fx.files.values_mut().next().unwrap());
|
||||
+1
-7
@@ -26,13 +26,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_new_track_segment_on_each_track_of_selected_file() {
|
||||
let mut fx = Fixture::default();
|
||||
New {
|
||||
name: "file",
|
||||
trackpoint: None,
|
||||
route: false,
|
||||
}
|
||||
.apply(&mut fx.state())
|
||||
.unwrap();
|
||||
New { name: "file" }.apply(&mut fx.state()).unwrap();
|
||||
NewTrack.apply(&mut fx.state()).unwrap();
|
||||
NewTrack.apply(&mut fx.state()).unwrap();
|
||||
NewTrackSegment.apply(&mut fx.state()).unwrap();
|
||||
+7
-22
@@ -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;
|
||||
@@ -51,12 +41,7 @@ mod tests {
|
||||
fn test_style_applies_to_all_tracks_of_selected_file_and_keeps_unset_fields() {
|
||||
let mut fx = Fixture::default();
|
||||
let data = std::fs::read("data/with_style.gpx").unwrap();
|
||||
crate::Load {
|
||||
data: &data,
|
||||
name: "file",
|
||||
}
|
||||
.apply(&mut fx.state())
|
||||
.unwrap();
|
||||
crate::Load { data: &data }.apply(&mut fx.state()).unwrap();
|
||||
let id = *fx.files.keys().next().unwrap();
|
||||
let before = fx.files[&id].clone();
|
||||
assert!(!before.trk.is_empty());
|
||||
+27
-110
@@ -1,43 +1,20 @@
|
||||
use std::rc::Rc;
|
||||
|
||||
use crate::{Apply, CommandError, FileId, Files, Selection, State, Waypoint};
|
||||
use crate::{
|
||||
Apply, CommandError, FileId, Selection, StackEntry, State, Waypoint, edit_waypoint_chunks,
|
||||
};
|
||||
|
||||
/// 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.
|
||||
#[derive(Debug)]
|
||||
pub struct Delete {
|
||||
pub whole_files: bool,
|
||||
}
|
||||
pub struct Delete;
|
||||
|
||||
impl Apply for Delete {
|
||||
fn apply(self, state: &mut State) -> Result<(), CommandError> {
|
||||
let files = state.selection.to_files();
|
||||
let selection = if self.whole_files {
|
||||
&files
|
||||
} else {
|
||||
&*state.selection
|
||||
};
|
||||
let next = match selection {
|
||||
let next = match &*state.selection {
|
||||
Selection::File { file_ids } => {
|
||||
state.files.retain(|id, _| !file_ids.contains(id));
|
||||
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
|
||||
@@ -89,14 +66,14 @@ impl Apply for Delete {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn delete_waypoints(
|
||||
files: &mut Files,
|
||||
fn delete_waypoints(
|
||||
files: &mut StackEntry,
|
||||
file_id: FileId,
|
||||
filter: impl Fn(&Waypoint) -> bool,
|
||||
) -> Result<Selection, CommandError> {
|
||||
let file = files.get(&file_id).ok_or(CommandError::NothingToDo)?;
|
||||
let mut file = (**file).clone();
|
||||
let changed = file.wpt.edit(&filter, |wpts| {
|
||||
let changed = edit_waypoint_chunks(&mut file, &filter, |wpts| {
|
||||
wpts.retain(|wpt| !filter(wpt));
|
||||
true
|
||||
});
|
||||
@@ -121,12 +98,7 @@ mod tests {
|
||||
fn loaded() -> (Fixture, FileId) {
|
||||
let mut fx = Fixture::default();
|
||||
let data = std::fs::read("data/with_tracks_and_segments.gpx").unwrap();
|
||||
Load {
|
||||
data: &data,
|
||||
name: "file",
|
||||
}
|
||||
.apply(&mut fx.state())
|
||||
.unwrap();
|
||||
Load { data: &data }.apply(&mut fx.state()).unwrap();
|
||||
let id = fx.order.0[0];
|
||||
(fx, id)
|
||||
}
|
||||
@@ -135,7 +107,7 @@ mod tests {
|
||||
fn test_delete_nothing_selected() {
|
||||
let mut fx = Fixture::default();
|
||||
assert_eq!(
|
||||
Delete { whole_files: false }.apply(&mut fx.state()),
|
||||
Delete.apply(&mut fx.state()),
|
||||
Err(CommandError::NothingToDo)
|
||||
);
|
||||
}
|
||||
@@ -143,20 +115,12 @@ mod tests {
|
||||
#[test]
|
||||
fn test_delete_selected_files() {
|
||||
let (mut fx, id) = loaded();
|
||||
crate::New {
|
||||
name: "keep",
|
||||
trackpoint: None,
|
||||
route: false,
|
||||
}
|
||||
.apply(&mut fx.state())
|
||||
.unwrap();
|
||||
crate::New { name: "keep" }.apply(&mut fx.state()).unwrap();
|
||||
let keep = fx.order.0[1];
|
||||
fx.selection = Selection::File {
|
||||
file_ids: HashSet::from([id]),
|
||||
};
|
||||
Delete { whole_files: false }
|
||||
.apply(&mut fx.state())
|
||||
.unwrap();
|
||||
Delete.apply(&mut fx.state()).unwrap();
|
||||
assert_eq!(fx.order.0, vec![keep]);
|
||||
assert!(fx.files.contains_key(&keep) && !fx.files.contains_key(&id));
|
||||
assert!(matches!(fx.selection, Selection::Empty));
|
||||
@@ -171,9 +135,7 @@ mod tests {
|
||||
file_id: id,
|
||||
trk_ids: HashSet::from([trk_id]),
|
||||
};
|
||||
Delete { whole_files: false }
|
||||
.apply(&mut fx.state())
|
||||
.unwrap();
|
||||
Delete.apply(&mut fx.state()).unwrap();
|
||||
let file = &fx.files[&id];
|
||||
assert_eq!(file.trk.len(), before - 1);
|
||||
assert!(file.trk.iter().all(|t| t.id != trk_id));
|
||||
@@ -190,9 +152,7 @@ mod tests {
|
||||
trk_id,
|
||||
trkseg_ids: HashSet::from([seg_id]),
|
||||
};
|
||||
Delete { whole_files: false }
|
||||
.apply(&mut fx.state())
|
||||
.unwrap();
|
||||
Delete.apply(&mut fx.state()).unwrap();
|
||||
let trk = &fx.files[&id].trk[0];
|
||||
assert_eq!(trk.trkseg.len(), before - 1);
|
||||
assert!(trk.trkseg.iter().all(|s| s.id != seg_id));
|
||||
@@ -205,10 +165,10 @@ mod tests {
|
||||
let wpts: Vec<_> = (0..n).map(|_| Waypoint::default()).collect();
|
||||
let ids = wpts.iter().map(|w| w.id).collect();
|
||||
let mut file = (*fx.files[&id]).clone();
|
||||
file.wpt = crate::Waypoints::new([crate::WaypointChunk {
|
||||
file.wpt = vec![Rc::new(crate::WaypointChunk {
|
||||
wpt: wpts,
|
||||
..Default::default()
|
||||
}]);
|
||||
})];
|
||||
fx.files.insert(id, Rc::new(file));
|
||||
ids
|
||||
}
|
||||
@@ -221,12 +181,14 @@ mod tests {
|
||||
file_id: id,
|
||||
wpt_ids: HashSet::from([ids[1]]),
|
||||
};
|
||||
let rev = fx.files[&id].wpt.rev_id;
|
||||
Delete { whole_files: false }
|
||||
.apply(&mut fx.state())
|
||||
.unwrap();
|
||||
assert_ne!(fx.files[&id].wpt.rev_id, rev);
|
||||
let left: Vec<_> = fx.files[&id].wpt.iter().map(|w| w.id).collect();
|
||||
let rev = fx.files[&id].wpt_rev_id;
|
||||
Delete.apply(&mut fx.state()).unwrap();
|
||||
assert_ne!(fx.files[&id].wpt_rev_id, rev);
|
||||
let left: Vec<_> = fx.files[&id]
|
||||
.wpt
|
||||
.iter()
|
||||
.flat_map(|c| c.wpt.iter().map(|w| w.id))
|
||||
.collect();
|
||||
assert_eq!(left, vec![ids[0], ids[2]]);
|
||||
assert_eq!(fx.selected_files(), HashSet::from([id]));
|
||||
}
|
||||
@@ -236,13 +198,11 @@ mod tests {
|
||||
let (mut fx, id) = loaded();
|
||||
with_waypoints(&mut fx, id, 3);
|
||||
fx.selection = Selection::Waypoints { file_id: id };
|
||||
Delete { whole_files: false }
|
||||
.apply(&mut fx.state())
|
||||
.unwrap();
|
||||
Delete.apply(&mut fx.state()).unwrap();
|
||||
assert!(fx.files[&id].wpt.is_empty());
|
||||
fx.selection = Selection::Waypoints { file_id: id };
|
||||
assert_eq!(
|
||||
Delete { whole_files: false }.apply(&mut fx.state()),
|
||||
Delete.apply(&mut fx.state()),
|
||||
Err(CommandError::NothingToDo)
|
||||
);
|
||||
}
|
||||
@@ -255,50 +215,7 @@ mod tests {
|
||||
trk_ids: HashSet::from([Default::default()]),
|
||||
};
|
||||
assert_eq!(
|
||||
Delete { whole_files: false }.apply(&mut fx.state()),
|
||||
Err(CommandError::NothingToDo)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_delete_whole_files_of_the_selected_elements() {
|
||||
for selection in [
|
||||
|id: FileId, fx: &Fixture| Selection::Track {
|
||||
file_id: id,
|
||||
trk_ids: HashSet::from([fx.files[&id].trk[0].id]),
|
||||
},
|
||||
|id: FileId, fx: &Fixture| Selection::TrackSegment {
|
||||
file_id: id,
|
||||
trk_id: fx.files[&id].trk[0].id,
|
||||
trkseg_ids: HashSet::from([fx.files[&id].trk[0].trkseg[0].id]),
|
||||
},
|
||||
|id: FileId, _: &Fixture| Selection::Waypoints { file_id: id },
|
||||
|id: FileId, _: &Fixture| Selection::File {
|
||||
file_ids: HashSet::from([id]),
|
||||
},
|
||||
] {
|
||||
let (mut fx, id) = loaded();
|
||||
crate::New {
|
||||
name: "keep",
|
||||
trackpoint: None,
|
||||
route: false,
|
||||
}
|
||||
.apply(&mut fx.state())
|
||||
.unwrap();
|
||||
let keep = fx.order.0[1];
|
||||
fx.selection = selection(id, &fx);
|
||||
Delete { whole_files: true }.apply(&mut fx.state()).unwrap();
|
||||
assert_eq!(fx.order.0, vec![keep]);
|
||||
assert!(!fx.files.contains_key(&id));
|
||||
assert!(matches!(fx.selection, Selection::Empty));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_delete_whole_files_nothing_selected() {
|
||||
let mut fx = Fixture::default();
|
||||
assert_eq!(
|
||||
Delete { whole_files: true }.apply(&mut fx.state()),
|
||||
Delete.apply(&mut fx.state()),
|
||||
Err(CommandError::NothingToDo)
|
||||
);
|
||||
}
|
||||
+2
-14
@@ -28,20 +28,8 @@ mod tests {
|
||||
DeleteAll.apply(&mut fx.state()),
|
||||
Err(CommandError::NothingToDo)
|
||||
);
|
||||
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();
|
||||
crate::New { name: "a" }.apply(&mut fx.state()).unwrap();
|
||||
crate::New { name: "b" }.apply(&mut fx.state()).unwrap();
|
||||
assert!(DeleteAll.apply(&mut fx.state()).is_ok());
|
||||
assert!(fx.files.is_empty());
|
||||
assert!(fx.order.0.is_empty());
|
||||
+106
-63
@@ -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, File, FileId, Selection, StackEntry, State, Track, TrackSegment, Waypoint,
|
||||
WaypointChunk,
|
||||
};
|
||||
|
||||
#[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
|
||||
@@ -131,23 +107,65 @@ impl Apply for Duplicate {
|
||||
}
|
||||
|
||||
fn duplicate_waypoints(
|
||||
files: &mut Files,
|
||||
files: &mut StackEntry,
|
||||
file_id: FileId,
|
||||
filter: impl Fn(&Waypoint) -> bool,
|
||||
) -> Result<Selection, CommandError> {
|
||||
let file = files.get(&file_id).ok_or(CommandError::NothingToDo)?;
|
||||
let selected: Vec<&Waypoint> = file.wpt.iter().filter(|wpt| filter(wpt)).collect();
|
||||
let last = selected.last().ok_or(CommandError::NothingToDo)?.id;
|
||||
let copies: Vec<Waypoint> = selected.into_iter().map(copy_waypoint).collect();
|
||||
let copy_ids = copies.iter().map(|wpt| wpt.id).collect();
|
||||
|
||||
// The copies go right after the last selected waypoint.
|
||||
let mut file = (**file).clone();
|
||||
file.wpt.insert_after(Some(last), copies);
|
||||
let last_chunk = file
|
||||
.wpt
|
||||
.iter()
|
||||
.rposition(|chunk| chunk.wpt.iter().any(&filter))
|
||||
.ok_or(CommandError::NothingToDo)?;
|
||||
|
||||
let mut copies = HashSet::new();
|
||||
let mut inserted = Vec::new();
|
||||
let mut chunk = WaypointChunk::default();
|
||||
for wpt in file
|
||||
.wpt
|
||||
.iter()
|
||||
.flat_map(|chunk| &chunk.wpt)
|
||||
.filter(|wpt| filter(wpt))
|
||||
{
|
||||
let mut copy = wpt.clone();
|
||||
copy.id = Default::default();
|
||||
copies.insert(copy.id);
|
||||
chunk.wpt.push(copy);
|
||||
if chunk.is_full() {
|
||||
inserted.push(Rc::new(std::mem::take(&mut chunk)));
|
||||
}
|
||||
}
|
||||
if !chunk.wpt.is_empty() {
|
||||
inserted.push(Rc::new(chunk));
|
||||
}
|
||||
|
||||
// The copies go right after the last selected waypoint: only the chunk holding it is cut
|
||||
// (when waypoints follow it), all the other chunks are kept as they are.
|
||||
let cut = &file.wpt[last_chunk];
|
||||
let split = cut.wpt.iter().rposition(&filter).unwrap() + 1;
|
||||
let replacement = if split == cut.wpt.len() {
|
||||
let mut chunks = vec![cut.clone()];
|
||||
chunks.extend(inserted);
|
||||
chunks
|
||||
} else {
|
||||
let part = |wpt: &[Waypoint]| {
|
||||
Rc::new(WaypointChunk {
|
||||
wpt: wpt.to_vec(),
|
||||
..Default::default()
|
||||
})
|
||||
};
|
||||
let mut chunks = vec![part(&cut.wpt[..split])];
|
||||
chunks.extend(inserted);
|
||||
chunks.push(part(&cut.wpt[split..]));
|
||||
chunks
|
||||
};
|
||||
file.wpt.splice(last_chunk..=last_chunk, replacement);
|
||||
file.wpt_rev_id = Default::default();
|
||||
files.insert(file_id, Rc::new(file));
|
||||
Ok(Selection::Waypoint {
|
||||
file_id,
|
||||
wpt_ids: copy_ids,
|
||||
wpt_ids: copies,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -160,6 +178,29 @@ fn append_copies<T>(items: &mut Vec<T>, filter: impl Fn(&T) -> bool, copy: impl
|
||||
items.splice(last + 1..last + 1, copies);
|
||||
}
|
||||
|
||||
// Track points are shared chunks, so copies are cheap.
|
||||
fn copy_segment(segment: &TrackSegment) -> TrackSegment {
|
||||
let mut copy = segment.clone();
|
||||
copy.id = Default::default();
|
||||
copy
|
||||
}
|
||||
|
||||
fn copy_track(track: &Track) -> Track {
|
||||
Track {
|
||||
id: Default::default(),
|
||||
trkseg: track.trkseg.iter().map(copy_segment).collect(),
|
||||
..track.clone()
|
||||
}
|
||||
}
|
||||
|
||||
fn copy_file(file: &File) -> File {
|
||||
File {
|
||||
id: Default::default(),
|
||||
trk: file.trk.iter().map(copy_track).collect(),
|
||||
..file.clone()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::engine::command::fixture::Fixture;
|
||||
@@ -170,12 +211,7 @@ mod tests {
|
||||
fn loaded() -> (Fixture, FileId) {
|
||||
let mut fx = Fixture::default();
|
||||
let data = std::fs::read("data/with_tracks_and_segments.gpx").unwrap();
|
||||
Load {
|
||||
data: &data,
|
||||
name: "file",
|
||||
}
|
||||
.apply(&mut fx.state())
|
||||
.unwrap();
|
||||
Load { data: &data }.apply(&mut fx.state()).unwrap();
|
||||
let id = fx.order.0[0];
|
||||
(fx, id)
|
||||
}
|
||||
@@ -214,13 +250,7 @@ mod tests {
|
||||
fn test_duplicate_files_go_after_last_selected() {
|
||||
let mut fx = Fixture::default();
|
||||
for name in ["a", "b", "c"] {
|
||||
crate::New {
|
||||
name,
|
||||
trackpoint: None,
|
||||
route: false,
|
||||
}
|
||||
.apply(&mut fx.state())
|
||||
.unwrap();
|
||||
crate::New { name }.apply(&mut fx.state()).unwrap();
|
||||
}
|
||||
let [a, b, c] = [fx.order.0[0], fx.order.0[1], fx.order.0[2]];
|
||||
fx.selection = Selection::File {
|
||||
@@ -263,44 +293,57 @@ mod tests {
|
||||
let wpts: Vec<_> = (0..3).map(|_| Waypoint::default()).collect();
|
||||
let ids: Vec<_> = wpts.iter().map(|w| w.id).collect();
|
||||
let mut file = (*fx.files[&id]).clone();
|
||||
file.wpt = crate::Waypoints::new([crate::WaypointChunk {
|
||||
file.wpt = vec![Rc::new(crate::WaypointChunk {
|
||||
wpt: wpts,
|
||||
..Default::default()
|
||||
}]);
|
||||
})];
|
||||
fx.files.insert(id, Rc::new(file));
|
||||
let original_chunk = fx.files[&id].wpt.chunks()[0].clone();
|
||||
let original_chunk = fx.files[&id].wpt[0].clone();
|
||||
|
||||
fx.selection = Selection::Waypoint {
|
||||
file_id: id,
|
||||
wpt_ids: HashSet::from([ids[0]]),
|
||||
};
|
||||
let rev = fx.files[&id].wpt.rev_id;
|
||||
let rev = fx.files[&id].wpt_rev_id;
|
||||
Duplicate.apply(&mut fx.state()).unwrap();
|
||||
assert_ne!(fx.files[&id].wpt.rev_id, rev);
|
||||
let all: Vec<_> = fx.files[&id].wpt.iter().map(|w| w.id).collect();
|
||||
assert_ne!(fx.files[&id].wpt_rev_id, rev);
|
||||
let all: Vec<_> = fx.files[&id]
|
||||
.wpt
|
||||
.iter()
|
||||
.flat_map(|c| c.wpt.iter().map(|w| w.id))
|
||||
.collect();
|
||||
assert_eq!(all.len(), 4);
|
||||
assert!(
|
||||
matches!(&fx.selection, Selection::Waypoint { wpt_ids, .. } if wpt_ids == &HashSet::from([all[1]]))
|
||||
);
|
||||
// the copy comes right after the selected waypoint, in a new chunk
|
||||
// the chunk is cut after the selected waypoint: [w0] [copy] [w1 w2]
|
||||
assert_eq!(all[..], [ids[0], all[1], ids[1], ids[2]]);
|
||||
assert_eq!(fx.files[&id].wpt.chunks().len(), 1);
|
||||
assert_ne!(fx.files[&id].wpt.chunks()[0].id, original_chunk.id);
|
||||
assert_eq!(fx.files[&id].wpt.len(), 3);
|
||||
assert_ne!(fx.files[&id].wpt[0].id, original_chunk.id);
|
||||
|
||||
// selecting the last waypoint: the copy goes at the end
|
||||
let last = fx.files[&id].wpt.iter().last().unwrap().id;
|
||||
// selecting the last waypoint of a chunk does not cut it
|
||||
let last = fx.files[&id].wpt.last().unwrap().wpt.last().unwrap().id;
|
||||
let chunks = fx.files[&id].wpt.clone();
|
||||
fx.selection = Selection::Waypoint {
|
||||
file_id: id,
|
||||
wpt_ids: HashSet::from([last]),
|
||||
};
|
||||
Duplicate.apply(&mut fx.state()).unwrap();
|
||||
let all: Vec<_> = fx.files[&id].wpt.iter().map(|w| w.id).collect();
|
||||
assert_eq!(all.len(), 5);
|
||||
assert_eq!(all[..4], [ids[0], all[1], ids[1], ids[2]]);
|
||||
let file = &fx.files[&id];
|
||||
assert_eq!(file.wpt.len(), 4);
|
||||
assert!(
|
||||
file.wpt[..3]
|
||||
.iter()
|
||||
.zip(&chunks)
|
||||
.all(|(a, b)| Rc::ptr_eq(a, b))
|
||||
);
|
||||
|
||||
fx.selection = Selection::Waypoints { file_id: id };
|
||||
Duplicate.apply(&mut fx.state()).unwrap();
|
||||
assert_eq!(fx.files[&id].wpt.len(), 10);
|
||||
assert_eq!(
|
||||
fx.files[&id].wpt.iter().map(|c| c.wpt.len()).sum::<usize>(),
|
||||
10
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -0,0 +1,48 @@
|
||||
use crate::{Apply, CommandError, State, parse, produce};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Load<'a> {
|
||||
pub data: &'a [u8],
|
||||
}
|
||||
|
||||
impl Apply for Load<'_> {
|
||||
fn apply(self, state: &mut State) -> Result<(), CommandError> {
|
||||
let file = parse(self.data).map_err(|err| CommandError::InvalidData(err.to_string()))?;
|
||||
produce(state, |_| vec![file]);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::engine::command::fixture::Fixture;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_load() {
|
||||
let mut fx = Fixture::default();
|
||||
let data = std::fs::read("data/with_tracks.gpx").unwrap();
|
||||
assert!(Load { data: &data }.apply(&mut fx.state()).is_ok());
|
||||
assert_eq!(fx.files.len(), 1);
|
||||
let file = fx.files.values().next().unwrap();
|
||||
assert!(!file.trk.is_empty());
|
||||
assert_eq!(fx.selected_files(), [file.id].into());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_load_invalid_file_changes_nothing() {
|
||||
let mut fx = Fixture::default();
|
||||
crate::New { name: "keep" }.apply(&mut fx.state()).unwrap();
|
||||
let selected = fx.selected_files();
|
||||
|
||||
let result = Load {
|
||||
data: b"<gpx><trk></gpx>",
|
||||
}
|
||||
.apply(&mut fx.state());
|
||||
assert!(matches!(result, Err(CommandError::InvalidData(_))));
|
||||
assert_eq!(fx.files.len(), 1);
|
||||
assert_eq!(fx.order.0.len(), 1);
|
||||
assert_eq!(fx.selected_files(), selected);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
mod delete;
|
||||
mod delete_all;
|
||||
mod duplicate;
|
||||
mod load;
|
||||
mod new;
|
||||
|
||||
pub use delete::*;
|
||||
pub use delete_all::*;
|
||||
pub use duplicate::*;
|
||||
pub use load::*;
|
||||
pub use new::*;
|
||||
@@ -0,0 +1,36 @@
|
||||
use crate::{Apply, CommandError, File, State, produce};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct New<'a> {
|
||||
pub name: &'a str,
|
||||
}
|
||||
|
||||
impl Apply for New<'_> {
|
||||
fn apply(self, state: &mut State) -> Result<(), CommandError> {
|
||||
produce(state, |_| {
|
||||
let mut file = File::default();
|
||||
file.info.name = self.name.to_owned();
|
||||
vec![file]
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::engine::command::fixture::Fixture;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_new() {
|
||||
let mut fx = Fixture::default();
|
||||
assert!(New { name: "new" }.apply(&mut fx.state()).is_ok());
|
||||
assert_eq!(fx.files.len(), 1);
|
||||
let file = fx.files.values().next().unwrap();
|
||||
assert_eq!(file.info.name, "new");
|
||||
assert!(file.trk.is_empty());
|
||||
assert_eq!(fx.selected_files(), [file.id].into());
|
||||
assert_eq!(fx.order.0, vec![file.id]);
|
||||
}
|
||||
}
|
||||
@@ -2,25 +2,21 @@
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use crate::{Clipboard, FileId, FileOrder, Files, Selection, State, TrackpointCategories};
|
||||
use crate::{FileId, FileOrder, Selection, StackEntry, State};
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Fixture {
|
||||
pub files: Files,
|
||||
pub files: StackEntry,
|
||||
pub selection: Selection,
|
||||
pub order: FileOrder,
|
||||
pub clipboard: Option<Clipboard>,
|
||||
pub categories: TrackpointCategories,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
pub fn state(&mut self) -> State<'_> {
|
||||
State {
|
||||
categories: &mut self.categories,
|
||||
files: &mut self.files,
|
||||
selection: &mut self.selection,
|
||||
order: &mut self.order,
|
||||
clipboard: &mut self.clipboard,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
mod apply;
|
||||
mod command;
|
||||
mod edit;
|
||||
mod file;
|
||||
#[cfg(test)]
|
||||
pub(crate) mod fixture;
|
||||
mod pattern;
|
||||
mod tools;
|
||||
|
||||
pub use apply::*;
|
||||
pub use command::*;
|
||||
pub use edit::*;
|
||||
pub use file::*;
|
||||
pub use pattern::*;
|
||||
pub use tools::*;
|
||||
@@ -0,0 +1,40 @@
|
||||
use std::rc::Rc;
|
||||
|
||||
use crate::{File, Waypoint, WaypointChunk};
|
||||
|
||||
/// Edits the waypoints of the chunks containing a waypoint accepted by `filter`.
|
||||
///
|
||||
/// `f` receives a copy of the chunk's waypoints and returns whether it changed them. A
|
||||
/// changed chunk is replaced by a new one (with a new id, so that derived data is recomputed)
|
||||
/// and chunks left empty are dropped. Returns whether anything changed.
|
||||
pub fn edit_waypoint_chunks(
|
||||
file: &mut File,
|
||||
filter: impl Fn(&Waypoint) -> bool,
|
||||
mut f: impl FnMut(&mut Vec<Waypoint>) -> bool,
|
||||
) -> bool {
|
||||
let mut changed = false;
|
||||
let mut chunks = Vec::with_capacity(file.wpt.len());
|
||||
for chunk in file.wpt.drain(..) {
|
||||
if !chunk.wpt.iter().any(&filter) {
|
||||
chunks.push(chunk);
|
||||
continue;
|
||||
}
|
||||
let mut wpt = chunk.wpt.clone();
|
||||
if !f(&mut wpt) {
|
||||
chunks.push(chunk);
|
||||
continue;
|
||||
}
|
||||
changed = true;
|
||||
if !wpt.is_empty() {
|
||||
chunks.push(Rc::new(WaypointChunk {
|
||||
wpt,
|
||||
..Default::default()
|
||||
}));
|
||||
}
|
||||
}
|
||||
file.wpt = chunks;
|
||||
if changed {
|
||||
file.wpt_rev_id = Default::default();
|
||||
}
|
||||
changed
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
mod edit_waypoint_chunks;
|
||||
mod produce;
|
||||
mod update_selected;
|
||||
|
||||
pub use edit_waypoint_chunks::*;
|
||||
pub use produce::*;
|
||||
pub use update_selected::*;
|
||||
File renamed without changes.
+22
-34
@@ -1,6 +1,8 @@
|
||||
use std::rc::Rc;
|
||||
|
||||
use crate::{File, FileId, Files, Route, Selection, State, Track, TrackSegment, Waypoint};
|
||||
use crate::{
|
||||
File, FileId, Selection, StackEntry, State, Track, TrackSegment, Waypoint, edit_waypoint_chunks,
|
||||
};
|
||||
|
||||
/// What an [`Editor`] hook did to the element it was given.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
@@ -21,19 +23,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 {
|
||||
@@ -76,7 +72,7 @@ fn edit_where<T>(
|
||||
|
||||
/// Edits a copy of the file (cheap, track points are shared chunks) and stores it back as a
|
||||
/// new snapshot only if something changed.
|
||||
fn update_file(files: &mut Files, id: FileId, f: impl FnOnce(&mut File) -> Edit) {
|
||||
fn update_file(files: &mut StackEntry, id: FileId, f: impl FnOnce(&mut File) -> Edit) {
|
||||
let Some(current) = files.get(&id) else {
|
||||
return;
|
||||
};
|
||||
@@ -91,7 +87,7 @@ fn edit_waypoints<E: Editor + ?Sized>(
|
||||
filter: impl Fn(&Waypoint) -> bool,
|
||||
editor: &mut E,
|
||||
) -> Edit {
|
||||
let changed = file.wpt.edit(&filter, |wpts| {
|
||||
let changed = edit_waypoint_chunks(file, &filter, |wpts| {
|
||||
edit_where(wpts, &filter, |wpt| editor.waypoint(wpt)) == Edit::Changed
|
||||
});
|
||||
if changed {
|
||||
@@ -101,7 +97,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 +105,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(
|
||||
@@ -192,7 +179,7 @@ mod tests {
|
||||
fn fixture_with_tracks() -> (Fixture, FileId) {
|
||||
let mut fx = Fixture::default();
|
||||
let data = std::fs::read("data/with_tracks_and_segments.gpx").unwrap();
|
||||
let file = Rc::new(crate::parse(&data, &mut Default::default()).unwrap());
|
||||
let file = Rc::new(crate::parse(&data).unwrap());
|
||||
let id = file.id;
|
||||
fx.files.insert(id, file);
|
||||
(fx, id)
|
||||
@@ -300,34 +287,35 @@ mod tests {
|
||||
let wpts: Vec<_> = (0..3).map(|_| Waypoint::default()).collect();
|
||||
let ids: Vec<_> = wpts.iter().map(|w| w.id).collect();
|
||||
let mut file = (*fx.files[&id]).clone();
|
||||
file.wpt = crate::Waypoints::new([crate::WaypointChunk {
|
||||
file.wpt = vec![Rc::new(crate::WaypointChunk {
|
||||
wpt: wpts,
|
||||
..Default::default()
|
||||
}]);
|
||||
})];
|
||||
fx.files.insert(id, Rc::new(file));
|
||||
let chunk_id = fx.files[&id].wpt.chunks()[0].id;
|
||||
let chunk_id = fx.files[&id].wpt[0].id;
|
||||
|
||||
// A file selection never touches waypoints.
|
||||
fx.selection = Selection::File {
|
||||
file_ids: HashSet::from([id]),
|
||||
};
|
||||
update_selected(&mut fx.state(), &mut Name);
|
||||
assert!(fx.files[&id].wpt.iter().all(|w| w.name.is_none()));
|
||||
assert!(fx.files[&id].wpt[0].wpt.iter().all(|w| w.name.is_none()));
|
||||
|
||||
fx.selection = Selection::Waypoint {
|
||||
file_id: id,
|
||||
wpt_ids: HashSet::from([ids[1]]),
|
||||
};
|
||||
let rev = fx.files[&id].wpt.rev_id;
|
||||
let rev = fx.files[&id].wpt_rev_id;
|
||||
update_selected(&mut fx.state(), &mut Name);
|
||||
assert_ne!(fx.files[&id].wpt.rev_id, rev);
|
||||
assert_ne!(fx.files[&id].wpt.chunks()[0].id, chunk_id);
|
||||
let named: Vec<_> = fx.files[&id].wpt.iter().map(|w| w.name.is_some()).collect();
|
||||
assert_ne!(fx.files[&id].wpt_rev_id, rev);
|
||||
let chunk = &fx.files[&id].wpt[0];
|
||||
assert_ne!(chunk.id, chunk_id);
|
||||
let named: Vec<_> = chunk.wpt.iter().map(|w| w.name.is_some()).collect();
|
||||
assert_eq!(named, [false, true, false]);
|
||||
|
||||
fx.selection = Selection::Waypoints { file_id: id };
|
||||
update_selected(&mut fx.state(), &mut Name);
|
||||
assert!(fx.files[&id].wpt.iter().all(|w| w.name.is_some()));
|
||||
assert!(fx.files[&id].wpt[0].wpt.iter().all(|w| w.name.is_some()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -0,0 +1,22 @@
|
||||
use crate::{Apply, CommandError, LngLatBounds, State};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CleanType {
|
||||
Inside,
|
||||
Outside,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Clean {
|
||||
pub bounds: LngLatBounds,
|
||||
pub type_: CleanType,
|
||||
pub trkpt: bool,
|
||||
pub wpt: bool,
|
||||
}
|
||||
|
||||
impl Apply for Clean {
|
||||
fn apply(self, _state: &mut State) -> Result<(), CommandError> {
|
||||
// TODO
|
||||
Err(CommandError::NotImplemented("clean"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
use crate::{Apply, CommandError, State};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Crop {
|
||||
pub start: u32,
|
||||
pub end: u32,
|
||||
}
|
||||
|
||||
impl Apply for Crop {
|
||||
fn apply(self, _state: &mut State) -> Result<(), CommandError> {
|
||||
// TODO
|
||||
Err(CommandError::NotImplemented("crop"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
use crate::{Apply, CommandError, State};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Elevation<'a> {
|
||||
pub ele: &'a [f64],
|
||||
}
|
||||
|
||||
impl Apply for Elevation<'_> {
|
||||
fn apply(self, _state: &mut State) -> Result<(), CommandError> {
|
||||
// TODO
|
||||
Err(CommandError::NotImplemented("elevation"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
use crate::{Apply, CommandError, State};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Extract;
|
||||
|
||||
impl Apply for Extract {
|
||||
fn apply(self, _state: &mut State) -> Result<(), CommandError> {
|
||||
// TODO
|
||||
Err(CommandError::NotImplemented("extract"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
use crate::{Apply, CommandError, State};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum MergeType {
|
||||
Connect,
|
||||
Group,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Merge {
|
||||
pub type_: MergeType,
|
||||
}
|
||||
|
||||
impl Apply for Merge {
|
||||
fn apply(self, _state: &mut State) -> Result<(), CommandError> {
|
||||
// TODO
|
||||
Err(CommandError::NotImplemented("merge"))
|
||||
}
|
||||
}
|
||||
+2
-12
@@ -1,33 +1,23 @@
|
||||
mod change_loop_start;
|
||||
mod clean;
|
||||
mod crop;
|
||||
mod edit_waypoint;
|
||||
mod elevation;
|
||||
mod extract;
|
||||
mod insert_anchor;
|
||||
mod merge;
|
||||
mod move_waypoint;
|
||||
mod new_waypoint;
|
||||
mod reduce;
|
||||
mod reverse;
|
||||
mod round_trip;
|
||||
mod route;
|
||||
mod splice_trackpoints;
|
||||
mod split;
|
||||
mod time;
|
||||
|
||||
pub use change_loop_start::*;
|
||||
pub use clean::*;
|
||||
pub use crop::*;
|
||||
pub use edit_waypoint::*;
|
||||
pub use elevation::*;
|
||||
pub use extract::*;
|
||||
pub use insert_anchor::*;
|
||||
pub use merge::*;
|
||||
pub use move_waypoint::*;
|
||||
pub use new_waypoint::*;
|
||||
pub use reduce::*;
|
||||
pub use reverse::*;
|
||||
pub use round_trip::*;
|
||||
pub use route::*;
|
||||
pub use splice_trackpoints::*;
|
||||
pub use split::*;
|
||||
pub use time::*;
|
||||
@@ -0,0 +1,15 @@
|
||||
use crate::{Apply, CommandError, State};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct MoveWaypoint {
|
||||
pub lng: f64,
|
||||
pub lat: f64,
|
||||
pub ele: f64,
|
||||
}
|
||||
|
||||
impl Apply for MoveWaypoint {
|
||||
fn apply(self, _state: &mut State) -> Result<(), CommandError> {
|
||||
// TODO
|
||||
Err(CommandError::NotImplemented("move waypoint"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
use crate::{Apply, CommandError, State};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct NewWaypoint<'a> {
|
||||
pub lng: f64,
|
||||
pub lat: f64,
|
||||
pub ele: f64,
|
||||
pub name: &'a str,
|
||||
pub desc: &'a str,
|
||||
pub icon: &'a str,
|
||||
pub link: &'a str,
|
||||
}
|
||||
|
||||
impl Apply for NewWaypoint<'_> {
|
||||
fn apply(self, _state: &mut State) -> Result<(), CommandError> {
|
||||
// TODO
|
||||
Err(CommandError::NotImplemented("new waypoint"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
use crate::{Apply, CommandError, State};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Reverse;
|
||||
|
||||
impl Apply for Reverse {
|
||||
fn apply(self, _state: &mut State) -> Result<(), CommandError> {
|
||||
// TODO
|
||||
Err(CommandError::NotImplemented("reverse"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
use std::rc::Rc;
|
||||
|
||||
use crate::{Apply, CommandError, File, FileId, LngLat, Selection, State, Trackpoint};
|
||||
|
||||
/// Replaces the trackpoints `start..end` of the last track segment of the selection by the
|
||||
/// given ones (a pure insertion when `start == end`, a pure removal when there are no new
|
||||
/// points).
|
||||
///
|
||||
/// The selection can be made of several files, tracks or track segments: the indices are
|
||||
/// meant for its very last segment, in file order, then track order, then segment order.
|
||||
#[derive(Debug)]
|
||||
pub struct SpliceTrackpoints<'a> {
|
||||
pub start: u32,
|
||||
pub end: u32,
|
||||
pub lng: &'a [f64],
|
||||
pub lat: &'a [f64],
|
||||
pub ele: &'a [f64],
|
||||
}
|
||||
|
||||
impl Apply for SpliceTrackpoints<'_> {
|
||||
fn apply(self, state: &mut State) -> Result<(), CommandError> {
|
||||
let (start, end) = (self.start as usize, self.end as usize);
|
||||
if start > end || self.lng.len() != self.lat.len() || self.lat.len() != self.ele.len() {
|
||||
return Err(CommandError::InvalidData(
|
||||
"invalid trackpoints range".into(),
|
||||
));
|
||||
}
|
||||
let (file_id, trk, seg) = last_segment(state).ok_or(CommandError::NothingToDo)?;
|
||||
let mut file = (*state.files[&file_id]).clone();
|
||||
let segment = &mut file.trk[trk].trkseg[seg];
|
||||
if end > segment.len() {
|
||||
return Err(CommandError::InvalidData(
|
||||
"trackpoints range out of bounds".into(),
|
||||
));
|
||||
}
|
||||
if start == end && self.lng.is_empty() {
|
||||
return Err(CommandError::NothingToDo);
|
||||
}
|
||||
let points = (0..self.lng.len())
|
||||
.map(|i| Trackpoint {
|
||||
coordinates: LngLat {
|
||||
lng: self.lng[i],
|
||||
lat: self.lat[i],
|
||||
},
|
||||
ele: self.ele[i],
|
||||
..Default::default()
|
||||
})
|
||||
.collect();
|
||||
segment.splice(start, end, points);
|
||||
segment.rev_id = Default::default();
|
||||
state.files.insert(file_id, Rc::new(file));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Position (file, track index, segment index) of the last segment of the selection.
|
||||
fn last_segment(state: &State) -> Option<(FileId, usize, usize)> {
|
||||
let last_of_track = |file: &File, trk: usize| file.trk[trk].trkseg.len().checked_sub(1);
|
||||
let last_of_file = |file: &File, filter: &dyn Fn(usize) -> bool| {
|
||||
(0..file.trk.len())
|
||||
.rev()
|
||||
.filter(|&trk| filter(trk))
|
||||
.find_map(|trk| last_of_track(file, trk).map(|seg| (trk, seg)))
|
||||
};
|
||||
match &*state.selection {
|
||||
Selection::File { file_ids } => state
|
||||
.order
|
||||
.0
|
||||
.iter()
|
||||
.rev()
|
||||
.filter(|id| file_ids.contains(id))
|
||||
.find_map(|id| {
|
||||
let (trk, seg) = last_of_file(state.files.get(id)?, &|_| true)?;
|
||||
Some((*id, trk, seg))
|
||||
}),
|
||||
Selection::Track { file_id, trk_ids } => {
|
||||
let file = state.files.get(file_id)?;
|
||||
let (trk, seg) = last_of_file(file, &|trk| trk_ids.contains(&file.trk[trk].id))?;
|
||||
Some((*file_id, trk, seg))
|
||||
}
|
||||
Selection::TrackSegment {
|
||||
file_id,
|
||||
trk_id,
|
||||
trkseg_ids,
|
||||
} => {
|
||||
let file = state.files.get(file_id)?;
|
||||
let trk = file.trk.iter().position(|trk| trk.id == *trk_id)?;
|
||||
let seg = file.trk[trk]
|
||||
.trkseg
|
||||
.iter()
|
||||
.rposition(|seg| trkseg_ids.contains(&seg.id))?;
|
||||
Some((*file_id, trk, seg))
|
||||
}
|
||||
Selection::Empty | Selection::Waypoints { .. } | Selection::Waypoint { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::HashSet;
|
||||
|
||||
use crate::{FileId, Load, engine::command::fixture::Fixture};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn loaded() -> (Fixture, FileId) {
|
||||
let mut fx = Fixture::default();
|
||||
let data = std::fs::read("data/with_tracks_and_segments.gpx").unwrap();
|
||||
Load { data: &data }.apply(&mut fx.state()).unwrap();
|
||||
let id = fx.order.0[0];
|
||||
let trk = &fx.files[&id].trk[0];
|
||||
fx.selection = Selection::TrackSegment {
|
||||
file_id: id,
|
||||
trk_id: trk.id,
|
||||
trkseg_ids: HashSet::from([trk.trkseg[0].id]),
|
||||
};
|
||||
(fx, id)
|
||||
}
|
||||
|
||||
fn splice<'a>(
|
||||
start: u32,
|
||||
end: u32,
|
||||
lng: &'a [f64],
|
||||
lat: &'a [f64],
|
||||
ele: &'a [f64],
|
||||
) -> SpliceTrackpoints<'a> {
|
||||
SpliceTrackpoints {
|
||||
start,
|
||||
end,
|
||||
lng,
|
||||
lat,
|
||||
ele,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_splice_replaces_points_of_selected_segment_only() {
|
||||
let (mut fx, id) = loaded();
|
||||
let before = fx.files[&id].clone();
|
||||
let len = before.trk[0].trkseg[0].len();
|
||||
assert!(len >= 3);
|
||||
|
||||
splice(1, 3, &[1.0, 2.0, 3.0], &[4.0, 5.0, 6.0], &[7.0, 8.0, 9.0])
|
||||
.apply(&mut fx.state())
|
||||
.unwrap();
|
||||
|
||||
let after = &fx.files[&id];
|
||||
let (old, new) = (&before.trk[0].trkseg[0], &after.trk[0].trkseg[0]);
|
||||
assert_eq!(new.len(), len + 1);
|
||||
assert_eq!(new[0].coordinates.lng, old[0].coordinates.lng);
|
||||
assert_eq!(new[1].coordinates.lng, 1.0);
|
||||
assert_eq!(new[3].coordinates.lat, 6.0);
|
||||
assert_eq!(new[3].ele, 9.0);
|
||||
assert_eq!(new[4].coordinates.lng, old[3].coordinates.lng);
|
||||
assert_ne!(new.rev_id, old.rev_id);
|
||||
assert_eq!(new.id, old.id);
|
||||
// other segments and tracks keep their revision
|
||||
for (b, a) in before.trk.iter().zip(&after.trk) {
|
||||
for (b, a) in b.trkseg.iter().zip(&a.trkseg) {
|
||||
if a.id != new.id {
|
||||
assert_eq!(a.rev_id, b.rev_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_splice_append_and_remove() {
|
||||
let (mut fx, id) = loaded();
|
||||
let len = fx.files[&id].trk[0].trkseg[0].len() as u32;
|
||||
splice(len, len, &[1.0], &[2.0], &[3.0])
|
||||
.apply(&mut fx.state())
|
||||
.unwrap();
|
||||
let seg = &fx.files[&id].trk[0].trkseg[0];
|
||||
assert_eq!(seg.len(), len as usize + 1);
|
||||
assert_eq!(seg[len as usize].ele, 3.0);
|
||||
|
||||
splice(0, len + 1, &[], &[], &[])
|
||||
.apply(&mut fx.state())
|
||||
.unwrap();
|
||||
assert_eq!(fx.files[&id].trk[0].trkseg[0].len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_splice_invalid_arguments_change_nothing() {
|
||||
let (mut fx, id) = loaded();
|
||||
let before = fx.files[&id].clone();
|
||||
let len = before.trk[0].trkseg[0].len() as u32;
|
||||
let results = [
|
||||
splice(2, 1, &[], &[], &[]).apply(&mut fx.state()),
|
||||
splice(0, 0, &[1.0], &[], &[]).apply(&mut fx.state()),
|
||||
splice(0, len + 1, &[], &[], &[]).apply(&mut fx.state()),
|
||||
];
|
||||
assert!(
|
||||
results
|
||||
.iter()
|
||||
.all(|r| matches!(r, Err(CommandError::InvalidData(_))))
|
||||
);
|
||||
assert_eq!(
|
||||
splice(0, 0, &[], &[], &[]).apply(&mut fx.state()),
|
||||
Err(CommandError::NothingToDo)
|
||||
);
|
||||
assert!(std::rc::Rc::ptr_eq(&fx.files[&id], &before));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_splice_needs_a_segment_selection() {
|
||||
let (mut fx, _) = loaded();
|
||||
fx.selection = Selection::Empty;
|
||||
assert_eq!(
|
||||
splice(0, 0, &[1.0], &[1.0], &[1.0]).apply(&mut fx.state()),
|
||||
Err(CommandError::NothingToDo)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_splice_targets_last_segment_of_the_selection() {
|
||||
let (mut fx, id) = loaded();
|
||||
let file = fx.files[&id].clone();
|
||||
assert!(file.trk.len() >= 2);
|
||||
let last_trk = file.trk.len() - 1;
|
||||
let last_seg = file.trk[last_trk].trkseg.len() - 1;
|
||||
|
||||
// whole file selected: last segment of its last track
|
||||
fx.selection = Selection::File {
|
||||
file_ids: HashSet::from([id]),
|
||||
};
|
||||
splice(0, 0, &[1.0], &[2.0], &[3.0])
|
||||
.apply(&mut fx.state())
|
||||
.unwrap();
|
||||
let after = &fx.files[&id];
|
||||
for (t, (b, a)) in file.trk.iter().zip(&after.trk).enumerate() {
|
||||
for (s, (b, a)) in b.trkseg.iter().zip(&a.trkseg).enumerate() {
|
||||
let target = (t, s) == (last_trk, last_seg);
|
||||
assert_eq!(a.len(), b.len() + usize::from(target));
|
||||
assert_eq!(a.rev_id != b.rev_id, target);
|
||||
}
|
||||
}
|
||||
|
||||
// several tracks selected: last selected one (in file order, whatever the set order)
|
||||
let ids: Vec<_> = file.trk.iter().map(|t| t.id).collect();
|
||||
fx.selection = Selection::Track {
|
||||
file_id: id,
|
||||
trk_ids: HashSet::from([ids[1], ids[0]]),
|
||||
};
|
||||
let len = |fx: &Fixture, t: usize| {
|
||||
let trk = &fx.files[&id].trk[t];
|
||||
trk.trkseg.last().unwrap().len()
|
||||
};
|
||||
let (l0, l1) = (len(&fx, 0), len(&fx, 1));
|
||||
splice(0, 0, &[1.0], &[2.0], &[3.0])
|
||||
.apply(&mut fx.state())
|
||||
.unwrap();
|
||||
assert_eq!(len(&fx, 0), l0);
|
||||
assert_eq!(len(&fx, 1), l1 + 1);
|
||||
|
||||
// several segments selected
|
||||
let trk = &fx.files[&id].trk[0];
|
||||
let seg_ids: Vec<_> = trk.trkseg.iter().map(|s| s.id).collect();
|
||||
if seg_ids.len() >= 2 {
|
||||
fx.selection = Selection::TrackSegment {
|
||||
file_id: id,
|
||||
trk_id: trk.id,
|
||||
trkseg_ids: seg_ids.iter().copied().collect(),
|
||||
};
|
||||
let lens: Vec<_> = trk.trkseg.iter().map(|s| s.len()).collect();
|
||||
splice(0, 0, &[1.0], &[2.0], &[3.0])
|
||||
.apply(&mut fx.state())
|
||||
.unwrap();
|
||||
let after: Vec<_> = fx.files[&id].trk[0]
|
||||
.trkseg
|
||||
.iter()
|
||||
.map(|s| s.len())
|
||||
.collect();
|
||||
let n = lens.len();
|
||||
assert_eq!(after[..n - 1], lens[..n - 1]);
|
||||
assert_eq!(after[n - 1], lens[n - 1] + 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_splice_on_multiple_files_uses_last_in_file_order() {
|
||||
let (mut fx, first) = loaded();
|
||||
let data = std::fs::read("data/with_tracks_and_segments.gpx").unwrap();
|
||||
Load { data: &data }.apply(&mut fx.state()).unwrap();
|
||||
let second = fx.order.0[1];
|
||||
fx.selection = Selection::File {
|
||||
file_ids: HashSet::from([second, first]),
|
||||
};
|
||||
let total = |fx: &Fixture, id: FileId| -> usize {
|
||||
fx.files[&id]
|
||||
.trk
|
||||
.iter()
|
||||
.flat_map(|t| &t.trkseg)
|
||||
.map(|s| s.len())
|
||||
.sum()
|
||||
};
|
||||
let (a, b) = (total(&fx, first), total(&fx, second));
|
||||
splice(0, 0, &[1.0], &[2.0], &[3.0])
|
||||
.apply(&mut fx.state())
|
||||
.unwrap();
|
||||
assert_eq!(total(&fx, first), a);
|
||||
assert_eq!(total(&fx, second), b + 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
use crate::{Apply, CommandError, State};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Split {
|
||||
pub at: u32,
|
||||
}
|
||||
|
||||
impl Apply for Split {
|
||||
fn apply(self, _state: &mut State) -> Result<(), CommandError> {
|
||||
// TODO
|
||||
Err(CommandError::NotImplemented("split"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
use crate::{Apply, CommandError, State};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Time;
|
||||
|
||||
impl Apply for Time {
|
||||
fn apply(self, _state: &mut State) -> Result<(), CommandError> {
|
||||
// TODO
|
||||
Err(CommandError::NotImplemented("time"))
|
||||
}
|
||||
}
|
||||
+16
-18
@@ -1,9 +1,11 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use crate::{FileId, FileWaypointsRevisionId, Files, TrackSegmentId, TrackSegmentRevisionId};
|
||||
use crate::{
|
||||
FileId, FileWaypointsRevisionId, StackEntry as 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)]
|
||||
@@ -21,16 +23,16 @@ impl CoordinatesCache {
|
||||
if self
|
||||
.waypoints
|
||||
.get(&file.id)
|
||||
.is_none_or(|(r, _)| *r != file.wpt.rev_id)
|
||||
.is_none_or(|(r, _)| *r != file.wpt_rev_id)
|
||||
{
|
||||
let mut coordinates = Vec::new();
|
||||
for wpt in file.wpt.iter() {
|
||||
for wpt in file.wpt.iter().flat_map(|chunk| &chunk.wpt) {
|
||||
coordinates.extend([wpt.coordinates.lng, wpt.coordinates.lat]);
|
||||
}
|
||||
self.waypoints
|
||||
.insert(file.id, (file.wpt.rev_id, coordinates));
|
||||
.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
|
||||
@@ -71,12 +73,7 @@ mod tests {
|
||||
fn loaded() -> (Fixture, FileId) {
|
||||
let mut fx = Fixture::default();
|
||||
let data = std::fs::read("data/with_tracks_and_segments.gpx").unwrap();
|
||||
Load {
|
||||
data: &data,
|
||||
name: "file",
|
||||
}
|
||||
.apply(&mut fx.state())
|
||||
.unwrap();
|
||||
Load { data: &data }.apply(&mut fx.state()).unwrap();
|
||||
let id = fx.order.0[0];
|
||||
(fx, id)
|
||||
}
|
||||
@@ -136,16 +133,17 @@ mod tests {
|
||||
..Default::default()
|
||||
};
|
||||
let mut file = (*fx.files[&id]).clone();
|
||||
file.wpt = crate::Waypoints::new([
|
||||
WaypointChunk {
|
||||
file.wpt_rev_id = Default::default();
|
||||
file.wpt = vec![
|
||||
Rc::new(WaypointChunk {
|
||||
wpt: vec![wpt(1.0, 2.0)],
|
||||
..Default::default()
|
||||
},
|
||||
WaypointChunk {
|
||||
}),
|
||||
Rc::new(WaypointChunk {
|
||||
wpt: vec![wpt(3.0, 4.0)],
|
||||
..Default::default()
|
||||
},
|
||||
]);
|
||||
}),
|
||||
];
|
||||
fx.files.insert(id, Rc::new(file));
|
||||
let mut cache = CoordinatesCache::default();
|
||||
cache.update(Some(&fx.files));
|
||||
+29
-82
@@ -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
|
||||
@@ -13,48 +12,16 @@ use crate::{
|
||||
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 segments: Vec<SegmentNode>,
|
||||
}
|
||||
|
||||
@@ -70,17 +37,6 @@ pub struct SegmentNode {
|
||||
pub struct WaypointNode {
|
||||
pub id: WaypointId,
|
||||
pub name: Option<String>,
|
||||
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 {
|
||||
@@ -88,41 +44,40 @@ impl FileStructure {
|
||||
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(),
|
||||
segments: trk
|
||||
.trkseg
|
||||
.iter()
|
||||
.map(|seg| SegmentNode {
|
||||
id: seg.id,
|
||||
rev_id: seg.rev_id,
|
||||
len: seg.len(),
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
.collect(),
|
||||
waypoints: file
|
||||
.wpt
|
||||
.iter()
|
||||
.flat_map(|chunk| &chunk.wpt)
|
||||
.map(|wpt| WaypointNode {
|
||||
id: wpt.id,
|
||||
name: wpt.name.clone(),
|
||||
sym: wpt.sym.clone(),
|
||||
})
|
||||
.collect(),
|
||||
wpt_rev_id: file.wpt.rev_id,
|
||||
wpt_rev_id: file.wpt_rev_id,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::rc::Rc;
|
||||
|
||||
use crate::{Apply, Load, Waypoint, WaypointChunk, engine::command::fixture::Fixture};
|
||||
|
||||
@@ -132,22 +87,13 @@ mod tests {
|
||||
fn test_structure_of_a_file() {
|
||||
let mut fx = Fixture::default();
|
||||
let data = std::fs::read("data/with_tracks_and_segments.gpx").unwrap();
|
||||
Load {
|
||||
data: &data,
|
||||
name: "file",
|
||||
}
|
||||
.apply(&mut fx.state())
|
||||
.unwrap();
|
||||
Load { data: &data }.apply(&mut fx.state()).unwrap();
|
||||
let file = &fx.files[&fx.order.0[0]];
|
||||
let node = FileStructure::new(file);
|
||||
assert_eq!(
|
||||
(node.id, &node.name, &node.desc),
|
||||
(file.id, &file.info.name, &file.info.desc)
|
||||
);
|
||||
assert_eq!((node.id, &node.name), (file.id, &file.info.name));
|
||||
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), (t.id, &t.info.name));
|
||||
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()));
|
||||
@@ -162,17 +108,18 @@ mod tests {
|
||||
name: Some(n.to_string()),
|
||||
..Default::default()
|
||||
};
|
||||
let before = file.wpt.rev_id;
|
||||
file.wpt = crate::Waypoints::new([
|
||||
WaypointChunk {
|
||||
let before = file.wpt_rev_id;
|
||||
file.wpt_rev_id = Default::default();
|
||||
file.wpt = vec![
|
||||
Rc::new(WaypointChunk {
|
||||
wpt: vec![wpt("a"), wpt("b")],
|
||||
..Default::default()
|
||||
},
|
||||
WaypointChunk {
|
||||
}),
|
||||
Rc::new(WaypointChunk {
|
||||
wpt: vec![wpt("c")],
|
||||
..Default::default()
|
||||
},
|
||||
]);
|
||||
}),
|
||||
];
|
||||
let node = FileStructure::new(&file);
|
||||
let names: Vec<_> = node
|
||||
.waypoints
|
||||
@@ -181,6 +128,6 @@ mod tests {
|
||||
.collect();
|
||||
assert_eq!(names, ["a", "b", "c"]);
|
||||
assert_ne!(node.wpt_rev_id, before);
|
||||
assert_eq!(node.wpt_rev_id, file.wpt.rev_id);
|
||||
assert_eq!(node.wpt_rev_id, file.wpt_rev_id);
|
||||
}
|
||||
}
|
||||
+3
-13
@@ -1,6 +1,6 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::{Diff, FileId, FileStructure, Files};
|
||||
use crate::{Diff, FileId, FileStructure, StackEntry as Files};
|
||||
|
||||
/// The structure of each file, only recomputed for the files that changed according to the
|
||||
/// [`Diff`] of the stack.
|
||||
@@ -41,18 +41,8 @@ mod tests {
|
||||
fn test_only_files_of_the_diff_are_recomputed() {
|
||||
let mut fx = Fixture::default();
|
||||
let data = std::fs::read("data/with_tracks_and_segments.gpx").unwrap();
|
||||
Load {
|
||||
data: &data,
|
||||
name: "file",
|
||||
}
|
||||
.apply(&mut fx.state())
|
||||
.unwrap();
|
||||
Load {
|
||||
data: &data,
|
||||
name: "file",
|
||||
}
|
||||
.apply(&mut fx.state())
|
||||
.unwrap();
|
||||
Load { data: &data }.apply(&mut fx.state()).unwrap();
|
||||
Load { data: &data }.apply(&mut fx.state()).unwrap();
|
||||
let (a, b) = (fx.order.0[0], fx.order.0[1]);
|
||||
|
||||
let mut cache = FileStructureCache::default();
|
||||
@@ -1,13 +1,11 @@
|
||||
mod coordinates_cache;
|
||||
mod file_structure;
|
||||
mod file_structure_cache;
|
||||
mod routing_buffer;
|
||||
mod statistics_buffer;
|
||||
mod statistics_cache;
|
||||
|
||||
pub use coordinates_cache::*;
|
||||
pub use file_structure::*;
|
||||
pub use file_structure_cache::*;
|
||||
pub use routing_buffer::*;
|
||||
pub use statistics_buffer::*;
|
||||
pub use statistics_cache::*;
|
||||
@@ -0,0 +1,149 @@
|
||||
use crate::{GlobalStatistics, Statistics, sum_options};
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct StatisticsBuffer {
|
||||
pub total_distance: Vec<f64>,
|
||||
pub moving_distance: Vec<f64>,
|
||||
pub total_time: Vec<i32>,
|
||||
pub moving_time: Vec<i32>,
|
||||
pub speed: Vec<f64>,
|
||||
pub elevation_gain: Vec<f64>,
|
||||
pub elevation_loss: Vec<f64>,
|
||||
pub slope: Vec<f64>,
|
||||
pub slope_segment_slope: Vec<f64>,
|
||||
pub slope_segment_distance: Vec<f64>,
|
||||
}
|
||||
|
||||
impl StatisticsBuffer {
|
||||
pub fn update(&mut self, stats: &[&Statistics]) {
|
||||
self.total_distance.clear();
|
||||
self.moving_distance.clear();
|
||||
self.total_time.clear();
|
||||
self.moving_time.clear();
|
||||
self.speed.clear();
|
||||
self.elevation_gain.clear();
|
||||
self.elevation_loss.clear();
|
||||
self.slope.clear();
|
||||
self.slope_segment_slope.clear();
|
||||
self.slope_segment_distance.clear();
|
||||
|
||||
let mut cumul_stats = GlobalStatistics::default();
|
||||
for stats in stats {
|
||||
for trkpt_stats in stats.local.iter() {
|
||||
self.total_distance
|
||||
.push(cumul_stats.total_distance + trkpt_stats.total_distance);
|
||||
self.moving_distance.push(
|
||||
sum_options(cumul_stats.moving_distance, trkpt_stats.moving_distance)
|
||||
.unwrap_or_default(),
|
||||
);
|
||||
self.total_time.push(
|
||||
sum_options(cumul_stats.total_time, trkpt_stats.total_time).unwrap_or_default(),
|
||||
);
|
||||
self.moving_time.push(
|
||||
sum_options(cumul_stats.moving_time, trkpt_stats.moving_time)
|
||||
.unwrap_or_default(),
|
||||
);
|
||||
self.speed.push(trkpt_stats.speed.unwrap_or_default());
|
||||
self.elevation_gain
|
||||
.push(cumul_stats.elevation_gain + trkpt_stats.elevation_gain);
|
||||
self.elevation_loss
|
||||
.push(cumul_stats.elevation_loss + trkpt_stats.elevation_loss);
|
||||
self.slope.push(trkpt_stats.slope);
|
||||
self.slope_segment_slope
|
||||
.push(trkpt_stats.slope_segment.slope);
|
||||
self.slope_segment_distance
|
||||
.push(trkpt_stats.slope_segment.distance);
|
||||
}
|
||||
cumul_stats.merge(&stats.global);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::parse;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn stats(path: &str) -> Statistics {
|
||||
let data = std::fs::read(path).unwrap();
|
||||
let file = parse(&data).unwrap();
|
||||
Statistics::compute(&file.trk[0].trkseg[0])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_empty() {
|
||||
let mut buffer = StatisticsBuffer::default();
|
||||
buffer.update(&[]);
|
||||
assert!(buffer.total_distance.is_empty());
|
||||
assert!(buffer.speed.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_single_segment_matches_local_stats() {
|
||||
let s = stats("data/simple.gpx");
|
||||
let mut buffer = StatisticsBuffer::default();
|
||||
buffer.update(&[&s]);
|
||||
|
||||
let n = s.local.len();
|
||||
for len in [
|
||||
buffer.total_distance.len(),
|
||||
buffer.moving_distance.len(),
|
||||
buffer.total_time.len(),
|
||||
buffer.moving_time.len(),
|
||||
buffer.speed.len(),
|
||||
buffer.elevation_gain.len(),
|
||||
buffer.elevation_loss.len(),
|
||||
buffer.slope.len(),
|
||||
buffer.slope_segment_slope.len(),
|
||||
buffer.slope_segment_distance.len(),
|
||||
] {
|
||||
assert_eq!(len, n);
|
||||
}
|
||||
for (i, local) in s.local.iter().enumerate() {
|
||||
assert_eq!(buffer.total_distance[i], local.total_distance);
|
||||
assert_eq!(buffer.slope[i], local.slope);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_distances_accumulate_over_segments() {
|
||||
let s = stats("data/simple.gpx");
|
||||
let n = s.local.len();
|
||||
let mut buffer = StatisticsBuffer::default();
|
||||
buffer.update(&[&s, &s]);
|
||||
|
||||
assert_eq!(buffer.total_distance.len(), 2 * n);
|
||||
// the second segment starts where the first one ended
|
||||
assert_eq!(buffer.total_distance[n], s.global.total_distance);
|
||||
assert!((buffer.total_distance[2 * n - 1] - 2.0 * s.global.total_distance).abs() < 1e-9);
|
||||
assert!(buffer.total_distance.windows(2).all(|w| w[0] <= w[1]));
|
||||
assert!((buffer.elevation_gain[2 * n - 1] - 2.0 * s.global.elevation_gain).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_total_time_accumulates_over_segments() {
|
||||
let s = stats("data/with_time.gpx");
|
||||
let n = s.local.len();
|
||||
let duration = s.global.total_time.unwrap();
|
||||
assert!(duration > 0);
|
||||
let mut buffer = StatisticsBuffer::default();
|
||||
buffer.update(&[&s, &s]);
|
||||
|
||||
assert_eq!(buffer.total_time[n - 1], duration);
|
||||
assert_eq!(buffer.total_time[n], duration);
|
||||
assert_eq!(buffer.total_time[2 * n - 1], 2 * duration);
|
||||
assert!(buffer.total_time.windows(2).all(|w| w[0] <= w[1]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_update_replaces_previous_content() {
|
||||
let s = stats("data/simple.gpx");
|
||||
let mut buffer = StatisticsBuffer::default();
|
||||
buffer.update(&[&s]);
|
||||
buffer.update(&[&s]);
|
||||
assert_eq!(buffer.total_distance.len(), s.local.len());
|
||||
buffer.update(&[]);
|
||||
assert!(buffer.total_distance.is_empty());
|
||||
}
|
||||
}
|
||||
+37
-111
@@ -1,12 +1,9 @@
|
||||
use std::collections::{HashMap, HashSet, hash_map::Entry};
|
||||
|
||||
use crate::{
|
||||
File, FileId, Files, GlobalStatistics, Selection, Statistics, Track, TrackSegment,
|
||||
TrackSegmentRevisionId,
|
||||
use std::{
|
||||
collections::{HashMap, HashSet, hash_map::Entry},
|
||||
rc::Rc,
|
||||
};
|
||||
|
||||
/// A segment and its statistics.
|
||||
pub type SelectedSegment<'a> = (&'a TrackSegment, &'a Statistics);
|
||||
use crate::{File, Selection, StackEntry, Statistics, Track, TrackSegment, TrackSegmentRevisionId};
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct StatisticsCache {
|
||||
@@ -14,17 +11,19 @@ pub struct StatisticsCache {
|
||||
}
|
||||
|
||||
impl StatisticsCache {
|
||||
pub fn update(&mut self, state: Option<&Files>) {
|
||||
pub fn update(&mut self, state: Option<&StackEntry>) {
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -35,48 +34,19 @@ impl StatisticsCache {
|
||||
}
|
||||
}
|
||||
|
||||
/// Statistics of the segments of the selection.
|
||||
#[cfg(test)]
|
||||
pub fn get<'a>(
|
||||
&'a self,
|
||||
state: Option<&'a Files>,
|
||||
state: Option<&StackEntry>,
|
||||
selection: &Selection,
|
||||
) -> Vec<&'a Statistics> {
|
||||
self.selected(state, selection, &[])
|
||||
.into_iter()
|
||||
.map(|(_, stats)| stats)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The segments of the selection with their statistics. The segments of several selected
|
||||
/// files follow `order` (the files missing from it come last).
|
||||
pub fn selected<'a>(
|
||||
&'a self,
|
||||
state: Option<&'a Files>,
|
||||
selection: &Selection,
|
||||
order: &[FileId],
|
||||
) -> Vec<SelectedSegment<'a>> {
|
||||
let mut selected = vec![];
|
||||
let mut stats = vec![];
|
||||
if let Some(state) = state {
|
||||
match selection {
|
||||
Selection::Empty => (),
|
||||
Selection::File { file_ids } => {
|
||||
let ordered = order
|
||||
.iter()
|
||||
.filter(|id| file_ids.contains(id))
|
||||
.chain(file_ids.iter().filter(|id| !order.contains(id)));
|
||||
for id in ordered {
|
||||
for id in file_ids.iter() {
|
||||
if let Some(file) = state.get(id) {
|
||||
self.add_file_stats(file, &mut selected);
|
||||
}
|
||||
}
|
||||
}
|
||||
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);
|
||||
}
|
||||
self.add_file_stats(file, &mut stats);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -84,7 +54,7 @@ impl StatisticsCache {
|
||||
if let Some(file) = state.get(file_id) {
|
||||
for trk in file.trk.iter() {
|
||||
if trk_ids.contains(&trk.id) {
|
||||
self.add_track_stats(trk, &mut selected);
|
||||
self.add_track_stats(trk, &mut stats);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -99,7 +69,7 @@ impl StatisticsCache {
|
||||
if *trk_id == trk.id {
|
||||
for trkseg in trk.trkseg.iter() {
|
||||
if trkseg_ids.contains(&trkseg.id) {
|
||||
self.add_segment_stats(trkseg, &mut selected);
|
||||
self.add_segment_stats(trkseg, &mut stats);
|
||||
}
|
||||
}
|
||||
break;
|
||||
@@ -109,7 +79,7 @@ impl StatisticsCache {
|
||||
}
|
||||
Selection::Waypoints { file_id } => {
|
||||
if let Some(file) = state.get(file_id) {
|
||||
self.add_file_stats(file, &mut selected);
|
||||
self.add_file_stats(file, &mut stats);
|
||||
}
|
||||
}
|
||||
Selection::Waypoint {
|
||||
@@ -117,60 +87,45 @@ impl StatisticsCache {
|
||||
wpt_ids: _,
|
||||
} => {
|
||||
if let Some(file) = state.get(file_id) {
|
||||
self.add_file_stats(file, &mut selected);
|
||||
self.add_file_stats(file, &mut stats);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
selected
|
||||
stats
|
||||
}
|
||||
|
||||
/// Global statistics of a file: its segments merged, in order.
|
||||
pub fn file_global(&self, file: &File) -> GlobalStatistics {
|
||||
let mut selected = vec![];
|
||||
self.add_file_stats(file, &mut selected);
|
||||
let mut global = GlobalStatistics::default();
|
||||
for (_, stats) in selected {
|
||||
global.merge(&stats.global);
|
||||
}
|
||||
global
|
||||
}
|
||||
|
||||
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);
|
||||
fn add_file_stats<'a>(&'a self, file: &Rc<File>, stats: &mut Vec<&'a Statistics>) {
|
||||
for trk in file.trk.iter() {
|
||||
self.add_track_stats(trk, stats);
|
||||
}
|
||||
}
|
||||
|
||||
fn add_track_stats<'a>(&'a self, trk: &'a Track, selected: &mut Vec<SelectedSegment<'a>>) {
|
||||
fn add_track_stats<'a>(&'a self, trk: &Track, stats: &mut Vec<&'a Statistics>) {
|
||||
for trkseg in trk.trkseg.iter() {
|
||||
self.add_segment_stats(trkseg, selected);
|
||||
self.add_segment_stats(trkseg, stats);
|
||||
}
|
||||
}
|
||||
|
||||
fn add_segment_stats<'a>(
|
||||
&'a self,
|
||||
trkseg: &'a TrackSegment,
|
||||
selected: &mut Vec<SelectedSegment<'a>>,
|
||||
) {
|
||||
if let Some(stats) = self.map.get(&trkseg.rev_id) {
|
||||
selected.push((trkseg, stats));
|
||||
fn add_segment_stats<'a>(&'a self, trkseg: &TrackSegment, stats: &mut Vec<&'a Statistics>) {
|
||||
if let Some(s) = self.map.get(&trkseg.rev_id) {
|
||||
stats.push(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{collections::HashSet, rc::Rc};
|
||||
use std::collections::HashSet;
|
||||
|
||||
use crate::{FileId, parse};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn state(path: &str) -> (Files, Rc<File>) {
|
||||
fn state(path: &str) -> (StackEntry, Rc<File>) {
|
||||
let data = std::fs::read(path).unwrap();
|
||||
let file = Rc::new(parse(&data, &mut Default::default()).unwrap());
|
||||
let mut state = Files::default();
|
||||
let file = Rc::new(parse(&data).unwrap());
|
||||
let mut state = StackEntry::default();
|
||||
state.insert(file.id, file.clone());
|
||||
(state, file)
|
||||
}
|
||||
@@ -243,7 +198,7 @@ mod tests {
|
||||
let before: *const Statistics = cache.get(Some(&state), &file_selection(file.id))[0];
|
||||
|
||||
// a new snapshot of the file that shares its segments (same revision ids)
|
||||
let mut next = Files::default();
|
||||
let mut next = StackEntry::default();
|
||||
let renamed = {
|
||||
let mut f = (*file).clone();
|
||||
f.info.name = "other".to_string();
|
||||
@@ -266,7 +221,7 @@ mod tests {
|
||||
let mut f = (*file).clone();
|
||||
f.trk[0].trkseg[0].rev_id = Default::default();
|
||||
let new_rev = f.trk[0].trkseg[0].rev_id;
|
||||
let mut next = Files::default();
|
||||
let mut next = StackEntry::default();
|
||||
next.insert(f.id, Rc::new(f));
|
||||
cache.update(Some(&next));
|
||||
assert!(cache.map.contains_key(&new_rev));
|
||||
@@ -275,33 +230,4 @@ mod tests {
|
||||
cache.update(None);
|
||||
assert!(cache.map.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_segments_of_several_files_follow_the_given_order() {
|
||||
let (mut state, first) = state("data/simple.gpx");
|
||||
let (other, second) = {
|
||||
let data = std::fs::read("data/with_time.gpx").unwrap();
|
||||
let file = Rc::new(parse(&data, &mut Default::default()).unwrap());
|
||||
(file.clone(), file)
|
||||
};
|
||||
state.insert(other.id, other);
|
||||
let mut cache = StatisticsCache::default();
|
||||
cache.update(Some(&state));
|
||||
let selection = Selection::File {
|
||||
file_ids: HashSet::from([first.id, second.id]),
|
||||
};
|
||||
|
||||
let ids = |order: &[FileId]| -> Vec<_> {
|
||||
cache
|
||||
.selected(Some(&state), &selection, order)
|
||||
.iter()
|
||||
.map(|(segment, _)| segment.id)
|
||||
.collect()
|
||||
};
|
||||
let (a, b) = (first.trk[0].trkseg[0].id, second.trk[0].trkseg[0].id);
|
||||
assert_eq!(ids(&[first.id, second.id]), vec![a, b]);
|
||||
assert_eq!(ids(&[second.id, first.id]), vec![b, a]);
|
||||
// the files that are not in the order come last
|
||||
assert_eq!(ids(&[second.id]), vec![b, a]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,449 @@
|
||||
// TODO license in every file
|
||||
|
||||
use crate::{
|
||||
Action, Apply, Command, CoordinatesCache, Diff, FileId, FileOrder, FileStructure,
|
||||
FileStructureCache, Selection, Stack, State, StatisticsBuffer, StatisticsCache, TrackSegmentId,
|
||||
};
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Engine {
|
||||
stack: Stack,
|
||||
selection: Selection,
|
||||
order: FileOrder,
|
||||
statistics_cache: StatisticsCache,
|
||||
coordinates_cache: CoordinatesCache,
|
||||
structure_cache: FileStructureCache,
|
||||
diff: Option<Diff>,
|
||||
order_changed: bool,
|
||||
selection_changed: bool,
|
||||
statistics_buffer: StatisticsBuffer,
|
||||
}
|
||||
|
||||
impl Engine {
|
||||
pub fn statistics(&self) -> &StatisticsBuffer {
|
||||
&self.statistics_buffer
|
||||
}
|
||||
|
||||
/// Files in display order.
|
||||
pub fn order(&self) -> &[FileId] {
|
||||
&self.order.0
|
||||
}
|
||||
|
||||
/// Name, tracks, segments and waypoints (with their ids) of a file.
|
||||
pub fn file_structure(&self, id: &FileId) -> Option<&FileStructure> {
|
||||
self.structure_cache.get(id)
|
||||
}
|
||||
|
||||
/// Which files the last action added, removed or modified.
|
||||
pub fn last_diff(&self) -> Option<&Diff> {
|
||||
self.diff.as_ref()
|
||||
}
|
||||
|
||||
/// Whether the last action changed the order of the files.
|
||||
pub fn order_changed(&self) -> bool {
|
||||
self.order_changed
|
||||
}
|
||||
|
||||
/// Currently selected elements.
|
||||
pub fn selection(&self) -> &Selection {
|
||||
&self.selection
|
||||
}
|
||||
|
||||
/// Whether the last action changed the selection.
|
||||
pub fn selection_changed(&self) -> bool {
|
||||
self.selection_changed
|
||||
}
|
||||
|
||||
/// Coordinates (`[lng, lat, ...]`) of the trackpoints of a segment.
|
||||
pub fn segment_coordinates(&self, id: &TrackSegmentId) -> &[f64] {
|
||||
self.coordinates_cache.segment(id)
|
||||
}
|
||||
|
||||
/// Coordinates (`[lng, lat, ...]`) of the waypoints of a file.
|
||||
pub fn waypoint_coordinates(&self, id: &FileId) -> &[f64] {
|
||||
self.coordinates_cache.waypoints(id)
|
||||
}
|
||||
|
||||
/// Single entry point for every action coming from the frontend. Returns whether anything
|
||||
/// changed.
|
||||
pub fn execute(&mut self, action: Action) -> bool {
|
||||
let selection_before = self.selection.clone();
|
||||
let order_before = self.order.0.clone();
|
||||
// the files change iff there is a diff, but selection and order actions have none
|
||||
self.diff = match action {
|
||||
Action::Edit(command) => self.edit(command),
|
||||
Action::Undo => self.stack.undo(),
|
||||
Action::Redo => self.stack.redo(),
|
||||
Action::Select { file_ids } => {
|
||||
self.selection = Selection::File {
|
||||
file_ids: file_ids.into_iter().collect(),
|
||||
};
|
||||
None
|
||||
}
|
||||
Action::AddSelect { file_ids } => {
|
||||
match &mut self.selection {
|
||||
Selection::File { file_ids: ids } => ids.extend(file_ids),
|
||||
selection => {
|
||||
*selection = Selection::File {
|
||||
file_ids: file_ids.into_iter().collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
Action::Reorder { file_ids, index } => {
|
||||
self.order.move_files(&file_ids, index);
|
||||
None
|
||||
}
|
||||
Action::SelectAll => {
|
||||
self.selection = Selection::File {
|
||||
file_ids: self.order.0.iter().copied().collect(),
|
||||
};
|
||||
None
|
||||
}
|
||||
};
|
||||
let changed = self.diff.is_some()
|
||||
|| self.selection != selection_before
|
||||
|| self.order.0 != order_before;
|
||||
if changed {
|
||||
self.refresh();
|
||||
}
|
||||
// after the refresh, which also syncs the order and selection with the files (undo, redo)
|
||||
self.order_changed = self.order.0 != order_before;
|
||||
self.selection_changed = self.selection != selection_before;
|
||||
changed
|
||||
}
|
||||
|
||||
fn edit(&mut self, command: Command) -> Option<Diff> {
|
||||
self.stack.create_and_push_next(|files| {
|
||||
let mut state = State {
|
||||
files,
|
||||
selection: &mut self.selection,
|
||||
order: &mut self.order,
|
||||
};
|
||||
command.apply(&mut state).map_err(|err| err.to_string())
|
||||
})
|
||||
}
|
||||
|
||||
/// Brings everything derived from the files back in line with the current stack entry.
|
||||
fn refresh(&mut self) {
|
||||
let current = self.stack.current();
|
||||
match current {
|
||||
Some(files) => {
|
||||
// files coming back after an undo/redo are added at the end of the order
|
||||
self.order.sync(files);
|
||||
self.selection.retain_existing(files);
|
||||
}
|
||||
None => {
|
||||
self.order.0.clear();
|
||||
self.selection = Selection::Empty;
|
||||
}
|
||||
}
|
||||
self.statistics_cache.update(current);
|
||||
self.coordinates_cache.update(current);
|
||||
self.structure_cache.update(current, self.diff.as_ref());
|
||||
self.statistics_buffer
|
||||
.update(&self.statistics_cache.get(current, &self.selection));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{Load, Metadata, New, NewTrack, Style};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn edit(engine: &mut Engine, command: Command) -> bool {
|
||||
engine.execute(Action::Edit(command))
|
||||
}
|
||||
|
||||
fn new(engine: &mut Engine, name: &str) -> bool {
|
||||
edit(engine, Command::New(New { name }))
|
||||
}
|
||||
|
||||
fn load(engine: &mut Engine, path: &str) -> bool {
|
||||
let data = std::fs::read(path).unwrap();
|
||||
edit(engine, Command::Load(Load { data: &data }))
|
||||
}
|
||||
|
||||
fn selected(engine: &Engine) -> Vec<FileId> {
|
||||
match &engine.selection {
|
||||
Selection::File { file_ids } => file_ids.iter().copied().collect(),
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_load_file() {
|
||||
let mut engine = Engine::default();
|
||||
assert!(load(&mut engine, "data/simple.gpx"));
|
||||
assert_eq!(engine.statistics_buffer.total_distance.len(), 80);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_new_file_has_no_statistics() {
|
||||
let mut engine = Engine::default();
|
||||
assert!(new(&mut engine, "empty"));
|
||||
assert_eq!(engine.stack.current().unwrap().len(), 1);
|
||||
assert_eq!(engine.order.0.len(), 1);
|
||||
assert!(engine.statistics().total_distance.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_statistics_follow_selection() {
|
||||
let mut engine = Engine::default();
|
||||
assert!(load(&mut engine, "data/simple.gpx"));
|
||||
let n = engine.statistics().total_distance.len();
|
||||
assert!(n > 0);
|
||||
|
||||
// a newly created (empty) file becomes the selection
|
||||
assert!(new(&mut engine, "empty"));
|
||||
assert!(engine.statistics().total_distance.is_empty());
|
||||
assert_eq!(engine.stack.current().unwrap().len(), 2);
|
||||
|
||||
// loading a file selects it again
|
||||
assert!(load(&mut engine, "data/simple.gpx"));
|
||||
assert_eq!(engine.statistics().total_distance.len(), n);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_invalid_load_is_rejected() {
|
||||
let mut engine = Engine::default();
|
||||
assert!(!edit(
|
||||
&mut engine,
|
||||
Command::Load(Load {
|
||||
data: b"<gpx><trk></gpx>"
|
||||
})
|
||||
));
|
||||
assert!(engine.stack.current().is_none());
|
||||
assert!(!engine.stack.can_undo());
|
||||
assert!(engine.order.0.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_not_implemented_command_is_rejected() {
|
||||
let mut engine = Engine::default();
|
||||
new(&mut engine, "file");
|
||||
assert!(!edit(&mut engine, Command::Reverse(crate::Reverse)));
|
||||
assert!(!engine.stack.can_redo());
|
||||
assert_eq!(engine.stack.current().unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_metadata_renames_selected_file() {
|
||||
let mut engine = Engine::default();
|
||||
new(&mut engine, "before");
|
||||
assert!(edit(
|
||||
&mut engine,
|
||||
Command::Metadata(Metadata {
|
||||
name: "after",
|
||||
desc: "about",
|
||||
})
|
||||
));
|
||||
let file = engine.stack.current().unwrap().values().next().unwrap();
|
||||
assert_eq!(file.info.name, "after");
|
||||
assert_eq!(file.info.desc.as_deref(), Some("about"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_metadata_without_selection_does_not_modify_files() {
|
||||
let mut engine = Engine::default();
|
||||
new(&mut engine, "file");
|
||||
engine.selection = Selection::Empty;
|
||||
edit(
|
||||
&mut engine,
|
||||
Command::Metadata(Metadata {
|
||||
name: "renamed",
|
||||
desc: "",
|
||||
}),
|
||||
);
|
||||
let file = engine.stack.current().unwrap().values().next().unwrap();
|
||||
assert_eq!(file.info.name, "file");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_edit_changes_statistics_when_segments_change() {
|
||||
let mut engine = Engine::default();
|
||||
load(&mut engine, "data/simple.gpx");
|
||||
let before = engine
|
||||
.statistics_cache
|
||||
.get(engine.stack.current(), &engine.selection)[0] as *const _;
|
||||
edit(&mut engine, Command::NewTrack(NewTrack));
|
||||
edit(
|
||||
&mut engine,
|
||||
Command::Style(Style {
|
||||
color: Some("ff0000"),
|
||||
opacity: None,
|
||||
width: None,
|
||||
}),
|
||||
);
|
||||
// styling does not touch the segments: their statistics are reused
|
||||
let after = engine
|
||||
.statistics_cache
|
||||
.get(engine.stack.current(), &engine.selection)[0] as *const _;
|
||||
assert!(std::ptr::eq(before, after));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_undo_redo_keep_selection_and_order_consistent() {
|
||||
let mut engine = Engine::default();
|
||||
new(&mut engine, "a");
|
||||
let a = selected(&engine)[0];
|
||||
new(&mut engine, "b");
|
||||
let b = selected(&engine)[0];
|
||||
assert_eq!(engine.order.0, vec![a, b]);
|
||||
|
||||
assert!(engine.execute(Action::Undo));
|
||||
assert_eq!(engine.order.0, vec![a]);
|
||||
assert!(selected(&engine).is_empty());
|
||||
|
||||
assert!(engine.execute(Action::Redo));
|
||||
assert_eq!(engine.order.0, vec![a, b]);
|
||||
|
||||
assert!(engine.execute(Action::Undo));
|
||||
assert!(engine.execute(Action::Undo));
|
||||
assert!(engine.order.0.is_empty());
|
||||
assert!(!engine.execute(Action::Undo));
|
||||
assert!(engine.stack.current().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_reorder_is_not_undoable_and_returning_files_go_last() {
|
||||
let mut engine = Engine::default();
|
||||
new(&mut engine, "a");
|
||||
let a = engine.order.0[0];
|
||||
new(&mut engine, "b");
|
||||
let b = engine.order.0[1];
|
||||
new(&mut engine, "c");
|
||||
let c = engine.order.0[2];
|
||||
|
||||
assert!(engine.execute(Action::Reorder {
|
||||
file_ids: vec![c],
|
||||
index: 0
|
||||
}));
|
||||
assert_eq!(engine.order.0, vec![c, a, b]);
|
||||
assert!(!engine.execute(Action::Reorder {
|
||||
file_ids: vec![c],
|
||||
index: 0
|
||||
}));
|
||||
|
||||
// undoing the creation of c does not undo the reorder
|
||||
assert!(engine.execute(Action::Undo));
|
||||
assert_eq!(engine.order.0, vec![a, b]);
|
||||
// c comes back at the end
|
||||
assert!(engine.execute(Action::Redo));
|
||||
assert_eq!(engine.order.0, vec![a, b, c]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_structures_and_coordinates_follow_actions() {
|
||||
let mut engine = Engine::default();
|
||||
assert!(engine.order().is_empty());
|
||||
load(&mut engine, "data/simple.gpx");
|
||||
let loaded_id = engine.order()[0];
|
||||
let diff = engine.last_diff().unwrap();
|
||||
assert_eq!(diff.added, vec![loaded_id]);
|
||||
assert!(engine.order_changed());
|
||||
|
||||
new(&mut engine, "empty");
|
||||
let empty_id = engine.order()[1];
|
||||
// only the new file is reported, the other one is not recomputed
|
||||
let diff = engine.last_diff().unwrap();
|
||||
assert_eq!(diff.added, vec![empty_id]);
|
||||
assert!(diff.modified.is_empty() && diff.removed.is_empty());
|
||||
assert_eq!(engine.file_structure(&empty_id).unwrap().name, "empty");
|
||||
|
||||
let structure = engine.file_structure(&loaded_id).unwrap();
|
||||
let seg = &structure.tracks[0].segments[0];
|
||||
let (seg_id, len) = (seg.id, seg.len);
|
||||
assert_eq!(engine.segment_coordinates(&seg_id).len(), len * 2);
|
||||
assert!(engine.waypoint_coordinates(&loaded_id).is_empty());
|
||||
|
||||
// reordering only changes the order
|
||||
assert!(engine.execute(Action::Reorder {
|
||||
file_ids: vec![loaded_id],
|
||||
index: 1
|
||||
}));
|
||||
assert_eq!(engine.order(), [empty_id, loaded_id]);
|
||||
assert!(engine.last_diff().is_none());
|
||||
assert!(engine.order_changed());
|
||||
|
||||
// an action that changes nothing reports nothing
|
||||
assert!(!engine.execute(Action::Reorder {
|
||||
file_ids: vec![loaded_id],
|
||||
index: 1
|
||||
}));
|
||||
assert!(engine.last_diff().is_none());
|
||||
assert!(!engine.order_changed());
|
||||
|
||||
// undo removes the empty file, redoing the load removes the other one too
|
||||
assert!(engine.execute(Action::Undo));
|
||||
let diff = engine.last_diff().unwrap();
|
||||
assert_eq!(diff.removed, vec![empty_id]);
|
||||
assert!(engine.order_changed());
|
||||
assert!(engine.file_structure(&empty_id).is_none());
|
||||
assert!(engine.execute(Action::Undo));
|
||||
assert!(engine.order().is_empty());
|
||||
assert!(engine.file_structure(&loaded_id).is_none());
|
||||
assert!(engine.segment_coordinates(&seg_id).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_selection_changed_flag() {
|
||||
let mut engine = Engine::default();
|
||||
new(&mut engine, "a");
|
||||
let a = engine.order()[0];
|
||||
// a new file is selected by the edit
|
||||
assert!(engine.selection_changed());
|
||||
assert!(!engine.execute(Action::Select { file_ids: vec![a] }));
|
||||
assert!(!engine.selection_changed());
|
||||
assert!(engine.execute(Action::Select { file_ids: vec![] }));
|
||||
assert!(engine.selection_changed());
|
||||
// undoing drops the selected file from the selection
|
||||
engine.execute(Action::Select { file_ids: vec![a] });
|
||||
assert!(engine.execute(Action::Undo));
|
||||
assert!(engine.selection_changed());
|
||||
assert_eq!(engine.selection(), &Selection::Empty);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_undo_updates_statistics() {
|
||||
let mut engine = Engine::default();
|
||||
load(&mut engine, "data/simple.gpx");
|
||||
assert!(!engine.statistics().total_distance.is_empty());
|
||||
engine.execute(Action::Undo);
|
||||
assert!(engine.statistics().total_distance.is_empty());
|
||||
engine.execute(Action::Redo);
|
||||
engine.execute(Action::SelectAll);
|
||||
assert_eq!(engine.statistics().total_distance.len(), 80);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_selection_actions() {
|
||||
let mut engine = Engine::default();
|
||||
new(&mut engine, "a");
|
||||
let a = selected(&engine)[0];
|
||||
new(&mut engine, "b");
|
||||
let b = selected(&engine)[0];
|
||||
assert_eq!(selected(&engine), vec![b]);
|
||||
|
||||
assert!(engine.execute(Action::Select { file_ids: vec![a] }));
|
||||
assert_eq!(selected(&engine), vec![a]);
|
||||
|
||||
assert!(engine.execute(Action::AddSelect { file_ids: vec![b] }));
|
||||
assert_eq!(selected(&engine).len(), 2);
|
||||
|
||||
engine.execute(Action::Select { file_ids: vec![] });
|
||||
assert!(engine.execute(Action::SelectAll));
|
||||
assert_eq!(selected(&engine).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_selection_does_not_create_undo_steps() {
|
||||
let mut engine = Engine::default();
|
||||
new(&mut engine, "a");
|
||||
engine.execute(Action::SelectAll);
|
||||
engine.execute(Action::Undo);
|
||||
assert!(engine.stack.current().is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
mod action;
|
||||
mod command;
|
||||
mod derived;
|
||||
mod engine;
|
||||
mod state;
|
||||
|
||||
pub use action::*;
|
||||
pub use command::*;
|
||||
pub use derived::*;
|
||||
pub use engine::*;
|
||||
pub use state::*;
|
||||
@@ -0,0 +1,13 @@
|
||||
mod order;
|
||||
mod selection;
|
||||
mod stack;
|
||||
|
||||
pub use order::*;
|
||||
pub use selection::*;
|
||||
pub use stack::*;
|
||||
|
||||
pub struct State<'a> {
|
||||
pub files: &'a mut StackEntry,
|
||||
pub selection: &'a mut Selection,
|
||||
pub order: &'a mut FileOrder,
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use crate::{FileId, Files};
|
||||
use crate::{FileId, StackEntry as Files};
|
||||
|
||||
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
||||
pub struct FileOrder(pub Vec<FileId>);
|
||||
@@ -0,0 +1,89 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use crate::{FileId, StackEntry, TrackId, TrackSegmentId, WaypointId};
|
||||
|
||||
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
||||
pub enum Selection {
|
||||
#[default]
|
||||
Empty,
|
||||
File {
|
||||
file_ids: HashSet<FileId>,
|
||||
},
|
||||
Track {
|
||||
file_id: FileId,
|
||||
trk_ids: HashSet<TrackId>,
|
||||
},
|
||||
TrackSegment {
|
||||
file_id: FileId,
|
||||
trk_id: TrackId,
|
||||
trkseg_ids: HashSet<TrackSegmentId>,
|
||||
},
|
||||
Waypoints {
|
||||
file_id: FileId,
|
||||
},
|
||||
Waypoint {
|
||||
file_id: FileId,
|
||||
wpt_ids: HashSet<WaypointId>,
|
||||
},
|
||||
}
|
||||
|
||||
impl Selection {
|
||||
/// Drops the files that do not exist anymore (e.g. after an undo).
|
||||
pub fn retain_existing(&mut self, files: &StackEntry) {
|
||||
match self {
|
||||
Selection::Empty => {}
|
||||
Selection::File { file_ids } => {
|
||||
file_ids.retain(|id| files.contains_key(id));
|
||||
if file_ids.is_empty() {
|
||||
*self = Selection::Empty;
|
||||
}
|
||||
}
|
||||
Selection::Track { file_id, .. }
|
||||
| Selection::TrackSegment { file_id, .. }
|
||||
| Selection::Waypoints { file_id }
|
||||
| Selection::Waypoint { file_id, .. } => {
|
||||
if !files.contains_key(file_id) {
|
||||
*self = Selection::Empty;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::rc::Rc;
|
||||
|
||||
use crate::File;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_retain_existing() {
|
||||
let file = File::default();
|
||||
let (kept, gone) = (file.id, FileId::default());
|
||||
let mut files = StackEntry::default();
|
||||
files.insert(kept, Rc::new(file));
|
||||
|
||||
let mut selection = Selection::File {
|
||||
file_ids: [kept, gone].into(),
|
||||
};
|
||||
selection.retain_existing(&files);
|
||||
assert!(
|
||||
matches!(&selection, Selection::File { file_ids } if file_ids.len() == 1 && file_ids.contains(&kept))
|
||||
);
|
||||
|
||||
let mut selection = Selection::File {
|
||||
file_ids: [gone].into(),
|
||||
};
|
||||
selection.retain_existing(&files);
|
||||
assert!(matches!(selection, Selection::Empty));
|
||||
|
||||
let mut selection = Selection::Waypoints { file_id: kept };
|
||||
selection.retain_existing(&files);
|
||||
assert!(matches!(selection, Selection::Waypoints { .. }));
|
||||
let mut selection = Selection::Waypoints { file_id: gone };
|
||||
selection.retain_existing(&files);
|
||||
assert!(matches!(selection, Selection::Empty));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
use std::{
|
||||
collections::{HashMap, HashSet},
|
||||
rc::Rc,
|
||||
};
|
||||
|
||||
use crate::{File, FileId};
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Stack {
|
||||
entries: Vec<StackEntry>,
|
||||
index: Option<usize>,
|
||||
}
|
||||
|
||||
impl Stack {
|
||||
pub fn current(&self) -> Option<&StackEntry> {
|
||||
self.index.map_or_default(|i| self.get(i))
|
||||
}
|
||||
|
||||
pub fn create_and_push_next<F>(&mut self, f: F) -> Option<Diff>
|
||||
where
|
||||
F: FnOnce(&mut StackEntry) -> Result<(), String>,
|
||||
{
|
||||
self.record_diff(|stack| {
|
||||
let mut next = stack.current().map_or_default(|c| c.clone());
|
||||
if f(&mut next).is_ok() {
|
||||
stack.push(next);
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn undo(&mut self) -> Option<Diff> {
|
||||
self.record_diff(|stack| {
|
||||
if let Some(i) = stack.index {
|
||||
if i == 0 {
|
||||
stack.index = None;
|
||||
} else {
|
||||
stack.index = Some(i - 1);
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn redo(&mut self) -> Option<Diff> {
|
||||
self.record_diff(|stack| match stack.index {
|
||||
Some(i) => {
|
||||
if i + 1 < stack.entries.len() {
|
||||
stack.index = Some(i + 1);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if !stack.entries.is_empty() {
|
||||
stack.index = Some(0);
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn can_undo(&self) -> bool {
|
||||
self.index.is_some()
|
||||
}
|
||||
|
||||
pub fn can_redo(&self) -> bool {
|
||||
match self.index {
|
||||
Some(i) => i + 1 < self.entries.len(),
|
||||
None => !self.entries.is_empty(),
|
||||
}
|
||||
}
|
||||
|
||||
fn get(&self, index: usize) -> Option<&StackEntry> {
|
||||
self.entries.get(index)
|
||||
}
|
||||
|
||||
fn push(&mut self, entry: StackEntry) {
|
||||
if let Some(i) = self.index {
|
||||
self.entries.truncate(i + 1);
|
||||
}
|
||||
|
||||
self.entries.push(entry);
|
||||
self.index = Some(self.entries.len() - 1);
|
||||
}
|
||||
|
||||
fn record_diff<F>(&mut self, f: F) -> Option<Diff>
|
||||
where
|
||||
F: FnOnce(&mut Self),
|
||||
{
|
||||
let prev = self.index;
|
||||
f(self);
|
||||
let cur = self.index;
|
||||
if prev == cur {
|
||||
return None;
|
||||
}
|
||||
let prev = prev.map_or_default(|i| self.get(i));
|
||||
let cur = cur.map_or_default(|i| self.get(i));
|
||||
let prev_ids: HashSet<FileId> = prev.map_or_default(|e| e.keys().copied().collect());
|
||||
let cur_ids: HashSet<FileId> = cur.map_or_default(|e| e.keys().copied().collect());
|
||||
let mut modified = vec![];
|
||||
for id in prev_ids.intersection(&cur_ids) {
|
||||
let before = prev.map_or_default(|e| e.get(id));
|
||||
let after = cur.map_or_default(|e| e.get(id));
|
||||
if !before.zip(after).is_some_and(|(b, a)| Rc::ptr_eq(b, a)) && before != after {
|
||||
modified.push(*id);
|
||||
}
|
||||
}
|
||||
Some(Diff {
|
||||
added: cur_ids.difference(&prev_ids).copied().collect(),
|
||||
removed: prev_ids.difference(&cur_ids).copied().collect(),
|
||||
modified,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub type StackEntry = HashMap<FileId, Rc<File>>;
|
||||
|
||||
/// Which files were added, removed or modified by a change of the current stack entry.
|
||||
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
||||
pub struct Diff {
|
||||
pub added: Vec<FileId>,
|
||||
pub removed: Vec<FileId>,
|
||||
pub modified: Vec<FileId>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_new_file() {
|
||||
let mut stack = Stack::default();
|
||||
|
||||
assert!(!stack.can_undo());
|
||||
assert!(!stack.can_redo());
|
||||
assert!(stack.current().is_none());
|
||||
|
||||
let diff = stack.create_and_push_next(|e| {
|
||||
let file = Rc::new(File::default());
|
||||
e.insert(file.id, file);
|
||||
Ok(())
|
||||
});
|
||||
|
||||
assert!(stack.can_undo());
|
||||
assert!(!stack.can_redo());
|
||||
assert!(stack.current().is_some());
|
||||
|
||||
assert!(diff.is_some());
|
||||
|
||||
let diff = diff.unwrap();
|
||||
assert_eq!(diff.added.len(), 1);
|
||||
assert!(diff.removed.is_empty());
|
||||
assert!(diff.modified.is_empty());
|
||||
}
|
||||
|
||||
fn add_file(stack: &mut Stack) -> FileId {
|
||||
let file = Rc::new(File::default());
|
||||
let id = file.id;
|
||||
stack
|
||||
.create_and_push_next(|e| {
|
||||
e.insert(id, file);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_failed_command_pushes_nothing() {
|
||||
let mut stack = Stack::default();
|
||||
let diff = stack.create_and_push_next(|e| {
|
||||
e.insert(FileId::default(), Rc::new(File::default()));
|
||||
Err("nope".to_string())
|
||||
});
|
||||
assert!(diff.is_none());
|
||||
assert!(!stack.can_undo());
|
||||
assert!(stack.current().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_undo_redo() {
|
||||
let mut stack = Stack::default();
|
||||
assert!(stack.undo().is_none());
|
||||
assert!(stack.redo().is_none());
|
||||
|
||||
let id = add_file(&mut stack);
|
||||
|
||||
let diff = stack.undo().unwrap();
|
||||
assert_eq!(diff.removed, vec![id]);
|
||||
assert!(diff.added.is_empty());
|
||||
assert!(stack.current().is_none());
|
||||
assert!(!stack.can_undo());
|
||||
assert!(stack.can_redo());
|
||||
assert!(stack.undo().is_none());
|
||||
|
||||
let diff = stack.redo().unwrap();
|
||||
assert_eq!(diff.added, vec![id]);
|
||||
assert!(stack.current().unwrap().contains_key(&id));
|
||||
assert!(stack.can_undo());
|
||||
assert!(!stack.can_redo());
|
||||
assert!(stack.redo().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_modified_and_removed() {
|
||||
let mut stack = Stack::default();
|
||||
let id = add_file(&mut stack);
|
||||
|
||||
let diff = stack
|
||||
.create_and_push_next(|e| {
|
||||
let mut file = (**e.get(&id).unwrap()).clone();
|
||||
file.info.name = "renamed".to_string();
|
||||
e.insert(id, Rc::new(file));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(diff.modified, vec![id]);
|
||||
assert!(diff.added.is_empty() && diff.removed.is_empty());
|
||||
|
||||
// an unchanged file is not reported as modified
|
||||
let diff = stack.create_and_push_next(|_| Ok(())).unwrap();
|
||||
assert!(diff.modified.is_empty());
|
||||
|
||||
let diff = stack
|
||||
.create_and_push_next(|e| {
|
||||
e.remove(&id);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(diff.removed, vec![id]);
|
||||
assert!(stack.current().unwrap().is_empty());
|
||||
|
||||
// going back restores the renamed file
|
||||
stack.undo();
|
||||
assert_eq!(stack.current().unwrap()[&id].info.name, "renamed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_push_after_undo_drops_redo_branch() {
|
||||
let mut stack = Stack::default();
|
||||
let first = add_file(&mut stack);
|
||||
let second = add_file(&mut stack);
|
||||
|
||||
stack.undo();
|
||||
assert!(stack.can_redo());
|
||||
assert!(!stack.current().unwrap().contains_key(&second));
|
||||
|
||||
let third = add_file(&mut stack);
|
||||
assert!(!stack.can_redo());
|
||||
assert!(stack.redo().is_none());
|
||||
let current = stack.current().unwrap();
|
||||
assert!(current.contains_key(&first));
|
||||
assert!(current.contains_key(&third));
|
||||
assert!(!current.contains_key(&second));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
mod core;
|
||||
mod engine;
|
||||
|
||||
pub use core::*;
|
||||
pub use engine::*;
|
||||
@@ -1,672 +0,0 @@
|
||||
//! The functions that edit the files or change the selection.
|
||||
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::dto::*;
|
||||
use crate::{self as engine, Action, Command, Engine, History, LngLat, LngLatBounds};
|
||||
|
||||
/// Executes an action and tells what it did.
|
||||
pub fn execute<H: History>(engine: &mut Engine<H>, action: Action) -> Outcome {
|
||||
match engine.execute(action) {
|
||||
Ok(outcome) => Outcome::new(&outcome, None),
|
||||
Err(error) => Outcome::failed(error.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn edit<H: History>(engine: &mut Engine<H>, command: Command) -> Outcome {
|
||||
execute(engine, Action::Edit(command))
|
||||
}
|
||||
|
||||
fn file_ids(ids: &[Uuid]) -> Vec<engine::FileId> {
|
||||
ids.iter().copied().map(engine::FileId).collect()
|
||||
}
|
||||
|
||||
// Selection
|
||||
|
||||
/// Selects files. Unknown files are ignored, and selecting nothing deselects everything.
|
||||
pub fn select<H: History>(
|
||||
engine: &mut Engine<H>,
|
||||
file_ids_: &[Uuid],
|
||||
mode: engine::SelectMode,
|
||||
) -> Outcome {
|
||||
select_elements(
|
||||
engine,
|
||||
engine::Selection::File {
|
||||
file_ids: file_ids(file_ids_).into_iter().collect(),
|
||||
},
|
||||
mode,
|
||||
)
|
||||
}
|
||||
|
||||
/// Selects elements: they are merged 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.
|
||||
pub fn select_elements<H: History>(
|
||||
engine: &mut Engine<H>,
|
||||
selection: engine::Selection,
|
||||
mode: engine::SelectMode,
|
||||
) -> Outcome {
|
||||
execute(engine, Action::Select { selection, mode })
|
||||
}
|
||||
|
||||
/// 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 when nothing is selected.
|
||||
pub fn select_all<H: History>(engine: &mut Engine<H>) -> Outcome {
|
||||
execute(engine, Action::SelectAll)
|
||||
}
|
||||
|
||||
/// Moves the selection to the next (`down`) or previous element of the same kind, like the arrow
|
||||
/// keys do in the file list. With `add` (shift + arrow), the element is added to the selection,
|
||||
/// otherwise it replaces it.
|
||||
pub fn arrow_select<H: History>(engine: &mut Engine<H>, down: bool, add: bool) -> Outcome {
|
||||
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,
|
||||
track_ids: &[Uuid],
|
||||
mode: engine::SelectMode,
|
||||
) -> Outcome {
|
||||
let selection = engine::Selection::Track {
|
||||
file_id: engine::FileId(file_id),
|
||||
trk_ids: track_ids.iter().copied().map(engine::TrackId).collect(),
|
||||
};
|
||||
select_elements(engine, selection, mode)
|
||||
}
|
||||
|
||||
pub fn select_segments<H: History>(
|
||||
engine: &mut Engine<H>,
|
||||
file_id: Uuid,
|
||||
track_id: Uuid,
|
||||
segment_ids: &[Uuid],
|
||||
mode: engine::SelectMode,
|
||||
) -> Outcome {
|
||||
let selection = engine::Selection::TrackSegment {
|
||||
file_id: engine::FileId(file_id),
|
||||
trk_id: engine::TrackId(track_id),
|
||||
trkseg_ids: segment_ids
|
||||
.iter()
|
||||
.copied()
|
||||
.map(engine::TrackSegmentId)
|
||||
.collect(),
|
||||
};
|
||||
select_elements(engine, selection, mode)
|
||||
}
|
||||
|
||||
/// Selects the node standing for all the waypoints of a file.
|
||||
pub fn select_waypoint_group<H: History>(
|
||||
engine: &mut Engine<H>,
|
||||
file_id: Uuid,
|
||||
mode: engine::SelectMode,
|
||||
) -> Outcome {
|
||||
let selection = engine::Selection::Waypoints {
|
||||
file_id: engine::FileId(file_id),
|
||||
};
|
||||
select_elements(engine, selection, mode)
|
||||
}
|
||||
|
||||
pub fn select_waypoints<H: History>(
|
||||
engine: &mut Engine<H>,
|
||||
file_id: Uuid,
|
||||
waypoint_ids: &[Uuid],
|
||||
mode: engine::SelectMode,
|
||||
) -> Outcome {
|
||||
let selection = engine::Selection::Waypoint {
|
||||
file_id: engine::FileId(file_id),
|
||||
wpt_ids: waypoint_ids
|
||||
.iter()
|
||||
.copied()
|
||||
.map(engine::WaypointId)
|
||||
.collect(),
|
||||
};
|
||||
select_elements(engine, selection, mode)
|
||||
}
|
||||
|
||||
// History
|
||||
|
||||
pub fn undo<H: History>(engine: &mut Engine<H>) -> Outcome {
|
||||
execute(engine, Action::Undo)
|
||||
}
|
||||
|
||||
pub fn redo<H: History>(engine: &mut Engine<H>) -> Outcome {
|
||||
execute(engine, Action::Redo)
|
||||
}
|
||||
|
||||
// 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.
|
||||
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,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// Loads files as a single command (one undo step). The files are in `data`, one after the other,
|
||||
/// `lengths` being the number of bytes of each one. `names`: the name of each file when its data
|
||||
/// has none (the name on disk, without extension). The files that cannot be read are skipped, the
|
||||
/// first one that was read is selected.
|
||||
pub fn load_files<H: History>(
|
||||
engine: &mut Engine<H>,
|
||||
data: &[u8],
|
||||
lengths: &[usize],
|
||||
names: &[String],
|
||||
) -> Outcome {
|
||||
if lengths.len() != names.len() {
|
||||
return Outcome::failed(format!(
|
||||
"{} lengths for {} names",
|
||||
lengths.len(),
|
||||
names.len()
|
||||
));
|
||||
}
|
||||
let mut files = Vec::with_capacity(names.len());
|
||||
let mut offset = 0;
|
||||
for (length, name) in lengths.iter().zip(names) {
|
||||
let end = offset + *length;
|
||||
let Some(data) = data.get(offset..end) else {
|
||||
return Outcome::failed(format!("the data of {name} is shorter than its length"));
|
||||
};
|
||||
files.push(engine::Load { data, name });
|
||||
offset = end;
|
||||
}
|
||||
edit(engine, Command::LoadFiles(engine::LoadFiles { files }))
|
||||
}
|
||||
|
||||
/// 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.
|
||||
pub fn sync_files<H: History>(
|
||||
engine: &mut Engine<H>,
|
||||
files: &[(Uuid, &[u8], &str)],
|
||||
remove: &[Uuid],
|
||||
) -> Outcome {
|
||||
let files = files
|
||||
.iter()
|
||||
.map(|(id, data, name)| engine::ExternalFile {
|
||||
id: engine::FileId(*id),
|
||||
data,
|
||||
name,
|
||||
})
|
||||
.collect();
|
||||
edit(
|
||||
engine,
|
||||
Command::SyncFiles(engine::SyncFiles {
|
||||
files,
|
||||
remove: file_ids(remove),
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn duplicate<H: History>(engine: &mut Engine<H>) -> Outcome {
|
||||
edit(engine, Command::Duplicate(engine::Duplicate))
|
||||
}
|
||||
|
||||
/// Deletes the selected elements. With `whole_files`, the files holding the selected elements are
|
||||
/// deleted instead, even if only a track or a waypoint is selected.
|
||||
pub fn delete<H: History>(engine: &mut Engine<H>, whole_files: bool) -> Outcome {
|
||||
edit(engine, Command::Delete(engine::Delete { whole_files }))
|
||||
}
|
||||
|
||||
pub fn delete_all<H: History>(engine: &mut Engine<H>) -> Outcome {
|
||||
edit(engine, Command::DeleteAll(engine::DeleteAll))
|
||||
}
|
||||
|
||||
/// Moves the files to `index` among the other files, in the given order (not undoable).
|
||||
pub fn reorder<H: History>(engine: &mut Engine<H>, file_ids_: &[Uuid], index: usize) -> Outcome {
|
||||
execute(
|
||||
engine,
|
||||
Action::Reorder {
|
||||
file_ids: file_ids(file_ids_),
|
||||
index,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// 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)
|
||||
}
|
||||
|
||||
/// Like `copy`, but the elements are moved when they are pasted.
|
||||
pub fn cut<H: History>(engine: &mut Engine<H>) -> Outcome {
|
||||
execute(engine, Action::Cut)
|
||||
}
|
||||
|
||||
/// Pastes the clipboard according to the selection (see `can_paste`). What is pasted is always the
|
||||
/// elements as they were when they were copied or cut, even if they were changed or deleted since.
|
||||
/// It can be pasted several times: what was copied is copied again, what was cut is moved the first
|
||||
/// time (and the clipboard is not cut after that), then it is copied.
|
||||
pub fn paste<H: History>(engine: &mut Engine<H>) -> Outcome {
|
||||
edit(engine, Command::Paste(engine::Paste))
|
||||
}
|
||||
|
||||
/// Moves elements to a place of the file tree, keeping their ids, like dragging and dropping them
|
||||
/// does. The moved elements are selected.
|
||||
///
|
||||
/// Files can only go among the files; tracks among the files (each becomes a file) or the tracks
|
||||
/// of a file; segments among the files (each becomes a file), the tracks of a file (each becomes
|
||||
/// a track) or the segments of a track; waypoints, or all the waypoints of a file, among the
|
||||
/// waypoints of a file.
|
||||
pub fn move_elements<H: History>(
|
||||
engine: &mut Engine<H>,
|
||||
what: Selection,
|
||||
to: MoveTarget,
|
||||
) -> Outcome {
|
||||
edit(
|
||||
engine,
|
||||
Command::Move(engine::Move {
|
||||
what: what.into(),
|
||||
to: to.into(),
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn metadata<H: History>(engine: &mut Engine<H>, name: &str, desc: &str) -> Outcome {
|
||||
edit(engine, Command::Metadata(engine::Metadata { name, desc }))
|
||||
}
|
||||
|
||||
/// Only the given fields are changed.
|
||||
pub fn style<H: History>(
|
||||
engine: &mut Engine<H>,
|
||||
color: Option<&str>,
|
||||
opacity: Option<f64>,
|
||||
width: Option<f64>,
|
||||
) -> Outcome {
|
||||
edit(
|
||||
engine,
|
||||
Command::Style(engine::Style {
|
||||
color,
|
||||
opacity,
|
||||
width,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// 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))
|
||||
}
|
||||
|
||||
pub fn new_track_segment<H: History>(engine: &mut Engine<H>) -> Outcome {
|
||||
edit(engine, Command::NewTrackSegment(engine::NewTrackSegment))
|
||||
}
|
||||
|
||||
// Waypoints. The strings that are empty are the fields that the waypoint does not have.
|
||||
|
||||
/// Adds a waypoint to each selected file (or to the file of the selected elements).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn new_waypoint<H: History>(
|
||||
engine: &mut Engine<H>,
|
||||
lng: f64,
|
||||
lat: f64,
|
||||
ele: f64,
|
||||
name: &str,
|
||||
desc: &str,
|
||||
icon: &str,
|
||||
link: &str,
|
||||
) -> Outcome {
|
||||
edit(
|
||||
engine,
|
||||
Command::NewWaypoint(engine::NewWaypoint {
|
||||
lng,
|
||||
lat,
|
||||
ele,
|
||||
name,
|
||||
desc,
|
||||
icon,
|
||||
link,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// Moves a waypoint of a file, whatever is selected.
|
||||
pub fn move_waypoint<H: History>(
|
||||
engine: &mut Engine<H>,
|
||||
file_id: Uuid,
|
||||
waypoint_id: Uuid,
|
||||
lng: f64,
|
||||
lat: f64,
|
||||
ele: f64,
|
||||
) -> Outcome {
|
||||
edit(
|
||||
engine,
|
||||
Command::MoveWaypoint(engine::MoveWaypoint {
|
||||
file_id: engine::FileId(file_id),
|
||||
waypoint_id: engine::WaypointId(waypoint_id),
|
||||
lng,
|
||||
lat,
|
||||
ele,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// Deletes a waypoint of a file, whatever is selected.
|
||||
pub fn delete_waypoint<H: History>(
|
||||
engine: &mut Engine<H>,
|
||||
file_id: Uuid,
|
||||
waypoint_id: Uuid,
|
||||
) -> Outcome {
|
||||
edit(
|
||||
engine,
|
||||
Command::DeleteWaypoint(engine::DeleteWaypoint {
|
||||
file_id: engine::FileId(file_id),
|
||||
waypoint_id: engine::WaypointId(waypoint_id),
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// Changes a waypoint of a file, whatever is selected: its name, description, icon, link,
|
||||
/// position and elevation.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn update_waypoint<H: History>(
|
||||
engine: &mut Engine<H>,
|
||||
file_id: Uuid,
|
||||
waypoint_id: Uuid,
|
||||
lng: f64,
|
||||
lat: f64,
|
||||
ele: f64,
|
||||
name: &str,
|
||||
desc: &str,
|
||||
icon: &str,
|
||||
link: &str,
|
||||
) -> Outcome {
|
||||
edit(
|
||||
engine,
|
||||
Command::EditWaypoint(engine::EditWaypoint {
|
||||
file_id: engine::FileId(file_id),
|
||||
waypoint_id: engine::WaypointId(waypoint_id),
|
||||
lng,
|
||||
lat,
|
||||
ele,
|
||||
name,
|
||||
desc,
|
||||
icon,
|
||||
link,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
// Tools
|
||||
|
||||
pub fn reverse<H: History>(engine: &mut Engine<H>) -> Outcome {
|
||||
edit(engine, Command::Reverse(engine::Reverse))
|
||||
}
|
||||
|
||||
/// Adds to each selected segment a reversed copy of itself (without repeating its last point), so
|
||||
/// that it goes back to where it started.
|
||||
pub fn round_trip<H: History>(engine: &mut Engine<H>) -> Outcome {
|
||||
edit(engine, Command::RoundTrip(engine::RoundTrip))
|
||||
}
|
||||
|
||||
/// Keeps the trackpoints `start` to `end` (both included) of the selection, counted over its
|
||||
/// segments one after the other, and removes the others (and what is left empty).
|
||||
pub fn crop<H: History>(engine: &mut Engine<H>, start: u32, end: u32) -> Outcome {
|
||||
if start > end {
|
||||
return Outcome::failed(format!("the range {start}..{end} is reversed"));
|
||||
}
|
||||
edit(engine, Command::Crop(engine::Crop { start, end }))
|
||||
}
|
||||
|
||||
/// Removes the trackpoints of the selection that are less than `tolerance` meters away from the
|
||||
/// line of their neighbours, except the ends of the segments.
|
||||
pub fn reduce<H: History>(engine: &mut Engine<H>, tolerance: f64) -> Outcome {
|
||||
edit(engine, Command::Reduce(engine::Reduce { tolerance }))
|
||||
}
|
||||
|
||||
/// Sets the timestamps of the selection, which starts at `start_time` (ms since the epoch): the
|
||||
/// trackpoints that have some keep their durations multiplied by `ratio`, the others follow the
|
||||
/// previous one at `speed` (km/h).
|
||||
pub fn change_timestamps<H: History>(
|
||||
engine: &mut Engine<H>,
|
||||
start_time: f64,
|
||||
speed: f64,
|
||||
ratio: f64,
|
||||
) -> Outcome {
|
||||
edit(
|
||||
engine,
|
||||
Command::Time(engine::Time {
|
||||
start_time: start_time as i64,
|
||||
kind: engine::TimeKind::Change { speed, ratio },
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// Makes up timestamps for the selection, which starts at `start_time` (ms since the epoch) and
|
||||
/// lasts `total_time` seconds.
|
||||
pub fn create_artificial_timestamps<H: History>(
|
||||
engine: &mut Engine<H>,
|
||||
start_time: f64,
|
||||
total_time: f64,
|
||||
) -> Outcome {
|
||||
edit(
|
||||
engine,
|
||||
Command::Time(engine::Time {
|
||||
start_time: start_time as i64,
|
||||
kind: engine::TimeKind::Artificial { total_time },
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// Merges the selection into its first element. `remove_gaps` brings the parts that are connected
|
||||
/// closer in time, if they have timestamps. Merged files are kept (and the result is a new file) if
|
||||
/// the history needs it, see [`History::KEEPS_ORIGINALS`].
|
||||
pub fn merge<H: History>(
|
||||
engine: &mut Engine<H>,
|
||||
type_: engine::MergeType,
|
||||
remove_gaps: bool,
|
||||
) -> Outcome {
|
||||
edit(
|
||||
engine,
|
||||
Command::Merge(engine::Merge {
|
||||
type_,
|
||||
remove_gaps,
|
||||
keep_originals: H::KEEPS_ORIGINALS,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// Extracted files are kept (and the result is new files) if the history needs it, see
|
||||
/// [`History::KEEPS_ORIGINALS`].
|
||||
pub fn extract<H: History>(engine: &mut Engine<H>) -> Outcome {
|
||||
edit(
|
||||
engine,
|
||||
Command::Extract(engine::Extract {
|
||||
keep_originals: H::KEEPS_ORIGINALS,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// Sets the elevation of the trackpoints of the selection, one elevation per trackpoint.
|
||||
pub fn elevation<H: History>(engine: &mut Engine<H>, ele: &[f64]) -> Outcome {
|
||||
edit(engine, Command::Elevation(engine::Elevation { ele }))
|
||||
}
|
||||
|
||||
/// Removes the trackpoints and/or waypoints of the selection inside (or outside) a rectangle.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn clean<H: History>(
|
||||
engine: &mut Engine<H>,
|
||||
west: f64,
|
||||
south: f64,
|
||||
east: f64,
|
||||
north: f64,
|
||||
type_: engine::CleanType,
|
||||
trkpt: bool,
|
||||
wpt: bool,
|
||||
) -> Outcome {
|
||||
edit(
|
||||
engine,
|
||||
Command::Clean(engine::Clean {
|
||||
bounds: LngLatBounds {
|
||||
sw: LngLat {
|
||||
lng: west,
|
||||
lat: south,
|
||||
},
|
||||
ne: LngLat {
|
||||
lng: east,
|
||||
lat: north,
|
||||
},
|
||||
},
|
||||
type_,
|
||||
trkpt,
|
||||
wpt,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
// Routing
|
||||
//
|
||||
// The indices of the trackpoints and of the anchors are the ones of the routing buffers: they only
|
||||
// mean something for the `revision` they were read with (`routing_revision`), and the commands
|
||||
// that use them do nothing if the selection is not the one of that revision anymore.
|
||||
|
||||
/// Makes the call `f`, unless the selection is not the one of the revision anymore.
|
||||
fn at_revision<H: History>(
|
||||
engine: &mut Engine<H>,
|
||||
revision: u32,
|
||||
f: impl FnOnce(&mut Engine<H>) -> Outcome,
|
||||
) -> Outcome {
|
||||
if engine.routing().revision == revision {
|
||||
f(engine)
|
||||
} else {
|
||||
Outcome::failed("the selection changed since the routing buffers were read")
|
||||
}
|
||||
}
|
||||
|
||||
/// Replaces the trackpoints `start..end` of the selection by the given ones, in a single segment
|
||||
/// (a pure insertion if `start == end`, a pure removal without new points). `attributes` holds the
|
||||
/// surface, highway, SAC scale and MTB scale of the new points, as intervals, and `anchors` the
|
||||
/// indices among the new points of the ones that become anchors.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn route<H: History>(
|
||||
engine: &mut Engine<H>,
|
||||
revision: u32,
|
||||
start: u32,
|
||||
end: u32,
|
||||
lng: &[f64],
|
||||
lat: &[f64],
|
||||
ele: &[f64],
|
||||
attributes: &RouteAttributes,
|
||||
anchors: &[u32],
|
||||
) -> Outcome {
|
||||
if lng.len() != lat.len() || lat.len() != ele.len() {
|
||||
return Outcome::failed("lng, lat and ele differ in length");
|
||||
}
|
||||
at_revision(engine, revision, |engine| {
|
||||
edit(
|
||||
engine,
|
||||
Command::Reroute(engine::Reroute {
|
||||
start,
|
||||
end,
|
||||
lng,
|
||||
lat,
|
||||
ele,
|
||||
surface: attributes.surface.view(),
|
||||
highway: attributes.highway.view(),
|
||||
sac_scale: attributes.sac_scale.view(),
|
||||
mtb_scale: attributes.mtb_scale.view(),
|
||||
anchors,
|
||||
}),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// Makes an anchor of the point of the selected segments that is the closest to the coordinates,
|
||||
/// inserting a trackpoint on the path if none is there.
|
||||
pub fn insert_anchor<H: History>(
|
||||
engine: &mut Engine<H>,
|
||||
revision: u32,
|
||||
lng: f64,
|
||||
lat: f64,
|
||||
) -> Outcome {
|
||||
at_revision(engine, revision, |engine| {
|
||||
edit(
|
||||
engine,
|
||||
Command::InsertAnchor(engine::InsertAnchor { lng, lat }),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// Makes the trackpoint `index` of the selection the start of its segment, which is a loop (the
|
||||
/// trackpoints before it go to the end, and the loop closes on it).
|
||||
pub fn change_loop_start<H: History>(engine: &mut Engine<H>, revision: u32, index: u32) -> Outcome {
|
||||
at_revision(engine, revision, |engine| {
|
||||
edit(
|
||||
engine,
|
||||
Command::ChangeLoopStart(engine::ChangeLoopStart { index }),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// Cuts the file, the route, 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`].
|
||||
pub fn split<H: History>(
|
||||
engine: &mut Engine<H>,
|
||||
revision: u32,
|
||||
at: u32,
|
||||
split_type: engine::SplitType,
|
||||
) -> Outcome {
|
||||
at_revision(engine, revision, |engine| {
|
||||
edit(
|
||||
engine,
|
||||
Command::Split(engine::Split {
|
||||
at,
|
||||
split_type,
|
||||
keep_originals: H::KEEPS_ORIGINALS,
|
||||
}),
|
||||
)
|
||||
})
|
||||
}
|
||||
@@ -1,616 +0,0 @@
|
||||
//! What crosses to the frontend, as plain data (serde): the shapes of the objects that the frontend
|
||||
//! reads, which `wasm/src/ts.rs` declares in TypeScript. Ids are hyphenated UUID strings, times
|
||||
//! are numbers (ms since the epoch), absent fields are skipped.
|
||||
|
||||
use crate as engine;
|
||||
use engine::{FileId, History};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
pub fn ids(items: &[FileId]) -> Vec<String> {
|
||||
items.iter().map(|id| id.0.to_string()).collect()
|
||||
}
|
||||
|
||||
// Outcome
|
||||
|
||||
/// What a call that edits the files or changes the selection did.
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Outcome {
|
||||
pub changed: bool,
|
||||
order_changed: bool,
|
||||
selection_changed: bool,
|
||||
clipboard_changed: bool,
|
||||
added: Vec<String>,
|
||||
modified: Vec<String>,
|
||||
removed: Vec<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
error: Option<String>,
|
||||
/// Whether the files changed in a way that has to be saved (not sent).
|
||||
#[serde(skip)]
|
||||
pub saves: bool,
|
||||
}
|
||||
|
||||
impl Outcome {
|
||||
pub fn new(outcome: &engine::Outcome, error: Option<String>) -> Self {
|
||||
let diff = outcome.diff.clone().unwrap_or_default();
|
||||
Self {
|
||||
changed: outcome.changed,
|
||||
order_changed: outcome.order_changed,
|
||||
selection_changed: outcome.selection_changed,
|
||||
clipboard_changed: outcome.clipboard_changed,
|
||||
added: ids(&diff.added),
|
||||
modified: ids(&diff.modified),
|
||||
removed: ids(&diff.removed),
|
||||
error,
|
||||
saves: outcome.changed && (outcome.diff.is_some() || outcome.order_changed),
|
||||
}
|
||||
}
|
||||
|
||||
/// The outcome of a frontend that knows nothing of the engine: all the files are added, and the
|
||||
/// order, the selection and the clipboard are to be read.
|
||||
pub fn everything<H: History>(engine: &engine::Engine<H>) -> Self {
|
||||
Self {
|
||||
changed: true,
|
||||
order_changed: true,
|
||||
selection_changed: true,
|
||||
clipboard_changed: true,
|
||||
added: ids(engine.order()),
|
||||
modified: vec![],
|
||||
removed: vec![],
|
||||
error: None,
|
||||
saves: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The outcome of a call that did nothing and has nothing to say.
|
||||
pub fn failed_none() -> Self {
|
||||
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()
|
||||
}
|
||||
|
||||
/// What two calls that were made one after the other did together.
|
||||
pub fn merge(mut self, other: Self) -> Self {
|
||||
fn union(into: &mut Vec<String>, from: Vec<String>) {
|
||||
for id in from {
|
||||
if !into.contains(&id) {
|
||||
into.push(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.changed |= other.changed;
|
||||
self.order_changed |= other.order_changed;
|
||||
self.selection_changed |= other.selection_changed;
|
||||
self.clipboard_changed |= other.clipboard_changed;
|
||||
self.saves |= other.saves;
|
||||
// a file that was added and then modified is still an added one, and one that was added
|
||||
// and then removed is not there at all
|
||||
let added_before = self.added.clone();
|
||||
union(&mut self.added, other.added);
|
||||
for id in other.modified {
|
||||
if !self.added.contains(&id) && !self.modified.contains(&id) {
|
||||
self.modified.push(id);
|
||||
}
|
||||
}
|
||||
for id in other.removed {
|
||||
self.added.retain(|added| *added != id);
|
||||
self.modified.retain(|modified| *modified != id);
|
||||
if !added_before.contains(&id) && !self.removed.contains(&id) {
|
||||
self.removed.push(id);
|
||||
}
|
||||
}
|
||||
self.error = self.error.or(other.error);
|
||||
self
|
||||
}
|
||||
|
||||
/// What a call that does nothing returns.
|
||||
pub fn failed(message: impl Into<String>) -> Self {
|
||||
Self::new(&engine::Outcome::default(), Some(message.into()))
|
||||
}
|
||||
}
|
||||
|
||||
// Selection and clipboard
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(
|
||||
tag = "type",
|
||||
rename_all = "camelCase",
|
||||
rename_all_fields = "camelCase"
|
||||
)]
|
||||
pub enum Selection {
|
||||
Empty,
|
||||
File {
|
||||
file_ids: Vec<Uuid>,
|
||||
},
|
||||
Route {
|
||||
file_id: Uuid,
|
||||
route_ids: Vec<Uuid>,
|
||||
},
|
||||
Track {
|
||||
file_id: Uuid,
|
||||
track_ids: Vec<Uuid>,
|
||||
},
|
||||
Segment {
|
||||
file_id: Uuid,
|
||||
track_id: Uuid,
|
||||
segment_ids: Vec<Uuid>,
|
||||
},
|
||||
Waypoints {
|
||||
file_id: Uuid,
|
||||
},
|
||||
Waypoint {
|
||||
file_id: Uuid,
|
||||
waypoint_ids: Vec<Uuid>,
|
||||
},
|
||||
}
|
||||
|
||||
impl From<&engine::Selection> for Selection {
|
||||
fn from(selection: &engine::Selection) -> Self {
|
||||
use engine::Selection as S;
|
||||
match selection {
|
||||
S::Empty => Self::Empty,
|
||||
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(),
|
||||
},
|
||||
S::TrackSegment {
|
||||
file_id,
|
||||
trk_id,
|
||||
trkseg_ids,
|
||||
} => Self::Segment {
|
||||
file_id: file_id.0,
|
||||
track_id: trk_id.0,
|
||||
segment_ids: trkseg_ids.iter().map(|id| id.0).collect(),
|
||||
},
|
||||
S::Waypoints { file_id } => Self::Waypoints { file_id: file_id.0 },
|
||||
S::Waypoint { file_id, wpt_ids } => Self::Waypoint {
|
||||
file_id: file_id.0,
|
||||
waypoint_ids: wpt_ids.iter().map(|id| id.0).collect(),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Selection> for engine::Selection {
|
||||
fn from(selection: Selection) -> Self {
|
||||
use engine::Selection as S;
|
||||
match selection {
|
||||
Selection::Empty => S::Empty,
|
||||
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(),
|
||||
},
|
||||
Selection::Segment {
|
||||
file_id,
|
||||
track_id,
|
||||
segment_ids,
|
||||
} => S::TrackSegment {
|
||||
file_id: FileId(file_id),
|
||||
trk_id: engine::TrackId(track_id),
|
||||
trkseg_ids: segment_ids
|
||||
.into_iter()
|
||||
.map(engine::TrackSegmentId)
|
||||
.collect(),
|
||||
},
|
||||
Selection::Waypoints { file_id } => S::Waypoints {
|
||||
file_id: FileId(file_id),
|
||||
},
|
||||
Selection::Waypoint {
|
||||
file_id,
|
||||
waypoint_ids,
|
||||
} => S::Waypoint {
|
||||
file_id: FileId(file_id),
|
||||
wpt_ids: waypoint_ids.into_iter().map(engine::WaypointId).collect(),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where moved elements go. A negative index is the start, an infinite one the end (which JSON
|
||||
/// writes as `null`, so the frontend sends a very large number instead).
|
||||
#[derive(Deserialize)]
|
||||
#[serde(
|
||||
tag = "type",
|
||||
rename_all = "camelCase",
|
||||
rename_all_fields = "camelCase"
|
||||
)]
|
||||
pub enum MoveTarget {
|
||||
Files {
|
||||
index: f64,
|
||||
},
|
||||
Routes {
|
||||
file_id: Uuid,
|
||||
index: f64,
|
||||
},
|
||||
Tracks {
|
||||
file_id: Uuid,
|
||||
index: f64,
|
||||
},
|
||||
Segments {
|
||||
file_id: Uuid,
|
||||
track_id: Uuid,
|
||||
index: f64,
|
||||
},
|
||||
Waypoints {
|
||||
file_id: Uuid,
|
||||
index: f64,
|
||||
},
|
||||
}
|
||||
|
||||
impl From<MoveTarget> for engine::MoveTarget {
|
||||
fn from(target: MoveTarget) -> Self {
|
||||
use engine::MoveTarget as T;
|
||||
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),
|
||||
},
|
||||
MoveTarget::Segments {
|
||||
file_id,
|
||||
track_id,
|
||||
index: i,
|
||||
} => T::Segments {
|
||||
file_id: FileId(file_id),
|
||||
trk_id: engine::TrackId(track_id),
|
||||
index: index(i),
|
||||
},
|
||||
MoveTarget::Waypoints { file_id, index: i } => T::Waypoints {
|
||||
file_id: FileId(file_id),
|
||||
index: index(i),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct Clipboard {
|
||||
#[serde(rename = "type")]
|
||||
kind: &'static str,
|
||||
ids: Vec<String>,
|
||||
cut: bool,
|
||||
}
|
||||
|
||||
impl Clipboard {
|
||||
pub fn new(clipboard: &engine::Clipboard) -> Self {
|
||||
let strings = |ids: Vec<Uuid>| ids.iter().map(Uuid::to_string).collect();
|
||||
let (kind, ids) = match clipboard.content.ids() {
|
||||
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()))
|
||||
}
|
||||
engine::ClipboardIds::Segments(ids) => (
|
||||
"segments",
|
||||
strings(ids.into_iter().map(|id| id.0).collect()),
|
||||
),
|
||||
engine::ClipboardIds::Waypoints(ids) => (
|
||||
"waypoints",
|
||||
strings(ids.into_iter().map(|id| id.0).collect()),
|
||||
),
|
||||
};
|
||||
Self {
|
||||
kind,
|
||||
ids,
|
||||
cut: clipboard.cut,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Files
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FileStructure {
|
||||
id: String,
|
||||
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 {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
name: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
desc: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
color: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
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>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct SegmentNode {
|
||||
id: String,
|
||||
rev: String,
|
||||
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,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
name: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
sym: Option<String>,
|
||||
}
|
||||
|
||||
impl FileStructure {
|
||||
pub fn new(file: &engine::FileStructure) -> Self {
|
||||
Self {
|
||||
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(),
|
||||
})
|
||||
.collect(),
|
||||
waypoints: file
|
||||
.waypoints
|
||||
.iter()
|
||||
.map(|wpt| WaypointNode {
|
||||
id: wpt.id.0.to_string(),
|
||||
name: wpt.name.clone(),
|
||||
sym: wpt.sym.clone(),
|
||||
})
|
||||
.collect(),
|
||||
waypoints_rev: file.wpt_rev_id.0.to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct GlobalStatistics {
|
||||
total_distance: f64,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
moving_distance: Option<f64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
total_time: Option<f64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
moving_time: Option<f64>,
|
||||
elevation_gain: f64,
|
||||
elevation_loss: f64,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
start_time: Option<f64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
end_time: Option<f64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
total_speed: Option<f64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
moving_speed: Option<f64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
bounds: Option<Bounds>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct Bounds {
|
||||
west: f64,
|
||||
south: f64,
|
||||
east: f64,
|
||||
north: f64,
|
||||
}
|
||||
|
||||
impl GlobalStatistics {
|
||||
pub fn new(stats: &engine::GlobalStatistics) -> Self {
|
||||
let seconds = |ms: Option<i64>| ms.map(|ms| ms as f64 / 1000.0);
|
||||
let (sw, ne) = (&stats.bounds.sw, &stats.bounds.ne);
|
||||
Self {
|
||||
total_distance: stats.total_distance,
|
||||
moving_distance: stats.moving_distance,
|
||||
total_time: seconds(stats.total_time),
|
||||
moving_time: seconds(stats.moving_time),
|
||||
elevation_gain: stats.elevation_gain,
|
||||
elevation_loss: stats.elevation_loss,
|
||||
start_time: stats.start_time.map(|t| t as f64),
|
||||
end_time: stats.end_time.map(|t| t as f64),
|
||||
total_speed: stats.total_speed(),
|
||||
moving_speed: stats.moving_speed(),
|
||||
bounds: (sw.lng <= ne.lng && sw.lat <= ne.lat).then_some(Bounds {
|
||||
west: sw.lng,
|
||||
south: sw.lat,
|
||||
east: ne.lng,
|
||||
north: ne.lat,
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct WaypointDetails {
|
||||
id: String,
|
||||
lng: f64,
|
||||
lat: f64,
|
||||
ele: f64,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
time: Option<f64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
name: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
desc: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
cmt: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
sym: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
links: Option<Vec<Link>>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct Link {
|
||||
href: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
text: Option<String>,
|
||||
}
|
||||
|
||||
impl WaypointDetails {
|
||||
pub fn new(wpt: &engine::Waypoint) -> Self {
|
||||
Self {
|
||||
id: wpt.id.0.to_string(),
|
||||
lng: wpt.coordinates.lng,
|
||||
lat: wpt.coordinates.lat,
|
||||
ele: wpt.ele,
|
||||
time: wpt.time.map(|t| t as f64),
|
||||
name: wpt.name.clone(),
|
||||
desc: wpt.desc.clone(),
|
||||
cmt: wpt.cmt.clone(),
|
||||
sym: wpt.sym.clone(),
|
||||
links: (!wpt.links.is_empty()).then(|| {
|
||||
wpt.links
|
||||
.iter()
|
||||
.map(|link| Link {
|
||||
href: link.href.clone(),
|
||||
text: link.text.clone(),
|
||||
})
|
||||
.collect()
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
#[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>,
|
||||
}
|
||||
|
||||
// Routing
|
||||
|
||||
/// A category of the trackpoints of a route, as in `RouteCategory` of the engine.
|
||||
#[derive(Default, Deserialize)]
|
||||
pub struct RouteCategory {
|
||||
pub starts: Vec<u32>,
|
||||
pub values: Vec<u8>,
|
||||
pub names: Vec<String>,
|
||||
}
|
||||
|
||||
impl RouteCategory {
|
||||
pub fn view(&self) -> engine::RouteCategory<'_> {
|
||||
engine::RouteCategory {
|
||||
starts: &self.starts,
|
||||
values: &self.values,
|
||||
names: &self.names,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct RouteAttributes {
|
||||
pub surface: RouteCategory,
|
||||
pub highway: RouteCategory,
|
||||
pub sac_scale: RouteCategory,
|
||||
pub mtb_scale: RouteCategory,
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
//! The interface to the engine, which the interfaces to the frontend share: the web page
|
||||
//! (`wasm`) and the desktop app (`tauri`) each expose these functions, and only convert what
|
||||
//! crosses to their own way of passing data.
|
||||
//!
|
||||
//! - `commands`: the functions that edit the files or change the selection. Each returns an
|
||||
//! `Outcome`: whether anything changed, what changed (to update what the frontend keeps), and why
|
||||
//! nothing was done when that is so (the command had nothing to do, the data is invalid, an
|
||||
//! argument is wrong).
|
||||
//! - `queries`: the functions that read the state of the engine.
|
||||
//! - `dto`: the data that crosses, as serde types.
|
||||
//!
|
||||
//! Ids are `Uuid`s: how the frontend sends them (strings, bytes) is for the interfaces to parse.
|
||||
//! Coordinates and statistics are slices of numbers, which the interfaces copy to typed arrays.
|
||||
|
||||
pub mod commands;
|
||||
pub mod dto;
|
||||
pub mod queries;
|
||||
|
||||
pub use commands::*;
|
||||
pub use dto::*;
|
||||
pub use queries::*;
|
||||
@@ -1,265 +0,0 @@
|
||||
//! The functions that read the state of the engine.
|
||||
//!
|
||||
//! The files are described by one ordered list of ids and one structure per file, so that the UI
|
||||
//! can react to what changed only: after each command, its `Outcome` tells which structures to
|
||||
//! (re)read or drop and whether the order changed. The trackpoints of a segment and the waypoints
|
||||
//! of a file are in the same order as the coordinates of their buffers.
|
||||
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::dto::*;
|
||||
use crate::{self as engine, Engine, FileId, History};
|
||||
|
||||
/// Ids of the files in display order.
|
||||
pub fn file_order<H: History>(engine: &Engine<H>) -> Vec<String> {
|
||||
ids(engine.order())
|
||||
}
|
||||
|
||||
/// Structure of a file, `None` if the id is unknown.
|
||||
pub fn file_structure<H: History>(engine: &Engine<H>, file_id: Uuid) -> Option<FileStructure> {
|
||||
engine
|
||||
.file_structure(&FileId(file_id))
|
||||
.map(FileStructure::new)
|
||||
}
|
||||
|
||||
/// Global statistics of a file, `None` if the id is unknown.
|
||||
pub fn file_statistics<H: History>(engine: &Engine<H>, file_id: Uuid) -> Option<GlobalStatistics> {
|
||||
engine
|
||||
.file_statistics(&FileId(file_id))
|
||||
.map(|stats| GlobalStatistics::new(&stats))
|
||||
}
|
||||
|
||||
/// The current selection.
|
||||
pub fn selection<H: History>(engine: &Engine<H>) -> Selection {
|
||||
engine.selection().into()
|
||||
}
|
||||
|
||||
/// What was copied or cut and is waiting to be pasted.
|
||||
pub fn clipboard<H: History>(engine: &Engine<H>) -> Option<Clipboard> {
|
||||
engine.clipboard().map(Clipboard::new)
|
||||
}
|
||||
|
||||
pub fn can_undo<H: History>(engine: &Engine<H>) -> bool {
|
||||
engine.can_undo()
|
||||
}
|
||||
|
||||
pub fn can_redo<H: History>(engine: &Engine<H>) -> bool {
|
||||
engine.can_redo()
|
||||
}
|
||||
|
||||
/// Whether the clipboard can be pasted with the current selection.
|
||||
pub fn can_paste<H: History>(engine: &Engine<H>) -> bool {
|
||||
engine.can_paste()
|
||||
}
|
||||
|
||||
/// All the data of a waypoint of a file, `None` if it does not exist.
|
||||
pub fn waypoint<H: History>(
|
||||
engine: &Engine<H>,
|
||||
file_id: Uuid,
|
||||
waypoint_id: Uuid,
|
||||
) -> Option<WaypointDetails> {
|
||||
engine
|
||||
.waypoint(&FileId(file_id), &engine::WaypointId(waypoint_id))
|
||||
.map(WaypointDetails::new)
|
||||
}
|
||||
|
||||
/// A file as GPX (UTF-8 bytes), `None` if it does not exist. The options say which data of the
|
||||
/// trackpoints to keep.
|
||||
pub fn export_file<H: History>(
|
||||
engine: &Engine<H>,
|
||||
file_id: Uuid,
|
||||
options: engine::ExportOptions,
|
||||
) -> Option<Vec<u8>> {
|
||||
engine.export(&FileId(file_id), options)
|
||||
}
|
||||
|
||||
/// The data that some files have, so that the ones that none has are not offered when exporting
|
||||
/// them: a bit for the time (1), heart rate (2), cadence (4), temperature (8), power (16) and the
|
||||
/// OpenStreetMap data (32).
|
||||
pub fn exportable_data<H: History>(engine: &Engine<H>, file_ids: &[Uuid]) -> u8 {
|
||||
let ids: Vec<FileId> = file_ids.iter().copied().map(FileId).collect();
|
||||
let data = engine.exportable_data(&ids);
|
||||
[
|
||||
data.time, data.hr, data.cad, data.atemp, data.power, data.osm,
|
||||
]
|
||||
.iter()
|
||||
.enumerate()
|
||||
.fold(0, |bits, (i, on)| bits | (u8::from(*on) << i))
|
||||
}
|
||||
|
||||
/// 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.
|
||||
pub fn reduction_distances<H: History>(engine: &Engine<H>) -> Vec<f64> {
|
||||
engine.reduction_distances()
|
||||
}
|
||||
|
||||
// Coordinates, as flat `[lng, lat, ...]` slices. Compare `rev` / `waypointsRev` of the file
|
||||
// structures with the previous ones to know which ones actually changed.
|
||||
|
||||
/// Coordinates of the trackpoints of a segment (empty if the id is unknown).
|
||||
pub fn segment_coordinates<H: History>(engine: &Engine<H>, segment_id: Uuid) -> &[f64] {
|
||||
engine.segment_coordinates(&engine::TrackSegmentId(segment_id))
|
||||
}
|
||||
|
||||
/// Coordinates of the waypoints of a file (empty if the id is unknown).
|
||||
pub fn waypoint_coordinates<H: History>(engine: &Engine<H>, file_id: Uuid) -> &[f64] {
|
||||
engine.waypoint_coordinates(&FileId(file_id))
|
||||
}
|
||||
|
||||
// Statistics of the selection
|
||||
|
||||
/// Global statistics of the whole selection (the buffers below cover it).
|
||||
pub fn selection_statistics<H: History>(engine: &Engine<H>) -> GlobalStatistics {
|
||||
GlobalStatistics::new(&engine.statistics().global)
|
||||
}
|
||||
|
||||
/// Global statistics of the trackpoints from `start` to `end` (both included) of the selection,
|
||||
/// as indexed by the buffers. `None` when the range is not in the selection.
|
||||
pub fn slice_statistics<H: History>(
|
||||
engine: &Engine<H>,
|
||||
start: usize,
|
||||
end: usize,
|
||||
) -> Option<GlobalStatistics> {
|
||||
engine
|
||||
.statistics()
|
||||
.slice(start, end)
|
||||
.map(|stats| GlobalStatistics::new(&stats))
|
||||
}
|
||||
|
||||
macro_rules! buffers {
|
||||
($($name:ident),*) => {$(
|
||||
pub fn $name<H: History>(engine: &Engine<H>) -> &[f64] {
|
||||
&engine.statistics().$name
|
||||
}
|
||||
)*};
|
||||
}
|
||||
|
||||
// One entry per trackpoint of the selection.
|
||||
buffers!(
|
||||
total_distance,
|
||||
elevation_gain,
|
||||
elevation_loss,
|
||||
lng,
|
||||
lat,
|
||||
ele
|
||||
);
|
||||
|
||||
macro_rules! optional_buffers {
|
||||
($($name:ident: $type:ty),*) => {$(
|
||||
/// `None` when no trackpoint of the selection has the value, else an entry per trackpoint,
|
||||
/// the missing ones being NaN (`NO_TIME` for the timestamps, 0 before the first trackpoint
|
||||
/// that has them for the cumulative distances and durations).
|
||||
pub fn $name<H: History>(engine: &Engine<H>) -> Option<&[$type]> {
|
||||
engine.statistics().$name.as_deref()
|
||||
}
|
||||
)*};
|
||||
}
|
||||
|
||||
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),
|
||||
})
|
||||
}
|
||||
|
||||
// Surface, highway, SAC scale and MTB scale of the trackpoints, as intervals of trackpoints that
|
||||
// have the same value: `<name>_starts` holds the index of the first trackpoint of each interval,
|
||||
// and `<name>_values` its value (0 when unknown, else 1 + the index in the names of the category).
|
||||
// A value that is unknown for every trackpoint is a single interval.
|
||||
macro_rules! categories {
|
||||
($starts:ident, $values:ident, $names:ident, $field:ident) => {
|
||||
pub fn $starts<H: History>(engine: &Engine<H>) -> &[u32] {
|
||||
&engine.statistics().$field.starts
|
||||
}
|
||||
|
||||
pub fn $values<H: History>(engine: &Engine<H>) -> &[u8] {
|
||||
&engine.statistics().$field.values
|
||||
}
|
||||
|
||||
/// The names of the category, in the order of their codes. The list only grows: a name
|
||||
/// keeps its index.
|
||||
pub fn $names<H: History>(engine: &Engine<H>) -> &[String] {
|
||||
engine.categories().$field.names()
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
categories!(surface_starts, surface_values, surfaces, surface);
|
||||
categories!(highway_starts, highway_values, highways, highway);
|
||||
categories!(sac_scale_starts, sac_scale_values, sac_scales, sac_scale);
|
||||
categories!(mtb_scale_starts, mtb_scale_values, mtb_scales, mtb_scale);
|
||||
|
||||
// The anchors of the routing tool among the trackpoints of the selection (numbered as in the
|
||||
// statistics). The ends of the segments are always anchors.
|
||||
|
||||
/// The index in the selection of each anchor.
|
||||
pub fn anchor_indices<H: History>(engine: &Engine<H>) -> &[u32] {
|
||||
&engine.routing().anchor_indices
|
||||
}
|
||||
|
||||
/// The lowest map zoom level at which each anchor is shown.
|
||||
pub fn anchor_zooms<H: History>(engine: &Engine<H>) -> &[u8] {
|
||||
&engine.routing().anchor_zooms
|
||||
}
|
||||
|
||||
/// Index in the selection of the first trackpoint of each selected segment that has some.
|
||||
pub fn segment_starts<H: History>(engine: &Engine<H>) -> &[u32] {
|
||||
&engine.routing().segment_starts
|
||||
}
|
||||
|
||||
/// The id of each selected segment that has trackpoints, as `segment_starts`.
|
||||
pub fn segment_ids<H: History>(engine: &Engine<H>) -> Vec<String> {
|
||||
engine
|
||||
.routing()
|
||||
.segment_ids
|
||||
.iter()
|
||||
.map(|id| id.0.to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Changes when the selected segments or their trackpoints change: the indices in the selection
|
||||
/// are only valid while it stays the same.
|
||||
pub fn routing_revision<H: History>(engine: &Engine<H>) -> u32 {
|
||||
engine.routing().revision
|
||||
}
|
||||
@@ -1,112 +0,0 @@
|
||||
use std::f64::consts::PI;
|
||||
|
||||
use crate::{
|
||||
TrackSegment, TrackSegmentIndex, core::utils::crossarc_lnglat, ramer_douglas_peucker_by,
|
||||
};
|
||||
|
||||
/// Highest zoom level of the map at which an anchor can appear.
|
||||
pub const MAX_ANCHOR_ZOOM: u8 = 22;
|
||||
|
||||
/// Details smaller than this (in meters) do not get an anchor.
|
||||
const ANCHOR_EPSILON: f64 = 1.0;
|
||||
|
||||
const EARTH_RADIUS_METERS: f64 = 6371008.8;
|
||||
|
||||
/// Lowest map zoom level at which an anchor selected at `distance` meters from the line of its
|
||||
/// neighbours is worth showing: the smaller the detail, the higher the zoom. The ends of a
|
||||
/// segment (no distance) are always shown.
|
||||
pub fn anchor_zoom(lat: f64, distance: Option<f64>) -> u8 {
|
||||
let Some(distance) = distance else {
|
||||
return 0;
|
||||
};
|
||||
let width = EARTH_RADIUS_METERS * (lat * PI / 180.0).cos() / distance;
|
||||
width.log2().round().clamp(0.0, MAX_ANCHOR_ZOOM as f64) as u8
|
||||
}
|
||||
|
||||
/// The anchors of a segment, as `(index, zoom)` sorted by index: the trackpoints kept by the
|
||||
/// Ramer-Douglas-Peucker simplification of its path, the ones for smaller details being shown at
|
||||
/// higher zoom levels only.
|
||||
pub fn compute_anchors(trkseg: &TrackSegment) -> Vec<(usize, u8)> {
|
||||
let measure = |start: TrackSegmentIndex, end: TrackSegmentIndex, idx: TrackSegmentIndex| {
|
||||
crossarc_lnglat(
|
||||
trkseg[start].coordinates,
|
||||
trkseg[end].coordinates,
|
||||
trkseg[idx].coordinates,
|
||||
)
|
||||
};
|
||||
ramer_douglas_peucker_by(trkseg, &measure, ANCHOR_EPSILON)
|
||||
.into_iter()
|
||||
.map(|(idx, distance)| (idx.flat, anchor_zoom(trkseg[idx].coordinates.lat, distance)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{LngLat, Trackpoint, TrackpointChunk};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn segment(points: &[(f64, f64)]) -> TrackSegment {
|
||||
let mut trkseg = TrackSegment::default();
|
||||
let mut chunk = TrackpointChunk::default();
|
||||
for (lng, lat) in points {
|
||||
chunk.trkpt.push(Trackpoint {
|
||||
coordinates: LngLat {
|
||||
lng: *lng,
|
||||
lat: *lat,
|
||||
},
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
trkseg.push(chunk);
|
||||
trkseg
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_zoom_depends_on_the_size_of_the_detail() {
|
||||
assert_eq!(anchor_zoom(45.0, None), 0);
|
||||
// 2^13 meters is close to the radius of the earth divided by 1 km
|
||||
assert_eq!(anchor_zoom(0.0, Some(1_000.0)), 13);
|
||||
assert!(anchor_zoom(0.0, Some(10.0)) > anchor_zoom(0.0, Some(1_000.0)));
|
||||
assert_eq!(anchor_zoom(0.0, Some(1e-9)), MAX_ANCHOR_ZOOM);
|
||||
assert_eq!(anchor_zoom(0.0, Some(1e9)), 0);
|
||||
// the poles do not give NaN or a panic
|
||||
assert_eq!(anchor_zoom(90.0, Some(10.0)), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_anchors_of_a_straight_line_are_its_ends() {
|
||||
let line: Vec<_> = (0..10).map(|i| (i as f64 * 0.001, 0.0)).collect();
|
||||
assert_eq!(compute_anchors(&segment(&line)), vec![(0, 0), (9, 0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_anchors_keep_the_corners() {
|
||||
// a big corner and a small bump
|
||||
let points = [
|
||||
(0.0, 0.0),
|
||||
(0.01, 0.0),
|
||||
(0.02, 0.0),
|
||||
(0.02, 0.01),
|
||||
(0.02, 0.02),
|
||||
(0.02, 0.020005),
|
||||
(0.02, 0.03),
|
||||
];
|
||||
let anchors = compute_anchors(&segment(&points));
|
||||
let indices: Vec<_> = anchors.iter().map(|(i, _)| *i).collect();
|
||||
assert_eq!(indices, vec![0, 2, 6]);
|
||||
assert_eq!(anchors[0].1, 0);
|
||||
assert_eq!(anchors[2].1, 0);
|
||||
assert!(anchors[1].1 > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_anchors_of_short_segments() {
|
||||
assert!(compute_anchors(&segment(&[])).is_empty());
|
||||
assert_eq!(compute_anchors(&segment(&[(1.0, 2.0)])), vec![(0, 0)]);
|
||||
assert_eq!(
|
||||
compute_anchors(&segment(&[(1.0, 2.0), (1.0, 2.1)])),
|
||||
vec![(0, 0), (1, 0)]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
mod anchors;
|
||||
mod reverse;
|
||||
mod simplify;
|
||||
mod smooth;
|
||||
mod timestamps;
|
||||
|
||||
pub use anchors::*;
|
||||
pub use reverse::*;
|
||||
pub use simplify::*;
|
||||
pub use timestamps::*;
|
||||
@@ -1,245 +0,0 @@
|
||||
//! Reversing a path: the order of its trackpoints, and of the segments and tracks that hold them.
|
||||
//!
|
||||
//! The timestamps are mirrored, so that the reversed path goes through the same period of time:
|
||||
//! a trackpoint at time `t` of a part that spans `start..end` ends up at `start + end - t`. When
|
||||
//! the part is made of several ones (the segments of a track, the tracks of a file), the gaps
|
||||
//! 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};
|
||||
|
||||
/// The time of the first trackpoint of a segment.
|
||||
pub fn start_time(segment: &TrackSegment) -> Option<i64> {
|
||||
segment.iter().next().and_then(|trkpt| trkpt.time)
|
||||
}
|
||||
|
||||
/// The time of the last trackpoint of a segment.
|
||||
pub fn end_time(segment: &TrackSegment) -> Option<i64> {
|
||||
segment.last_index().and_then(|idx| segment[idx].time)
|
||||
}
|
||||
|
||||
/// The time of the first trackpoint of a track.
|
||||
pub fn track_start_time(track: &Track) -> Option<i64> {
|
||||
track.trkseg.first().and_then(start_time)
|
||||
}
|
||||
|
||||
/// The time of the last trackpoint of a track.
|
||||
pub fn track_end_time(track: &Track) -> Option<i64> {
|
||||
track.trkseg.last().and_then(end_time)
|
||||
}
|
||||
|
||||
/// Reverses the trackpoints of a segment.
|
||||
///
|
||||
/// `original_next` is the time at which what came after the segment started, and `new_previous`
|
||||
/// the time at which what comes before it now ends: the segment is mirrored to start there. Both
|
||||
/// are those of the segment itself if the segment is reversed on its own, which are the ones
|
||||
/// used when they are missing (`new_previous` is the start of the segment, and `original_next`
|
||||
/// follows from the duration of the segment). Without timestamps, the trackpoints are only put
|
||||
/// in the opposite order.
|
||||
pub fn reverse_segment(
|
||||
segment: &mut TrackSegment,
|
||||
original_next: Option<i64>,
|
||||
new_previous: Option<i64>,
|
||||
) {
|
||||
let (original_start, original_end) = (start_time(segment), end_time(segment));
|
||||
let new_previous = new_previous.or(original_start);
|
||||
let original_next = original_next.or_else(|| {
|
||||
// the segment lasts as long as before
|
||||
Some(new_previous? + original_end? - original_start?)
|
||||
});
|
||||
|
||||
let len = segment.len();
|
||||
let mut points: Vec<Trackpoint> = segment.iter().cloned().collect();
|
||||
if let (Some(next), Some(previous), Some(end)) = (original_next, new_previous, original_end) {
|
||||
let new_start = previous + next - end;
|
||||
for point in points.iter_mut() {
|
||||
point.time = point.time.map(|time| new_start + (end - time));
|
||||
}
|
||||
}
|
||||
points.reverse();
|
||||
segment.splice(0, len, points);
|
||||
segment.rev_id = Default::default();
|
||||
}
|
||||
|
||||
/// Makes a segment go back where it started: a reversed copy of it is added after its last
|
||||
/// trackpoint, without the first trackpoint of the copy, which is the last one of the segment.
|
||||
///
|
||||
/// The timestamps of the copy go on from the end of the segment: it would start at the time of the
|
||||
/// last trackpoint, and it lasts as long as the segment. Only the end of the segment changes, so
|
||||
/// its other chunks stay shared.
|
||||
pub fn round_trip(segment: &mut TrackSegment) {
|
||||
let len = segment.len();
|
||||
let end = end_time(segment);
|
||||
let mut back = segment.clone();
|
||||
reverse_segment(&mut back, end, end);
|
||||
segment.splice(len, len, back.iter().skip(1).cloned().collect());
|
||||
segment.rev_id = Default::default();
|
||||
}
|
||||
|
||||
/// Reverses the segments of a track, and their trackpoints: see [`reverse_segment`] for the
|
||||
/// meaning of the times, which are the ones of the track as a whole.
|
||||
pub fn reverse_segments(
|
||||
segments: &mut [TrackSegment],
|
||||
original_next: Option<i64>,
|
||||
new_previous: Option<i64>,
|
||||
) {
|
||||
segments.reverse();
|
||||
let (mut next, mut previous) = (original_next, new_previous);
|
||||
for segment in segments.iter_mut() {
|
||||
// the next one is the one that was before, which started here
|
||||
let original_start = start_time(segment);
|
||||
reverse_segment(segment, next, previous);
|
||||
next = original_start;
|
||||
previous = end_time(segment);
|
||||
}
|
||||
}
|
||||
|
||||
/// 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();
|
||||
let (mut next, mut previous) = (original_next, new_previous);
|
||||
for track in tracks.iter_mut() {
|
||||
let original_start = track_start_time(track);
|
||||
reverse_segments(&mut track.trkseg, next, previous);
|
||||
next = original_start;
|
||||
previous = track_end_time(track);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::LngLat;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn segment(points: &[(f64, Option<i64>)]) -> TrackSegment {
|
||||
let mut segment = TrackSegment::default();
|
||||
let points = points
|
||||
.iter()
|
||||
.map(|(lng, time)| Trackpoint {
|
||||
coordinates: LngLat {
|
||||
lng: *lng,
|
||||
lat: 0.0,
|
||||
},
|
||||
time: *time,
|
||||
..Default::default()
|
||||
})
|
||||
.collect();
|
||||
segment.splice(0, 0, points);
|
||||
segment
|
||||
}
|
||||
|
||||
fn lngs(segment: &TrackSegment) -> Vec<f64> {
|
||||
segment.iter().map(|p| p.coordinates.lng).collect()
|
||||
}
|
||||
|
||||
fn times(segment: &TrackSegment) -> Vec<Option<i64>> {
|
||||
segment.iter().map(|p| p.time).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_a_segment_is_mirrored_in_its_own_time_span() {
|
||||
let mut s = segment(&[(0.0, Some(0)), (1.0, Some(10)), (2.0, Some(40))]);
|
||||
let (start, end) = (start_time(&s), end_time(&s));
|
||||
reverse_segment(&mut s, end, start);
|
||||
assert_eq!(lngs(&s), [2.0, 1.0, 0.0]);
|
||||
// same span, the durations between points follow the points
|
||||
assert_eq!(times(&s), [Some(0), Some(30), Some(40)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_reverse_segment_defaults() {
|
||||
// without the times around, the segment is mirrored where it is
|
||||
let mut s = segment(&[(0.0, Some(100)), (1.0, Some(130))]);
|
||||
reverse_segment(&mut s, None, None);
|
||||
assert_eq!(times(&s), [Some(100), Some(130)]);
|
||||
assert_eq!(lngs(&s), [1.0, 0.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_a_segment_without_times_is_only_reversed() {
|
||||
let mut s = segment(&[(0.0, None), (1.0, None), (2.0, None)]);
|
||||
reverse_segment(&mut s, None, None);
|
||||
assert_eq!(lngs(&s), [2.0, 1.0, 0.0]);
|
||||
assert_eq!(times(&s), [None, None, None]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_round_trip_goes_back_in_time_from_the_end() {
|
||||
let mut s = segment(&[(0.0, Some(0)), (1.0, Some(10)), (2.0, Some(40))]);
|
||||
let first = s.rev_id;
|
||||
round_trip(&mut s);
|
||||
assert_ne!(s.rev_id, first);
|
||||
// the last trackpoint is the turning point, it is not repeated
|
||||
assert_eq!(lngs(&s), [0.0, 1.0, 2.0, 1.0, 0.0]);
|
||||
// the way back lasts as long as the way there, and starts when it ended
|
||||
assert_eq!(times(&s), [Some(0), Some(10), Some(40), Some(70), Some(80)]);
|
||||
// and it is a segment whose ends are anchors
|
||||
assert_eq!(s[0].anchor, Some(0));
|
||||
assert_eq!(s[4].anchor, Some(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_round_trip_without_times() {
|
||||
let mut s = segment(&[(0.0, None), (1.0, None)]);
|
||||
round_trip(&mut s);
|
||||
assert_eq!(lngs(&s), [0.0, 1.0, 0.0]);
|
||||
assert_eq!(times(&s), [None; 3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_segments_keep_the_gaps_between_them() {
|
||||
// 0..20, then 100..120: a gap of 80
|
||||
let mut segments = vec![
|
||||
segment(&[(0.0, Some(0)), (1.0, Some(10)), (2.0, Some(20))]),
|
||||
segment(&[(3.0, Some(100)), (4.0, Some(110)), (5.0, Some(120))]),
|
||||
];
|
||||
let (end, start) = (end_time(&segments[1]), start_time(&segments[0]));
|
||||
reverse_segments(&mut segments, end, start);
|
||||
assert_eq!(lngs(&segments[0]), [5.0, 4.0, 3.0]);
|
||||
assert_eq!(lngs(&segments[1]), [2.0, 1.0, 0.0]);
|
||||
assert_eq!(times(&segments[0]), [Some(0), Some(10), Some(20)]);
|
||||
// the gap is still 80
|
||||
assert_eq!(times(&segments[1]), [Some(100), Some(110), Some(120)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tracks_are_reversed_like_segments() {
|
||||
let track = |segments: Vec<TrackSegment>| Track {
|
||||
trkseg: segments,
|
||||
..Default::default()
|
||||
};
|
||||
let mut tracks = vec![
|
||||
track(vec![
|
||||
segment(&[(0.0, Some(0)), (1.0, Some(10))]),
|
||||
segment(&[(2.0, Some(50)), (3.0, Some(60))]),
|
||||
]),
|
||||
track(vec![segment(&[(4.0, Some(200)), (5.0, Some(230))])]),
|
||||
];
|
||||
let (end, start) = (track_end_time(&tracks[1]), track_start_time(&tracks[0]));
|
||||
reverse_tracks(&mut tracks, end, start);
|
||||
let all: Vec<f64> = tracks
|
||||
.iter()
|
||||
.flat_map(|t| t.trkseg.iter().flat_map(lngs))
|
||||
.collect();
|
||||
assert_eq!(all, [5.0, 4.0, 3.0, 2.0, 1.0, 0.0]);
|
||||
// 3 segments: durations 10, 10, 30 and gaps 40 and 140 are reversed to 30, 10, 10 and
|
||||
// gaps 140 and 40 (the first part of the time is the longest)
|
||||
assert_eq!(times(&tracks[0].trkseg[0]), [Some(0), Some(30)]);
|
||||
assert_eq!(times(&tracks[1].trkseg[0]), [Some(170), Some(180)]);
|
||||
assert_eq!(times(&tracks[1].trkseg[1]), [Some(220), Some(230)]);
|
||||
}
|
||||
}
|
||||
Loaded 100 of 825 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user