mirror of
https://github.com/gpxstudio/gpx.studio.git
synced 2026-11-18 07:27:43 +00:00
Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c0e6e3d2eb | ||
|
|
9bd38cd5f8 | ||
|
|
a163e1b897 | ||
|
|
33abec525a | ||
|
|
77c542d9aa | ||
|
|
17b5c1d567 | ||
|
|
2048076fe6 | ||
|
|
d7ff7d645b | ||
|
|
262b590bd4 | ||
|
|
14bf9cddd2 | ||
|
|
b9566160e5 | ||
|
|
0cc9d6f664 | ||
|
|
1942e0b9e1 | ||
|
|
70a24f53b3 | ||
|
|
001246a49e | ||
|
|
8fe7d8d64d |
No files matched your search
@@ -0,0 +1,67 @@
|
|||||||
|
name: Deploy to Cloudflare Pages
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: 'dev'
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: cloudflare-${{ github.ref }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
deploy:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
deployments: write
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v5
|
||||||
|
|
||||||
|
- 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: wasm32-unknown-unknown
|
||||||
|
|
||||||
|
- 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: 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
|
||||||
|
|
||||||
|
- name: Build website
|
||||||
|
env:
|
||||||
|
BASE_PATH: ''
|
||||||
|
run: npm run build --prefix website
|
||||||
|
|
||||||
|
- name: Deploy to Cloudflare Pages
|
||||||
|
uses: cloudflare/wrangler-action@v3
|
||||||
|
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 }}
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
name: Desktop beta
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: 'dev'
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: desktop-beta-${{ github.ref }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
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
|
||||||
|
bundles: target/universal-apple-darwin/release/bundle/dmg/*.dmg
|
||||||
|
# the oldest supported Ubuntu, so that the AppImage runs on older systems too
|
||||||
|
- platform: ubuntu-22.04
|
||||||
|
rust_targets: wasm32-unknown-unknown
|
||||||
|
args: ''
|
||||||
|
bundles: |
|
||||||
|
target/release/bundle/deb/*.deb
|
||||||
|
target/release/bundle/rpm/*.rpm
|
||||||
|
target/release/bundle/appimage/*.AppImage
|
||||||
|
- platform: windows-latest
|
||||||
|
rust_targets: wasm32-unknown-unknown
|
||||||
|
args: ''
|
||||||
|
bundles: |
|
||||||
|
target/release/bundle/msi/*.msi
|
||||||
|
target/release/bundle/nsis/*.exe
|
||||||
|
|
||||||
|
runs-on: ${{ matrix.platform }}
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
- name: Build app
|
||||||
|
run: npx --yes @tauri-apps/cli@2 build ${{ matrix.args }}
|
||||||
|
working-directory: tauri
|
||||||
|
|
||||||
|
# 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
|
||||||
|
|
||||||
|
- name: Upload bundles
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: bundles-${{ matrix.platform }}
|
||||||
|
path: ${{ matrix.bundles }}
|
||||||
|
if-no-files-found: error
|
||||||
|
|
||||||
|
# replaces the beta release only once every platform is built
|
||||||
|
release:
|
||||||
|
needs: build
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
GH_REPO: ${{ github.repository }}
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Download bundles
|
||||||
|
uses: actions/download-artifact@v5
|
||||||
|
with:
|
||||||
|
pattern: bundles-*
|
||||||
|
path: bundles
|
||||||
|
merge-multiple: true
|
||||||
|
|
||||||
|
- name: Publish beta release
|
||||||
|
# the bundles of a platform are in a folder per format (deb, msi…)
|
||||||
|
run: |
|
||||||
|
mapfile -t files < <(find bundles -type f)
|
||||||
|
gh release delete desktop-beta --cleanup-tag --yes || true
|
||||||
|
gh release create desktop-beta "${files[@]}" \
|
||||||
|
--prerelease \
|
||||||
|
--target ${{ github.sha }} \
|
||||||
|
--title "Desktop beta" \
|
||||||
|
--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."
|
||||||
@@ -0,0 +1,505 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<gpx xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xmlns="http://www.topografix.com/GPX/1/1"
|
||||||
|
xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd
|
||||||
|
http://www.garmin.com/xmlschemas/GpxExtensions/v3 http://www.garmin.com/xmlschemas/GpxExtensionsv3.xsd
|
||||||
|
http://www.garmin.com/xmlschemas/TrackPointExtension/v1 http://www.garmin.com/xmlschemas/TrackPointExtensionv1.xsd
|
||||||
|
http://www.topografix.com/GPX/gpx_style/0/2 http://www.topografix.com/GPX/gpx_style/0/2/gpx_style.xsd"
|
||||||
|
xmlns:gpxtpx="http://www.garmin.com/xmlschemas/TrackPointExtension/v1"
|
||||||
|
xmlns:gpxpx="http://www.garmin.com/xmlschemas/PowerExtension/v1"
|
||||||
|
xmlns:gpx_style="http://www.topografix.com/GPX/gpx_style/0/2" version="1.1"
|
||||||
|
creator="https://gpx.studio">
|
||||||
|
<metadata>
|
||||||
|
<name>with_power</name>
|
||||||
|
<author>
|
||||||
|
<name>gpx.studio</name>
|
||||||
|
<link href="https://gpx.studio"></link>
|
||||||
|
</author>
|
||||||
|
</metadata>
|
||||||
|
<trk>
|
||||||
|
<name>with_power</name>
|
||||||
|
<type>Cycling</type>
|
||||||
|
<trkseg>
|
||||||
|
<trkpt lat="50.790867" lon="4.404968">
|
||||||
|
<ele>109.0</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.790714" lon="4.405036">
|
||||||
|
<ele>110.8</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.790336" lon="4.405259">
|
||||||
|
<ele>110.3</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.790165" lon="4.405331">
|
||||||
|
<ele>110.0</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.790008" lon="4.405359">
|
||||||
|
<ele>110.3</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.789818" lon="4.405359">
|
||||||
|
<ele>109.3</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.789409" lon="4.40534">
|
||||||
|
<ele>107.0</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.789105" lon="4.405411">
|
||||||
|
<ele>106.0</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.788799" lon="4.405527">
|
||||||
|
<ele>108.5</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.788645" lon="4.405606">
|
||||||
|
<ele>109.8</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.7885" lon="4.405711">
|
||||||
|
<ele>110.8</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.78822" lon="4.405959">
|
||||||
|
<ele>112.0</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.787956" lon="4.406092">
|
||||||
|
<ele>112.8</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.787814" lon="4.406143">
|
||||||
|
<ele>113.5</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.787674" lon="4.406177">
|
||||||
|
<ele>114.3</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.787451" lon="4.406199">
|
||||||
|
<ele>115.3</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.787297" lon="4.406177">
|
||||||
|
<ele>114.8</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.78716" lon="4.406098">
|
||||||
|
<ele>114.3</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.787045" lon="4.405984">
|
||||||
|
<ele>114.3</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.786683" lon="4.405653">
|
||||||
|
<ele>114.5</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.786538" lon="4.405543">
|
||||||
|
<ele>115.0</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.78635" lon="4.405441">
|
||||||
|
<ele>115.8</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.786275" lon="4.40542">
|
||||||
|
<ele>115.8</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.786182" lon="4.405435">
|
||||||
|
<ele>116.0</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.786121" lon="4.405475">
|
||||||
|
<ele>115.8</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.786042" lon="4.405558">
|
||||||
|
<ele>115.5</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.785821" lon="4.405925">
|
||||||
|
<ele>114.5</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.785672" lon="4.406119">
|
||||||
|
<ele>112.5</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.785516" lon="4.406256">
|
||||||
|
<ele>110.8</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.785384" lon="4.406364">
|
||||||
|
<ele>109.0</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.785126" lon="4.406475">
|
||||||
|
<ele>106.3</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.784697" lon="4.406537">
|
||||||
|
<ele>104.3</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.784591" lon="4.40657">
|
||||||
|
<ele>104.0</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.784507" lon="4.406612">
|
||||||
|
<ele>103.8</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.784435" lon="4.40669">
|
||||||
|
<ele>103.3</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.784209" lon="4.407148">
|
||||||
|
<ele>103.5</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.784162" lon="4.407257">
|
||||||
|
<ele>103.8</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.784077" lon="4.407372">
|
||||||
|
<ele>104.8</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.784006" lon="4.407435">
|
||||||
|
<ele>105.8</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.783924" lon="4.407471">
|
||||||
|
<ele>106.8</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.783837" lon="4.407486">
|
||||||
|
<ele>107.8</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.783771" lon="4.407472">
|
||||||
|
<ele>108.5</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.783697" lon="4.407428">
|
||||||
|
<ele>109.3</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.783626" lon="4.407363">
|
||||||
|
<ele>110.0</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.783548" lon="4.407274">
|
||||||
|
<ele>110.5</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.783458" lon="4.407134">
|
||||||
|
<ele>110.8</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.783123" lon="4.406435">
|
||||||
|
<ele>111.8</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.782982" lon="4.406168">
|
||||||
|
<ele>112.8</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.782871" lon="4.406044">
|
||||||
|
<ele>113.3</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.78279" lon="4.406021">
|
||||||
|
<ele>113.5</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.782714" lon="4.406018">
|
||||||
|
<ele>113.5</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.782607" lon="4.406047">
|
||||||
|
<ele>113.8</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.782405" lon="4.406194">
|
||||||
|
<ele>114.8</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.782175" lon="4.406413">
|
||||||
|
<ele>115.8</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.781749" lon="4.407018">
|
||||||
|
<ele>118.5</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.781654" lon="4.407316">
|
||||||
|
<ele>119.5</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.781563" lon="4.407764">
|
||||||
|
<ele>121.3</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.781487" lon="4.407984">
|
||||||
|
<ele>122.0</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.781422" lon="4.408216">
|
||||||
|
<ele>122.8</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.781395" lon="4.408508">
|
||||||
|
<ele>123.5</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.781399" lon="4.409114">
|
||||||
|
<ele>126.3</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.781367" lon="4.409428">
|
||||||
|
<ele>128.0</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.781286" lon="4.409607">
|
||||||
|
<ele>129.0</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.78116" lon="4.409789">
|
||||||
|
<ele>130.0</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.780804" lon="4.409993">
|
||||||
|
<ele>130.8</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.780389" lon="4.410334">
|
||||||
|
<ele>131.8</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.780232" lon="4.410563">
|
||||||
|
<ele>132.3</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.780094" lon="4.410827">
|
||||||
|
<ele>132.8</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.779723" lon="4.411582">
|
||||||
|
<ele>135.8</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.779591" lon="4.411791">
|
||||||
|
<ele>135.5</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.779125" lon="4.412435">
|
||||||
|
<ele>132.5</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.778676" lon="4.412979">
|
||||||
|
<ele>134.0</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.778194" lon="4.413466">
|
||||||
|
<ele>136.8</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.777427" lon="4.414302">
|
||||||
|
<ele>137.5</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.777165" lon="4.414736">
|
||||||
|
<ele>137.3</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.776927" lon="4.415201">
|
||||||
|
<ele>137.5</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.776778" lon="4.415613">
|
||||||
|
<ele>137.3</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.776553" lon="4.416425">
|
||||||
|
<ele>134.8</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.776326" lon="4.417304">
|
||||||
|
<ele>132.3</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
<trkpt lat="50.776129" lon="4.418383">
|
||||||
|
<ele>129.5</ele>
|
||||||
|
<extensions>
|
||||||
|
<gpxpx:PowerInWatts>210</gpxpx:PowerInWatts>
|
||||||
|
</extensions>
|
||||||
|
</trkpt>
|
||||||
|
</trkseg>
|
||||||
|
</trk>
|
||||||
|
</gpx>
|
||||||
@@ -49,7 +49,7 @@ pub fn select_elements<H: History>(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Selects all the elements of the same kind as the selected ones, in the same place: all the
|
/// Selects all the elements of the same kind as the selected ones, in the same place: all the
|
||||||
/// files, the tracks of the file, the segments of the track, the waypoints of the file. 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.
|
/// files when nothing is selected.
|
||||||
pub fn select_all<H: History>(engine: &mut Engine<H>) -> Outcome {
|
pub fn select_all<H: History>(engine: &mut Engine<H>) -> Outcome {
|
||||||
execute(engine, Action::SelectAll)
|
execute(engine, Action::SelectAll)
|
||||||
@@ -62,6 +62,19 @@ pub fn arrow_select<H: History>(engine: &mut Engine<H>, down: bool, add: bool) -
|
|||||||
execute(engine, Action::ArrowSelect { down, add })
|
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>(
|
pub fn select_tracks<H: History>(
|
||||||
engine: &mut Engine<H>,
|
engine: &mut Engine<H>,
|
||||||
file_id: Uuid,
|
file_id: Uuid,
|
||||||
@@ -135,21 +148,30 @@ pub fn redo<H: History>(engine: &mut Engine<H>) -> Outcome {
|
|||||||
|
|
||||||
// Files
|
// Files
|
||||||
|
|
||||||
/// Creates a file and selects it. With `lng` and `lat`, it starts with a track and a segment that
|
/// Creates a file and selects it. With `route`, it starts with a route. With `lng` and `lat`, it
|
||||||
/// hold that trackpoint (at `ele`, 0 by default).
|
/// 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>(
|
pub fn new_file<H: History>(
|
||||||
engine: &mut Engine<H>,
|
engine: &mut Engine<H>,
|
||||||
name: &str,
|
name: &str,
|
||||||
lng: Option<f64>,
|
lng: Option<f64>,
|
||||||
lat: Option<f64>,
|
lat: Option<f64>,
|
||||||
ele: Option<f64>,
|
ele: Option<f64>,
|
||||||
|
route: bool,
|
||||||
) -> Outcome {
|
) -> Outcome {
|
||||||
let trackpoint = lng.zip(lat).map(|(lng, lat)| engine::NewTrackpoint {
|
let trackpoint = lng.zip(lat).map(|(lng, lat)| engine::NewTrackpoint {
|
||||||
lng,
|
lng,
|
||||||
lat,
|
lat,
|
||||||
ele: ele.unwrap_or_default(),
|
ele: ele.unwrap_or_default(),
|
||||||
});
|
});
|
||||||
edit(engine, Command::New(engine::New { name, trackpoint }))
|
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,
|
/// Loads files as a single command (one undo step). The files are in `data`, one after the other,
|
||||||
@@ -183,8 +205,8 @@ pub fn load_files<H: History>(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Brings changes of the files from the outside in (see [`engine::SyncFiles`]): each file is
|
/// 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; it is called
|
/// `(id, data, name)`, and replaces the file of that id, or is added if there is none; `name` is
|
||||||
/// `name`, whatever its data says. The files to `remove` are deleted. The selection is left alone.
|
/// its name when its data has none. The files to `remove` are deleted. The selection is left alone.
|
||||||
pub fn sync_files<H: History>(
|
pub fn sync_files<H: History>(
|
||||||
engine: &mut Engine<H>,
|
engine: &mut Engine<H>,
|
||||||
files: &[(Uuid, &[u8], &str)],
|
files: &[(Uuid, &[u8], &str)],
|
||||||
@@ -304,6 +326,15 @@ pub fn style<H: History>(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Converts the selected routes to tracks, or the selected tracks or segments to routes.
|
||||||
|
pub fn convert<H: History>(engine: &mut Engine<H>) -> Outcome {
|
||||||
|
edit(engine, Command::Convert(engine::Convert))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn new_route<H: History>(engine: &mut Engine<H>) -> Outcome {
|
||||||
|
edit(engine, Command::NewRoute(engine::NewRoute))
|
||||||
|
}
|
||||||
|
|
||||||
pub fn new_track<H: History>(engine: &mut Engine<H>) -> Outcome {
|
pub fn new_track<H: History>(engine: &mut Engine<H>) -> Outcome {
|
||||||
edit(engine, Command::NewTrack(engine::NewTrack))
|
edit(engine, Command::NewTrack(engine::NewTrack))
|
||||||
}
|
}
|
||||||
@@ -575,7 +606,7 @@ pub fn route<H: History>(
|
|||||||
at_revision(engine, revision, |engine| {
|
at_revision(engine, revision, |engine| {
|
||||||
edit(
|
edit(
|
||||||
engine,
|
engine,
|
||||||
Command::Route(engine::Route {
|
Command::Reroute(engine::Reroute {
|
||||||
start,
|
start,
|
||||||
end,
|
end,
|
||||||
lng,
|
lng,
|
||||||
@@ -618,7 +649,7 @@ pub fn change_loop_start<H: History>(engine: &mut Engine<H>, revision: u32, inde
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Cuts the file, the track or the segment (see `SplitType`) of the trackpoint `at` of the
|
/// 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
|
/// 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
|
/// is cut is kept (and its two parts are new files) if the history needs it, see
|
||||||
/// [`History::KEEPS_ORIGINALS`].
|
/// [`History::KEEPS_ORIGINALS`].
|
||||||
|
|||||||
+74
-16
@@ -131,6 +131,10 @@ pub enum Selection {
|
|||||||
File {
|
File {
|
||||||
file_ids: Vec<Uuid>,
|
file_ids: Vec<Uuid>,
|
||||||
},
|
},
|
||||||
|
Route {
|
||||||
|
file_id: Uuid,
|
||||||
|
route_ids: Vec<Uuid>,
|
||||||
|
},
|
||||||
Track {
|
Track {
|
||||||
file_id: Uuid,
|
file_id: Uuid,
|
||||||
track_ids: Vec<Uuid>,
|
track_ids: Vec<Uuid>,
|
||||||
@@ -157,6 +161,10 @@ impl From<&engine::Selection> for Selection {
|
|||||||
S::File { file_ids } => Self::File {
|
S::File { file_ids } => Self::File {
|
||||||
file_ids: file_ids.iter().map(|id| id.0).collect(),
|
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 {
|
S::Track { file_id, trk_ids } => Self::Track {
|
||||||
file_id: file_id.0,
|
file_id: file_id.0,
|
||||||
track_ids: trk_ids.iter().map(|id| id.0).collect(),
|
track_ids: trk_ids.iter().map(|id| id.0).collect(),
|
||||||
@@ -187,6 +195,10 @@ impl From<Selection> for engine::Selection {
|
|||||||
Selection::File { file_ids } => S::File {
|
Selection::File { file_ids } => S::File {
|
||||||
file_ids: file_ids.into_iter().map(FileId).collect(),
|
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 {
|
Selection::Track { file_id, track_ids } => S::Track {
|
||||||
file_id: FileId(file_id),
|
file_id: FileId(file_id),
|
||||||
trk_ids: track_ids.into_iter().map(engine::TrackId).collect(),
|
trk_ids: track_ids.into_iter().map(engine::TrackId).collect(),
|
||||||
@@ -229,6 +241,10 @@ pub enum MoveTarget {
|
|||||||
Files {
|
Files {
|
||||||
index: f64,
|
index: f64,
|
||||||
},
|
},
|
||||||
|
Routes {
|
||||||
|
file_id: Uuid,
|
||||||
|
index: f64,
|
||||||
|
},
|
||||||
Tracks {
|
Tracks {
|
||||||
file_id: Uuid,
|
file_id: Uuid,
|
||||||
index: f64,
|
index: f64,
|
||||||
@@ -250,6 +266,10 @@ impl From<MoveTarget> for engine::MoveTarget {
|
|||||||
let index = |index: f64| index.max(0.0) as usize;
|
let index = |index: f64| index.max(0.0) as usize;
|
||||||
match target {
|
match target {
|
||||||
MoveTarget::Files { index: i } => T::Files { index: index(i) },
|
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 {
|
MoveTarget::Tracks { file_id, index: i } => T::Tracks {
|
||||||
file_id: FileId(file_id),
|
file_id: FileId(file_id),
|
||||||
index: index(i),
|
index: index(i),
|
||||||
@@ -286,6 +306,9 @@ impl Clipboard {
|
|||||||
engine::ClipboardIds::Files(ids) => {
|
engine::ClipboardIds::Files(ids) => {
|
||||||
("files", strings(ids.into_iter().map(|id| id.0).collect()))
|
("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) => {
|
engine::ClipboardIds::Tracks(ids) => {
|
||||||
("tracks", strings(ids.into_iter().map(|id| id.0).collect()))
|
("tracks", strings(ids.into_iter().map(|id| id.0).collect()))
|
||||||
}
|
}
|
||||||
@@ -315,14 +338,15 @@ pub struct FileStructure {
|
|||||||
name: String,
|
name: String,
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
desc: Option<String>,
|
desc: Option<String>,
|
||||||
|
routes: Vec<RouteNode>,
|
||||||
tracks: Vec<TrackNode>,
|
tracks: Vec<TrackNode>,
|
||||||
waypoints: Vec<WaypointNode>,
|
waypoints: Vec<WaypointNode>,
|
||||||
waypoints_rev: String,
|
waypoints_rev: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The name, description and style of a route or a track.
|
||||||
#[derive(Serialize)]
|
#[derive(Serialize)]
|
||||||
struct TrackNode {
|
struct PathInfo {
|
||||||
id: String,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
name: Option<String>,
|
name: Option<String>,
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
@@ -333,6 +357,33 @@ struct TrackNode {
|
|||||||
opacity: Option<f64>,
|
opacity: Option<f64>,
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
width: Option<f64>,
|
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>,
|
segments: Vec<SegmentNode>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -343,6 +394,16 @@ struct SegmentNode {
|
|||||||
length: f64,
|
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)]
|
#[derive(Serialize)]
|
||||||
struct WaypointNode {
|
struct WaypointNode {
|
||||||
id: String,
|
id: String,
|
||||||
@@ -358,25 +419,22 @@ impl FileStructure {
|
|||||||
id: file.id.0.to_string(),
|
id: file.id.0.to_string(),
|
||||||
name: file.name.clone(),
|
name: file.name.clone(),
|
||||||
desc: file.desc.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: file
|
||||||
.tracks
|
.tracks
|
||||||
.iter()
|
.iter()
|
||||||
.map(|trk| TrackNode {
|
.map(|trk| TrackNode {
|
||||||
id: trk.id.0.to_string(),
|
id: trk.id.0.to_string(),
|
||||||
name: trk.name.clone(),
|
info: (&trk.info).into(),
|
||||||
desc: trk.desc.clone(),
|
segments: trk.segments.iter().map(Into::into).collect(),
|
||||||
color: trk.color.clone(),
|
|
||||||
opacity: trk.opacity,
|
|
||||||
width: trk.width,
|
|
||||||
segments: trk
|
|
||||||
.segments
|
|
||||||
.iter()
|
|
||||||
.map(|seg| SegmentNode {
|
|
||||||
id: seg.id.0.to_string(),
|
|
||||||
rev: seg.rev_id.0.to_string(),
|
|
||||||
length: seg.len as f64,
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
})
|
})
|
||||||
.collect(),
|
.collect(),
|
||||||
waypoints: file
|
waypoints: file
|
||||||
|
|||||||
@@ -76,9 +76,7 @@ pub fn trackpoint<H: History>(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// A file as GPX (UTF-8 bytes), `None` if it does not exist. The options say which data of the
|
/// A file as GPX (UTF-8 bytes), `None` if it does not exist. The options say which data of the
|
||||||
/// trackpoints to keep, and with `as_route` that the segments are written as routes (`rte`)
|
/// trackpoints to keep.
|
||||||
/// instead of tracks: the anchors are the route points, and the trackpoints between them the
|
|
||||||
/// points of their path.
|
|
||||||
pub fn export_file<H: History>(
|
pub fn export_file<H: History>(
|
||||||
engine: &Engine<H>,
|
engine: &Engine<H>,
|
||||||
file_id: Uuid,
|
file_id: Uuid,
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
//! between them are kept: every part comes after the previous one in the new order, as late as the
|
//! 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.
|
//! original one came after the part that followed it.
|
||||||
|
|
||||||
use crate::{Track, TrackSegment, Trackpoint};
|
use crate::{Route, Track, TrackSegment, Trackpoint};
|
||||||
|
|
||||||
/// The time of the first trackpoint of a segment.
|
/// The time of the first trackpoint of a segment.
|
||||||
pub fn start_time(segment: &TrackSegment) -> Option<i64> {
|
pub fn start_time(segment: &TrackSegment) -> Option<i64> {
|
||||||
@@ -94,6 +94,19 @@ pub fn reverse_segments(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Reverses the routes of a file, and their trackpoints, like the segments of a track (see
|
||||||
|
/// [`reverse_segments`]).
|
||||||
|
pub fn reverse_routes(routes: &mut [Route], original_next: Option<i64>, new_previous: Option<i64>) {
|
||||||
|
routes.reverse();
|
||||||
|
let (mut next, mut previous) = (original_next, new_previous);
|
||||||
|
for route in routes.iter_mut() {
|
||||||
|
let original_start = start_time(&route.seg);
|
||||||
|
reverse_segment(&mut route.seg, next, previous);
|
||||||
|
next = original_start;
|
||||||
|
previous = end_time(&route.seg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Reverses the tracks of a file, and their segments and trackpoints.
|
/// 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>) {
|
pub fn reverse_tracks(tracks: &mut [Track], original_next: Option<i64>, new_previous: Option<i64>) {
|
||||||
tracks.reverse();
|
tracks.reverse();
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use crate::{Link, Track, Waypoints};
|
use crate::{Link, Route, Track, TrackSegment, Waypoints};
|
||||||
|
|
||||||
use super::common::uuid_id;
|
use super::common::uuid_id;
|
||||||
|
|
||||||
@@ -8,6 +8,9 @@ uuid_id!(FileId);
|
|||||||
pub struct File {
|
pub struct File {
|
||||||
pub id: FileId,
|
pub id: FileId,
|
||||||
pub info: FileInfo,
|
pub info: FileInfo,
|
||||||
|
/// The routes come before the tracks, as in GPX: everything that goes through the segments
|
||||||
|
/// of a file (statistics, the elevation profile...) takes the ones of the routes first.
|
||||||
|
pub rte: Vec<Route>,
|
||||||
pub trk: Vec<Track>,
|
pub trk: Vec<Track>,
|
||||||
pub wpt: Waypoints,
|
pub wpt: Waypoints,
|
||||||
}
|
}
|
||||||
@@ -29,3 +32,50 @@ pub struct Author {
|
|||||||
/// The author has a single link, unlike the other elements.
|
/// The author has a single link, unlike the other elements.
|
||||||
pub link: Option<Link>,
|
pub link: Option<Link>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Where a segment is in its file: the one of a route, or one of a track.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum SegmentIndex {
|
||||||
|
Route(usize),
|
||||||
|
Track { trk: usize, seg: usize },
|
||||||
|
}
|
||||||
|
|
||||||
|
impl File {
|
||||||
|
/// The segments of the routes, then the ones of the tracks.
|
||||||
|
pub fn segments(&self) -> impl Iterator<Item = &TrackSegment> {
|
||||||
|
self.rte
|
||||||
|
.iter()
|
||||||
|
.map(|rte| &rte.seg)
|
||||||
|
.chain(self.trk.iter().flat_map(|trk| &trk.trkseg))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where the segments are, in the order of [`File::segments`].
|
||||||
|
pub fn segment_indices(&self) -> impl Iterator<Item = SegmentIndex> + '_ {
|
||||||
|
(0..self.rte.len())
|
||||||
|
.map(SegmentIndex::Route)
|
||||||
|
.chain(self.trk.iter().enumerate().flat_map(|(trk, track)| {
|
||||||
|
(0..track.trkseg.len()).map(move |seg| SegmentIndex::Track { trk, seg })
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The segment at `index`. Panics if there is none.
|
||||||
|
pub fn segment(&self, index: SegmentIndex) -> &TrackSegment {
|
||||||
|
match index {
|
||||||
|
SegmentIndex::Route(rte) => &self.rte[rte].seg,
|
||||||
|
SegmentIndex::Track { trk, seg } => &self.trk[trk].trkseg[seg],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The segment at `index`. Panics if there is none.
|
||||||
|
pub fn segment_mut(&mut self, index: SegmentIndex) -> &mut TrackSegment {
|
||||||
|
match index {
|
||||||
|
SegmentIndex::Route(rte) => &mut self.rte[rte].seg,
|
||||||
|
SegmentIndex::Track { trk, seg } => &mut self.trk[trk].trkseg[seg],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the file has no route nor track.
|
||||||
|
pub fn has_no_path(&self) -> bool {
|
||||||
|
self.rte.is_empty() && self.trk.is_empty()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ mod chunk;
|
|||||||
mod chunked;
|
mod chunked;
|
||||||
mod common;
|
mod common;
|
||||||
mod file;
|
mod file;
|
||||||
|
mod route;
|
||||||
mod segment;
|
mod segment;
|
||||||
mod track;
|
mod track;
|
||||||
mod trackpoint;
|
mod trackpoint;
|
||||||
@@ -14,6 +15,7 @@ pub use chunk::*;
|
|||||||
pub use chunked::*;
|
pub use chunked::*;
|
||||||
pub use common::*;
|
pub use common::*;
|
||||||
pub use file::*;
|
pub use file::*;
|
||||||
|
pub use route::*;
|
||||||
pub use segment::*;
|
pub use segment::*;
|
||||||
pub use track::*;
|
pub use track::*;
|
||||||
pub use trackpoint::*;
|
pub use trackpoint::*;
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
use crate::{TrackInfo, TrackSegment};
|
||||||
|
|
||||||
|
use super::common::uuid_id;
|
||||||
|
|
||||||
|
uuid_id!(RouteId);
|
||||||
|
|
||||||
|
/// A route of the file (`rte`): like a track, but with a single segment, its points.
|
||||||
|
///
|
||||||
|
/// It has the information of a track: GPX gives the same to both.
|
||||||
|
#[derive(Debug, Default, Clone)]
|
||||||
|
pub struct Route {
|
||||||
|
pub id: RouteId,
|
||||||
|
pub info: TrackInfo,
|
||||||
|
pub seg: TrackSegment,
|
||||||
|
}
|
||||||
+56
-44
@@ -1,6 +1,6 @@
|
|||||||
use crate::{
|
use crate::{
|
||||||
Author, Chunk, File, Link, LngLat, Track, TrackSegment, Trackpoint, TrackpointCategories,
|
Author, Chunk, File, Link, LngLat, Route, Track, TrackSegment, Trackpoint,
|
||||||
TrackpointChunk, Waypoint, WaypointChunk, distance,
|
TrackpointCategories, TrackpointChunk, Waypoint, WaypointChunk, distance,
|
||||||
};
|
};
|
||||||
use chrono::DateTime;
|
use chrono::DateTime;
|
||||||
use quick_xml::Error;
|
use quick_xml::Error;
|
||||||
@@ -18,6 +18,7 @@ enum GPXElement {
|
|||||||
Author(Author),
|
Author(Author),
|
||||||
Link(Link),
|
Link(Link),
|
||||||
Text,
|
Text,
|
||||||
|
/// A track, or a route, whose information is read the same way.
|
||||||
Track(Track),
|
Track(Track),
|
||||||
Segment(TrackSegment),
|
Segment(TrackSegment),
|
||||||
Trackpoint(Trackpoint),
|
Trackpoint(Trackpoint),
|
||||||
@@ -396,7 +397,7 @@ pub fn parse(data: &[u8], categories: &mut TrackpointCategories) -> Result<File,
|
|||||||
let mut stack: Vec<GPXElement> = vec![];
|
let mut stack: Vec<GPXElement> = vec![];
|
||||||
let mut trkpt_chunk = TrackpointChunk::default();
|
let mut trkpt_chunk = TrackpointChunk::default();
|
||||||
let mut wpt_chunk = WaypointChunk::default();
|
let mut wpt_chunk = WaypointChunk::default();
|
||||||
// Routes are read as tracks of a single segment, see `RouteReader`. The points of the detailed
|
// The segment of a route is read by `RouteReader`. The points of the detailed
|
||||||
// path that a route point comes with (`gpxx:rpt`) are collected until the route point is read.
|
// path that a route point comes with (`gpxx:rpt`) are collected until the route point is read.
|
||||||
let mut route = RouteReader::default();
|
let mut route = RouteReader::default();
|
||||||
let mut rpt_points: Vec<Trackpoint> = vec![];
|
let mut rpt_points: Vec<Trackpoint> = vec![];
|
||||||
@@ -530,12 +531,12 @@ pub fn parse(data: &[u8], categories: &mut TrackpointCategories) -> Result<File,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
"rte" => {
|
"rte" => {
|
||||||
if let Some(GPXElement::Track(mut trk)) = stack.pop() {
|
if let Some(GPXElement::Track(trk)) = stack.pop() {
|
||||||
let trkseg = std::mem::take(&mut route).finish();
|
gpx.rte.push(Route {
|
||||||
if !trkseg.is_empty() {
|
info: trk.info,
|
||||||
trk.trkseg.push(trkseg);
|
seg: std::mem::take(&mut route).finish(),
|
||||||
}
|
..Default::default()
|
||||||
gpx.trk.push(trk);
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
"rtept" => {
|
"rtept" => {
|
||||||
@@ -740,38 +741,37 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_parse_routes_as_tracks() {
|
fn test_parse_routes() {
|
||||||
let gpx = parse_data("with_routes");
|
let gpx = parse_data("with_routes");
|
||||||
|
|
||||||
assert_eq!(gpx.trk.len(), 2);
|
assert!(gpx.trk.is_empty());
|
||||||
let trk = &gpx.trk[0];
|
assert_eq!(gpx.rte.len(), 2);
|
||||||
assert_eq!(trk.info.name.as_deref(), Some("route 1"));
|
let rte = &gpx.rte[0];
|
||||||
assert_eq!(trk.info.type_.as_deref(), Some("Cycling"));
|
assert_eq!(rte.info.name.as_deref(), Some("route 1"));
|
||||||
assert_eq!(trk.trkseg.len(), 1);
|
assert_eq!(rte.info.type_.as_deref(), Some("Cycling"));
|
||||||
let trkseg = &trk.trkseg[0];
|
assert_eq!(rte.seg.len(), 49);
|
||||||
assert_eq!(trkseg.len(), 49);
|
let trkpt = &rte.seg[0];
|
||||||
let trkpt = &trkseg[0];
|
|
||||||
assert_eq!(trkpt.coordinates.lat, 50.790867);
|
assert_eq!(trkpt.coordinates.lat, 50.790867);
|
||||||
assert_eq!(trkpt.coordinates.lng, 4.404968);
|
assert_eq!(trkpt.coordinates.lng, 4.404968);
|
||||||
assert_eq!(trkpt.ele, 109.0);
|
assert_eq!(trkpt.ele, 109.0);
|
||||||
|
|
||||||
let trk = &gpx.trk[1];
|
let rte = &gpx.rte[1];
|
||||||
assert_eq!(trk.info.name.as_deref(), Some("route 2"));
|
assert_eq!(rte.info.name.as_deref(), Some("route 2"));
|
||||||
assert_eq!(trk.trkseg[0].len(), 28);
|
assert_eq!(rte.seg.len(), 28);
|
||||||
|
assert_ne!(gpx.rte[0].id, rte.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_parse_route_point_extensions() {
|
fn test_parse_route_point_extensions() {
|
||||||
let gpx = parse_data("with_route_extensions");
|
let gpx = parse_data("with_route_extensions");
|
||||||
|
|
||||||
// a route without points has no segment
|
// a route without points has an empty segment
|
||||||
assert_eq!(gpx.trk.len(), 2);
|
assert_eq!(gpx.rte.len(), 2);
|
||||||
assert!(gpx.trk[1].trkseg.is_empty());
|
assert!(gpx.rte[1].seg.is_empty());
|
||||||
|
|
||||||
let trk = &gpx.trk[0];
|
let rte = &gpx.rte[0];
|
||||||
assert_eq!(trk.info.name.as_deref(), Some("with extensions"));
|
assert_eq!(rte.info.name.as_deref(), Some("with extensions"));
|
||||||
assert_eq!(trk.trkseg.len(), 1);
|
let points: Vec<_> = rte.seg.iter().collect();
|
||||||
let points: Vec<_> = trk.trkseg[0].iter().collect();
|
|
||||||
// the route points are kept, the points of the detailed path follow the one they come with
|
// the route points are kept, the points of the detailed path follow the one they come with
|
||||||
let coordinates: Vec<_> = points
|
let coordinates: Vec<_> = points
|
||||||
.iter()
|
.iter()
|
||||||
@@ -788,14 +788,13 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_route_points_are_the_anchors_and_nothing_else_is() {
|
fn test_route_points_are_the_anchors_and_nothing_else_is() {
|
||||||
let gpx = parse_data("with_route_extensions");
|
let gpx = parse_data("with_route_extensions");
|
||||||
let anchors: Vec<_> = gpx.trk[0].trkseg[0].iter().map(|p| p.anchor).collect();
|
let anchors: Vec<_> = gpx.rte[0].seg.iter().map(|p| p.anchor).collect();
|
||||||
assert_eq!(anchors, [Some(0), None, None, Some(0), Some(0)]);
|
assert_eq!(anchors, [Some(0), None, None, Some(0), Some(0)]);
|
||||||
|
|
||||||
// no anchor is computed for the points of a route that has none in between
|
// no anchor is computed for the points of a route that has none in between
|
||||||
let gpx = parse_data("with_routes");
|
let gpx = parse_data("with_routes");
|
||||||
for trk in &gpx.trk {
|
for rte in &gpx.rte {
|
||||||
let segment = &trk.trkseg[0];
|
assert!(rte.seg.iter().all(|p| p.anchor == Some(0)));
|
||||||
assert!(segment.iter().all(|p| p.anchor == Some(0)));
|
|
||||||
}
|
}
|
||||||
// while a track gets the anchors that its shape needs
|
// while a track gets the anchors that its shape needs
|
||||||
let track = parse_data("with_tracks");
|
let track = parse_data("with_tracks");
|
||||||
@@ -807,14 +806,14 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_parse_the_points_of_the_detailed_path_of_a_route() {
|
fn test_parse_the_points_of_the_detailed_path_of_a_route() {
|
||||||
let gpx = parse_data("with_route_points");
|
let gpx = parse_data("with_route_points");
|
||||||
assert_eq!(gpx.trk.len(), 1);
|
assert_eq!(gpx.rte.len(), 1);
|
||||||
let trk = &gpx.trk[0];
|
let rte = &gpx.rte[0];
|
||||||
assert_eq!(trk.info.name.as_deref(), Some("Lausanne"));
|
assert_eq!(rte.info.name.as_deref(), Some("Lausanne"));
|
||||||
assert_eq!(trk.info.cmt.as_deref(), Some("comment"));
|
assert_eq!(rte.info.cmt.as_deref(), Some("comment"));
|
||||||
assert_eq!(trk.info.desc.as_deref(), Some("description"));
|
assert_eq!(rte.info.desc.as_deref(), Some("description"));
|
||||||
assert_eq!(trk.info.type_.as_deref(), Some("Cycling"));
|
assert_eq!(rte.info.type_.as_deref(), Some("Cycling"));
|
||||||
|
|
||||||
let points: Vec<_> = trk.trkseg[0].iter().cloned().collect();
|
let points: Vec<_> = rte.seg.iter().cloned().collect();
|
||||||
// 3 route points and 4 points between them, the repeated one being kept
|
// 3 route points and 4 points between them, the repeated one being kept
|
||||||
assert_eq!(points.len(), 7);
|
assert_eq!(points.len(), 7);
|
||||||
let kinds: Vec<_> = points.iter().map(|p| p.anchor.is_some()).collect();
|
let kinds: Vec<_> = points.iter().map(|p| p.anchor.is_some()).collect();
|
||||||
@@ -846,7 +845,7 @@ mod tests {
|
|||||||
</rtept>
|
</rtept>
|
||||||
</rte></gpx>"#;
|
</rte></gpx>"#;
|
||||||
let gpx = parse(data.as_bytes(), &mut Default::default()).unwrap();
|
let gpx = parse(data.as_bytes(), &mut Default::default()).unwrap();
|
||||||
let points: Vec<_> = gpx.trk[0].trkseg[0].iter().cloned().collect();
|
let points: Vec<_> = gpx.rte[0].seg.iter().cloned().collect();
|
||||||
let coordinates: Vec<_> = points.iter().map(|p| p.coordinates.lat).collect();
|
let coordinates: Vec<_> = points.iter().map(|p| p.coordinates.lat).collect();
|
||||||
assert_eq!(coordinates, [1.0, 2.0, 2.1, 2.2]);
|
assert_eq!(coordinates, [1.0, 2.0, 2.1, 2.2]);
|
||||||
// the route point is an anchor, and so is the end of the path
|
// the route point is an anchor, and so is the end of the path
|
||||||
@@ -861,7 +860,7 @@ mod tests {
|
|||||||
<gpxx:RoutePointExtension><gpxx:rpt lat="1.5" lon="1.5"/></gpxx:RoutePointExtension>
|
<gpxx:RoutePointExtension><gpxx:rpt lat="1.5" lon="1.5"/></gpxx:RoutePointExtension>
|
||||||
</extensions></rtept></rte></gpx>"#;
|
</extensions></rtept></rte></gpx>"#;
|
||||||
let gpx = parse(data.as_bytes(), &mut Default::default()).unwrap();
|
let gpx = parse(data.as_bytes(), &mut Default::default()).unwrap();
|
||||||
let anchors: Vec<_> = gpx.trk[0].trkseg[0].iter().map(|p| p.anchor).collect();
|
let anchors: Vec<_> = gpx.rte[0].seg.iter().map(|p| p.anchor).collect();
|
||||||
assert_eq!(anchors, [Some(0), Some(0)]);
|
assert_eq!(anchors, [Some(0), Some(0)]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -930,14 +929,14 @@ mod tests {
|
|||||||
assert_eq!(waypoints[0].links[2].text.as_deref(), Some("three"));
|
assert_eq!(waypoints[0].links[2].text.as_deref(), Some("three"));
|
||||||
assert!(waypoints[1].links.is_empty());
|
assert!(waypoints[1].links.is_empty());
|
||||||
|
|
||||||
// tracks, and routes which are read as tracks
|
// tracks, and routes
|
||||||
assert_eq!(gpx.trk.len(), 2);
|
assert_eq!((gpx.trk.len(), gpx.rte.len()), (1, 1));
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
hrefs(&gpx.trk[0].info.links),
|
hrefs(&gpx.trk[0].info.links),
|
||||||
["https://example.com/trk-1", "https://example.com/trk-2"]
|
["https://example.com/trk-1", "https://example.com/trk-2"]
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
hrefs(&gpx.trk[1].info.links),
|
hrefs(&gpx.rte[0].info.links),
|
||||||
["https://example.com/rte-1", "https://example.com/rte-2"]
|
["https://example.com/rte-1", "https://example.com/rte-2"]
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1223,6 +1222,19 @@ mod tests {
|
|||||||
assert!(trkpt.power.is_some_and(|p| p == 200));
|
assert!(trkpt.power.is_some_and(|p| p == 200));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_parse_trackpoint_power_3() {
|
||||||
|
let gpx = parse_data("with_power_3");
|
||||||
|
|
||||||
|
assert_eq!(gpx.trk.len(), 1);
|
||||||
|
let trk = &gpx.trk[0];
|
||||||
|
assert_eq!(trk.trkseg.len(), 1);
|
||||||
|
let trkseg = &trk.trkseg[0];
|
||||||
|
assert!(!trkseg.is_empty());
|
||||||
|
let trkpt = &trkseg[0];
|
||||||
|
assert!(trkpt.power.is_some_and(|p| p == 200));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_parse_trackpoint_atemp() {
|
fn test_parse_trackpoint_atemp() {
|
||||||
let gpx = parse_data("with_temp");
|
let gpx = parse_data("with_temp");
|
||||||
|
|||||||
+154
-117
@@ -8,9 +8,6 @@ use crate::{File, Link, Track, Trackpoint, TrackpointCategories, Waypoint};
|
|||||||
|
|
||||||
/// What the written file contains: the data of the trackpoints that are `false` are left out.
|
/// What the written file contains: the data of the trackpoints that are `false` are left out.
|
||||||
/// The same type tells which data a file has, see [`File::exportable_data`].
|
/// The same type tells which data a file has, see [`File::exportable_data`].
|
||||||
///
|
|
||||||
/// With `as_route`, the file is written with routes instead of tracks, see [`write`]. It is not
|
|
||||||
/// data: it is off in `ALL` and `NONE`, and in what [`File::exportable_data`] gives.
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
pub struct ExportOptions {
|
pub struct ExportOptions {
|
||||||
pub time: bool,
|
pub time: bool,
|
||||||
@@ -20,8 +17,6 @@ pub struct ExportOptions {
|
|||||||
pub power: bool,
|
pub power: bool,
|
||||||
/// The OpenStreetMap data: surface, highway, SAC scale and MTB scale.
|
/// The OpenStreetMap data: surface, highway, SAC scale and MTB scale.
|
||||||
pub osm: bool,
|
pub osm: bool,
|
||||||
/// Writes every segment as a route (`rte`) instead of a track.
|
|
||||||
pub as_route: bool,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ExportOptions {
|
impl ExportOptions {
|
||||||
@@ -36,7 +31,6 @@ impl ExportOptions {
|
|||||||
atemp: value,
|
atemp: value,
|
||||||
power: value,
|
power: value,
|
||||||
osm: value,
|
osm: value,
|
||||||
as_route: false,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -49,7 +43,6 @@ impl ExportOptions {
|
|||||||
atemp: self.atemp || other.atemp,
|
atemp: self.atemp || other.atemp,
|
||||||
power: self.power || other.power,
|
power: self.power || other.power,
|
||||||
osm: self.osm || other.osm,
|
osm: self.osm || other.osm,
|
||||||
as_route: self.as_route || other.as_route,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -59,12 +52,7 @@ impl File {
|
|||||||
/// options of [`write`] can leave out.
|
/// options of [`write`] can leave out.
|
||||||
pub fn exportable_data(&self) -> ExportOptions {
|
pub fn exportable_data(&self) -> ExportOptions {
|
||||||
let mut data = ExportOptions::NONE;
|
let mut data = ExportOptions::NONE;
|
||||||
for point in self
|
for point in self.segments().flat_map(|seg| seg.iter()) {
|
||||||
.trk
|
|
||||||
.iter()
|
|
||||||
.flat_map(|trk| &trk.trkseg)
|
|
||||||
.flat_map(|seg| seg.iter())
|
|
||||||
{
|
|
||||||
data.time |= point.time.is_some();
|
data.time |= point.time.is_some();
|
||||||
data.hr |= point.hr.is_some();
|
data.hr |= point.hr.is_some();
|
||||||
data.cad |= point.cad.is_some();
|
data.cad |= point.cad.is_some();
|
||||||
@@ -82,6 +70,10 @@ impl File {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The highest zoom level from which an anchor is shown that makes it a route point, see [`write`]:
|
||||||
|
/// the anchors that only appear when zooming in further are details of the path.
|
||||||
|
pub const ROUTE_POINT_MAX_ZOOM: u8 = 12;
|
||||||
|
|
||||||
const SCHEMA_LOCATION: &str = "http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd http://www.garmin.com/xmlschemas/GpxExtensions/v3 http://www.garmin.com/xmlschemas/GpxExtensionsv3.xsd http://www.garmin.com/xmlschemas/TrackPointExtension/v1 http://www.garmin.com/xmlschemas/TrackPointExtensionv1.xsd http://www.garmin.com/xmlschemas/PowerExtension/v1 http://www.garmin.com/xmlschemas/PowerExtensionv1.xsd http://www.topografix.com/GPX/gpx_style/0/2 http://www.topografix.com/GPX/gpx_style/0/2/gpx_style.xsd";
|
const SCHEMA_LOCATION: &str = "http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd http://www.garmin.com/xmlschemas/GpxExtensions/v3 http://www.garmin.com/xmlschemas/GpxExtensionsv3.xsd http://www.garmin.com/xmlschemas/TrackPointExtension/v1 http://www.garmin.com/xmlschemas/TrackPointExtensionv1.xsd http://www.garmin.com/xmlschemas/PowerExtension/v1 http://www.garmin.com/xmlschemas/PowerExtensionv1.xsd http://www.topografix.com/GPX/gpx_style/0/2 http://www.topografix.com/GPX/gpx_style/0/2/gpx_style.xsd";
|
||||||
|
|
||||||
type XmlWriter = Writer<Vec<u8>>;
|
type XmlWriter = Writer<Vec<u8>>;
|
||||||
@@ -89,10 +81,10 @@ type XmlWriter = Writer<Vec<u8>>;
|
|||||||
/// Writes a file as GPX 1.1, in UTF-8. The surface, highway, SAC scale and MTB scale of the trackpoints are
|
/// Writes a file as GPX 1.1, in UTF-8. The surface, highway, SAC scale and MTB scale of the trackpoints are
|
||||||
/// the names of their codes in `categories`.
|
/// the names of their codes in `categories`.
|
||||||
///
|
///
|
||||||
/// The segments are written as tracks, or with `options.as_route` as routes: a segment becomes a
|
/// The routes are written as routes (`rte`): the anchors of their segment that are shown from the
|
||||||
/// `rte` that has the information of its track, its anchors are the `rtept` and the trackpoints
|
/// zoom level [`ROUTE_POINT_MAX_ZOOM`] or a lower one are the `rtept`, and the trackpoints between
|
||||||
/// between two anchors are the `gpxx:rpt` of the `rtept` before them (which only have a
|
/// two of them are the `gpxx:rpt` of the `rtept` before them (which only have a position, unlike
|
||||||
/// position, unlike the `rtept`). The first and last trackpoints always are `rtept`.
|
/// the `rtept`). The first and last trackpoints always are `rtept`.
|
||||||
pub fn write(file: &File, categories: &TrackpointCategories, options: ExportOptions) -> Vec<u8> {
|
pub fn write(file: &File, categories: &TrackpointCategories, options: ExportOptions) -> Vec<u8> {
|
||||||
let mut writer = Writer::new_with_indent(Vec::new(), b' ', 4);
|
let mut writer = Writer::new_with_indent(Vec::new(), b' ', 4);
|
||||||
// writing to memory does not fail
|
// writing to memory does not fail
|
||||||
@@ -100,9 +92,9 @@ pub fn write(file: &File, categories: &TrackpointCategories, options: ExportOpti
|
|||||||
writer.into_inner()
|
writer.into_inner()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn write_file(
|
fn write_file<'a>(
|
||||||
w: &mut XmlWriter,
|
w: &mut XmlWriter,
|
||||||
file: &File,
|
file: &'a File,
|
||||||
categories: &TrackpointCategories,
|
categories: &TrackpointCategories,
|
||||||
options: ExportOptions,
|
options: ExportOptions,
|
||||||
) -> io::Result<()> {
|
) -> io::Result<()> {
|
||||||
@@ -136,20 +128,18 @@ fn write_file(
|
|||||||
for wpt in file.wpt.iter() {
|
for wpt in file.wpt.iter() {
|
||||||
write_waypoint(w, wpt, options)?;
|
write_waypoint(w, wpt, options)?;
|
||||||
}
|
}
|
||||||
for trk in &file.trk {
|
// a single unnamed route or track is named like the file
|
||||||
// a single unnamed track is named like the file
|
let alone = file.rte.len() + file.trk.len() == 1;
|
||||||
let name = match (&trk.info.name, file.trk.len()) {
|
let name = |info: &'a crate::TrackInfo| match &info.name {
|
||||||
(Some(name), _) if !name.is_empty() => Some(name.as_str()),
|
Some(name) if !name.is_empty() => Some(name.as_str()),
|
||||||
(_, 1) => Some(file.info.name.as_str()),
|
_ if alone => Some(file.info.name.as_str()),
|
||||||
_ => None,
|
_ => None,
|
||||||
};
|
};
|
||||||
if options.as_route {
|
for rte in &file.rte {
|
||||||
for segment in trk.trkseg.iter().filter(|segment| !segment.is_empty()) {
|
write_route(w, &rte.info, &rte.seg, name(&rte.info), categories, options)?;
|
||||||
write_route(w, trk, segment, name, categories, options)?;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
write_track(w, trk, name, categories, options)?;
|
|
||||||
}
|
}
|
||||||
|
for trk in &file.trk {
|
||||||
|
write_track(w, trk, name(&trk.info), categories, options)?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
})?;
|
})?;
|
||||||
@@ -311,22 +301,28 @@ fn write_track(
|
|||||||
|
|
||||||
fn write_route(
|
fn write_route(
|
||||||
w: &mut XmlWriter,
|
w: &mut XmlWriter,
|
||||||
trk: &Track,
|
info: &crate::TrackInfo,
|
||||||
segment: &crate::TrackSegment,
|
segment: &crate::TrackSegment,
|
||||||
name: Option<&str>,
|
name: Option<&str>,
|
||||||
categories: &TrackpointCategories,
|
categories: &TrackpointCategories,
|
||||||
options: ExportOptions,
|
options: ExportOptions,
|
||||||
) -> io::Result<()> {
|
) -> io::Result<()> {
|
||||||
w.create_element("rte").write_inner_content(|w| {
|
w.create_element("rte").write_inner_content(|w| {
|
||||||
write_track_info(w, name, &trk.info)?;
|
write_track_info(w, name, info)?;
|
||||||
let points: Vec<&Trackpoint> = segment.iter().collect();
|
let points: Vec<&Trackpoint> = segment.iter().collect();
|
||||||
let last = points.len() - 1;
|
let last = points.len().saturating_sub(1);
|
||||||
let is_anchor = |i: usize| i == 0 || i == last || points[i].anchor.is_some();
|
let is_route_point = |i: usize| {
|
||||||
|
i == 0
|
||||||
|
|| i == last
|
||||||
|
|| points[i]
|
||||||
|
.anchor
|
||||||
|
.is_some_and(|zoom| zoom <= ROUTE_POINT_MAX_ZOOM)
|
||||||
|
};
|
||||||
let mut i = 0;
|
let mut i = 0;
|
||||||
while i < points.len() {
|
while i < points.len() {
|
||||||
// the trackpoints up to the next anchor
|
// the trackpoints up to the next route point
|
||||||
let mut next = i + 1;
|
let mut next = i + 1;
|
||||||
while next < points.len() && !is_anchor(next) {
|
while next < points.len() && !is_route_point(next) {
|
||||||
next += 1;
|
next += 1;
|
||||||
}
|
}
|
||||||
write_point(
|
write_point(
|
||||||
@@ -406,9 +402,10 @@ fn write_point(
|
|||||||
Ok(())
|
Ok(())
|
||||||
})?;
|
})?;
|
||||||
}
|
}
|
||||||
|
// `PowerInWatts` is itself the root element of Garmin's power extension, without a
|
||||||
|
// wrapper
|
||||||
if let Some(power) = power {
|
if let Some(power) = power {
|
||||||
w.create_element("gpxpx:PowerExtension")
|
number(w, "gpxpx:PowerInWatts", power)?;
|
||||||
.write_inner_content(|w| number(w, "gpxpx:PowerInWatts", power))?;
|
|
||||||
}
|
}
|
||||||
if !path.is_empty() {
|
if !path.is_empty() {
|
||||||
w.create_element("gpxx:RoutePointExtension")
|
w.create_element("gpxx:RoutePointExtension")
|
||||||
@@ -455,9 +452,7 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn points(file: &File) -> Vec<Trackpoint> {
|
fn points(file: &File) -> Vec<Trackpoint> {
|
||||||
file.trk
|
file.segments()
|
||||||
.iter()
|
|
||||||
.flat_map(|trk| &trk.trkseg)
|
|
||||||
.flat_map(|seg| seg.iter().cloned())
|
.flat_map(|seg| seg.iter().cloned())
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
@@ -517,6 +512,7 @@ mod tests {
|
|||||||
"with_temp",
|
"with_temp",
|
||||||
"with_power_1",
|
"with_power_1",
|
||||||
"with_power_2",
|
"with_power_2",
|
||||||
|
"with_power_3",
|
||||||
"with_surface",
|
"with_surface",
|
||||||
"with_highway",
|
"with_highway",
|
||||||
"with_style",
|
"with_style",
|
||||||
@@ -584,6 +580,16 @@ mod tests {
|
|||||||
assert_eq!(again.trk[0].info.name.as_deref(), Some("a <b> & c"));
|
assert_eq!(again.trk[0].info.name.as_deref(), Some("a <b> & c"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_power_is_written_without_a_wrapper() {
|
||||||
|
let (file, categories) = read("with_power_2");
|
||||||
|
let text: String = written_text(&file, &categories, ExportOptions::ALL)
|
||||||
|
.split_whitespace()
|
||||||
|
.collect();
|
||||||
|
assert!(text.contains("<extensions><gpxpx:PowerInWatts>200</gpxpx:PowerInWatts>"));
|
||||||
|
assert!(!text.contains("<gpxpx:PowerExtension>"));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_exportable_data() {
|
fn test_exportable_data() {
|
||||||
let (file, _) = read("with_time");
|
let (file, _) = read("with_time");
|
||||||
@@ -595,11 +601,20 @@ mod tests {
|
|||||||
assert!(file.exportable_data().power);
|
assert!(file.exportable_data().power);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn as_route() -> ExportOptions {
|
/// The file with each segment of its tracks as a route, which has the information of its
|
||||||
ExportOptions {
|
/// track.
|
||||||
as_route: true,
|
fn as_routes(mut file: File) -> File {
|
||||||
..ExportOptions::ALL
|
file.rte = std::mem::take(&mut file.trk)
|
||||||
}
|
.into_iter()
|
||||||
|
.flat_map(|trk| {
|
||||||
|
trk.trkseg.into_iter().map(move |seg| crate::Route {
|
||||||
|
info: trk.info.clone(),
|
||||||
|
seg,
|
||||||
|
..Default::default()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
file
|
||||||
}
|
}
|
||||||
|
|
||||||
fn count(text: &str, pattern: &str) -> usize {
|
fn count(text: &str, pattern: &str) -> usize {
|
||||||
@@ -607,19 +622,17 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_export_as_route_writes_routes_instead_of_tracks() {
|
fn test_routes_are_written_with_their_route_points_and_their_path() {
|
||||||
let (file, categories) = read("with_route_points");
|
let (file, categories) = read("with_route_points");
|
||||||
let text = written_text(&file, &categories, as_route());
|
let text = written_text(&file, &categories, ExportOptions::ALL);
|
||||||
|
|
||||||
assert_eq!(count(&text, "<rte>"), 1);
|
assert_eq!(count(&text, "<rte>"), 1);
|
||||||
assert_eq!(count(&text, "<trk>"), 0);
|
assert_eq!(count(&text, "<trk>"), 0);
|
||||||
assert_eq!(count(&text, "<trkseg>"), 0);
|
|
||||||
assert_eq!(count(&text, "<trkpt"), 0);
|
assert_eq!(count(&text, "<trkpt"), 0);
|
||||||
// the anchors are the route points, the trackpoints between them the points of their path
|
// the anchors are the route points, the trackpoints between them the points of their path
|
||||||
assert_eq!(count(&text, "<rtept"), 3);
|
assert_eq!(count(&text, "<rtept"), 3);
|
||||||
assert_eq!(count(&text, "<gpxx:rpt"), 4);
|
assert_eq!(count(&text, "<gpxx:rpt"), 4);
|
||||||
assert_eq!(count(&text, "<gpxx:RoutePointExtension>"), 2);
|
assert_eq!(count(&text, "<gpxx:RoutePointExtension>"), 2);
|
||||||
// a route has the information of its track
|
|
||||||
assert!(text.contains("<name>Lausanne</name>"));
|
assert!(text.contains("<name>Lausanne</name>"));
|
||||||
assert!(text.contains("<cmt>comment</cmt>"));
|
assert!(text.contains("<cmt>comment</cmt>"));
|
||||||
assert!(text.contains("<desc>description</desc>"));
|
assert!(text.contains("<desc>description</desc>"));
|
||||||
@@ -634,14 +647,14 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_a_route_survives_being_exported_as_a_route() {
|
fn test_a_route_survives_being_written() {
|
||||||
let (file, mut categories) = read("with_route_points");
|
let (file, mut categories) = read("with_route_points");
|
||||||
let written = write(&file, &categories, as_route());
|
let written = write(&file, &categories, ExportOptions::ALL);
|
||||||
let again = parse(&written, &mut categories).unwrap();
|
let again = parse(&written, &mut categories).unwrap();
|
||||||
|
|
||||||
assert_eq!(again.trk.len(), 1);
|
assert_eq!(again.rte.len(), 1);
|
||||||
assert_eq!(again.trk[0].info, file.trk[0].info);
|
assert_eq!(again.rte[0].info, file.rte[0].info);
|
||||||
let (a, b) = (&file.trk[0].trkseg[0], &again.trk[0].trkseg[0]);
|
let (a, b) = (&file.rte[0].seg, &again.rte[0].seg);
|
||||||
assert_eq!(a.len(), b.len());
|
assert_eq!(a.len(), b.len());
|
||||||
for (a, b) in a.iter().zip(b.iter()) {
|
for (a, b) in a.iter().zip(b.iter()) {
|
||||||
assert_eq!(a.coordinates.lat, b.coordinates.lat);
|
assert_eq!(a.coordinates.lat, b.coordinates.lat);
|
||||||
@@ -659,85 +672,121 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_tracks_become_one_route_per_segment_with_the_information_of_the_track() {
|
fn test_the_anchors_shown_up_to_zoom_12_are_the_route_points() {
|
||||||
let (file, mut categories) = read("with_tracks_and_segments");
|
let (file, mut categories) = read("with_tracks_and_segments");
|
||||||
let segments: usize = file.trk.iter().map(|t| t.trkseg.len()).sum();
|
let file = as_routes(file);
|
||||||
assert!(segments > 2);
|
assert!(file.rte.len() > 2);
|
||||||
let written = write(&file, &categories, as_route());
|
let written = write(&file, &categories, ExportOptions::ALL);
|
||||||
let text = String::from_utf8(written.clone()).unwrap();
|
|
||||||
assert_eq!(count(&text, "<rte>"), segments);
|
|
||||||
assert_eq!(count(&text, "<trk>"), 0);
|
|
||||||
// every route starts and ends with a route point
|
|
||||||
assert_eq!(count(&text, "</rte>"), segments);
|
|
||||||
|
|
||||||
let again = parse(&written, &mut categories).unwrap();
|
let again = parse(&written, &mut categories).unwrap();
|
||||||
assert_eq!(again.trk.len(), segments);
|
assert_eq!(again.rte.len(), file.rte.len());
|
||||||
let mut routes = again.trk.iter();
|
let anchors = |s: &crate::TrackSegment, max_zoom: u8| {
|
||||||
for track in &file.trk {
|
|
||||||
for segment in &track.trkseg {
|
|
||||||
let route = routes.next().unwrap();
|
|
||||||
// the information of the track, repeated for each of its segments
|
|
||||||
assert_eq!(route.info.name, track.info.name);
|
|
||||||
assert_eq!(route.info.type_, track.info.type_);
|
|
||||||
let (a, b) = (segment, &route.trkseg[0]);
|
|
||||||
assert_eq!(a.len(), b.len());
|
|
||||||
for (a, b) in a.iter().zip(b.iter()) {
|
|
||||||
assert_eq!(
|
|
||||||
(a.coordinates.lat, a.coordinates.lng),
|
|
||||||
(b.coordinates.lat, b.coordinates.lng)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
// the anchors of the segment are the ones of its route
|
|
||||||
let anchors = |s: &crate::TrackSegment| {
|
|
||||||
s.iter()
|
s.iter()
|
||||||
.enumerate()
|
.enumerate()
|
||||||
.filter(|(_, p)| p.anchor.is_some())
|
.filter(|(_, p)| p.anchor.is_some_and(|zoom| zoom <= max_zoom))
|
||||||
.map(|(i, _)| i)
|
.map(|(i, _)| i)
|
||||||
.collect::<Vec<_>>()
|
.collect::<Vec<_>>()
|
||||||
};
|
};
|
||||||
assert_eq!(anchors(a), anchors(b));
|
for (a, b) in file.rte.iter().zip(&again.rte) {
|
||||||
}
|
assert_eq!(a.info.name, b.info.name);
|
||||||
|
assert_eq!(a.seg.len(), b.seg.len());
|
||||||
|
// the route points come back as anchors, the other anchors as points of the path
|
||||||
|
assert_eq!(
|
||||||
|
anchors(&a.seg, ROUTE_POINT_MAX_ZOOM),
|
||||||
|
anchors(&b.seg, u8::MAX)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_anchors_shown_from_a_higher_zoom_are_points_of_the_path() {
|
||||||
|
let (file, categories) = read("simple");
|
||||||
|
let mut file = as_routes(file);
|
||||||
|
let segment = &mut file.rte[0].seg;
|
||||||
|
segment.update_all(|_, point| point.anchor = None);
|
||||||
|
let len = segment.len();
|
||||||
|
segment.set_anchor(5, ROUTE_POINT_MAX_ZOOM);
|
||||||
|
segment.set_anchor(10, ROUTE_POINT_MAX_ZOOM + 1);
|
||||||
|
let text = written_text(&file, &categories, ExportOptions::ALL);
|
||||||
|
// the ends, and the anchor shown from zoom 12
|
||||||
|
assert_eq!(count(&text, "<rtept"), 3);
|
||||||
|
assert_eq!(count(&text, "<gpxx:rpt"), len - 3);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_the_ends_of_a_route_are_route_points_even_without_anchors() {
|
fn test_the_ends_of_a_route_are_route_points_even_without_anchors() {
|
||||||
let (mut file, categories) = read("simple");
|
let (file, categories) = read("simple");
|
||||||
file.trk[0].trkseg[0].update_all(|_, point| point.anchor = None);
|
let mut file = as_routes(file);
|
||||||
let len = file.trk[0].trkseg[0].len();
|
file.rte[0].seg.update_all(|_, point| point.anchor = None);
|
||||||
let text = written_text(&file, &categories, as_route());
|
let len = file.rte[0].seg.len();
|
||||||
|
let text = written_text(&file, &categories, ExportOptions::ALL);
|
||||||
assert_eq!(count(&text, "<rtept"), 2);
|
assert_eq!(count(&text, "<rtept"), 2);
|
||||||
assert_eq!(count(&text, "<gpxx:rpt"), len - 2);
|
assert_eq!(count(&text, "<gpxx:rpt"), len - 2);
|
||||||
// and a single trackpoint is a route of one point
|
// and a single trackpoint is a route of one point
|
||||||
file.trk[0].trkseg[0].splice(1, len, vec![]);
|
file.rte[0].seg.splice(1, len, vec![]);
|
||||||
let text = written_text(&file, &categories, as_route());
|
let text = written_text(&file, &categories, ExportOptions::ALL);
|
||||||
assert_eq!(count(&text, "<rtept"), 1);
|
assert_eq!(count(&text, "<rtept"), 1);
|
||||||
assert_eq!(count(&text, "<gpxx:rpt"), 0);
|
assert_eq!(count(&text, "<gpxx:rpt"), 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_empty_segments_are_not_routes() {
|
fn test_routes_keep_their_style() {
|
||||||
let (mut file, categories) = read("simple");
|
|
||||||
file.trk[0].trkseg.push(crate::TrackSegment::default());
|
|
||||||
let text = written_text(&file, &categories, as_route());
|
|
||||||
assert_eq!(count(&text, "<rte>"), 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_routes_have_the_style_of_their_track() {
|
|
||||||
let (file, categories) = read("with_style");
|
let (file, categories) = read("with_style");
|
||||||
let text = written_text(&file, &categories, as_route());
|
let file = as_routes(file);
|
||||||
|
let text = written_text(&file, &categories, ExportOptions::ALL);
|
||||||
assert!(count(&text, "<gpx_style:line>") >= 1);
|
assert!(count(&text, "<gpx_style:line>") >= 1);
|
||||||
assert_eq!(count(&text, "<gpx_style:line>"), count(&text, "<rte>"));
|
assert_eq!(count(&text, "<gpx_style:line>"), count(&text, "<rte>"));
|
||||||
let again = parse(text.as_bytes(), &mut Default::default()).unwrap();
|
let again = parse(text.as_bytes(), &mut Default::default()).unwrap();
|
||||||
assert_eq!(again.trk[0].info.color, file.trk[0].info.color);
|
assert_eq!(again.rte[0].info.color, file.rte[0].info.color);
|
||||||
assert_eq!(again.trk[0].info.width, file.trk[0].info.width);
|
assert_eq!(again.rte[0].info.width, file.rte[0].info.width);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_routes_are_written_as_routes_before_the_tracks() {
|
||||||
|
let (mut file, categories) = read("with_tracks");
|
||||||
|
let (routes, _) = read("with_routes");
|
||||||
|
file.rte = routes.rte.clone();
|
||||||
|
let text = written_text(&file, &categories, ExportOptions::ALL);
|
||||||
|
assert_eq!(count(&text, "<rte>"), routes.rte.len());
|
||||||
|
assert_eq!(count(&text, "<trk>"), file.trk.len());
|
||||||
|
assert!(text.rfind("</rte>").unwrap() < text.find("<trk>").unwrap());
|
||||||
|
|
||||||
|
let again = parse(text.as_bytes(), &mut categories.clone()).unwrap();
|
||||||
|
assert_eq!(again.rte.len(), file.rte.len());
|
||||||
|
assert_eq!(again.trk.len(), file.trk.len());
|
||||||
|
for (a, b) in file.rte.iter().zip(&again.rte) {
|
||||||
|
assert_eq!(a.info, b.info);
|
||||||
|
same_points(
|
||||||
|
&a.seg.iter().cloned().collect::<Vec<_>>(),
|
||||||
|
&b.seg.iter().cloned().collect::<Vec<_>>(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
same_points(&points(&file), &points(&again));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_an_empty_route_is_written_and_a_single_route_is_named_like_the_file() {
|
||||||
|
let mut file = File::default();
|
||||||
|
file.info.name = "file".into();
|
||||||
|
file.rte.push(crate::Route::default());
|
||||||
|
let text = written_text(&file, &Default::default(), ExportOptions::ALL);
|
||||||
|
assert_eq!(count(&text, "<rte>"), 1);
|
||||||
|
assert_eq!(count(&text, "<rtept"), 0);
|
||||||
|
let again = parse(text.as_bytes(), &mut Default::default()).unwrap();
|
||||||
|
assert_eq!(again.rte.len(), 1);
|
||||||
|
assert_eq!(again.rte[0].info.name.as_deref(), Some("file"));
|
||||||
|
|
||||||
|
// not when there are others
|
||||||
|
file.trk.push(Track::default());
|
||||||
|
let text = written_text(&file, &Default::default(), ExportOptions::ALL);
|
||||||
|
// the metadata only
|
||||||
|
assert_eq!(count(&text, "<name>file</name>"), 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_route_points_keep_their_data_and_the_options_apply_to_them() {
|
fn test_route_points_keep_their_data_and_the_options_apply_to_them() {
|
||||||
let (file, categories) = read("with_hr");
|
let (file, categories) = read("with_hr");
|
||||||
let with_all = written_text(&file, &categories, as_route());
|
let file = as_routes(file);
|
||||||
|
let with_all = written_text(&file, &categories, ExportOptions::ALL);
|
||||||
assert!(with_all.contains("<gpxtpx:hr>"));
|
assert!(with_all.contains("<gpxtpx:hr>"));
|
||||||
let without = written_text(
|
let without = written_text(
|
||||||
&file,
|
&file,
|
||||||
@@ -745,22 +794,10 @@ mod tests {
|
|||||||
ExportOptions {
|
ExportOptions {
|
||||||
hr: false,
|
hr: false,
|
||||||
time: false,
|
time: false,
|
||||||
as_route: true,
|
|
||||||
..ExportOptions::ALL
|
..ExportOptions::ALL
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
assert!(!without.contains("<gpxtpx:hr>"));
|
assert!(!without.contains("<gpxtpx:hr>"));
|
||||||
assert!(!without.contains("<time>"));
|
assert!(!without.contains("<time>"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_the_route_option_is_not_data() {
|
|
||||||
let (file, _) = read("with_route_points");
|
|
||||||
assert!(!file.exportable_data().as_route);
|
|
||||||
// it is a way to write the data, never part of them
|
|
||||||
let all = std::hint::black_box(ExportOptions::ALL);
|
|
||||||
assert!(!all.as_route && !ExportOptions::NONE.as_route);
|
|
||||||
assert!(as_route().union(ExportOptions::NONE).as_route);
|
|
||||||
assert!(!ExportOptions::ALL.union(ExportOptions::NONE).as_route);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
use std::{collections::HashSet, rc::Rc};
|
||||||
|
|
||||||
|
use crate::{Apply, CommandError, FileId, Route, Selection, State, Track};
|
||||||
|
|
||||||
|
/// Converts the selected routes to tracks, or the selected tracks or segments to routes, in their
|
||||||
|
/// file:
|
||||||
|
///
|
||||||
|
/// - a route becomes a track with its segment. The new tracks go before the other tracks, right
|
||||||
|
/// after the routes;
|
||||||
|
/// - a track becomes one route per segment, as a route has a single segment, and goes away. A
|
||||||
|
/// selected segment becomes a route and leaves its track, which stays even if it has no segment
|
||||||
|
/// left. The routes have the information of their track, and go after the other routes;
|
||||||
|
/// - a file with routes only has all of them converted to tracks, and a file with tracks only
|
||||||
|
/// has all of them converted to routes. The files with both, or neither, stay as they are.
|
||||||
|
///
|
||||||
|
/// The segments keep their ids, the new routes and tracks are selected (the files stay selected).
|
||||||
|
/// There is nothing to do for the other selections, or for tracks without segments.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Convert;
|
||||||
|
|
||||||
|
impl Apply for Convert {
|
||||||
|
fn apply(self, state: &mut State) -> Result<(), CommandError> {
|
||||||
|
let selection = state.selection.clone();
|
||||||
|
let next = match &selection {
|
||||||
|
Selection::Route { file_id, rte_ids } => {
|
||||||
|
let file = Rc::make_mut(
|
||||||
|
state
|
||||||
|
.files
|
||||||
|
.get_mut(file_id)
|
||||||
|
.ok_or(CommandError::NothingToDo)?,
|
||||||
|
);
|
||||||
|
let (converted, kept) = std::mem::take(&mut file.rte)
|
||||||
|
.into_iter()
|
||||||
|
.partition::<Vec<_>, _>(|rte| rte_ids.contains(&rte.id));
|
||||||
|
file.rte = kept;
|
||||||
|
let tracks = to_tracks(converted);
|
||||||
|
let trk_ids: HashSet<_> = tracks.iter().map(|trk| trk.id).collect();
|
||||||
|
file.trk.splice(0..0, tracks);
|
||||||
|
Selection::Track {
|
||||||
|
file_id: *file_id,
|
||||||
|
trk_ids,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Selection::Track { file_id, trk_ids } => {
|
||||||
|
let file = Rc::make_mut(
|
||||||
|
state
|
||||||
|
.files
|
||||||
|
.get_mut(file_id)
|
||||||
|
.ok_or(CommandError::NothingToDo)?,
|
||||||
|
);
|
||||||
|
let (converted, kept) = std::mem::take(&mut file.trk)
|
||||||
|
.into_iter()
|
||||||
|
.partition::<Vec<_>, _>(|trk| trk_ids.contains(&trk.id));
|
||||||
|
file.trk = kept;
|
||||||
|
add_routes(&mut file.rte, *file_id, to_routes(converted))
|
||||||
|
}
|
||||||
|
Selection::TrackSegment {
|
||||||
|
file_id,
|
||||||
|
trk_id,
|
||||||
|
trkseg_ids,
|
||||||
|
} => {
|
||||||
|
let file = Rc::make_mut(
|
||||||
|
state
|
||||||
|
.files
|
||||||
|
.get_mut(file_id)
|
||||||
|
.ok_or(CommandError::NothingToDo)?,
|
||||||
|
);
|
||||||
|
let trk = file
|
||||||
|
.trk
|
||||||
|
.iter_mut()
|
||||||
|
.find(|trk| trk.id == *trk_id)
|
||||||
|
.ok_or(CommandError::NothingToDo)?;
|
||||||
|
let (converted, kept) = std::mem::take(&mut trk.trkseg)
|
||||||
|
.into_iter()
|
||||||
|
.partition::<Vec<_>, _>(|seg| trkseg_ids.contains(&seg.id));
|
||||||
|
trk.trkseg = kept;
|
||||||
|
let info = trk.info.clone();
|
||||||
|
let routes = converted.into_iter().map(|seg| Route {
|
||||||
|
id: Default::default(),
|
||||||
|
info: info.clone(),
|
||||||
|
seg,
|
||||||
|
});
|
||||||
|
add_routes(&mut file.rte, *file_id, routes)
|
||||||
|
}
|
||||||
|
Selection::File { file_ids } => {
|
||||||
|
let mut converted = false;
|
||||||
|
for file_id in file_ids {
|
||||||
|
let Some(file) = state.files.get_mut(file_id) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
if !file.rte.is_empty() && file.trk.is_empty() {
|
||||||
|
let file = Rc::make_mut(file);
|
||||||
|
file.trk = to_tracks(std::mem::take(&mut file.rte));
|
||||||
|
} else if file.rte.is_empty()
|
||||||
|
&& file.trk.iter().any(|trk| !trk.trkseg.is_empty())
|
||||||
|
{
|
||||||
|
let file = Rc::make_mut(file);
|
||||||
|
file.rte = to_routes(std::mem::take(&mut file.trk)).collect();
|
||||||
|
} else {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
converted = true;
|
||||||
|
}
|
||||||
|
return if converted {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(CommandError::NothingToDo)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
Selection::Empty | Selection::Waypoints { .. } | Selection::Waypoint { .. } => {
|
||||||
|
return Err(CommandError::NothingToDo);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let empty = match &next {
|
||||||
|
Selection::Route { rte_ids, .. } => rte_ids.is_empty(),
|
||||||
|
Selection::Track { trk_ids, .. } => trk_ids.is_empty(),
|
||||||
|
_ => true,
|
||||||
|
};
|
||||||
|
if empty {
|
||||||
|
// nothing was converted (the changed copy of the file is dropped)
|
||||||
|
return Err(CommandError::NothingToDo);
|
||||||
|
}
|
||||||
|
*state.selection = next;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The tracks of the routes, each with the segment of its route.
|
||||||
|
fn to_tracks(routes: Vec<Route>) -> Vec<Track> {
|
||||||
|
routes
|
||||||
|
.into_iter()
|
||||||
|
.map(|rte| Track {
|
||||||
|
id: Default::default(),
|
||||||
|
info: rte.info,
|
||||||
|
trkseg: vec![rte.seg],
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The routes of the tracks, one per segment, each with the information of its track.
|
||||||
|
fn to_routes(tracks: Vec<Track>) -> impl Iterator<Item = Route> {
|
||||||
|
tracks.into_iter().flat_map(|trk| {
|
||||||
|
trk.trkseg.into_iter().map(move |seg| Route {
|
||||||
|
id: Default::default(),
|
||||||
|
info: trk.info.clone(),
|
||||||
|
seg,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Adds the routes after the other routes, and gives the selection of them.
|
||||||
|
fn add_routes(
|
||||||
|
rte: &mut Vec<Route>,
|
||||||
|
file_id: FileId,
|
||||||
|
routes: impl Iterator<Item = Route>,
|
||||||
|
) -> Selection {
|
||||||
|
let start = rte.len();
|
||||||
|
rte.extend(routes);
|
||||||
|
Selection::Route {
|
||||||
|
file_id,
|
||||||
|
rte_ids: rte[start..].iter().map(|rte| rte.id).collect(),
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,6 @@
|
|||||||
use crate::{Apply, CommandError, Edit, Editor, File, State, Track, update_selected};
|
use crate::{
|
||||||
|
Apply, CommandError, Edit, Editor, File, Route, State, Track, TrackInfo, update_selected,
|
||||||
|
};
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct Metadata<'a> {
|
pub struct Metadata<'a> {
|
||||||
@@ -13,21 +15,33 @@ impl Apply for Metadata<'_> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Metadata<'_> {
|
||||||
|
fn set(&self, info: &mut TrackInfo) -> Edit {
|
||||||
|
info.name = Some(self.name.to_owned());
|
||||||
|
info.desc = Some(self.desc.to_owned());
|
||||||
|
Edit::Changed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl Editor for Metadata<'_> {
|
impl Editor for Metadata<'_> {
|
||||||
fn file(&mut self, file: &mut File) -> Edit {
|
fn file(&mut self, file: &mut File) -> Edit {
|
||||||
file.info.name = self.name.to_owned();
|
file.info.name = self.name.to_owned();
|
||||||
file.info.desc = Some(self.desc.to_owned());
|
file.info.desc = Some(self.desc.to_owned());
|
||||||
// a single track is named like the file
|
// a single route or track is named like the file
|
||||||
if let [track] = file.trk.as_mut_slice() {
|
match (file.rte.as_mut_slice(), file.trk.as_mut_slice()) {
|
||||||
track.info.name = Some(self.name.to_owned());
|
([route], []) => route.info.name = Some(self.name.to_owned()),
|
||||||
|
([], [track]) => track.info.name = Some(self.name.to_owned()),
|
||||||
|
_ => {}
|
||||||
}
|
}
|
||||||
Edit::Changed
|
Edit::Changed
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn route(&mut self, route: &mut Route) -> Edit {
|
||||||
|
self.set(&mut route.info)
|
||||||
|
}
|
||||||
|
|
||||||
fn track(&mut self, track: &mut Track) -> Edit {
|
fn track(&mut self, track: &mut Track) -> Edit {
|
||||||
track.info.name = Some(self.name.to_owned());
|
self.set(&mut track.info)
|
||||||
track.info.desc = Some(self.desc.to_owned());
|
|
||||||
Edit::Changed
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -45,12 +59,14 @@ mod tests {
|
|||||||
New {
|
New {
|
||||||
name: "first",
|
name: "first",
|
||||||
trackpoint: None,
|
trackpoint: None,
|
||||||
|
route: false,
|
||||||
}
|
}
|
||||||
.apply(&mut fx.state())
|
.apply(&mut fx.state())
|
||||||
.unwrap();
|
.unwrap();
|
||||||
New {
|
New {
|
||||||
name: "second",
|
name: "second",
|
||||||
trackpoint: None,
|
trackpoint: None,
|
||||||
|
route: false,
|
||||||
}
|
}
|
||||||
.apply(&mut fx.state())
|
.apply(&mut fx.state())
|
||||||
.unwrap(); // now selected
|
.unwrap(); // now selected
|
||||||
@@ -108,6 +124,7 @@ mod tests {
|
|||||||
New {
|
New {
|
||||||
name: "file",
|
name: "file",
|
||||||
trackpoint: None,
|
trackpoint: None,
|
||||||
|
route: false,
|
||||||
}
|
}
|
||||||
.apply(&mut fx.state())
|
.apply(&mut fx.state())
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|||||||
@@ -1,9 +1,13 @@
|
|||||||
|
mod convert;
|
||||||
mod metadata;
|
mod metadata;
|
||||||
|
mod new_route;
|
||||||
mod new_track;
|
mod new_track;
|
||||||
mod new_track_segment;
|
mod new_track_segment;
|
||||||
mod style;
|
mod style;
|
||||||
|
|
||||||
|
pub use convert::*;
|
||||||
pub use metadata::*;
|
pub use metadata::*;
|
||||||
|
pub use new_route::*;
|
||||||
pub use new_track::*;
|
pub use new_track::*;
|
||||||
pub use new_track_segment::*;
|
pub use new_track_segment::*;
|
||||||
pub use style::*;
|
pub use style::*;
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
use crate::{Apply, CommandError, Edit, Editor, File, Route, State, update_selected};
|
||||||
|
|
||||||
|
use super::new_track::common_style;
|
||||||
|
|
||||||
|
/// Adds an empty route to the selected files, with the style that their routes and tracks agree
|
||||||
|
/// on (see [`crate::NewTrack`]).
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct NewRoute;
|
||||||
|
|
||||||
|
impl Apply for NewRoute {
|
||||||
|
fn apply(mut self, state: &mut State) -> Result<(), CommandError> {
|
||||||
|
update_selected(state, &mut self);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Editor for NewRoute {
|
||||||
|
fn file(&mut self, file: &mut File) -> Edit {
|
||||||
|
file.rte.push(Route {
|
||||||
|
info: common_style(file),
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
Edit::Changed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use crate::{New, engine::command::fixture::Fixture};
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_new_route_has_the_style_of_the_tracks_and_an_empty_segment() {
|
||||||
|
let mut fx = Fixture::default();
|
||||||
|
New {
|
||||||
|
name: "file",
|
||||||
|
trackpoint: None,
|
||||||
|
route: false,
|
||||||
|
}
|
||||||
|
.apply(&mut fx.state())
|
||||||
|
.unwrap();
|
||||||
|
crate::NewTrack.apply(&mut fx.state()).unwrap();
|
||||||
|
let file = std::rc::Rc::make_mut(fx.files.values_mut().next().unwrap());
|
||||||
|
file.trk[0].info.color = Some("ff0000".into());
|
||||||
|
NewRoute.apply(&mut fx.state()).unwrap();
|
||||||
|
NewRoute.apply(&mut fx.state()).unwrap();
|
||||||
|
|
||||||
|
let file = fx.files.values().next().unwrap();
|
||||||
|
assert_eq!(file.rte.len(), 2);
|
||||||
|
assert_ne!(file.rte[0].id, file.rte[1].id);
|
||||||
|
assert!(file.rte[0].seg.is_empty());
|
||||||
|
assert_eq!(file.rte[1].info.color.as_deref(), Some("ff0000"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
use crate::{Apply, CommandError, Edit, Editor, File, State, Track, update_selected};
|
use crate::{Apply, CommandError, Edit, Editor, File, State, Track, TrackInfo, update_selected};
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct NewTrack;
|
pub struct NewTrack;
|
||||||
@@ -12,20 +12,41 @@ impl Apply for NewTrack {
|
|||||||
|
|
||||||
impl Editor for NewTrack {
|
impl Editor for NewTrack {
|
||||||
fn file(&mut self, file: &mut File) -> Edit {
|
fn file(&mut self, file: &mut File) -> Edit {
|
||||||
let mut track = Track::default();
|
file.trk.push(Track {
|
||||||
track.info.color = common(file, |t| &t.info.color);
|
info: common_style(file),
|
||||||
track.info.opacity = common(file, |t| &t.info.opacity);
|
..Default::default()
|
||||||
track.info.width = common(file, |t| &t.info.width);
|
});
|
||||||
file.trk.push(track);
|
|
||||||
Edit::Changed
|
Edit::Changed
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the value of a style attribute if all existing tracks agree on it.
|
/// The style that all the routes and tracks of the file agree on: each attribute is set if they
|
||||||
fn common<T: Clone + PartialEq>(file: &File, get: impl Fn(&Track) -> &Option<T>) -> Option<T> {
|
/// all have the same value for it.
|
||||||
let mut tracks = file.trk.iter();
|
pub(super) fn common_style(file: &File) -> TrackInfo {
|
||||||
let first = get(tracks.next()?);
|
let infos: Vec<&TrackInfo> = file
|
||||||
tracks.all(|t| get(t) == first).then(|| first.clone())?
|
.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())?
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
@@ -40,6 +61,7 @@ mod tests {
|
|||||||
New {
|
New {
|
||||||
name: "file",
|
name: "file",
|
||||||
trackpoint: None,
|
trackpoint: None,
|
||||||
|
route: false,
|
||||||
}
|
}
|
||||||
.apply(&mut fx.state())
|
.apply(&mut fx.state())
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@@ -56,6 +78,7 @@ mod tests {
|
|||||||
New {
|
New {
|
||||||
name: "file",
|
name: "file",
|
||||||
trackpoint: None,
|
trackpoint: None,
|
||||||
|
route: false,
|
||||||
}
|
}
|
||||||
.apply(&mut fx.state())
|
.apply(&mut fx.state())
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ mod tests {
|
|||||||
New {
|
New {
|
||||||
name: "file",
|
name: "file",
|
||||||
trackpoint: None,
|
trackpoint: None,
|
||||||
|
route: false,
|
||||||
}
|
}
|
||||||
.apply(&mut fx.state())
|
.apply(&mut fx.state())
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use crate::{Apply, CommandError, Edit, Editor, State, Track, update_selected};
|
use crate::{Apply, CommandError, Edit, Editor, Route, State, Track, TrackInfo, update_selected};
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct Style<'a> {
|
pub struct Style<'a> {
|
||||||
@@ -14,21 +14,31 @@ impl Apply for Style<'_> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Editor for Style<'_> {
|
impl Style<'_> {
|
||||||
fn track(&mut self, track: &mut Track) -> Edit {
|
fn set(&self, info: &mut TrackInfo) -> Edit {
|
||||||
if let Some(color) = self.color {
|
if let Some(color) = self.color {
|
||||||
track.info.color = Some(color.to_owned());
|
info.color = Some(color.to_owned());
|
||||||
}
|
}
|
||||||
if self.opacity.is_some() {
|
if self.opacity.is_some() {
|
||||||
track.info.opacity = self.opacity;
|
info.opacity = self.opacity;
|
||||||
}
|
}
|
||||||
if self.width.is_some() {
|
if self.width.is_some() {
|
||||||
track.info.width = self.width;
|
info.width = self.width;
|
||||||
}
|
}
|
||||||
Edit::Changed
|
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)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use std::collections::HashSet;
|
use std::collections::HashSet;
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ use std::rc::Rc;
|
|||||||
use crate::{Apply, CommandError, FileId, Files, Selection, State, Waypoint};
|
use crate::{Apply, CommandError, FileId, Files, Selection, State, Waypoint};
|
||||||
|
|
||||||
/// Deletes the selected elements. With `whole_files`, the files holding the selected elements
|
/// 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.
|
/// are deleted instead, even if only a route, a track or a waypoint is selected.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct Delete {
|
pub struct Delete {
|
||||||
pub whole_files: bool,
|
pub whole_files: bool,
|
||||||
@@ -23,6 +23,21 @@ impl Apply for Delete {
|
|||||||
state.order.0.retain(|id| !file_ids.contains(id));
|
state.order.0.retain(|id| !file_ids.contains(id));
|
||||||
Selection::Empty
|
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 } => {
|
Selection::Track { file_id, trk_ids } => {
|
||||||
let file = state
|
let file = state
|
||||||
.files
|
.files
|
||||||
@@ -131,6 +146,7 @@ mod tests {
|
|||||||
crate::New {
|
crate::New {
|
||||||
name: "keep",
|
name: "keep",
|
||||||
trackpoint: None,
|
trackpoint: None,
|
||||||
|
route: false,
|
||||||
}
|
}
|
||||||
.apply(&mut fx.state())
|
.apply(&mut fx.state())
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@@ -265,6 +281,7 @@ mod tests {
|
|||||||
crate::New {
|
crate::New {
|
||||||
name: "keep",
|
name: "keep",
|
||||||
trackpoint: None,
|
trackpoint: None,
|
||||||
|
route: false,
|
||||||
}
|
}
|
||||||
.apply(&mut fx.state())
|
.apply(&mut fx.state())
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|||||||
@@ -31,12 +31,14 @@ mod tests {
|
|||||||
crate::New {
|
crate::New {
|
||||||
name: "a",
|
name: "a",
|
||||||
trackpoint: None,
|
trackpoint: None,
|
||||||
|
route: false,
|
||||||
}
|
}
|
||||||
.apply(&mut fx.state())
|
.apply(&mut fx.state())
|
||||||
.unwrap();
|
.unwrap();
|
||||||
crate::New {
|
crate::New {
|
||||||
name: "b",
|
name: "b",
|
||||||
trackpoint: None,
|
trackpoint: None,
|
||||||
|
route: false,
|
||||||
}
|
}
|
||||||
.apply(&mut fx.state())
|
.apply(&mut fx.state())
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
use std::{collections::HashSet, rc::Rc};
|
use std::{collections::HashSet, rc::Rc};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
Apply, CommandError, FileId, Files, Selection, State, Waypoint, copy_file, copy_segment,
|
Apply, CommandError, FileId, Files, Selection, State, Waypoint, copy_file, copy_route,
|
||||||
copy_track, copy_waypoint,
|
copy_segment, copy_track, copy_waypoint,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
@@ -35,6 +35,30 @@ impl Apply for Duplicate {
|
|||||||
state.order.0.splice(at..at, order);
|
state.order.0.splice(at..at, order);
|
||||||
Selection::File { file_ids: copies }
|
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 } => {
|
Selection::Track { file_id, trk_ids } => {
|
||||||
let file = state
|
let file = state
|
||||||
.files
|
.files
|
||||||
@@ -193,6 +217,7 @@ mod tests {
|
|||||||
crate::New {
|
crate::New {
|
||||||
name,
|
name,
|
||||||
trackpoint: None,
|
trackpoint: None,
|
||||||
|
route: false,
|
||||||
}
|
}
|
||||||
.apply(&mut fx.state())
|
.apply(&mut fx.state())
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|||||||
@@ -85,6 +85,7 @@ mod tests {
|
|||||||
crate::New {
|
crate::New {
|
||||||
name: "keep",
|
name: "keep",
|
||||||
trackpoint: None,
|
trackpoint: None,
|
||||||
|
route: false,
|
||||||
}
|
}
|
||||||
.apply(&mut fx.state())
|
.apply(&mut fx.state())
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@@ -140,6 +141,7 @@ mod tests {
|
|||||||
crate::New {
|
crate::New {
|
||||||
name: "before",
|
name: "before",
|
||||||
trackpoint: None,
|
trackpoint: None,
|
||||||
|
route: false,
|
||||||
}
|
}
|
||||||
.apply(&mut fx.state())
|
.apply(&mut fx.state())
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@@ -189,6 +191,7 @@ mod tests {
|
|||||||
crate::New {
|
crate::New {
|
||||||
name: "keep",
|
name: "keep",
|
||||||
trackpoint: None,
|
trackpoint: None,
|
||||||
|
route: false,
|
||||||
}
|
}
|
||||||
.apply(&mut fx.state())
|
.apply(&mut fx.state())
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ use crate::{
|
|||||||
pub enum MoveTarget {
|
pub enum MoveTarget {
|
||||||
/// The list of files.
|
/// The list of files.
|
||||||
Files { index: usize },
|
Files { index: usize },
|
||||||
|
/// The routes of a file.
|
||||||
|
Routes { file_id: FileId, index: usize },
|
||||||
/// The tracks of a file.
|
/// The tracks of a file.
|
||||||
Tracks { file_id: FileId, index: usize },
|
Tracks { file_id: FileId, index: usize },
|
||||||
/// The segments of a track.
|
/// The segments of a track.
|
||||||
@@ -26,9 +28,10 @@ pub enum MoveTarget {
|
|||||||
///
|
///
|
||||||
/// What can go where:
|
/// What can go where:
|
||||||
/// - files: among the files;
|
/// - files: among the files;
|
||||||
/// - tracks: among the files (each track becomes a file), or among the tracks of a file;
|
/// - routes and tracks: among the files (each one becomes a file), or among the routes or the
|
||||||
/// - segments: among the files (each segment becomes a file), among the tracks of a file (each
|
/// tracks of a file, where they keep their kind (see [`Destination`]);
|
||||||
/// segment becomes a track), or among the segments of a track;
|
/// - segments: among the files (each segment becomes a file), among the routes or the tracks of a
|
||||||
|
/// file (each segment becomes a route or a track), or among the segments of a track;
|
||||||
/// - waypoints, or all the waypoints of a file (the waypoints node): among the waypoints of a
|
/// - waypoints, or all the waypoints of a file (the waypoints node): among the waypoints of a
|
||||||
/// file.
|
/// file.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
@@ -41,6 +44,9 @@ impl From<MoveTarget> for Destination {
|
|||||||
fn from(target: MoveTarget) -> Self {
|
fn from(target: MoveTarget) -> Self {
|
||||||
match target {
|
match target {
|
||||||
MoveTarget::Files { index } => Destination::Files(Place::Index(index)),
|
MoveTarget::Files { index } => Destination::Files(Place::Index(index)),
|
||||||
|
MoveTarget::Routes { file_id, index } => {
|
||||||
|
Destination::Routes(file_id, Place::Index(index))
|
||||||
|
}
|
||||||
MoveTarget::Tracks { file_id, index } => {
|
MoveTarget::Tracks { file_id, index } => {
|
||||||
Destination::Tracks(file_id, Place::Index(index))
|
Destination::Tracks(file_id, Place::Index(index))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,16 @@
|
|||||||
use crate::{Apply, CommandError, File, LngLat, State, Track, TrackSegment, Trackpoint, produce};
|
use crate::{
|
||||||
|
Apply, CommandError, File, LngLat, Route, State, Track, TrackSegment, Trackpoint, produce,
|
||||||
|
};
|
||||||
|
|
||||||
/// Creates an empty file and selects it. With a `trackpoint`, the file starts with a track and a
|
/// Creates an empty file and selects it. With `route`, the file starts with a route, which is
|
||||||
/// segment that hold it: it is how the routing tool starts a route on an empty map, in a single
|
/// empty. With a `trackpoint`, the file starts with a segment that holds it, the one of its route
|
||||||
/// undo step.
|
/// with `route` or of a track otherwise: it is how the routing tool starts a route on an empty map,
|
||||||
|
/// in a single undo step.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct New<'a> {
|
pub struct New<'a> {
|
||||||
pub name: &'a str,
|
pub name: &'a str,
|
||||||
pub trackpoint: Option<NewTrackpoint>,
|
pub trackpoint: Option<NewTrackpoint>,
|
||||||
|
pub route: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy)]
|
#[derive(Debug, Clone, Copy)]
|
||||||
@@ -21,8 +25,8 @@ impl Apply for New<'_> {
|
|||||||
produce(state, |_| {
|
produce(state, |_| {
|
||||||
let mut file = File::default();
|
let mut file = File::default();
|
||||||
file.info.name = self.name.to_owned();
|
file.info.name = self.name.to_owned();
|
||||||
if let Some(point) = self.trackpoint {
|
|
||||||
let mut segment = TrackSegment::default();
|
let mut segment = TrackSegment::default();
|
||||||
|
if let Some(point) = self.trackpoint {
|
||||||
// the ends of a segment are anchors of the routing tool
|
// the ends of a segment are anchors of the routing tool
|
||||||
segment.splice(
|
segment.splice(
|
||||||
0,
|
0,
|
||||||
@@ -36,6 +40,13 @@ impl Apply for New<'_> {
|
|||||||
..Default::default()
|
..Default::default()
|
||||||
}],
|
}],
|
||||||
);
|
);
|
||||||
|
}
|
||||||
|
if self.route {
|
||||||
|
file.rte.push(Route {
|
||||||
|
seg: segment,
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
} else if self.trackpoint.is_some() {
|
||||||
file.trk.push(Track {
|
file.trk.push(Track {
|
||||||
trkseg: vec![segment],
|
trkseg: vec![segment],
|
||||||
..Default::default()
|
..Default::default()
|
||||||
@@ -59,7 +70,8 @@ mod tests {
|
|||||||
assert!(
|
assert!(
|
||||||
New {
|
New {
|
||||||
name: "new",
|
name: "new",
|
||||||
trackpoint: None
|
trackpoint: None,
|
||||||
|
route: false,
|
||||||
}
|
}
|
||||||
.apply(&mut fx.state())
|
.apply(&mut fx.state())
|
||||||
.is_ok()
|
.is_ok()
|
||||||
@@ -83,6 +95,7 @@ mod tests {
|
|||||||
New {
|
New {
|
||||||
name: "new",
|
name: "new",
|
||||||
trackpoint: Some(point),
|
trackpoint: Some(point),
|
||||||
|
route: false,
|
||||||
}
|
}
|
||||||
.apply(&mut fx.state())
|
.apply(&mut fx.state())
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@@ -98,4 +111,38 @@ mod tests {
|
|||||||
assert_eq!(segment[0].anchor, Some(0));
|
assert_eq!(segment[0].anchor, Some(0));
|
||||||
assert_eq!(fx.selected_files(), [file.id].into());
|
assert_eq!(fx.selected_files(), [file.id].into());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_new_with_a_route() {
|
||||||
|
let mut fx = Fixture::default();
|
||||||
|
New {
|
||||||
|
name: "new",
|
||||||
|
trackpoint: None,
|
||||||
|
route: true,
|
||||||
|
}
|
||||||
|
.apply(&mut fx.state())
|
||||||
|
.unwrap();
|
||||||
|
let file = fx.files.values().next().unwrap();
|
||||||
|
assert_eq!((file.rte.len(), file.trk.len()), (1, 0));
|
||||||
|
assert!(file.rte[0].seg.is_empty());
|
||||||
|
assert_eq!(fx.selected_files(), [file.id].into());
|
||||||
|
|
||||||
|
// the trackpoint goes to the route
|
||||||
|
let mut fx = Fixture::default();
|
||||||
|
New {
|
||||||
|
name: "new",
|
||||||
|
trackpoint: Some(NewTrackpoint {
|
||||||
|
lng: 1.0,
|
||||||
|
lat: 2.0,
|
||||||
|
ele: 3.0,
|
||||||
|
}),
|
||||||
|
route: true,
|
||||||
|
}
|
||||||
|
.apply(&mut fx.state())
|
||||||
|
.unwrap();
|
||||||
|
let file = fx.files.values().next().unwrap();
|
||||||
|
assert_eq!((file.rte.len(), file.trk.len()), (1, 0));
|
||||||
|
assert_eq!(file.rte[0].seg.len(), 1);
|
||||||
|
assert_eq!(file.rte[0].seg[0].anchor, Some(0));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,18 +1,21 @@
|
|||||||
use std::{collections::HashSet, hash::Hash};
|
use std::{collections::HashSet, hash::Hash};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
Apply, ClipboardContent, CommandError, Destination, FileId, Place, Selection, State, TrackId,
|
Apply, ClipboardContent, CommandError, Destination, FileId, Place, RouteId, Selection, State,
|
||||||
TrackSegmentId, WaypointId, transfer, waypoint_ids,
|
TrackId, TrackSegmentId, WaypointId, transfer, waypoint_ids,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Pastes what was copied or cut (see [`crate::Clipboard`]).
|
/// Pastes what was copied or cut (see [`crate::Clipboard`]).
|
||||||
///
|
///
|
||||||
/// Where it goes depends on the selection, see [`crate::Clipboard::can_paste`]:
|
/// Where it goes depends on the selection, see [`crate::Clipboard::can_paste`]:
|
||||||
/// - nothing selected: the files are copied, and tracks and segments become new files (named
|
/// - nothing selected: the files are copied, and routes, tracks and segments become new files
|
||||||
/// like their track, or like the file they come from);
|
/// (named like their route or track, or like the file they come from);
|
||||||
/// - a file: the tracks are added to it, segments become new tracks in it, and the waypoints are
|
/// - a file: the routes and tracks are added to it, segments become new tracks in it, and the
|
||||||
/// added to its own;
|
/// waypoints are added to its own;
|
||||||
/// - a track: the segments are added to it, tracks go after it in its file;
|
/// - a route: routes, and segments as new routes, go after it in its file, tracks go before the
|
||||||
|
/// other tracks (right after the routes);
|
||||||
|
/// - a track: the segments are added to it, tracks go after it in its file, and routes after the
|
||||||
|
/// other routes;
|
||||||
/// - a segment: the segments go after it in its track;
|
/// - a segment: the segments go after it in its track;
|
||||||
/// - the waypoints or a waypoint: the waypoints are added to their file, after the waypoint.
|
/// - the waypoints or a waypoint: the waypoints are added to their file, after the waypoint.
|
||||||
///
|
///
|
||||||
@@ -46,6 +49,14 @@ impl Apply for Paste {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn route_ids_of(state: &State, file_id: FileId) -> Vec<RouteId> {
|
||||||
|
state
|
||||||
|
.files
|
||||||
|
.get(&file_id)
|
||||||
|
.map(|file| file.rte.iter().map(|rte| rte.id).collect())
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
fn track_ids_of(state: &State, file_id: FileId) -> Vec<TrackId> {
|
fn track_ids_of(state: &State, file_id: FileId) -> Vec<TrackId> {
|
||||||
state
|
state
|
||||||
.files
|
.files
|
||||||
@@ -79,14 +90,34 @@ fn destination(state: &State, content: &ClipboardContent) -> Result<Destination,
|
|||||||
};
|
};
|
||||||
Ok(match (content, &*state.selection) {
|
Ok(match (content, &*state.selection) {
|
||||||
(ClipboardContent::Files(_), _) => Destination::Files(Place::End),
|
(ClipboardContent::Files(_), _) => Destination::Files(Place::End),
|
||||||
(ClipboardContent::Tracks(_) | ClipboardContent::Segments(_), Selection::Empty) => {
|
(
|
||||||
Destination::Files(Place::End)
|
ClipboardContent::Routes(_)
|
||||||
|
| ClipboardContent::Tracks(_)
|
||||||
|
| ClipboardContent::Segments(_),
|
||||||
|
Selection::Empty,
|
||||||
|
) => Destination::Files(Place::End),
|
||||||
|
(ClipboardContent::Routes(_), Selection::File { file_ids }) => {
|
||||||
|
Destination::Routes(last_file(file_ids)?, Place::End)
|
||||||
|
}
|
||||||
|
// routes and tracks keep their kind (see `Destination`)
|
||||||
|
(
|
||||||
|
ClipboardContent::Routes(_)
|
||||||
|
| ClipboardContent::Tracks(_)
|
||||||
|
| ClipboardContent::Segments(_),
|
||||||
|
Selection::Route { file_id, rte_ids },
|
||||||
|
) => {
|
||||||
|
let last =
|
||||||
|
last_selected(route_ids_of(state, *file_id).into_iter(), rte_ids).ok_or(nothing)?;
|
||||||
|
Destination::Routes(*file_id, Place::After(last))
|
||||||
}
|
}
|
||||||
(
|
(
|
||||||
ClipboardContent::Tracks(_) | ClipboardContent::Segments(_),
|
ClipboardContent::Tracks(_) | ClipboardContent::Segments(_),
|
||||||
Selection::File { file_ids },
|
Selection::File { file_ids },
|
||||||
) => Destination::Tracks(last_file(file_ids)?, Place::End),
|
) => Destination::Tracks(last_file(file_ids)?, Place::End),
|
||||||
(ClipboardContent::Tracks(_), Selection::Track { file_id, trk_ids }) => {
|
(
|
||||||
|
ClipboardContent::Routes(_) | ClipboardContent::Tracks(_),
|
||||||
|
Selection::Track { file_id, trk_ids },
|
||||||
|
) => {
|
||||||
let last =
|
let last =
|
||||||
last_selected(track_ids_of(state, *file_id).into_iter(), trk_ids).ok_or(nothing)?;
|
last_selected(track_ids_of(state, *file_id).into_iter(), trk_ids).ok_or(nothing)?;
|
||||||
Destination::Tracks(*file_id, Place::After(last))
|
Destination::Tracks(*file_id, Place::After(last))
|
||||||
|
|||||||
@@ -7,8 +7,8 @@ use crate::{Apply, CommandError, FileId, Load, State};
|
|||||||
pub struct ExternalFile<'a> {
|
pub struct ExternalFile<'a> {
|
||||||
pub id: FileId,
|
pub id: FileId,
|
||||||
pub data: &'a [u8],
|
pub data: &'a [u8],
|
||||||
/// Name of the file outside (the name of the file on the disk, without its extension), which
|
/// Name of the file when the data has none (the name of the file on the disk, without its
|
||||||
/// is its name here whatever the data says: a file has a single name.
|
/// extension).
|
||||||
pub name: &'a str,
|
pub name: &'a str,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -16,8 +16,7 @@ pub struct ExternalFile<'a> {
|
|||||||
/// that are given replace the ones of the same id (which stay where they are in the order, and keep
|
/// that are given replace the ones of the same id (which stay where they are in the order, and keep
|
||||||
/// their id), or are added at the end if there are none; the ones to `remove` are deleted.
|
/// their id), or are added at the end if there are none; the ones to `remove` are deleted.
|
||||||
///
|
///
|
||||||
/// Unlike [`crate::LoadFiles`], the files are named as they are outside (see [`ExternalFile`]), and
|
/// Unlike [`crate::LoadFiles`], the selection is left alone (what it holds of a file that was
|
||||||
/// the selection is left alone (what it holds of a file that was
|
|
||||||
/// replaced or deleted is dropped by the engine afterwards, as with any edit).
|
/// replaced or deleted is dropped by the engine afterwards, as with any edit).
|
||||||
///
|
///
|
||||||
/// The files that cannot be read are skipped, and the files that are here stay as they are. It is an
|
/// The files that cannot be read are skipped, and the files that are here stay as they are. It is an
|
||||||
@@ -40,9 +39,6 @@ impl Apply for SyncFiles<'_> {
|
|||||||
match load.parse(state.categories) {
|
match load.parse(state.categories) {
|
||||||
Ok(mut file) => {
|
Ok(mut file) => {
|
||||||
file.id = external.id;
|
file.id = external.id;
|
||||||
if !external.name.trim().is_empty() {
|
|
||||||
file.info.name = external.name.to_owned();
|
|
||||||
}
|
|
||||||
if state.files.insert(external.id, Rc::new(file)).is_none() {
|
if state.files.insert(external.id, Rc::new(file)).is_none() {
|
||||||
state.order.0.push(external.id);
|
state.order.0.push(external.id);
|
||||||
}
|
}
|
||||||
@@ -80,6 +76,7 @@ mod tests {
|
|||||||
New {
|
New {
|
||||||
name,
|
name,
|
||||||
trackpoint: None,
|
trackpoint: None,
|
||||||
|
route: false,
|
||||||
}
|
}
|
||||||
.apply(&mut fx.state())
|
.apply(&mut fx.state())
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@@ -106,8 +103,8 @@ mod tests {
|
|||||||
.apply(&mut fx.state())
|
.apply(&mut fx.state())
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert_eq!(fx.order.0, [first, second]);
|
assert_eq!(fx.order.0, [first, second]);
|
||||||
// named as it is outside, not as the data says
|
// named as the data says, the name outside is only for a file that has none
|
||||||
assert_eq!(fx.files[&first].info.name, "name");
|
assert_eq!(fx.files[&first].info.name, "from disk");
|
||||||
assert_eq!(fx.files[&first].id, first);
|
assert_eq!(fx.files[&first].id, first);
|
||||||
// the selection is not changed
|
// the selection is not changed
|
||||||
assert_eq!(fx.selected_files(), [second].into());
|
assert_eq!(fx.selected_files(), [second].into());
|
||||||
|
|||||||
@@ -5,9 +5,9 @@
|
|||||||
use std::{collections::HashSet, rc::Rc};
|
use std::{collections::HashSet, rc::Rc};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
ClipboardContent, ClipboardSegment, ClipboardTrack, CommandError, File, FileId, Selection,
|
ClipboardContent, ClipboardRoute, ClipboardSegment, ClipboardTrack, CommandError, File, FileId,
|
||||||
State, Track, TrackId, TrackSegment, TrackSegmentId, Waypoint, WaypointId, copy_file,
|
Route, RouteId, Selection, State, Track, TrackId, TrackSegment, TrackSegmentId, Waypoint,
|
||||||
copy_segment, copy_track, copy_waypoint,
|
WaypointId, copy_file, copy_route, copy_segment, copy_track, copy_waypoint,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Where elements are put, among the others of the same list.
|
/// Where elements are put, among the others of the same list.
|
||||||
@@ -37,15 +37,20 @@ impl<T: Copy + PartialEq> Place<T> {
|
|||||||
|
|
||||||
/// Where elements go. What can go where:
|
/// Where elements go. What can go where:
|
||||||
/// - files: among the files;
|
/// - files: among the files;
|
||||||
|
/// - routes: among the files (each route becomes a file, named like the route, or like the file
|
||||||
|
/// it comes from), or among the routes of a file. Among the tracks of a file, they stay routes,
|
||||||
|
/// which come before the tracks: they go after the other routes;
|
||||||
/// - tracks: among the files (each track becomes a file, named like the track, or like the file
|
/// - tracks: among the files (each track becomes a file, named like the track, or like the file
|
||||||
/// it comes from), or among the tracks of a file;
|
/// it comes from), or among the tracks of a file. Among the routes of a file, they stay tracks,
|
||||||
|
/// which come after the routes: they go before the other tracks;
|
||||||
/// - segments: among the files (each segment becomes a file with a track, named like its track,
|
/// - segments: among the files (each segment becomes a file with a track, named like its track,
|
||||||
/// or like its file), among the tracks of a file (each segment becomes a track), or among the
|
/// or like its file), among the routes or the tracks of a file (each segment becomes a route or
|
||||||
/// segments of a track;
|
/// a track), or among the segments of a track;
|
||||||
/// - waypoints: among the waypoints of a file.
|
/// - waypoints: among the waypoints of a file.
|
||||||
#[derive(Debug, Clone, Copy)]
|
#[derive(Debug, Clone, Copy)]
|
||||||
pub enum Destination {
|
pub enum Destination {
|
||||||
Files(Place<FileId>),
|
Files(Place<FileId>),
|
||||||
|
Routes(FileId, Place<RouteId>),
|
||||||
Tracks(FileId, Place<TrackId>),
|
Tracks(FileId, Place<TrackId>),
|
||||||
Segments(FileId, TrackId, Place<TrackSegmentId>),
|
Segments(FileId, TrackId, Place<TrackSegmentId>),
|
||||||
Waypoints(FileId, Place<WaypointId>),
|
Waypoints(FileId, Place<WaypointId>),
|
||||||
@@ -93,6 +98,14 @@ pub fn remove_elements(state: &mut State, content: &ClipboardContent) {
|
|||||||
state.files.retain(|id, _| !ids.contains(id));
|
state.files.retain(|id, _| !ids.contains(id));
|
||||||
state.order.0.retain(|id| !ids.contains(id));
|
state.order.0.retain(|id| !ids.contains(id));
|
||||||
}
|
}
|
||||||
|
ClipboardContent::Routes(routes) => {
|
||||||
|
let ids: HashSet<RouteId> = routes.iter().map(|rte| rte.route.id).collect();
|
||||||
|
for file in state.files.values_mut() {
|
||||||
|
if file.rte.iter().any(|rte| ids.contains(&rte.id)) {
|
||||||
|
Rc::make_mut(file).rte.retain(|rte| !ids.contains(&rte.id));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
ClipboardContent::Tracks(tracks) => {
|
ClipboardContent::Tracks(tracks) => {
|
||||||
let ids: HashSet<TrackId> = tracks.iter().map(|trk| trk.track.id).collect();
|
let ids: HashSet<TrackId> = tracks.iter().map(|trk| trk.track.id).collect();
|
||||||
for file in state.files.values_mut() {
|
for file in state.files.values_mut() {
|
||||||
@@ -141,7 +154,9 @@ pub fn transfer(
|
|||||||
// the destination has to be there, before anything is changed
|
// the destination has to be there, before anything is changed
|
||||||
let exists = match to {
|
let exists = match to {
|
||||||
Destination::Files(_) => true,
|
Destination::Files(_) => true,
|
||||||
Destination::Tracks(file_id, _) => state.files.contains_key(&file_id),
|
Destination::Routes(file_id, _) | Destination::Tracks(file_id, _) => {
|
||||||
|
state.files.contains_key(&file_id)
|
||||||
|
}
|
||||||
Destination::Segments(file_id, trk_id, _) => state
|
Destination::Segments(file_id, trk_id, _) => state
|
||||||
.files
|
.files
|
||||||
.get(&file_id)
|
.get(&file_id)
|
||||||
@@ -152,17 +167,21 @@ pub fn transfer(
|
|||||||
(content, to),
|
(content, to),
|
||||||
(ClipboardContent::Files(_), Destination::Files(_))
|
(ClipboardContent::Files(_), Destination::Files(_))
|
||||||
| (
|
| (
|
||||||
ClipboardContent::Tracks(_),
|
ClipboardContent::Routes(_) | ClipboardContent::Tracks(_),
|
||||||
Destination::Files(_) | Destination::Tracks(..)
|
Destination::Files(_) | Destination::Routes(..) | Destination::Tracks(..)
|
||||||
)
|
)
|
||||||
| (
|
| (
|
||||||
ClipboardContent::Segments(_),
|
ClipboardContent::Segments(_),
|
||||||
Destination::Files(_) | Destination::Tracks(..) | Destination::Segments(..),
|
Destination::Files(_)
|
||||||
|
| Destination::Routes(..)
|
||||||
|
| Destination::Tracks(..)
|
||||||
|
| Destination::Segments(..),
|
||||||
)
|
)
|
||||||
| (ClipboardContent::Waypoints(_), Destination::Waypoints(..))
|
| (ClipboardContent::Waypoints(_), Destination::Waypoints(..))
|
||||||
);
|
);
|
||||||
let empty = match content {
|
let empty = match content {
|
||||||
ClipboardContent::Files(files) => files.is_empty(),
|
ClipboardContent::Files(files) => files.is_empty(),
|
||||||
|
ClipboardContent::Routes(routes) => routes.is_empty(),
|
||||||
ClipboardContent::Tracks(tracks) => tracks.is_empty(),
|
ClipboardContent::Tracks(tracks) => tracks.is_empty(),
|
||||||
ClipboardContent::Segments(segments) => segments.is_empty(),
|
ClipboardContent::Segments(segments) => segments.is_empty(),
|
||||||
ClipboardContent::Waypoints(waypoints) => waypoints.is_empty(),
|
ClipboardContent::Waypoints(waypoints) => waypoints.is_empty(),
|
||||||
@@ -189,6 +208,7 @@ pub fn transfer(
|
|||||||
.collect();
|
.collect();
|
||||||
Ok(add_files(state, files, place))
|
Ok(add_files(state, files, place))
|
||||||
}
|
}
|
||||||
|
(ClipboardContent::Routes(routes), to) => transfer_routes(state, routes, copy, to),
|
||||||
(ClipboardContent::Tracks(tracks), to) => transfer_tracks(state, tracks, copy, to),
|
(ClipboardContent::Tracks(tracks), to) => transfer_tracks(state, tracks, copy, to),
|
||||||
(ClipboardContent::Segments(segments), to) => transfer_segments(state, segments, copy, to),
|
(ClipboardContent::Segments(segments), to) => transfer_segments(state, segments, copy, to),
|
||||||
(ClipboardContent::Waypoints(waypoints), Destination::Waypoints(file_id, place)) => {
|
(ClipboardContent::Waypoints(waypoints), Destination::Waypoints(file_id, place)) => {
|
||||||
@@ -198,6 +218,89 @@ pub fn transfer(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Puts the routes among the routes of a file, at `place`, and gives the selection of them.
|
||||||
|
fn insert_routes(
|
||||||
|
state: &mut State,
|
||||||
|
file_id: FileId,
|
||||||
|
place: Place<RouteId>,
|
||||||
|
routes: Vec<Route>,
|
||||||
|
) -> Result<Selection, CommandError> {
|
||||||
|
let ids: HashSet<RouteId> = routes.iter().map(|rte| rte.id).collect();
|
||||||
|
let file = file_mut(state, file_id)?;
|
||||||
|
let existing: Vec<RouteId> = file.rte.iter().map(|rte| rte.id).collect();
|
||||||
|
let at = place.position(&existing);
|
||||||
|
file.rte.splice(at..at, routes);
|
||||||
|
Ok(Selection::Route {
|
||||||
|
file_id,
|
||||||
|
rte_ids: ids,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn transfer_routes(
|
||||||
|
state: &mut State,
|
||||||
|
routes: &[ClipboardRoute],
|
||||||
|
copy: bool,
|
||||||
|
to: Destination,
|
||||||
|
) -> Result<Selection, CommandError> {
|
||||||
|
let routes: Vec<(Route, &str)> = routes
|
||||||
|
.iter()
|
||||||
|
.map(|clip| {
|
||||||
|
let route = if copy {
|
||||||
|
copy_route(&clip.route)
|
||||||
|
} else {
|
||||||
|
clip.route.clone()
|
||||||
|
};
|
||||||
|
(route, clip.file_name.as_str())
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
match to {
|
||||||
|
Destination::Files(place) => {
|
||||||
|
let files = routes
|
||||||
|
.into_iter()
|
||||||
|
.map(|(route, file_name)| {
|
||||||
|
let name = route
|
||||||
|
.info
|
||||||
|
.name
|
||||||
|
.clone()
|
||||||
|
.unwrap_or_else(|| file_name.to_owned());
|
||||||
|
Rc::new(File {
|
||||||
|
rte: vec![route],
|
||||||
|
..new_file(&name, vec![])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
Ok(add_files(state, files, place))
|
||||||
|
}
|
||||||
|
Destination::Routes(file_id, place) => {
|
||||||
|
let routes = routes.into_iter().map(|(route, _)| route).collect();
|
||||||
|
insert_routes(state, file_id, place, routes)
|
||||||
|
}
|
||||||
|
Destination::Tracks(file_id, _) => {
|
||||||
|
let routes = routes.into_iter().map(|(route, _)| route).collect();
|
||||||
|
insert_routes(state, file_id, Place::End, routes)
|
||||||
|
}
|
||||||
|
_ => Err(CommandError::NothingToDo),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Puts the tracks among the tracks of a file, at `place`, and gives the selection of them.
|
||||||
|
fn insert_tracks(
|
||||||
|
state: &mut State,
|
||||||
|
file_id: FileId,
|
||||||
|
place: Place<TrackId>,
|
||||||
|
tracks: Vec<Track>,
|
||||||
|
) -> Result<Selection, CommandError> {
|
||||||
|
let ids: HashSet<TrackId> = tracks.iter().map(|trk| trk.id).collect();
|
||||||
|
let file = file_mut(state, file_id)?;
|
||||||
|
let existing: Vec<TrackId> = file.trk.iter().map(|trk| trk.id).collect();
|
||||||
|
let at = place.position(&existing);
|
||||||
|
file.trk.splice(at..at, tracks);
|
||||||
|
Ok(Selection::Track {
|
||||||
|
file_id,
|
||||||
|
trk_ids: ids,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
fn transfer_tracks(
|
fn transfer_tracks(
|
||||||
state: &mut State,
|
state: &mut State,
|
||||||
tracks: &[ClipboardTrack],
|
tracks: &[ClipboardTrack],
|
||||||
@@ -231,16 +334,12 @@ fn transfer_tracks(
|
|||||||
Ok(add_files(state, files, place))
|
Ok(add_files(state, files, place))
|
||||||
}
|
}
|
||||||
Destination::Tracks(file_id, place) => {
|
Destination::Tracks(file_id, place) => {
|
||||||
let tracks: Vec<Track> = tracks.into_iter().map(|(track, _)| track).collect();
|
let tracks = tracks.into_iter().map(|(track, _)| track).collect();
|
||||||
let ids: HashSet<TrackId> = tracks.iter().map(|trk| trk.id).collect();
|
insert_tracks(state, file_id, place, tracks)
|
||||||
let file = file_mut(state, file_id)?;
|
}
|
||||||
let existing: Vec<TrackId> = file.trk.iter().map(|trk| trk.id).collect();
|
Destination::Routes(file_id, _) => {
|
||||||
let at = place.position(&existing);
|
let tracks = tracks.into_iter().map(|(track, _)| track).collect();
|
||||||
file.trk.splice(at..at, tracks);
|
insert_tracks(state, file_id, Place::Index(0), tracks)
|
||||||
Ok(Selection::Track {
|
|
||||||
file_id,
|
|
||||||
trk_ids: ids,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
_ => Err(CommandError::NothingToDo),
|
_ => Err(CommandError::NothingToDo),
|
||||||
}
|
}
|
||||||
@@ -276,20 +375,22 @@ fn transfer_segments(
|
|||||||
.collect();
|
.collect();
|
||||||
Ok(add_files(state, files, place))
|
Ok(add_files(state, files, place))
|
||||||
}
|
}
|
||||||
|
Destination::Routes(file_id, place) => {
|
||||||
|
let routes = segments
|
||||||
|
.into_iter()
|
||||||
|
.map(|(seg, _)| Route {
|
||||||
|
seg,
|
||||||
|
..Default::default()
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
insert_routes(state, file_id, place, routes)
|
||||||
|
}
|
||||||
Destination::Tracks(file_id, place) => {
|
Destination::Tracks(file_id, place) => {
|
||||||
let tracks: Vec<Track> = segments
|
let tracks = segments
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|(segment, _)| own_track(segment))
|
.map(|(segment, _)| own_track(segment))
|
||||||
.collect();
|
.collect();
|
||||||
let ids = tracks.iter().map(|trk| trk.id).collect();
|
insert_tracks(state, file_id, place, tracks)
|
||||||
let file = file_mut(state, file_id)?;
|
|
||||||
let existing: Vec<TrackId> = file.trk.iter().map(|trk| trk.id).collect();
|
|
||||||
let at = place.position(&existing);
|
|
||||||
file.trk.splice(at..at, tracks);
|
|
||||||
Ok(Selection::Track {
|
|
||||||
file_id,
|
|
||||||
trk_ids: ids,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
Destination::Segments(file_id, trk_id, place) => {
|
Destination::Segments(file_id, trk_id, place) => {
|
||||||
let segments: Vec<TrackSegment> =
|
let segments: Vec<TrackSegment> =
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ mod file;
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
pub(crate) mod fixture;
|
pub(crate) mod fixture;
|
||||||
mod pattern;
|
mod pattern;
|
||||||
|
#[cfg(test)]
|
||||||
|
mod routes_tests;
|
||||||
mod tools;
|
mod tools;
|
||||||
|
|
||||||
pub use apply::*;
|
pub use apply::*;
|
||||||
@@ -31,13 +33,15 @@ pub enum Command<'a> {
|
|||||||
Move(Move),
|
Move(Move),
|
||||||
DeleteAll(DeleteAll),
|
DeleteAll(DeleteAll),
|
||||||
DeleteWaypoint(DeleteWaypoint),
|
DeleteWaypoint(DeleteWaypoint),
|
||||||
|
Convert(Convert),
|
||||||
Metadata(Metadata<'a>),
|
Metadata(Metadata<'a>),
|
||||||
Style(Style<'a>),
|
Style(Style<'a>),
|
||||||
|
NewRoute(NewRoute),
|
||||||
NewTrack(NewTrack),
|
NewTrack(NewTrack),
|
||||||
NewTrackSegment(NewTrackSegment),
|
NewTrackSegment(NewTrackSegment),
|
||||||
Reverse(Reverse),
|
Reverse(Reverse),
|
||||||
RoundTrip(RoundTrip),
|
RoundTrip(RoundTrip),
|
||||||
Route(Route<'a>),
|
Reroute(Reroute<'a>),
|
||||||
NewWaypoint(NewWaypoint<'a>),
|
NewWaypoint(NewWaypoint<'a>),
|
||||||
EditWaypoint(EditWaypoint<'a>),
|
EditWaypoint(EditWaypoint<'a>),
|
||||||
MoveWaypoint(MoveWaypoint),
|
MoveWaypoint(MoveWaypoint),
|
||||||
@@ -66,13 +70,15 @@ impl Apply for Command<'_> {
|
|||||||
Command::Move(c) => c.apply(state),
|
Command::Move(c) => c.apply(state),
|
||||||
Command::DeleteAll(c) => c.apply(state),
|
Command::DeleteAll(c) => c.apply(state),
|
||||||
Command::DeleteWaypoint(c) => c.apply(state),
|
Command::DeleteWaypoint(c) => c.apply(state),
|
||||||
|
Command::Convert(c) => c.apply(state),
|
||||||
Command::Metadata(c) => c.apply(state),
|
Command::Metadata(c) => c.apply(state),
|
||||||
Command::Style(c) => c.apply(state),
|
Command::Style(c) => c.apply(state),
|
||||||
|
Command::NewRoute(c) => c.apply(state),
|
||||||
Command::NewTrack(c) => c.apply(state),
|
Command::NewTrack(c) => c.apply(state),
|
||||||
Command::NewTrackSegment(c) => c.apply(state),
|
Command::NewTrackSegment(c) => c.apply(state),
|
||||||
Command::Reverse(c) => c.apply(state),
|
Command::Reverse(c) => c.apply(state),
|
||||||
Command::RoundTrip(c) => c.apply(state),
|
Command::RoundTrip(c) => c.apply(state),
|
||||||
Command::Route(c) => c.apply(state),
|
Command::Reroute(c) => c.apply(state),
|
||||||
Command::NewWaypoint(c) => c.apply(state),
|
Command::NewWaypoint(c) => c.apply(state),
|
||||||
Command::EditWaypoint(c) => c.apply(state),
|
Command::EditWaypoint(c) => c.apply(state),
|
||||||
Command::MoveWaypoint(c) => c.apply(state),
|
Command::MoveWaypoint(c) => c.apply(state),
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use crate::{File, Track, TrackSegment, Waypoint};
|
use crate::{File, Route, Track, TrackSegment, Waypoint};
|
||||||
|
|
||||||
// The trackpoints of a segment are shared chunks, so copying elements is cheap.
|
// The trackpoints of a segment are shared chunks, so copying elements is cheap.
|
||||||
|
|
||||||
@@ -18,10 +18,20 @@ pub fn copy_track(track: &Track) -> Track {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A copy of the file and of its tracks and segments, with new ids.
|
/// A copy of the route and of its segment, with new ids.
|
||||||
|
pub fn copy_route(route: &Route) -> Route {
|
||||||
|
Route {
|
||||||
|
id: Default::default(),
|
||||||
|
seg: copy_segment(&route.seg),
|
||||||
|
..route.clone()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A copy of the file and of its routes, tracks and segments, with new ids.
|
||||||
pub fn copy_file(file: &File) -> File {
|
pub fn copy_file(file: &File) -> File {
|
||||||
File {
|
File {
|
||||||
id: Default::default(),
|
id: Default::default(),
|
||||||
|
rte: file.rte.iter().map(copy_route).collect(),
|
||||||
trk: file.trk.iter().map(copy_track).collect(),
|
trk: file.trk.iter().map(copy_track).collect(),
|
||||||
..file.clone()
|
..file.clone()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ pub fn update_segments(
|
|||||||
let file = files
|
let file = files
|
||||||
.entry(location.file_id)
|
.entry(location.file_id)
|
||||||
.or_insert_with(|| (*state.files[&location.file_id]).clone());
|
.or_insert_with(|| (*state.files[&location.file_id]).clone());
|
||||||
f(i, &mut file.trk[location.trk].trkseg[location.seg]);
|
f(i, file.segment_mut(location.index));
|
||||||
}
|
}
|
||||||
for (file_id, file) in files {
|
for (file_id, file) in files {
|
||||||
state.files.insert(file_id, Rc::new(file));
|
state.files.insert(file_id, Rc::new(file));
|
||||||
@@ -31,6 +31,8 @@ mod tests {
|
|||||||
|
|
||||||
use crate::engine::command::fixture::Fixture;
|
use crate::engine::command::fixture::Fixture;
|
||||||
|
|
||||||
|
use crate::SegmentIndex;
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
fn fixture() -> (Fixture, FileId) {
|
fn fixture() -> (Fixture, FileId) {
|
||||||
@@ -49,13 +51,11 @@ mod tests {
|
|||||||
let locations = [
|
let locations = [
|
||||||
SegmentLocation {
|
SegmentLocation {
|
||||||
file_id: id,
|
file_id: id,
|
||||||
trk: 1,
|
index: SegmentIndex::Track { trk: 1, seg: 0 },
|
||||||
seg: 0,
|
|
||||||
},
|
},
|
||||||
SegmentLocation {
|
SegmentLocation {
|
||||||
file_id: id,
|
file_id: id,
|
||||||
trk: 0,
|
index: SegmentIndex::Track { trk: 0, seg: 0 },
|
||||||
seg: 0,
|
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
let mut calls = vec![];
|
let mut calls = vec![];
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
|
|
||||||
use crate::{File, FileId, Files, Selection, State, Track, TrackSegment, Waypoint};
|
use crate::{File, FileId, Files, Route, Selection, State, Track, TrackSegment, Waypoint};
|
||||||
|
|
||||||
/// What an [`Editor`] hook did to the element it was given.
|
/// What an [`Editor`] hook did to the element it was given.
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
@@ -21,13 +21,19 @@ impl Edit {
|
|||||||
|
|
||||||
/// Independent edit of each selected element, without needing the rest of the state.
|
/// Independent edit of each selected element, without needing the rest of the state.
|
||||||
///
|
///
|
||||||
/// A selected file, track or segment is passed to the hook of its own level. By default a
|
/// A selected file, route, track or segment is passed to the hook of its own level. By default
|
||||||
/// file is forwarded to its tracks and a track to its segments, so an editor only overrides
|
/// a file is forwarded to its routes and tracks, and a route or a track to its segments, so an
|
||||||
/// the level(s) it cares about (metadata: file and track, style: track, reverse: segment).
|
/// editor only overrides the level(s) it cares about (metadata: file, route and track, style:
|
||||||
/// Waypoints are only edited when selected, never through their file.
|
/// route and track, reverse: segment). Waypoints are only edited when selected, never through
|
||||||
|
/// their file.
|
||||||
pub trait Editor {
|
pub trait Editor {
|
||||||
fn file(&mut self, file: &mut File) -> Edit {
|
fn file(&mut self, file: &mut File) -> Edit {
|
||||||
edit_each(&mut file.trk, |trk| self.track(trk))
|
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)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn track(&mut self, track: &mut Track) -> Edit {
|
fn track(&mut self, track: &mut Track) -> Edit {
|
||||||
@@ -95,7 +101,7 @@ fn edit_waypoints<E: Editor + ?Sized>(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Applies the editor to every selected file, track or segment.
|
/// Applies the editor to every selected file, route, track or segment.
|
||||||
pub fn update_selected<E: Editor>(state: &mut State, editor: &mut E) {
|
pub fn update_selected<E: Editor>(state: &mut State, editor: &mut E) {
|
||||||
match &*state.selection {
|
match &*state.selection {
|
||||||
Selection::File { file_ids } => {
|
Selection::File { file_ids } => {
|
||||||
@@ -103,6 +109,15 @@ pub fn update_selected<E: Editor>(state: &mut State, editor: &mut E) {
|
|||||||
update_file(state.files, *id, |file| editor.file(file));
|
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 } => {
|
Selection::Track { file_id, trk_ids } => {
|
||||||
update_file(state.files, *file_id, |file| {
|
update_file(state.files, *file_id, |file| {
|
||||||
edit_where(
|
edit_where(
|
||||||
|
|||||||
@@ -0,0 +1,724 @@
|
|||||||
|
//! The commands on routes: they work as on tracks, a route being a track of a single segment.
|
||||||
|
|
||||||
|
use std::rc::Rc;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
Apply, Clean, CleanType, Clipboard, ClipboardContent, CommandError, Convert, Crop, Delete,
|
||||||
|
Duplicate, Extract, File, FileId, LngLat, LngLatBounds, Merge, MergeType, Metadata, Move,
|
||||||
|
MoveTarget, Paste, Reverse, RouteId, SegmentIndex, Selection, Split, SplitType, Style,
|
||||||
|
engine::command::fixture::Fixture, parse,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// A file with the 2 routes of `with_routes` and the 2 tracks (of 2 segments) of
|
||||||
|
/// `with_tracks_and_segments`, which is the only file and is in the order.
|
||||||
|
fn fixture() -> (Fixture, FileId) {
|
||||||
|
let read = |name: &str| {
|
||||||
|
let data = std::fs::read(format!("data/{name}.gpx")).unwrap();
|
||||||
|
parse(&data, &mut Default::default()).unwrap()
|
||||||
|
};
|
||||||
|
let mut file = read("with_tracks_and_segments");
|
||||||
|
file.rte = read("with_routes").rte;
|
||||||
|
assert_eq!((file.rte.len(), file.trk.len()), (2, 2));
|
||||||
|
let mut fx = Fixture::default();
|
||||||
|
let id = file.id;
|
||||||
|
fx.files.insert(id, Rc::new(file));
|
||||||
|
fx.order.0.push(id);
|
||||||
|
(fx, id)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn file(fx: &Fixture, id: FileId) -> &File {
|
||||||
|
&fx.files[&id]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn routes(fx: &Fixture, id: FileId, indices: &[usize]) -> Selection {
|
||||||
|
Selection::Route {
|
||||||
|
file_id: id,
|
||||||
|
rte_ids: indices.iter().map(|i| file(fx, id).rte[*i].id).collect(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn whole(id: FileId) -> Selection {
|
||||||
|
Selection::File {
|
||||||
|
file_ids: [id].into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lengths(file: &File) -> Vec<usize> {
|
||||||
|
file.segments().map(|segment| segment.len()).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_the_segments_of_a_file_are_the_ones_of_its_routes_then_its_tracks() {
|
||||||
|
let (fx, id) = fixture();
|
||||||
|
let file = file(&fx, id);
|
||||||
|
let locations = whole(id).segment_locations(&fx.files, &fx.order.0);
|
||||||
|
let indices: Vec<SegmentIndex> = locations.iter().map(|l| l.index).collect();
|
||||||
|
assert_eq!(
|
||||||
|
indices,
|
||||||
|
[
|
||||||
|
SegmentIndex::Route(0),
|
||||||
|
SegmentIndex::Route(1),
|
||||||
|
SegmentIndex::Track { trk: 0, seg: 0 },
|
||||||
|
SegmentIndex::Track { trk: 0, seg: 1 },
|
||||||
|
SegmentIndex::Track { trk: 1, seg: 0 },
|
||||||
|
SegmentIndex::Track { trk: 1, seg: 1 },
|
||||||
|
]
|
||||||
|
);
|
||||||
|
// a selection of routes covers their segments only
|
||||||
|
let selected = routes(&fx, id, &[1]).segment_locations(&fx.files, &fx.order.0);
|
||||||
|
assert_eq!(selected.len(), 1);
|
||||||
|
assert_eq!(selected[0].segment(&fx.files).id, file.rte[1].seg.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_routes_are_selected_like_tracks() {
|
||||||
|
let (fx, id) = fixture();
|
||||||
|
let ids: Vec<RouteId> = file(&fx, id).rte.iter().map(|r| r.id).collect();
|
||||||
|
|
||||||
|
let mut selection = routes(&fx, id, &[0]);
|
||||||
|
selection.extend(routes(&fx, id, &[1]));
|
||||||
|
assert_eq!(selection, routes(&fx, id, &[0, 1]));
|
||||||
|
selection.toggle(routes(&fx, id, &[0]));
|
||||||
|
assert_eq!(selection, routes(&fx, id, &[1]));
|
||||||
|
// routes and tracks are not selected together
|
||||||
|
let track = Selection::Track {
|
||||||
|
file_id: id,
|
||||||
|
trk_ids: [file(&fx, id).trk[0].id].into(),
|
||||||
|
};
|
||||||
|
selection.extend(track.clone());
|
||||||
|
assert_eq!(selection, track);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
routes(&fx, id, &[0]).all_at_level(&fx.files, &fx.order.0),
|
||||||
|
Some(routes(&fx, id, &[0, 1]))
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
routes(&fx, id, &[0]).neighbour(&fx.files, &fx.order.0, true),
|
||||||
|
Some(routes(&fx, id, &[1]))
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
routes(&fx, id, &[1]).neighbour(&fx.files, &fx.order.0, true),
|
||||||
|
None
|
||||||
|
);
|
||||||
|
assert_eq!(routes(&fx, id, &[1]).to_files(), whole(id));
|
||||||
|
|
||||||
|
let mut gone = Selection::Route {
|
||||||
|
file_id: id,
|
||||||
|
rte_ids: [ids[0], RouteId::default()].into(),
|
||||||
|
};
|
||||||
|
gone.retain_existing(&fx.files);
|
||||||
|
assert_eq!(gone, routes(&fx, id, &[0]));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_delete_and_duplicate_routes() {
|
||||||
|
let (mut fx, id) = fixture();
|
||||||
|
let kept = file(&fx, id).rte[1].id;
|
||||||
|
fx.selection = routes(&fx, id, &[0]);
|
||||||
|
Delete { whole_files: false }
|
||||||
|
.apply(&mut fx.state())
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(file(&fx, id).rte.len(), 1);
|
||||||
|
assert_eq!(file(&fx, id).rte[0].id, kept);
|
||||||
|
assert_eq!(file(&fx, id).trk.len(), 2);
|
||||||
|
assert_eq!(fx.selection, whole(id));
|
||||||
|
|
||||||
|
fx.selection = routes(&fx, id, &[0]);
|
||||||
|
Duplicate.apply(&mut fx.state()).unwrap();
|
||||||
|
let file = file(&fx, id);
|
||||||
|
assert_eq!(file.rte.len(), 2);
|
||||||
|
assert_ne!(file.rte[1].id, kept);
|
||||||
|
assert_ne!(file.rte[1].seg.id, file.rte[0].seg.id);
|
||||||
|
assert_eq!(file.rte[1].info, file.rte[0].info);
|
||||||
|
assert_eq!(
|
||||||
|
fx.selection,
|
||||||
|
Selection::Route {
|
||||||
|
file_id: id,
|
||||||
|
rte_ids: [file.rte[1].id].into()
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_metadata_and_style_of_routes() {
|
||||||
|
let (mut fx, id) = fixture();
|
||||||
|
fx.selection = routes(&fx, id, &[1]);
|
||||||
|
Metadata {
|
||||||
|
name: "renamed",
|
||||||
|
desc: "about",
|
||||||
|
}
|
||||||
|
.apply(&mut fx.state())
|
||||||
|
.unwrap();
|
||||||
|
Style {
|
||||||
|
color: Some("00ff00"),
|
||||||
|
opacity: None,
|
||||||
|
width: Some(3.0),
|
||||||
|
}
|
||||||
|
.apply(&mut fx.state())
|
||||||
|
.unwrap();
|
||||||
|
let file = file(&fx, id);
|
||||||
|
let info = &file.rte[1].info;
|
||||||
|
assert_eq!(info.name.as_deref(), Some("renamed"));
|
||||||
|
assert_eq!(info.desc.as_deref(), Some("about"));
|
||||||
|
assert_eq!(info.color.as_deref(), Some("00ff00"));
|
||||||
|
assert_eq!(info.width, Some(3.0));
|
||||||
|
assert_ne!(file.rte[0].info.name.as_deref(), Some("renamed"));
|
||||||
|
|
||||||
|
// the style of a file is the one of its routes and tracks
|
||||||
|
fx.selection = whole(id);
|
||||||
|
Style {
|
||||||
|
color: Some("ff0000"),
|
||||||
|
opacity: None,
|
||||||
|
width: None,
|
||||||
|
}
|
||||||
|
.apply(&mut fx.state())
|
||||||
|
.unwrap();
|
||||||
|
let file = &fx.files[&id];
|
||||||
|
assert!(
|
||||||
|
file.rte
|
||||||
|
.iter()
|
||||||
|
.map(|r| &r.info)
|
||||||
|
.chain(file.trk.iter().map(|t| &t.info))
|
||||||
|
.all(|info| info.color.as_deref() == Some("ff0000"))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_copy_and_paste_routes() {
|
||||||
|
let (mut fx, id) = fixture();
|
||||||
|
let copied = file(&fx, id).rte[0].clone();
|
||||||
|
fx.clipboard = Clipboard::new(&routes(&fx, id, &[0]), &fx.files, &fx.order.0, false);
|
||||||
|
assert!(matches!(
|
||||||
|
fx.clipboard.as_ref().unwrap().content,
|
||||||
|
ClipboardContent::Routes(_)
|
||||||
|
));
|
||||||
|
|
||||||
|
// after the selected route
|
||||||
|
fx.selection = routes(&fx, id, &[1]);
|
||||||
|
Paste.apply(&mut fx.state()).unwrap();
|
||||||
|
let file = file(&fx, id);
|
||||||
|
assert_eq!(file.rte.len(), 3);
|
||||||
|
assert_ne!(file.rte[2].id, copied.id);
|
||||||
|
assert_eq!(file.rte[2].seg.len(), copied.seg.len());
|
||||||
|
assert!(
|
||||||
|
matches!(&fx.selection, Selection::Route { rte_ids, .. } if rte_ids.contains(&file.rte[2].id))
|
||||||
|
);
|
||||||
|
|
||||||
|
// nothing selected: a new file, named like the route
|
||||||
|
fx.selection = Selection::Empty;
|
||||||
|
Paste.apply(&mut fx.state()).unwrap();
|
||||||
|
assert_eq!(fx.order.0.len(), 2);
|
||||||
|
let new = &fx.files[&fx.order.0[1]];
|
||||||
|
assert_eq!(new.rte.len(), 1);
|
||||||
|
assert!(new.trk.is_empty());
|
||||||
|
assert_eq!(Some(&new.info.name), copied.info.name.as_ref());
|
||||||
|
|
||||||
|
// a track selected: among the routes of its file
|
||||||
|
fx.selection = Selection::Track {
|
||||||
|
file_id: id,
|
||||||
|
trk_ids: [fx.files[&id].trk[0].id].into(),
|
||||||
|
};
|
||||||
|
Paste.apply(&mut fx.state()).unwrap();
|
||||||
|
assert_eq!(fx.files[&id].rte.len(), 4);
|
||||||
|
|
||||||
|
// segments do not go in a route, but become routes next to it
|
||||||
|
let file = &fx.files[&id];
|
||||||
|
let track = &file.trk[0];
|
||||||
|
fx.clipboard = Clipboard::new(
|
||||||
|
&Selection::TrackSegment {
|
||||||
|
file_id: id,
|
||||||
|
trk_id: track.id,
|
||||||
|
trkseg_ids: [track.trkseg[1].id].into(),
|
||||||
|
},
|
||||||
|
&fx.files,
|
||||||
|
&fx.order.0,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
fx.selection = routes(&fx, id, &[0]);
|
||||||
|
Paste.apply(&mut fx.state()).unwrap();
|
||||||
|
let file = &fx.files[&id];
|
||||||
|
assert_eq!(file.rte.len(), 5);
|
||||||
|
assert_eq!(file.rte[1].seg.len(), file.trk[0].trkseg[1].len());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_cut_tracks_pasted_on_a_route_go_first_among_the_tracks() {
|
||||||
|
let (mut fx, id) = fixture();
|
||||||
|
let moved = file(&fx, id).trk[1].id;
|
||||||
|
fx.clipboard = Clipboard::new(
|
||||||
|
&Selection::Track {
|
||||||
|
file_id: id,
|
||||||
|
trk_ids: [moved].into(),
|
||||||
|
},
|
||||||
|
&fx.files,
|
||||||
|
&fx.order.0,
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
fx.selection = routes(&fx, id, &[0]);
|
||||||
|
Paste.apply(&mut fx.state()).unwrap();
|
||||||
|
let file = file(&fx, id);
|
||||||
|
assert_eq!(file.trk.len(), 2);
|
||||||
|
assert_eq!(file.trk[0].id, moved);
|
||||||
|
assert_eq!(file.rte.len(), 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_move_routes() {
|
||||||
|
let (mut fx, id) = fixture();
|
||||||
|
let ids: Vec<RouteId> = file(&fx, id).rte.iter().map(|r| r.id).collect();
|
||||||
|
Move {
|
||||||
|
what: routes(&fx, id, &[1]),
|
||||||
|
to: MoveTarget::Routes {
|
||||||
|
file_id: id,
|
||||||
|
index: 0,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
.apply(&mut fx.state())
|
||||||
|
.unwrap();
|
||||||
|
let order: Vec<RouteId> = file(&fx, id).rte.iter().map(|r| r.id).collect();
|
||||||
|
assert_eq!(order, [ids[1], ids[0]]);
|
||||||
|
|
||||||
|
// to the files: a file of its own
|
||||||
|
Move {
|
||||||
|
what: routes(&fx, id, &[0]),
|
||||||
|
to: MoveTarget::Files { index: 1 },
|
||||||
|
}
|
||||||
|
.apply(&mut fx.state())
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(file(&fx, id).rte.len(), 1);
|
||||||
|
let new = &fx.files[&fx.order.0[1]];
|
||||||
|
assert_eq!(new.rte[0].id, ids[1]);
|
||||||
|
|
||||||
|
// a segment moved among the routes becomes one
|
||||||
|
let track = &file(&fx, id).trk[0];
|
||||||
|
let segment = track.trkseg[0].id;
|
||||||
|
Move {
|
||||||
|
what: Selection::TrackSegment {
|
||||||
|
file_id: id,
|
||||||
|
trk_id: track.id,
|
||||||
|
trkseg_ids: [segment].into(),
|
||||||
|
},
|
||||||
|
to: MoveTarget::Routes {
|
||||||
|
file_id: id,
|
||||||
|
index: 1,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
.apply(&mut fx.state())
|
||||||
|
.unwrap();
|
||||||
|
let file = file(&fx, id);
|
||||||
|
assert_eq!(file.rte[1].seg.id, segment);
|
||||||
|
assert_eq!(file.trk[0].trkseg.len(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_routes_and_tracks_moved_among_each_other_keep_their_kind() {
|
||||||
|
let (mut fx, id) = fixture();
|
||||||
|
let route = file(&fx, id).rte[0].id;
|
||||||
|
let track = file(&fx, id).trk[1].id;
|
||||||
|
|
||||||
|
// a route among the tracks: after the other routes, which come first
|
||||||
|
Move {
|
||||||
|
what: routes(&fx, id, &[0]),
|
||||||
|
to: MoveTarget::Tracks {
|
||||||
|
file_id: id,
|
||||||
|
index: 1,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
.apply(&mut fx.state())
|
||||||
|
.unwrap();
|
||||||
|
let moved = file(&fx, id);
|
||||||
|
assert_eq!((moved.rte.len(), moved.trk.len()), (2, 2));
|
||||||
|
assert_eq!(moved.rte[1].id, route);
|
||||||
|
assert_eq!(
|
||||||
|
fx.selection,
|
||||||
|
Selection::Route {
|
||||||
|
file_id: id,
|
||||||
|
rte_ids: [route].into()
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
// a track among the routes: before the other tracks, which come after the routes
|
||||||
|
Move {
|
||||||
|
what: Selection::Track {
|
||||||
|
file_id: id,
|
||||||
|
trk_ids: [track].into(),
|
||||||
|
},
|
||||||
|
to: MoveTarget::Routes {
|
||||||
|
file_id: id,
|
||||||
|
index: 0,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
.apply(&mut fx.state())
|
||||||
|
.unwrap();
|
||||||
|
let moved = file(&fx, id);
|
||||||
|
assert_eq!((moved.rte.len(), moved.trk.len()), (2, 2));
|
||||||
|
assert_eq!(moved.trk[0].id, track);
|
||||||
|
|
||||||
|
// and copied routes pasted on a track stay routes
|
||||||
|
fx.clipboard = Clipboard::new(&routes(&fx, id, &[0]), &fx.files, &fx.order.0, false);
|
||||||
|
fx.selection = Selection::Track {
|
||||||
|
file_id: id,
|
||||||
|
trk_ids: [track].into(),
|
||||||
|
};
|
||||||
|
Paste.apply(&mut fx.state()).unwrap();
|
||||||
|
let pasted = file(&fx, id);
|
||||||
|
assert_eq!((pasted.rte.len(), pasted.trk.len()), (3, 2));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_merge_routes() {
|
||||||
|
let (mut fx, id) = fixture();
|
||||||
|
let before = lengths(file(&fx, id));
|
||||||
|
let first = file(&fx, id).rte[0].id;
|
||||||
|
fx.selection = routes(&fx, id, &[0, 1]);
|
||||||
|
let merge = |type_| Merge {
|
||||||
|
type_,
|
||||||
|
remove_gaps: false,
|
||||||
|
keep_originals: false,
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
merge(MergeType::Group).apply(&mut fx.state()),
|
||||||
|
Err(CommandError::NothingToDo)
|
||||||
|
);
|
||||||
|
merge(MergeType::Connect).apply(&mut fx.state()).unwrap();
|
||||||
|
let file = file(&fx, id);
|
||||||
|
assert_eq!(file.rte.len(), 1);
|
||||||
|
assert_eq!(file.rte[0].id, first);
|
||||||
|
assert_eq!(file.rte[0].seg.len(), before[0] + before[1]);
|
||||||
|
assert_eq!(file.trk.len(), 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_merge_files_with_routes() {
|
||||||
|
let (mut fx, id) = fixture();
|
||||||
|
let other = File {
|
||||||
|
rte: file(&fx, id).rte.iter().map(crate::copy_route).collect(),
|
||||||
|
..File::default()
|
||||||
|
};
|
||||||
|
let other_id = other.id;
|
||||||
|
fx.files.insert(other_id, Rc::new(other));
|
||||||
|
fx.order.0.push(other_id);
|
||||||
|
let total: usize = lengths(file(&fx, id)).iter().sum::<usize>()
|
||||||
|
+ lengths(&fx.files[&other_id]).iter().sum::<usize>();
|
||||||
|
|
||||||
|
let mut grouped = Fixture {
|
||||||
|
files: fx.files.clone(),
|
||||||
|
order: fx.order.clone(),
|
||||||
|
selection: Selection::File {
|
||||||
|
file_ids: [id, other_id].into(),
|
||||||
|
},
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
Merge {
|
||||||
|
type_: MergeType::Group,
|
||||||
|
remove_gaps: false,
|
||||||
|
keep_originals: false,
|
||||||
|
}
|
||||||
|
.apply(&mut grouped.state())
|
||||||
|
.unwrap();
|
||||||
|
let merged = &grouped.files[&id];
|
||||||
|
assert_eq!((merged.rte.len(), merged.trk.len()), (4, 2));
|
||||||
|
assert!(!grouped.files.contains_key(&other_id));
|
||||||
|
|
||||||
|
// connected in the first route, which comes first
|
||||||
|
fx.selection = Selection::File {
|
||||||
|
file_ids: [id, other_id].into(),
|
||||||
|
};
|
||||||
|
Merge {
|
||||||
|
type_: MergeType::Connect,
|
||||||
|
remove_gaps: false,
|
||||||
|
keep_originals: false,
|
||||||
|
}
|
||||||
|
.apply(&mut fx.state())
|
||||||
|
.unwrap();
|
||||||
|
let merged = &fx.files[&id];
|
||||||
|
assert_eq!((merged.rte.len(), merged.trk.len()), (1, 0));
|
||||||
|
assert_eq!(merged.rte[0].seg.len(), total);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_extract_a_file_with_routes() {
|
||||||
|
let (mut fx, id) = fixture();
|
||||||
|
let names: Vec<_> = file(&fx, id)
|
||||||
|
.rte
|
||||||
|
.iter()
|
||||||
|
.map(|r| r.info.name.clone().unwrap())
|
||||||
|
.collect();
|
||||||
|
fx.selection = whole(id);
|
||||||
|
Extract {
|
||||||
|
keep_originals: false,
|
||||||
|
}
|
||||||
|
.apply(&mut fx.state())
|
||||||
|
.unwrap();
|
||||||
|
// one file per route and one per track
|
||||||
|
assert_eq!(fx.order.0.len(), 4);
|
||||||
|
let files: Vec<&File> = fx.order.0.iter().map(|id| &*fx.files[id]).collect();
|
||||||
|
for (file, name) in files.iter().zip(&names) {
|
||||||
|
assert_eq!((file.rte.len(), file.trk.len()), (1, 0));
|
||||||
|
assert_eq!(&file.info.name, name);
|
||||||
|
}
|
||||||
|
for file in &files[2..] {
|
||||||
|
assert_eq!((file.rte.len(), file.trk.len()), (0, 2));
|
||||||
|
}
|
||||||
|
|
||||||
|
// a route has nothing to extract
|
||||||
|
let (mut fx, id) = fixture();
|
||||||
|
fx.selection = routes(&fx, id, &[0]);
|
||||||
|
assert_eq!(
|
||||||
|
Extract {
|
||||||
|
keep_originals: false
|
||||||
|
}
|
||||||
|
.apply(&mut fx.state()),
|
||||||
|
Err(CommandError::NothingToDo)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_split_a_route() {
|
||||||
|
let (mut fx, id) = fixture();
|
||||||
|
let before = file(&fx, id).rte[1].clone();
|
||||||
|
fx.selection = routes(&fx, id, &[1]);
|
||||||
|
Split {
|
||||||
|
at: 10,
|
||||||
|
split_type: SplitType::Routes,
|
||||||
|
keep_originals: false,
|
||||||
|
}
|
||||||
|
.apply(&mut fx.state())
|
||||||
|
.unwrap();
|
||||||
|
// two routes, which share the trackpoint
|
||||||
|
let split = file(&fx, id);
|
||||||
|
assert_eq!(split.rte.len(), 3);
|
||||||
|
assert_eq!(split.rte[1].id, before.id);
|
||||||
|
assert_ne!(split.rte[2].id, before.id);
|
||||||
|
assert_eq!(split.rte[1].seg.len(), 11);
|
||||||
|
assert_eq!(split.rte[2].seg.len(), before.seg.len() - 10);
|
||||||
|
assert_eq!(split.rte[2].info, before.info);
|
||||||
|
|
||||||
|
// a route is not a track nor a segment, and the other way around
|
||||||
|
let (mut fx, id) = fixture();
|
||||||
|
fx.selection = whole(id);
|
||||||
|
let segment_start = lengths(file(&fx, id))[..2].iter().sum::<usize>() as u32;
|
||||||
|
for (at, split_type) in [
|
||||||
|
(10, SplitType::Tracks),
|
||||||
|
(10, SplitType::Segments),
|
||||||
|
(segment_start + 10, SplitType::Routes),
|
||||||
|
] {
|
||||||
|
assert_eq!(
|
||||||
|
Split {
|
||||||
|
at,
|
||||||
|
split_type,
|
||||||
|
keep_originals: false,
|
||||||
|
}
|
||||||
|
.apply(&mut fx.state()),
|
||||||
|
Err(CommandError::NothingToDo)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert_eq!(file(&fx, id).rte.len(), 2);
|
||||||
|
|
||||||
|
// into two files: the following routes and the tracks go to the second one
|
||||||
|
let (mut fx, id) = fixture();
|
||||||
|
let first_len = file(&fx, id).rte[0].seg.len();
|
||||||
|
fx.selection = whole(id);
|
||||||
|
Split {
|
||||||
|
at: 5,
|
||||||
|
split_type: SplitType::Files,
|
||||||
|
keep_originals: false,
|
||||||
|
}
|
||||||
|
.apply(&mut fx.state())
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(fx.order.0.len(), 2);
|
||||||
|
let (a, b) = (&fx.files[&fx.order.0[0]], &fx.files[&fx.order.0[1]]);
|
||||||
|
assert_eq!(a.id, id);
|
||||||
|
assert_eq!((a.rte.len(), a.trk.len()), (1, 0));
|
||||||
|
assert_eq!(a.rte[0].seg.len(), 6);
|
||||||
|
assert_eq!((b.rte.len(), b.trk.len()), (2, 2));
|
||||||
|
assert_eq!(b.rte[0].seg.len(), first_len - 5);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_crop_removes_the_routes_left_without_trackpoints() {
|
||||||
|
let (mut fx, id) = fixture();
|
||||||
|
let len = lengths(file(&fx, id));
|
||||||
|
fx.selection = whole(id);
|
||||||
|
// the second route only
|
||||||
|
let start = len[0] as u32;
|
||||||
|
Crop {
|
||||||
|
start,
|
||||||
|
end: start + len[1] as u32 - 1,
|
||||||
|
}
|
||||||
|
.apply(&mut fx.state())
|
||||||
|
.unwrap();
|
||||||
|
let file = file(&fx, id);
|
||||||
|
assert_eq!((file.rte.len(), file.trk.len()), (1, 0));
|
||||||
|
assert_eq!(file.rte[0].seg.len(), len[1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_clean_removes_the_routes_left_without_trackpoints() {
|
||||||
|
let (mut fx, id) = fixture();
|
||||||
|
fx.selection = routes(&fx, id, &[0]);
|
||||||
|
let everywhere = LngLatBounds {
|
||||||
|
sw: LngLat {
|
||||||
|
lng: -180.0,
|
||||||
|
lat: -90.0,
|
||||||
|
},
|
||||||
|
ne: LngLat {
|
||||||
|
lng: 180.0,
|
||||||
|
lat: 90.0,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
Clean {
|
||||||
|
bounds: everywhere,
|
||||||
|
type_: CleanType::Inside,
|
||||||
|
trkpt: true,
|
||||||
|
wpt: false,
|
||||||
|
}
|
||||||
|
.apply(&mut fx.state())
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(file(&fx, id).rte.len(), 1);
|
||||||
|
assert_eq!(fx.selection, whole(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_reverse_a_route_and_the_routes_of_a_file() {
|
||||||
|
let (mut fx, id) = fixture();
|
||||||
|
let before = file(&fx, id).clone();
|
||||||
|
fx.selection = routes(&fx, id, &[0]);
|
||||||
|
Reverse.apply(&mut fx.state()).unwrap();
|
||||||
|
let route = &file(&fx, id).rte[0].seg;
|
||||||
|
let original = &before.rte[0].seg;
|
||||||
|
assert_eq!(
|
||||||
|
route[0].coordinates.lat,
|
||||||
|
original[original.len() - 1].coordinates.lat
|
||||||
|
);
|
||||||
|
assert_eq!(file(&fx, id).rte[1].seg.rev_id, before.rte[1].seg.rev_id);
|
||||||
|
|
||||||
|
let (mut fx, id) = fixture();
|
||||||
|
let before = file(&fx, id).clone();
|
||||||
|
fx.selection = whole(id);
|
||||||
|
Reverse.apply(&mut fx.state()).unwrap();
|
||||||
|
let file = file(&fx, id);
|
||||||
|
// the routes are in the opposite order, and still before the tracks
|
||||||
|
assert_eq!(file.rte[0].id, before.rte[1].id);
|
||||||
|
assert_eq!(file.trk[0].id, before.trk[1].id);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_convert_routes_to_tracks_and_back() {
|
||||||
|
let (mut fx, id) = fixture();
|
||||||
|
let before = file(&fx, id).clone();
|
||||||
|
|
||||||
|
// a route becomes a track, first among the tracks, with its segment and its information
|
||||||
|
fx.selection = routes(&fx, id, &[1]);
|
||||||
|
Convert.apply(&mut fx.state()).unwrap();
|
||||||
|
let converted = file(&fx, id);
|
||||||
|
assert_eq!((converted.rte.len(), converted.trk.len()), (1, 3));
|
||||||
|
assert_eq!(converted.trk[0].info, before.rte[1].info);
|
||||||
|
assert_eq!(converted.trk[0].trkseg.len(), 1);
|
||||||
|
assert_eq!(converted.trk[0].trkseg[0].id, before.rte[1].seg.id);
|
||||||
|
assert_eq!(
|
||||||
|
fx.selection,
|
||||||
|
Selection::Track {
|
||||||
|
file_id: id,
|
||||||
|
trk_ids: [converted.trk[0].id].into()
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
// and back: a route again, after the other routes
|
||||||
|
Convert.apply(&mut fx.state()).unwrap();
|
||||||
|
let back = file(&fx, id);
|
||||||
|
assert_eq!((back.rte.len(), back.trk.len()), (2, 2));
|
||||||
|
assert_eq!(back.rte[1].seg.id, before.rte[1].seg.id);
|
||||||
|
assert_eq!(back.rte[1].info, before.rte[1].info);
|
||||||
|
assert!(
|
||||||
|
matches!(&fx.selection, Selection::Route { rte_ids, .. } if rte_ids.contains(&back.rte[1].id))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_convert_a_track_to_one_route_per_segment() {
|
||||||
|
let (mut fx, id) = fixture();
|
||||||
|
let track = file(&fx, id).trk[0].clone();
|
||||||
|
assert_eq!(track.trkseg.len(), 2);
|
||||||
|
fx.selection = Selection::Track {
|
||||||
|
file_id: id,
|
||||||
|
trk_ids: [track.id].into(),
|
||||||
|
};
|
||||||
|
Convert.apply(&mut fx.state()).unwrap();
|
||||||
|
let converted = file(&fx, id);
|
||||||
|
assert_eq!((converted.rte.len(), converted.trk.len()), (4, 1));
|
||||||
|
for (route, segment) in converted.rte[2..].iter().zip(&track.trkseg) {
|
||||||
|
assert_eq!(route.seg.id, segment.id);
|
||||||
|
assert_eq!(route.info, track.info);
|
||||||
|
}
|
||||||
|
assert!(matches!(&fx.selection, Selection::Route { rte_ids, .. } if rte_ids.len() == 2));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_convert_segments_to_routes_keeps_their_track() {
|
||||||
|
let (mut fx, id) = fixture();
|
||||||
|
let track = file(&fx, id).trk[1].clone();
|
||||||
|
fx.selection = Selection::TrackSegment {
|
||||||
|
file_id: id,
|
||||||
|
trk_id: track.id,
|
||||||
|
trkseg_ids: [track.trkseg[0].id, track.trkseg[1].id].into(),
|
||||||
|
};
|
||||||
|
Convert.apply(&mut fx.state()).unwrap();
|
||||||
|
let converted = file(&fx, id);
|
||||||
|
assert_eq!((converted.rte.len(), converted.trk.len()), (4, 2));
|
||||||
|
assert!(converted.trk[1].trkseg.is_empty());
|
||||||
|
assert_eq!(converted.rte[2].seg.id, track.trkseg[0].id);
|
||||||
|
|
||||||
|
// nothing to convert otherwise
|
||||||
|
for selection in [
|
||||||
|
whole(id),
|
||||||
|
Selection::Empty,
|
||||||
|
Selection::Waypoints { file_id: id },
|
||||||
|
] {
|
||||||
|
fx.selection = selection;
|
||||||
|
assert_eq!(
|
||||||
|
Convert.apply(&mut fx.state()),
|
||||||
|
Err(CommandError::NothingToDo)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_convert_a_file_with_routes_or_tracks_only() {
|
||||||
|
let (mut fx, id) = fixture();
|
||||||
|
let before = file(&fx, id).clone();
|
||||||
|
let only_tracks = File {
|
||||||
|
trk: before.trk.clone(),
|
||||||
|
..File::default()
|
||||||
|
};
|
||||||
|
let only_tracks_id = only_tracks.id;
|
||||||
|
fx.files.insert(only_tracks_id, Rc::new(only_tracks));
|
||||||
|
fx.order.0.push(only_tracks_id);
|
||||||
|
|
||||||
|
// the file with both stays as it is, the other gets one route per segment
|
||||||
|
fx.selection = Selection::File {
|
||||||
|
file_ids: [id, only_tracks_id].into(),
|
||||||
|
};
|
||||||
|
Convert.apply(&mut fx.state()).unwrap();
|
||||||
|
assert_eq!(lengths(file(&fx, id)), lengths(&before));
|
||||||
|
let routes = file(&fx, only_tracks_id);
|
||||||
|
assert_eq!((routes.rte.len(), routes.trk.len()), (4, 0));
|
||||||
|
assert_eq!(routes.rte[0].seg.id, before.trk[0].trkseg[0].id);
|
||||||
|
assert_eq!(routes.rte[0].info, before.trk[0].info);
|
||||||
|
|
||||||
|
// and back: one track per route
|
||||||
|
fx.selection = Selection::File {
|
||||||
|
file_ids: [only_tracks_id].into(),
|
||||||
|
};
|
||||||
|
Convert.apply(&mut fx.state()).unwrap();
|
||||||
|
let tracks = file(&fx, only_tracks_id);
|
||||||
|
assert_eq!((tracks.rte.len(), tracks.trk.len()), (0, 4));
|
||||||
|
assert_eq!(tracks.trk[0].trkseg[0].id, before.trk[0].trkseg[0].id);
|
||||||
|
|
||||||
|
// nothing to do for a file with both
|
||||||
|
fx.selection = whole(id);
|
||||||
|
assert_eq!(
|
||||||
|
Convert.apply(&mut fx.state()),
|
||||||
|
Err(CommandError::NothingToDo)
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -24,7 +24,7 @@ impl Apply for ChangeLoopStart {
|
|||||||
let index = self.index as usize;
|
let index = self.index as usize;
|
||||||
let target = find_target(state, index, index)?.ok_or(CommandError::NothingToDo)?;
|
let target = find_target(state, index, index)?.ok_or(CommandError::NothingToDo)?;
|
||||||
let mut file = (*state.files[&target.location.file_id]).clone();
|
let mut file = (*state.files[&target.location.file_id]).clone();
|
||||||
let segment = &mut file.trk[target.location.trk].trkseg[target.location.seg];
|
let segment = file.segment_mut(target.location.index);
|
||||||
let (start, len) = (target.start, segment.len());
|
let (start, len) = (target.start, segment.len());
|
||||||
if start == 0 || start >= len {
|
if start == 0 || start >= len {
|
||||||
// it already is the start, or it is not a trackpoint
|
// it already is the start, or it is not a trackpoint
|
||||||
|
|||||||
@@ -13,8 +13,8 @@ pub enum CleanType {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Removes the trackpoints and/or waypoints of the selection lying inside (or outside) a
|
/// Removes the trackpoints and/or waypoints of the selection lying inside (or outside) a
|
||||||
/// rectangle. A selected file cleans its tracks and its waypoints, a selected track or segment
|
/// rectangle. A selected file cleans its routes, its tracks and its waypoints, a selected route,
|
||||||
/// only trackpoints, selected waypoints only waypoints.
|
/// track or segment only trackpoints, selected waypoints only waypoints.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct Clean {
|
pub struct Clean {
|
||||||
pub bounds: LngLatBounds,
|
pub bounds: LngLatBounds,
|
||||||
@@ -85,6 +85,11 @@ struct Cleaner<'a> {
|
|||||||
impl Editor for Cleaner<'_> {
|
impl Editor for Cleaner<'_> {
|
||||||
fn file(&mut self, file: &mut File) -> Edit {
|
fn file(&mut self, file: &mut File) -> Edit {
|
||||||
let mut edit = Edit::Unchanged;
|
let mut edit = Edit::Unchanged;
|
||||||
|
for rte in &mut file.rte {
|
||||||
|
if self.route(rte) == Edit::Changed {
|
||||||
|
edit = Edit::Changed;
|
||||||
|
}
|
||||||
|
}
|
||||||
for trk in &mut file.trk {
|
for trk in &mut file.trk {
|
||||||
if self.track(trk) == Edit::Changed {
|
if self.track(trk) == Edit::Changed {
|
||||||
edit = Edit::Changed;
|
edit = Edit::Changed;
|
||||||
@@ -124,24 +129,21 @@ impl Editor for Cleaner<'_> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Removes what the clean left empty: the emptied segments and the tracks that lost all their
|
/// Removes what the clean left empty: the emptied segments, the routes of these segments and the
|
||||||
/// segments. A file is never removed, even if nothing is left in it: it stays, empty. The
|
/// tracks that lost all their segments. A file is never removed, even if nothing is left in it: it stays, empty. The
|
||||||
/// selection falls back to the closest element still existing.
|
/// selection falls back to the closest element still existing.
|
||||||
fn prune(state: &mut State, emptied: &HashSet<TrackSegmentId>, wpt_files: &HashSet<FileId>) {
|
fn prune(state: &mut State, emptied: &HashSet<TrackSegmentId>, wpt_files: &HashSet<FileId>) {
|
||||||
let ids: Vec<FileId> = state
|
let ids: Vec<FileId> = state
|
||||||
.files
|
.files
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|(id, file)| {
|
.filter(|(id, file)| {
|
||||||
wpt_files.contains(id)
|
wpt_files.contains(id) || file.segments().any(|seg| emptied.contains(&seg.id))
|
||||||
|| file
|
|
||||||
.trk
|
|
||||||
.iter()
|
|
||||||
.any(|trk| trk.trkseg.iter().any(|seg| emptied.contains(&seg.id)))
|
|
||||||
})
|
})
|
||||||
.map(|(id, _)| *id)
|
.map(|(id, _)| *id)
|
||||||
.collect();
|
.collect();
|
||||||
for id in ids {
|
for id in ids {
|
||||||
let mut file = (*state.files[&id]).clone();
|
let mut file = (*state.files[&id]).clone();
|
||||||
|
file.rte.retain(|rte| !emptied.contains(&rte.seg.id));
|
||||||
file.trk.retain_mut(|trk| {
|
file.trk.retain_mut(|trk| {
|
||||||
let len = trk.trkseg.len();
|
let len = trk.trkseg.len();
|
||||||
trk.trkseg.retain(|seg| !emptied.contains(&seg.id));
|
trk.trkseg.retain(|seg| !emptied.contains(&seg.id));
|
||||||
@@ -167,6 +169,27 @@ fn fixed_selection(state: &State) -> Selection {
|
|||||||
Selection::File { file_ids }
|
Selection::File { file_ids }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Selection::Route { file_id, rte_ids } => {
|
||||||
|
let Some(file) = files.get(file_id) else {
|
||||||
|
return Selection::Empty;
|
||||||
|
};
|
||||||
|
let rte_ids: HashSet<_> = file
|
||||||
|
.rte
|
||||||
|
.iter()
|
||||||
|
.map(|rte| rte.id)
|
||||||
|
.filter(|id| rte_ids.contains(id))
|
||||||
|
.collect();
|
||||||
|
if rte_ids.is_empty() {
|
||||||
|
Selection::File {
|
||||||
|
file_ids: [*file_id].into(),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Selection::Route {
|
||||||
|
file_id: *file_id,
|
||||||
|
rte_ids,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Selection::Track { file_id, trk_ids } => {
|
Selection::Track { file_id, trk_ids } => {
|
||||||
let Some(file) = files.get(file_id) else {
|
let Some(file) = files.get(file_id) else {
|
||||||
return Selection::Empty;
|
return Selection::Empty;
|
||||||
|
|||||||
@@ -11,9 +11,9 @@ use crate::{
|
|||||||
/// Keeps the trackpoints `start` to `end` (both included) of the selection, which are counted
|
/// Keeps the trackpoints `start` to `end` (both included) of the selection, which are counted
|
||||||
/// over its segments one after the other (as in the `RoutingBuffer`), and removes the others.
|
/// over its segments one after the other (as in the `RoutingBuffer`), and removes the others.
|
||||||
///
|
///
|
||||||
/// The segments that have no trackpoint left are removed. So are the tracks that have no segment
|
/// The segments that have no trackpoint left are removed, and so are the routes of these segments.
|
||||||
/// left, if tracks or files are selected (not if only segments are), and the files that have no
|
/// So are the tracks that have no segment left, if tracks or files are selected (not if only
|
||||||
/// trackpoint left, if files are selected. A range that goes past the last trackpoint stops at it.
|
/// segments are), and the files that have no trackpoint left, if files are selected. A range that goes past the last trackpoint stops at it.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct Crop {
|
pub struct Crop {
|
||||||
pub start: u32,
|
pub start: u32,
|
||||||
@@ -43,8 +43,7 @@ impl Apply for Crop {
|
|||||||
.segment_locations(state.files, &state.order.0)
|
.segment_locations(state.files, &state.order.0)
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|location| {
|
.map(|location| {
|
||||||
let len =
|
let len = location.segment(state.files).len();
|
||||||
state.files[&location.file_id].trk[location.trk].trkseg[location.seg].len();
|
|
||||||
let keep = (len > 0 && start < offset + len && end >= offset)
|
let keep = (len > 0 && start < offset + len && end >= offset)
|
||||||
.then(|| (start.saturating_sub(offset), (end - offset).min(len - 1)));
|
.then(|| (start.saturating_sub(offset), (end - offset).min(len - 1)));
|
||||||
offset += len;
|
offset += len;
|
||||||
@@ -73,14 +72,14 @@ impl Apply for Crop {
|
|||||||
let mut removed: HashSet<TrackSegmentId> = HashSet::new();
|
let mut removed: HashSet<TrackSegmentId> = HashSet::new();
|
||||||
let mut had_points: HashSet<FileId> = HashSet::new();
|
let mut had_points: HashSet<FileId> = HashSet::new();
|
||||||
for plan in &plans {
|
for plan in &plans {
|
||||||
let SegmentLocation { file_id, trk, seg } = plan.location;
|
let SegmentLocation { file_id, index } = plan.location;
|
||||||
let file = files
|
let file = files
|
||||||
.entry(file_id)
|
.entry(file_id)
|
||||||
.or_insert_with(|| (*state.files[&file_id]).clone());
|
.or_insert_with(|| (*state.files[&file_id]).clone());
|
||||||
if plan.len > 0 {
|
if plan.len > 0 {
|
||||||
had_points.insert(file_id);
|
had_points.insert(file_id);
|
||||||
}
|
}
|
||||||
let segment = &mut file.trk[trk].trkseg[seg];
|
let segment = file.segment_mut(index);
|
||||||
match plan.keep {
|
match plan.keep {
|
||||||
None => {
|
None => {
|
||||||
removed.insert(segment.id);
|
removed.insert(segment.id);
|
||||||
@@ -91,6 +90,8 @@ impl Apply for Crop {
|
|||||||
|
|
||||||
let mut gone: Vec<FileId> = vec![];
|
let mut gone: Vec<FileId> = vec![];
|
||||||
for (file_id, file) in files.iter_mut() {
|
for (file_id, file) in files.iter_mut() {
|
||||||
|
// a route has its segment, or is not there
|
||||||
|
file.rte.retain(|route| !removed.contains(&route.seg.id));
|
||||||
// the tracks that lost segments
|
// the tracks that lost segments
|
||||||
let touched: Vec<bool> = file
|
let touched: Vec<bool> = file
|
||||||
.trk
|
.trk
|
||||||
@@ -108,7 +109,7 @@ impl Apply for Crop {
|
|||||||
file.trk
|
file.trk
|
||||||
.retain(|track| !(touched.next().unwrap() && track.trkseg.is_empty()));
|
.retain(|track| !(touched.next().unwrap() && track.trkseg.is_empty()));
|
||||||
}
|
}
|
||||||
if prune_files && file.trk.is_empty() && had_points.contains(file_id) {
|
if prune_files && file.has_no_path() && had_points.contains(file_id) {
|
||||||
gone.push(*file_id);
|
gone.push(*file_id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,9 +14,7 @@ impl Apply for Elevation<'_> {
|
|||||||
.segment_locations(state.files, &state.order.0);
|
.segment_locations(state.files, &state.order.0);
|
||||||
let count: usize = locations
|
let count: usize = locations
|
||||||
.iter()
|
.iter()
|
||||||
.map(|location| {
|
.map(|location| location.segment(state.files).len())
|
||||||
state.files[&location.file_id].trk[location.trk].trkseg[location.seg].len()
|
|
||||||
})
|
|
||||||
.sum();
|
.sum();
|
||||||
if count == 0 {
|
if count == 0 {
|
||||||
return Err(CommandError::NothingToDo);
|
return Err(CommandError::NothingToDo);
|
||||||
|
|||||||
@@ -1,22 +1,23 @@
|
|||||||
use std::{collections::HashSet, rc::Rc};
|
use std::{collections::HashSet, rc::Rc};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
Apply, CommandError, File, FileId, LngLat, LngLatBounds, Selection, State, Track, TrackId,
|
Apply, CommandError, File, FileId, LngLat, LngLatBounds, Route, Selection, State, Track,
|
||||||
TrackSegment, Waypoint, Waypoints, copy_file, copy_waypoint, crossarc_lnglat, distance,
|
TrackId, TrackSegment, Waypoint, Waypoints, copy_file, copy_waypoint, crossarc_lnglat,
|
||||||
|
distance,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Splits the selected elements that are made of several segments into elements that have one
|
/// Splits the selected elements that are made of several segments into elements that have one
|
||||||
/// each:
|
/// each:
|
||||||
///
|
///
|
||||||
/// - files: a file with several tracks becomes one file per track, in which the track is split
|
/// - files: a file with several routes and tracks becomes one file per route and per track, in
|
||||||
/// into one track per segment. A file with a single track becomes one file per segment. The new
|
/// which the track is split into one track per segment. A file with a single track becomes one
|
||||||
/// files are in the place of the file, which goes, and are selected. They are named after the
|
/// file per segment. The new files are in the place of the file, which goes, and are selected.
|
||||||
/// track, or the file, and numbered. The waypoints go to the files that have the segments
|
/// They are named after the route or track, or the file, and numbered. The waypoints go to the files that have the segments
|
||||||
/// closest to them (to the first file if the file has no trackpoint).
|
/// closest to them (to the first file if the file has no trackpoint).
|
||||||
/// - tracks: each selected track is replaced by one track per segment, which are selected. They
|
/// - tracks: each selected track is replaced by one track per segment, which are selected. They
|
||||||
/// are named after the track and numbered.
|
/// are named after the track and numbered.
|
||||||
///
|
///
|
||||||
/// What has a single segment is left as it is. There is nothing to do if nothing was changed.
|
/// What has a single segment is left as it is, which routes always are. There is nothing to do if nothing was changed.
|
||||||
///
|
///
|
||||||
/// With `keep_originals`, the files that are extracted stay where they are, and the new files come
|
/// With `keep_originals`, the files that are extracted stay where they are, and the new files come
|
||||||
/// right after each of them, and only the new files are selected. Extracting
|
/// right after each of them, and only the new files are selected. Extracting
|
||||||
@@ -46,8 +47,7 @@ fn extract_files(
|
|||||||
let mut extracted: Vec<(FileId, Vec<File>)> = vec![];
|
let mut extracted: Vec<(FileId, Vec<File>)> = vec![];
|
||||||
for id in state.order.0.iter().filter(|id| file_ids.contains(id)) {
|
for id in state.order.0.iter().filter(|id| file_ids.contains(id)) {
|
||||||
let file = &state.files[id];
|
let file = &state.files[id];
|
||||||
let segments: usize = file.trk.iter().map(|track| track.trkseg.len()).sum();
|
if file.segments().count() > 1 {
|
||||||
if segments > 1 {
|
|
||||||
let mut files = extract_file(file);
|
let mut files = extract_file(file);
|
||||||
if keep_originals {
|
if keep_originals {
|
||||||
// the tracks and segments are the ones of the file, which stays: they need new ids
|
// the tracks and segments are the ones of the file, which stays: they need new ids
|
||||||
@@ -95,31 +95,35 @@ fn extract_files(
|
|||||||
|
|
||||||
/// The files that a file with several segments becomes.
|
/// The files that a file with several segments becomes.
|
||||||
fn extract_file(file: &File) -> Vec<File> {
|
fn extract_file(file: &File) -> Vec<File> {
|
||||||
// for each new file: its tracks and its name, and the segments that go with it
|
// for each new file: its routes, its tracks and its name, and the segments that go with it
|
||||||
struct Part {
|
struct Part {
|
||||||
|
routes: Vec<Route>,
|
||||||
tracks: Vec<Track>,
|
tracks: Vec<Track>,
|
||||||
name: String,
|
name: String,
|
||||||
}
|
}
|
||||||
let (parts, owner): (Vec<Part>, Vec<usize>) = if file.trk.len() > 1 {
|
let name = |name: &Option<String>, i: usize| {
|
||||||
// one file per track, the segments of a track follow it
|
name.clone()
|
||||||
let parts = file
|
.unwrap_or_else(|| format!("{} ({})", file.info.name, i + 1))
|
||||||
.trk
|
};
|
||||||
.iter()
|
let (parts, owner): (Vec<Part>, Vec<usize>) =
|
||||||
.enumerate()
|
if file.rte.len() + file.trk.len() > 1 {
|
||||||
.map(|(i, track)| Part {
|
// one file per route and per track, the segments of a track follow it
|
||||||
|
let routes = file.rte.iter().enumerate().map(|(i, route)| Part {
|
||||||
|
routes: vec![route.clone()],
|
||||||
|
tracks: vec![],
|
||||||
|
name: name(&route.info.name, i),
|
||||||
|
});
|
||||||
|
let tracks = file.trk.iter().enumerate().map(|(i, track)| Part {
|
||||||
|
routes: vec![],
|
||||||
tracks: split_track(track),
|
tracks: split_track(track),
|
||||||
name: track
|
name: name(&track.info.name, file.rte.len() + i),
|
||||||
.info
|
});
|
||||||
.name
|
let parts = routes.chain(tracks).collect();
|
||||||
.clone()
|
let owner =
|
||||||
.unwrap_or_else(|| format!("{} ({})", file.info.name, i + 1)),
|
(0..file.rte.len())
|
||||||
})
|
.chain(file.trk.iter().enumerate().flat_map(|(i, track)| {
|
||||||
.collect();
|
track.trkseg.iter().map(move |_| file.rte.len() + i)
|
||||||
let owner = file
|
}))
|
||||||
.trk
|
|
||||||
.iter()
|
|
||||||
.enumerate()
|
|
||||||
.flat_map(|(i, track)| track.trkseg.iter().map(move |_| i))
|
|
||||||
.collect();
|
.collect();
|
||||||
(parts, owner)
|
(parts, owner)
|
||||||
} else {
|
} else {
|
||||||
@@ -135,6 +139,7 @@ fn extract_file(file: &File) -> Vec<File> {
|
|||||||
.iter()
|
.iter()
|
||||||
.enumerate()
|
.enumerate()
|
||||||
.map(|(i, segment)| Part {
|
.map(|(i, segment)| Part {
|
||||||
|
routes: vec![],
|
||||||
tracks: vec![Track {
|
tracks: vec![Track {
|
||||||
id: if i == 0 { track.id } else { Default::default() },
|
id: if i == 0 { track.id } else { Default::default() },
|
||||||
trkseg: vec![segment.clone()],
|
trkseg: vec![segment.clone()],
|
||||||
@@ -148,7 +153,7 @@ fn extract_file(file: &File) -> Vec<File> {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// the waypoints go with the segments that are the closest to them
|
// the waypoints go with the segments that are the closest to them
|
||||||
let segments: Vec<&TrackSegment> = file.trk.iter().flat_map(|track| &track.trkseg).collect();
|
let segments: Vec<&TrackSegment> = file.segments().collect();
|
||||||
let mut waypoints: Vec<Vec<Waypoint>> = vec![vec![]; parts.len()];
|
let mut waypoints: Vec<Vec<Waypoint>> = vec![vec![]; parts.len()];
|
||||||
for waypoint in file.wpt.iter() {
|
for waypoint in file.wpt.iter() {
|
||||||
let mut owners: Vec<usize> = closest_segments(&segments, waypoint.coordinates)
|
let mut owners: Vec<usize> = closest_segments(&segments, waypoint.coordinates)
|
||||||
@@ -176,6 +181,7 @@ fn extract_file(file: &File) -> Vec<File> {
|
|||||||
.map(|(part, waypoints)| {
|
.map(|(part, waypoints)| {
|
||||||
let mut extracted = File {
|
let mut extracted = File {
|
||||||
id: Default::default(),
|
id: Default::default(),
|
||||||
|
rte: part.routes,
|
||||||
trk: part.tracks,
|
trk: part.tracks,
|
||||||
wpt: Waypoints::default(),
|
wpt: Waypoints::default(),
|
||||||
..file.clone()
|
..file.clone()
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ impl Apply for InsertAnchor {
|
|||||||
.selection
|
.selection
|
||||||
.segment_locations(state.files, &state.order.0)
|
.segment_locations(state.files, &state.order.0)
|
||||||
{
|
{
|
||||||
let segment = &state.files[&location.file_id].trk[location.trk].trkseg[location.seg];
|
let segment = location.segment(state.files);
|
||||||
let mut points = segment.iter();
|
let mut points = segment.iter();
|
||||||
let Some(mut previous) = points.next() else {
|
let Some(mut previous) = points.next() else {
|
||||||
continue;
|
continue;
|
||||||
@@ -81,7 +81,7 @@ impl Apply for InsertAnchor {
|
|||||||
let closest = closest.ok_or(CommandError::NothingToDo)?;
|
let closest = closest.ok_or(CommandError::NothingToDo)?;
|
||||||
|
|
||||||
let mut file = (*state.files[&closest.location.file_id]).clone();
|
let mut file = (*state.files[&closest.location.file_id]).clone();
|
||||||
let segment = &mut file.trk[closest.location.trk].trkseg[closest.location.seg];
|
let segment = file.segment_mut(closest.location.index);
|
||||||
let before = closest.before;
|
let before = closest.before;
|
||||||
// on a trackpoint already, if it is closer than `SNAP_DISTANCE`
|
// on a trackpoint already, if it is closer than `SNAP_DISTANCE`
|
||||||
let snapped = if segment.len() == 1 {
|
let snapped = if segment.len() == 1 {
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
use std::{collections::HashSet, rc::Rc};
|
use std::{collections::HashSet, rc::Rc};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
Apply, CommandError, FileId, GlobalStatistics, Selection, State, Statistics, Track, TrackId,
|
Apply, CommandError, FileId, GlobalStatistics, Route, RouteId, Selection, State, Statistics,
|
||||||
TrackSegment, TrackSegmentId, Waypoint, Waypoints, copy_track, replace_trackpoints,
|
Track, TrackId, TrackSegment, TrackSegmentId, Waypoint, Waypoints, copy_route, copy_track,
|
||||||
|
replace_trackpoints,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)]
|
||||||
@@ -16,13 +17,16 @@ pub enum MergeType {
|
|||||||
|
|
||||||
/// Merges the selected elements into the first of them:
|
/// Merges the selected elements into the first of them:
|
||||||
///
|
///
|
||||||
/// - files: the other files are deleted. The tracks of all of them are in the first file, as
|
/// - files: the other files are deleted. The routes and tracks of all of them are in the first
|
||||||
/// they are with `Group`, or all connected in the first track with `Connect`. The waypoints of
|
/// file, as they are with `Group`, or all connected in the first of them (a route or a track,
|
||||||
|
/// the routes of a file coming before its tracks) with `Connect`. The waypoints of
|
||||||
/// all of them are in the first file too, except the ones that are the same. With
|
/// all of them are in the first file too, except the ones that are the same. With
|
||||||
/// `keep_originals`, no file is deleted nor changed: the result is a new file (with the info of
|
/// `keep_originals`, no file is deleted nor changed: the result is a new file (with the info of
|
||||||
/// the first one and new ids), which comes right after the last of the files and is selected.
|
/// the first one and new ids), which comes right after the last of the files and is selected.
|
||||||
/// - tracks of a file: the first track gets their segments, as they are with `Group`, or all
|
/// - tracks of a file: the first track gets their segments, as they are with `Group`, or all
|
||||||
/// connected in one segment with `Connect`. The other tracks are removed.
|
/// connected in one segment with `Connect`. The other tracks are removed.
|
||||||
|
/// - routes of a file: the first route gets their trackpoints, all connected with `Connect`, and
|
||||||
|
/// the other routes are removed. A route has a single segment, so there is nothing to `Group`.
|
||||||
/// - segments of a track: they are all connected in a segment at the position of the first one
|
/// - segments of a track: they are all connected in a segment at the position of the first one
|
||||||
/// with `Connect`. With `Group` they are put one after the other, at that position.
|
/// with `Connect`. With `Group` they are put one after the other, at that position.
|
||||||
///
|
///
|
||||||
@@ -44,6 +48,7 @@ impl Apply for Merge {
|
|||||||
let selection = state.selection.clone();
|
let selection = state.selection.clone();
|
||||||
match &selection {
|
match &selection {
|
||||||
Selection::File { file_ids } => self.merge_files(state, file_ids),
|
Selection::File { file_ids } => self.merge_files(state, file_ids),
|
||||||
|
Selection::Route { file_id, rte_ids } => self.merge_routes(state, *file_id, rte_ids),
|
||||||
Selection::Track { file_id, trk_ids } => self.merge_tracks(state, *file_id, trk_ids),
|
Selection::Track { file_id, trk_ids } => self.merge_tracks(state, *file_id, trk_ids),
|
||||||
Selection::TrackSegment {
|
Selection::TrackSegment {
|
||||||
file_id,
|
file_id,
|
||||||
@@ -77,21 +82,26 @@ impl Merge {
|
|||||||
return Err(CommandError::NothingToDo);
|
return Err(CommandError::NothingToDo);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let mut routes: Vec<Route> = vec![];
|
||||||
let mut tracks: Vec<Track> = vec![];
|
let mut tracks: Vec<Track> = vec![];
|
||||||
|
let mut segments: Vec<TrackSegment> = vec![];
|
||||||
let mut waypoints: Vec<Waypoint> = vec![];
|
let mut waypoints: Vec<Waypoint> = vec![];
|
||||||
for id in &ordered {
|
for id in &ordered {
|
||||||
let file = &state.files[id];
|
let file = &state.files[id];
|
||||||
|
routes.extend(file.rte.iter().cloned());
|
||||||
tracks.extend(file.trk.iter().cloned());
|
tracks.extend(file.trk.iter().cloned());
|
||||||
|
segments.extend(file.segments().cloned());
|
||||||
for waypoint in file.wpt.iter() {
|
for waypoint in file.wpt.iter() {
|
||||||
if !waypoints.iter().any(|kept| kept.same_content(waypoint)) {
|
if !waypoints.iter().any(|kept| kept.same_content(waypoint)) {
|
||||||
waypoints.push(waypoint.clone());
|
waypoints.push(waypoint.clone());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let segments: Vec<TrackSegment> = tracks
|
// the first route or track, which holds the connected segment
|
||||||
.iter()
|
let first_is_route = ordered.iter().find_map(|id| {
|
||||||
.flat_map(|track| track.trkseg.iter().cloned())
|
let file = &state.files[id];
|
||||||
.collect();
|
(!file.has_no_path()).then(|| !file.rte.is_empty())
|
||||||
|
});
|
||||||
|
|
||||||
match self.type_ {
|
match self.type_ {
|
||||||
MergeType::Group if ordered.len() == 1 => return Err(CommandError::NothingToDo),
|
MergeType::Group if ordered.len() == 1 => return Err(CommandError::NothingToDo),
|
||||||
@@ -99,24 +109,35 @@ impl Merge {
|
|||||||
return Err(CommandError::NothingToDo);
|
return Err(CommandError::NothingToDo);
|
||||||
}
|
}
|
||||||
MergeType::Connect if !segments.is_empty() => {
|
MergeType::Connect if !segments.is_empty() => {
|
||||||
// a single track, which is the first one, with the connected segment
|
// a single route or track, which is the first one, with the connected segment
|
||||||
let merged = connect(&segments, segments[0].id, self.remove_gaps);
|
let merged = connect(&segments, segments[0].id, self.remove_gaps);
|
||||||
|
if first_is_route == Some(true) {
|
||||||
|
let first = Route {
|
||||||
|
seg: merged,
|
||||||
|
..routes[0].clone()
|
||||||
|
};
|
||||||
|
(routes, tracks) = (vec![first], vec![]);
|
||||||
|
} else {
|
||||||
let first = Track {
|
let first = Track {
|
||||||
trkseg: vec![merged],
|
trkseg: vec![merged],
|
||||||
..tracks[0].clone()
|
..tracks[0].clone()
|
||||||
};
|
};
|
||||||
tracks = vec![first];
|
(routes, tracks) = (vec![], vec![first]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut target = (*state.files[&target_id]).clone();
|
let mut target = (*state.files[&target_id]).clone();
|
||||||
|
target.rte = routes;
|
||||||
target.trk = tracks;
|
target.trk = tracks;
|
||||||
target.wpt = Waypoints::default();
|
target.wpt = Waypoints::default();
|
||||||
target.wpt.insert_at(0, waypoints);
|
target.wpt.insert_at(0, waypoints);
|
||||||
if self.keep_originals {
|
if self.keep_originals {
|
||||||
// a new file, whose tracks and segments do not share their ids with the originals
|
// a new file, whose routes, tracks and segments do not share their ids with the
|
||||||
|
// originals
|
||||||
target.id = Default::default();
|
target.id = Default::default();
|
||||||
|
target.rte = target.rte.iter().map(copy_route).collect();
|
||||||
target.trk = target.trk.iter().map(copy_track).collect();
|
target.trk = target.trk.iter().map(copy_track).collect();
|
||||||
let at = state
|
let at = state
|
||||||
.order
|
.order
|
||||||
@@ -139,6 +160,33 @@ impl Merge {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn merge_routes(
|
||||||
|
&self,
|
||||||
|
state: &mut State,
|
||||||
|
file_id: FileId,
|
||||||
|
rte_ids: &HashSet<RouteId>,
|
||||||
|
) -> Result<(), CommandError> {
|
||||||
|
let file = state.files.get(&file_id).ok_or(CommandError::NothingToDo)?;
|
||||||
|
let selected: Vec<usize> = (0..file.rte.len())
|
||||||
|
.filter(|i| rte_ids.contains(&file.rte[*i].id))
|
||||||
|
.collect();
|
||||||
|
if selected.len() < 2 || self.type_ == MergeType::Group {
|
||||||
|
return Err(CommandError::NothingToDo);
|
||||||
|
}
|
||||||
|
let first = selected[0];
|
||||||
|
let segments: Vec<TrackSegment> =
|
||||||
|
selected.iter().map(|i| file.rte[*i].seg.clone()).collect();
|
||||||
|
let mut file = (**file).clone();
|
||||||
|
file.rte[first].seg = connect(&segments, segments[0].id, self.remove_gaps);
|
||||||
|
let mut index = 0;
|
||||||
|
file.rte.retain(|_| {
|
||||||
|
index += 1;
|
||||||
|
!selected[1..].contains(&(index - 1))
|
||||||
|
});
|
||||||
|
state.files.insert(file_id, Rc::new(file));
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
fn merge_tracks(
|
fn merge_tracks(
|
||||||
&self,
|
&self,
|
||||||
state: &mut State,
|
state: &mut State,
|
||||||
|
|||||||
@@ -58,7 +58,8 @@ impl Apply for NewWaypoint<'_> {
|
|||||||
.filter(|id| file_ids.contains(id))
|
.filter(|id| file_ids.contains(id))
|
||||||
.copied()
|
.copied()
|
||||||
.collect(),
|
.collect(),
|
||||||
Selection::Track { file_id, .. }
|
Selection::Route { file_id, .. }
|
||||||
|
| Selection::Track { file_id, .. }
|
||||||
| Selection::TrackSegment { file_id, .. }
|
| Selection::TrackSegment { file_id, .. }
|
||||||
| Selection::Waypoints { file_id }
|
| Selection::Waypoints { file_id }
|
||||||
| Selection::Waypoint { file_id, .. } => vec![*file_id],
|
| Selection::Waypoint { file_id, .. } => vec![*file_id],
|
||||||
@@ -118,12 +119,14 @@ mod tests {
|
|||||||
New {
|
New {
|
||||||
name: "a",
|
name: "a",
|
||||||
trackpoint: None,
|
trackpoint: None,
|
||||||
|
route: false,
|
||||||
}
|
}
|
||||||
.apply(&mut fx.state())
|
.apply(&mut fx.state())
|
||||||
.unwrap();
|
.unwrap();
|
||||||
New {
|
New {
|
||||||
name: "b",
|
name: "b",
|
||||||
trackpoint: None,
|
trackpoint: None,
|
||||||
|
route: false,
|
||||||
}
|
}
|
||||||
.apply(&mut fx.state())
|
.apply(&mut fx.state())
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@@ -169,6 +172,7 @@ mod tests {
|
|||||||
New {
|
New {
|
||||||
name: "a",
|
name: "a",
|
||||||
trackpoint: None,
|
trackpoint: None,
|
||||||
|
route: false,
|
||||||
}
|
}
|
||||||
.apply(&mut fx.state())
|
.apply(&mut fx.state())
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@@ -196,6 +200,7 @@ mod tests {
|
|||||||
New {
|
New {
|
||||||
name,
|
name,
|
||||||
trackpoint: None,
|
trackpoint: None,
|
||||||
|
route: false,
|
||||||
}
|
}
|
||||||
.apply(&mut fx.state())
|
.apply(&mut fx.state())
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@@ -234,6 +239,7 @@ mod tests {
|
|||||||
New {
|
New {
|
||||||
name: "a",
|
name: "a",
|
||||||
trackpoint: None,
|
trackpoint: None,
|
||||||
|
route: false,
|
||||||
}
|
}
|
||||||
.apply(&mut fx.state())
|
.apply(&mut fx.state())
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@@ -250,6 +256,7 @@ mod tests {
|
|||||||
New {
|
New {
|
||||||
name: "a",
|
name: "a",
|
||||||
trackpoint: None,
|
trackpoint: None,
|
||||||
|
route: false,
|
||||||
}
|
}
|
||||||
.apply(&mut fx.state())
|
.apply(&mut fx.state())
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ impl Apply for Reduce {
|
|||||||
let mut changed = vec![];
|
let mut changed = vec![];
|
||||||
let mut kept_points = vec![];
|
let mut kept_points = vec![];
|
||||||
for location in &locations {
|
for location in &locations {
|
||||||
let segment = &state.files[&location.file_id].trk[location.trk].trkseg[location.seg];
|
let segment = location.segment(state.files);
|
||||||
let kept = reduce_indices(segment, self.tolerance);
|
let kept = reduce_indices(segment, self.tolerance);
|
||||||
if kept.len() == segment.len() {
|
if kept.len() == segment.len() {
|
||||||
continue;
|
continue;
|
||||||
|
|||||||
@@ -1,14 +1,15 @@
|
|||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
Apply, CommandError, File, FileId, Selection, State, TrackId, TrackSegmentId, end_time,
|
Apply, CommandError, File, FileId, RouteId, Selection, State, TrackId, TrackSegmentId,
|
||||||
reverse_segment, reverse_segments, reverse_tracks, start_time, track_end_time,
|
end_time, reverse_routes, reverse_segment, reverse_segments, reverse_tracks, start_time,
|
||||||
track_start_time,
|
track_end_time, track_start_time,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Reverses the direction of the selected elements: the whole of each selected file (its tracks,
|
/// Reverses the direction of the selected elements: the whole of each selected file (its routes,
|
||||||
/// the segments of its tracks and their trackpoints are in the opposite order), of each selected
|
/// its tracks, the segments of its tracks and their trackpoints are in the opposite order; the
|
||||||
/// track (its segments and their trackpoints), or each selected segment on its own (its
|
/// routes and the tracks are two wholes, as the routes stay before the tracks), of each selected
|
||||||
|
/// track (its segments and their trackpoints), or each selected route or segment on its own (its
|
||||||
/// trackpoints). The timestamps are mirrored, see [`reverse_segment`].
|
/// trackpoints). The timestamps are mirrored, see [`reverse_segment`].
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct Reverse;
|
pub struct Reverse;
|
||||||
@@ -20,9 +21,7 @@ impl Apply for Reverse {
|
|||||||
.segment_locations(state.files, &state.order.0);
|
.segment_locations(state.files, &state.order.0);
|
||||||
let points: usize = locations
|
let points: usize = locations
|
||||||
.iter()
|
.iter()
|
||||||
.map(|location| {
|
.map(|location| location.segment(state.files).len())
|
||||||
state.files[&location.file_id].trk[location.trk].trkseg[location.seg].len()
|
|
||||||
})
|
|
||||||
.sum();
|
.sum();
|
||||||
if points <= 1 {
|
if points <= 1 {
|
||||||
return Err(CommandError::NothingToDo);
|
return Err(CommandError::NothingToDo);
|
||||||
@@ -40,12 +39,18 @@ impl Apply for Reverse {
|
|||||||
Selection::File { file_ids } => {
|
Selection::File { file_ids } => {
|
||||||
for file_id in file_ids {
|
for file_id in file_ids {
|
||||||
edit(file_id, &|file| {
|
edit(file_id, &|file| {
|
||||||
|
let end = file.rte.last().and_then(|rte| end_time(&rte.seg));
|
||||||
|
let start = file.rte.first().and_then(|rte| start_time(&rte.seg));
|
||||||
|
reverse_routes(&mut file.rte, end, start);
|
||||||
let end = file.trk.last().and_then(track_end_time);
|
let end = file.trk.last().and_then(track_end_time);
|
||||||
let start = file.trk.first().and_then(track_start_time);
|
let start = file.trk.first().and_then(track_start_time);
|
||||||
reverse_tracks(&mut file.trk, end, start);
|
reverse_tracks(&mut file.trk, end, start);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Selection::Route { file_id, rte_ids } => edit(file_id, &|file| {
|
||||||
|
reverse_selected_routes(file, rte_ids);
|
||||||
|
}),
|
||||||
Selection::Track { file_id, trk_ids } => edit(file_id, &|file| {
|
Selection::Track { file_id, trk_ids } => edit(file_id, &|file| {
|
||||||
reverse_selected_tracks(file, trk_ids);
|
reverse_selected_tracks(file, trk_ids);
|
||||||
}),
|
}),
|
||||||
@@ -66,6 +71,13 @@ impl Apply for Reverse {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn reverse_selected_routes(file: &mut File, ids: &std::collections::HashSet<RouteId>) {
|
||||||
|
for route in file.rte.iter_mut().filter(|route| ids.contains(&route.id)) {
|
||||||
|
let (end, start) = (end_time(&route.seg), start_time(&route.seg));
|
||||||
|
reverse_segment(&mut route.seg, end, start);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn reverse_selected_tracks(file: &mut File, ids: &std::collections::HashSet<TrackId>) {
|
fn reverse_selected_tracks(file: &mut File, ids: &std::collections::HashSet<TrackId>) {
|
||||||
for track in file.trk.iter_mut().filter(|track| ids.contains(&track.id)) {
|
for track in file.trk.iter_mut().filter(|track| ids.contains(&track.id)) {
|
||||||
let end = track.trkseg.last().and_then(end_time);
|
let end = track.trkseg.last().and_then(end_time);
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ impl Apply for RoundTrip {
|
|||||||
.selection
|
.selection
|
||||||
.segment_locations(state.files, &state.order.0)
|
.segment_locations(state.files, &state.order.0)
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.filter(|l| state.files[&l.file_id].trk[l.trk].trkseg[l.seg].len() >= 2)
|
.filter(|l| l.segment(state.files).len() >= 2)
|
||||||
.collect();
|
.collect();
|
||||||
if locations.is_empty() {
|
if locations.is_empty() {
|
||||||
return Err(CommandError::NothingToDo);
|
return Err(CommandError::NothingToDo);
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
Apply, Categories, CommandError, FileId, SegmentLocation, Selection, State, Statistics, Track,
|
Apply, Categories, CommandError, FileId, SegmentIndex, SegmentLocation, Selection, State,
|
||||||
TrackSegment, Trackpoint, distance, replace_trackpoints,
|
Statistics, Track, TrackSegment, Trackpoint, distance, replace_trackpoints,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// The values of an OSM attribute (surface, highway...) of the new trackpoints of a [`Route`], as
|
/// The values of an OSM attribute (surface, highway...) of the new trackpoints of a [`Reroute`], as
|
||||||
/// the intervals of consecutive trackpoints that share one: `starts[i]` is the index of the first
|
/// the intervals of consecutive trackpoints that share one: `starts[i]` is the index of the first
|
||||||
/// trackpoint of the interval `i`, and `values[i]` its value, 0 when unknown, else 1 + the index
|
/// trackpoint of the interval `i`, and `values[i]` its value, 0 when unknown, else 1 + the index
|
||||||
/// of its name in `names`. No intervals means that the attribute is unknown everywhere.
|
/// of its name in `names`. No intervals means that the attribute is unknown everywhere.
|
||||||
@@ -64,7 +64,7 @@ impl RouteCategory<'_> {
|
|||||||
/// anchors anyway. The ones right before and after the range, between which the route goes, become
|
/// anchors anyway. The ones right before and after the range, between which the route goes, become
|
||||||
/// shown at every zoom level as well.
|
/// shown at every zoom level as well.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct Route<'a> {
|
pub struct Reroute<'a> {
|
||||||
pub start: u32,
|
pub start: u32,
|
||||||
pub end: u32,
|
pub end: u32,
|
||||||
pub lng: &'a [f64],
|
pub lng: &'a [f64],
|
||||||
@@ -89,7 +89,7 @@ pub(super) struct Target {
|
|||||||
pub end: usize,
|
pub end: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Apply for Route<'_> {
|
impl Apply for Reroute<'_> {
|
||||||
fn apply(self, state: &mut State) -> Result<(), CommandError> {
|
fn apply(self, state: &mut State) -> Result<(), CommandError> {
|
||||||
let (start, end) = (self.start as usize, self.end as usize);
|
let (start, end) = (self.start as usize, self.end as usize);
|
||||||
let len = self.lng.len();
|
let len = self.lng.len();
|
||||||
@@ -152,14 +152,17 @@ impl Apply for Route<'_> {
|
|||||||
}
|
}
|
||||||
let seg = file.trk[trk].trkseg.len() - 1;
|
let seg = file.trk[trk].trkseg.len() - 1;
|
||||||
Target {
|
Target {
|
||||||
location: SegmentLocation { file_id, trk, seg },
|
location: SegmentLocation {
|
||||||
|
file_id,
|
||||||
|
index: SegmentIndex::Track { trk, seg },
|
||||||
|
},
|
||||||
start: 0,
|
start: 0,
|
||||||
end: 0,
|
end: 0,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let segment = &mut file.trk[target.location.trk].trkseg[target.location.seg];
|
let segment = file.segment_mut(target.location.index);
|
||||||
let new_len = points.len();
|
let new_len = points.len();
|
||||||
let (speed, start_time) = speed_and_start_time(segment, &target, &points);
|
let (speed, start_time) = speed_and_start_time(segment, &target, &points);
|
||||||
let has_times = !segment.is_empty() && segment[0].time.is_some();
|
let has_times = !segment.is_empty() && segment[0].time.is_some();
|
||||||
@@ -208,7 +211,7 @@ pub(super) fn find_target(
|
|||||||
let segments: Vec<(SegmentLocation, usize)> = locations
|
let segments: Vec<(SegmentLocation, usize)> = locations
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|location| {
|
.map(|location| {
|
||||||
let segment = &state.files[&location.file_id].trk[location.trk].trkseg[location.seg];
|
let segment = location.segment(state.files);
|
||||||
(location, segment.len())
|
(location, segment.len())
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
@@ -382,8 +385,8 @@ mod tests {
|
|||||||
lng: &'a [f64],
|
lng: &'a [f64],
|
||||||
lat: &'a [f64],
|
lat: &'a [f64],
|
||||||
ele: &'a [f64],
|
ele: &'a [f64],
|
||||||
) -> Route<'a> {
|
) -> Reroute<'a> {
|
||||||
Route {
|
Reroute {
|
||||||
start,
|
start,
|
||||||
end,
|
end,
|
||||||
lng,
|
lng,
|
||||||
@@ -459,7 +462,7 @@ mod tests {
|
|||||||
route(0, 0, &[1.0], &[], &[]).apply(&mut fx.state()),
|
route(0, 0, &[1.0], &[], &[]).apply(&mut fx.state()),
|
||||||
route(0, len + 1, &[], &[], &[]).apply(&mut fx.state()),
|
route(0, len + 1, &[], &[], &[]).apply(&mut fx.state()),
|
||||||
route(len + 1, len + 1, &[1.0], &[1.0], &[1.0]).apply(&mut fx.state()),
|
route(len + 1, len + 1, &[1.0], &[1.0], &[1.0]).apply(&mut fx.state()),
|
||||||
Route {
|
Reroute {
|
||||||
anchors: &[1],
|
anchors: &[1],
|
||||||
..route(0, 0, &[1.0], &[1.0], &[1.0])
|
..route(0, 0, &[1.0], &[1.0], &[1.0])
|
||||||
}
|
}
|
||||||
@@ -589,7 +592,7 @@ mod tests {
|
|||||||
|
|
||||||
// 5 new points replacing the 2 in the middle, two of them are anchors
|
// 5 new points replacing the 2 in the middle, two of them are anchors
|
||||||
let (lng, lat, ele) = ([1.0; 5], [2.0; 5], [3.0; 5]);
|
let (lng, lat, ele) = ([1.0; 5], [2.0; 5], [3.0; 5]);
|
||||||
Route {
|
Reroute {
|
||||||
anchors: &[1, 3],
|
anchors: &[1, 3],
|
||||||
..route(1, 3, &lng, &lat, &ele)
|
..route(1, 3, &lng, &lat, &ele)
|
||||||
}
|
}
|
||||||
@@ -639,7 +642,7 @@ mod tests {
|
|||||||
let names = ["asphalt".to_string(), "gravel".to_string()];
|
let names = ["asphalt".to_string(), "gravel".to_string()];
|
||||||
let (lng, lat, ele) = ([1.0; 4], [2.0; 4], [3.0; 4]);
|
let (lng, lat, ele) = ([1.0; 4], [2.0; 4], [3.0; 4]);
|
||||||
// asphalt, asphalt, unknown, gravel
|
// asphalt, asphalt, unknown, gravel
|
||||||
Route {
|
Reroute {
|
||||||
surface: RouteCategory {
|
surface: RouteCategory {
|
||||||
starts: &[0, 2, 3],
|
starts: &[0, 2, 3],
|
||||||
values: &[1, 0, 2],
|
values: &[1, 0, 2],
|
||||||
@@ -683,7 +686,7 @@ mod tests {
|
|||||||
},
|
},
|
||||||
];
|
];
|
||||||
for surface in broken {
|
for surface in broken {
|
||||||
let result = Route {
|
let result = Reroute {
|
||||||
surface,
|
surface,
|
||||||
..route(0, 0, &lng, &lat, &ele)
|
..route(0, 0, &lng, &lat, &ele)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
Apply, CommandError, File, Selection, State, Track, TrackSegment, Waypoints, copy_file,
|
Apply, CommandError, File, Route, SegmentIndex, Selection, State, Track, TrackSegment,
|
||||||
copy_segment, copy_track, copy_waypoint,
|
Waypoints, copy_file, copy_route, copy_segment, copy_track, copy_waypoint,
|
||||||
};
|
};
|
||||||
|
|
||||||
use super::route::find_target;
|
use super::route::find_target;
|
||||||
@@ -13,24 +13,27 @@ use super::route::find_target;
|
|||||||
pub enum SplitType {
|
pub enum SplitType {
|
||||||
/// The file becomes two files, which both have the waypoints (copies, in the second one).
|
/// The file becomes two files, which both have the waypoints (copies, in the second one).
|
||||||
Files,
|
Files,
|
||||||
|
/// The route becomes two routes.
|
||||||
|
Routes,
|
||||||
/// The track becomes two tracks.
|
/// The track becomes two tracks.
|
||||||
Tracks,
|
Tracks,
|
||||||
/// The segment becomes two segments.
|
/// The segment of a track becomes two segments.
|
||||||
Segments,
|
Segments,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Cuts the file, the track or the segment of the trackpoint `at` of the selection (see
|
/// Cuts the file, the route, the track or the segment of the trackpoint `at` of the selection (see
|
||||||
/// `RoutingBuffer`) in two, there: the trackpoint is the last one of the first part and the first
|
/// `RoutingBuffer`) in two, there: the trackpoint is the last one of the first part and the first
|
||||||
/// one of the second part.
|
/// one of the second part. Cutting a route needs the trackpoint to be in a route, and cutting a
|
||||||
|
/// track or a segment needs it to be in a track: there is nothing to do otherwise.
|
||||||
///
|
///
|
||||||
/// The first part keeps the ids of what is cut, the second one has new ids, as the elements that
|
/// The first part keeps the ids of what is cut, the second one has new ids, as the elements that
|
||||||
/// come after the trackpoint (the following segments of the track, the following tracks of the
|
/// come after the trackpoint (the following segments of the track, the following routes and
|
||||||
/// file), which are moved to it. When the file is cut, the new file comes right after it. The
|
/// tracks of the file, the routes coming before the tracks), which are moved to it. When the file
|
||||||
/// selection does not change.
|
/// is cut, the new file comes right after it. The selection does not change.
|
||||||
///
|
///
|
||||||
/// With `keep_originals`, a file that is cut (`SplitType::Files`) is left as it is: its two parts
|
/// With `keep_originals`, a file that is cut (`SplitType::Files`) is left as it is: its two parts
|
||||||
/// are two new files, with new ids, which come right after it and are selected. Cutting a track
|
/// are two new files, with new ids, which come right after it and are selected. Cutting a route, a
|
||||||
/// or a segment changes the file in place anyway, so the flag has no effect on them.
|
/// track or a segment changes the file in place anyway, so the flag has no effect on them.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct Split {
|
pub struct Split {
|
||||||
pub at: u32,
|
pub at: u32,
|
||||||
@@ -43,104 +46,115 @@ impl Apply for Split {
|
|||||||
let at = self.at as usize;
|
let at = self.at as usize;
|
||||||
let target = find_target(state, at, at)?.ok_or(CommandError::NothingToDo)?;
|
let target = find_target(state, at, at)?.ok_or(CommandError::NothingToDo)?;
|
||||||
let location = target.location;
|
let location = target.location;
|
||||||
let (file_id, trk, seg, index) =
|
let (file_id, index) = (location.file_id, target.start);
|
||||||
(location.file_id, location.trk, location.seg, target.start);
|
let in_route = matches!(location.index, SegmentIndex::Route(_));
|
||||||
|
let fits = match self.split_type {
|
||||||
|
SplitType::Files => true,
|
||||||
|
SplitType::Routes => in_route,
|
||||||
|
SplitType::Tracks | SplitType::Segments => !in_route,
|
||||||
|
};
|
||||||
|
if !fits {
|
||||||
|
return Err(CommandError::NothingToDo);
|
||||||
|
}
|
||||||
let mut file = (*state.files[&file_id]).clone();
|
let mut file = (*state.files[&file_id]).clone();
|
||||||
if index >= file.trk[trk].trkseg[seg].len() {
|
if index >= file.segment(location.index).len() {
|
||||||
return Err(CommandError::InvalidData(
|
return Err(CommandError::InvalidData(
|
||||||
"trackpoint out of the segment".into(),
|
"trackpoint out of the segment".into(),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// with `SplitType::Files`, what goes to the second file: what comes after the trackpoint
|
||||||
|
let mut second_file = File {
|
||||||
|
id: Default::default(),
|
||||||
|
rte: vec![],
|
||||||
|
trk: vec![],
|
||||||
|
wpt: Waypoints::default(),
|
||||||
|
..file.clone()
|
||||||
|
};
|
||||||
|
match location.index {
|
||||||
|
SegmentIndex::Route(rte) => {
|
||||||
|
let route = file.rte[rte].clone();
|
||||||
|
let first = Route {
|
||||||
|
seg: keep_up_to(&route.seg, index),
|
||||||
|
..route.clone()
|
||||||
|
};
|
||||||
|
let second = Route {
|
||||||
|
id: Default::default(),
|
||||||
|
seg: keep_from(&route.seg, index),
|
||||||
|
..route.clone()
|
||||||
|
};
|
||||||
|
if self.split_type == SplitType::Routes {
|
||||||
|
file.rte.splice(rte..=rte, [first, second]);
|
||||||
|
state.files.insert(file_id, Rc::new(file));
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
// the following routes, and the tracks, which come after the routes
|
||||||
|
second_file.rte = [second]
|
||||||
|
.into_iter()
|
||||||
|
.chain(file.rte[rte + 1..].iter().map(copy_route))
|
||||||
|
.collect();
|
||||||
|
second_file.trk = file.trk.iter().map(copy_track).collect();
|
||||||
|
file.rte.truncate(rte);
|
||||||
|
file.rte.push(first);
|
||||||
|
file.trk.clear();
|
||||||
|
}
|
||||||
|
SegmentIndex::Track { trk, seg } => {
|
||||||
let track = file.trk[trk].clone();
|
let track = file.trk[trk].clone();
|
||||||
let segment = &track.trkseg[seg];
|
let segment = &track.trkseg[seg];
|
||||||
let (first, second) = (keep_up_to(segment, index), keep_from(segment, index));
|
let (first, second) = (keep_up_to(segment, index), keep_from(segment, index));
|
||||||
// the track is cut: what is before the segment, and its first part, then the second part
|
if self.split_type == SplitType::Segments {
|
||||||
// and what is after it
|
file.trk[trk].trkseg.splice(seg..=seg, [first, second]);
|
||||||
let split_track = || {
|
state.files.insert(file_id, Rc::new(file));
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
// the track is cut: what is before the segment, and its first part, then the
|
||||||
|
// second part and what is after it
|
||||||
let mut first_track = track.clone();
|
let mut first_track = track.clone();
|
||||||
first_track.trkseg.truncate(seg);
|
first_track.trkseg.truncate(seg);
|
||||||
first_track.trkseg.push(first.clone());
|
first_track.trkseg.push(first);
|
||||||
let mut second_track = Track {
|
let mut second_track = Track {
|
||||||
id: Default::default(),
|
id: Default::default(),
|
||||||
trkseg: vec![second.clone()],
|
trkseg: vec![second],
|
||||||
..track.clone()
|
..track.clone()
|
||||||
};
|
};
|
||||||
second_track
|
second_track
|
||||||
.trkseg
|
.trkseg
|
||||||
.extend(track.trkseg[seg + 1..].iter().map(copy_segment));
|
.extend(track.trkseg[seg + 1..].iter().map(copy_segment));
|
||||||
(first_track, second_track)
|
if self.split_type == SplitType::Tracks {
|
||||||
};
|
|
||||||
|
|
||||||
match self.split_type {
|
|
||||||
SplitType::Segments => {
|
|
||||||
file.trk[trk].trkseg.splice(seg..=seg, [first, second]);
|
|
||||||
}
|
|
||||||
SplitType::Tracks => {
|
|
||||||
let (first_track, second_track) = split_track();
|
|
||||||
file.trk.splice(trk..=trk, [first_track, second_track]);
|
file.trk.splice(trk..=trk, [first_track, second_track]);
|
||||||
|
state.files.insert(file_id, Rc::new(file));
|
||||||
|
return Ok(());
|
||||||
}
|
}
|
||||||
SplitType::Files if self.keep_originals => {
|
second_file.trk = [second_track]
|
||||||
let (first_track, second_track) = split_track();
|
.into_iter()
|
||||||
// the parts are new files: nothing is shared by id with the file, nor between them
|
.chain(file.trk[trk + 1..].iter().map(copy_track))
|
||||||
let first_file = copy_file(&File {
|
.collect();
|
||||||
trk: file.trk[..trk]
|
file.trk.truncate(trk);
|
||||||
.iter()
|
file.trk.push(first_track);
|
||||||
.cloned()
|
}
|
||||||
.chain([first_track])
|
}
|
||||||
.collect(),
|
|
||||||
..file.clone()
|
// the file is cut: both parts have the waypoints
|
||||||
});
|
|
||||||
let mut second_file = File {
|
|
||||||
id: Default::default(),
|
|
||||||
trk: vec![second_track],
|
|
||||||
wpt: Waypoints::default(),
|
|
||||||
..file.clone()
|
|
||||||
};
|
|
||||||
second_file
|
|
||||||
.trk
|
|
||||||
.extend(file.trk[trk + 1..].iter().map(copy_track));
|
|
||||||
second_file
|
second_file
|
||||||
.wpt
|
.wpt
|
||||||
.insert_at(0, file.wpt.iter().map(copy_waypoint).collect());
|
.insert_at(0, file.wpt.iter().map(copy_waypoint).collect());
|
||||||
|
|
||||||
let ids = [first_file.id, second_file.id];
|
|
||||||
let position = state.order.0.iter().position(|id| *id == file_id);
|
let position = state.order.0.iter().position(|id| *id == file_id);
|
||||||
let at = position.map_or(state.order.0.len(), |p| p + 1);
|
let at = position.map_or(state.order.0.len(), |p| p + 1);
|
||||||
|
if self.keep_originals {
|
||||||
|
// the parts are new files: nothing is shared by id with the file, nor between them
|
||||||
|
let first_file = copy_file(&file);
|
||||||
|
let ids = [first_file.id, second_file.id];
|
||||||
state.order.0.splice(at..at, ids);
|
state.order.0.splice(at..at, ids);
|
||||||
state.files.insert(first_file.id, Rc::new(first_file));
|
state.files.insert(first_file.id, Rc::new(first_file));
|
||||||
state.files.insert(second_file.id, Rc::new(second_file));
|
state.files.insert(second_file.id, Rc::new(second_file));
|
||||||
*state.selection = Selection::File {
|
*state.selection = Selection::File {
|
||||||
file_ids: ids.into(),
|
file_ids: ids.into(),
|
||||||
};
|
};
|
||||||
return Ok(());
|
} else {
|
||||||
}
|
state.order.0.insert(at, second_file.id);
|
||||||
SplitType::Files => {
|
|
||||||
let (first_track, second_track) = split_track();
|
|
||||||
let mut second_file = File {
|
|
||||||
id: Default::default(),
|
|
||||||
trk: vec![second_track],
|
|
||||||
wpt: Waypoints::default(),
|
|
||||||
..file.clone()
|
|
||||||
};
|
|
||||||
second_file
|
|
||||||
.trk
|
|
||||||
.extend(file.trk[trk + 1..].iter().map(copy_track));
|
|
||||||
second_file
|
|
||||||
.wpt
|
|
||||||
.insert_at(0, file.wpt.iter().map(copy_waypoint).collect());
|
|
||||||
|
|
||||||
file.trk.truncate(trk);
|
|
||||||
file.trk.push(first_track);
|
|
||||||
let position = state.order.0.iter().position(|id| *id == file_id);
|
|
||||||
state.order.0.insert(
|
|
||||||
position.map_or(state.order.0.len(), |p| p + 1),
|
|
||||||
second_file.id,
|
|
||||||
);
|
|
||||||
state.files.insert(second_file.id, Rc::new(second_file));
|
state.files.insert(second_file.id, Rc::new(second_file));
|
||||||
}
|
|
||||||
}
|
|
||||||
state.files.insert(file_id, Rc::new(file));
|
state.files.insert(file_id, Rc::new(file));
|
||||||
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -45,10 +45,8 @@ impl Apply for Time {
|
|||||||
let locations = state
|
let locations = state
|
||||||
.selection
|
.selection
|
||||||
.segment_locations(state.files, &state.order.0);
|
.segment_locations(state.files, &state.order.0);
|
||||||
let segments: Vec<&TrackSegment> = locations
|
let segments: Vec<&TrackSegment> =
|
||||||
.iter()
|
locations.iter().map(|l| l.segment(state.files)).collect();
|
||||||
.map(|l| &state.files[&l.file_id].trk[l.trk].trkseg[l.seg])
|
|
||||||
.collect();
|
|
||||||
if segments.iter().all(|segment| segment.is_empty()) {
|
if segments.iter().all(|segment| segment.is_empty()) {
|
||||||
return Err(CommandError::NothingToDo);
|
return Err(CommandError::NothingToDo);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ use std::collections::{HashMap, HashSet};
|
|||||||
use crate::{FileId, FileWaypointsRevisionId, Files, TrackSegmentId, TrackSegmentRevisionId};
|
use crate::{FileId, FileWaypointsRevisionId, Files, TrackSegmentId, TrackSegmentRevisionId};
|
||||||
|
|
||||||
/// Coordinates buffers, as flat `[lng, lat, lng, lat, ...]` arrays so that they can be handed
|
/// Coordinates buffers, as flat `[lng, lat, lng, lat, ...]` arrays so that they can be handed
|
||||||
/// to the UI without per-point calls: one per track segment (its trackpoints) and one per file
|
/// to the UI without per-point calls: one per segment of a route or track (its trackpoints) and one per file
|
||||||
/// (its waypoints). A buffer is only rebuilt when the revision of its segment (or the waypoints
|
/// (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.
|
/// of its file) changes, so editing a segment does not touch the buffers of the others.
|
||||||
#[derive(Debug, Default)]
|
#[derive(Debug, Default)]
|
||||||
@@ -30,7 +30,7 @@ impl CoordinatesCache {
|
|||||||
self.waypoints
|
self.waypoints
|
||||||
.insert(file.id, (file.wpt.rev_id, coordinates));
|
.insert(file.id, (file.wpt.rev_id, coordinates));
|
||||||
}
|
}
|
||||||
for seg in file.trk.iter().flat_map(|trk| &trk.trkseg) {
|
for seg in file.segments() {
|
||||||
segments.insert(seg.id);
|
segments.insert(seg.id);
|
||||||
if self
|
if self
|
||||||
.segments
|
.segments
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
use crate::{
|
use crate::{
|
||||||
File, FileId, FileWaypointsRevisionId, TrackId, TrackSegmentId, TrackSegmentRevisionId,
|
File, FileId, FileWaypointsRevisionId, RouteId, TrackId, TrackInfo, TrackSegment,
|
||||||
WaypointId,
|
TrackSegmentId, TrackSegmentRevisionId, WaypointId,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// What the UI needs to display a file: its name and the structure of its tracks and waypoints,
|
/// What the UI needs to display a file: its name and the structure of its routes, tracks and
|
||||||
|
/// waypoints,
|
||||||
/// with the ids that reference every element. Coordinates are not part of it, they are read
|
/// 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
|
/// 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
|
/// of a file is the `i`-th coordinates pair of its waypoint buffer, same for the trackpoints of
|
||||||
@@ -13,21 +14,47 @@ pub struct FileStructure {
|
|||||||
pub id: FileId,
|
pub id: FileId,
|
||||||
pub name: String,
|
pub name: String,
|
||||||
pub desc: Option<String>,
|
pub desc: Option<String>,
|
||||||
|
pub routes: Vec<RouteNode>,
|
||||||
pub tracks: Vec<TrackNode>,
|
pub tracks: Vec<TrackNode>,
|
||||||
pub waypoints: Vec<WaypointNode>,
|
pub waypoints: Vec<WaypointNode>,
|
||||||
/// Changes whenever the waypoints of the file (hence their buffer) change.
|
/// Changes whenever the waypoints of the file (hence their buffer) change.
|
||||||
pub wpt_rev_id: FileWaypointsRevisionId,
|
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)]
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
pub struct TrackNode {
|
pub struct PathInfo {
|
||||||
pub id: TrackId,
|
|
||||||
pub name: Option<String>,
|
pub name: Option<String>,
|
||||||
pub desc: Option<String>,
|
pub desc: Option<String>,
|
||||||
/// Style of the track, only when the file defines it.
|
|
||||||
pub color: Option<String>,
|
pub color: Option<String>,
|
||||||
pub opacity: Option<f64>,
|
pub opacity: Option<f64>,
|
||||||
pub width: 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 segments: Vec<SegmentNode>,
|
pub segments: Vec<SegmentNode>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -46,31 +73,38 @@ pub struct WaypointNode {
|
|||||||
pub sym: 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 {
|
impl FileStructure {
|
||||||
pub fn new(file: &File) -> Self {
|
pub fn new(file: &File) -> Self {
|
||||||
Self {
|
Self {
|
||||||
id: file.id,
|
id: file.id,
|
||||||
name: file.info.name.clone(),
|
name: file.info.name.clone(),
|
||||||
desc: file.info.desc.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
|
tracks: file
|
||||||
.trk
|
.trk
|
||||||
.iter()
|
.iter()
|
||||||
.map(|trk| TrackNode {
|
.map(|trk| TrackNode {
|
||||||
id: trk.id,
|
id: trk.id,
|
||||||
name: trk.info.name.clone(),
|
info: (&trk.info).into(),
|
||||||
desc: trk.info.desc.clone(),
|
segments: trk.trkseg.iter().map(Into::into).collect(),
|
||||||
color: trk.info.color.clone(),
|
|
||||||
opacity: trk.info.opacity,
|
|
||||||
width: trk.info.width,
|
|
||||||
segments: trk
|
|
||||||
.trkseg
|
|
||||||
.iter()
|
|
||||||
.map(|seg| SegmentNode {
|
|
||||||
id: seg.id,
|
|
||||||
rev_id: seg.rev_id,
|
|
||||||
len: seg.len(),
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
})
|
})
|
||||||
.collect(),
|
.collect(),
|
||||||
waypoints: file
|
waypoints: file
|
||||||
@@ -112,11 +146,8 @@ mod tests {
|
|||||||
);
|
);
|
||||||
assert_eq!(node.tracks.len(), file.trk.len());
|
assert_eq!(node.tracks.len(), file.trk.len());
|
||||||
for (n, t) in node.tracks.iter().zip(&file.trk) {
|
for (n, t) in node.tracks.iter().zip(&file.trk) {
|
||||||
assert_eq!((n.id, &n.name, &n.desc), (t.id, &t.info.name, &t.info.desc));
|
assert_eq!(n.id, t.id);
|
||||||
assert_eq!(
|
assert_eq!(n.info, PathInfo::from(&t.info));
|
||||||
(&n.color, n.opacity, n.width),
|
|
||||||
(&t.info.color, t.info.opacity, t.info.width)
|
|
||||||
);
|
|
||||||
assert_eq!(n.segments.len(), t.trkseg.len());
|
assert_eq!(n.segments.len(), t.trkseg.len());
|
||||||
for (n, s) in n.segments.iter().zip(&t.trkseg) {
|
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()));
|
assert_eq!((n.id, n.rev_id, n.len), (s.id, s.rev_id, s.len()));
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ impl RoutingBuffer {
|
|||||||
.map(|files| selection.segment_locations(files, order))
|
.map(|files| selection.segment_locations(files, order))
|
||||||
.unwrap_or_default()
|
.unwrap_or_default()
|
||||||
{
|
{
|
||||||
let segment = &files.unwrap()[&location.file_id].trk[location.trk].trkseg[location.seg];
|
let segment = location.segment(files.unwrap());
|
||||||
signature.push((segment.id, segment.rev_id));
|
signature.push((segment.id, segment.rev_id));
|
||||||
if segment.is_empty() {
|
if segment.is_empty() {
|
||||||
continue;
|
continue;
|
||||||
|
|||||||
@@ -18,8 +18,7 @@ impl StatisticsCache {
|
|||||||
let mut stale: HashSet<TrackSegmentRevisionId> = self.map.keys().copied().collect();
|
let mut stale: HashSet<TrackSegmentRevisionId> = self.map.keys().copied().collect();
|
||||||
if let Some(state) = state {
|
if let Some(state) = state {
|
||||||
for file in state.values() {
|
for file in state.values() {
|
||||||
for trk in file.trk.iter() {
|
for trkseg in file.segments() {
|
||||||
for trkseg in trk.trkseg.iter() {
|
|
||||||
match self.map.entry(trkseg.rev_id) {
|
match self.map.entry(trkseg.rev_id) {
|
||||||
Entry::Occupied(_) => {
|
Entry::Occupied(_) => {
|
||||||
stale.remove(&trkseg.rev_id);
|
stale.remove(&trkseg.rev_id);
|
||||||
@@ -31,7 +30,6 @@ impl StatisticsCache {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
for id in stale.iter() {
|
for id in stale.iter() {
|
||||||
self.map.remove(id);
|
self.map.remove(id);
|
||||||
}
|
}
|
||||||
@@ -72,6 +70,15 @@ impl StatisticsCache {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Selection::Route { file_id, rte_ids } => {
|
||||||
|
if let Some(file) = state.get(file_id) {
|
||||||
|
for rte in file.rte.iter() {
|
||||||
|
if rte_ids.contains(&rte.id) {
|
||||||
|
self.add_segment_stats(&rte.seg, &mut selected);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Selection::Track { file_id, trk_ids } => {
|
Selection::Track { file_id, trk_ids } => {
|
||||||
if let Some(file) = state.get(file_id) {
|
if let Some(file) = state.get(file_id) {
|
||||||
for trk in file.trk.iter() {
|
for trk in file.trk.iter() {
|
||||||
@@ -129,8 +136,8 @@ impl StatisticsCache {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn add_file_stats<'a>(&'a self, file: &'a File, selected: &mut Vec<SelectedSegment<'a>>) {
|
fn add_file_stats<'a>(&'a self, file: &'a File, selected: &mut Vec<SelectedSegment<'a>>) {
|
||||||
for trk in file.trk.iter() {
|
for trkseg in file.segments() {
|
||||||
self.add_track_stats(trk, selected);
|
self.add_segment_stats(trkseg, selected);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -82,7 +82,7 @@ impl<H: History> Engine<H> {
|
|||||||
.find(|wpt| wpt.id == *id)
|
.find(|wpt| wpt.id == *id)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A trackpoint of a segment of a file. `None` if it does not exist.
|
/// A trackpoint of a segment (of a route or a track) of a file. `None` if it does not exist.
|
||||||
pub fn trackpoint(
|
pub fn trackpoint(
|
||||||
&self,
|
&self,
|
||||||
file_id: &FileId,
|
file_id: &FileId,
|
||||||
@@ -93,9 +93,7 @@ impl<H: History> Engine<H> {
|
|||||||
.history
|
.history
|
||||||
.current()?
|
.current()?
|
||||||
.get(file_id)?
|
.get(file_id)?
|
||||||
.trk
|
.segments()
|
||||||
.iter()
|
|
||||||
.flat_map(|trk| &trk.trkseg)
|
|
||||||
.find(|seg| seg.id == *segment_id)?;
|
.find(|seg| seg.id == *segment_id)?;
|
||||||
(index < segment.len()).then(|| &segment[index])
|
(index < segment.len()).then(|| &segment[index])
|
||||||
}
|
}
|
||||||
@@ -109,11 +107,7 @@ impl<H: History> Engine<H> {
|
|||||||
self.selection
|
self.selection
|
||||||
.segment_locations(files, &self.order.0)
|
.segment_locations(files, &self.order.0)
|
||||||
.iter()
|
.iter()
|
||||||
.flat_map(|location| {
|
.flat_map(|location| reduction_distances(location.segment(files)))
|
||||||
reduction_distances(
|
|
||||||
&files[&location.file_id].trk[location.trk].trkseg[location.seg],
|
|
||||||
)
|
|
||||||
})
|
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,10 +3,18 @@ use std::rc::Rc;
|
|||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
File, FileId, Files, Selection, Track, TrackId, TrackSegment, TrackSegmentId, Waypoint,
|
File, FileId, Files, Route, RouteId, Selection, Track, TrackId, TrackSegment, TrackSegmentId,
|
||||||
WaypointId,
|
Waypoint, WaypointId,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/// A route in the clipboard, with the name of the file it comes from (the name of the new file
|
||||||
|
/// when it is pasted on its own).
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct ClipboardRoute {
|
||||||
|
pub route: Route,
|
||||||
|
pub file_name: String,
|
||||||
|
}
|
||||||
|
|
||||||
/// A track in the clipboard, with the name of the file it comes from (the name of the new file
|
/// A track in the clipboard, with the name of the file it comes from (the name of the new file
|
||||||
/// when it is pasted on its own).
|
/// when it is pasted on its own).
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
@@ -31,6 +39,7 @@ pub struct ClipboardSegment {
|
|||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub enum ClipboardContent {
|
pub enum ClipboardContent {
|
||||||
Files(Vec<Rc<File>>),
|
Files(Vec<Rc<File>>),
|
||||||
|
Routes(Vec<ClipboardRoute>),
|
||||||
Tracks(Vec<ClipboardTrack>),
|
Tracks(Vec<ClipboardTrack>),
|
||||||
Segments(Vec<ClipboardSegment>),
|
Segments(Vec<ClipboardSegment>),
|
||||||
Waypoints(Vec<Waypoint>),
|
Waypoints(Vec<Waypoint>),
|
||||||
@@ -84,6 +93,19 @@ impl Clipboard {
|
|||||||
.filter_map(|id| files.get(id).cloned())
|
.filter_map(|id| files.get(id).cloned())
|
||||||
.collect(),
|
.collect(),
|
||||||
),
|
),
|
||||||
|
Selection::Route { file_id, rte_ids } => {
|
||||||
|
let file = files.get(file_id)?;
|
||||||
|
ClipboardContent::Routes(
|
||||||
|
file.rte
|
||||||
|
.iter()
|
||||||
|
.filter(|rte| rte_ids.contains(&rte.id))
|
||||||
|
.map(|rte| ClipboardRoute {
|
||||||
|
route: rte.clone(),
|
||||||
|
file_name: file.info.name.clone(),
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
)
|
||||||
|
}
|
||||||
Selection::Track { file_id, trk_ids } => {
|
Selection::Track { file_id, trk_ids } => {
|
||||||
let file = files.get(file_id)?;
|
let file = files.get(file_id)?;
|
||||||
ClipboardContent::Tracks(
|
ClipboardContent::Tracks(
|
||||||
@@ -144,21 +166,23 @@ impl Clipboard {
|
|||||||
pub fn is_empty(&self) -> bool {
|
pub fn is_empty(&self) -> bool {
|
||||||
match &self.content {
|
match &self.content {
|
||||||
ClipboardContent::Files(files) => files.is_empty(),
|
ClipboardContent::Files(files) => files.is_empty(),
|
||||||
|
ClipboardContent::Routes(routes) => routes.is_empty(),
|
||||||
ClipboardContent::Tracks(tracks) => tracks.is_empty(),
|
ClipboardContent::Tracks(tracks) => tracks.is_empty(),
|
||||||
ClipboardContent::Segments(segments) => segments.is_empty(),
|
ClipboardContent::Segments(segments) => segments.is_empty(),
|
||||||
ClipboardContent::Waypoints(waypoints) => waypoints.is_empty(),
|
ClipboardContent::Waypoints(waypoints) => waypoints.is_empty(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether the content can be pasted when `target` is selected: files and tracks can be
|
/// Whether the content can be pasted when `target` is selected: files, routes and tracks can
|
||||||
/// pasted anywhere above them in the file tree, and nothing selected stands for the list of
|
/// be pasted anywhere above them in the file tree (routes and tracks are at the same level),
|
||||||
/// files.
|
/// and nothing selected stands for the list of files.
|
||||||
///
|
///
|
||||||
/// | copied | pasted when selected |
|
/// | copied | pasted when selected |
|
||||||
/// |-----------|------------------------------------------|
|
/// |-----------|-----------------------------------------------|
|
||||||
/// | files | nothing, a file |
|
/// | files | nothing, a file |
|
||||||
/// | tracks | nothing, a file, a track |
|
/// | routes | nothing, a file, a route, a track |
|
||||||
/// | segments | nothing, a file, a track, a segment |
|
/// | tracks | nothing, a file, a route, a track |
|
||||||
|
/// | segments | nothing, a file, a route, a track, a segment |
|
||||||
/// | waypoints | a file, the waypoints, a waypoint |
|
/// | waypoints | a file, the waypoints, a waypoint |
|
||||||
pub fn can_paste(&self, target: &Selection) -> bool {
|
pub fn can_paste(&self, target: &Selection) -> bool {
|
||||||
use ClipboardContent as C;
|
use ClipboardContent as C;
|
||||||
@@ -166,10 +190,13 @@ impl Clipboard {
|
|||||||
matches!(
|
matches!(
|
||||||
(&self.content, target),
|
(&self.content, target),
|
||||||
(C::Files(_), Empty | File { .. })
|
(C::Files(_), Empty | File { .. })
|
||||||
| (C::Tracks(_), Empty | File { .. } | Track { .. })
|
| (
|
||||||
|
C::Routes(_) | C::Tracks(_),
|
||||||
|
Empty | File { .. } | Route { .. } | Track { .. }
|
||||||
|
)
|
||||||
| (
|
| (
|
||||||
C::Segments(_),
|
C::Segments(_),
|
||||||
Empty | File { .. } | Track { .. } | TrackSegment { .. }
|
Empty | File { .. } | Route { .. } | Track { .. } | TrackSegment { .. }
|
||||||
)
|
)
|
||||||
| (
|
| (
|
||||||
C::Waypoints(_),
|
C::Waypoints(_),
|
||||||
@@ -183,6 +210,7 @@ impl Clipboard {
|
|||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub enum ClipboardIds {
|
pub enum ClipboardIds {
|
||||||
Files(Vec<FileId>),
|
Files(Vec<FileId>),
|
||||||
|
Routes(Vec<RouteId>),
|
||||||
Tracks(Vec<TrackId>),
|
Tracks(Vec<TrackId>),
|
||||||
Segments(Vec<TrackSegmentId>),
|
Segments(Vec<TrackSegmentId>),
|
||||||
Waypoints(Vec<WaypointId>),
|
Waypoints(Vec<WaypointId>),
|
||||||
@@ -194,6 +222,9 @@ impl ClipboardContent {
|
|||||||
ClipboardContent::Files(files) => {
|
ClipboardContent::Files(files) => {
|
||||||
ClipboardIds::Files(files.iter().map(|file| file.id).collect())
|
ClipboardIds::Files(files.iter().map(|file| file.id).collect())
|
||||||
}
|
}
|
||||||
|
ClipboardContent::Routes(routes) => {
|
||||||
|
ClipboardIds::Routes(routes.iter().map(|rte| rte.route.id).collect())
|
||||||
|
}
|
||||||
ClipboardContent::Tracks(tracks) => {
|
ClipboardContent::Tracks(tracks) => {
|
||||||
ClipboardIds::Tracks(tracks.iter().map(|trk| trk.track.id).collect())
|
ClipboardIds::Tracks(tracks.iter().map(|trk| trk.track.id).collect())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
use std::collections::HashSet;
|
use std::collections::HashSet;
|
||||||
|
|
||||||
use crate::{FileId, Files, TrackId, TrackSegmentId, WaypointId};
|
use crate::{
|
||||||
|
File, FileId, Files, RouteId, SegmentIndex, TrackId, TrackSegment, TrackSegmentId, WaypointId,
|
||||||
|
};
|
||||||
|
|
||||||
/// How a new selection combines with the current one.
|
/// How a new selection combines with the current one.
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)]
|
||||||
@@ -23,6 +25,10 @@ pub enum Selection {
|
|||||||
File {
|
File {
|
||||||
file_ids: HashSet<FileId>,
|
file_ids: HashSet<FileId>,
|
||||||
},
|
},
|
||||||
|
Route {
|
||||||
|
file_id: FileId,
|
||||||
|
rte_ids: HashSet<RouteId>,
|
||||||
|
},
|
||||||
Track {
|
Track {
|
||||||
file_id: FileId,
|
file_id: FileId,
|
||||||
trk_ids: HashSet<TrackId>,
|
trk_ids: HashSet<TrackId>,
|
||||||
@@ -41,12 +47,19 @@ pub enum Selection {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Where a track segment is: its file, then its track and its own position in it.
|
/// Where a segment is: its file, then its place in it (its route, or its track and its own
|
||||||
|
/// position in it).
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
pub struct SegmentLocation {
|
pub struct SegmentLocation {
|
||||||
pub file_id: FileId,
|
pub file_id: FileId,
|
||||||
pub trk: usize,
|
pub index: SegmentIndex,
|
||||||
pub seg: usize,
|
}
|
||||||
|
|
||||||
|
impl SegmentLocation {
|
||||||
|
/// The segment, in `files`. Panics if it is not there.
|
||||||
|
pub fn segment<'a>(&self, files: &'a Files) -> &'a TrackSegment {
|
||||||
|
files[&self.file_id].segment(self.index)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Selection {
|
impl Selection {
|
||||||
@@ -89,23 +102,18 @@ impl Selection {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Selection {
|
impl Selection {
|
||||||
/// The track segments covered by the selection, in order: the segments of several selected
|
/// The segments covered by the selection, in order: the segments of several selected files
|
||||||
/// files follow `order` (the files missing from it come last), then the tracks and segments
|
/// follow `order` (the files missing from it come last), then the routes, tracks and segments
|
||||||
/// follow the file. Waypoints are not segments: selecting only waypoints covers none.
|
/// follow the file (see [`File::segments`]). Waypoints are not segments: selecting only
|
||||||
|
/// waypoints covers none.
|
||||||
pub fn segment_locations(&self, files: &Files, order: &[FileId]) -> Vec<SegmentLocation> {
|
pub fn segment_locations(&self, files: &Files, order: &[FileId]) -> Vec<SegmentLocation> {
|
||||||
let mut locations = vec![];
|
let mut locations = vec![];
|
||||||
let mut add = |file_id: FileId,
|
let mut add = |file_id: FileId, filter: &dyn Fn(&File, SegmentIndex) -> bool| {
|
||||||
trk_filter: &dyn Fn(&crate::Track) -> bool,
|
|
||||||
seg_filter: &dyn Fn(&crate::TrackSegment) -> bool| {
|
|
||||||
let Some(file) = files.get(&file_id) else {
|
let Some(file) = files.get(&file_id) else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
for (trk, track) in file.trk.iter().enumerate().filter(|(_, t)| trk_filter(t)) {
|
for index in file.segment_indices().filter(|index| filter(file, *index)) {
|
||||||
for (seg, segment) in track.trkseg.iter().enumerate() {
|
locations.push(SegmentLocation { file_id, index });
|
||||||
if seg_filter(segment) {
|
|
||||||
locations.push(SegmentLocation { file_id, trk, seg });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
match self {
|
match self {
|
||||||
@@ -116,25 +124,35 @@ impl Selection {
|
|||||||
.filter(|id| file_ids.contains(id))
|
.filter(|id| file_ids.contains(id))
|
||||||
.chain(file_ids.iter().filter(|id| !order.contains(id)));
|
.chain(file_ids.iter().filter(|id| !order.contains(id)));
|
||||||
for id in ordered {
|
for id in ordered {
|
||||||
add(*id, &|_| true, &|_| true);
|
add(*id, &|_, _| true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Selection::Track { file_id, trk_ids } => {
|
Selection::Route { file_id, rte_ids } => add(*file_id, &|file, index| match index {
|
||||||
add(*file_id, &|trk| trk_ids.contains(&trk.id), &|_| true)
|
SegmentIndex::Route(rte) => rte_ids.contains(&file.rte[rte].id),
|
||||||
}
|
SegmentIndex::Track { .. } => false,
|
||||||
|
}),
|
||||||
|
Selection::Track { file_id, trk_ids } => add(*file_id, &|file, index| match index {
|
||||||
|
SegmentIndex::Track { trk, .. } => trk_ids.contains(&file.trk[trk].id),
|
||||||
|
SegmentIndex::Route(_) => false,
|
||||||
|
}),
|
||||||
Selection::TrackSegment {
|
Selection::TrackSegment {
|
||||||
file_id,
|
file_id,
|
||||||
trk_id,
|
trk_id,
|
||||||
trkseg_ids,
|
trkseg_ids,
|
||||||
} => add(*file_id, &|trk| trk.id == *trk_id, &|seg| {
|
} => add(*file_id, &|file, index| match index {
|
||||||
trkseg_ids.contains(&seg.id)
|
SegmentIndex::Track { trk, seg } => {
|
||||||
|
let track = &file.trk[trk];
|
||||||
|
track.id == *trk_id && trkseg_ids.contains(&track.trkseg[seg].id)
|
||||||
|
}
|
||||||
|
SegmentIndex::Route(_) => false,
|
||||||
}),
|
}),
|
||||||
}
|
}
|
||||||
locations
|
locations
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Drops what does not exist anymore (e.g. after an undo): files, and the tracks, segments
|
/// Drops what does not exist anymore (e.g. after an undo): files, and the routes, tracks,
|
||||||
/// and waypoints of the files that remain. A selection left with nothing becomes empty.
|
/// segments and waypoints of the files that remain. A selection left with nothing becomes
|
||||||
|
/// empty.
|
||||||
pub fn retain_existing(&mut self, files: &Files) {
|
pub fn retain_existing(&mut self, files: &Files) {
|
||||||
let empty = match self {
|
let empty = match self {
|
||||||
Selection::Empty => false,
|
Selection::Empty => false,
|
||||||
@@ -142,6 +160,13 @@ impl Selection {
|
|||||||
file_ids.retain(|id| files.contains_key(id));
|
file_ids.retain(|id| files.contains_key(id));
|
||||||
file_ids.is_empty()
|
file_ids.is_empty()
|
||||||
}
|
}
|
||||||
|
Selection::Route { file_id, rte_ids } => match files.get(file_id) {
|
||||||
|
Some(file) => {
|
||||||
|
rte_ids.retain(|id| file.rte.iter().any(|rte| rte.id == *id));
|
||||||
|
rte_ids.is_empty()
|
||||||
|
}
|
||||||
|
None => true,
|
||||||
|
},
|
||||||
Selection::Track { file_id, trk_ids } => match files.get(file_id) {
|
Selection::Track { file_id, trk_ids } => match files.get(file_id) {
|
||||||
Some(file) => {
|
Some(file) => {
|
||||||
trk_ids.retain(|id| file.trk.iter().any(|trk| trk.id == *id));
|
trk_ids.retain(|id| file.trk.iter().any(|trk| trk.id == *id));
|
||||||
@@ -185,6 +210,13 @@ impl Selection {
|
|||||||
(Selection::File { file_ids }, Selection::File { file_ids: other }) => {
|
(Selection::File { file_ids }, Selection::File { file_ids: other }) => {
|
||||||
file_ids.extend(other)
|
file_ids.extend(other)
|
||||||
}
|
}
|
||||||
|
(
|
||||||
|
Selection::Route { file_id, rte_ids },
|
||||||
|
Selection::Route {
|
||||||
|
file_id: other_file,
|
||||||
|
rte_ids: other,
|
||||||
|
},
|
||||||
|
) if *file_id == other_file => rte_ids.extend(other),
|
||||||
(
|
(
|
||||||
Selection::Track { file_id, trk_ids },
|
Selection::Track { file_id, trk_ids },
|
||||||
Selection::Track {
|
Selection::Track {
|
||||||
@@ -232,6 +264,16 @@ impl Selection {
|
|||||||
toggle_ids(file_ids, other);
|
toggle_ids(file_ids, other);
|
||||||
file_ids.is_empty()
|
file_ids.is_empty()
|
||||||
}
|
}
|
||||||
|
(
|
||||||
|
Selection::Route { file_id, rte_ids },
|
||||||
|
Selection::Route {
|
||||||
|
file_id: other_file,
|
||||||
|
rte_ids: other,
|
||||||
|
},
|
||||||
|
) if *file_id == other_file => {
|
||||||
|
toggle_ids(rte_ids, other);
|
||||||
|
rte_ids.is_empty()
|
||||||
|
}
|
||||||
(
|
(
|
||||||
Selection::Track { file_id, trk_ids },
|
Selection::Track { file_id, trk_ids },
|
||||||
Selection::Track {
|
Selection::Track {
|
||||||
@@ -325,7 +367,8 @@ impl Selection {
|
|||||||
match self {
|
match self {
|
||||||
Selection::Empty => Selection::Empty,
|
Selection::Empty => Selection::Empty,
|
||||||
Selection::File { .. } => self.clone(),
|
Selection::File { .. } => self.clone(),
|
||||||
Selection::Track { file_id, .. }
|
Selection::Route { file_id, .. }
|
||||||
|
| Selection::Track { file_id, .. }
|
||||||
| Selection::TrackSegment { file_id, .. }
|
| Selection::TrackSegment { file_id, .. }
|
||||||
| Selection::Waypoints { file_id }
|
| Selection::Waypoints { file_id }
|
||||||
| Selection::Waypoint { file_id, .. } => Selection::File {
|
| Selection::Waypoint { file_id, .. } => Selection::File {
|
||||||
@@ -335,7 +378,7 @@ impl Selection {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Selects all the elements of the same kind as the selected ones, in the same place: all
|
/// Selects all the elements of the same kind as the selected ones, in the same place: all
|
||||||
/// the files, all the tracks of the file, all the segments of the track, all the waypoints
|
/// the files, all the routes (or tracks) of the file, all the segments of the track, all the waypoints
|
||||||
/// of the file. All the files when nothing is selected. `None` when there is nothing to
|
/// of the file. All the files when nothing is selected. `None` when there is nothing to
|
||||||
/// select (the waypoints node, or a file that does not exist).
|
/// select (the waypoints node, or a file that does not exist).
|
||||||
pub fn all_at_level(&self, files: &Files, order: &[FileId]) -> Option<Selection> {
|
pub fn all_at_level(&self, files: &Files, order: &[FileId]) -> Option<Selection> {
|
||||||
@@ -343,6 +386,10 @@ impl Selection {
|
|||||||
Selection::Empty | Selection::File { .. } => Some(Selection::File {
|
Selection::Empty | Selection::File { .. } => Some(Selection::File {
|
||||||
file_ids: order.iter().copied().collect(),
|
file_ids: order.iter().copied().collect(),
|
||||||
}),
|
}),
|
||||||
|
Selection::Route { file_id, .. } => Some(Selection::Route {
|
||||||
|
file_id: *file_id,
|
||||||
|
rte_ids: files.get(file_id)?.rte.iter().map(|rte| rte.id).collect(),
|
||||||
|
}),
|
||||||
Selection::Track { file_id, .. } => Some(Selection::Track {
|
Selection::Track { file_id, .. } => Some(Selection::Track {
|
||||||
file_id: *file_id,
|
file_id: *file_id,
|
||||||
trk_ids: files.get(file_id)?.trk.iter().map(|trk| trk.id).collect(),
|
trk_ids: files.get(file_id)?.trk.iter().map(|trk| trk.id).collect(),
|
||||||
@@ -371,7 +418,7 @@ impl Selection {
|
|||||||
|
|
||||||
/// The element next to the selected ones, as a selection of that one element: the next one
|
/// The element next to the selected ones, as a selection of that one element: the next one
|
||||||
/// (`down`) or the previous one among the elements of the same kind, in the same place.
|
/// (`down`) or the previous one among the elements of the same kind, in the same place.
|
||||||
/// The tracks, segments and waypoints stop at their ends, the files wrap around and skip
|
/// The routes, tracks, segments and waypoints stop at their ends, the files wrap around and skip
|
||||||
/// the ones that are already selected. `None` when there is no such element.
|
/// the ones that are already selected. `None` when there is no such element.
|
||||||
pub fn neighbour(&self, files: &Files, order: &[FileId], down: bool) -> Option<Selection> {
|
pub fn neighbour(&self, files: &Files, order: &[FileId], down: bool) -> Option<Selection> {
|
||||||
match self {
|
match self {
|
||||||
@@ -393,6 +440,13 @@ impl Selection {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Selection::Route { file_id, rte_ids } => {
|
||||||
|
let ids: Vec<RouteId> = files.get(file_id)?.rte.iter().map(|r| r.id).collect();
|
||||||
|
Some(Selection::Route {
|
||||||
|
file_id: *file_id,
|
||||||
|
rte_ids: [neighbour(&ids, rte_ids, down)?].into(),
|
||||||
|
})
|
||||||
|
}
|
||||||
Selection::Track { file_id, trk_ids } => {
|
Selection::Track { file_id, trk_ids } => {
|
||||||
let ids: Vec<TrackId> = files.get(file_id)?.trk.iter().map(|t| t.id).collect();
|
let ids: Vec<TrackId> = files.get(file_id)?.trk.iter().map(|t| t.id).collect();
|
||||||
Some(Selection::Track {
|
Some(Selection::Track {
|
||||||
|
|||||||
@@ -87,6 +87,7 @@ fn new(engine: &mut TestEngine, name: &str) -> bool {
|
|||||||
Command::New(New {
|
Command::New(New {
|
||||||
name,
|
name,
|
||||||
trackpoint: None,
|
trackpoint: None,
|
||||||
|
route: false,
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1489,6 +1490,7 @@ mod per_file_history {
|
|||||||
.execute(Action::Edit(Command::New(New {
|
.execute(Action::Edit(Command::New(New {
|
||||||
name,
|
name,
|
||||||
trackpoint: None,
|
trackpoint: None,
|
||||||
|
route: false,
|
||||||
})))
|
})))
|
||||||
.unwrap();
|
.unwrap();
|
||||||
*engine.order().last().unwrap()
|
*engine.order().last().unwrap()
|
||||||
|
|||||||
@@ -18,9 +18,9 @@ use serde::{Deserialize, Serialize};
|
|||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
File, FileId, FileInfo, Track, TrackId, TrackInfo, TrackSegment, TrackSegmentId,
|
File, FileId, FileInfo, Route, RouteId, Track, TrackId, TrackInfo, TrackSegment,
|
||||||
TrackpointCategories, TrackpointChunk, TrackpointChunkId, Waypoint, WaypointChunk,
|
TrackSegmentId, TrackpointCategories, TrackpointChunk, TrackpointChunkId, Waypoint,
|
||||||
WaypointChunkId, Waypoints,
|
WaypointChunk, WaypointChunkId, Waypoints,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// The version that is written.
|
/// The version that is written.
|
||||||
@@ -54,10 +54,17 @@ fn parse<'a, T: Deserialize<'a>>(data: &'a [u8]) -> Result<T, DecodeError> {
|
|||||||
/// A file without its trackpoints and waypoints, which are in chunks.
|
/// A file without its trackpoints and waypoints, which are in chunks.
|
||||||
pub struct FileRecord {
|
pub struct FileRecord {
|
||||||
info: FileInfo,
|
info: FileInfo,
|
||||||
|
routes: Vec<RouteRecord>,
|
||||||
tracks: Vec<TrackRecord>,
|
tracks: Vec<TrackRecord>,
|
||||||
waypoints: Vec<WaypointChunkId>,
|
waypoints: Vec<WaypointChunkId>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
struct RouteRecord {
|
||||||
|
id: RouteId,
|
||||||
|
info: TrackInfo,
|
||||||
|
segment: SegmentRecord,
|
||||||
|
}
|
||||||
|
|
||||||
struct TrackRecord {
|
struct TrackRecord {
|
||||||
id: TrackId,
|
id: TrackId,
|
||||||
info: TrackInfo,
|
info: TrackInfo,
|
||||||
@@ -69,24 +76,35 @@ struct SegmentRecord {
|
|||||||
chunks: Vec<TrackpointChunkId>,
|
chunks: Vec<TrackpointChunkId>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl From<v1::SegmentRecord1> for SegmentRecord {
|
||||||
|
fn from(segment: v1::SegmentRecord1) -> Self {
|
||||||
|
Self {
|
||||||
|
id: TrackSegmentId(segment.id),
|
||||||
|
chunks: segment.chunks.into_iter().map(TrackpointChunkId).collect(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl From<v1::FileRecord1> for FileRecord {
|
impl From<v1::FileRecord1> for FileRecord {
|
||||||
fn from(record: v1::FileRecord1) -> Self {
|
fn from(record: v1::FileRecord1) -> Self {
|
||||||
Self {
|
Self {
|
||||||
info: record.info.into(),
|
info: record.info.into(),
|
||||||
|
routes: record
|
||||||
|
.routes
|
||||||
|
.into_iter()
|
||||||
|
.map(|route| RouteRecord {
|
||||||
|
id: RouteId(route.id),
|
||||||
|
info: route.info.into(),
|
||||||
|
segment: route.segment.into(),
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
tracks: record
|
tracks: record
|
||||||
.tracks
|
.tracks
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|track| TrackRecord {
|
.map(|track| TrackRecord {
|
||||||
id: TrackId(track.id),
|
id: TrackId(track.id),
|
||||||
info: track.info.into(),
|
info: track.info.into(),
|
||||||
segments: track
|
segments: track.segments.into_iter().map(Into::into).collect(),
|
||||||
.segments
|
|
||||||
.into_iter()
|
|
||||||
.map(|segment| SegmentRecord {
|
|
||||||
id: TrackSegmentId(segment.id),
|
|
||||||
chunks: segment.chunks.into_iter().map(TrackpointChunkId).collect(),
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
})
|
})
|
||||||
.collect(),
|
.collect(),
|
||||||
waypoints: record.waypoints.into_iter().map(WaypointChunkId).collect(),
|
waypoints: record.waypoints.into_iter().map(WaypointChunkId).collect(),
|
||||||
@@ -108,16 +126,27 @@ impl FileRecord {
|
|||||||
info: self.info,
|
info: self.info,
|
||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
for track in self.tracks {
|
let segment = |record: SegmentRecord| {
|
||||||
let mut trkseg = Vec::with_capacity(track.segments.len());
|
|
||||||
for segment in track.segments {
|
|
||||||
let mut built = TrackSegment::default();
|
let mut built = TrackSegment::default();
|
||||||
built.id = segment.id;
|
built.id = record.id;
|
||||||
for chunk in &segment.chunks {
|
for chunk in &record.chunks {
|
||||||
built.push_shared(trackpoint_chunks(chunk)?);
|
built.push_shared(trackpoint_chunks(chunk)?);
|
||||||
}
|
}
|
||||||
trkseg.push(built);
|
Some(built)
|
||||||
|
};
|
||||||
|
for route in self.routes {
|
||||||
|
file.rte.push(Route {
|
||||||
|
id: route.id,
|
||||||
|
info: route.info,
|
||||||
|
seg: segment(route.segment)?,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
for track in self.tracks {
|
||||||
|
let trkseg = track
|
||||||
|
.segments
|
||||||
|
.into_iter()
|
||||||
|
.map(segment)
|
||||||
|
.collect::<Option<Vec<_>>>()?;
|
||||||
file.trk.push(Track {
|
file.trk.push(Track {
|
||||||
id: track.id,
|
id: track.id,
|
||||||
info: track.info,
|
info: track.info,
|
||||||
@@ -292,6 +321,20 @@ mod tests {
|
|||||||
});
|
});
|
||||||
let mut empty = TrackSegment::default();
|
let mut empty = TrackSegment::default();
|
||||||
empty.id = TrackSegmentId(id(6));
|
empty.id = TrackSegmentId(id(6));
|
||||||
|
// a route, whose segment shares the chunk of the track
|
||||||
|
let mut route_segment = TrackSegment::default();
|
||||||
|
route_segment.id = TrackSegmentId(id(10));
|
||||||
|
route_segment.push_shared(segment.chunks()[0].clone());
|
||||||
|
file.rte.push(Route {
|
||||||
|
id: RouteId(id(9)),
|
||||||
|
info: TrackInfo {
|
||||||
|
name: Some("route".into()),
|
||||||
|
type_: Some("Hiking".into()),
|
||||||
|
color: Some("00ff00".into()),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
seg: route_segment,
|
||||||
|
});
|
||||||
file.trk.push(Track {
|
file.trk.push(Track {
|
||||||
id: TrackId(id(2)),
|
id: TrackId(id(2)),
|
||||||
info: TrackInfo {
|
info: TrackInfo {
|
||||||
@@ -352,9 +395,7 @@ mod tests {
|
|||||||
HashMap<WaypointChunkId, Rc<WaypointChunk>>,
|
HashMap<WaypointChunkId, Rc<WaypointChunk>>,
|
||||||
) {
|
) {
|
||||||
let trackpoints = file
|
let trackpoints = file
|
||||||
.trk
|
.segments()
|
||||||
.iter()
|
|
||||||
.flat_map(|track| &track.trkseg)
|
|
||||||
.flat_map(|segment| segment.chunks().iter().map(|c| (c.id, c.clone())))
|
.flat_map(|segment| segment.chunks().iter().map(|c| (c.id, c.clone())))
|
||||||
.collect();
|
.collect();
|
||||||
let waypoints = file
|
let waypoints = file
|
||||||
@@ -373,20 +414,29 @@ mod tests {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn assert_same_file(a: &File, b: &File) {
|
fn assert_same_segment(a: &TrackSegment, b: &TrackSegment) {
|
||||||
assert_eq!(a.id, b.id);
|
|
||||||
assert_eq!(a.info, b.info);
|
|
||||||
assert_eq!(a.trk.len(), b.trk.len());
|
|
||||||
for (a, b) in a.trk.iter().zip(&b.trk) {
|
|
||||||
assert_eq!((a.id, &a.info), (b.id, &b.info));
|
|
||||||
assert_eq!(a.trkseg.len(), b.trkseg.len());
|
|
||||||
for (a, b) in a.trkseg.iter().zip(&b.trkseg) {
|
|
||||||
assert_eq!(a.id, b.id);
|
assert_eq!(a.id, b.id);
|
||||||
assert_eq!(a.len(), b.len());
|
assert_eq!(a.len(), b.len());
|
||||||
for (a, b) in a.chunks().iter().zip(b.chunks()) {
|
for (a, b) in a.chunks().iter().zip(b.chunks()) {
|
||||||
assert!(Rc::ptr_eq(a, b), "the chunks are the ones that were given");
|
assert!(Rc::ptr_eq(a, b), "the chunks are the ones that were given");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn assert_same_file(a: &File, b: &File) {
|
||||||
|
assert_eq!(a.id, b.id);
|
||||||
|
assert_eq!(a.info, b.info);
|
||||||
|
assert_eq!(a.rte.len(), b.rte.len());
|
||||||
|
for (a, b) in a.rte.iter().zip(&b.rte) {
|
||||||
|
assert_eq!((a.id, &a.info), (b.id, &b.info));
|
||||||
|
assert_same_segment(&a.seg, &b.seg);
|
||||||
|
}
|
||||||
|
assert_eq!(a.trk.len(), b.trk.len());
|
||||||
|
for (a, b) in a.trk.iter().zip(&b.trk) {
|
||||||
|
assert_eq!((a.id, &a.info), (b.id, &b.info));
|
||||||
|
assert_eq!(a.trkseg.len(), b.trkseg.len());
|
||||||
|
for (a, b) in a.trkseg.iter().zip(&b.trkseg) {
|
||||||
|
assert_same_segment(a, b);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
assert_eq!(a.wpt.len(), b.wpt.len());
|
assert_eq!(a.wpt.len(), b.wpt.len());
|
||||||
for (a, b) in a.wpt.chunks().iter().zip(b.wpt.chunks()) {
|
for (a, b) in a.wpt.chunks().iter().zip(b.wpt.chunks()) {
|
||||||
@@ -425,7 +475,7 @@ mod tests {
|
|||||||
.unwrap()
|
.unwrap()
|
||||||
.build(file.id, &|_| None, &|_| None)
|
.build(file.id, &|_| None, &|_| None)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert!(built.trk.is_empty() && built.wpt.is_empty());
|
assert!(built.rte.is_empty() && built.trk.is_empty() && built.wpt.is_empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The names of the categories of a trackpoint.
|
/// The names of the categories of a trackpoint.
|
||||||
@@ -611,13 +661,15 @@ mod tests {
|
|||||||
"70733a2f2f6578616d706c652e636f6d2f736f6d656f6e65021868747470733a2f2f6578616d706c652e636f",
|
"70733a2f2f6578616d706c652e636f6d2f736f6d656f6e65021868747470733a2f2f6578616d706c652e636f",
|
||||||
"6d2f66696c65012074657874206f662068747470733a2f2f6578616d706c652e636f6d2f66696c651a687474",
|
"6d2f66696c65012074657874206f662068747470733a2f2f6578616d706c652e636f6d2f66696c651a687474",
|
||||||
"70733a2f2f6578616d706c652e636f6d2f66696c652d32012274657874206f662068747470733a2f2f657861",
|
"70733a2f2f6578616d706c652e636f6d2f66696c652d32012274657874206f662068747470733a2f2f657861",
|
||||||
"6d706c652e636f6d2f66696c652d320180a0abfef96201100000000000000000000000000000000201057472",
|
"6d706c652e636f6d2f66696c652d320180a0abfef9620110000000000000000000000000000000090105726f",
|
||||||
"61636b0103636d740104646573630103737263021968747470733a2f2f6578616d706c652e636f6d2f747261",
|
"75746500000000010648696b696e6701063030666630300000100000000000000000000000000000000a0110",
|
||||||
"636b012174657874206f662068747470733a2f2f6578616d706c652e636f6d2f747261636b1b68747470733a",
|
"000000000000000000000000000000040110000000000000000000000000000000020105747261636b010363",
|
||||||
"2f2f6578616d706c652e636f6d2f747261636b2d32012374657874206f662068747470733a2f2f6578616d70",
|
"6d740104646573630103737263021968747470733a2f2f6578616d706c652e636f6d2f747261636b01217465",
|
||||||
"6c652e636f6d2f747261636b2d3201074379636c696e67010666663030303001000000000000e03f01000000",
|
"7874206f662068747470733a2f2f6578616d706c652e636f6d2f747261636b1b68747470733a2f2f6578616d",
|
||||||
"0000001840021000000000000000000000000000000003011000000000000000000000000000000004100000",
|
"706c652e636f6d2f747261636b2d32012374657874206f662068747470733a2f2f6578616d706c652e636f6d",
|
||||||
"000000000000000000000000000600011000000000000000000000000000000005",
|
"2f747261636b2d3201074379636c696e67010666663030303001000000000000e03f01000000000000184002",
|
||||||
|
"1000000000000000000000000000000003011000000000000000000000000000000004100000000000000000",
|
||||||
|
"000000000000000600011000000000000000000000000000000005",
|
||||||
);
|
);
|
||||||
const TRACKPOINTS_V1: &str = concat!(
|
const TRACKPOINTS_V1: &str = concat!(
|
||||||
"01020667726176656c0761737068616c74010470617468010668696b696e6701046d74623003000000000000",
|
"01020667726176656c0761737068616c74010470617468010668696b696e6701046d74623003000000000000",
|
||||||
|
|||||||
@@ -8,8 +8,8 @@ use serde::{Deserialize, Serialize};
|
|||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
Author, Categories, File, FileInfo, Link, LngLat, TrackInfo, Trackpoint, TrackpointCategories,
|
Author, Categories, File, FileInfo, Link, LngLat, TrackInfo, TrackSegment, Trackpoint,
|
||||||
Waypoint, WaypointId,
|
TrackpointCategories, Waypoint, WaypointId,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize)]
|
#[derive(Serialize, Deserialize)]
|
||||||
@@ -133,10 +133,18 @@ impl From<TrackInfo1> for TrackInfo {
|
|||||||
#[derive(Serialize, Deserialize)]
|
#[derive(Serialize, Deserialize)]
|
||||||
pub struct FileRecord1 {
|
pub struct FileRecord1 {
|
||||||
pub info: FileInfo1,
|
pub info: FileInfo1,
|
||||||
|
pub routes: Vec<RouteRecord1>,
|
||||||
pub tracks: Vec<TrackRecord1>,
|
pub tracks: Vec<TrackRecord1>,
|
||||||
pub waypoints: Vec<Uuid>,
|
pub waypoints: Vec<Uuid>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
pub struct RouteRecord1 {
|
||||||
|
pub id: Uuid,
|
||||||
|
pub info: TrackInfo1,
|
||||||
|
pub segment: SegmentRecord1,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize)]
|
#[derive(Serialize, Deserialize)]
|
||||||
pub struct TrackRecord1 {
|
pub struct TrackRecord1 {
|
||||||
pub id: Uuid,
|
pub id: Uuid,
|
||||||
@@ -150,24 +158,35 @@ pub struct SegmentRecord1 {
|
|||||||
pub chunks: Vec<Uuid>,
|
pub chunks: Vec<Uuid>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl SegmentRecord1 {
|
||||||
|
fn new(segment: &TrackSegment) -> Self {
|
||||||
|
Self {
|
||||||
|
id: segment.id.0,
|
||||||
|
chunks: segment.chunks().iter().map(|chunk| chunk.id.0).collect(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl FileRecord1 {
|
impl FileRecord1 {
|
||||||
pub fn new(file: &File) -> Self {
|
pub fn new(file: &File) -> Self {
|
||||||
Self {
|
Self {
|
||||||
info: (&file.info).into(),
|
info: (&file.info).into(),
|
||||||
|
routes: file
|
||||||
|
.rte
|
||||||
|
.iter()
|
||||||
|
.map(|route| RouteRecord1 {
|
||||||
|
id: route.id.0,
|
||||||
|
info: (&route.info).into(),
|
||||||
|
segment: SegmentRecord1::new(&route.seg),
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
tracks: file
|
tracks: file
|
||||||
.trk
|
.trk
|
||||||
.iter()
|
.iter()
|
||||||
.map(|track| TrackRecord1 {
|
.map(|track| TrackRecord1 {
|
||||||
id: track.id.0,
|
id: track.id.0,
|
||||||
info: (&track.info).into(),
|
info: (&track.info).into(),
|
||||||
segments: track
|
segments: track.trkseg.iter().map(SegmentRecord1::new).collect(),
|
||||||
.trkseg
|
|
||||||
.iter()
|
|
||||||
.map(|segment| SegmentRecord1 {
|
|
||||||
id: segment.id.0,
|
|
||||||
chunks: segment.chunks().iter().map(|chunk| chunk.id.0).collect(),
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
})
|
})
|
||||||
.collect(),
|
.collect(),
|
||||||
waypoints: file.wpt.chunks().iter().map(|chunk| chunk.id.0).collect(),
|
waypoints: file.wpt.chunks().iter().map(|chunk| chunk.id.0).collect(),
|
||||||
|
|||||||
@@ -217,8 +217,7 @@ impl Persister {
|
|||||||
.files
|
.files
|
||||||
.get(id)
|
.get(id)
|
||||||
.is_none_or(|saved| !Rc::ptr_eq(saved, file));
|
.is_none_or(|saved| !Rc::ptr_eq(saved, file));
|
||||||
let segments = file.trk.iter().flat_map(|track| &track.trkseg);
|
for chunk in file.segments().flat_map(|segment| segment.chunks()) {
|
||||||
for chunk in segments.flat_map(|segment| segment.chunks()) {
|
|
||||||
let key = ChunkKey::trackpoints(chunk.id.0);
|
let key = ChunkKey::trackpoints(chunk.id.0);
|
||||||
if chunks.insert(key) && changed && !self.chunks.contains(&key) {
|
if chunks.insert(key) && changed && !self.chunks.contains(&key) {
|
||||||
batch
|
batch
|
||||||
|
|||||||
@@ -7,6 +7,15 @@ edition = "2024"
|
|||||||
[lib]
|
[lib]
|
||||||
name = "gpx_studio_desktop_lib"
|
name = "gpx_studio_desktop_lib"
|
||||||
crate-type = ["staticlib", "cdylib", "rlib"]
|
crate-type = ["staticlib", "cdylib", "rlib"]
|
||||||
|
# the tests are in `tests/app`: on Windows, a test binary of the library or of the app could not
|
||||||
|
# start without the manifest, which `build.rs` only gives to the binaries of `tests`
|
||||||
|
test = false
|
||||||
|
doctest = false
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "gpx-studio-desktop"
|
||||||
|
path = "src/main.rs"
|
||||||
|
test = false
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
tauri = { version = "2", features = ["test"] }
|
tauri = { version = "2", features = ["test"] }
|
||||||
|
|||||||
@@ -1,3 +1,20 @@
|
|||||||
fn main() {
|
fn main() {
|
||||||
|
// On Windows, the dialogs need Common Controls v6, which a binary only gets with a manifest that
|
||||||
|
// asks for it: tauri-build gives one to the app, but not to the test binaries, which would stop
|
||||||
|
// with STATUS_ENTRYPOINT_NOT_FOUND before running any test. This gives them the same manifest
|
||||||
|
// (`-tests` only reaches the binaries of `tests`, hence the tests are there).
|
||||||
|
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows")
|
||||||
|
&& std::env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("msvc")
|
||||||
|
{
|
||||||
|
let manifest = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||||
|
.join("tests")
|
||||||
|
.join("windows-test.manifest");
|
||||||
|
println!("cargo:rerun-if-changed={}", manifest.display());
|
||||||
|
println!("cargo:rustc-link-arg-tests=/MANIFEST:EMBED");
|
||||||
|
println!(
|
||||||
|
"cargo:rustc-link-arg-tests=/MANIFESTINPUT:{}",
|
||||||
|
manifest.display()
|
||||||
|
);
|
||||||
|
}
|
||||||
tauri_build::build()
|
tauri_build::build()
|
||||||
}
|
}
|
||||||
+18
-21
@@ -14,7 +14,6 @@ use tauri::{AppHandle, Runtime, State};
|
|||||||
use tauri_plugin_dialog::{DialogExt, FilePath};
|
use tauri_plugin_dialog::{DialogExt, FilePath};
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use crate::commands::edit;
|
|
||||||
use crate::state::AppState;
|
use crate::state::AppState;
|
||||||
use crate::workspace::{Entry, Unsaved, WorkspaceState, free_path};
|
use crate::workspace::{Entry, Unsaved, WorkspaceState, free_path};
|
||||||
|
|
||||||
@@ -313,7 +312,6 @@ pub struct ExportArguments {
|
|||||||
atemp: bool,
|
atemp: bool,
|
||||||
power: bool,
|
power: bool,
|
||||||
osm: bool,
|
osm: bool,
|
||||||
as_route: bool,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<ExportArguments> for ExportOptions {
|
impl From<ExportArguments> for ExportOptions {
|
||||||
@@ -325,7 +323,6 @@ impl From<ExportArguments> for ExportOptions {
|
|||||||
atemp: arguments.atemp,
|
atemp: arguments.atemp,
|
||||||
power: arguments.power,
|
power: arguments.power,
|
||||||
osm: arguments.osm,
|
osm: arguments.osm,
|
||||||
as_route: arguments.as_route,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -388,28 +385,28 @@ pub fn create_folder(
|
|||||||
state.core(move |core| core.workspace.create_folder(&parent, &name))
|
state.core(move |core| core.workspace.create_folder(&parent, &name))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Renames a file or a folder of the open folder. An open file is renamed like in its info (it is
|
/// Renames a file or a folder of the open folder, on the disk only: an open file keeps its name,
|
||||||
/// selected), which can be undone; the rest is renamed on the disk, and the open files that are in
|
/// and follows. Not undoable.
|
||||||
/// a folder that is renamed follow.
|
|
||||||
#[tauri::command(async)]
|
#[tauri::command(async)]
|
||||||
pub fn rename_path(
|
pub fn rename_path(state: State<AppState>, path: PathBuf, name: String) -> Result<(), String> {
|
||||||
state: State<AppState>,
|
|
||||||
path: PathBuf,
|
|
||||||
name: String,
|
|
||||||
) -> Result<api::Outcome, String> {
|
|
||||||
state.core(move |core| {
|
state.core(move |core| {
|
||||||
if let Some(id) = core.workspace.linked(&path) {
|
|
||||||
let selected = api::select(&mut core.engine, &[id], gpx_engine::SelectMode::Replace);
|
|
||||||
let desc = core
|
|
||||||
.engine
|
|
||||||
.file_structure(&FileId(id))
|
|
||||||
.and_then(|structure| structure.desc.clone())
|
|
||||||
.unwrap_or_default();
|
|
||||||
return Ok(selected.merge(edit::rename_selection(core, name, desc)));
|
|
||||||
}
|
|
||||||
core.workspace.rename_path(&path, &name)?;
|
core.workspace.rename_path(&path, &name)?;
|
||||||
core.commit(None);
|
core.commit(None);
|
||||||
Ok(api::Outcome::failed_none())
|
Ok(())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Renames the file on the disk of an open file, next to where it is (see `Workspace::rename_file`).
|
||||||
|
/// Not undoable, the name of the file in the engine is not changed. Says whether it was renamed:
|
||||||
|
/// not for a file that is not on the disk.
|
||||||
|
#[tauri::command(async)]
|
||||||
|
pub fn rename_file(state: State<AppState>, file_id: Uuid, name: String) -> Result<bool, String> {
|
||||||
|
state.core(move |core| {
|
||||||
|
let renamed = core.workspace.rename_file(file_id, &name)?;
|
||||||
|
if renamed {
|
||||||
|
core.commit(None);
|
||||||
|
}
|
||||||
|
Ok(renamed)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+15
-19
@@ -1,31 +1,17 @@
|
|||||||
//! Editing the metadata, the style, the structure and the waypoints of the files, and the tools:
|
//! Editing the metadata, the style, the structure and the waypoints of the files, and the tools:
|
||||||
//! reversing, cropping, reducing, timestamps, merging, cleaning...
|
//! reversing, cropping, reducing, timestamps, merging, cleaning...
|
||||||
|
|
||||||
use gpx_engine::{CleanType, FileId, MergeType, Selection, SplitType, api};
|
use gpx_engine::{CleanType, MergeType, SplitType, api};
|
||||||
use tauri::State;
|
use tauri::State;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use crate::state::{AppState, Core};
|
use crate::state::AppState;
|
||||||
|
|
||||||
/// Names and describes the selected files or tracks. A file on the disk is renamed with it (and back
|
/// Names and describes the selected files or tracks. The files on the disk keep their name: see
|
||||||
/// when it is undone): its name is one that a file can have, and not the one of another file.
|
/// `disk::rename_file`.
|
||||||
#[tauri::command(async)]
|
#[tauri::command(async)]
|
||||||
pub fn metadata(state: State<AppState>, name: String, desc: String) -> api::Outcome {
|
pub fn metadata(state: State<AppState>, name: String, desc: String) -> api::Outcome {
|
||||||
state.core(move |core| rename_selection(core, name, desc))
|
state.run(move |e| api::metadata(e, &name, &desc))
|
||||||
}
|
|
||||||
|
|
||||||
/// See `metadata`.
|
|
||||||
pub fn rename_selection(core: &mut Core, name: String, desc: String) -> api::Outcome {
|
|
||||||
let mut name = name;
|
|
||||||
if let Selection::File { file_ids } = core.engine.selection() {
|
|
||||||
for FileId(id) in file_ids.clone() {
|
|
||||||
match core.workspace.name_for(id, &name) {
|
|
||||||
Ok(valid) => name = valid,
|
|
||||||
Err(error) => return api::Outcome::failed(error),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
core.edit(move |e| api::metadata(e, &name, &desc))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command(async)]
|
#[tauri::command(async)]
|
||||||
@@ -38,6 +24,16 @@ pub fn style(
|
|||||||
state.run(move |e| api::style(e, color.as_deref(), opacity, width))
|
state.run(move |e| api::style(e, color.as_deref(), opacity, width))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tauri::command(async)]
|
||||||
|
pub fn convert(state: State<AppState>) -> api::Outcome {
|
||||||
|
state.run(api::convert)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command(async)]
|
||||||
|
pub fn new_route(state: State<AppState>) -> api::Outcome {
|
||||||
|
state.run(api::new_route)
|
||||||
|
}
|
||||||
|
|
||||||
#[tauri::command(async)]
|
#[tauri::command(async)]
|
||||||
pub fn new_track(state: State<AppState>) -> api::Outcome {
|
pub fn new_track(state: State<AppState>) -> api::Outcome {
|
||||||
state.run(api::new_track)
|
state.run(api::new_track)
|
||||||
|
|||||||
@@ -16,10 +16,16 @@ pub fn new_file(
|
|||||||
lng: Option<f64>,
|
lng: Option<f64>,
|
||||||
lat: Option<f64>,
|
lat: Option<f64>,
|
||||||
ele: Option<f64>,
|
ele: Option<f64>,
|
||||||
|
route: Option<bool>,
|
||||||
folder: Option<PathBuf>,
|
folder: Option<PathBuf>,
|
||||||
) -> api::Outcome {
|
) -> api::Outcome {
|
||||||
|
let route = route.unwrap_or_default();
|
||||||
// in `folder` if it is given, otherwise like the selected file, otherwise in the open folder
|
// in `folder` if it is given, otherwise like the selected file, otherwise in the open folder
|
||||||
state.core(move |core| core.creating(folder, true, |e| api::new_file(e, &name, lng, lat, ele)))
|
state.core(move |core| {
|
||||||
|
core.creating(folder, true, |e| {
|
||||||
|
api::new_file(e, &name, lng, lat, ele, route)
|
||||||
|
})
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The files are in the body, one after the other, the headers `lengths` and `names` (JSON,
|
/// The files are in the body, one after the other, the headers `lengths` and `names` (JSON,
|
||||||
@@ -109,10 +115,10 @@ pub fn move_elements(
|
|||||||
|
|
||||||
#[tauri::command(async)]
|
#[tauri::command(async)]
|
||||||
pub fn undo(state: State<AppState>) -> api::Outcome {
|
pub fn undo(state: State<AppState>) -> api::Outcome {
|
||||||
state.edit(api::undo)
|
state.run(api::undo)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command(async)]
|
#[tauri::command(async)]
|
||||||
pub fn redo(state: State<AppState>) -> api::Outcome {
|
pub fn redo(state: State<AppState>) -> api::Outcome {
|
||||||
state.edit(api::redo)
|
state.run(api::redo)
|
||||||
}
|
}
|
||||||
@@ -79,7 +79,6 @@ pub fn export_file(
|
|||||||
atemp: bool,
|
atemp: bool,
|
||||||
power: bool,
|
power: bool,
|
||||||
osm: bool,
|
osm: bool,
|
||||||
as_route: bool,
|
|
||||||
) -> Bytes {
|
) -> Bytes {
|
||||||
let options = ExportOptions {
|
let options = ExportOptions {
|
||||||
time,
|
time,
|
||||||
@@ -88,7 +87,6 @@ pub fn export_file(
|
|||||||
atemp,
|
atemp,
|
||||||
power,
|
power,
|
||||||
osm,
|
osm,
|
||||||
as_route,
|
|
||||||
};
|
};
|
||||||
optional(state.read(move |e| api::export_file(e, file_id, options)))
|
optional(state.read(move |e| api::export_file(e, file_id, options)))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,6 +21,16 @@ pub fn arrow_select(state: State<AppState>, down: bool, add: bool) -> api::Outco
|
|||||||
state.run(move |e| api::arrow_select(e, down, add))
|
state.run(move |e| api::arrow_select(e, down, add))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tauri::command(async)]
|
||||||
|
pub fn select_routes(
|
||||||
|
state: State<AppState>,
|
||||||
|
file_id: Uuid,
|
||||||
|
route_ids: Vec<Uuid>,
|
||||||
|
mode: SelectMode,
|
||||||
|
) -> api::Outcome {
|
||||||
|
state.run(move |e| api::select_routes(e, file_id, &route_ids, mode))
|
||||||
|
}
|
||||||
|
|
||||||
#[tauri::command(async)]
|
#[tauri::command(async)]
|
||||||
pub fn select_tracks(
|
pub fn select_tracks(
|
||||||
state: State<AppState>,
|
state: State<AppState>,
|
||||||
|
|||||||
+10
-9
@@ -3,20 +3,20 @@
|
|||||||
|
|
||||||
mod bytes;
|
mod bytes;
|
||||||
mod commands;
|
mod commands;
|
||||||
mod state;
|
pub mod state;
|
||||||
mod store;
|
pub mod store;
|
||||||
mod workspace;
|
pub mod workspace;
|
||||||
|
|
||||||
use commands::*;
|
use commands::*;
|
||||||
use tauri::{Emitter, Manager};
|
use tauri::{Emitter, Manager};
|
||||||
|
|
||||||
/// The engine of the app: each file has its own history, so that undoing only concerns the
|
/// The engine of the app: each file has its own history, so that undoing only concerns the
|
||||||
/// selected files, and opening or closing a file is not something to undo.
|
/// selected files, and opening or closing a file is not something to undo.
|
||||||
pub(crate) type Engine = gpx_engine::Engine<gpx_engine::PerFileHistory>;
|
pub type Engine = gpx_engine::Engine<gpx_engine::PerFileHistory>;
|
||||||
|
|
||||||
/// The GPX files among what the system gave to the app (the arguments of the command line, when a
|
/// The GPX files among what the system gave to the app (the arguments of the command line, when a
|
||||||
/// file is opened with it).
|
/// file is opened with it).
|
||||||
fn gpx_paths(arguments: impl IntoIterator<Item = String>) -> Vec<std::path::PathBuf> {
|
pub fn gpx_paths(arguments: impl IntoIterator<Item = String>) -> Vec<std::path::PathBuf> {
|
||||||
arguments
|
arguments
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(std::path::PathBuf::from)
|
.map(std::path::PathBuf::from)
|
||||||
@@ -108,12 +108,13 @@ fn menu<R: tauri::Runtime>(app: &tauri::AppHandle<R>) -> tauri::Result<tauri::me
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Gives the builder the commands that reach the engine (which it has to be given as `AppState`).
|
/// Gives the builder the commands that reach the engine (which it has to be given as `AppState`).
|
||||||
fn register_commands<R: tauri::Runtime>(builder: tauri::Builder<R>) -> tauri::Builder<R> {
|
pub fn register_commands<R: tauri::Runtime>(builder: tauri::Builder<R>) -> tauri::Builder<R> {
|
||||||
builder.invoke_handler(tauri::generate_handler![
|
builder.invoke_handler(tauri::generate_handler![
|
||||||
// selection
|
// selection
|
||||||
selection::select,
|
selection::select,
|
||||||
selection::select_all,
|
selection::select_all,
|
||||||
selection::arrow_select,
|
selection::arrow_select,
|
||||||
|
selection::select_routes,
|
||||||
selection::select_tracks,
|
selection::select_tracks,
|
||||||
selection::select_segments,
|
selection::select_segments,
|
||||||
selection::select_waypoint_group,
|
selection::select_waypoint_group,
|
||||||
@@ -134,6 +135,8 @@ fn register_commands<R: tauri::Runtime>(builder: tauri::Builder<R>) -> tauri::Bu
|
|||||||
// edits and tools
|
// edits and tools
|
||||||
edit::metadata,
|
edit::metadata,
|
||||||
edit::style,
|
edit::style,
|
||||||
|
edit::convert,
|
||||||
|
edit::new_route,
|
||||||
edit::new_track,
|
edit::new_track,
|
||||||
edit::new_track_segment,
|
edit::new_track_segment,
|
||||||
edit::new_waypoint,
|
edit::new_waypoint,
|
||||||
@@ -223,6 +226,7 @@ fn register_commands<R: tauri::Runtime>(builder: tauri::Builder<R>) -> tauri::Bu
|
|||||||
disk::list_folder,
|
disk::list_folder,
|
||||||
disk::create_folder,
|
disk::create_folder,
|
||||||
disk::rename_path,
|
disk::rename_path,
|
||||||
|
disk::rename_file,
|
||||||
disk::move_paths,
|
disk::move_paths,
|
||||||
disk::delete_paths,
|
disk::delete_paths,
|
||||||
// the system
|
// the system
|
||||||
@@ -230,6 +234,3 @@ fn register_commands<R: tauri::Runtime>(builder: tauri::Builder<R>) -> tauri::Bu
|
|||||||
system::reveal_path,
|
system::reveal_path,
|
||||||
])
|
])
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests;
|
|
||||||
+7
-45
@@ -94,11 +94,8 @@ impl Core {
|
|||||||
self.commit(None);
|
self.commit(None);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Runs `f` on the engine, which can change: what changed is kept, and the files on the disk are
|
/// Runs `f` on the engine, which can change: what changed is kept.
|
||||||
/// renamed like the files of the engine were (an edit of the name, or its undo). Gives what
|
fn editing<T>(&mut self, f: impl FnOnce(&mut Engine) -> T) -> T {
|
||||||
/// could not be renamed.
|
|
||||||
fn editing<T>(&mut self, f: impl FnOnce(&mut Engine) -> T) -> (T, Vec<String>) {
|
|
||||||
let names = self.workspace.names(&self.engine);
|
|
||||||
let preview = self.workspace.preview;
|
let preview = self.workspace.preview;
|
||||||
let preview_before = preview.and_then(|id| signature(&self.engine, id));
|
let preview_before = preview.and_then(|id| signature(&self.engine, id));
|
||||||
let result = f(&mut self.engine);
|
let result = f(&mut self.engine);
|
||||||
@@ -107,32 +104,18 @@ impl Core {
|
|||||||
if let Some(id) = preview.filter(|_| kept) {
|
if let Some(id) = preview.filter(|_| kept) {
|
||||||
self.workspace.keep(&[id]);
|
self.workspace.keep(&[id]);
|
||||||
}
|
}
|
||||||
let (renamed, errors) = self.workspace.follow_names(&mut self.engine, &names);
|
|
||||||
// and it goes when something else is selected
|
// and it goes when something else is selected
|
||||||
let dropped = self.workspace.drop_preview(&mut self.engine);
|
let dropped = self.workspace.drop_preview(&mut self.engine);
|
||||||
if kept || renamed || dropped.is_some() {
|
if kept || dropped.is_some() {
|
||||||
self.commit(dropped.as_ref());
|
self.commit(dropped.as_ref());
|
||||||
} else {
|
} else {
|
||||||
self.persist();
|
self.persist();
|
||||||
}
|
}
|
||||||
(result, errors)
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Like `editing`, for an edit that can rename files: the outcome tells the first thing that
|
/// After files were written (`result`): what changed in the engine is kept and told, with where
|
||||||
/// could not be renamed (a key of the dictionaries of the frontend, which shows it).
|
/// the files are. Says whether they were written.
|
||||||
pub fn edit(&mut self, f: impl FnOnce(&mut Engine) -> api::Outcome) -> api::Outcome {
|
|
||||||
let (outcome, errors) = self.editing(f);
|
|
||||||
match errors.first() {
|
|
||||||
Some(error) if !outcome.has_error() => {
|
|
||||||
outcome.merge(api::Outcome::failed(error.clone()))
|
|
||||||
}
|
|
||||||
_ => outcome,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// After files were written (`result`): what changed in the engine (the files are called like
|
|
||||||
/// the files they were written to) is kept and told, with where the files are. Says whether
|
|
||||||
/// they were written.
|
|
||||||
pub fn wrote(&mut self, result: Result<api::Outcome, String>) -> Result<bool, String> {
|
pub fn wrote(&mut self, result: Result<api::Outcome, String>) -> Result<bool, String> {
|
||||||
self.commit(result.as_ref().ok().filter(|outcome| outcome.changed));
|
self.commit(result.as_ref().ok().filter(|outcome| outcome.changed));
|
||||||
result.map(|_| true)
|
result.map(|_| true)
|
||||||
@@ -297,13 +280,6 @@ impl AppState {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// An engine that keeps its data in a directory of its own, and has nobody to tell.
|
|
||||||
#[cfg(test)]
|
|
||||||
pub fn temporary() -> Self {
|
|
||||||
let directory = std::env::temp_dir().join(format!("gpx-studio-{}", uuid::Uuid::new_v4()));
|
|
||||||
Self::open(directory, Arc::new(|_, _| {})).expect("the storage can be opened")
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Opens files that the system gave to the app, see `Core::open_external`.
|
/// Opens files that the system gave to the app, see `Core::open_external`.
|
||||||
pub fn open_external(&self, paths: Vec<PathBuf>) {
|
pub fn open_external(&self, paths: Vec<PathBuf>) {
|
||||||
self.core(move |core| core.open_external(&paths));
|
self.core(move |core| core.open_external(&paths));
|
||||||
@@ -325,21 +301,7 @@ impl AppState {
|
|||||||
|
|
||||||
/// Runs `f` on the engine, which can change: what changed is kept (see `Core::editing`).
|
/// Runs `f` on the engine, which can change: what changed is kept (see `Core::editing`).
|
||||||
pub fn run<T: Send + 'static>(&self, f: impl FnOnce(&mut Engine) -> T + Send + 'static) -> T {
|
pub fn run<T: Send + 'static>(&self, f: impl FnOnce(&mut Engine) -> T + Send + 'static) -> T {
|
||||||
self.core(move |core| {
|
self.core(move |core| core.editing(f))
|
||||||
let (result, errors) = core.editing(f);
|
|
||||||
for error in errors {
|
|
||||||
eprintln!("{error}");
|
|
||||||
}
|
|
||||||
result
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Like `run`, for an edit that can rename files: the outcome tells what could not be renamed.
|
|
||||||
pub fn edit(
|
|
||||||
&self,
|
|
||||||
f: impl FnOnce(&mut Engine) -> api::Outcome + Send + 'static,
|
|
||||||
) -> api::Outcome {
|
|
||||||
self.core(move |core| core.edit(f))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Reads from the engine.
|
/// Reads from the engine.
|
||||||
|
|||||||
@@ -217,69 +217,3 @@ impl Storage for FileStorage {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use crate::Engine;
|
|
||||||
use gpx_engine::{Action, Command, Load, LoadFiles, Persister};
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
fn directory() -> PathBuf {
|
|
||||||
std::env::temp_dir().join(format!("gpx-studio-store-{}", Uuid::new_v4()))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn engine_with_a_file() -> Engine {
|
|
||||||
let mut engine = Engine::default();
|
|
||||||
let data = std::fs::read("../gpx-rs/data/simple.gpx").unwrap();
|
|
||||||
engine
|
|
||||||
.execute(Action::Edit(Command::LoadFiles(LoadFiles {
|
|
||||||
files: vec![Load {
|
|
||||||
data: &data,
|
|
||||||
name: "simple",
|
|
||||||
}],
|
|
||||||
})))
|
|
||||||
.unwrap();
|
|
||||||
engine
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn keeps_the_files_and_the_settings_between_sessions() {
|
|
||||||
let root = directory();
|
|
||||||
let engine = engine_with_a_file();
|
|
||||||
let order = engine.order().to_vec();
|
|
||||||
|
|
||||||
let storage = FileStorage::open(&root).unwrap();
|
|
||||||
pollster::block_on(Persister::default().save(&storage, engine.snapshot())).unwrap();
|
|
||||||
pollster::block_on(storage.put_setting("units", "\"metric\"")).unwrap();
|
|
||||||
|
|
||||||
// another session
|
|
||||||
let storage = FileStorage::open(&root).unwrap();
|
|
||||||
let restored = pollster::block_on(Persister::default().restore(&storage)).unwrap();
|
|
||||||
let mut other = Engine::default();
|
|
||||||
other.restore(restored);
|
|
||||||
assert_eq!(other.order(), order);
|
|
||||||
assert_eq!(
|
|
||||||
other.file_statistics(&order[0]).unwrap().total_distance,
|
|
||||||
engine.file_statistics(&order[0]).unwrap().total_distance
|
|
||||||
);
|
|
||||||
assert_eq!(storage.settings()["units"], "\"metric\"");
|
|
||||||
fs::remove_dir_all(root).unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn refuses_a_commit_that_is_not_based_on_the_head() {
|
|
||||||
let root = directory();
|
|
||||||
let storage = FileStorage::open(&root).unwrap();
|
|
||||||
let batch = Batch {
|
|
||||||
order: Some(vec![]),
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
assert_eq!(pollster::block_on(storage.commit(&batch)), Ok(Revision(1)));
|
|
||||||
assert_eq!(
|
|
||||||
pollster::block_on(storage.commit(&batch)),
|
|
||||||
Err(CommitError::Stale { head: Revision(1) })
|
|
||||||
);
|
|
||||||
fs::remove_dir_all(root).unwrap();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+27
-895
@@ -148,7 +148,7 @@ pub struct Entry {
|
|||||||
pub is_dir: bool,
|
pub is_dir: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn is_gpx(path: &Path) -> bool {
|
pub fn is_gpx(path: &Path) -> bool {
|
||||||
path.extension()
|
path.extension()
|
||||||
.and_then(|extension| extension.to_str())
|
.and_then(|extension| extension.to_str())
|
||||||
.is_some_and(|extension| extension.eq_ignore_ascii_case("gpx"))
|
.is_some_and(|extension| extension.eq_ignore_ascii_case("gpx"))
|
||||||
@@ -156,7 +156,7 @@ fn is_gpx(path: &Path) -> bool {
|
|||||||
|
|
||||||
/// Compares names the way people read them: the numbers in them by their value ("track 2" before
|
/// Compares names the way people read them: the numbers in them by their value ("track 2" before
|
||||||
/// "track 10"), the rest regardless of case.
|
/// "track 10"), the rest regardless of case.
|
||||||
fn natural_cmp(a: &str, b: &str) -> Ordering {
|
pub fn natural_cmp(a: &str, b: &str) -> Ordering {
|
||||||
let (mut a, mut b) = (a.chars().peekable(), b.chars().peekable());
|
let (mut a, mut b) = (a.chars().peekable(), b.chars().peekable());
|
||||||
loop {
|
loop {
|
||||||
let order = match (a.peek().copied(), b.peek().copied()) {
|
let order = match (a.peek().copied(), b.peek().copied()) {
|
||||||
@@ -695,8 +695,8 @@ impl Workspace {
|
|||||||
|
|
||||||
/// Writes files to the disk, replacing what is there: they are the same as their file from
|
/// Writes files to the disk, replacing what is there: they are the same as their file from
|
||||||
/// then on. A file that is not on the disk goes in its folder, or at its path in `paths`, or in
|
/// then on. A file that is not on the disk goes in its folder, or at its path in `paths`, or in
|
||||||
/// `folder`, under its name (changed if that is the one of something else), which the file then
|
/// `folder`, under its name (changed if that is the one of something else). Stops at the first
|
||||||
/// has (see `write_file`). Stops at the first error, the files that were written stay written.
|
/// error, the files that were written stay written.
|
||||||
pub fn save(
|
pub fn save(
|
||||||
&mut self,
|
&mut self,
|
||||||
engine: &mut Engine,
|
engine: &mut Engine,
|
||||||
@@ -725,8 +725,7 @@ impl Workspace {
|
|||||||
|
|
||||||
/// Writes the new files among `ids` in their folder, under their name. A name that is the one of
|
/// Writes the new files among `ids` in their folder, under their name. A name that is the one of
|
||||||
/// something else is changed (`name (2)`). Files that would be called the same, like the parts
|
/// something else is changed (`name (2)`). Files that would be called the same, like the parts
|
||||||
/// of a split, are numbered from 1 (`name (1)`, `name (2)`). The files are called like the file
|
/// of a split, are numbered from 1 (`name (1)`, `name (2)`). The files keep their name.
|
||||||
/// they are written to.
|
|
||||||
pub fn save_new(&mut self, engine: &mut Engine, ids: &[Uuid]) -> Result<api::Outcome, String> {
|
pub fn save_new(&mut self, engine: &mut Engine, ids: &[Uuid]) -> Result<api::Outcome, String> {
|
||||||
let names: Vec<Option<(Uuid, PathBuf, String)>> = ids
|
let names: Vec<Option<(Uuid, PathBuf, String)>> = ids
|
||||||
.iter()
|
.iter()
|
||||||
@@ -760,30 +759,6 @@ impl Workspace {
|
|||||||
Ok(outcome)
|
Ok(outcome)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The names of the files that are on the disk, and whether they are the files on the disk, to
|
|
||||||
/// tell which ones were renamed by an edit (see `follow_names`).
|
|
||||||
pub fn names(&self, engine: &Engine) -> BTreeMap<Uuid, (String, bool)> {
|
|
||||||
self.links
|
|
||||||
.keys()
|
|
||||||
.filter_map(|id| {
|
|
||||||
let name = engine.file_structure(&FileId(*id))?.name.clone();
|
|
||||||
Some((*id, (name, !self.is_dirty(engine, *id))))
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The name that a file can be given. A file on the disk is called like its file: the name is
|
|
||||||
/// one that a file can have (see `file_name`), and not the one of another file next to it
|
|
||||||
/// (`NAME_TAKEN`). The other files get theirs when they are written.
|
|
||||||
pub fn name_for(&self, id: Uuid, name: &str) -> Result<String, String> {
|
|
||||||
if !self.links.contains_key(&id) {
|
|
||||||
return Ok(name.to_owned());
|
|
||||||
}
|
|
||||||
let name = file_name(name);
|
|
||||||
self.renamed_path(id, &name)?;
|
|
||||||
Ok(name)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Where a file on the disk goes when it is called `name`: next to where it is, with the same
|
/// Where a file on the disk goes when it is called `name`: next to where it is, with the same
|
||||||
/// extension. `None` if it is there already, an error if something else is.
|
/// extension. `None` if it is there already, an error if something else is.
|
||||||
fn renamed_path(&self, id: Uuid, name: &str) -> Result<Option<PathBuf>, String> {
|
fn renamed_path(&self, id: Uuid, name: &str) -> Result<Option<PathBuf>, String> {
|
||||||
@@ -813,49 +788,24 @@ impl Workspace {
|
|||||||
Ok(Some(path))
|
Ok(Some(path))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Renames the files on the disk whose name changed in the engine since it had `before` (see
|
/// Renames the file on the disk of an open file, next to where it is: the name is one that a
|
||||||
/// `names`): an edit of the name, or its undo, renames the file. A file that was the one on the
|
/// file can have (see `file_name`), and not the one of another file (`NAME_TAKEN`). It is not
|
||||||
/// disk is written too, so that it still is: the rename is not something to save. A file with
|
/// an edit, nothing is undone; the file has the same content, so it is as saved as it was.
|
||||||
/// edits is not, its edits are not saved for it. A file that cannot be renamed keeps its place,
|
/// Nothing happens to a file that is not on the disk. Says whether it was renamed.
|
||||||
/// with the reason in the errors. Says whether a file was renamed.
|
pub fn rename_file(&mut self, id: Uuid, name: &str) -> Result<bool, String> {
|
||||||
pub fn follow_names(
|
let Some(path) = self.renamed_path(id, name)? else {
|
||||||
&mut self,
|
return Ok(false);
|
||||||
engine: &mut Engine,
|
|
||||||
before: &BTreeMap<Uuid, (String, bool)>,
|
|
||||||
) -> (bool, Vec<String>) {
|
|
||||||
let mut renamed = false;
|
|
||||||
let mut errors = vec![];
|
|
||||||
for (id, (old, clean)) in before {
|
|
||||||
let Some(structure) = engine.file_structure(&FileId(*id)) else {
|
|
||||||
continue;
|
|
||||||
};
|
};
|
||||||
if structure.name == *old {
|
let link = self.links.get_mut(&id).expect("the file is on the disk");
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let path = match self.renamed_path(*id, &structure.name) {
|
|
||||||
Ok(Some(path)) => path,
|
|
||||||
Ok(None) => continue,
|
|
||||||
Err(error) => {
|
|
||||||
errors.push(error);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let link = self.links.get_mut(id).expect("the file is on the disk");
|
|
||||||
// a file that is gone is written at its new place when it is saved
|
// a file that is gone is written at its new place when it is saved
|
||||||
if !link.missing
|
if !link.missing {
|
||||||
&& let Err(error) = fs::rename(&link.path, &path)
|
fs::rename(&link.path, &path).map_err(|error| {
|
||||||
{
|
|
||||||
eprintln!("{} cannot be renamed: {error}", link.path.display());
|
eprintln!("{} cannot be renamed: {error}", link.path.display());
|
||||||
errors.push(RENAME_FAILED.to_owned());
|
RENAME_FAILED.to_owned()
|
||||||
continue;
|
})?;
|
||||||
}
|
}
|
||||||
link.path = path.clone();
|
link.path = path;
|
||||||
renamed = true;
|
Ok(true)
|
||||||
if *clean && let Err(error) = self.write_file(engine, *id, &path) {
|
|
||||||
errors.push(error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
(renamed, errors)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Writes a file to a path of the user's choice, which is the place of the file from then on.
|
/// Writes a file to a path of the user's choice, which is the place of the file from then on.
|
||||||
@@ -873,30 +823,21 @@ impl Workspace {
|
|||||||
self.write_file(engine, id, path)
|
self.write_file(engine, id, path)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Writes a file to `path`, which it is linked to from then on. It is called like the file it is
|
/// Writes a file to `path`, which it is linked to from then on. Says what changed in the engine
|
||||||
/// written to (a file has a single name), as if it always had been: that is not an edit to
|
/// (nothing: its name is its own, whatever the name of the file it is written to).
|
||||||
/// undo. Says what changed in the engine.
|
|
||||||
fn write_file(
|
fn write_file(
|
||||||
&mut self,
|
&mut self,
|
||||||
engine: &mut Engine,
|
engine: &mut Engine,
|
||||||
id: Uuid,
|
id: Uuid,
|
||||||
path: &Path,
|
path: &Path,
|
||||||
) -> Result<api::Outcome, String> {
|
) -> Result<api::Outcome, String> {
|
||||||
let Some(structure) = engine.file_structure(&FileId(id)) else {
|
let unchanged = api::Outcome::failed_none();
|
||||||
return Ok(api::Outcome::failed_none());
|
|
||||||
};
|
|
||||||
let name = stem(path);
|
|
||||||
let renamed = if structure.name != name {
|
|
||||||
api::rename_file(engine, id, &name)
|
|
||||||
} else {
|
|
||||||
api::Outcome::failed_none()
|
|
||||||
};
|
|
||||||
let Some(bytes) = api::export_file(engine, id, ExportOptions::ALL) else {
|
let Some(bytes) = api::export_file(engine, id, ExportOptions::ALL) else {
|
||||||
return Ok(renamed);
|
return Ok(unchanged);
|
||||||
};
|
};
|
||||||
write_atomically(path, &bytes).map_err(|error| format!("{}: {error}", path.display()))?;
|
write_atomically(path, &bytes).map_err(|error| format!("{}: {error}", path.display()))?;
|
||||||
let Some(signature) = signature(engine, id) else {
|
let Some(signature) = signature(engine, id) else {
|
||||||
return Ok(renamed);
|
return Ok(unchanged);
|
||||||
};
|
};
|
||||||
// the folder, if there is one, may watch what was just written: the hash tells it is known
|
// the folder, if there is one, may watch what was just written: the hash tells it is known
|
||||||
self.links.insert(
|
self.links.insert(
|
||||||
@@ -911,7 +852,7 @@ impl Workspace {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
self.dirs.remove(&id);
|
self.dirs.remove(&id);
|
||||||
Ok(renamed)
|
Ok(unchanged)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The folders and the GPX files that are in a folder of the open folder (or in it), the
|
/// The folders and the GPX files that are in a folder of the open folder (or in it), the
|
||||||
@@ -1026,8 +967,8 @@ impl Workspace {
|
|||||||
Ok(path)
|
Ok(path)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Renames a file or a folder of the tree that is not an open file (which is renamed in the
|
/// Renames a file or a folder of the tree. A file keeps its extension, and an open file keeps its
|
||||||
/// engine, see `follow_names`). A file keeps its extension. Gives the new path.
|
/// name (see `rename_file`). Gives the new path.
|
||||||
pub fn rename_path(&mut self, path: &Path, name: &str) -> Result<PathBuf, String> {
|
pub fn rename_path(&mut self, path: &Path, name: &str) -> Result<PathBuf, String> {
|
||||||
let path = self.tree_item(path)?;
|
let path = self.tree_item(path)?;
|
||||||
let name = file_name(name);
|
let name = file_name(name);
|
||||||
@@ -1099,812 +1040,3 @@ impl Workspace {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use gpx_engine::SelectMode;
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
fn gpx(name: &str) -> String {
|
|
||||||
format!(
|
|
||||||
r#"<?xml version="1.0"?><gpx version="1.1" creator="test" xmlns="http://www.topografix.com/GPX/1/1"><metadata><name>{name}</name></metadata><trk><name>{name}</name><trkseg><trkpt lat="50.0" lon="4.0"><ele>10</ele></trkpt><trkpt lat="50.1" lon="4.1"><ele>20</ele></trkpt></trkseg></trk></gpx>"#
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The GPX files of a folder and of the folders in it.
|
|
||||||
pub(super) fn gpx_files(folder: &Path) -> Vec<PathBuf> {
|
|
||||||
let mut found = vec![];
|
|
||||||
for entry in fs::read_dir(folder).unwrap().flatten() {
|
|
||||||
let path = entry.path();
|
|
||||||
if path.is_dir() {
|
|
||||||
found.extend(gpx_files(&path));
|
|
||||||
} else if is_gpx(&path) {
|
|
||||||
found.push(path);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
found.sort();
|
|
||||||
found
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Fixture {
|
|
||||||
folder: PathBuf,
|
|
||||||
engine: Engine,
|
|
||||||
workspace: Workspace,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Fixture {
|
|
||||||
fn new() -> Self {
|
|
||||||
let folder =
|
|
||||||
canonical(&std::env::temp_dir()).join(format!("gpx-ws-{}", Uuid::new_v4()));
|
|
||||||
fs::create_dir_all(&folder).unwrap();
|
|
||||||
Self {
|
|
||||||
folder,
|
|
||||||
engine: Engine::default(),
|
|
||||||
workspace: Workspace::default(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn write(&self, name: &str, title: &str) -> PathBuf {
|
|
||||||
let path = self.folder.join(name);
|
|
||||||
fs::write(&path, gpx(title)).unwrap();
|
|
||||||
path
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Opens the folder, and all the files that are in it.
|
|
||||||
fn open_folder(&mut self) {
|
|
||||||
let folder = self.folder.clone();
|
|
||||||
self.workspace.open_folder(&mut self.engine, &folder, false);
|
|
||||||
let files = gpx_files(&folder);
|
|
||||||
self.workspace.open_files(&mut self.engine, &files, false);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn reconcile(&mut self, changed: Option<&[PathBuf]>) -> Option<api::Outcome> {
|
|
||||||
self.workspace.reconcile(&mut self.engine, changed)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn save(&mut self, ids: &[Uuid]) {
|
|
||||||
self.workspace
|
|
||||||
.save(&mut self.engine, ids, &BTreeMap::new(), None)
|
|
||||||
.unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
fn ids(&self) -> Vec<Uuid> {
|
|
||||||
self.engine.order().iter().map(|id| id.0).collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn id_named(&self, name: &str) -> Uuid {
|
|
||||||
self.ids()
|
|
||||||
.into_iter()
|
|
||||||
.find(|id| self.name(*id) == name)
|
|
||||||
.unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn name(&self, id: Uuid) -> String {
|
|
||||||
self.engine
|
|
||||||
.file_structure(&FileId(id))
|
|
||||||
.unwrap()
|
|
||||||
.name
|
|
||||||
.clone()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What the file holds: the name of its track (its own name is the one of the file).
|
|
||||||
fn content(&self, id: Uuid) -> String {
|
|
||||||
self.engine.file_structure(&FileId(id)).unwrap().tracks[0]
|
|
||||||
.name
|
|
||||||
.clone()
|
|
||||||
.unwrap_or_default()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn rename(&mut self, id: Uuid, name: &str) {
|
|
||||||
api::select(&mut self.engine, &[id], SelectMode::Replace);
|
|
||||||
assert!(!api::metadata(&mut self.engine, name, "").has_error());
|
|
||||||
}
|
|
||||||
|
|
||||||
fn status(&self, id: Uuid) -> FileStatus {
|
|
||||||
self.workspace
|
|
||||||
.state(&self.engine)
|
|
||||||
.files
|
|
||||||
.remove(&id.to_string())
|
|
||||||
.unwrap()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Drop for Fixture {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
let _ = fs::remove_dir_all(&self.folder);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn an_opened_file_is_clean_until_it_is_edited_and_clean_again_once_saved() {
|
|
||||||
let mut fx = Fixture::new();
|
|
||||||
let path = fx.write("a.gpx", "a");
|
|
||||||
fx.workspace
|
|
||||||
.open_files(&mut fx.engine, std::slice::from_ref(&path), true);
|
|
||||||
let id = fx.ids()[0];
|
|
||||||
assert!(!fx.workspace.is_dirty(&fx.engine, id));
|
|
||||||
assert_eq!(fx.status(id).path.as_deref(), path.to_str());
|
|
||||||
|
|
||||||
fx.rename(id, "renamed");
|
|
||||||
assert!(fx.workspace.is_dirty(&fx.engine, id));
|
|
||||||
// nothing is written before it is saved
|
|
||||||
assert!(fs::read_to_string(&path).unwrap().contains(">a<"));
|
|
||||||
|
|
||||||
fx.save(&[id]);
|
|
||||||
assert!(!fx.workspace.is_dirty(&fx.engine, id));
|
|
||||||
assert!(fs::read_to_string(&path).unwrap().contains(">renamed<"));
|
|
||||||
|
|
||||||
// going back before the save is an edit again
|
|
||||||
api::select(&mut fx.engine, &[id], SelectMode::Replace);
|
|
||||||
api::undo(&mut fx.engine);
|
|
||||||
assert!(fx.workspace.is_dirty(&fx.engine, id));
|
|
||||||
api::redo(&mut fx.engine);
|
|
||||||
assert!(!fx.workspace.is_dirty(&fx.engine, id));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_file_that_is_not_on_the_disk_is_unsaved_until_it_is_given_a_place() {
|
|
||||||
let mut fx = Fixture::new();
|
|
||||||
api::new_file(&mut fx.engine, "fresh", None, None, None);
|
|
||||||
let id = fx.ids()[0];
|
|
||||||
assert!(fx.workspace.is_dirty(&fx.engine, id));
|
|
||||||
assert_eq!(
|
|
||||||
fx.workspace.unlinked(&fx.engine, &[id]),
|
|
||||||
[(id, "fresh".to_string())]
|
|
||||||
);
|
|
||||||
// nowhere to put it without being told
|
|
||||||
fx.save(&[id]);
|
|
||||||
assert!(fx.workspace.is_dirty(&fx.engine, id));
|
|
||||||
|
|
||||||
let path = fx.folder.join("fresh.gpx");
|
|
||||||
let paths = BTreeMap::from([(id, path.clone())]);
|
|
||||||
fx.workspace
|
|
||||||
.save(&mut fx.engine, &[id], &paths, None)
|
|
||||||
.unwrap();
|
|
||||||
assert!(path.exists());
|
|
||||||
assert!(!fx.workspace.is_dirty(&fx.engine, id));
|
|
||||||
assert!(fx.workspace.unlinked(&fx.engine, &[id]).is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn several_files_without_a_place_go_in_a_folder_with_names_that_are_free() {
|
|
||||||
let mut fx = Fixture::new();
|
|
||||||
fx.write("fresh.gpx", "already there");
|
|
||||||
api::new_file(&mut fx.engine, "fresh", None, None, None);
|
|
||||||
api::new_file(&mut fx.engine, "a/b: c", None, None, None);
|
|
||||||
api::new_file(&mut fx.engine, "fresh", None, None, None);
|
|
||||||
let ids = fx.ids();
|
|
||||||
let folder = fx.folder.clone();
|
|
||||||
fx.workspace
|
|
||||||
.save(&mut fx.engine, &ids, &BTreeMap::new(), Some(&folder))
|
|
||||||
.unwrap();
|
|
||||||
for name in ["fresh (2).gpx", "fresh (3).gpx", "a_b_ c.gpx"] {
|
|
||||||
assert!(fx.folder.join(name).exists(), "{name}");
|
|
||||||
}
|
|
||||||
assert!(ids.iter().all(|id| !fx.workspace.is_dirty(&fx.engine, *id)));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn what_this_app_writes_is_not_a_change_of_the_disk() {
|
|
||||||
let mut fx = Fixture::new();
|
|
||||||
let path = fx.write("a.gpx", "a");
|
|
||||||
fx.open_folder();
|
|
||||||
let id = fx.ids()[0];
|
|
||||||
api::select(&mut fx.engine, &[id], SelectMode::Replace);
|
|
||||||
assert!(!api::style(&mut fx.engine, Some("#ff0000"), None, None).has_error());
|
|
||||||
fx.save(&[id]);
|
|
||||||
assert!(fx.reconcile(Some(&[path])).is_none());
|
|
||||||
assert!(!fx.status(id).replaced && !fx.status(id).dirty);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_folders_of_the_files_outside_the_open_folder_are_watched_too() {
|
|
||||||
let mut fx = Fixture::new();
|
|
||||||
let inside = fx.write("in.gpx", "in");
|
|
||||||
let elsewhere = canonical(&std::env::temp_dir()).join(format!("gpx-ws-{}", Uuid::new_v4()));
|
|
||||||
fs::create_dir_all(&elsewhere).unwrap();
|
|
||||||
let (one, two) = (elsewhere.join("one.gpx"), elsewhere.join("two.gpx"));
|
|
||||||
fs::write(&one, gpx("one")).unwrap();
|
|
||||||
fs::write(&two, gpx("two")).unwrap();
|
|
||||||
let folder = fx.folder.clone();
|
|
||||||
|
|
||||||
// no folder: only the folder of the files
|
|
||||||
fx.workspace.open_files(&mut fx.engine, &[one, two], false);
|
|
||||||
assert_eq!(fx.workspace.watched(), [(elsewhere.clone(), false)]);
|
|
||||||
|
|
||||||
// the open folder as a whole, and the file in it needs nothing more
|
|
||||||
fx.workspace.open_folder(&mut fx.engine, &folder, false);
|
|
||||||
fx.workspace.open_files(&mut fx.engine, &[inside], false);
|
|
||||||
assert_eq!(
|
|
||||||
fx.workspace.watched(),
|
|
||||||
[(folder, true), (elsewhere.clone(), false)]
|
|
||||||
);
|
|
||||||
|
|
||||||
// closing the files stops it
|
|
||||||
let ids = fx.ids();
|
|
||||||
fx.workspace.close_files(&mut fx.engine, &ids, true);
|
|
||||||
assert_eq!(fx.workspace.watched(), [(fx.folder.clone(), true)]);
|
|
||||||
fs::remove_dir_all(elsewhere).unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn opening_a_folder_does_not_open_its_files() {
|
|
||||||
let mut fx = Fixture::new();
|
|
||||||
fx.write("a.gpx", "a");
|
|
||||||
let folder = fx.folder.clone();
|
|
||||||
let outcome = fx.workspace.open_folder(&mut fx.engine, &folder, false);
|
|
||||||
assert!(!outcome.changed);
|
|
||||||
assert!(fx.ids().is_empty());
|
|
||||||
assert_eq!(fx.workspace.folder.as_deref(), Some(folder.as_path()));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn folders_are_made_renamed_and_moved_and_the_open_files_follow() {
|
|
||||||
let mut fx = Fixture::new();
|
|
||||||
let a = fx.write("a.gpx", "a");
|
|
||||||
fx.open_folder();
|
|
||||||
let id = fx.ids()[0];
|
|
||||||
let root = fx.folder.clone();
|
|
||||||
let path_of = |fx: &Fixture| PathBuf::from(fx.status(id).path.unwrap());
|
|
||||||
|
|
||||||
let first = fx.workspace.create_folder(&root, "New folder").unwrap();
|
|
||||||
let second = fx.workspace.create_folder(&root, "New folder").unwrap();
|
|
||||||
assert_eq!(first, root.join("New folder"));
|
|
||||||
assert_eq!(second, root.join("New folder 2"));
|
|
||||||
|
|
||||||
fx.workspace.move_paths(&[a], &first).unwrap();
|
|
||||||
assert_eq!(path_of(&fx), first.join("a.gpx"));
|
|
||||||
assert!(first.join("a.gpx").exists() && !fx.status(id).dirty);
|
|
||||||
|
|
||||||
let trips = fx.workspace.rename_path(&first, "Trips").unwrap();
|
|
||||||
assert_eq!(path_of(&fx), root.join("Trips/a.gpx"));
|
|
||||||
// a folder does not go into itself, nor onto something else
|
|
||||||
assert!(
|
|
||||||
fx.workspace
|
|
||||||
.move_paths(std::slice::from_ref(&trips), &trips)
|
|
||||||
.is_err()
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
fx.workspace.rename_path(&trips, "New folder 2"),
|
|
||||||
Err(NAME_TAKEN.to_owned())
|
|
||||||
);
|
|
||||||
fx.workspace.move_paths(&[trips], &second).unwrap();
|
|
||||||
assert_eq!(path_of(&fx), second.join("Trips/a.gpx"));
|
|
||||||
|
|
||||||
// a file keeps its extension
|
|
||||||
let closed = fx.write("c.gpx", "c");
|
|
||||||
assert_eq!(
|
|
||||||
fx.workspace.rename_path(&closed, "d").unwrap(),
|
|
||||||
root.join("d.gpx")
|
|
||||||
);
|
|
||||||
// the open folder and what is not in it are left alone
|
|
||||||
assert!(fx.workspace.rename_path(&root, "x").is_err());
|
|
||||||
let elsewhere = canonical(&std::env::temp_dir());
|
|
||||||
assert!(fx.workspace.rename_path(&elsewhere, "x").is_err());
|
|
||||||
assert!(fx.workspace.create_folder(&elsewhere, "x").is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn deleted_files_are_closed_unless_they_have_edits() {
|
|
||||||
let mut fx = Fixture::new();
|
|
||||||
let a = fx.write("a.gpx", "a");
|
|
||||||
let b = fx.write("b.gpx", "b");
|
|
||||||
fx.open_folder();
|
|
||||||
let (id_a, id_b) = (fx.id_named("a"), fx.id_named("b"));
|
|
||||||
api::select(&mut fx.engine, &[id_b], SelectMode::Replace);
|
|
||||||
assert!(!api::style(&mut fx.engine, Some("#ff0000"), None, None).has_error());
|
|
||||||
|
|
||||||
let outcome = fx
|
|
||||||
.workspace
|
|
||||||
.delete_paths(&mut fx.engine, &[a.clone(), b.clone()], |paths| {
|
|
||||||
paths.iter().for_each(|path| fs::remove_file(path).unwrap());
|
|
||||||
Ok(())
|
|
||||||
})
|
|
||||||
.unwrap();
|
|
||||||
assert!(outcome.changed);
|
|
||||||
assert_eq!(fx.ids(), [id_b]);
|
|
||||||
assert!(!fx.ids().contains(&id_a));
|
|
||||||
let status = fx.status(id_b);
|
|
||||||
assert!(status.dirty && status.missing);
|
|
||||||
assert!(!a.exists() && !b.exists());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_tree_of_the_folder_shows_folders_first_and_only_gpx_files() {
|
|
||||||
let mut fx = Fixture::new();
|
|
||||||
fx.write("b.gpx", "b");
|
|
||||||
fx.write("A.GPX", "a");
|
|
||||||
fx.write("b 10.gpx", "b 10");
|
|
||||||
fx.write("b 2.gpx", "b 2");
|
|
||||||
fx.write("notes.txt", "not a track");
|
|
||||||
fx.write(".hidden.gpx", "hidden");
|
|
||||||
fs::create_dir(fx.folder.join("zoo")).unwrap();
|
|
||||||
fs::create_dir(fx.folder.join("Alps")).unwrap();
|
|
||||||
fs::create_dir(fx.folder.join(".git")).unwrap();
|
|
||||||
fx.write("zoo/c.gpx", "c");
|
|
||||||
let folder = fx.folder.clone();
|
|
||||||
fx.workspace.open_folder(&mut fx.engine, &folder, false);
|
|
||||||
|
|
||||||
let names = |entries: Vec<Entry>| -> Vec<(String, bool)> {
|
|
||||||
entries.into_iter().map(|e| (e.name, e.is_dir)).collect()
|
|
||||||
};
|
|
||||||
assert_eq!(
|
|
||||||
names(fx.workspace.list_folder(&folder).unwrap()),
|
|
||||||
[
|
|
||||||
("Alps".to_string(), true),
|
|
||||||
("zoo".to_string(), true),
|
|
||||||
("A.GPX".to_string(), false),
|
|
||||||
("b.gpx".to_string(), false),
|
|
||||||
("b 2.gpx".to_string(), false),
|
|
||||||
("b 10.gpx".to_string(), false),
|
|
||||||
]
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
names(fx.workspace.list_folder(&folder.join("zoo")).unwrap()),
|
|
||||||
[("c.gpx".to_string(), false)]
|
|
||||||
);
|
|
||||||
// only what is in the open folder can be listed
|
|
||||||
let elsewhere = canonical(&std::env::temp_dir());
|
|
||||||
assert!(fx.workspace.list_folder(&elsewhere).is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn names_are_sorted_by_the_numbers_they_hold() {
|
|
||||||
let mut names = vec![
|
|
||||||
"track 10",
|
|
||||||
"track 2",
|
|
||||||
"Track 1",
|
|
||||||
"track",
|
|
||||||
"track 02b",
|
|
||||||
"track 2a",
|
|
||||||
"b",
|
|
||||||
"A",
|
|
||||||
];
|
|
||||||
names.sort_by(|a, b| natural_cmp(a, b).then_with(|| a.cmp(b)));
|
|
||||||
assert_eq!(
|
|
||||||
names,
|
|
||||||
[
|
|
||||||
"A",
|
|
||||||
"b",
|
|
||||||
"track",
|
|
||||||
"Track 1",
|
|
||||||
"track 2",
|
|
||||||
"track 2a",
|
|
||||||
"track 02b",
|
|
||||||
"track 10",
|
|
||||||
]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_file_without_edits_is_read_again_when_the_disk_changes() {
|
|
||||||
let mut fx = Fixture::new();
|
|
||||||
let a = fx.write("a.gpx", "a");
|
|
||||||
fx.open_folder();
|
|
||||||
let id = fx.ids()[0];
|
|
||||||
|
|
||||||
fx.write("a.gpx", "theirs");
|
|
||||||
let outcome = fx.reconcile(Some(std::slice::from_ref(&a))).unwrap();
|
|
||||||
assert!(outcome.changed);
|
|
||||||
// the same file, now the one on the disk
|
|
||||||
assert_eq!(fx.ids(), [id]);
|
|
||||||
assert_eq!(fx.content(id), "theirs");
|
|
||||||
let status = fx.status(id);
|
|
||||||
assert!(!status.dirty && !status.replaced);
|
|
||||||
// looking again changes nothing
|
|
||||||
assert!(fx.reconcile(Some(std::slice::from_ref(&a))).is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_file_with_edits_is_flagged_when_the_disk_changes_and_not_read_again() {
|
|
||||||
let mut fx = Fixture::new();
|
|
||||||
let a = fx.write("a.gpx", "a");
|
|
||||||
fx.open_folder();
|
|
||||||
let id = fx.ids()[0];
|
|
||||||
fx.rename(id, "mine");
|
|
||||||
|
|
||||||
fx.write("a.gpx", "theirs");
|
|
||||||
let outcome = fx.reconcile(Some(std::slice::from_ref(&a))).unwrap();
|
|
||||||
assert!(!outcome.changed);
|
|
||||||
assert_eq!(fx.name(id), "mine");
|
|
||||||
let status = fx.status(id);
|
|
||||||
assert!(status.dirty && status.replaced && !status.missing);
|
|
||||||
// looking again changes nothing
|
|
||||||
assert!(fx.reconcile(Some(std::slice::from_ref(&a))).is_none());
|
|
||||||
|
|
||||||
// the disk goes back to what was read: only the edits are left
|
|
||||||
fx.write("a.gpx", "a");
|
|
||||||
assert!(fx.reconcile(Some(std::slice::from_ref(&a))).is_some());
|
|
||||||
let status = fx.status(id);
|
|
||||||
assert!(status.dirty && !status.replaced);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_user_can_take_the_disk_instead_of_the_edits() {
|
|
||||||
let mut fx = Fixture::new();
|
|
||||||
fx.write("a.gpx", "a");
|
|
||||||
fx.open_folder();
|
|
||||||
let id = fx.ids()[0];
|
|
||||||
fx.rename(id, "mine");
|
|
||||||
fx.write("a.gpx", "theirs");
|
|
||||||
fx.reconcile(None);
|
|
||||||
assert!(fx.status(id).replaced);
|
|
||||||
|
|
||||||
fx.workspace.reload(&mut fx.engine, &[id]).unwrap();
|
|
||||||
assert_eq!(fx.content(id), "theirs");
|
|
||||||
let status = fx.status(id);
|
|
||||||
assert!(!status.dirty && !status.replaced);
|
|
||||||
// and it is one undo step
|
|
||||||
api::select(&mut fx.engine, &[id], SelectMode::Replace);
|
|
||||||
api::undo(&mut fx.engine);
|
|
||||||
assert_eq!(fx.content(id), "mine");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn saving_overwrites_what_replaced_the_file() {
|
|
||||||
let mut fx = Fixture::new();
|
|
||||||
let a = fx.write("a.gpx", "a");
|
|
||||||
fx.open_folder();
|
|
||||||
let id = fx.ids()[0];
|
|
||||||
fx.rename(id, "mine");
|
|
||||||
fx.write("a.gpx", "theirs");
|
|
||||||
fx.reconcile(None);
|
|
||||||
assert!(fx.status(id).replaced);
|
|
||||||
|
|
||||||
fx.save(&[id]);
|
|
||||||
assert!(fs::read_to_string(a).unwrap().contains(">mine<"));
|
|
||||||
assert!(!fx.status(id).replaced && !fx.status(id).dirty);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_file_that_is_gone_from_the_disk_stays_open_and_dirty_until_it_is_saved_again() {
|
|
||||||
let mut fx = Fixture::new();
|
|
||||||
let a = fx.write("a.gpx", "a");
|
|
||||||
fx.open_folder();
|
|
||||||
let id = fx.ids()[0];
|
|
||||||
|
|
||||||
fs::remove_file(&a).unwrap();
|
|
||||||
assert!(fx.reconcile(Some(std::slice::from_ref(&a))).is_some());
|
|
||||||
assert_eq!(fx.ids(), [id]);
|
|
||||||
let status = fx.status(id);
|
|
||||||
assert!(status.dirty && status.missing && status.path.is_some());
|
|
||||||
|
|
||||||
// saving puts it back
|
|
||||||
fx.save(&[id]);
|
|
||||||
assert!(a.exists());
|
|
||||||
let status = fx.status(id);
|
|
||||||
assert!(!status.dirty && !status.missing);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_file_that_comes_back_different_is_read_again() {
|
|
||||||
let mut fx = Fixture::new();
|
|
||||||
let a = fx.write("a.gpx", "a");
|
|
||||||
fx.open_folder();
|
|
||||||
let id = fx.ids()[0];
|
|
||||||
fs::remove_file(&a).unwrap();
|
|
||||||
fx.reconcile(None);
|
|
||||||
assert!(fx.status(id).missing);
|
|
||||||
|
|
||||||
fx.write("a.gpx", "back");
|
|
||||||
fx.reconcile(None);
|
|
||||||
assert_eq!(fx.content(id), "back");
|
|
||||||
let status = fx.status(id);
|
|
||||||
assert!(!status.dirty && !status.missing);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn what_changed_while_the_app_was_closed_is_found_when_it_starts() {
|
|
||||||
let mut fx = Fixture::new();
|
|
||||||
let a = fx.write("a.gpx", "a");
|
|
||||||
fx.open_folder();
|
|
||||||
let id = fx.ids()[0];
|
|
||||||
fx.write("a.gpx", "changed");
|
|
||||||
assert!(fx.reconcile(None).is_some());
|
|
||||||
assert_eq!(fx.content(id), "changed");
|
|
||||||
fs::remove_file(a).unwrap();
|
|
||||||
assert!(fx.reconcile(None).is_some());
|
|
||||||
assert!(fx.status(id).missing);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn new_files_made_from_a_file_of_the_folder_are_saved_next_to_it() {
|
|
||||||
let mut fx = Fixture::new();
|
|
||||||
fs::create_dir(fx.folder.join("sub")).unwrap();
|
|
||||||
fx.write("sub/b.gpx", "b");
|
|
||||||
fx.write("a.gpx", "a");
|
|
||||||
fx.open_folder();
|
|
||||||
let b = fx.id_named("b");
|
|
||||||
let sub = fx.folder.join("sub");
|
|
||||||
assert_eq!(fx.workspace.source_dir(&[b]), Some(canonical(&sub)));
|
|
||||||
|
|
||||||
let before = fx.ids();
|
|
||||||
api::select(&mut fx.engine, &[b], SelectMode::Replace);
|
|
||||||
let outcome = api::duplicate(&mut fx.engine);
|
|
||||||
let copy = fx
|
|
||||||
.ids()
|
|
||||||
.into_iter()
|
|
||||||
.find(|id| !before.contains(id))
|
|
||||||
.unwrap();
|
|
||||||
fx.workspace.inherit(outcome.added(), &canonical(&sub));
|
|
||||||
assert_eq!(fx.status(copy).folder.as_deref(), canonical(&sub).to_str());
|
|
||||||
assert!(fx.status(copy).path.is_none() && fx.status(copy).dirty);
|
|
||||||
// nobody needs to be asked where it goes
|
|
||||||
assert!(fx.workspace.unlinked(&fx.engine, &[copy]).is_empty());
|
|
||||||
|
|
||||||
fx.save(&[copy]);
|
|
||||||
assert!(sub.join("b (2).gpx").exists());
|
|
||||||
let status = fx.status(copy);
|
|
||||||
assert!(!status.dirty && status.folder.is_none());
|
|
||||||
assert_eq!(
|
|
||||||
status.path.as_deref(),
|
|
||||||
canonical(&sub.join("b (2).gpx")).to_str()
|
|
||||||
);
|
|
||||||
// the copy of the copy is next to it as well
|
|
||||||
assert_eq!(fx.workspace.source_dir(&[copy]), Some(canonical(&sub)));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_file_outside_the_open_folder_hands_nothing_down() {
|
|
||||||
let mut fx = Fixture::new();
|
|
||||||
let elsewhere = canonical(&std::env::temp_dir()).join(format!("gpx-ws-{}", Uuid::new_v4()));
|
|
||||||
fs::create_dir_all(&elsewhere).unwrap();
|
|
||||||
let outside = elsewhere.join("o.gpx");
|
|
||||||
fs::write(&outside, gpx("o")).unwrap();
|
|
||||||
let folder = fx.folder.clone();
|
|
||||||
fx.workspace.open_folder(&mut fx.engine, &folder, false);
|
|
||||||
fx.workspace
|
|
||||||
.open_files(&mut fx.engine, std::slice::from_ref(&outside), true);
|
|
||||||
let id = fx.ids()[0];
|
|
||||||
assert_eq!(fx.workspace.source_dir(&[id]), None);
|
|
||||||
// a new file with no source is not linked to a folder by `source_dir`: the caller falls back
|
|
||||||
fs::remove_dir_all(elsewhere).unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn closing_files_asks_what_to_do_with_the_unsaved_ones() {
|
|
||||||
let mut fx = Fixture::new();
|
|
||||||
fx.write("a.gpx", "a");
|
|
||||||
fx.write("b.gpx", "b");
|
|
||||||
fx.open_folder();
|
|
||||||
let (a, b) = (fx.id_named("a"), fx.id_named("b"));
|
|
||||||
fx.rename(a, "edited");
|
|
||||||
assert_eq!(fx.workspace.unsaved(&fx.engine, &[a, b]), [a]);
|
|
||||||
|
|
||||||
// without a choice what has edits stays
|
|
||||||
let outcome = fx.workspace.close_files(&mut fx.engine, &[a, b], false);
|
|
||||||
assert!(outcome.changed);
|
|
||||||
assert_eq!(fx.ids(), [a]);
|
|
||||||
|
|
||||||
// saved first
|
|
||||||
fx.save(&[a]);
|
|
||||||
fx.workspace.close_files(&mut fx.engine, &[a], false);
|
|
||||||
assert!(fx.ids().is_empty());
|
|
||||||
assert!(
|
|
||||||
fs::read_to_string(fx.folder.join("a.gpx"))
|
|
||||||
.unwrap()
|
|
||||||
.contains("edited")
|
|
||||||
);
|
|
||||||
assert!(fx.workspace.links.is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn closing_files_can_discard_their_edits() {
|
|
||||||
let mut fx = Fixture::new();
|
|
||||||
fx.write("a.gpx", "a");
|
|
||||||
fx.open_folder();
|
|
||||||
let a = fx.ids()[0];
|
|
||||||
fx.rename(a, "edited");
|
|
||||||
api::new_file(&mut fx.engine, "fresh", None, None, None);
|
|
||||||
let fresh = fx.id_named("fresh");
|
|
||||||
fx.workspace.close_files(&mut fx.engine, &[a, fresh], true);
|
|
||||||
assert!(fx.ids().is_empty());
|
|
||||||
assert!(
|
|
||||||
fs::read_to_string(fx.folder.join("a.gpx"))
|
|
||||||
.unwrap()
|
|
||||||
.contains(">a<")
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn closing_the_folder_closes_every_file() {
|
|
||||||
let mut fx = Fixture::new();
|
|
||||||
fx.write("a.gpx", "a");
|
|
||||||
fx.open_folder();
|
|
||||||
api::new_file(&mut fx.engine, "fresh", None, None, None);
|
|
||||||
assert_eq!(fx.ids().len(), 2);
|
|
||||||
|
|
||||||
// the new file has nowhere to go: it has to be discarded
|
|
||||||
let outcome = fx.workspace.close_folder(&mut fx.engine, false);
|
|
||||||
assert!(outcome.changed);
|
|
||||||
assert_eq!(fx.ids().len(), 1);
|
|
||||||
assert!(fx.workspace.folder.is_none());
|
|
||||||
|
|
||||||
let outcome = fx.workspace.close_folder(&mut fx.engine, true);
|
|
||||||
assert!(outcome.changed);
|
|
||||||
assert!(fx.ids().is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn opening_another_folder_closes_the_first_with_all_its_files() {
|
|
||||||
let mut fx = Fixture::new();
|
|
||||||
fx.write("a.gpx", "a");
|
|
||||||
fx.open_folder();
|
|
||||||
let a = fx.ids()[0];
|
|
||||||
fx.rename(a, "edited");
|
|
||||||
let other = canonical(&std::env::temp_dir()).join(format!("gpx-ws-{}", Uuid::new_v4()));
|
|
||||||
fs::create_dir_all(&other).unwrap();
|
|
||||||
|
|
||||||
// the edits stay, nothing is lost without a choice
|
|
||||||
fx.workspace.open_folder(&mut fx.engine, &other, false);
|
|
||||||
assert_eq!(fx.ids(), [a]);
|
|
||||||
assert_eq!(fx.workspace.folder.as_deref(), Some(other.as_path()));
|
|
||||||
|
|
||||||
let first = fx.folder.clone();
|
|
||||||
fx.workspace.open_folder(&mut fx.engine, &first, true);
|
|
||||||
assert!(fx.ids().is_empty());
|
|
||||||
assert!(
|
|
||||||
fs::read_to_string(fx.folder.join("a.gpx"))
|
|
||||||
.unwrap()
|
|
||||||
.contains(">a<")
|
|
||||||
);
|
|
||||||
fs::remove_dir_all(other).unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn opening_the_same_folder_again_changes_nothing() {
|
|
||||||
let mut fx = Fixture::new();
|
|
||||||
fx.write("a.gpx", "a");
|
|
||||||
fx.open_folder();
|
|
||||||
let folder = fx.folder.clone();
|
|
||||||
let outcome = fx.workspace.open_folder(&mut fx.engine, &folder, true);
|
|
||||||
assert!(!outcome.changed);
|
|
||||||
assert_eq!(fx.ids().len(), 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_failed_save_stops_at_the_file_and_leaves_it_dirty() {
|
|
||||||
let mut fx = Fixture::new();
|
|
||||||
fx.write("a.gpx", "a");
|
|
||||||
fx.open_folder();
|
|
||||||
let id = fx.ids()[0];
|
|
||||||
fx.rename(id, "edited");
|
|
||||||
// the place of the file is taken by a folder
|
|
||||||
fs::remove_file(fx.folder.join("a.gpx")).unwrap();
|
|
||||||
fs::create_dir(fx.folder.join("a.gpx")).unwrap();
|
|
||||||
let result = fx
|
|
||||||
.workspace
|
|
||||||
.save(&mut fx.engine, &[id], &BTreeMap::new(), None);
|
|
||||||
assert!(result.is_err());
|
|
||||||
assert!(fx.workspace.is_dirty(&fx.engine, id));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn saving_as_gives_the_file_another_place() {
|
|
||||||
let mut fx = Fixture::new();
|
|
||||||
let a = fx.write("a.gpx", "a");
|
|
||||||
fx.write("b.gpx", "b");
|
|
||||||
fx.open_folder();
|
|
||||||
let id = fx.id_named("a");
|
|
||||||
let other = fx.id_named("b");
|
|
||||||
fx.rename(id, "edited");
|
|
||||||
|
|
||||||
let target = fx.folder.join("copy.gpx");
|
|
||||||
fx.workspace.save_as(&mut fx.engine, id, &target).unwrap();
|
|
||||||
assert!(fs::read_to_string(&target).unwrap().contains("edited"));
|
|
||||||
assert!(fs::read_to_string(a).unwrap().contains(">a<"));
|
|
||||||
let status = fx.status(id);
|
|
||||||
assert!(!status.dirty);
|
|
||||||
assert_eq!(status.path.as_deref(), canonical(&target).to_str());
|
|
||||||
|
|
||||||
// the place of another open file is not available
|
|
||||||
let taken = fx.folder.join("b.gpx");
|
|
||||||
assert!(fx.workspace.save_as(&mut fx.engine, id, &taken).is_err());
|
|
||||||
assert!(!fx.workspace.is_dirty(&fx.engine, other));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod restart_tests {
|
|
||||||
use gpx_engine::Persister;
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
use crate::store::FileStorage;
|
|
||||||
|
|
||||||
/// What the app does when it starts again: the engine and the links are read from what was
|
|
||||||
/// kept.
|
|
||||||
fn restart(engine: &Engine, workspace: &Workspace, root: &Path) -> (Engine, Workspace) {
|
|
||||||
let storage = FileStorage::open(root).unwrap();
|
|
||||||
pollster::block_on(Persister::default().save(&storage, engine.snapshot())).unwrap();
|
|
||||||
let mut restarted = Engine::default();
|
|
||||||
let restored = pollster::block_on(Persister::default().restore(&storage)).unwrap();
|
|
||||||
restarted.restore(restored);
|
|
||||||
let links = serde_json::to_string(workspace).unwrap();
|
|
||||||
(restarted, serde_json::from_str(&links).unwrap())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn setup() -> (PathBuf, Engine, Workspace, Vec<Uuid>) {
|
|
||||||
let root = std::env::temp_dir().join(format!("gpx-restart-{}", Uuid::new_v4()));
|
|
||||||
let folder = root.join("tracks");
|
|
||||||
fs::create_dir_all(&folder).unwrap();
|
|
||||||
for name in ["with_tracks", "with_time", "with_waypoint"] {
|
|
||||||
let _ = fs::copy(
|
|
||||||
format!("../gpx-rs/data/{name}.gpx"),
|
|
||||||
folder.join(format!("{name}.gpx")),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
let mut engine = Engine::default();
|
|
||||||
let mut workspace = Workspace::default();
|
|
||||||
workspace.open_folder(&mut engine, &folder, false);
|
|
||||||
workspace.open_files(&mut engine, &tests::gpx_files(&folder), false);
|
|
||||||
let ids = engine.order().iter().map(|id| id.0).collect();
|
|
||||||
(root, engine, workspace, ids)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn files_that_were_not_edited_are_not_unsaved_after_a_restart() {
|
|
||||||
let (root, engine, workspace, ids) = setup();
|
|
||||||
assert!(ids.len() >= 2);
|
|
||||||
let (restarted, mut workspace) = restart(&engine, &workspace, &root.join("store"));
|
|
||||||
// the files are the same, but the engine knows their contents by new identities
|
|
||||||
assert!(ids.iter().any(|id| workspace.is_dirty(&restarted, *id)));
|
|
||||||
workspace.verify(&restarted);
|
|
||||||
assert!(ids.iter().all(|id| !workspace.is_dirty(&restarted, *id)));
|
|
||||||
fs::remove_dir_all(root).unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn files_that_were_edited_are_still_unsaved_after_a_restart() {
|
|
||||||
let (root, mut engine, workspace, ids) = setup();
|
|
||||||
api::select(&mut engine, &[ids[0]], gpx_engine::SelectMode::Replace);
|
|
||||||
api::metadata(&mut engine, "edited", "");
|
|
||||||
assert!(workspace.is_dirty(&engine, ids[0]));
|
|
||||||
let (restarted, mut workspace) = restart(&engine, &workspace, &root.join("store"));
|
|
||||||
workspace.verify(&restarted);
|
|
||||||
assert!(workspace.is_dirty(&restarted, ids[0]));
|
|
||||||
assert!(
|
|
||||||
ids[1..]
|
|
||||||
.iter()
|
|
||||||
.all(|id| !workspace.is_dirty(&restarted, *id))
|
|
||||||
);
|
|
||||||
fs::remove_dir_all(root).unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn links_made_before_the_content_was_kept_are_checked_against_the_disk() {
|
|
||||||
let (root, mut engine, mut workspace, ids) = setup();
|
|
||||||
api::select(&mut engine, &[ids[0]], gpx_engine::SelectMode::Replace);
|
|
||||||
api::metadata(&mut engine, "edited", "");
|
|
||||||
for link in workspace.links.values_mut() {
|
|
||||||
link.export_hash = 0;
|
|
||||||
}
|
|
||||||
let (restarted, mut workspace) = restart(&engine, &workspace, &root.join("store"));
|
|
||||||
workspace.verify(&restarted);
|
|
||||||
assert!(workspace.is_dirty(&restarted, ids[0]));
|
|
||||||
assert!(
|
|
||||||
ids[1..]
|
|
||||||
.iter()
|
|
||||||
.all(|id| !workspace.is_dirty(&restarted, *id))
|
|
||||||
);
|
|
||||||
fs::remove_dir_all(root).unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_folders_of_new_files_and_the_old_flag_name_survive_a_restart() {
|
|
||||||
let (root, engine, mut workspace, ids) = setup();
|
|
||||||
let folder = workspace.folder.clone().unwrap();
|
|
||||||
let fresh = Uuid::new_v4();
|
|
||||||
workspace.inherit(&[fresh.to_string()], &folder);
|
|
||||||
workspace.links.get_mut(&ids[0]).unwrap().replaced = true;
|
|
||||||
let json = serde_json::to_string(&workspace).unwrap();
|
|
||||||
// links written by the previous version had `conflict`, which is the same thing
|
|
||||||
let json = json.replace("\"replaced\"", "\"conflict\"");
|
|
||||||
assert!(json.contains("\"conflict\":true"));
|
|
||||||
let read: Workspace = serde_json::from_str(&json).unwrap();
|
|
||||||
assert!(read.links[&ids[0]].replaced);
|
|
||||||
assert_eq!(read.dirs.get(&fresh), Some(&folder));
|
|
||||||
let _ = engine;
|
|
||||||
fs::remove_dir_all(root).unwrap();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -6,12 +6,21 @@ use tauri::test::{INVOKE_KEY, get_ipc_response, mock_builder, mock_context, noop
|
|||||||
use tauri::webview::InvokeRequest;
|
use tauri::webview::InvokeRequest;
|
||||||
use tauri::{WebviewWindow, ipc::CallbackFn, ipc::InvokeBody, ipc::InvokeResponseBody};
|
use tauri::{WebviewWindow, ipc::CallbackFn, ipc::InvokeBody, ipc::InvokeResponseBody};
|
||||||
|
|
||||||
|
/// The origin of the pages of the app, the one Tauri allows the commands from: Windows has no
|
||||||
|
/// custom protocols, the pages come from `http://tauri.localhost` there.
|
||||||
|
const ORIGIN: &str = if cfg!(windows) {
|
||||||
|
"http://tauri.localhost"
|
||||||
|
} else {
|
||||||
|
"tauri://localhost"
|
||||||
|
};
|
||||||
|
|
||||||
struct App(WebviewWindow<tauri::test::MockRuntime>);
|
struct App(WebviewWindow<tauri::test::MockRuntime>);
|
||||||
|
|
||||||
impl App {
|
impl App {
|
||||||
fn new() -> Self {
|
fn new() -> Self {
|
||||||
let app =
|
let app = gpx_studio_desktop_lib::register_commands(
|
||||||
crate::register_commands(mock_builder().manage(crate::state::AppState::temporary()))
|
mock_builder().manage(crate::temporary_state()),
|
||||||
|
)
|
||||||
.build(mock_context(noop_assets()))
|
.build(mock_context(noop_assets()))
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let window = tauri::WebviewWindowBuilder::new(&app, "main", Default::default())
|
let window = tauri::WebviewWindowBuilder::new(&app, "main", Default::default())
|
||||||
@@ -34,7 +43,7 @@ impl App {
|
|||||||
cmd: cmd.into(),
|
cmd: cmd.into(),
|
||||||
callback: CallbackFn(0),
|
callback: CallbackFn(0),
|
||||||
error: CallbackFn(1),
|
error: CallbackFn(1),
|
||||||
url: "tauri://localhost".parse().unwrap(),
|
url: ORIGIN.parse().unwrap(),
|
||||||
body,
|
body,
|
||||||
headers,
|
headers,
|
||||||
invoke_key: INVOKE_KEY.to_string(),
|
invoke_key: INVOKE_KEY.to_string(),
|
||||||
@@ -50,6 +59,20 @@ impl App {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The error of a command that fails.
|
||||||
|
fn error(&self, cmd: &str, args: Value) -> Value {
|
||||||
|
let request = InvokeRequest {
|
||||||
|
cmd: cmd.into(),
|
||||||
|
callback: CallbackFn(0),
|
||||||
|
error: CallbackFn(1),
|
||||||
|
url: ORIGIN.parse().unwrap(),
|
||||||
|
body: InvokeBody::Json(args),
|
||||||
|
headers: Default::default(),
|
||||||
|
invoke_key: INVOKE_KEY.to_string(),
|
||||||
|
};
|
||||||
|
get_ipc_response(&self.0, request).expect_err(&format!("{cmd} did not fail"))
|
||||||
|
}
|
||||||
|
|
||||||
fn bytes(&self, cmd: &str, args: Value) -> Vec<u8> {
|
fn bytes(&self, cmd: &str, args: Value) -> Vec<u8> {
|
||||||
match self.request(cmd, InvokeBody::Json(args), Default::default()) {
|
match self.request(cmd, InvokeBody::Json(args), Default::default()) {
|
||||||
InvokeResponseBody::Raw(bytes) => bytes,
|
InvokeResponseBody::Raw(bytes) => bytes,
|
||||||
@@ -257,7 +280,7 @@ fn waypoints_exports_and_routing_revisions() {
|
|||||||
|
|
||||||
let exported = app.bytes(
|
let exported = app.bytes(
|
||||||
"export_file",
|
"export_file",
|
||||||
json!({ "fileId": file, "time": true, "hr": true, "cad": true, "atemp": true, "power": true, "osm": true, "asRoute": false }),
|
json!({ "fileId": file, "time": true, "hr": true, "cad": true, "atemp": true, "power": true, "osm": true }),
|
||||||
);
|
);
|
||||||
assert_eq!(exported[0], 1);
|
assert_eq!(exported[0], 1);
|
||||||
assert!(
|
assert!(
|
||||||
@@ -297,8 +320,8 @@ fn keeps_settings_for_the_session() {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn the_files_are_still_there_in_the_next_session() {
|
fn the_files_are_still_there_in_the_next_session() {
|
||||||
use crate::state::AppState;
|
|
||||||
use gpx_engine::api;
|
use gpx_engine::api;
|
||||||
|
use gpx_studio_desktop_lib::state::AppState;
|
||||||
|
|
||||||
let directory =
|
let directory =
|
||||||
std::env::temp_dir().join(format!("gpx-studio-session-{}", uuid::Uuid::new_v4()));
|
std::env::temp_dir().join(format!("gpx-studio-session-{}", uuid::Uuid::new_v4()));
|
||||||
@@ -333,14 +356,14 @@ fn only_gpx_files_that_exist_are_taken_from_what_the_system_gives() {
|
|||||||
text.to_string_lossy().into_owned(),
|
text.to_string_lossy().into_owned(),
|
||||||
directory.join("missing.gpx").to_string_lossy().into_owned(),
|
directory.join("missing.gpx").to_string_lossy().into_owned(),
|
||||||
];
|
];
|
||||||
assert_eq!(crate::gpx_paths(arguments), [track]);
|
assert_eq!(gpx_studio_desktop_lib::gpx_paths(arguments), [track]);
|
||||||
std::fs::remove_dir_all(directory).unwrap();
|
std::fs::remove_dir_all(directory).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_file_opened_with_the_app_is_opened_selected_and_announced() {
|
fn a_file_opened_with_the_app_is_opened_selected_and_announced() {
|
||||||
use crate::state::AppState;
|
|
||||||
use gpx_engine::api;
|
use gpx_engine::api;
|
||||||
|
use gpx_studio_desktop_lib::state::AppState;
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
let directory = std::env::temp_dir().join(format!("gpx-studio-open-{}", uuid::Uuid::new_v4()));
|
let directory = std::env::temp_dir().join(format!("gpx-studio-open-{}", uuid::Uuid::new_v4()));
|
||||||
@@ -427,7 +450,7 @@ fn a_file_outside_the_open_folder_is_read_again_when_the_disk_changes() {
|
|||||||
|
|
||||||
let (events, received) = mpsc::channel();
|
let (events, received) = mpsc::channel();
|
||||||
let directory = std::env::temp_dir().join(format!("gpx-store-{}", uuid::Uuid::new_v4()));
|
let directory = std::env::temp_dir().join(format!("gpx-store-{}", uuid::Uuid::new_v4()));
|
||||||
let state = crate::state::AppState::open(
|
let state = gpx_studio_desktop_lib::state::AppState::open(
|
||||||
directory.clone(),
|
directory.clone(),
|
||||||
std::sync::Arc::new(move |name, _| {
|
std::sync::Arc::new(move |name, _| {
|
||||||
let _ = events.send(name.to_string());
|
let _ = events.send(name.to_string());
|
||||||
@@ -447,8 +470,8 @@ fn a_file_outside_the_open_folder_is_read_again_when_the_disk_changes() {
|
|||||||
});
|
});
|
||||||
let id = uuid::Uuid::parse_str(&id).unwrap();
|
let id = uuid::Uuid::parse_str(&id).unwrap();
|
||||||
// the name comes from the path, which does not change: the content does
|
// the name comes from the path, which does not change: the content does
|
||||||
let signature = |state: &crate::state::AppState| {
|
let signature = |state: &gpx_studio_desktop_lib::state::AppState| {
|
||||||
state.core(move |core| crate::workspace::signature(&core.engine, id))
|
state.core(move |core| gpx_studio_desktop_lib::workspace::signature(&core.engine, id))
|
||||||
};
|
};
|
||||||
let before = signature(&state);
|
let before = signature(&state);
|
||||||
|
|
||||||
@@ -469,7 +492,7 @@ fn a_file_outside_the_open_folder_is_read_again_when_the_disk_changes() {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn files_made_from_a_file_of_the_open_folder_are_written_next_to_it_at_once() {
|
fn files_made_from_a_file_of_the_open_folder_are_written_next_to_it_at_once() {
|
||||||
let state = crate::state::AppState::temporary();
|
let state = crate::temporary_state();
|
||||||
let folder = std::env::temp_dir().join(format!("gpx-tests-{}", uuid::Uuid::new_v4()));
|
let folder = std::env::temp_dir().join(format!("gpx-tests-{}", uuid::Uuid::new_v4()));
|
||||||
std::fs::create_dir_all(folder.join("sub")).unwrap();
|
std::fs::create_dir_all(folder.join("sub")).unwrap();
|
||||||
std::fs::copy("../gpx-rs/data/simple.gpx", folder.join("sub/track.gpx")).unwrap();
|
std::fs::copy("../gpx-rs/data/simple.gpx", folder.join("sub/track.gpx")).unwrap();
|
||||||
@@ -483,7 +506,7 @@ fn files_made_from_a_file_of_the_open_folder_are_written_next_to_it_at_once() {
|
|||||||
assert_eq!(opened.added().len(), 1);
|
assert_eq!(opened.added().len(), 1);
|
||||||
let copy = core.creating(None, false, gpx_engine::api::duplicate);
|
let copy = core.creating(None, false, gpx_engine::api::duplicate);
|
||||||
let fresh = core.creating(None, true, |e| {
|
let fresh = core.creating(None, true, |e| {
|
||||||
gpx_engine::api::new_file(e, "fresh", None, None, None)
|
gpx_engine::api::new_file(e, "fresh", None, None, None, false)
|
||||||
});
|
});
|
||||||
// a copy of the file goes next to it, a new file with nothing selected in the selection
|
// a copy of the file goes next to it, a new file with nothing selected in the selection
|
||||||
// of the file that was just made
|
// of the file that was just made
|
||||||
@@ -500,21 +523,25 @@ fn files_made_from_a_file_of_the_open_folder_are_written_next_to_it_at_once() {
|
|||||||
.values()
|
.values()
|
||||||
.map(|file| file.path.clone().unwrap())
|
.map(|file| file.path.clone().unwrap())
|
||||||
.collect();
|
.collect();
|
||||||
// the copy is in the subfolder, named after the file
|
// the copy is in the subfolder, named after its name (the one in the file, not of the file)
|
||||||
assert!(
|
assert!(
|
||||||
paths.iter().any(|path| path.ends_with("sub/track (2).gpx")),
|
paths
|
||||||
|
.iter()
|
||||||
|
.any(|path| std::path::Path::new(path).ends_with("sub/simple.gpx")),
|
||||||
"{paths:?}"
|
"{paths:?}"
|
||||||
);
|
);
|
||||||
// the new file went where the selected file is
|
// the new file went where the selected file is
|
||||||
assert!(
|
assert!(
|
||||||
paths.iter().any(|path| path.ends_with("sub/fresh.gpx")),
|
paths
|
||||||
|
.iter()
|
||||||
|
.any(|path| std::path::Path::new(path).ends_with("sub/fresh.gpx")),
|
||||||
"{paths:?}"
|
"{paths:?}"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn the_parts_of_a_split_are_numbered_from_one() {
|
fn the_parts_of_a_split_are_numbered_from_one() {
|
||||||
let state = crate::state::AppState::temporary();
|
let state = crate::temporary_state();
|
||||||
let folder = std::env::temp_dir().join(format!("gpx-tests-{}", uuid::Uuid::new_v4()));
|
let folder = std::env::temp_dir().join(format!("gpx-tests-{}", uuid::Uuid::new_v4()));
|
||||||
std::fs::create_dir_all(&folder).unwrap();
|
std::fs::create_dir_all(&folder).unwrap();
|
||||||
std::fs::copy("../gpx-rs/data/simple.gpx", folder.join("track.gpx")).unwrap();
|
std::fs::copy("../gpx-rs/data/simple.gpx", folder.join("track.gpx")).unwrap();
|
||||||
@@ -536,8 +563,8 @@ fn the_parts_of_a_split_are_numbered_from_one() {
|
|||||||
.map(|entry| entry.file_name().to_string_lossy().into_owned())
|
.map(|entry| entry.file_name().to_string_lossy().into_owned())
|
||||||
.collect();
|
.collect();
|
||||||
names.sort();
|
names.sort();
|
||||||
// the file stays, its two parts are numbered from 1
|
// the file stays, its two parts are numbered from 1, under their name (the one in the file)
|
||||||
assert_eq!(names, ["track (1).gpx", "track (2).gpx", "track.gpx"]);
|
assert_eq!(names, ["simple (1).gpx", "simple (2).gpx", "track.gpx"]);
|
||||||
std::fs::remove_dir_all(folder).unwrap();
|
std::fs::remove_dir_all(folder).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -581,8 +608,18 @@ fn name_of(app: &App, id: &str) -> String {
|
|||||||
.to_string()
|
.to_string()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The name of the file on the disk of an open file, without its extension.
|
||||||
|
fn file_stem_of(app: &App, id: &str) -> String {
|
||||||
|
let path = app.call("workspace_state", json!({}))["files"][id]["path"].clone();
|
||||||
|
std::path::Path::new(path.as_str().unwrap())
|
||||||
|
.file_stem()
|
||||||
|
.unwrap()
|
||||||
|
.to_string_lossy()
|
||||||
|
.into_owned()
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_file_is_called_like_its_file_and_renaming_it_renames_the_file() {
|
fn a_file_keeps_its_name_and_its_file_is_renamed_apart() {
|
||||||
let app = App::new();
|
let app = App::new();
|
||||||
let folder = folder_with(&["outside", "taken"]);
|
let folder = folder_with(&["outside", "taken"]);
|
||||||
let outcome = app.call(
|
let outcome = app.call(
|
||||||
@@ -590,76 +627,62 @@ fn a_file_is_called_like_its_file_and_renaming_it_renames_the_file() {
|
|||||||
json!({ "paths": [folder.join("outside.gpx")] }),
|
json!({ "paths": [folder.join("outside.gpx")] }),
|
||||||
);
|
);
|
||||||
let id = outcome["added"][0].as_str().unwrap().to_string();
|
let id = outcome["added"][0].as_str().unwrap().to_string();
|
||||||
|
let dirty = |app: &App| app.call("workspace_state", json!({}))["files"][&id]["dirty"].clone();
|
||||||
|
let inside = |name: &str| std::fs::read_to_string(folder.join(format!("{name}.gpx"))).unwrap();
|
||||||
|
|
||||||
// the name in the file is not the name of the file: the file wins, and nothing is unsaved
|
// the name in the file is its name, not the one of the file
|
||||||
assert_eq!(name_of(&app, &id), "outside");
|
assert_eq!(name_of(&app, &id), "Inside");
|
||||||
assert_eq!(
|
assert_eq!(file_stem_of(&app, &id), "outside");
|
||||||
app.call("workspace_state", json!({}))["files"][&id]["dirty"],
|
assert_eq!(dirty(&app), false);
|
||||||
false
|
|
||||||
);
|
|
||||||
|
|
||||||
// renaming renames the file on the disk
|
// renaming it is an edit of the file only, which is undone
|
||||||
app.call("select", json!({ "fileIds": [id], "mode": "replace" }));
|
app.call("select", json!({ "fileIds": [id], "mode": "replace" }));
|
||||||
let outcome = app.call("metadata", json!({ "name": "renamed", "desc": "" }));
|
let outcome = app.call("metadata", json!({ "name": "renamed", "desc": "" }));
|
||||||
assert!(outcome.get("error").is_none());
|
assert!(outcome.get("error").is_none());
|
||||||
assert!(folder.join("renamed.gpx").exists());
|
assert_eq!(name_of(&app, &id), "renamed");
|
||||||
assert!(!folder.join("outside.gpx").exists());
|
assert_eq!(file_stem_of(&app, &id), "outside");
|
||||||
let path = app.call("workspace_state", json!({}))["files"][&id]["path"].clone();
|
assert_eq!(dirty(&app), true);
|
||||||
assert!(path.as_str().unwrap().ends_with("renamed.gpx"));
|
|
||||||
// the file had nothing unsaved: it is written with its new name, and still has nothing unsaved
|
|
||||||
let dirty = |app: &App| app.call("workspace_state", json!({}))["files"][&id]["dirty"].clone();
|
|
||||||
let inside = |name: &str| std::fs::read_to_string(folder.join(format!("{name}.gpx"))).unwrap();
|
|
||||||
assert_eq!(dirty(&app), false);
|
|
||||||
assert!(inside("renamed").contains("<name>renamed</name>"));
|
|
||||||
|
|
||||||
// undone and redone, on the disk too, still with nothing unsaved
|
|
||||||
app.call("undo", json!({}));
|
app.call("undo", json!({}));
|
||||||
assert_eq!(name_of(&app, &id), "outside");
|
assert_eq!(name_of(&app, &id), "Inside");
|
||||||
assert!(folder.join("outside.gpx").exists() && !folder.join("renamed.gpx").exists());
|
|
||||||
assert_eq!(dirty(&app), false);
|
|
||||||
assert!(inside("outside").contains("<name>outside</name>"));
|
|
||||||
app.call("redo", json!({}));
|
|
||||||
assert_eq!(name_of(&app, &id), "renamed");
|
|
||||||
assert!(folder.join("renamed.gpx").exists() && !folder.join("outside.gpx").exists());
|
|
||||||
assert_eq!(dirty(&app), false);
|
assert_eq!(dirty(&app), false);
|
||||||
|
|
||||||
// the name of another file is not taken, nothing changes
|
// the file on the disk is renamed apart: not an edit, the file is as saved as it was
|
||||||
let outcome = app.call("metadata", json!({ "name": "taken", "desc": "" }));
|
let renamed = app.call("rename_file", json!({ "fileId": id, "name": "moved" }));
|
||||||
assert_eq!(outcome["error"], crate::workspace::NAME_TAKEN);
|
assert_eq!(renamed, true);
|
||||||
assert_eq!(name_of(&app, &id), "renamed");
|
assert!(folder.join("moved.gpx").exists() && !folder.join("outside.gpx").exists());
|
||||||
assert!(folder.join("renamed.gpx").exists());
|
assert_eq!(file_stem_of(&app, &id), "moved");
|
||||||
|
assert_eq!(name_of(&app, &id), "Inside");
|
||||||
|
assert_eq!(dirty(&app), false);
|
||||||
|
assert_eq!(app.call("can_undo", json!({})), false);
|
||||||
|
// saving writes to the new place, under the name of the file
|
||||||
|
app.call("metadata", json!({ "name": "saved", "desc": "" }));
|
||||||
|
app.call("save_files", json!({ "fileIds": [id] }));
|
||||||
|
assert!(inside("moved").contains("<name>saved</name>"));
|
||||||
|
assert_eq!(name_of(&app, &id), "saved");
|
||||||
|
|
||||||
|
// the name of another file is not taken
|
||||||
|
let error = app.error("rename_file", json!({ "fileId": id, "name": "taken" }));
|
||||||
|
assert_eq!(error, gpx_studio_desktop_lib::workspace::NAME_TAKEN);
|
||||||
|
assert!(folder.join("moved.gpx").exists());
|
||||||
|
|
||||||
// a name is one that a file can have
|
// a name is one that a file can have
|
||||||
app.call("metadata", json!({ "name": "a/b", "desc": "" }));
|
app.call("rename_file", json!({ "fileId": id, "name": "a/b" }));
|
||||||
assert_eq!(name_of(&app, &id), "a_b");
|
|
||||||
assert!(folder.join("a_b.gpx").exists());
|
assert!(folder.join("a_b.gpx").exists());
|
||||||
|
|
||||||
// a file with edits is renamed, but not written: its edits are not saved for it
|
|
||||||
app.call("style", json!({ "color": "#ff0000" }));
|
|
||||||
assert_eq!(dirty(&app), true);
|
|
||||||
app.call("metadata", json!({ "name": "edited", "desc": "" }));
|
|
||||||
assert!(folder.join("edited.gpx").exists());
|
|
||||||
assert_eq!(dirty(&app), true);
|
|
||||||
assert!(!inside("edited").contains("ff0000"));
|
|
||||||
app.call("undo", json!({}));
|
|
||||||
app.call("undo", json!({}));
|
|
||||||
assert_eq!(name_of(&app, &id), "a_b");
|
|
||||||
assert_eq!(dirty(&app), false);
|
|
||||||
|
|
||||||
// only the case changes: the same file
|
// only the case changes: the same file
|
||||||
app.call("metadata", json!({ "name": "A_B", "desc": "" }));
|
app.call("rename_file", json!({ "fileId": id, "name": "A_B" }));
|
||||||
assert_eq!(name_of(&app, &id), "A_B");
|
|
||||||
let names: Vec<String> = std::fs::read_dir(&folder)
|
let names: Vec<String> = std::fs::read_dir(&folder)
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
|
.map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
|
||||||
.collect();
|
.collect();
|
||||||
assert!(names.contains(&"A_B.gpx".to_string()));
|
assert!(names.contains(&"A_B.gpx".to_string()));
|
||||||
assert_eq!(names.len(), 2);
|
assert_eq!(names.len(), 2);
|
||||||
|
assert_eq!(name_of(&app, &id), "saved");
|
||||||
std::fs::remove_dir_all(folder).unwrap();
|
std::fs::remove_dir_all(folder).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_new_file_written_under_another_name_takes_it() {
|
fn a_new_file_written_under_another_name_keeps_its_own() {
|
||||||
let app = App::new();
|
let app = App::new();
|
||||||
let folder = folder_with(&["route"]);
|
let folder = folder_with(&["route"]);
|
||||||
// a new file made in the folder is written there at once: route.gpx is taken
|
// a new file made in the folder is written there at once: route.gpx is taken
|
||||||
@@ -669,7 +692,8 @@ fn a_new_file_written_under_another_name_takes_it() {
|
|||||||
);
|
);
|
||||||
let id = created["added"][0].as_str().unwrap().to_string();
|
let id = created["added"][0].as_str().unwrap().to_string();
|
||||||
assert!(folder.join("route (2).gpx").exists());
|
assert!(folder.join("route (2).gpx").exists());
|
||||||
assert_eq!(name_of(&app, &id), "route (2)");
|
// the file keeps its name, whatever the name of the file it was written to
|
||||||
|
assert_eq!(name_of(&app, &id), "route");
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
app.call("workspace_state", json!({}))["files"][&id]["dirty"],
|
app.call("workspace_state", json!({}))["files"][&id]["dirty"],
|
||||||
false
|
false
|
||||||
@@ -698,7 +722,7 @@ fn a_file_open_as_a_preview_is_replaced_until_it_is_kept_or_edited() {
|
|||||||
.as_array()
|
.as_array()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.iter()
|
.iter()
|
||||||
.map(|id| name_of(app, id.as_str().unwrap()))
|
.map(|id| file_stem_of(app, id.as_str().unwrap()))
|
||||||
.collect()
|
.collect()
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
//! The tests of the desktop app. They are integration tests, in a single binary, rather than unit
|
||||||
|
//! tests: on Windows, only test binaries can be given the manifest that the app needs to start
|
||||||
|
//! (see `build.rs`).
|
||||||
|
|
||||||
|
mod commands;
|
||||||
|
mod store;
|
||||||
|
mod workspace;
|
||||||
|
|
||||||
|
use gpx_studio_desktop_lib::state::AppState;
|
||||||
|
|
||||||
|
/// An engine that keeps its data in a directory of its own, and has nobody to tell.
|
||||||
|
fn temporary_state() -> AppState {
|
||||||
|
let directory = std::env::temp_dir().join(format!("gpx-studio-{}", uuid::Uuid::new_v4()));
|
||||||
|
AppState::open(directory, std::sync::Arc::new(|_, _| {})).expect("the storage can be opened")
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
//! The storage of the engine on the file system (`store`).
|
||||||
|
|
||||||
|
use std::fs;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
use gpx_engine::{
|
||||||
|
Action, Batch, Command, CommitError, Load, LoadFiles, Persister, Revision, Storage,
|
||||||
|
};
|
||||||
|
use gpx_studio_desktop_lib::Engine;
|
||||||
|
use gpx_studio_desktop_lib::store::FileStorage;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
fn directory() -> PathBuf {
|
||||||
|
std::env::temp_dir().join(format!("gpx-studio-store-{}", Uuid::new_v4()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn engine_with_a_file() -> Engine {
|
||||||
|
let mut engine = Engine::default();
|
||||||
|
let data = std::fs::read("../gpx-rs/data/simple.gpx").unwrap();
|
||||||
|
engine
|
||||||
|
.execute(Action::Edit(Command::LoadFiles(LoadFiles {
|
||||||
|
files: vec![Load {
|
||||||
|
data: &data,
|
||||||
|
name: "simple",
|
||||||
|
}],
|
||||||
|
})))
|
||||||
|
.unwrap();
|
||||||
|
engine
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn keeps_the_files_and_the_settings_between_sessions() {
|
||||||
|
let root = directory();
|
||||||
|
let engine = engine_with_a_file();
|
||||||
|
let order = engine.order().to_vec();
|
||||||
|
|
||||||
|
let storage = FileStorage::open(&root).unwrap();
|
||||||
|
pollster::block_on(Persister::default().save(&storage, engine.snapshot())).unwrap();
|
||||||
|
pollster::block_on(storage.put_setting("units", "\"metric\"")).unwrap();
|
||||||
|
|
||||||
|
// another session
|
||||||
|
let storage = FileStorage::open(&root).unwrap();
|
||||||
|
let restored = pollster::block_on(Persister::default().restore(&storage)).unwrap();
|
||||||
|
let mut other = Engine::default();
|
||||||
|
other.restore(restored);
|
||||||
|
assert_eq!(other.order(), order);
|
||||||
|
assert_eq!(
|
||||||
|
other.file_statistics(&order[0]).unwrap().total_distance,
|
||||||
|
engine.file_statistics(&order[0]).unwrap().total_distance
|
||||||
|
);
|
||||||
|
assert_eq!(storage.settings()["units"], "\"metric\"");
|
||||||
|
fs::remove_dir_all(root).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn refuses_a_commit_that_is_not_based_on_the_head() {
|
||||||
|
let root = directory();
|
||||||
|
let storage = FileStorage::open(&root).unwrap();
|
||||||
|
let batch = Batch {
|
||||||
|
order: Some(vec![]),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
assert_eq!(pollster::block_on(storage.commit(&batch)), Ok(Revision(1)));
|
||||||
|
assert_eq!(
|
||||||
|
pollster::block_on(storage.commit(&batch)),
|
||||||
|
Err(CommitError::Stale { head: Revision(1) })
|
||||||
|
);
|
||||||
|
fs::remove_dir_all(root).unwrap();
|
||||||
|
}
|
||||||
@@ -0,0 +1,811 @@
|
|||||||
|
//! The places of the files of the engine on the disk (`workspace`).
|
||||||
|
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
use std::fs;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use gpx_engine::{FileId, SelectMode, api};
|
||||||
|
use gpx_studio_desktop_lib::Engine;
|
||||||
|
use gpx_studio_desktop_lib::workspace::*;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
fn gpx(name: &str) -> String {
|
||||||
|
format!(
|
||||||
|
r#"<?xml version="1.0"?><gpx version="1.1" creator="test" xmlns="http://www.topografix.com/GPX/1/1"><metadata><name>{name}</name></metadata><trk><name>{name}</name><trkseg><trkpt lat="50.0" lon="4.0"><ele>10</ele></trkpt><trkpt lat="50.1" lon="4.1"><ele>20</ele></trkpt></trkseg></trk></gpx>"#
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The GPX files of a folder and of the folders in it.
|
||||||
|
pub fn gpx_files(folder: &Path) -> Vec<PathBuf> {
|
||||||
|
let mut found = vec![];
|
||||||
|
for entry in fs::read_dir(folder).unwrap().flatten() {
|
||||||
|
let path = entry.path();
|
||||||
|
if path.is_dir() {
|
||||||
|
found.extend(gpx_files(&path));
|
||||||
|
} else if is_gpx(&path) {
|
||||||
|
found.push(path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
found.sort();
|
||||||
|
found
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Fixture {
|
||||||
|
folder: PathBuf,
|
||||||
|
engine: Engine,
|
||||||
|
workspace: Workspace,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Fixture {
|
||||||
|
fn new() -> Self {
|
||||||
|
let folder = canonical(&std::env::temp_dir()).join(format!("gpx-ws-{}", Uuid::new_v4()));
|
||||||
|
fs::create_dir_all(&folder).unwrap();
|
||||||
|
Self {
|
||||||
|
folder,
|
||||||
|
engine: Engine::default(),
|
||||||
|
workspace: Workspace::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write(&self, name: &str, title: &str) -> PathBuf {
|
||||||
|
let path = self.folder.join(name);
|
||||||
|
fs::write(&path, gpx(title)).unwrap();
|
||||||
|
path
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Opens the folder, and all the files that are in it.
|
||||||
|
fn open_folder(&mut self) {
|
||||||
|
let folder = self.folder.clone();
|
||||||
|
self.workspace.open_folder(&mut self.engine, &folder, false);
|
||||||
|
let files = gpx_files(&folder);
|
||||||
|
self.workspace.open_files(&mut self.engine, &files, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reconcile(&mut self, changed: Option<&[PathBuf]>) -> Option<api::Outcome> {
|
||||||
|
self.workspace.reconcile(&mut self.engine, changed)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn save(&mut self, ids: &[Uuid]) {
|
||||||
|
self.workspace
|
||||||
|
.save(&mut self.engine, ids, &BTreeMap::new(), None)
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ids(&self) -> Vec<Uuid> {
|
||||||
|
self.engine.order().iter().map(|id| id.0).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn id_named(&self, name: &str) -> Uuid {
|
||||||
|
self.ids()
|
||||||
|
.into_iter()
|
||||||
|
.find(|id| self.name(*id) == name)
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn name(&self, id: Uuid) -> String {
|
||||||
|
self.engine
|
||||||
|
.file_structure(&FileId(id))
|
||||||
|
.unwrap()
|
||||||
|
.name
|
||||||
|
.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the file holds: the name of its track (its own name is the one of the file).
|
||||||
|
fn content(&self, id: Uuid) -> String {
|
||||||
|
self.engine.file_structure(&FileId(id)).unwrap().tracks[0]
|
||||||
|
.info
|
||||||
|
.name
|
||||||
|
.clone()
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rename(&mut self, id: Uuid, name: &str) {
|
||||||
|
api::select(&mut self.engine, &[id], SelectMode::Replace);
|
||||||
|
assert!(!api::metadata(&mut self.engine, name, "").has_error());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn status(&self, id: Uuid) -> FileStatus {
|
||||||
|
self.workspace
|
||||||
|
.state(&self.engine)
|
||||||
|
.files
|
||||||
|
.remove(&id.to_string())
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for Fixture {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
let _ = fs::remove_dir_all(&self.folder);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_opened_file_is_clean_until_it_is_edited_and_clean_again_once_saved() {
|
||||||
|
let mut fx = Fixture::new();
|
||||||
|
let path = fx.write("a.gpx", "a");
|
||||||
|
fx.workspace
|
||||||
|
.open_files(&mut fx.engine, std::slice::from_ref(&path), true);
|
||||||
|
let id = fx.ids()[0];
|
||||||
|
assert!(!fx.workspace.is_dirty(&fx.engine, id));
|
||||||
|
assert_eq!(fx.status(id).path.as_deref(), path.to_str());
|
||||||
|
|
||||||
|
fx.rename(id, "renamed");
|
||||||
|
assert!(fx.workspace.is_dirty(&fx.engine, id));
|
||||||
|
// nothing is written before it is saved
|
||||||
|
assert!(fs::read_to_string(&path).unwrap().contains(">a<"));
|
||||||
|
|
||||||
|
fx.save(&[id]);
|
||||||
|
assert!(!fx.workspace.is_dirty(&fx.engine, id));
|
||||||
|
assert!(fs::read_to_string(&path).unwrap().contains(">renamed<"));
|
||||||
|
|
||||||
|
// going back before the save is an edit again
|
||||||
|
api::select(&mut fx.engine, &[id], SelectMode::Replace);
|
||||||
|
api::undo(&mut fx.engine);
|
||||||
|
assert!(fx.workspace.is_dirty(&fx.engine, id));
|
||||||
|
api::redo(&mut fx.engine);
|
||||||
|
assert!(!fx.workspace.is_dirty(&fx.engine, id));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_file_that_is_not_on_the_disk_is_unsaved_until_it_is_given_a_place() {
|
||||||
|
let mut fx = Fixture::new();
|
||||||
|
api::new_file(&mut fx.engine, "fresh", None, None, None, false);
|
||||||
|
let id = fx.ids()[0];
|
||||||
|
assert!(fx.workspace.is_dirty(&fx.engine, id));
|
||||||
|
assert_eq!(
|
||||||
|
fx.workspace.unlinked(&fx.engine, &[id]),
|
||||||
|
[(id, "fresh".to_string())]
|
||||||
|
);
|
||||||
|
// nowhere to put it without being told
|
||||||
|
fx.save(&[id]);
|
||||||
|
assert!(fx.workspace.is_dirty(&fx.engine, id));
|
||||||
|
|
||||||
|
let path = fx.folder.join("fresh.gpx");
|
||||||
|
let paths = BTreeMap::from([(id, path.clone())]);
|
||||||
|
fx.workspace
|
||||||
|
.save(&mut fx.engine, &[id], &paths, None)
|
||||||
|
.unwrap();
|
||||||
|
assert!(path.exists());
|
||||||
|
assert!(!fx.workspace.is_dirty(&fx.engine, id));
|
||||||
|
assert!(fx.workspace.unlinked(&fx.engine, &[id]).is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn several_files_without_a_place_go_in_a_folder_with_names_that_are_free() {
|
||||||
|
let mut fx = Fixture::new();
|
||||||
|
fx.write("fresh.gpx", "already there");
|
||||||
|
api::new_file(&mut fx.engine, "fresh", None, None, None, false);
|
||||||
|
api::new_file(&mut fx.engine, "a/b: c", None, None, None, false);
|
||||||
|
api::new_file(&mut fx.engine, "fresh", None, None, None, false);
|
||||||
|
let ids = fx.ids();
|
||||||
|
let folder = fx.folder.clone();
|
||||||
|
fx.workspace
|
||||||
|
.save(&mut fx.engine, &ids, &BTreeMap::new(), Some(&folder))
|
||||||
|
.unwrap();
|
||||||
|
for name in ["fresh (2).gpx", "fresh (3).gpx", "a_b_ c.gpx"] {
|
||||||
|
assert!(fx.folder.join(name).exists(), "{name}");
|
||||||
|
}
|
||||||
|
assert!(ids.iter().all(|id| !fx.workspace.is_dirty(&fx.engine, *id)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn what_this_app_writes_is_not_a_change_of_the_disk() {
|
||||||
|
let mut fx = Fixture::new();
|
||||||
|
let path = fx.write("a.gpx", "a");
|
||||||
|
fx.open_folder();
|
||||||
|
let id = fx.ids()[0];
|
||||||
|
api::select(&mut fx.engine, &[id], SelectMode::Replace);
|
||||||
|
assert!(!api::style(&mut fx.engine, Some("#ff0000"), None, None).has_error());
|
||||||
|
fx.save(&[id]);
|
||||||
|
assert!(fx.reconcile(Some(&[path])).is_none());
|
||||||
|
assert!(!fx.status(id).replaced && !fx.status(id).dirty);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_folders_of_the_files_outside_the_open_folder_are_watched_too() {
|
||||||
|
let mut fx = Fixture::new();
|
||||||
|
let inside = fx.write("in.gpx", "in");
|
||||||
|
let elsewhere = canonical(&std::env::temp_dir()).join(format!("gpx-ws-{}", Uuid::new_v4()));
|
||||||
|
fs::create_dir_all(&elsewhere).unwrap();
|
||||||
|
let (one, two) = (elsewhere.join("one.gpx"), elsewhere.join("two.gpx"));
|
||||||
|
fs::write(&one, gpx("one")).unwrap();
|
||||||
|
fs::write(&two, gpx("two")).unwrap();
|
||||||
|
let folder = fx.folder.clone();
|
||||||
|
|
||||||
|
// no folder: only the folder of the files
|
||||||
|
fx.workspace.open_files(&mut fx.engine, &[one, two], false);
|
||||||
|
assert_eq!(fx.workspace.watched(), [(elsewhere.clone(), false)]);
|
||||||
|
|
||||||
|
// the open folder as a whole, and the file in it needs nothing more
|
||||||
|
fx.workspace.open_folder(&mut fx.engine, &folder, false);
|
||||||
|
fx.workspace.open_files(&mut fx.engine, &[inside], false);
|
||||||
|
assert_eq!(
|
||||||
|
fx.workspace.watched(),
|
||||||
|
[(folder, true), (elsewhere.clone(), false)]
|
||||||
|
);
|
||||||
|
|
||||||
|
// closing the files stops it
|
||||||
|
let ids = fx.ids();
|
||||||
|
fx.workspace.close_files(&mut fx.engine, &ids, true);
|
||||||
|
assert_eq!(fx.workspace.watched(), [(fx.folder.clone(), true)]);
|
||||||
|
fs::remove_dir_all(elsewhere).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn opening_a_folder_does_not_open_its_files() {
|
||||||
|
let mut fx = Fixture::new();
|
||||||
|
fx.write("a.gpx", "a");
|
||||||
|
let folder = fx.folder.clone();
|
||||||
|
let outcome = fx.workspace.open_folder(&mut fx.engine, &folder, false);
|
||||||
|
assert!(!outcome.changed);
|
||||||
|
assert!(fx.ids().is_empty());
|
||||||
|
assert_eq!(fx.workspace.folder.as_deref(), Some(folder.as_path()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn folders_are_made_renamed_and_moved_and_the_open_files_follow() {
|
||||||
|
let mut fx = Fixture::new();
|
||||||
|
let a = fx.write("a.gpx", "a");
|
||||||
|
fx.open_folder();
|
||||||
|
let id = fx.ids()[0];
|
||||||
|
let root = fx.folder.clone();
|
||||||
|
let path_of = |fx: &Fixture| PathBuf::from(fx.status(id).path.unwrap());
|
||||||
|
|
||||||
|
let first = fx.workspace.create_folder(&root, "New folder").unwrap();
|
||||||
|
let second = fx.workspace.create_folder(&root, "New folder").unwrap();
|
||||||
|
assert_eq!(first, root.join("New folder"));
|
||||||
|
assert_eq!(second, root.join("New folder 2"));
|
||||||
|
|
||||||
|
fx.workspace.move_paths(&[a], &first).unwrap();
|
||||||
|
assert_eq!(path_of(&fx), first.join("a.gpx"));
|
||||||
|
assert!(first.join("a.gpx").exists() && !fx.status(id).dirty);
|
||||||
|
|
||||||
|
let trips = fx.workspace.rename_path(&first, "Trips").unwrap();
|
||||||
|
assert_eq!(path_of(&fx), root.join("Trips/a.gpx"));
|
||||||
|
// a folder does not go into itself, nor onto something else
|
||||||
|
assert!(
|
||||||
|
fx.workspace
|
||||||
|
.move_paths(std::slice::from_ref(&trips), &trips)
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
fx.workspace.rename_path(&trips, "New folder 2"),
|
||||||
|
Err(NAME_TAKEN.to_owned())
|
||||||
|
);
|
||||||
|
fx.workspace.move_paths(&[trips], &second).unwrap();
|
||||||
|
assert_eq!(path_of(&fx), second.join("Trips/a.gpx"));
|
||||||
|
|
||||||
|
// a file keeps its extension
|
||||||
|
let closed = fx.write("c.gpx", "c");
|
||||||
|
assert_eq!(
|
||||||
|
fx.workspace.rename_path(&closed, "d").unwrap(),
|
||||||
|
root.join("d.gpx")
|
||||||
|
);
|
||||||
|
// the open folder and what is not in it are left alone
|
||||||
|
assert!(fx.workspace.rename_path(&root, "x").is_err());
|
||||||
|
let elsewhere = canonical(&std::env::temp_dir());
|
||||||
|
assert!(fx.workspace.rename_path(&elsewhere, "x").is_err());
|
||||||
|
assert!(fx.workspace.create_folder(&elsewhere, "x").is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn deleted_files_are_closed_unless_they_have_edits() {
|
||||||
|
let mut fx = Fixture::new();
|
||||||
|
let a = fx.write("a.gpx", "a");
|
||||||
|
let b = fx.write("b.gpx", "b");
|
||||||
|
fx.open_folder();
|
||||||
|
let (id_a, id_b) = (fx.id_named("a"), fx.id_named("b"));
|
||||||
|
api::select(&mut fx.engine, &[id_b], SelectMode::Replace);
|
||||||
|
assert!(!api::style(&mut fx.engine, Some("#ff0000"), None, None).has_error());
|
||||||
|
|
||||||
|
let outcome = fx
|
||||||
|
.workspace
|
||||||
|
.delete_paths(&mut fx.engine, &[a.clone(), b.clone()], |paths| {
|
||||||
|
paths.iter().for_each(|path| fs::remove_file(path).unwrap());
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
assert!(outcome.changed);
|
||||||
|
assert_eq!(fx.ids(), [id_b]);
|
||||||
|
assert!(!fx.ids().contains(&id_a));
|
||||||
|
let status = fx.status(id_b);
|
||||||
|
assert!(status.dirty && status.missing);
|
||||||
|
assert!(!a.exists() && !b.exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_tree_of_the_folder_shows_folders_first_and_only_gpx_files() {
|
||||||
|
let mut fx = Fixture::new();
|
||||||
|
fx.write("b.gpx", "b");
|
||||||
|
fx.write("A.GPX", "a");
|
||||||
|
fx.write("b 10.gpx", "b 10");
|
||||||
|
fx.write("b 2.gpx", "b 2");
|
||||||
|
fx.write("notes.txt", "not a track");
|
||||||
|
fx.write(".hidden.gpx", "hidden");
|
||||||
|
fs::create_dir(fx.folder.join("zoo")).unwrap();
|
||||||
|
fs::create_dir(fx.folder.join("Alps")).unwrap();
|
||||||
|
fs::create_dir(fx.folder.join(".git")).unwrap();
|
||||||
|
fx.write("zoo/c.gpx", "c");
|
||||||
|
let folder = fx.folder.clone();
|
||||||
|
fx.workspace.open_folder(&mut fx.engine, &folder, false);
|
||||||
|
|
||||||
|
let names = |entries: Vec<Entry>| -> Vec<(String, bool)> {
|
||||||
|
entries.into_iter().map(|e| (e.name, e.is_dir)).collect()
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
names(fx.workspace.list_folder(&folder).unwrap()),
|
||||||
|
[
|
||||||
|
("Alps".to_string(), true),
|
||||||
|
("zoo".to_string(), true),
|
||||||
|
("A.GPX".to_string(), false),
|
||||||
|
("b.gpx".to_string(), false),
|
||||||
|
("b 2.gpx".to_string(), false),
|
||||||
|
("b 10.gpx".to_string(), false),
|
||||||
|
]
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
names(fx.workspace.list_folder(&folder.join("zoo")).unwrap()),
|
||||||
|
[("c.gpx".to_string(), false)]
|
||||||
|
);
|
||||||
|
// only what is in the open folder can be listed
|
||||||
|
let elsewhere = canonical(&std::env::temp_dir());
|
||||||
|
assert!(fx.workspace.list_folder(&elsewhere).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn names_are_sorted_by_the_numbers_they_hold() {
|
||||||
|
let mut names = vec![
|
||||||
|
"track 10",
|
||||||
|
"track 2",
|
||||||
|
"Track 1",
|
||||||
|
"track",
|
||||||
|
"track 02b",
|
||||||
|
"track 2a",
|
||||||
|
"b",
|
||||||
|
"A",
|
||||||
|
];
|
||||||
|
names.sort_by(|a, b| natural_cmp(a, b).then_with(|| a.cmp(b)));
|
||||||
|
assert_eq!(
|
||||||
|
names,
|
||||||
|
[
|
||||||
|
"A",
|
||||||
|
"b",
|
||||||
|
"track",
|
||||||
|
"Track 1",
|
||||||
|
"track 2",
|
||||||
|
"track 2a",
|
||||||
|
"track 02b",
|
||||||
|
"track 10",
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_file_without_edits_is_read_again_when_the_disk_changes() {
|
||||||
|
let mut fx = Fixture::new();
|
||||||
|
let a = fx.write("a.gpx", "a");
|
||||||
|
fx.open_folder();
|
||||||
|
let id = fx.ids()[0];
|
||||||
|
|
||||||
|
fx.write("a.gpx", "theirs");
|
||||||
|
let outcome = fx.reconcile(Some(std::slice::from_ref(&a))).unwrap();
|
||||||
|
assert!(outcome.changed);
|
||||||
|
// the same file, now the one on the disk
|
||||||
|
assert_eq!(fx.ids(), [id]);
|
||||||
|
assert_eq!(fx.content(id), "theirs");
|
||||||
|
let status = fx.status(id);
|
||||||
|
assert!(!status.dirty && !status.replaced);
|
||||||
|
// looking again changes nothing
|
||||||
|
assert!(fx.reconcile(Some(std::slice::from_ref(&a))).is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_file_with_edits_is_flagged_when_the_disk_changes_and_not_read_again() {
|
||||||
|
let mut fx = Fixture::new();
|
||||||
|
let a = fx.write("a.gpx", "a");
|
||||||
|
fx.open_folder();
|
||||||
|
let id = fx.ids()[0];
|
||||||
|
fx.rename(id, "mine");
|
||||||
|
|
||||||
|
fx.write("a.gpx", "theirs");
|
||||||
|
let outcome = fx.reconcile(Some(std::slice::from_ref(&a))).unwrap();
|
||||||
|
assert!(!outcome.changed);
|
||||||
|
assert_eq!(fx.name(id), "mine");
|
||||||
|
let status = fx.status(id);
|
||||||
|
assert!(status.dirty && status.replaced && !status.missing);
|
||||||
|
// looking again changes nothing
|
||||||
|
assert!(fx.reconcile(Some(std::slice::from_ref(&a))).is_none());
|
||||||
|
|
||||||
|
// the disk goes back to what was read: only the edits are left
|
||||||
|
fx.write("a.gpx", "a");
|
||||||
|
assert!(fx.reconcile(Some(std::slice::from_ref(&a))).is_some());
|
||||||
|
let status = fx.status(id);
|
||||||
|
assert!(status.dirty && !status.replaced);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_user_can_take_the_disk_instead_of_the_edits() {
|
||||||
|
let mut fx = Fixture::new();
|
||||||
|
fx.write("a.gpx", "a");
|
||||||
|
fx.open_folder();
|
||||||
|
let id = fx.ids()[0];
|
||||||
|
fx.rename(id, "mine");
|
||||||
|
fx.write("a.gpx", "theirs");
|
||||||
|
fx.reconcile(None);
|
||||||
|
assert!(fx.status(id).replaced);
|
||||||
|
|
||||||
|
fx.workspace.reload(&mut fx.engine, &[id]).unwrap();
|
||||||
|
assert_eq!(fx.content(id), "theirs");
|
||||||
|
let status = fx.status(id);
|
||||||
|
assert!(!status.dirty && !status.replaced);
|
||||||
|
// and it is one undo step
|
||||||
|
api::select(&mut fx.engine, &[id], SelectMode::Replace);
|
||||||
|
api::undo(&mut fx.engine);
|
||||||
|
assert_eq!(fx.content(id), "mine");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn saving_overwrites_what_replaced_the_file() {
|
||||||
|
let mut fx = Fixture::new();
|
||||||
|
let a = fx.write("a.gpx", "a");
|
||||||
|
fx.open_folder();
|
||||||
|
let id = fx.ids()[0];
|
||||||
|
fx.rename(id, "mine");
|
||||||
|
fx.write("a.gpx", "theirs");
|
||||||
|
fx.reconcile(None);
|
||||||
|
assert!(fx.status(id).replaced);
|
||||||
|
|
||||||
|
fx.save(&[id]);
|
||||||
|
assert!(fs::read_to_string(a).unwrap().contains(">mine<"));
|
||||||
|
assert!(!fx.status(id).replaced && !fx.status(id).dirty);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_file_that_is_gone_from_the_disk_stays_open_and_dirty_until_it_is_saved_again() {
|
||||||
|
let mut fx = Fixture::new();
|
||||||
|
let a = fx.write("a.gpx", "a");
|
||||||
|
fx.open_folder();
|
||||||
|
let id = fx.ids()[0];
|
||||||
|
|
||||||
|
fs::remove_file(&a).unwrap();
|
||||||
|
assert!(fx.reconcile(Some(std::slice::from_ref(&a))).is_some());
|
||||||
|
assert_eq!(fx.ids(), [id]);
|
||||||
|
let status = fx.status(id);
|
||||||
|
assert!(status.dirty && status.missing && status.path.is_some());
|
||||||
|
|
||||||
|
// saving puts it back
|
||||||
|
fx.save(&[id]);
|
||||||
|
assert!(a.exists());
|
||||||
|
let status = fx.status(id);
|
||||||
|
assert!(!status.dirty && !status.missing);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_file_that_comes_back_different_is_read_again() {
|
||||||
|
let mut fx = Fixture::new();
|
||||||
|
let a = fx.write("a.gpx", "a");
|
||||||
|
fx.open_folder();
|
||||||
|
let id = fx.ids()[0];
|
||||||
|
fs::remove_file(&a).unwrap();
|
||||||
|
fx.reconcile(None);
|
||||||
|
assert!(fx.status(id).missing);
|
||||||
|
|
||||||
|
fx.write("a.gpx", "back");
|
||||||
|
fx.reconcile(None);
|
||||||
|
assert_eq!(fx.content(id), "back");
|
||||||
|
let status = fx.status(id);
|
||||||
|
assert!(!status.dirty && !status.missing);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn what_changed_while_the_app_was_closed_is_found_when_it_starts() {
|
||||||
|
let mut fx = Fixture::new();
|
||||||
|
let a = fx.write("a.gpx", "a");
|
||||||
|
fx.open_folder();
|
||||||
|
let id = fx.ids()[0];
|
||||||
|
fx.write("a.gpx", "changed");
|
||||||
|
assert!(fx.reconcile(None).is_some());
|
||||||
|
assert_eq!(fx.content(id), "changed");
|
||||||
|
fs::remove_file(a).unwrap();
|
||||||
|
assert!(fx.reconcile(None).is_some());
|
||||||
|
assert!(fx.status(id).missing);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn new_files_made_from_a_file_of_the_folder_are_saved_next_to_it() {
|
||||||
|
let mut fx = Fixture::new();
|
||||||
|
fs::create_dir(fx.folder.join("sub")).unwrap();
|
||||||
|
fx.write("sub/b.gpx", "b");
|
||||||
|
fx.write("a.gpx", "a");
|
||||||
|
fx.open_folder();
|
||||||
|
let b = fx.id_named("b");
|
||||||
|
let sub = fx.folder.join("sub");
|
||||||
|
assert_eq!(fx.workspace.source_dir(&[b]), Some(canonical(&sub)));
|
||||||
|
|
||||||
|
let before = fx.ids();
|
||||||
|
api::select(&mut fx.engine, &[b], SelectMode::Replace);
|
||||||
|
let outcome = api::duplicate(&mut fx.engine);
|
||||||
|
let copy = fx
|
||||||
|
.ids()
|
||||||
|
.into_iter()
|
||||||
|
.find(|id| !before.contains(id))
|
||||||
|
.unwrap();
|
||||||
|
fx.workspace.inherit(outcome.added(), &canonical(&sub));
|
||||||
|
assert_eq!(fx.status(copy).folder.as_deref(), canonical(&sub).to_str());
|
||||||
|
assert!(fx.status(copy).path.is_none() && fx.status(copy).dirty);
|
||||||
|
// nobody needs to be asked where it goes
|
||||||
|
assert!(fx.workspace.unlinked(&fx.engine, &[copy]).is_empty());
|
||||||
|
|
||||||
|
fx.save(&[copy]);
|
||||||
|
assert!(sub.join("b (2).gpx").exists());
|
||||||
|
let status = fx.status(copy);
|
||||||
|
assert!(!status.dirty && status.folder.is_none());
|
||||||
|
assert_eq!(
|
||||||
|
status.path.as_deref(),
|
||||||
|
canonical(&sub.join("b (2).gpx")).to_str()
|
||||||
|
);
|
||||||
|
// the copy of the copy is next to it as well
|
||||||
|
assert_eq!(fx.workspace.source_dir(&[copy]), Some(canonical(&sub)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_file_outside_the_open_folder_hands_nothing_down() {
|
||||||
|
let mut fx = Fixture::new();
|
||||||
|
let elsewhere = canonical(&std::env::temp_dir()).join(format!("gpx-ws-{}", Uuid::new_v4()));
|
||||||
|
fs::create_dir_all(&elsewhere).unwrap();
|
||||||
|
let outside = elsewhere.join("o.gpx");
|
||||||
|
fs::write(&outside, gpx("o")).unwrap();
|
||||||
|
let folder = fx.folder.clone();
|
||||||
|
fx.workspace.open_folder(&mut fx.engine, &folder, false);
|
||||||
|
fx.workspace
|
||||||
|
.open_files(&mut fx.engine, std::slice::from_ref(&outside), true);
|
||||||
|
let id = fx.ids()[0];
|
||||||
|
assert_eq!(fx.workspace.source_dir(&[id]), None);
|
||||||
|
// a new file with no source is not linked to a folder by `source_dir`: the caller falls back
|
||||||
|
fs::remove_dir_all(elsewhere).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn closing_files_asks_what_to_do_with_the_unsaved_ones() {
|
||||||
|
let mut fx = Fixture::new();
|
||||||
|
fx.write("a.gpx", "a");
|
||||||
|
fx.write("b.gpx", "b");
|
||||||
|
fx.open_folder();
|
||||||
|
let (a, b) = (fx.id_named("a"), fx.id_named("b"));
|
||||||
|
fx.rename(a, "edited");
|
||||||
|
assert_eq!(fx.workspace.unsaved(&fx.engine, &[a, b]), [a]);
|
||||||
|
|
||||||
|
// without a choice what has edits stays
|
||||||
|
let outcome = fx.workspace.close_files(&mut fx.engine, &[a, b], false);
|
||||||
|
assert!(outcome.changed);
|
||||||
|
assert_eq!(fx.ids(), [a]);
|
||||||
|
|
||||||
|
// saved first
|
||||||
|
fx.save(&[a]);
|
||||||
|
fx.workspace.close_files(&mut fx.engine, &[a], false);
|
||||||
|
assert!(fx.ids().is_empty());
|
||||||
|
assert!(
|
||||||
|
fs::read_to_string(fx.folder.join("a.gpx"))
|
||||||
|
.unwrap()
|
||||||
|
.contains("edited")
|
||||||
|
);
|
||||||
|
assert!(fx.workspace.links.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn closing_files_can_discard_their_edits() {
|
||||||
|
let mut fx = Fixture::new();
|
||||||
|
fx.write("a.gpx", "a");
|
||||||
|
fx.open_folder();
|
||||||
|
let a = fx.ids()[0];
|
||||||
|
fx.rename(a, "edited");
|
||||||
|
api::new_file(&mut fx.engine, "fresh", None, None, None, false);
|
||||||
|
let fresh = fx.id_named("fresh");
|
||||||
|
fx.workspace.close_files(&mut fx.engine, &[a, fresh], true);
|
||||||
|
assert!(fx.ids().is_empty());
|
||||||
|
assert!(
|
||||||
|
fs::read_to_string(fx.folder.join("a.gpx"))
|
||||||
|
.unwrap()
|
||||||
|
.contains(">a<")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn closing_the_folder_closes_every_file() {
|
||||||
|
let mut fx = Fixture::new();
|
||||||
|
fx.write("a.gpx", "a");
|
||||||
|
fx.open_folder();
|
||||||
|
api::new_file(&mut fx.engine, "fresh", None, None, None, false);
|
||||||
|
assert_eq!(fx.ids().len(), 2);
|
||||||
|
|
||||||
|
// the new file has nowhere to go: it has to be discarded
|
||||||
|
let outcome = fx.workspace.close_folder(&mut fx.engine, false);
|
||||||
|
assert!(outcome.changed);
|
||||||
|
assert_eq!(fx.ids().len(), 1);
|
||||||
|
assert!(fx.workspace.folder.is_none());
|
||||||
|
|
||||||
|
let outcome = fx.workspace.close_folder(&mut fx.engine, true);
|
||||||
|
assert!(outcome.changed);
|
||||||
|
assert!(fx.ids().is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn opening_another_folder_closes_the_first_with_all_its_files() {
|
||||||
|
let mut fx = Fixture::new();
|
||||||
|
fx.write("a.gpx", "a");
|
||||||
|
fx.open_folder();
|
||||||
|
let a = fx.ids()[0];
|
||||||
|
fx.rename(a, "edited");
|
||||||
|
let other = canonical(&std::env::temp_dir()).join(format!("gpx-ws-{}", Uuid::new_v4()));
|
||||||
|
fs::create_dir_all(&other).unwrap();
|
||||||
|
|
||||||
|
// the edits stay, nothing is lost without a choice
|
||||||
|
fx.workspace.open_folder(&mut fx.engine, &other, false);
|
||||||
|
assert_eq!(fx.ids(), [a]);
|
||||||
|
assert_eq!(fx.workspace.folder.as_deref(), Some(other.as_path()));
|
||||||
|
|
||||||
|
let first = fx.folder.clone();
|
||||||
|
fx.workspace.open_folder(&mut fx.engine, &first, true);
|
||||||
|
assert!(fx.ids().is_empty());
|
||||||
|
assert!(
|
||||||
|
fs::read_to_string(fx.folder.join("a.gpx"))
|
||||||
|
.unwrap()
|
||||||
|
.contains(">a<")
|
||||||
|
);
|
||||||
|
fs::remove_dir_all(other).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn opening_the_same_folder_again_changes_nothing() {
|
||||||
|
let mut fx = Fixture::new();
|
||||||
|
fx.write("a.gpx", "a");
|
||||||
|
fx.open_folder();
|
||||||
|
let folder = fx.folder.clone();
|
||||||
|
let outcome = fx.workspace.open_folder(&mut fx.engine, &folder, true);
|
||||||
|
assert!(!outcome.changed);
|
||||||
|
assert_eq!(fx.ids().len(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_failed_save_stops_at_the_file_and_leaves_it_dirty() {
|
||||||
|
let mut fx = Fixture::new();
|
||||||
|
fx.write("a.gpx", "a");
|
||||||
|
fx.open_folder();
|
||||||
|
let id = fx.ids()[0];
|
||||||
|
fx.rename(id, "edited");
|
||||||
|
// the place of the file is taken by a folder
|
||||||
|
fs::remove_file(fx.folder.join("a.gpx")).unwrap();
|
||||||
|
fs::create_dir(fx.folder.join("a.gpx")).unwrap();
|
||||||
|
let result = fx
|
||||||
|
.workspace
|
||||||
|
.save(&mut fx.engine, &[id], &BTreeMap::new(), None);
|
||||||
|
assert!(result.is_err());
|
||||||
|
assert!(fx.workspace.is_dirty(&fx.engine, id));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn saving_as_gives_the_file_another_place() {
|
||||||
|
let mut fx = Fixture::new();
|
||||||
|
let a = fx.write("a.gpx", "a");
|
||||||
|
fx.write("b.gpx", "b");
|
||||||
|
fx.open_folder();
|
||||||
|
let id = fx.id_named("a");
|
||||||
|
let other = fx.id_named("b");
|
||||||
|
fx.rename(id, "edited");
|
||||||
|
|
||||||
|
let target = fx.folder.join("copy.gpx");
|
||||||
|
fx.workspace.save_as(&mut fx.engine, id, &target).unwrap();
|
||||||
|
assert!(fs::read_to_string(&target).unwrap().contains("edited"));
|
||||||
|
assert!(fs::read_to_string(a).unwrap().contains(">a<"));
|
||||||
|
let status = fx.status(id);
|
||||||
|
assert!(!status.dirty);
|
||||||
|
assert_eq!(status.path.as_deref(), canonical(&target).to_str());
|
||||||
|
|
||||||
|
// the place of another open file is not available
|
||||||
|
let taken = fx.folder.join("b.gpx");
|
||||||
|
assert!(fx.workspace.save_as(&mut fx.engine, id, &taken).is_err());
|
||||||
|
assert!(!fx.workspace.is_dirty(&fx.engine, other));
|
||||||
|
}
|
||||||
|
|
||||||
|
mod restart {
|
||||||
|
use gpx_engine::Persister;
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
use gpx_studio_desktop_lib::store::FileStorage;
|
||||||
|
|
||||||
|
/// What the app does when it starts again: the engine and the links are read from what was
|
||||||
|
/// kept.
|
||||||
|
fn restart(engine: &Engine, workspace: &Workspace, root: &Path) -> (Engine, Workspace) {
|
||||||
|
let storage = FileStorage::open(root).unwrap();
|
||||||
|
pollster::block_on(Persister::default().save(&storage, engine.snapshot())).unwrap();
|
||||||
|
let mut restarted = Engine::default();
|
||||||
|
let restored = pollster::block_on(Persister::default().restore(&storage)).unwrap();
|
||||||
|
restarted.restore(restored);
|
||||||
|
let links = serde_json::to_string(workspace).unwrap();
|
||||||
|
(restarted, serde_json::from_str(&links).unwrap())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn setup() -> (PathBuf, Engine, Workspace, Vec<Uuid>) {
|
||||||
|
let root = std::env::temp_dir().join(format!("gpx-restart-{}", Uuid::new_v4()));
|
||||||
|
let folder = root.join("tracks");
|
||||||
|
fs::create_dir_all(&folder).unwrap();
|
||||||
|
for name in ["with_tracks", "with_time", "with_waypoint"] {
|
||||||
|
let _ = fs::copy(
|
||||||
|
format!("../gpx-rs/data/{name}.gpx"),
|
||||||
|
folder.join(format!("{name}.gpx")),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let mut engine = Engine::default();
|
||||||
|
let mut workspace = Workspace::default();
|
||||||
|
workspace.open_folder(&mut engine, &folder, false);
|
||||||
|
workspace.open_files(&mut engine, &gpx_files(&folder), false);
|
||||||
|
let ids = engine.order().iter().map(|id| id.0).collect();
|
||||||
|
(root, engine, workspace, ids)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn files_that_were_not_edited_are_not_unsaved_after_a_restart() {
|
||||||
|
let (root, engine, workspace, ids) = setup();
|
||||||
|
assert!(ids.len() >= 2);
|
||||||
|
let (restarted, mut workspace) = restart(&engine, &workspace, &root.join("store"));
|
||||||
|
// the files are the same, but the engine knows their contents by new identities
|
||||||
|
assert!(ids.iter().any(|id| workspace.is_dirty(&restarted, *id)));
|
||||||
|
workspace.verify(&restarted);
|
||||||
|
assert!(ids.iter().all(|id| !workspace.is_dirty(&restarted, *id)));
|
||||||
|
fs::remove_dir_all(root).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn files_that_were_edited_are_still_unsaved_after_a_restart() {
|
||||||
|
let (root, mut engine, workspace, ids) = setup();
|
||||||
|
api::select(&mut engine, &[ids[0]], gpx_engine::SelectMode::Replace);
|
||||||
|
api::metadata(&mut engine, "edited", "");
|
||||||
|
assert!(workspace.is_dirty(&engine, ids[0]));
|
||||||
|
let (restarted, mut workspace) = restart(&engine, &workspace, &root.join("store"));
|
||||||
|
workspace.verify(&restarted);
|
||||||
|
assert!(workspace.is_dirty(&restarted, ids[0]));
|
||||||
|
assert!(
|
||||||
|
ids[1..]
|
||||||
|
.iter()
|
||||||
|
.all(|id| !workspace.is_dirty(&restarted, *id))
|
||||||
|
);
|
||||||
|
fs::remove_dir_all(root).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn links_made_before_the_content_was_kept_are_checked_against_the_disk() {
|
||||||
|
let (root, mut engine, mut workspace, ids) = setup();
|
||||||
|
api::select(&mut engine, &[ids[0]], gpx_engine::SelectMode::Replace);
|
||||||
|
api::metadata(&mut engine, "edited", "");
|
||||||
|
for link in workspace.links.values_mut() {
|
||||||
|
link.export_hash = 0;
|
||||||
|
}
|
||||||
|
let (restarted, mut workspace) = restart(&engine, &workspace, &root.join("store"));
|
||||||
|
workspace.verify(&restarted);
|
||||||
|
assert!(workspace.is_dirty(&restarted, ids[0]));
|
||||||
|
assert!(
|
||||||
|
ids[1..]
|
||||||
|
.iter()
|
||||||
|
.all(|id| !workspace.is_dirty(&restarted, *id))
|
||||||
|
);
|
||||||
|
fs::remove_dir_all(root).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_folders_of_new_files_and_the_old_flag_name_survive_a_restart() {
|
||||||
|
let (root, engine, mut workspace, ids) = setup();
|
||||||
|
let folder = workspace.folder.clone().unwrap();
|
||||||
|
let fresh = Uuid::new_v4();
|
||||||
|
workspace.inherit(&[fresh.to_string()], &folder);
|
||||||
|
workspace.links.get_mut(&ids[0]).unwrap().replaced = true;
|
||||||
|
let json = serde_json::to_string(&workspace).unwrap();
|
||||||
|
// links written by the previous version had `conflict`, which is the same thing
|
||||||
|
let json = json.replace("\"replaced\"", "\"conflict\"");
|
||||||
|
assert!(json.contains("\"conflict\":true"));
|
||||||
|
let read: Workspace = serde_json::from_str(&json).unwrap();
|
||||||
|
assert!(read.links[&ids[0]].replaced);
|
||||||
|
assert_eq!(read.dirs.get(&fresh), Some(&folder));
|
||||||
|
let _ = engine;
|
||||||
|
fs::remove_dir_all(root).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
|
||||||
|
<dependency>
|
||||||
|
<dependentAssembly>
|
||||||
|
<assemblyIdentity
|
||||||
|
type="win32"
|
||||||
|
name="Microsoft.Windows.Common-Controls"
|
||||||
|
version="6.0.0.0"
|
||||||
|
processorArchitecture="*"
|
||||||
|
publicKeyToken="6595b64144ccf1df"
|
||||||
|
language="*"
|
||||||
|
/>
|
||||||
|
</dependentAssembly>
|
||||||
|
</dependency>
|
||||||
|
</assembly>
|
||||||
@@ -18,6 +18,17 @@ pub fn style(color: Option<String>, opacity: Option<f64>, width: Option<f64>) ->
|
|||||||
run(|e| api::style(e, color.as_deref(), opacity, width))
|
run(|e| api::style(e, color.as_deref(), opacity, width))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Converts the selected routes to tracks, or the selected tracks or segments to routes.
|
||||||
|
#[wasm_bindgen]
|
||||||
|
pub fn convert() -> Outcome {
|
||||||
|
run(api::convert)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[wasm_bindgen]
|
||||||
|
pub fn new_route() -> Outcome {
|
||||||
|
run(api::new_route)
|
||||||
|
}
|
||||||
|
|
||||||
#[wasm_bindgen]
|
#[wasm_bindgen]
|
||||||
pub fn new_track() -> Outcome {
|
pub fn new_track() -> Outcome {
|
||||||
run(api::new_track)
|
run(api::new_track)
|
||||||
|
|||||||
@@ -10,11 +10,18 @@ use crate::ts::*;
|
|||||||
|
|
||||||
// File commands
|
// File commands
|
||||||
|
|
||||||
/// Creates a file and selects it. With `lng` and `lat`, it starts with a track and a segment that
|
/// Creates a file and selects it. With `route`, it starts with a route. With `lng` and `lat`, it
|
||||||
/// hold that trackpoint (at `ele`, 0 by default).
|
/// starts with a segment that holds that trackpoint (at `ele`, 0 by default): the one of its route
|
||||||
|
/// with `route`, of a track otherwise.
|
||||||
#[wasm_bindgen]
|
#[wasm_bindgen]
|
||||||
pub fn new_file(name: &str, lng: Option<f64>, lat: Option<f64>, ele: Option<f64>) -> Outcome {
|
pub fn new_file(
|
||||||
run(|e| api::new_file(e, name, lng, lat, ele))
|
name: &str,
|
||||||
|
lng: Option<f64>,
|
||||||
|
lat: Option<f64>,
|
||||||
|
ele: Option<f64>,
|
||||||
|
route: bool,
|
||||||
|
) -> Outcome {
|
||||||
|
run(|e| api::new_file(e, name, lng, lat, ele, route))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Loads files as a single command (one undo step). The files are in `data`, one after the
|
/// Loads files as a single command (one undo step). The files are in `data`, one after the
|
||||||
|
|||||||
@@ -45,10 +45,8 @@ pub fn selection_statistics() -> GlobalStatistics {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// A file as GPX (UTF-8 bytes), `undefined` if it does not exist. The options say which data of the trackpoints
|
/// A file as GPX (UTF-8 bytes), `undefined` if it does not exist. The options say which data of the trackpoints
|
||||||
/// to keep, and with `as_route` that the segments are written as routes (`rte`) instead of tracks:
|
/// to keep.
|
||||||
/// the anchors are the route points, and the trackpoints between them the points of their path.
|
|
||||||
#[wasm_bindgen]
|
#[wasm_bindgen]
|
||||||
#[allow(clippy::too_many_arguments)]
|
|
||||||
pub fn export_file(
|
pub fn export_file(
|
||||||
file_id: &str,
|
file_id: &str,
|
||||||
time: bool,
|
time: bool,
|
||||||
@@ -57,7 +55,6 @@ pub fn export_file(
|
|||||||
atemp: bool,
|
atemp: bool,
|
||||||
power: bool,
|
power: bool,
|
||||||
osm: bool,
|
osm: bool,
|
||||||
as_route: bool,
|
|
||||||
) -> Option<Vec<u8>> {
|
) -> Option<Vec<u8>> {
|
||||||
let id = parse_uuid(file_id)?;
|
let id = parse_uuid(file_id)?;
|
||||||
let options = ExportOptions {
|
let options = ExportOptions {
|
||||||
@@ -67,7 +64,6 @@ pub fn export_file(
|
|||||||
atemp,
|
atemp,
|
||||||
power,
|
power,
|
||||||
osm,
|
osm,
|
||||||
as_route,
|
|
||||||
};
|
};
|
||||||
with_engine(|e| api::export_file(e, id, options)).flatten()
|
with_engine(|e| api::export_file(e, id, options)).flatten()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -41,6 +41,14 @@ pub fn arrow_select(down: bool, add: bool) -> Outcome {
|
|||||||
// with the selection when it holds elements of the same kind in the same place (same file, same
|
// 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.
|
// track for segments), otherwise they replace it.
|
||||||
|
|
||||||
|
#[wasm_bindgen]
|
||||||
|
pub fn select_routes(file_id: &str, route_ids_bytes: &[u8], mode: SelectMode) -> Outcome {
|
||||||
|
match parse_uuid(file_id).zip(uuid_list(route_ids_bytes)) {
|
||||||
|
Some((file_id, ids)) => run(|e| api::select_routes(e, file_id, &ids, mode.into())),
|
||||||
|
None => fail("the ids are not UUIDs"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[wasm_bindgen]
|
#[wasm_bindgen]
|
||||||
pub fn select_tracks(file_id: &str, track_ids_bytes: &[u8], mode: SelectMode) -> Outcome {
|
pub fn select_tracks(file_id: &str, track_ids_bytes: &[u8], mode: SelectMode) -> Outcome {
|
||||||
match parse_uuid(file_id).zip(uuid_list(track_ids_bytes)) {
|
match parse_uuid(file_id).zip(uuid_list(track_ids_bytes)) {
|
||||||
|
|||||||
+27
-21
@@ -16,6 +16,7 @@ use crate::types::*;
|
|||||||
const SIMPLE: &[u8] = include_bytes!("../../gpx-rs/data/simple.gpx");
|
const SIMPLE: &[u8] = include_bytes!("../../gpx-rs/data/simple.gpx");
|
||||||
const WITH_TIME: &[u8] = include_bytes!("../../gpx-rs/data/with_time.gpx");
|
const WITH_TIME: &[u8] = include_bytes!("../../gpx-rs/data/with_time.gpx");
|
||||||
const WITH_SURFACE: &[u8] = include_bytes!("../../gpx-rs/data/with_surface.gpx");
|
const WITH_SURFACE: &[u8] = include_bytes!("../../gpx-rs/data/with_surface.gpx");
|
||||||
|
const WITH_ROUTES: &[u8] = include_bytes!("../../gpx-rs/data/with_routes.gpx");
|
||||||
|
|
||||||
thread_local! {
|
thread_local! {
|
||||||
static LAST: std::cell::RefCell<JsValue> = const { std::cell::RefCell::new(JsValue::UNDEFINED) };
|
static LAST: std::cell::RefCell<JsValue> = const { std::cell::RefCell::new(JsValue::UNDEFINED) };
|
||||||
@@ -83,7 +84,7 @@ fn uuid_bytes(ids: &[String]) -> Vec<u8> {
|
|||||||
fn test_new_file_is_listed_and_selected() {
|
fn test_new_file_is_listed_and_selected() {
|
||||||
start();
|
start();
|
||||||
assert!(run(crate::command::files::new_file(
|
assert!(run(crate::command::files::new_file(
|
||||||
"route", None, None, None
|
"route", None, None, None, false
|
||||||
)));
|
)));
|
||||||
assert_eq!(last_error(), None);
|
assert_eq!(last_error(), None);
|
||||||
|
|
||||||
@@ -112,10 +113,7 @@ fn test_unknown_file_has_no_structure() {
|
|||||||
assert!(crate::queries::files::file_structure(&id).is_undefined());
|
assert!(crate::queries::files::file_structure(&id).is_undefined());
|
||||||
assert!(crate::queries::files::file_structure("not an id").is_undefined());
|
assert!(crate::queries::files::file_structure("not an id").is_undefined());
|
||||||
assert!(crate::queries::files::file_statistics(&id).is_undefined());
|
assert!(crate::queries::files::file_statistics(&id).is_undefined());
|
||||||
assert!(
|
assert!(crate::queries::files::export_file(&id, true, true, true, true, true, true).is_none());
|
||||||
crate::queries::files::export_file(&id, true, true, true, true, true, true, false)
|
|
||||||
.is_none()
|
|
||||||
);
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
crate::queries::coordinates::segment_coordinates(&id).length(),
|
crate::queries::coordinates::segment_coordinates(&id).length(),
|
||||||
0
|
0
|
||||||
@@ -200,7 +198,9 @@ fn test_the_reason_of_a_failure_can_be_read() {
|
|||||||
assert!(!run(crate::command::tools::reverse()));
|
assert!(!run(crate::command::tools::reverse()));
|
||||||
assert_eq!(last_error().as_deref(), Some("nothing to do"));
|
assert_eq!(last_error().as_deref(), Some("nothing to do"));
|
||||||
// the next call starts afresh
|
// the next call starts afresh
|
||||||
assert!(run(crate::command::files::new_file("a", None, None, None)));
|
assert!(run(crate::command::files::new_file(
|
||||||
|
"a", None, None, None, false
|
||||||
|
)));
|
||||||
assert_eq!(last_error(), None);
|
assert_eq!(last_error(), None);
|
||||||
|
|
||||||
// invalid data
|
// invalid data
|
||||||
@@ -253,7 +253,9 @@ fn test_the_reason_of_a_failure_can_be_read() {
|
|||||||
assert!(last_error().is_some());
|
assert!(last_error().is_some());
|
||||||
|
|
||||||
// answers are not failures
|
// answers are not failures
|
||||||
assert!(run(crate::command::files::new_file("b", None, None, None)));
|
assert!(run(crate::command::files::new_file(
|
||||||
|
"b", None, None, None, false
|
||||||
|
)));
|
||||||
assert!(!crate::command::files::can_paste());
|
assert!(!crate::command::files::can_paste());
|
||||||
assert_eq!(last_error(), None);
|
assert_eq!(last_error(), None);
|
||||||
}
|
}
|
||||||
@@ -262,7 +264,9 @@ fn test_the_reason_of_a_failure_can_be_read() {
|
|||||||
fn test_undo_and_redo() {
|
fn test_undo_and_redo() {
|
||||||
started_with(&[]);
|
started_with(&[]);
|
||||||
assert!(!can_undo() && !can_redo());
|
assert!(!can_undo() && !can_redo());
|
||||||
assert!(run(crate::command::files::new_file("a", None, None, None)));
|
assert!(run(crate::command::files::new_file(
|
||||||
|
"a", None, None, None, false
|
||||||
|
)));
|
||||||
assert!(can_undo() && !can_redo());
|
assert!(can_undo() && !can_redo());
|
||||||
assert!(run(undo()));
|
assert!(run(undo()));
|
||||||
assert!(order().is_empty());
|
assert!(order().is_empty());
|
||||||
@@ -279,8 +283,7 @@ fn test_export_and_exportable_data() {
|
|||||||
let ids = order();
|
let ids = order();
|
||||||
|
|
||||||
let bytes =
|
let bytes =
|
||||||
crate::queries::files::export_file(&ids[0], true, true, true, true, true, true, false)
|
crate::queries::files::export_file(&ids[0], true, true, true, true, true, true).unwrap();
|
||||||
.unwrap();
|
|
||||||
assert!(String::from_utf8(bytes).unwrap().contains("<gpx"));
|
assert!(String::from_utf8(bytes).unwrap().contains("<gpx"));
|
||||||
|
|
||||||
// the time is the first bit
|
// the time is the first bit
|
||||||
@@ -300,18 +303,17 @@ fn test_export_and_exportable_data() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[wasm_bindgen_test]
|
#[wasm_bindgen_test]
|
||||||
fn test_export_as_route() {
|
fn test_export_tracks_and_routes() {
|
||||||
started_with(&[(SIMPLE, "plain")]);
|
started_with(&[(SIMPLE, "track"), (WITH_ROUTES, "routes")]);
|
||||||
let id = order().remove(0);
|
let text = |id: &str| {
|
||||||
let text = |as_route| {
|
|
||||||
let bytes =
|
let bytes =
|
||||||
crate::queries::files::export_file(&id, true, true, true, true, true, true, as_route)
|
crate::queries::files::export_file(id, true, true, true, true, true, true).unwrap();
|
||||||
.unwrap();
|
|
||||||
String::from_utf8(bytes).unwrap()
|
String::from_utf8(bytes).unwrap()
|
||||||
};
|
};
|
||||||
let tracks = text(false);
|
let ids = order();
|
||||||
|
let tracks = text(&ids[0]);
|
||||||
assert!(tracks.contains("<trk>") && !tracks.contains("<rte>"));
|
assert!(tracks.contains("<trk>") && !tracks.contains("<rte>"));
|
||||||
let routes = text(true);
|
let routes = text(&ids[1]);
|
||||||
assert!(routes.contains("<rte>") && !routes.contains("<trk>"));
|
assert!(routes.contains("<rte>") && !routes.contains("<trk>"));
|
||||||
assert!(routes.contains("<rtept"));
|
assert!(routes.contains("<rtept"));
|
||||||
}
|
}
|
||||||
@@ -390,7 +392,7 @@ fn test_move_elements_takes_js_objects() {
|
|||||||
fn test_waypoints() {
|
fn test_waypoints() {
|
||||||
started_with(&[]);
|
started_with(&[]);
|
||||||
assert!(run(crate::command::files::new_file(
|
assert!(run(crate::command::files::new_file(
|
||||||
"file", None, None, None
|
"file", None, None, None, false
|
||||||
)));
|
)));
|
||||||
let file = order().remove(0);
|
let file = order().remove(0);
|
||||||
assert!(run(crate::command::waypoints::new_waypoint(
|
assert!(run(crate::command::waypoints::new_waypoint(
|
||||||
@@ -494,7 +496,9 @@ fn test_editing_tools_change_the_statistics() {
|
|||||||
#[wasm_bindgen_test]
|
#[wasm_bindgen_test]
|
||||||
fn test_last_update_describes_the_last_call_only() {
|
fn test_last_update_describes_the_last_call_only() {
|
||||||
started_with(&[]);
|
started_with(&[]);
|
||||||
assert!(run(crate::command::files::new_file("a", None, None, None)));
|
assert!(run(crate::command::files::new_file(
|
||||||
|
"a", None, None, None, false
|
||||||
|
)));
|
||||||
let update = last_outcome();
|
let update = last_outcome();
|
||||||
assert_eq!(array(get(&update, "added")).length(), 1);
|
assert_eq!(array(get(&update, "added")).length(), 1);
|
||||||
assert_eq!(get(&update, "orderChanged").as_bool(), Some(true));
|
assert_eq!(get(&update, "orderChanged").as_bool(), Some(true));
|
||||||
@@ -506,7 +510,9 @@ fn test_last_update_describes_the_last_call_only() {
|
|||||||
assert_eq!(get(&update, "orderChanged").as_bool(), Some(false));
|
assert_eq!(get(&update, "orderChanged").as_bool(), Some(false));
|
||||||
assert_eq!(get(&update, "selectionChanged").as_bool(), Some(false));
|
assert_eq!(get(&update, "selectionChanged").as_bool(), Some(false));
|
||||||
|
|
||||||
assert!(run(crate::command::files::new_file("b", None, None, None)));
|
assert!(run(crate::command::files::new_file(
|
||||||
|
"b", None, None, None, false
|
||||||
|
)));
|
||||||
assert!(!run(crate::command::tools::crop(3, 1)));
|
assert!(!run(crate::command::tools::crop(3, 1)));
|
||||||
let update = last_outcome();
|
let update = last_outcome();
|
||||||
assert_eq!(array(get(&update, "added")).length(), 0);
|
assert_eq!(array(get(&update, "added")).length(), 0);
|
||||||
|
|||||||
+18
-5
@@ -28,16 +28,19 @@ const FILE_STRUCTURE_TS: &str = r#"
|
|||||||
export type Selection =
|
export type Selection =
|
||||||
| { type: 'empty' }
|
| { type: 'empty' }
|
||||||
| { type: 'file'; fileIds: string[] }
|
| { type: 'file'; fileIds: string[] }
|
||||||
|
| { type: 'route'; fileId: string; routeIds: string[] }
|
||||||
| { type: 'track'; fileId: string; trackIds: string[] }
|
| { type: 'track'; fileId: string; trackIds: string[] }
|
||||||
| { type: 'segment'; fileId: string; trackId: string; segmentIds: string[] }
|
| { type: 'segment'; fileId: string; trackId: string; segmentIds: string[] }
|
||||||
| { type: 'waypoints'; fileId: string }
|
| { type: 'waypoints'; fileId: string }
|
||||||
| { type: 'waypoint'; fileId: string; waypointIds: string[] };
|
| { type: 'waypoint'; fileId: string; waypointIds: string[] };
|
||||||
/**
|
/**
|
||||||
* Where moved elements go: a list of the file tree and the position in it, counted among the
|
* Where moved elements go: a list of the file tree and the position in it, counted among the
|
||||||
* elements of the list that are not moved.
|
* elements of the list that are not moved. Routes and tracks keep their kind: moved among the
|
||||||
|
* other kind, routes go after the routes, tracks before the tracks.
|
||||||
*/
|
*/
|
||||||
export type MoveTarget =
|
export type MoveTarget =
|
||||||
| { type: 'files'; index: number }
|
| { type: 'files'; index: number }
|
||||||
|
| { type: 'routes'; fileId: string; index: number }
|
||||||
| { type: 'tracks'; fileId: string; index: number }
|
| { type: 'tracks'; fileId: string; index: number }
|
||||||
| { type: 'segments'; fileId: string; trackId: string; index: number }
|
| { type: 'segments'; fileId: string; trackId: string; index: number }
|
||||||
| { type: 'waypoints'; fileId: string; index: number };
|
| { type: 'waypoints'; fileId: string; index: number };
|
||||||
@@ -83,7 +86,7 @@ export interface SelectionPoint {
|
|||||||
}
|
}
|
||||||
/** What was copied or cut, to be pasted: the kind of the elements and their ids. */
|
/** What was copied or cut, to be pasted: the kind of the elements and their ids. */
|
||||||
export interface Clipboard {
|
export interface Clipboard {
|
||||||
type: 'files' | 'tracks' | 'segments' | 'waypoints';
|
type: 'files' | 'routes' | 'tracks' | 'segments' | 'waypoints';
|
||||||
ids: string[];
|
ids: string[];
|
||||||
cut: boolean;
|
cut: boolean;
|
||||||
}
|
}
|
||||||
@@ -119,6 +122,8 @@ export interface FileStructure {
|
|||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
desc?: string;
|
desc?: string;
|
||||||
|
/** The routes come before the tracks, in the file and in the statistics. */
|
||||||
|
routes: RouteNode[];
|
||||||
tracks: TrackNode[];
|
tracks: TrackNode[];
|
||||||
waypoints: WaypointNode[];
|
waypoints: WaypointNode[];
|
||||||
/** Changes when the waypoints of the file change: refetch their coordinates. */
|
/** Changes when the waypoints of the file change: refetch their coordinates. */
|
||||||
@@ -146,14 +151,22 @@ export interface GlobalStatistics {
|
|||||||
/** Absent when there are no trackpoints. */
|
/** Absent when there are no trackpoints. */
|
||||||
bounds?: { west: number; south: number; east: number; north: number };
|
bounds?: { west: number; south: number; east: number; north: number };
|
||||||
}
|
}
|
||||||
export interface TrackNode {
|
/** The name, description and style of a route or a track. */
|
||||||
id: string;
|
export interface PathInfo {
|
||||||
name?: string;
|
name?: string;
|
||||||
desc?: string;
|
desc?: string;
|
||||||
/** Style of the track, only present when the file defines it. */
|
/** Style, only present when the file defines it. */
|
||||||
color?: string;
|
color?: string;
|
||||||
opacity?: number;
|
opacity?: number;
|
||||||
width?: number;
|
width?: number;
|
||||||
|
}
|
||||||
|
/** A route: like a track, with a single segment. */
|
||||||
|
export interface RouteNode extends PathInfo {
|
||||||
|
id: string;
|
||||||
|
segment: SegmentNode;
|
||||||
|
}
|
||||||
|
export interface TrackNode extends PathInfo {
|
||||||
|
id: string;
|
||||||
segments: SegmentNode[];
|
segments: SegmentNode[];
|
||||||
}
|
}
|
||||||
export interface SegmentNode {
|
export interface SegmentNode {
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ pub enum MergeType {
|
|||||||
#[derive(Clone, Copy)]
|
#[derive(Clone, Copy)]
|
||||||
pub enum SplitType {
|
pub enum SplitType {
|
||||||
Files,
|
Files,
|
||||||
|
Routes,
|
||||||
Tracks,
|
Tracks,
|
||||||
Segments,
|
Segments,
|
||||||
}
|
}
|
||||||
@@ -23,6 +24,7 @@ impl From<SplitType> for engine::SplitType {
|
|||||||
fn from(t: SplitType) -> Self {
|
fn from(t: SplitType) -> Self {
|
||||||
match t {
|
match t {
|
||||||
SplitType::Files => Self::Files,
|
SplitType::Files => Self::Files,
|
||||||
|
SplitType::Routes => Self::Routes,
|
||||||
SplitType::Tracks => Self::Tracks,
|
SplitType::Tracks => Self::Tracks,
|
||||||
SplitType::Segments => Self::Segments,
|
SplitType::Segments => Self::Segments,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +0,0 @@
|
|||||||
.DS_Store
|
|
||||||
node_modules
|
|
||||||
/build
|
|
||||||
/.svelte-kit
|
|
||||||
/package
|
|
||||||
.env
|
|
||||||
.env.*
|
|
||||||
!.env.example
|
|
||||||
|
|
||||||
# Ignore files for PNPM, NPM and YARN
|
|
||||||
pnpm-lock.yaml
|
|
||||||
package-lock.json
|
|
||||||
yarn.lock
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
/** @type { import("eslint").Linter.Config } */
|
|
||||||
module.exports = {
|
|
||||||
root: true,
|
|
||||||
extends: [
|
|
||||||
'eslint:recommended',
|
|
||||||
'plugin:@typescript-eslint/recommended',
|
|
||||||
'plugin:svelte/recommended',
|
|
||||||
'prettier',
|
|
||||||
],
|
|
||||||
parser: '@typescript-eslint/parser',
|
|
||||||
plugins: ['@typescript-eslint'],
|
|
||||||
parserOptions: {
|
|
||||||
sourceType: 'module',
|
|
||||||
ecmaVersion: 2020,
|
|
||||||
extraFileExtensions: ['.svelte'],
|
|
||||||
},
|
|
||||||
env: {
|
|
||||||
browser: true,
|
|
||||||
es2017: true,
|
|
||||||
node: true,
|
|
||||||
},
|
|
||||||
overrides: [
|
|
||||||
{
|
|
||||||
files: ['*.svelte'],
|
|
||||||
parser: 'svelte-eslint-parser',
|
|
||||||
parserOptions: {
|
|
||||||
parser: '@typescript-eslint/parser',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import js from '@eslint/js';
|
||||||
|
import ts from '@typescript-eslint/eslint-plugin';
|
||||||
|
import tsParser from '@typescript-eslint/parser';
|
||||||
|
import svelte from 'eslint-plugin-svelte';
|
||||||
|
import prettier from 'eslint-config-prettier';
|
||||||
|
import globals from 'globals';
|
||||||
|
|
||||||
|
/** @type {import('eslint').Linter.Config[]} */
|
||||||
|
export default [
|
||||||
|
{
|
||||||
|
ignores: ['build/', '.svelte-kit/', 'package/'],
|
||||||
|
},
|
||||||
|
js.configs.recommended,
|
||||||
|
...ts.configs['flat/recommended'],
|
||||||
|
...svelte.configs['flat/recommended'],
|
||||||
|
prettier,
|
||||||
|
...svelte.configs['flat/prettier'],
|
||||||
|
{
|
||||||
|
languageOptions: {
|
||||||
|
globals: { ...globals.browser, ...globals.node },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
rules: {
|
||||||
|
// TypeScript already reports undefined names
|
||||||
|
'no-undef': 'off',
|
||||||
|
'no-empty': ['error', { allowEmptyCatch: true }],
|
||||||
|
'@typescript-eslint/no-unused-vars': [
|
||||||
|
'error',
|
||||||
|
{ argsIgnorePattern: '^_', varsIgnorePattern: '^_' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
files: ['**/*.svelte', '**/*.svelte.ts', '**/*.svelte.js'],
|
||||||
|
languageOptions: {
|
||||||
|
parserOptions: {
|
||||||
|
parser: tsParser,
|
||||||
|
extraFileExtensions: ['.svelte'],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
rules: {
|
||||||
|
// $effect dependencies are tracked by reading them
|
||||||
|
'@typescript-eslint/no-unused-expressions': 'off',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
Generated
+32
-2
@@ -20,7 +20,7 @@
|
|||||||
"mapillary-js": "^4.1.2",
|
"mapillary-js": "^4.1.2",
|
||||||
"maplibre-gl": "^6.15.0",
|
"maplibre-gl": "^6.15.0",
|
||||||
"sanitize-html": "^2.17.0",
|
"sanitize-html": "^2.17.0",
|
||||||
"sortablejs": "^1.15.6"
|
"sortablejs": "^1.15.7"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@fontsource-variable/inter": "^5.2.8",
|
"@fontsource-variable/inter": "^5.2.8",
|
||||||
@@ -39,11 +39,12 @@
|
|||||||
"@types/mapbox__tilebelt": "^1.0.4",
|
"@types/mapbox__tilebelt": "^1.0.4",
|
||||||
"@types/node": "^22.15.30",
|
"@types/node": "^22.15.30",
|
||||||
"@types/sanitize-html": "^2.16.0",
|
"@types/sanitize-html": "^2.16.0",
|
||||||
"@types/sortablejs": "^1.15.8",
|
"@types/sortablejs": "^1.15.9",
|
||||||
"@typescript-eslint/eslint-plugin": "^8.33.1",
|
"@typescript-eslint/eslint-plugin": "^8.33.1",
|
||||||
"@typescript-eslint/parser": "^8.33.1",
|
"@typescript-eslint/parser": "^8.33.1",
|
||||||
"bits-ui": "^2.17.2",
|
"bits-ui": "^2.17.2",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
|
"cross-env": "^10.1.0",
|
||||||
"eslint": "^9.28.0",
|
"eslint": "^9.28.0",
|
||||||
"eslint-config-prettier": "^10.1.5",
|
"eslint-config-prettier": "^10.1.5",
|
||||||
"eslint-plugin-svelte": "^3.9.1",
|
"eslint-plugin-svelte": "^3.9.1",
|
||||||
@@ -354,6 +355,13 @@
|
|||||||
"tslib": "^2.4.0"
|
"tslib": "^2.4.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@epic-web/invariant": {
|
||||||
|
"version": "1.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@epic-web/invariant/-/invariant-1.0.0.tgz",
|
||||||
|
"integrity": "sha512-lrTPqgvfFQtR/eY/qkIzp98OGdNJu0m5ji3q/nJI8v3SXkRKEnWiOxMmbvcSoAIzv/cGiuvRy57k4suKQSAdwA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/@esbuild/aix-ppc64": {
|
"node_modules/@esbuild/aix-ppc64": {
|
||||||
"version": "0.27.7",
|
"version": "0.27.7",
|
||||||
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.7.tgz",
|
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.7.tgz",
|
||||||
@@ -2762,6 +2770,8 @@
|
|||||||
},
|
},
|
||||||
"node_modules/@types/sortablejs": {
|
"node_modules/@types/sortablejs": {
|
||||||
"version": "1.15.9",
|
"version": "1.15.9",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/sortablejs/-/sortablejs-1.15.9.tgz",
|
||||||
|
"integrity": "sha512-7HP+rZGE2p886PKV9c9OJzLBI6BBJu1O7lJGYnPyG3fS4/duUCcngkNCjsLwIMV+WMqANe3tt4irrXHSIe68OQ==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
@@ -3273,6 +3283,24 @@
|
|||||||
"version": "1.0.3",
|
"version": "1.0.3",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/cross-env": {
|
||||||
|
"version": "10.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/cross-env/-/cross-env-10.1.0.tgz",
|
||||||
|
"integrity": "sha512-GsYosgnACZTADcmEyJctkJIoqAhHjttw7RsFrVoJNXbsWWqaq6Ym+7kZjq6mS45O0jij6vtiReppKQEtqWy6Dw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@epic-web/invariant": "^1.0.0",
|
||||||
|
"cross-spawn": "^7.0.6"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"cross-env": "dist/bin/cross-env.js",
|
||||||
|
"cross-env-shell": "dist/bin/cross-env-shell.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/cross-spawn": {
|
"node_modules/cross-spawn": {
|
||||||
"version": "7.0.6",
|
"version": "7.0.6",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
@@ -5599,6 +5627,8 @@
|
|||||||
},
|
},
|
||||||
"node_modules/sortablejs": {
|
"node_modules/sortablejs": {
|
||||||
"version": "1.15.7",
|
"version": "1.15.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/sortablejs/-/sortablejs-1.15.7.tgz",
|
||||||
|
"integrity": "sha512-Kk8wLQPlS+yi1ZEf48a4+fzHa4yxjC30M/Sr2AnQu+f/MPwvvX9XjZ6OWejiz8crBsLwSq8GHqaxaET7u6ux0A==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/source-map-js": {
|
"node_modules/source-map-js": {
|
||||||
|
|||||||
@@ -5,11 +5,12 @@
|
|||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite dev",
|
"dev": "vite dev",
|
||||||
"build": "vite build",
|
"build": "vite build",
|
||||||
"build:desktop": "BUILD_TARGET=desktop BASE_PATH='' vite build",
|
"build:desktop": "cross-env BUILD_TARGET=desktop BASE_PATH= vite build",
|
||||||
"prebuild": "npx tsx src/lib/scripts/pwa-manifest.ts",
|
"prebuild": "npx tsx src/lib/scripts/pwa-manifest.ts",
|
||||||
"postbuild": "npx tsx src/lib/scripts/sitemap.ts",
|
"postbuild": "npx tsx src/lib/scripts/sitemap.ts",
|
||||||
"preview": "vite preview",
|
"preview": "vite preview",
|
||||||
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
|
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
|
||||||
|
"pretest": "svelte-kit sync",
|
||||||
"test": "node --import tsx --import ./src/test/register.mjs --experimental-wasm-modules --disable-warning=ExperimentalWarning --test \"src/**/*.test.ts\"",
|
"test": "node --import tsx --import ./src/test/register.mjs --experimental-wasm-modules --disable-warning=ExperimentalWarning --test \"src/**/*.test.ts\"",
|
||||||
"generate:example": "node --import tsx src/lib/scripts/example-statistics.ts",
|
"generate:example": "node --import tsx src/lib/scripts/example-statistics.ts",
|
||||||
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
|
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
|
||||||
@@ -33,11 +34,12 @@
|
|||||||
"@types/mapbox__tilebelt": "^1.0.4",
|
"@types/mapbox__tilebelt": "^1.0.4",
|
||||||
"@types/node": "^22.15.30",
|
"@types/node": "^22.15.30",
|
||||||
"@types/sanitize-html": "^2.16.0",
|
"@types/sanitize-html": "^2.16.0",
|
||||||
"@types/sortablejs": "^1.15.8",
|
"@types/sortablejs": "^1.15.9",
|
||||||
"@typescript-eslint/eslint-plugin": "^8.33.1",
|
"@typescript-eslint/eslint-plugin": "^8.33.1",
|
||||||
"@typescript-eslint/parser": "^8.33.1",
|
"@typescript-eslint/parser": "^8.33.1",
|
||||||
"bits-ui": "^2.17.2",
|
"bits-ui": "^2.17.2",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
|
"cross-env": "^10.1.0",
|
||||||
"eslint": "^9.28.0",
|
"eslint": "^9.28.0",
|
||||||
"eslint-config-prettier": "^10.1.5",
|
"eslint-config-prettier": "^10.1.5",
|
||||||
"eslint-plugin-svelte": "^3.9.1",
|
"eslint-plugin-svelte": "^3.9.1",
|
||||||
@@ -80,6 +82,6 @@
|
|||||||
"mapillary-js": "^4.1.2",
|
"mapillary-js": "^4.1.2",
|
||||||
"maplibre-gl": "^6.15.0",
|
"maplibre-gl": "^6.15.0",
|
||||||
"sanitize-html": "^2.17.0",
|
"sanitize-html": "^2.17.0",
|
||||||
"sortablejs": "^1.15.6"
|
"sortablejs": "^1.15.7"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+2
-2
@@ -1,7 +1,7 @@
|
|||||||
@import 'tailwindcss';
|
@import 'tailwindcss';
|
||||||
@import 'tw-animate-css';
|
@import 'tw-animate-css';
|
||||||
@import "shadcn-svelte/tailwind.css";
|
@import 'shadcn-svelte/tailwind.css';
|
||||||
@import "@fontsource-variable/inter";
|
@import '@fontsource-variable/inter';
|
||||||
|
|
||||||
@custom-variant dark (&:is(.dark *));
|
@custom-variant dark (&:is(.dark *));
|
||||||
|
|
||||||
|
|||||||
Vendored
+5
@@ -8,6 +8,11 @@ declare global {
|
|||||||
// interface PageState {}
|
// interface PageState {}
|
||||||
// interface Platform {}
|
// interface Platform {}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface Window {
|
||||||
|
/** The map, for extensions (set once it has loaded). */
|
||||||
|
_map?: import('maplibre-gl').Map;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export {};
|
export {};
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { base } from '$app/paths';
|
import { asset, resolve as resolvePath } from '$app/paths';
|
||||||
import { languages } from '$lib/i18n/languages';
|
import { languages } from '$lib/i18n/languages';
|
||||||
import { getURLForLanguage } from '$lib/utils';
|
import { getURLForLanguage } from '$lib/utils';
|
||||||
|
|
||||||
@@ -37,16 +37,16 @@ export async function handle({ event, resolve }) {
|
|||||||
<meta property="og:description" content="${description}" />
|
<meta property="og:description" content="${description}" />
|
||||||
<meta name="twitter:title" content="gpx.studio — ${title}" />
|
<meta name="twitter:title" content="gpx.studio — ${title}" />
|
||||||
<meta name="twitter:description" content="${description}" />
|
<meta name="twitter:description" content="${description}" />
|
||||||
<meta property="og:image" content="https://gpx.studio${base}/og_logo.png" />
|
<meta property="og:image" content="https://gpx.studio${asset('/og_logo.png')}" />
|
||||||
<meta property="og:url" content="https://gpx.studio/" />
|
<meta property="og:url" content="https://gpx.studio/" />
|
||||||
<meta property="og:type" content="website" />
|
<meta property="og:type" content="website" />
|
||||||
<meta property="og:site_name" content="gpx.studio" />
|
<meta property="og:site_name" content="gpx.studio" />
|
||||||
<meta name="twitter:card" content="summary_large_image" />
|
<meta name="twitter:card" content="summary_large_image" />
|
||||||
<meta name="twitter:image" content="https://gpx.studio${base}/og_logo.png" />
|
<meta name="twitter:image" content="https://gpx.studio${asset('/og_logo.png')}" />
|
||||||
<meta name="twitter:url" content="https://gpx.studio/" />
|
<meta name="twitter:url" content="https://gpx.studio/" />
|
||||||
<meta name="twitter:site" content="@gpxstudio" />
|
<meta name="twitter:site" content="@gpxstudio" />
|
||||||
<meta name="twitter:creator" content="@gpxstudio" />
|
<meta name="twitter:creator" content="@gpxstudio" />
|
||||||
<link rel="alternate" hreflang="x-default" href="https://gpx.studio${getURLForLanguage('en', path)}" />`;
|
<link rel="alternate" hreflang="x-default" href="https://gpx.studio${resolvePath(getURLForLanguage('en', path))}" />`;
|
||||||
|
|
||||||
// the manifests are made for the website, not for the desktop app (`npm run build:desktop`)
|
// the manifests are made for the website, not for the desktop app (`npm run build:desktop`)
|
||||||
if (process.env.BUILD_TARGET !== 'desktop') {
|
if (process.env.BUILD_TARGET !== 'desktop') {
|
||||||
@@ -56,7 +56,7 @@ export async function handle({ event, resolve }) {
|
|||||||
|
|
||||||
if (page !== '404') {
|
if (page !== '404') {
|
||||||
for (let lang of Object.keys(languages)) {
|
for (let lang of Object.keys(languages)) {
|
||||||
headTag += ` <link rel="alternate" hreflang="${lang}" href="https://gpx.studio${getURLForLanguage(lang, path)}" />
|
headTag += ` <link rel="alternate" hreflang="${lang}" href="https://gpx.studio${resolvePath(getURLForLanguage(lang, path))}" />
|
||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,6 +20,12 @@ export function createFile() {
|
|||||||
currentTool.set(Tool.ROUTING);
|
currentTool.set(Tool.ROUTING);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Creates a file that starts with an empty route, which the routing tool then draws. */
|
||||||
|
export function createRouteFile() {
|
||||||
|
engine.newFile(newFileName(), undefined, true);
|
||||||
|
currentTool.set(Tool.ROUTING);
|
||||||
|
}
|
||||||
|
|
||||||
/** Asks for the files to open: with the file picker of the system in the desktop app. */
|
/** Asks for the files to open: with the file picker of the system in the desktop app. */
|
||||||
export async function openFiles() {
|
export async function openFiles() {
|
||||||
if (get(engine.workspace)) {
|
if (get(engine.workspace)) {
|
||||||
|
|||||||
@@ -60,7 +60,7 @@
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<svelte:head>
|
<svelte:head>
|
||||||
<link rel="preconnect" href="https://21XLD94PE3-dsn.algolia.net" crossorigin />
|
<link rel="preconnect" href="https://21XLD94PE3-dsn.algolia.net" crossorigin="anonymous" />
|
||||||
</svelte:head>
|
</svelte:head>
|
||||||
|
|
||||||
<div id="docsearch" class={props.class ?? ''}></div>
|
<div id="docsearch" class={props.class ?? ''}></div>
|
||||||
|
|||||||
@@ -26,7 +26,7 @@
|
|||||||
<Tooltip.Root>
|
<Tooltip.Root>
|
||||||
<Tooltip.Trigger>
|
<Tooltip.Trigger>
|
||||||
{#snippet child({ props })}
|
{#snippet child({ props })}
|
||||||
<Button {...props} {variant} class="bg-inherit {className}" {onclick}>
|
<Button {...props} {variant} {disabled} class="bg-inherit {className}" {onclick}>
|
||||||
{@render children()}
|
{@render children()}
|
||||||
</Button>
|
</Button>
|
||||||
{/snippet}
|
{/snippet}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
|
import { resolve } from '$app/paths';
|
||||||
import { Button } from '$lib/components/ui/button';
|
import { Button } from '$lib/components/ui/button';
|
||||||
import LanguageSelect from '$lib/components/LanguageSelect.svelte';
|
import LanguageSelect from '$lib/components/LanguageSelect.svelte';
|
||||||
import ModeSwitch from '$lib/components/ModeSwitch.svelte';
|
import ModeSwitch from '$lib/components/ModeSwitch.svelte';
|
||||||
@@ -31,7 +32,7 @@
|
|||||||
<Button
|
<Button
|
||||||
variant="link"
|
variant="link"
|
||||||
class="h-6 px-0 has-[>svg]:px-0 text-muted-foreground"
|
class="h-6 px-0 has-[>svg]:px-0 text-muted-foreground"
|
||||||
href={getURLForLanguage(i18n.lang, '/')}
|
href={resolve(getURLForLanguage(i18n.lang, '/'))}
|
||||||
>
|
>
|
||||||
<House size="16" />
|
<House size="16" />
|
||||||
{i18n._('homepage.home')}
|
{i18n._('homepage.home')}
|
||||||
@@ -40,7 +41,7 @@
|
|||||||
data-sveltekit-reload
|
data-sveltekit-reload
|
||||||
variant="link"
|
variant="link"
|
||||||
class="h-6 px-0 has-[>svg]:px-0 text-muted-foreground"
|
class="h-6 px-0 has-[>svg]:px-0 text-muted-foreground"
|
||||||
href={getURLForLanguage(i18n.lang, '/app')}
|
href={resolve(getURLForLanguage(i18n.lang, '/app'))}
|
||||||
>
|
>
|
||||||
<Map size="16" />
|
<Map size="16" />
|
||||||
{i18n._('homepage.app')}
|
{i18n._('homepage.app')}
|
||||||
@@ -48,7 +49,7 @@
|
|||||||
<Button
|
<Button
|
||||||
variant="link"
|
variant="link"
|
||||||
class="h-6 px-0 has-[>svg]:px-0 text-muted-foreground"
|
class="h-6 px-0 has-[>svg]:px-0 text-muted-foreground"
|
||||||
href={getURLForLanguage(i18n.lang, '/help')}
|
href={resolve(getURLForLanguage(i18n.lang, '/help'))}
|
||||||
>
|
>
|
||||||
<BookOpenText size="16" />
|
<BookOpenText size="16" />
|
||||||
{i18n._('menu.help')}
|
{i18n._('menu.help')}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
import { CircleQuestionMark } from '@lucide/svelte';
|
import { CircleQuestionMark } from '@lucide/svelte';
|
||||||
import { i18n } from '$lib/i18n/i18n.svelte';
|
import { i18n } from '$lib/i18n/i18n.svelte';
|
||||||
import type { Snippet } from 'svelte';
|
import type { Snippet } from 'svelte';
|
||||||
|
import { resolve } from '$app/paths';
|
||||||
|
|
||||||
let {
|
let {
|
||||||
link,
|
link,
|
||||||
@@ -19,7 +20,7 @@
|
|||||||
<div>
|
<div>
|
||||||
{@render children()}
|
{@render children()}
|
||||||
{#if link}
|
{#if link}
|
||||||
<a href={link} target="_blank" class="text-[13px] text-link hover:underline">
|
<a href={resolve(link)} target="_blank" class="text-[13px] text-link hover:underline">
|
||||||
{i18n._('menu.more')}
|
{i18n._('menu.more')}
|
||||||
</a>
|
</a>
|
||||||
{/if}
|
{/if}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
|
import { resolve } from '$app/paths';
|
||||||
import { page } from '$app/state';
|
import { page } from '$app/state';
|
||||||
import * as Select from '$lib/components/ui/select';
|
import * as Select from '$lib/components/ui/select';
|
||||||
import { languages } from '$lib/i18n/languages';
|
import { languages } from '$lib/i18n/languages';
|
||||||
@@ -15,13 +16,13 @@
|
|||||||
</span>
|
</span>
|
||||||
</Select.Trigger>
|
</Select.Trigger>
|
||||||
<Select.Content>
|
<Select.Content>
|
||||||
{#each Object.entries(languages) as [lang, label]}
|
{#each Object.entries(languages) as [lang, label] (lang)}
|
||||||
{#if page.url.pathname.includes('404')}
|
{#if page.url.pathname.includes('404')}
|
||||||
<a href={getURLForLanguage(lang, '/')}>
|
<a href={resolve(getURLForLanguage(lang, '/'))}>
|
||||||
<Select.Item value={lang}>{label}</Select.Item>
|
<Select.Item value={lang}>{label}</Select.Item>
|
||||||
</a>
|
</a>
|
||||||
{:else}
|
{:else}
|
||||||
<a href={getURLForLanguage(lang, page.url.pathname)}>
|
<a href={resolve(getURLForLanguage(lang, page.url.pathname))}>
|
||||||
<Select.Item value={lang}>{label}</Select.Item>
|
<Select.Item value={lang}>{label}</Select.Item>
|
||||||
</a>
|
</a>
|
||||||
{/if}
|
{/if}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { mode } from 'mode-watcher';
|
import { mode } from 'mode-watcher';
|
||||||
import { base } from '$app/paths';
|
import { asset } from '$app/paths';
|
||||||
|
|
||||||
let {
|
let {
|
||||||
iconOnly = false,
|
iconOnly = false,
|
||||||
@@ -9,13 +9,13 @@
|
|||||||
}: {
|
}: {
|
||||||
iconOnly?: boolean;
|
iconOnly?: boolean;
|
||||||
company?: 'gpx.studio' | 'github' | 'crowdin' | 'facebook' | 'reddit';
|
company?: 'gpx.studio' | 'github' | 'crowdin' | 'facebook' | 'reddit';
|
||||||
[key: string]: any;
|
[key: string]: unknown;
|
||||||
} = $props();
|
} = $props();
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
{#if company === 'gpx.studio'}
|
{#if company === 'gpx.studio'}
|
||||||
<img
|
<img
|
||||||
src="{base}/{iconOnly ? 'icon' : 'logo'}{mode.current === 'dark' ? '-dark' : ''}.svg"
|
src={asset(`/${iconOnly ? 'icon' : 'logo'}${mode.current === 'dark' ? '-dark' : ''}.svg`)}
|
||||||
alt="Logo of gpx.studio."
|
alt="Logo of gpx.studio."
|
||||||
{...others}
|
{...others}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
|
import { resolve } from '$app/paths';
|
||||||
import * as Menubar from '$lib/components/ui/menubar/index.js';
|
import * as Menubar from '$lib/components/ui/menubar/index.js';
|
||||||
import { Button } from '$lib/components/ui/button';
|
import { Button } from '$lib/components/ui/button';
|
||||||
import Logo from '$lib/components/Logo.svelte';
|
import Logo from '$lib/components/Logo.svelte';
|
||||||
@@ -48,6 +49,7 @@
|
|||||||
Maximize2,
|
Maximize2,
|
||||||
Minimize2,
|
Minimize2,
|
||||||
FolderX,
|
FolderX,
|
||||||
|
ArrowRightLeft,
|
||||||
} from '@lucide/svelte';
|
} from '@lucide/svelte';
|
||||||
import { map } from '$lib/components/map/map';
|
import { map } from '$lib/components/map/map';
|
||||||
import { editMetadata } from '$lib/components/file-list/metadata/utils.svelte';
|
import { editMetadata } from '$lib/components/file-list/metadata/utils.svelte';
|
||||||
@@ -67,6 +69,7 @@
|
|||||||
closeFiles,
|
closeFiles,
|
||||||
closeFolder,
|
closeFolder,
|
||||||
createFile,
|
createFile,
|
||||||
|
createRouteFile,
|
||||||
loadFiles,
|
loadFiles,
|
||||||
openFiles,
|
openFiles,
|
||||||
openFolder,
|
openFolder,
|
||||||
@@ -76,7 +79,7 @@
|
|||||||
} from '$lib/actions/file-actions';
|
} from '$lib/actions/file-actions';
|
||||||
import UnsavedDialog from '$lib/components/file-list/UnsavedDialog.svelte';
|
import UnsavedDialog from '$lib/components/file-list/UnsavedDialog.svelte';
|
||||||
import { engine } from '$lib/engine';
|
import { engine } from '$lib/engine';
|
||||||
import { allHidden } from '$lib/engine/all-hidden';
|
import { allHidden, selectedFilesConversion } from '$lib/engine/selection-stores';
|
||||||
import { selectedFileIds, selectionSize } from '$lib/engine/selection-helpers';
|
import { selectedFileIds, selectionSize } from '$lib/engine/selection-helpers';
|
||||||
import { boundsManager } from '$lib/state/bounds';
|
import { boundsManager } from '$lib/state/bounds';
|
||||||
import { onMount } from 'svelte';
|
import { onMount } from 'svelte';
|
||||||
@@ -105,8 +108,10 @@
|
|||||||
let desktop = $derived($workspace !== undefined);
|
let desktop = $derived($workspace !== undefined);
|
||||||
let selectedIds = $derived(selectedFileIds($selection));
|
let selectedIds = $derived(selectedFileIds($selection));
|
||||||
let anyUnsaved = $derived(Object.values($workspace?.files ?? {}).some((file) => file.dirty));
|
let anyUnsaved = $derived(Object.values($workspace?.files ?? {}).some((file) => file.dirty));
|
||||||
// metadata and style can be edited for files and tracks only
|
// metadata and style can be edited for files, routes and tracks only
|
||||||
let filesOrTracksSelected = $derived($selection.type === 'file' || $selection.type === 'track');
|
let filesOrTracksSelected = $derived(
|
||||||
|
$selection.type === 'file' || $selection.type === 'route' || $selection.type === 'track'
|
||||||
|
);
|
||||||
|
|
||||||
function switchBasemaps() {
|
function switchBasemaps() {
|
||||||
[$currentBasemap, $previousBasemap] = [$previousBasemap, $currentBasemap];
|
[$currentBasemap, $previousBasemap] = [$previousBasemap, $currentBasemap];
|
||||||
@@ -144,7 +149,7 @@
|
|||||||
<div
|
<div
|
||||||
class="w-fit flex flex-row items-center justify-center p-1 bg-background rounded-b-md md:rounded-md pointer-events-auto shadow-md"
|
class="w-fit flex flex-row items-center justify-center p-1 bg-background rounded-b-md md:rounded-md pointer-events-auto shadow-md"
|
||||||
>
|
>
|
||||||
<a href={getURLForLanguage(i18n.lang, '/')} target="_blank" class="shrink-0">
|
<a href={resolve(getURLForLanguage(i18n.lang, '/'))} target="_blank" class="shrink-0">
|
||||||
<Logo class="h-5 mt-0.5 mx-2 md:hidden" iconOnly={true} width="16" />
|
<Logo class="h-5 mt-0.5 mx-2 md:hidden" iconOnly={true} width="16" />
|
||||||
<Logo class="h-5 mt-0.5 mx-2 hidden md:block" width="96" />
|
<Logo class="h-5 mt-0.5 mx-2 hidden md:block" width="96" />
|
||||||
</a>
|
</a>
|
||||||
@@ -157,9 +162,13 @@
|
|||||||
<Menubar.Content class="border-none">
|
<Menubar.Content class="border-none">
|
||||||
<Menubar.Item onclick={createFile}>
|
<Menubar.Item onclick={createFile}>
|
||||||
<Plus size="16" />
|
<Plus size="16" />
|
||||||
{i18n._('menu.new')}
|
{i18n._('menu.new_file')}
|
||||||
<Shortcut key="+" ctrl={true} />
|
<Shortcut key="+" ctrl={true} />
|
||||||
</Menubar.Item>
|
</Menubar.Item>
|
||||||
|
<Menubar.Item onclick={createRouteFile}>
|
||||||
|
<Plus size="16" />
|
||||||
|
{i18n._('menu.new_route_file')}
|
||||||
|
</Menubar.Item>
|
||||||
<Menubar.Separator />
|
<Menubar.Separator />
|
||||||
<Menubar.Item onclick={openFiles}>
|
<Menubar.Item onclick={openFiles}>
|
||||||
<FolderOpen size="16" />
|
<FolderOpen size="16" />
|
||||||
@@ -285,19 +294,6 @@
|
|||||||
<PaintBucket size="16" />
|
<PaintBucket size="16" />
|
||||||
{i18n._('menu.style.button')}
|
{i18n._('menu.style.button')}
|
||||||
</Menubar.Item>
|
</Menubar.Item>
|
||||||
<Menubar.Item
|
|
||||||
onclick={() => engine.setSelectionHidden(!$allHidden)}
|
|
||||||
disabled={selectionCount == 0}
|
|
||||||
>
|
|
||||||
{#if $allHidden}
|
|
||||||
<Eye size="16" />
|
|
||||||
{i18n._('menu.unhide')}
|
|
||||||
{:else}
|
|
||||||
<EyeOff size="16" />
|
|
||||||
{i18n._('menu.hide')}
|
|
||||||
{/if}
|
|
||||||
<Shortcut key="H" ctrl={true} />
|
|
||||||
</Menubar.Item>
|
|
||||||
{#if $treeFileView}
|
{#if $treeFileView}
|
||||||
{#if $selection.type === 'file'}
|
{#if $selection.type === 'file'}
|
||||||
<Menubar.Separator />
|
<Menubar.Separator />
|
||||||
@@ -308,6 +304,13 @@
|
|||||||
<Plus size="16" />
|
<Plus size="16" />
|
||||||
{i18n._('menu.new_track')}
|
{i18n._('menu.new_track')}
|
||||||
</Menubar.Item>
|
</Menubar.Item>
|
||||||
|
<Menubar.Item
|
||||||
|
onclick={() => engine.newRoute()}
|
||||||
|
disabled={selectionCount !== 1}
|
||||||
|
>
|
||||||
|
<Plus size="16" />
|
||||||
|
{i18n._('menu.new_route')}
|
||||||
|
</Menubar.Item>
|
||||||
{:else if $selection.type === 'track'}
|
{:else if $selection.type === 'track'}
|
||||||
<Menubar.Separator />
|
<Menubar.Separator />
|
||||||
<Menubar.Item
|
<Menubar.Item
|
||||||
@@ -318,6 +321,32 @@
|
|||||||
{i18n._('menu.new_segment')}
|
{i18n._('menu.new_segment')}
|
||||||
</Menubar.Item>
|
</Menubar.Item>
|
||||||
{/if}
|
{/if}
|
||||||
|
{#if $selection.type === 'route' || $selection.type === 'track' || $selection.type === 'segment'}
|
||||||
|
{#if $selection.type !== 'track'}
|
||||||
|
<Menubar.Separator />
|
||||||
|
{/if}
|
||||||
|
<Menubar.Item onclick={() => engine.convert()}>
|
||||||
|
<ArrowRightLeft size="16" />
|
||||||
|
{i18n._(
|
||||||
|
$selection.type === 'route'
|
||||||
|
? 'menu.convert_to_track'
|
||||||
|
: 'menu.convert_to_route'
|
||||||
|
)}
|
||||||
|
</Menubar.Item>
|
||||||
|
{/if}
|
||||||
|
{/if}
|
||||||
|
{#if $selectedFilesConversion}
|
||||||
|
{#if !$treeFileView}
|
||||||
|
<Menubar.Separator />
|
||||||
|
{/if}
|
||||||
|
<Menubar.Item onclick={() => engine.convert()}>
|
||||||
|
<ArrowRightLeft size="16" />
|
||||||
|
{i18n._(
|
||||||
|
$selectedFilesConversion === 'route'
|
||||||
|
? 'menu.convert_to_routes'
|
||||||
|
: 'menu.convert_to_tracks'
|
||||||
|
)}
|
||||||
|
</Menubar.Item>
|
||||||
{/if}
|
{/if}
|
||||||
<Menubar.Separator />
|
<Menubar.Separator />
|
||||||
<Menubar.Item onclick={() => engine.selectAll()} disabled={noFiles}>
|
<Menubar.Item onclick={() => engine.selectAll()} disabled={noFiles}>
|
||||||
@@ -325,18 +354,6 @@
|
|||||||
{i18n._('menu.select_all')}
|
{i18n._('menu.select_all')}
|
||||||
<Shortcut key="A" ctrl={true} />
|
<Shortcut key="A" ctrl={true} />
|
||||||
</Menubar.Item>
|
</Menubar.Item>
|
||||||
<Menubar.Item
|
|
||||||
onclick={() => {
|
|
||||||
if (selectionCount > 0) {
|
|
||||||
boundsManager.centerMapOnSelection();
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
disabled={selectionCount == 0}
|
|
||||||
>
|
|
||||||
<Maximize size="16" />
|
|
||||||
{i18n._('menu.center')}
|
|
||||||
<Shortcut key="⏎" ctrl={true} />
|
|
||||||
</Menubar.Item>
|
|
||||||
{#if $treeFileView}
|
{#if $treeFileView}
|
||||||
<Menubar.Separator />
|
<Menubar.Separator />
|
||||||
<Menubar.Item onclick={() => engine.copy()} disabled={selectionCount === 0}>
|
<Menubar.Item onclick={() => engine.copy()} disabled={selectionCount === 0}>
|
||||||
@@ -401,6 +418,34 @@
|
|||||||
/>
|
/>
|
||||||
</Menubar.CheckboxItem>
|
</Menubar.CheckboxItem>
|
||||||
<Menubar.Separator />
|
<Menubar.Separator />
|
||||||
|
<Menubar.Item
|
||||||
|
inset
|
||||||
|
onclick={() => engine.setSelectionHidden(!$allHidden)}
|
||||||
|
disabled={selectionCount == 0}
|
||||||
|
>
|
||||||
|
{#if $allHidden}
|
||||||
|
<Eye size="16" />
|
||||||
|
{i18n._('menu.unhide')}
|
||||||
|
{:else}
|
||||||
|
<EyeOff size="16" />
|
||||||
|
{i18n._('menu.hide')}
|
||||||
|
{/if}
|
||||||
|
<Shortcut key="H" ctrl={true} />
|
||||||
|
</Menubar.Item>
|
||||||
|
<Menubar.Item
|
||||||
|
inset
|
||||||
|
onclick={() => {
|
||||||
|
if (selectionCount > 0) {
|
||||||
|
boundsManager.centerMapOnSelection();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
disabled={selectionCount == 0}
|
||||||
|
>
|
||||||
|
<Maximize size="16" />
|
||||||
|
{i18n._('menu.center')}
|
||||||
|
<Shortcut key="⏎" ctrl={true} />
|
||||||
|
</Menubar.Item>
|
||||||
|
<Menubar.Separator />
|
||||||
<Menubar.Item inset onclick={() => map.toggle3D()}>
|
<Menubar.Item inset onclick={() => map.toggle3D()}>
|
||||||
<Box size="16" />
|
<Box size="16" />
|
||||||
{i18n._('menu.toggle_3d')}
|
{i18n._('menu.toggle_3d')}
|
||||||
@@ -482,8 +527,8 @@
|
|||||||
</Menubar.SubTrigger>
|
</Menubar.SubTrigger>
|
||||||
<Menubar.SubContent>
|
<Menubar.SubContent>
|
||||||
<Menubar.RadioGroup value={i18n.lang}>
|
<Menubar.RadioGroup value={i18n.lang}>
|
||||||
{#each Object.entries(languages) as [lang, label]}
|
{#each Object.entries(languages) as [lang, label] (lang)}
|
||||||
<a href={getURLForLanguage(lang, '/app')}>
|
<a href={resolve(getURLForLanguage(lang, '/app'))}>
|
||||||
<Menubar.RadioItem value={lang}>{label}</Menubar.RadioItem>
|
<Menubar.RadioItem value={lang}>{label}</Menubar.RadioItem>
|
||||||
</a>
|
</a>
|
||||||
{/each}
|
{/each}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
|
import { resolve } from '$app/paths';
|
||||||
import Logo from '$lib/components/Logo.svelte';
|
import Logo from '$lib/components/Logo.svelte';
|
||||||
import { Button } from '$lib/components/ui/button';
|
import { Button } from '$lib/components/ui/button';
|
||||||
import { BookOpenText, House, Map } from '@lucide/svelte';
|
import { BookOpenText, House, Map } from '@lucide/svelte';
|
||||||
@@ -9,7 +10,7 @@
|
|||||||
<nav class="sticky top-0 w-full px-12 py-2 bg-background z-50 flex flex-col items-center border-b">
|
<nav class="sticky top-0 w-full px-12 py-2 bg-background z-50 flex flex-col items-center border-b">
|
||||||
<div class="w-full max-w-5xl flex flex-row items-center gap-4 sm:gap-8">
|
<div class="w-full max-w-5xl flex flex-row items-center gap-4 sm:gap-8">
|
||||||
<a
|
<a
|
||||||
href={getURLForLanguage(i18n.lang, '/')}
|
href={resolve(getURLForLanguage(i18n.lang, '/'))}
|
||||||
class="shrink-0 translate-y-0.25 justify-self-start"
|
class="shrink-0 translate-y-0.25 justify-self-start"
|
||||||
>
|
>
|
||||||
<Logo class="h-8 xs:hidden" iconOnly={true} width="26" />
|
<Logo class="h-8 xs:hidden" iconOnly={true} width="26" />
|
||||||
@@ -18,7 +19,7 @@
|
|||||||
<Button
|
<Button
|
||||||
variant="link"
|
variant="link"
|
||||||
class="text-base px-0 has-[>svg]:px-0 ml-auto"
|
class="text-base px-0 has-[>svg]:px-0 ml-auto"
|
||||||
href={getURLForLanguage(i18n.lang, '/')}
|
href={resolve(getURLForLanguage(i18n.lang, '/'))}
|
||||||
>
|
>
|
||||||
<House size="18" />
|
<House size="18" />
|
||||||
{i18n._('homepage.home')}
|
{i18n._('homepage.home')}
|
||||||
@@ -27,7 +28,7 @@
|
|||||||
data-sveltekit-reload
|
data-sveltekit-reload
|
||||||
variant="link"
|
variant="link"
|
||||||
class="text-base px-0 has-[>svg]:px-0"
|
class="text-base px-0 has-[>svg]:px-0"
|
||||||
href={getURLForLanguage(i18n.lang, '/app')}
|
href={resolve(getURLForLanguage(i18n.lang, '/app'))}
|
||||||
>
|
>
|
||||||
<Map size="18" />
|
<Map size="18" />
|
||||||
{i18n._('homepage.app')}
|
{i18n._('homepage.app')}
|
||||||
@@ -35,7 +36,7 @@
|
|||||||
<Button
|
<Button
|
||||||
variant="link"
|
variant="link"
|
||||||
class="text-base px-0 has-[>svg]:px-0"
|
class="text-base px-0 has-[>svg]:px-0"
|
||||||
href={getURLForLanguage(i18n.lang, '/help')}
|
href={resolve(getURLForLanguage(i18n.lang, '/help'))}
|
||||||
>
|
>
|
||||||
<BookOpenText size="18" />
|
<BookOpenText size="18" />
|
||||||
{i18n._('menu.help')}
|
{i18n._('menu.help')}
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ export function getPreviousGuide(currentGuide: string): string | undefined {
|
|||||||
return `${previousGuide}/${guides[previousGuide][guides[previousGuide].length - 1]}`;
|
return `${previousGuide}/${guides[previousGuide][guides[previousGuide].length - 1]}`;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (guides.hasOwnProperty(subguides[0])) {
|
if (Object.hasOwn(guides, subguides[0])) {
|
||||||
const subguideIndex = guides[subguides[0]].indexOf(subguides[1]);
|
const subguideIndex = guides[subguides[0]].indexOf(subguides[1]);
|
||||||
if (subguideIndex > 0) {
|
if (subguideIndex > 0) {
|
||||||
return `${subguides[0]}/${guides[subguides[0]][subguideIndex - 1]}`;
|
return `${subguides[0]}/${guides[subguides[0]][subguideIndex - 1]}`;
|
||||||
@@ -56,7 +56,7 @@ export function getNextGuide(currentGuide: string): string | undefined {
|
|||||||
const subguides = currentGuide.split('/');
|
const subguides = currentGuide.split('/');
|
||||||
|
|
||||||
if (subguides.length === 1) {
|
if (subguides.length === 1) {
|
||||||
if (guides.hasOwnProperty(currentGuide)) {
|
if (Object.hasOwn(guides, currentGuide)) {
|
||||||
if (guides[currentGuide].length === 0) {
|
if (guides[currentGuide].length === 0) {
|
||||||
const keys = Object.keys(guides);
|
const keys = Object.keys(guides);
|
||||||
const index = keys.indexOf(currentGuide);
|
const index = keys.indexOf(currentGuide);
|
||||||
@@ -68,7 +68,7 @@ export function getNextGuide(currentGuide: string): string | undefined {
|
|||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (guides.hasOwnProperty(subguides[0])) {
|
if (Object.hasOwn(guides, subguides[0])) {
|
||||||
const subguideIndex = guides[subguides[0]].indexOf(subguides[1]);
|
const subguideIndex = guides[subguides[0]].indexOf(subguides[1]);
|
||||||
if (subguideIndex < guides[subguides[0]].length - 1) {
|
if (subguideIndex < guides[subguides[0]].length - 1) {
|
||||||
return `${subguides[0]}/${guides[subguides[0]][subguideIndex + 1]}`;
|
return `${subguides[0]}/${guides[subguides[0]][subguideIndex + 1]}`;
|
||||||
|
|||||||
@@ -148,7 +148,7 @@ export class ElevationProfile {
|
|||||||
}
|
}
|
||||||
|
|
||||||
initialize() {
|
initialize() {
|
||||||
let options: ChartOptions<'line'> = {
|
const options: ChartOptions<'line'> = {
|
||||||
animation: false,
|
animation: false,
|
||||||
parsing: false,
|
parsing: false,
|
||||||
maintainAspectRatio: false,
|
maintainAspectRatio: false,
|
||||||
@@ -178,6 +178,7 @@ export class ElevationProfile {
|
|||||||
tension: 0.4,
|
tension: 0.4,
|
||||||
borderWidth: 2,
|
borderWidth: 2,
|
||||||
cubicInterpolationMode: 'monotone',
|
cubicInterpolationMode: 'monotone',
|
||||||
|
spanGaps: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
interaction: {
|
interaction: {
|
||||||
@@ -199,7 +200,7 @@ export class ElevationProfile {
|
|||||||
return '';
|
return '';
|
||||||
},
|
},
|
||||||
label: (context: TooltipItem<'line'>) => {
|
label: (context: TooltipItem<'line'>) => {
|
||||||
let point = context.raw as ElevationProfilePoint;
|
const point = context.raw as ElevationProfilePoint;
|
||||||
if (context.datasetIndex === 0) {
|
if (context.datasetIndex === 0) {
|
||||||
this._hoveredPoint.set(
|
this._hoveredPoint.set(
|
||||||
this._dragging
|
this._dragging
|
||||||
@@ -223,16 +224,18 @@ export class ElevationProfile {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
afterBody: (contexts: TooltipItem<'line'>[]) => {
|
afterBody: (contexts: TooltipItem<'line'>[]) => {
|
||||||
let context = contexts.filter((context) => context.datasetIndex === 0);
|
const context = contexts.filter(
|
||||||
|
(context) => context.datasetIndex === 0
|
||||||
|
);
|
||||||
if (context.length === 0) return;
|
if (context.length === 0) return;
|
||||||
let point = context[0].raw as ElevationProfilePoint;
|
const point = context[0].raw as ElevationProfilePoint;
|
||||||
// the rest of the data is there once it is read (see `hover`)
|
// the rest of the data is there once it is read (see `hover`)
|
||||||
const hovered = this._hovered;
|
const hovered = this._hovered;
|
||||||
const details =
|
const details =
|
||||||
hovered?.index === point.index ? hovered.point : undefined;
|
hovered?.index === point.index ? hovered.point : undefined;
|
||||||
const elevationFill = get(this._elevationFill);
|
const elevationFill = get(this._elevationFill);
|
||||||
|
|
||||||
let labels = [
|
const labels = [
|
||||||
` ${i18n._('quantities.distance')}: ${getDistanceWithUnits(point.x, false)}`,
|
` ${i18n._('quantities.distance')}: ${getDistanceWithUnits(point.x, false)}`,
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -250,10 +253,10 @@ export class ElevationProfile {
|
|||||||
}
|
}
|
||||||
labels.push(` ${i18n._('quantities.slope')}: ${slope}`);
|
labels.push(` ${i18n._('quantities.slope')}: ${slope}`);
|
||||||
}
|
}
|
||||||
let surface = details.surface ?? 'unknown';
|
const surface = details.surface ?? 'unknown';
|
||||||
let highway = details.highway ?? 'unknown';
|
const highway = details.highway ?? 'unknown';
|
||||||
let sacScale = details.sacScale;
|
const sacScale = details.sacScale;
|
||||||
let mtbScale = details.mtbScale;
|
const mtbScale = details.mtbScale;
|
||||||
|
|
||||||
if (elevationFill === 'surface') {
|
if (elevationFill === 'surface') {
|
||||||
labels.push(
|
labels.push(
|
||||||
@@ -305,7 +308,7 @@ export class ElevationProfile {
|
|||||||
enabled: true,
|
enabled: true,
|
||||||
},
|
},
|
||||||
mode: 'x',
|
mode: 'x',
|
||||||
onZoomStart: ({ chart, event }: { chart: Chart; event: any }) => {
|
onZoomStart: ({ event }: { event: any }) => {
|
||||||
if (!this._chart) {
|
if (!this._chart) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -335,7 +338,7 @@ export class ElevationProfile {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
let datasets: string[] = ['speed', 'hr', 'cad', 'atemp', 'power'];
|
const datasets: string[] = ['speed', 'hr', 'cad', 'atemp', 'power'];
|
||||||
datasets.forEach((id) => {
|
datasets.forEach((id) => {
|
||||||
options.scales![`y${id}`] = {
|
options.scales![`y${id}`] = {
|
||||||
type: 'linear',
|
type: 'linear',
|
||||||
@@ -343,7 +346,8 @@ export class ElevationProfile {
|
|||||||
grid: {
|
grid: {
|
||||||
display: false,
|
display: false,
|
||||||
},
|
},
|
||||||
reverse: () => id === 'speed' && get(velocityUnits) === 'pace',
|
// the pace axis is reversed: set with the data, which the units change
|
||||||
|
reverse: false,
|
||||||
display: false,
|
display: false,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
@@ -559,6 +563,8 @@ export class ElevationProfile {
|
|||||||
global.totalDistance,
|
global.totalDistance,
|
||||||
units.distance
|
units.distance
|
||||||
);
|
);
|
||||||
|
// a faster pace is a lower value, it goes up like a higher speed
|
||||||
|
this._chart.options.scales!.yspeed!.reverse = units.velocity === 'pace';
|
||||||
|
|
||||||
this.setVisibility();
|
this.setVisibility();
|
||||||
this.setFill();
|
this.setFill();
|
||||||
@@ -580,11 +586,11 @@ export class ElevationProfile {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const additionalDatasets = get(this._additionalDatasets);
|
const additionalDatasets = get(this._additionalDatasets);
|
||||||
let includeSpeed = additionalDatasets.includes('speed');
|
const includeSpeed = additionalDatasets.includes('speed');
|
||||||
let includeHeartRate = additionalDatasets.includes('hr');
|
const includeHeartRate = additionalDatasets.includes('hr');
|
||||||
let includeCadence = additionalDatasets.includes('cad');
|
const includeCadence = additionalDatasets.includes('cad');
|
||||||
let includeTemperature = additionalDatasets.includes('atemp');
|
const includeTemperature = additionalDatasets.includes('atemp');
|
||||||
let includePower = additionalDatasets.includes('power');
|
const includePower = additionalDatasets.includes('power');
|
||||||
if (this._chart.data.datasets.length == 6) {
|
if (this._chart.data.datasets.length == 6) {
|
||||||
this._chart.data.datasets[1].hidden = !includeSpeed;
|
this._chart.data.datasets[1].hidden = !includeSpeed;
|
||||||
this._chart.data.datasets[2].hidden = !includeHeartRate;
|
this._chart.data.datasets[2].hidden = !includeHeartRate;
|
||||||
@@ -639,21 +645,21 @@ export class ElevationProfile {
|
|||||||
|
|
||||||
const slicedStatistics = get(this._slicedStatistics);
|
const slicedStatistics = get(this._slicedStatistics);
|
||||||
if (slicedStatistics) {
|
if (slicedStatistics) {
|
||||||
let startIndex = slicedStatistics.start;
|
const startIndex = slicedStatistics.start;
|
||||||
let endIndex = slicedStatistics.end;
|
const endIndex = slicedStatistics.end;
|
||||||
|
|
||||||
// Draw selection rectangle
|
// Draw selection rectangle
|
||||||
let selectionContext = this._overlay.getContext('2d');
|
const selectionContext = this._overlay.getContext('2d');
|
||||||
if (selectionContext) {
|
if (selectionContext) {
|
||||||
selectionContext.fillStyle = mode.current === 'dark' ? 'white' : 'black';
|
selectionContext.fillStyle = mode.current === 'dark' ? 'white' : 'black';
|
||||||
selectionContext.globalAlpha = mode.current === 'dark' ? 0.2 : 0.1;
|
selectionContext.globalAlpha = mode.current === 'dark' ? 0.2 : 0.1;
|
||||||
selectionContext.clearRect(0, 0, this._overlay.width, this._overlay.height);
|
selectionContext.clearRect(0, 0, this._overlay.width, this._overlay.height);
|
||||||
|
|
||||||
const statistics = get(this._statistics);
|
const statistics = get(this._statistics);
|
||||||
let startPixel = this._chart.scales.x.getPixelForValue(
|
const startPixel = this._chart.scales.x.getPixelForValue(
|
||||||
getConvertedDistance(statistics.totalDistance[startIndex] ?? 0)
|
getConvertedDistance(statistics.totalDistance[startIndex] ?? 0)
|
||||||
);
|
);
|
||||||
let endPixel = this._chart.scales.x.getPixelForValue(
|
const endPixel = this._chart.scales.x.getPixelForValue(
|
||||||
getConvertedDistance(statistics.totalDistance[endIndex] ?? 0)
|
getConvertedDistance(statistics.totalDistance[endIndex] ?? 0)
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -665,7 +671,7 @@ export class ElevationProfile {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
} else if (this._overlay) {
|
} else if (this._overlay) {
|
||||||
let selectionContext = this._overlay.getContext('2d');
|
const selectionContext = this._overlay.getContext('2d');
|
||||||
if (selectionContext) {
|
if (selectionContext) {
|
||||||
selectionContext.clearRect(0, 0, this._overlay.width, this._overlay.height);
|
selectionContext.clearRect(0, 0, this._overlay.width, this._overlay.height);
|
||||||
}
|
}
|
||||||
|
|||||||
Loaded 100 of 517 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user