88 Commits
Author SHA1 Message Date
vcoppe ed73d78562 New translations en.json (Spanish)
[ci skip]
2026-11-30 10:25:14 +01:00
vcoppe 12a8e4183a Merge pull request #414 from gpxstudio/l10n
New Crowdin updates
2026-11-29 22:48:58 +01:00
vcoppe 2070fe8139 New translations en.json (French)
[ci skip]
2026-11-29 22:43:40 +01:00
vcoppe 092f8b8592 New translations en.json (Serbian (Latin))
[ci skip]
2026-11-29 22:36:01 +01:00
vcoppe bfde34c571 New translations en.json (Chinese Traditional, Hong Kong)
[ci skip]
2026-11-29 22:36:00 +01:00
vcoppe 3aacc73b29 New translations en.json (Latvian)
[ci skip]
2026-11-29 22:35:58 +01:00
vcoppe 8e5af4457a New translations en.json (Thai)
[ci skip]
2026-11-29 22:35:57 +01:00
vcoppe 49c125b9c8 New translations en.json (Indonesian)
[ci skip]
2026-11-29 22:35:56 +01:00
vcoppe 1284675a2f New translations en.json (Portuguese, Brazilian)
[ci skip]
2026-11-29 22:35:54 +01:00
vcoppe 49a433c1e9 New translations en.json (Vietnamese)
[ci skip]
2026-11-29 22:35:53 +01:00
vcoppe a106872dd0 New translations en.json (Chinese Simplified)
[ci skip]
2026-11-29 22:35:51 +01:00
vcoppe a091f61741 New translations en.json (Ukrainian)
[ci skip]
2026-11-29 22:35:50 +01:00
vcoppe acecae33e2 New translations en.json (Turkish)
[ci skip]
2026-11-29 22:35:49 +01:00
vcoppe 308d4dc10f New translations en.json (Swedish)
[ci skip]
2026-11-29 22:35:47 +01:00
vcoppe e8ed485e70 New translations en.json (Russian)
[ci skip]
2026-11-29 22:35:46 +01:00
vcoppe a52eb3688a New translations en.json (Portuguese)
[ci skip]
2026-11-29 22:35:44 +01:00
vcoppe b3e18922c5 New translations en.json (Polish)
[ci skip]
2026-11-29 22:35:43 +01:00
vcoppe c0cd04b5a1 New translations en.json (Norwegian)
[ci skip]
2026-11-29 22:35:42 +01:00
vcoppe 5a549487d0 New translations en.json (Lithuanian)
[ci skip]
2026-11-29 22:35:40 +01:00
vcoppe 20adbf3865 New translations en.json (Italian)
[ci skip]
2026-11-29 22:35:39 +01:00
vcoppe 545a02157b New translations en.json (Hungarian)
[ci skip]
2026-11-29 22:35:37 +01:00
vcoppe 6d8d160d8e New translations en.json (Hebrew)
[ci skip]
2026-11-29 22:35:36 +01:00
vcoppe 99bc3eab86 New translations en.json (Finnish)
[ci skip]
2026-11-29 22:35:34 +01:00
vcoppe d9bd3f1de0 New translations en.json (Basque)
[ci skip]
2026-11-29 22:35:33 +01:00
vcoppe 654299f5da New translations en.json (Greek)
[ci skip]
2026-11-29 22:35:31 +01:00
vcoppe 199eb0da2a New translations en.json (German)
[ci skip]
2026-11-29 22:35:30 +01:00
vcoppe 6934ce85e6 New translations en.json (Danish)
[ci skip]
2026-11-29 22:35:29 +01:00
vcoppe 46225ae934 New translations en.json (Czech)
[ci skip]
2026-11-29 22:35:27 +01:00
vcoppe 8fc6aa8729 New translations en.json (Catalan)
[ci skip]
2026-11-29 22:35:26 +01:00
vcoppe 5b4e441fcd New translations en.json (Belarusian)
[ci skip]
2026-11-29 22:35:24 +01:00
vcoppe 4b421b665c New translations en.json (Spanish)
[ci skip]
2026-11-29 22:35:23 +01:00
vcoppe c705a126fe New translations en.json (French)
[ci skip]
2026-11-29 22:35:21 +01:00
vcoppe 45225a4f20 New translations en.json (Romanian)
[ci skip]
2026-11-29 22:35:20 +01:00
vcoppe 4bd3e1cc25 New translations en.json (Dutch)
[ci skip]
2026-11-29 22:35:19 +01:00
vcoppe 73487b38ff New translations en.json (Korean)
[ci skip]
2026-11-29 22:35:17 +01:00
vcoppe dc3ea63c0f add danish topo map 2026-11-29 22:34:37 +01:00
vcoppe 3ac084be65 more national imagery 2026-11-29 22:25:45 +01:00
vcoppe 183bc38e9d New translations elevation.mdx (Dutch)
[ci skip]
2026-11-29 18:53:56 +01:00
vcoppe e42e619af6 New translations en.json (Dutch)
[ci skip]
2026-11-29 17:09:27 +01:00
vcoppe 9372df1c61 split 256px and 512px sources 2026-11-29 16:37:22 +01:00
vcoppe 4e4142dabc New Crowdin updates (#413)
* New translations en.json (Dutch)

[ci skip]

* New translations edit.mdx (Basque)

[ci skip]

* New translations en.json (Korean)

[ci skip]

* New translations en.json (Dutch)

[ci skip]

* New translations en.json (Romanian)

[ci skip]

* New translations en.json (French)

[ci skip]

* New translations en.json (Spanish)

[ci skip]

* New translations en.json (Belarusian)

[ci skip]

* New translations en.json (Catalan)

[ci skip]

* New translations en.json (Czech)

[ci skip]

* New translations en.json (Danish)

[ci skip]

* New translations en.json (German)

[ci skip]

* New translations en.json (Greek)

[ci skip]

* New translations en.json (Basque)

[ci skip]

* New translations en.json (Finnish)

[ci skip]

* New translations en.json (Hebrew)

[ci skip]

* New translations en.json (Hungarian)

[ci skip]

* New translations en.json (Italian)

[ci skip]

* New translations en.json (Lithuanian)

[ci skip]

* New translations en.json (Norwegian)

[ci skip]

* New translations en.json (Polish)

[ci skip]

* New translations en.json (Portuguese)

[ci skip]

* New translations en.json (Russian)

[ci skip]

* New translations en.json (Swedish)

[ci skip]

* New translations en.json (Turkish)

[ci skip]

* New translations en.json (Ukrainian)

[ci skip]

* New translations en.json (Chinese Simplified)

[ci skip]

* New translations en.json (Vietnamese)

[ci skip]

* New translations en.json (Portuguese, Brazilian)

[ci skip]

* New translations en.json (Indonesian)

[ci skip]

* New translations en.json (Thai)

[ci skip]

* New translations en.json (Latvian)

[ci skip]

* New translations en.json (Chinese Traditional, Hong Kong)

[ci skip]

* New translations en.json (Serbian (Latin))

[ci skip]
2026-11-29 16:03:32 +01:00
vcoppe 4d4804203f use border tiles to cut patchwork precisely 2026-11-29 15:06:35 +01:00
vcoppe 657cf8786c remove temporary layer 2026-11-29 13:16:57 +01:00
vcoppe 5f46b08eda uniform low zoom level imagery 2026-11-29 13:09:26 +01:00
vcoppe 2cf9a9f982 poc 2026-11-29 12:52:41 +01:00
vcoppe 1bd8ac46fe add integration info to readme 2026-11-15 16:18:04 +01:00
vcoppe 304eaa7892 remove extension api v1 2026-11-15 16:12:18 +01:00
vcoppe 2e0edc716b Merge branch 'dev' 2026-11-15 13:15:08 +01:00
vcoppe 776be33ff9 Merge branch 'dev' of https://github.com/gpxstudio/gpx.studio into dev 2026-11-15 13:14:41 +01:00
vcoppe 2fa721586b add testing info 2026-11-15 13:12:27 +01:00
vcoppe 25e10dbd82 add tauri info to readme 2026-11-15 13:09:48 +01:00
vcoppe 2681900a0a New Crowdin updates (#407)
* New translations en.json (Chinese Simplified)

[ci skip]

* New translations en.json (Chinese Simplified)

[ci skip]

* New translations files-and-stats.mdx (Chinese Simplified)

[ci skip]

* New translations gpx.mdx (Chinese Simplified)

[ci skip]

* New translations edit.mdx (Chinese Simplified)

[ci skip]

* New translations merge.mdx (Chinese Simplified)

[ci skip]

* New translations scissors.mdx (Chinese Simplified)

[ci skip]
2026-11-15 11:36:16 +01:00
vcoppe af46423859 parse gpx time metadata 2026-11-15 11:01:42 +01:00
Jay Hemnaniandvcoppe 8aede444fc keep waypoint time on import (#409)
* keep waypoint time on import

* Remove extra newline in parse.rs test file

---------

Co-authored-by: vcoppe <vianney.coppe@gmail.com>
2026-11-15 10:57:06 +01:00
Jay Hemnani 58b2861160 read decimal temperatures in trackpoint extensions (#408) 2026-11-15 10:45:45 +01:00
vcoppe 9da64274ac upgrade maplibre 2026-11-14 16:27:03 +01:00
vcoppe 761cfcae42 Merge branch 'dev' 2026-11-11 11:07:08 +01:00
vcoppe b719fe908f fix slow elevation profile tooltip 2026-11-11 11:06:39 +01:00
vcoppe b6a7df3cf2 Merge branch 'dev' 2026-11-11 09:40:45 +01:00
vcoppe 8ef3eca819 replace deprecated method 2026-11-11 09:32:28 +01:00
vcoppe 0e2a5a39df New Crowdin updates (#405)
* New translations en.json (Spanish)

[ci skip]

* New translations en.json (Spanish)

[ci skip]

* New translations edit.mdx (Spanish)

[ci skip]

* New translations en.json (Romanian)

[ci skip]

* New translations en.json (French)

[ci skip]

* New translations en.json (Spanish)

[ci skip]

* New translations en.json (Belarusian)

[ci skip]

* New translations en.json (Catalan)

[ci skip]

* New translations en.json (Czech)

[ci skip]

* New translations en.json (Danish)

[ci skip]

* New translations en.json (German)

[ci skip]

* New translations en.json (Greek)

[ci skip]

* New translations en.json (Basque)

[ci skip]

* New translations en.json (Finnish)

[ci skip]

* New translations en.json (Hebrew)

[ci skip]

* New translations en.json (Hungarian)

[ci skip]

* New translations en.json (Italian)

[ci skip]

* New translations en.json (Korean)

[ci skip]

* New translations en.json (Lithuanian)

[ci skip]

* New translations en.json (Dutch)

[ci skip]

* New translations en.json (Norwegian)

[ci skip]

* New translations en.json (Polish)

[ci skip]

* New translations en.json (Portuguese)

[ci skip]

* New translations en.json (Russian)

[ci skip]

* New translations en.json (Swedish)

[ci skip]

* New translations en.json (Turkish)

[ci skip]

* New translations en.json (Ukrainian)

[ci skip]

* New translations en.json (Chinese Simplified)

[ci skip]

* New translations en.json (Vietnamese)

[ci skip]

* New translations en.json (Portuguese, Brazilian)

[ci skip]

* New translations en.json (Indonesian)

[ci skip]

* New translations en.json (Thai)

[ci skip]

* New translations en.json (Latvian)

[ci skip]

* New translations en.json (Chinese Traditional, Hong Kong)

[ci skip]

* New translations en.json (Serbian (Latin))

[ci skip]

* New translations en.json (Basque)

[ci skip]

* New translations en.json (Basque)

[ci skip]

* New translations en.json (Dutch)

[ci skip]

* New translations en.json (French)

[ci skip]

* New translations en.json (Lithuanian)

[ci skip]

* New translations en.json (Lithuanian)

[ci skip]

* New translations en.json (Spanish)

[ci skip]
2026-11-11 09:23:41 +01:00
vcoppe 59c9427778 rename extension api event 2026-11-08 17:42:13 +01:00
vcoppe 57c34b388b filter out extension layers on load 2026-11-08 17:34:35 +01:00
vcoppe 4050420b3c extension api v2, ref #395 2026-11-08 17:23:22 +01:00
vcoppe 7474f892ce cleaning 2026-11-08 15:32:12 +01:00
vcoppe 002fd259aa hide point info in routing and scissors tools 2026-11-08 15:15:16 +01:00
vcoppe 21e27a4416 show hovered point on elevation profile 2026-11-08 15:06:03 +01:00
b80fa7d942 fix a click on the temporary anchor (#397)
Hovering a line in the routing tool shows a temporary anchor, which is
drawn in the anchors' layer with the index one past the last anchor.
Clicking it reached onClick, which looked that index up in the anchors,
got undefined and threw reading its properties. The click now adds the
anchor, as a click on the line does.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: vcoppe <vianney.coppe@gmail.com>
2026-11-08 14:26:58 +01:00
Nathan Cahillandvcoppe 2608870505 fix a latitude typed past ±90 in the waypoint tool (#398)
The pin followed the latitude and longitude fields on every keystroke,
and min/max on a number field don't stop typing, so a value on the way
to a coordinate (389) reached Marker.setLngLat and MapLibre threw
"Invalid LngLat latitude value". An empty field moved the pin to the
equator, saving with one threw on null.toFixed, and an out-of-range
value saved as typed.

The pin now stays where it was and Save is disabled until both fields
hold a coordinate in range, and the field that doesn't is marked
invalid.

Co-authored-by: vcoppe <vianney.coppe@gmail.com>
2026-11-08 14:17:45 +01:00
vcoppe 9e289c33be rework time component 2026-11-08 14:03:48 +01:00
vcoppe 419489bcfe #206 continued 2026-11-07 14:31:24 +01:00
vcoppe 7a7749a9d3 closes #206 2026-11-05 20:29:23 +01:00
vcoppe eee76f05d4 batch of fixes 2026-11-04 21:27:14 +01:00
vcoppe a67b982b1c clean builds and add auto-updater 2026-11-04 20:02:18 +01:00
vcoppe c0afd1fea9 cloudflare build only 2026-11-04 18:46:23 +01:00
vcoppe c0e6e3d2eb fix release step 2026-11-01 17:43:28 +01:00
vcoppe 9bd38cd5f8 fix tests 2026-11-01 17:24:49 +01:00
vcoppe a163e1b897 New Crowdin updates (#404)
* New translations en.json (Dutch)

[ci skip]

* New translations files-and-stats.mdx (Romanian)

[ci skip]

* New translations files-and-stats.mdx (French)

[ci skip]

* New translations files-and-stats.mdx (Spanish)

[ci skip]

* New translations files-and-stats.mdx (Belarusian)

[ci skip]

* New translations files-and-stats.mdx (Catalan)

[ci skip]

* New translations files-and-stats.mdx (Czech)

[ci skip]

* New translations files-and-stats.mdx (Danish)

[ci skip]

* New translations files-and-stats.mdx (German)

[ci skip]

* New translations files-and-stats.mdx (Greek)

[ci skip]

* New translations files-and-stats.mdx (Basque)

[ci skip]

* New translations files-and-stats.mdx (Finnish)

[ci skip]

* New translations files-and-stats.mdx (Hebrew)

[ci skip]

* New translations files-and-stats.mdx (Hungarian)

[ci skip]

* New translations files-and-stats.mdx (Italian)

[ci skip]

* New translations files-and-stats.mdx (Korean)

[ci skip]

* New translations files-and-stats.mdx (Lithuanian)

[ci skip]

* New translations files-and-stats.mdx (Dutch)

[ci skip]

* New translations files-and-stats.mdx (Norwegian)

[ci skip]

* New translations files-and-stats.mdx (Polish)

[ci skip]

* New translations files-and-stats.mdx (Portuguese)

[ci skip]

* New translations files-and-stats.mdx (Russian)

[ci skip]

* New translations files-and-stats.mdx (Swedish)

[ci skip]

* New translations files-and-stats.mdx (Turkish)

[ci skip]

* New translations files-and-stats.mdx (Ukrainian)

[ci skip]

* New translations files-and-stats.mdx (Chinese Simplified)

[ci skip]

* New translations files-and-stats.mdx (Vietnamese)

[ci skip]

* New translations files-and-stats.mdx (Portuguese, Brazilian)

[ci skip]

* New translations files-and-stats.mdx (Indonesian)

[ci skip]

* New translations files-and-stats.mdx (Thai)

[ci skip]

* New translations files-and-stats.mdx (Latvian)

[ci skip]

* New translations files-and-stats.mdx (Chinese Traditional, Hong Kong)

[ci skip]

* New translations files-and-stats.mdx (Serbian (Latin))

[ci skip]

* New translations gpx.mdx (Dutch)

[ci skip]

* New translations map-controls.mdx (Basque)

[ci skip]

* New translations edit.mdx (Dutch)

[ci skip]
2026-11-01 17:18:56 +01:00
vcoppe 33abec525a remove unused key in locales 2026-11-01 17:00:12 +01:00
vcoppe 77c542d9aa fix windows build continued 2026-11-01 16:52:36 +01:00
vcoppe 17b5c1d567 fix windows build 2026-11-01 16:07:49 +01:00
vcoppe 2048076fe6 tauri build test 2026-11-01 15:52:34 +01:00
vcoppe d7ff7d645b New Crowdin updates (#403)
* New translations edit.mdx (Lithuanian)

[ci skip]

* New translations edit.mdx (Dutch)

[ci skip]

* New translations edit.mdx (Norwegian)

[ci skip]

* New translations edit.mdx (Polish)

[ci skip]

* New translations edit.mdx (Portuguese)

[ci skip]

* New translations edit.mdx (Russian)

[ci skip]

* New translations edit.mdx (Swedish)

[ci skip]

* New translations edit.mdx (Turkish)

[ci skip]

* New translations edit.mdx (Ukrainian)

[ci skip]

* New translations edit.mdx (Chinese Simplified)

[ci skip]

* New translations edit.mdx (Vietnamese)

[ci skip]

* New translations edit.mdx (Portuguese, Brazilian)

[ci skip]

* New translations edit.mdx (Indonesian)

[ci skip]

* New translations edit.mdx (Thai)

[ci skip]

* New translations edit.mdx (Latvian)

[ci skip]

* New translations edit.mdx (Chinese Traditional, Hong Kong)

[ci skip]

* New translations edit.mdx (Serbian (Latin))

[ci skip]

* New translations file.mdx (Romanian)

[ci skip]

* New translations file.mdx (French)

[ci skip]

* New translations file.mdx (Spanish)

[ci skip]

* New translations file.mdx (Belarusian)

[ci skip]

* New translations file.mdx (Catalan)

[ci skip]

* New translations file.mdx (Czech)

[ci skip]

* New translations file.mdx (Danish)

[ci skip]

* New translations file.mdx (German)

[ci skip]

* New translations file.mdx (Greek)

[ci skip]

* New translations file.mdx (Basque)

[ci skip]

* New translations file.mdx (Finnish)

[ci skip]

* New translations file.mdx (Hebrew)

[ci skip]

* New translations file.mdx (Hungarian)

[ci skip]

* New translations file.mdx (Italian)

[ci skip]

* New translations file.mdx (Korean)

[ci skip]

* New translations file.mdx (Lithuanian)

[ci skip]

* New translations file.mdx (Dutch)

[ci skip]

* New translations file.mdx (Norwegian)

[ci skip]

* New translations file.mdx (Polish)

[ci skip]

* New translations file.mdx (Portuguese)

[ci skip]

* New translations file.mdx (Russian)

[ci skip]

* New translations file.mdx (Swedish)

[ci skip]

* New translations file.mdx (Turkish)

[ci skip]

* New translations file.mdx (Ukrainian)

[ci skip]

* New translations file.mdx (Chinese Simplified)

[ci skip]

* New translations file.mdx (Vietnamese)

[ci skip]

* New translations file.mdx (Portuguese, Brazilian)

[ci skip]

* New translations file.mdx (Indonesian)

[ci skip]

* New translations file.mdx (Thai)

[ci skip]

* New translations file.mdx (Latvian)

[ci skip]

* New translations file.mdx (Chinese Traditional, Hong Kong)

[ci skip]

* New translations file.mdx (Serbian (Latin))

[ci skip]

* New translations view.mdx (Romanian)

[ci skip]

* New translations view.mdx (French)

[ci skip]

* New translations view.mdx (Spanish)

[ci skip]

* New translations view.mdx (Belarusian)

[ci skip]

* New translations view.mdx (Catalan)

[ci skip]

* New translations view.mdx (Czech)

[ci skip]

* New translations view.mdx (Danish)

[ci skip]

* New translations view.mdx (German)

[ci skip]

* New translations view.mdx (Greek)

[ci skip]

* New translations view.mdx (Basque)

[ci skip]

* New translations view.mdx (Finnish)

[ci skip]

* New translations view.mdx (Hebrew)

[ci skip]

* New translations view.mdx (Hungarian)

[ci skip]

* New translations view.mdx (Italian)

[ci skip]

* New translations view.mdx (Korean)

[ci skip]

* New translations view.mdx (Lithuanian)

[ci skip]

* New translations view.mdx (Dutch)

[ci skip]

* New translations view.mdx (Norwegian)

[ci skip]

* New translations view.mdx (Polish)

[ci skip]

* New translations view.mdx (Portuguese)

[ci skip]

* New translations view.mdx (Russian)

[ci skip]

* New translations view.mdx (Swedish)

[ci skip]

* New translations view.mdx (Turkish)

[ci skip]

* New translations view.mdx (Ukrainian)

[ci skip]

* New translations view.mdx (Chinese Simplified)

[ci skip]

* New translations view.mdx (Vietnamese)

[ci skip]

* New translations view.mdx (Portuguese, Brazilian)

[ci skip]

* New translations view.mdx (Indonesian)

[ci skip]

* New translations view.mdx (Thai)

[ci skip]

* New translations view.mdx (Latvian)

[ci skip]

* New translations view.mdx (Chinese Traditional, Hong Kong)

[ci skip]

* New translations view.mdx (Serbian (Latin))

[ci skip]

* New translations extract.mdx (Romanian)

[ci skip]

* New translations extract.mdx (French)

[ci skip]

* New translations extract.mdx (Spanish)

[ci skip]

* New translations extract.mdx (Belarusian)

[ci skip]

* New translations extract.mdx (Catalan)

[ci skip]

* New translations extract.mdx (Czech)

[ci skip]

* New translations extract.mdx (Danish)

[ci skip]

* New translations extract.mdx (German)

[ci skip]

* New translations extract.mdx (Greek)

[ci skip]

* New translations extract.mdx (Basque)

[ci skip]

* New translations extract.mdx (Finnish)

[ci skip]

* New translations extract.mdx (Hebrew)

[ci skip]

* New translations extract.mdx (Hungarian)

[ci skip]

* New translations extract.mdx (Italian)

[ci skip]

* New translations extract.mdx (Korean)

[ci skip]

* New translations extract.mdx (Lithuanian)

[ci skip]

* New translations extract.mdx (Dutch)

[ci skip]

* New translations extract.mdx (Norwegian)

[ci skip]

* New translations extract.mdx (Polish)

[ci skip]

* New translations extract.mdx (Portuguese)

[ci skip]

* New translations extract.mdx (Russian)

[ci skip]

* New translations extract.mdx (Swedish)

[ci skip]

* New translations extract.mdx (Turkish)

[ci skip]

* New translations extract.mdx (Ukrainian)

[ci skip]

* New translations extract.mdx (Chinese Simplified)

[ci skip]

* New translations extract.mdx (Vietnamese)

[ci skip]

* New translations extract.mdx (Portuguese, Brazilian)

[ci skip]

* New translations extract.mdx (Indonesian)

[ci skip]

* New translations extract.mdx (Thai)

[ci skip]

* New translations extract.mdx (Latvian)

[ci skip]

* New translations extract.mdx (Chinese Traditional, Hong Kong)

[ci skip]

* New translations extract.mdx (Serbian (Latin))

[ci skip]

* New translations merge.mdx (Romanian)

[ci skip]

* New translations merge.mdx (French)

[ci skip]

* New translations merge.mdx (Spanish)

[ci skip]

* New translations merge.mdx (Belarusian)

[ci skip]

* New translations merge.mdx (Catalan)

[ci skip]

* New translations merge.mdx (Czech)

[ci skip]

* New translations merge.mdx (Danish)

[ci skip]

* New translations merge.mdx (German)

[ci skip]

* New translations merge.mdx (Greek)

[ci skip]

* New translations merge.mdx (Basque)

[ci skip]

* New translations merge.mdx (Finnish)

[ci skip]

* New translations merge.mdx (Hebrew)

[ci skip]

* New translations merge.mdx (Hungarian)

[ci skip]

* New translations merge.mdx (Italian)

[ci skip]

* New translations merge.mdx (Korean)

[ci skip]

* New translations merge.mdx (Lithuanian)

[ci skip]

* New translations merge.mdx (Dutch)

[ci skip]

* New translations merge.mdx (Norwegian)

[ci skip]

* New translations merge.mdx (Polish)

[ci skip]

* New translations merge.mdx (Portuguese)

[ci skip]

* New translations merge.mdx (Russian)

[ci skip]

* New translations merge.mdx (Swedish)

[ci skip]

* New translations merge.mdx (Turkish)

[ci skip]

* New translations merge.mdx (Ukrainian)

[ci skip]

* New translations merge.mdx (Chinese Simplified)

[ci skip]

* New translations merge.mdx (Vietnamese)

[ci skip]

* New translations merge.mdx (Portuguese, Brazilian)

[ci skip]

* New translations merge.mdx (Indonesian)

[ci skip]

* New translations merge.mdx (Thai)

[ci skip]

* New translations merge.mdx (Latvian)

[ci skip]

* New translations merge.mdx (Chinese Traditional, Hong Kong)

[ci skip]

* New translations merge.mdx (Serbian (Latin))

[ci skip]

* New translations scissors.mdx (Romanian)

[ci skip]

* New translations scissors.mdx (French)

[ci skip]

* New translations scissors.mdx (Spanish)

[ci skip]

* New translations scissors.mdx (Belarusian)

[ci skip]

* New translations scissors.mdx (Catalan)

[ci skip]

* New translations scissors.mdx (Czech)

[ci skip]

* New translations scissors.mdx (Danish)

[ci skip]

* New translations scissors.mdx (German)

[ci skip]

* New translations scissors.mdx (Greek)

[ci skip]

* New translations scissors.mdx (Basque)

[ci skip]

* New translations scissors.mdx (Finnish)

[ci skip]

* New translations scissors.mdx (Hebrew)

[ci skip]

* New translations scissors.mdx (Hungarian)

[ci skip]

* New translations scissors.mdx (Italian)

[ci skip]

* New translations scissors.mdx (Korean)

[ci skip]

* New translations scissors.mdx (Lithuanian)

[ci skip]

* New translations scissors.mdx (Dutch)

[ci skip]

* New translations scissors.mdx (Norwegian)

[ci skip]

* New translations scissors.mdx (Polish)

[ci skip]

* New translations scissors.mdx (Portuguese)

[ci skip]

* New translations scissors.mdx (Russian)

[ci skip]

* New translations scissors.mdx (Swedish)

[ci skip]

* New translations scissors.mdx (Turkish)

[ci skip]

* New translations scissors.mdx (Ukrainian)

[ci skip]

* New translations scissors.mdx (Chinese Simplified)

[ci skip]

* New translations scissors.mdx (Vietnamese)

[ci skip]

* New translations scissors.mdx (Portuguese, Brazilian)

[ci skip]

* New translations scissors.mdx (Indonesian)

[ci skip]

* New translations scissors.mdx (Thai)

[ci skip]

* New translations scissors.mdx (Latvian)

[ci skip]

* New translations scissors.mdx (Chinese Traditional, Hong Kong)

[ci skip]

* New translations scissors.mdx (Serbian (Latin))

[ci skip]

* New translations en.json (French)

[ci skip]

* New translations edit.mdx (Romanian)

[ci skip]

* New translations edit.mdx (French)

[ci skip]

* New translations edit.mdx (Spanish)

[ci skip]

* New translations edit.mdx (Belarusian)

[ci skip]

* New translations edit.mdx (Catalan)

[ci skip]

* New translations edit.mdx (Czech)

[ci skip]

* New translations edit.mdx (Danish)

[ci skip]

* New translations edit.mdx (German)

[ci skip]

* New translations edit.mdx (Greek)

[ci skip]

* New translations edit.mdx (Basque)

[ci skip]

* New translations edit.mdx (Finnish)

[ci skip]

* New translations edit.mdx (Hebrew)

[ci skip]

* New translations edit.mdx (Hungarian)

[ci skip]

* New translations edit.mdx (Italian)

[ci skip]

* New translations edit.mdx (Korean)

[ci skip]

* New translations edit.mdx (Lithuanian)

[ci skip]

* New translations edit.mdx (Dutch)

[ci skip]

* New translations edit.mdx (Norwegian)

[ci skip]

* New translations edit.mdx (Polish)

[ci skip]

* New translations edit.mdx (Portuguese)

[ci skip]

* New translations edit.mdx (Russian)

[ci skip]

* New translations edit.mdx (Swedish)

[ci skip]

* New translations edit.mdx (Turkish)

[ci skip]

* New translations edit.mdx (Ukrainian)

[ci skip]

* New translations edit.mdx (Chinese Simplified)

[ci skip]

* New translations edit.mdx (Vietnamese)

[ci skip]

* New translations edit.mdx (Portuguese, Brazilian)

[ci skip]

* New translations edit.mdx (Indonesian)

[ci skip]

* New translations edit.mdx (Thai)

[ci skip]

* New translations edit.mdx (Latvian)

[ci skip]

* New translations edit.mdx (Chinese Traditional, Hong Kong)

[ci skip]

* New translations edit.mdx (Serbian (Latin))

[ci skip]

* New translations file.mdx (French)

[ci skip]

* New translations view.mdx (French)

[ci skip]

* New translations extract.mdx (French)

[ci skip]

* New translations merge.mdx (French)

[ci skip]

* New translations scissors.mdx (French)

[ci skip]

* New translations files-and-stats.mdx (French)

[ci skip]

* New translations gpx.mdx (French)

[ci skip]

* New translations edit.mdx (Romanian)

[ci skip]

* New translations edit.mdx (French)

[ci skip]

* New translations edit.mdx (Spanish)

[ci skip]

* New translations edit.mdx (Belarusian)

[ci skip]

* New translations edit.mdx (Catalan)

[ci skip]

* New translations edit.mdx (Czech)

[ci skip]

* New translations edit.mdx (Danish)

[ci skip]

* New translations edit.mdx (German)

[ci skip]

* New translations edit.mdx (Greek)

[ci skip]

* New translations edit.mdx (Basque)

[ci skip]

* New translations edit.mdx (Finnish)

[ci skip]

* New translations edit.mdx (Hebrew)

[ci skip]

* New translations edit.mdx (Hungarian)

[ci skip]

* New translations edit.mdx (Italian)

[ci skip]

* New translations edit.mdx (Korean)

[ci skip]

* New translations edit.mdx (Lithuanian)

[ci skip]

* New translations edit.mdx (Dutch)

[ci skip]

* New translations edit.mdx (Norwegian)

[ci skip]

* New translations edit.mdx (Polish)

[ci skip]

* New translations edit.mdx (Portuguese)

[ci skip]

* New translations edit.mdx (Russian)

[ci skip]

* New translations edit.mdx (Swedish)

[ci skip]

* New translations edit.mdx (Turkish)

[ci skip]

* New translations edit.mdx (Ukrainian)

[ci skip]

* New translations edit.mdx (Chinese Simplified)

[ci skip]

* New translations edit.mdx (Vietnamese)

[ci skip]

* New translations edit.mdx (Portuguese, Brazilian)

[ci skip]

* New translations edit.mdx (Indonesian)

[ci skip]

* New translations edit.mdx (Thai)

[ci skip]

* New translations edit.mdx (Latvian)

[ci skip]

* New translations edit.mdx (Chinese Traditional, Hong Kong)

[ci skip]

* New translations edit.mdx (Serbian (Latin))

[ci skip]

* New translations en.json (French)

[ci skip]
2026-11-01 15:41:07 +01:00
vcoppe 262b590bd4 remove note 2026-11-01 15:04:24 +01:00
vcoppe 14bf9cddd2 Merge branch 'dev' of https://github.com/gpxstudio/gpx.studio into dev 2026-11-01 14:51:44 +01:00
vcoppe b9566160e5 rephrasing 2026-11-01 14:51:42 +01:00
vcoppe 9a23762af4 temporary dual deployment 2026-11-01 09:15:02 +01:00
vcoppe 0cc9d6f664 New Crowdin updates (#402)
* New translations en.json (Polish)

[ci skip]

* New translations en.json (Romanian)

[ci skip]

* New translations en.json (French)

[ci skip]

* New translations en.json (Spanish)

[ci skip]

* New translations en.json (Belarusian)

[ci skip]

* New translations en.json (Catalan)

[ci skip]

* New translations en.json (Czech)

[ci skip]

* New translations en.json (Danish)

[ci skip]

* New translations en.json (German)

[ci skip]

* New translations en.json (Greek)

[ci skip]

* New translations en.json (Basque)

[ci skip]

* New translations en.json (Finnish)

[ci skip]

* New translations en.json (Hebrew)

[ci skip]

* New translations en.json (Italian)

[ci skip]

* New translations en.json (Korean)

[ci skip]

* New translations en.json (Lithuanian)

[ci skip]

* New translations en.json (Dutch)

[ci skip]

* New translations en.json (Norwegian)

[ci skip]

* New translations en.json (Portuguese)

[ci skip]

* New translations en.json (Russian)

[ci skip]

* New translations en.json (Swedish)

[ci skip]

* New translations en.json (Turkish)

[ci skip]

* New translations en.json (Ukrainian)

[ci skip]

* New translations en.json (Chinese Simplified)

[ci skip]

* New translations en.json (Vietnamese)

[ci skip]

* New translations en.json (Portuguese, Brazilian)

[ci skip]

* New translations en.json (Indonesian)

[ci skip]

* New translations en.json (Thai)

[ci skip]

* New translations en.json (Latvian)

[ci skip]

* New translations en.json (Chinese Traditional, Hong Kong)

[ci skip]

* New translations en.json (Serbian (Latin))

[ci skip]

* New translations files-and-stats.mdx (Romanian)

[ci skip]

* New translations files-and-stats.mdx (French)

[ci skip]

* New translations files-and-stats.mdx (Spanish)

[ci skip]

* New translations files-and-stats.mdx (Belarusian)

[ci skip]

* New translations files-and-stats.mdx (Catalan)

[ci skip]

* New translations files-and-stats.mdx (Czech)

[ci skip]

* New translations files-and-stats.mdx (Danish)

[ci skip]

* New translations files-and-stats.mdx (German)

[ci skip]

* New translations files-and-stats.mdx (Greek)

[ci skip]

* New translations files-and-stats.mdx (Basque)

[ci skip]

* New translations files-and-stats.mdx (Finnish)

[ci skip]

* New translations files-and-stats.mdx (Hebrew)

[ci skip]

* New translations files-and-stats.mdx (Hungarian)

[ci skip]

* New translations files-and-stats.mdx (Italian)

[ci skip]

* New translations files-and-stats.mdx (Korean)

[ci skip]

* New translations files-and-stats.mdx (Lithuanian)

[ci skip]

* New translations files-and-stats.mdx (Dutch)

[ci skip]

* New translations files-and-stats.mdx (Norwegian)

[ci skip]

* New translations files-and-stats.mdx (Polish)

[ci skip]

* New translations files-and-stats.mdx (Portuguese)

[ci skip]

* New translations files-and-stats.mdx (Russian)

[ci skip]

* New translations files-and-stats.mdx (Swedish)

[ci skip]

* New translations files-and-stats.mdx (Turkish)

[ci skip]

* New translations files-and-stats.mdx (Ukrainian)

[ci skip]

* New translations files-and-stats.mdx (Chinese Simplified)

[ci skip]

* New translations files-and-stats.mdx (Vietnamese)

[ci skip]

* New translations files-and-stats.mdx (Portuguese, Brazilian)

[ci skip]

* New translations files-and-stats.mdx (Indonesian)

[ci skip]

* New translations files-and-stats.mdx (Thai)

[ci skip]

* New translations files-and-stats.mdx (Latvian)

[ci skip]

* New translations files-and-stats.mdx (Chinese Traditional, Hong Kong)

[ci skip]

* New translations files-and-stats.mdx (Serbian (Latin))

[ci skip]
2026-10-31 18:53:31 +01:00
169 changed files with 5214 additions and 2449 deletions

No files matched your search

-67
View File
@@ -1,67 +0,0 @@
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 }}
+21 -29
View File
@@ -1,11 +1,21 @@
name: Deploy to GitHub Pages name: Deploy to Cloudflare Pages
on: on:
push: push:
branches: 'main' branches: ['main', 'dev']
workflow_dispatch:
concurrency:
group: cloudflare-${{ github.ref }}
cancel-in-progress: true
jobs: jobs:
build_site: deploy:
runs-on: ubuntu-latest runs-on: ubuntu-latest
permissions:
contents: read
deployments: write
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v5 uses: actions/checkout@v5
@@ -41,35 +51,17 @@ jobs:
run: npm test --prefix website run: npm test --prefix website
- name: Create env file - name: Create env file
run: | run: echo PUBLIC_MAPTILER_KEY=${{ secrets.PUBLIC_MAPTILER_KEY }} >> website/.env
touch website/.env
echo PUBLIC_MAPTILER_KEY=${{ secrets.PUBLIC_MAPTILER_KEY }} >> website/.env
cat website/.env
- name: Build website - name: Build website
env: env:
BASE_PATH: '' BASE_PATH: ''
run: | run: npm run build --prefix website
npm run build --prefix website
- name: Upload Artifacts - name: Deploy to Cloudflare Pages
uses: actions/upload-pages-artifact@v4 uses: cloudflare/wrangler-action@v3
with: with:
path: 'website/build/' apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
deploy: command: pages deploy website/build --project-name=${{ vars.CLOUDFLARE_PROJECT_NAME || 'gpxstudio' }} --branch=${{ github.ref_name }} --commit-dirty=true
needs: build_site gitHubToken: ${{ secrets.GITHUB_TOKEN }}
runs-on: ubuntu-latest
permissions:
pages: write
id-token: write
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- name: Deploy
id: deployment
uses: actions/deploy-pages@v4
+214
View File
@@ -0,0 +1,214 @@
name: Desktop release
# run by hand: from `main` for a release, from `dev` for a pre-release
on:
workflow_dispatch:
concurrency:
group: desktop-${{ github.ref }}
jobs:
# the release stays a draft until every platform is built and tested
prepare:
runs-on: ubuntu-latest
permissions:
contents: write
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
outputs:
version: ${{ steps.version.outputs.version }}
draft_tag: ${{ steps.version.outputs.draft_tag }}
release_id: ${{ steps.draft.outputs.release_id }}
steps:
- name: Checkout
uses: actions/checkout@v5
- name: Choose version
id: version
run: |
base=$(jq -r .version tauri/tauri.conf.json)
if [[ ! "$base" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "::error::The version in tauri.conf.json should be x.y.z, not $base"
exit 1
fi
case "$GITHUB_REF_NAME" in
main)
version=$base
draft_tag=desktop-v$base
if git ls-remote --exit-code --tags origin "refs/tags/$draft_tag"; then
echo "::error::$draft_tag is already released: bump the version in tauri.conf.json"
exit 1
fi
if [ -z "$(jq -r '.plugins.updater.pubkey' tauri/tauri.conf.json)" ]; then
echo "::error::The public key of the updater is missing from tauri.conf.json"
exit 1
fi
;;
dev)
version=$base-beta.$GITHUB_RUN_NUMBER
draft_tag=desktop-beta-$GITHUB_RUN_NUMBER
;;
*)
echo "::error::Desktop builds are made from main or dev, not $GITHUB_REF_NAME"
exit 1
;;
esac
echo "version=$version" >> "$GITHUB_OUTPUT"
echo "draft_tag=$draft_tag" >> "$GITHUB_OUTPUT"
- name: Create draft release
id: draft
env:
VERSION: ${{ steps.version.outputs.version }}
DRAFT_TAG: ${{ steps.version.outputs.draft_tag }}
run: |
# what a previous attempt left: this tag is not released, so it can only be a draft
gh release delete "$DRAFT_TAG" --yes || true
if [ "$GITHUB_REF_NAME" = main ]; then
gh release create "$DRAFT_TAG" --draft --target "$GITHUB_SHA" \
--title "Desktop $VERSION" --generate-notes
else
gh release create "$DRAFT_TAG" --draft --prerelease --target "$GITHUB_SHA" \
--title "Desktop beta $VERSION" \
--notes "Beta of the desktop app, built from $GITHUB_SHA on the dev branch. The builds are not signed yet: macOS and Windows will warn before opening them."
fi
echo "release_id=$(gh release view "$DRAFT_TAG" --json databaseId --jq .databaseId)" >> "$GITHUB_OUTPUT"
build:
needs: prepare
strategy:
fail-fast: false
matrix:
include:
- platform: macos-latest
rust_targets: aarch64-apple-darwin,x86_64-apple-darwin,wasm32-unknown-unknown
args: --target universal-apple-darwin
# the oldest supported Ubuntu, so that the AppImage runs on older systems too
- platform: ubuntu-22.04
rust_targets: wasm32-unknown-unknown
args: ''
- platform: windows-latest
rust_targets: wasm32-unknown-unknown
args: ''
runs-on: ${{ matrix.platform }}
permissions:
contents: write
steps:
- name: Checkout
uses: actions/checkout@v5
- name: Install Linux dependencies
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf
- name: Install Node.js
uses: actions/setup-node@v6
with:
node-version: 24
cache: npm
cache-dependency-path: website/package-lock.json
- name: Install Rust
uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.rust_targets }}
- name: Cache Rust build
uses: Swatinem/rust-cache@v2
- name: Install wasm-pack
uses: taiki-e/install-action@v2
with:
tool: wasm-pack
# the desktop app does not use it, but the website depends on its package
- name: Build wasm
run: wasm-pack build --target bundler
working-directory: wasm
- name: Install dependencies for website
run: npm install --prefix website
# the key would be readable in the app: it is left empty, so only the MapTiler layer fails
- name: Create env file
run: echo "PUBLIC_MAPTILER_KEY=" >> website/.env
# only the releases update themselves: they need the updater files, and the signing key
- name: Set version and updater files
shell: bash
env:
VERSION: ${{ needs.prepare.outputs.version }}
UPDATER: ${{ github.ref_name == 'main' }}
run: |
node -e "
const fs = require('fs');
const path = 'tauri/tauri.conf.json';
const config = JSON.parse(fs.readFileSync(path));
config.version = process.env.VERSION;
config.bundle.createUpdaterArtifacts = process.env.UPDATER === 'true';
fs.writeFileSync(path, JSON.stringify(config, null, 4));
"
- name: Build app and upload it to the draft
uses: tauri-apps/tauri-action@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_SIGNING_PRIVATE_KEY: ${{ github.ref_name == 'main' && secrets.TAURI_SIGNING_PRIVATE_KEY || '' }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ github.ref_name == 'main' && secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD || '' }}
with:
projectPath: tauri
tauriScript: npx --yes @tauri-apps/cli@2
args: ${{ matrix.args }}
releaseId: ${{ needs.prepare.outputs.release_id }}
# given with the id for the addresses in `latest.json`
tagName: ${{ needs.prepare.outputs.draft_tag }}
uploadUpdaterJson: ${{ github.ref_name == 'main' }}
# after the build, which gives the app the website it embeds
- name: Test engine and app
run: cargo test -p gpx-engine -p gpx-studio-desktop
# `releases/latest`, which the updater reads, only changes here
publish:
needs: [prepare, build]
runs-on: ubuntu-latest
permissions:
contents: write
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
DRAFT_TAG: ${{ needs.prepare.outputs.draft_tag }}
steps:
# the builds of the platforms add themselves to it in parallel, and could overwrite each other
- name: Check updater file
if: github.ref_name == 'main'
run: |
gh release download "$DRAFT_TAG" --pattern latest.json
for platform in darwin-aarch64 darwin-x86_64 linux-x86_64 windows-x86_64; do
if ! jq -e --arg platform "$platform" '.platforms[$platform].signature | length > 0' latest.json; then
echo "::error::latest.json has no signed update for $platform"
exit 1
fi
done
- name: Publish release
if: github.ref_name == 'main'
run: gh release edit "$DRAFT_TAG" --draft=false --latest
- name: Replace beta release
if: github.ref_name == 'dev'
run: |
gh release delete desktop-beta --cleanup-tag --yes || true
gh release edit "$DRAFT_TAG" --tag desktop-beta --draft=false --prerelease --latest=false
Generated
+516 -9
View File
@@ -475,6 +475,12 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
[[package]]
name = "cfg_aliases"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
[[package]] [[package]]
name = "chrono" name = "chrono"
version = "0.4.45" version = "0.4.45"
@@ -537,6 +543,16 @@ dependencies = [
"version_check", "version_check",
] ]
[[package]]
name = "core-foundation"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]] [[package]]
name = "core-foundation" name = "core-foundation"
version = "0.10.1" version = "0.10.1"
@@ -560,7 +576,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "064badf302c3194842cf2c5d61f56cc88e54a759313879cdf03abdd27d0c3b97" checksum = "064badf302c3194842cf2c5d61f56cc88e54a759313879cdf03abdd27d0c3b97"
dependencies = [ dependencies = [
"bitflags 2.13.2", "bitflags 2.13.2",
"core-foundation", "core-foundation 0.10.1",
"core-graphics-types", "core-graphics-types",
"foreign-types", "foreign-types",
"libc", "libc",
@@ -573,7 +589,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb" checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb"
dependencies = [ dependencies = [
"bitflags 2.13.2", "bitflags 2.13.2",
"core-foundation", "core-foundation 0.10.1",
"libc", "libc",
] ]
@@ -1020,6 +1036,16 @@ dependencies = [
"rustc_version", "rustc_version",
] ]
[[package]]
name = "filetime"
version = "0.2.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759"
dependencies = [
"cfg-if",
"libc",
]
[[package]] [[package]]
name = "find-msvc-tools" name = "find-msvc-tools"
version = "0.1.12" version = "0.1.12"
@@ -1287,6 +1313,17 @@ dependencies = [
"version_check", "version_check",
] ]
[[package]]
name = "getrandom"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
dependencies = [
"cfg-if",
"libc",
"wasi",
]
[[package]] [[package]]
name = "getrandom" name = "getrandom"
version = "0.3.4" version = "0.3.4"
@@ -1306,8 +1343,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"js-sys",
"libc", "libc",
"r-efi 6.0.0", "r-efi 6.0.0",
"wasm-bindgen",
] ]
[[package]] [[package]]
@@ -1431,7 +1470,9 @@ dependencies = [
"tauri-build", "tauri-build",
"tauri-plugin-dialog", "tauri-plugin-dialog",
"tauri-plugin-opener", "tauri-plugin-opener",
"tauri-plugin-process",
"tauri-plugin-single-instance", "tauri-plugin-single-instance",
"tauri-plugin-updater",
"trash", "trash",
"uuid", "uuid",
] ]
@@ -1631,6 +1672,21 @@ dependencies = [
"want", "want",
] ]
[[package]]
name = "hyper-rustls"
version = "0.27.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53"
dependencies = [
"http",
"hyper",
"hyper-util",
"rustls",
"tokio",
"tokio-rustls",
"tower-service",
]
[[package]] [[package]]
name = "hyper-util" name = "hyper-util"
version = "0.1.21" version = "0.1.21"
@@ -1650,9 +1706,11 @@ dependencies = [
"percent-encoding", "percent-encoding",
"pin-project-lite", "pin-project-lite",
"socket2", "socket2",
"system-configuration",
"tokio", "tokio",
"tower-service", "tower-service",
"tracing", "tracing",
"windows-registry",
] ]
[[package]] [[package]]
@@ -1990,6 +2048,36 @@ dependencies = [
"windows-sys 0.45.0", "windows-sys 0.45.0",
] ]
[[package]]
name = "jni"
version = "0.22.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498"
dependencies = [
"cfg-if",
"combine",
"jni-macros",
"jni-sys 0.4.1",
"log",
"simd_cesu8",
"thiserror 2.0.21",
"walkdir",
"windows-link",
]
[[package]]
name = "jni-macros"
version = "0.22.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3"
dependencies = [
"proc-macro2",
"quote",
"rustc_version",
"simd_cesu8",
"syn 2.0.118",
]
[[package]] [[package]]
name = "jni-sys" name = "jni-sys"
version = "0.3.1" version = "0.3.1"
@@ -2214,6 +2302,12 @@ dependencies = [
"walkdir", "walkdir",
] ]
[[package]]
name = "minisign-verify"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "871285dc19d8d0ebe0eef3d0e99a205f2a71363b122632cbbfa4a6c370a960ce"
[[package]] [[package]]
name = "miniz_oxide" name = "miniz_oxide"
version = "0.8.9" version = "0.8.9"
@@ -2303,6 +2397,18 @@ version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
[[package]]
name = "nix"
version = "0.31.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d"
dependencies = [
"bitflags 2.13.2",
"cfg-if",
"cfg_aliases",
"libc",
]
[[package]] [[package]]
name = "notify" name = "notify"
version = "8.2.0" version = "8.2.0"
@@ -2529,6 +2635,18 @@ dependencies = [
"objc2-core-foundation", "objc2-core-foundation",
] ]
[[package]]
name = "objc2-osa-kit"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f112d1746737b0da274ef79a23aac283376f335f4095a083a267a082f21db0c0"
dependencies = [
"bitflags 2.13.2",
"objc2",
"objc2-app-kit",
"objc2-foundation",
]
[[package]] [[package]]
name = "objc2-quartz-core" name = "objc2-quartz-core"
version = "0.3.2" version = "0.3.2"
@@ -2609,6 +2727,12 @@ dependencies = [
"libc", "libc",
] ]
[[package]]
name = "openssl-probe"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1"
[[package]] [[package]]
name = "option-ext" name = "option-ext"
version = "0.2.0" version = "0.2.0"
@@ -2625,6 +2749,20 @@ dependencies = [
"pin-project-lite", "pin-project-lite",
] ]
[[package]]
name = "osakit"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "732c71caeaa72c065bb69d7ea08717bd3f4863a4f451402fc9513e29dbd5261b"
dependencies = [
"objc2",
"objc2-foundation",
"objc2-osa-kit",
"serde",
"serde_json",
"thiserror 2.0.21",
]
[[package]] [[package]]
name = "pango" name = "pango"
version = "0.18.3" version = "0.18.3"
@@ -3049,15 +3187,20 @@ dependencies = [
"http-body", "http-body",
"http-body-util", "http-body-util",
"hyper", "hyper",
"hyper-rustls",
"hyper-util", "hyper-util",
"js-sys", "js-sys",
"log", "log",
"percent-encoding", "percent-encoding",
"pin-project-lite", "pin-project-lite",
"rustls",
"rustls-pki-types",
"rustls-platform-verifier",
"serde", "serde",
"serde_json", "serde_json",
"sync_wrapper", "sync_wrapper",
"tokio", "tokio",
"tokio-rustls",
"tokio-util", "tokio-util",
"tower", "tower",
"tower-http", "tower-http",
@@ -3093,6 +3236,20 @@ dependencies = [
"windows-sys 0.60.2", "windows-sys 0.60.2",
] ]
[[package]]
name = "ring"
version = "0.17.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
dependencies = [
"cc",
"cfg-if",
"getrandom 0.2.17",
"libc",
"untrusted",
"windows-sys 0.52.0",
]
[[package]] [[package]]
name = "rustc-hash" name = "rustc-hash"
version = "2.1.3" version = "2.1.3"
@@ -3121,6 +3278,79 @@ dependencies = [
"windows-sys 0.61.2", "windows-sys 0.61.2",
] ]
[[package]]
name = "rustls"
version = "0.23.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
dependencies = [
"once_cell",
"ring",
"rustls-pki-types",
"rustls-webpki",
"subtle",
"zeroize",
]
[[package]]
name = "rustls-native-certs"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4"
dependencies = [
"openssl-probe",
"rustls-pki-types",
"schannel",
"security-framework",
]
[[package]]
name = "rustls-pki-types"
version = "1.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"
dependencies = [
"zeroize",
]
[[package]]
name = "rustls-platform-verifier"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98"
dependencies = [
"core-foundation 0.10.1",
"core-foundation-sys",
"jni 0.22.4",
"log",
"once_cell",
"rustls",
"rustls-native-certs",
"rustls-platform-verifier-android",
"rustls-webpki",
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.61.2",
]
[[package]]
name = "rustls-platform-verifier-android"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f"
[[package]]
name = "rustls-webpki"
version = "0.103.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281"
dependencies = [
"ring",
"rustls-pki-types",
"untrusted",
]
[[package]] [[package]]
name = "rustversion" name = "rustversion"
version = "1.0.23" version = "1.0.23"
@@ -3136,6 +3366,15 @@ dependencies = [
"winapi-util", "winapi-util",
] ]
[[package]]
name = "schannel"
version = "0.1.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5"
dependencies = [
"windows-sys 0.61.2",
]
[[package]] [[package]]
name = "schemars" name = "schemars"
version = "0.8.22" version = "0.8.22"
@@ -3193,6 +3432,29 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "security-framework"
version = "3.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"
dependencies = [
"bitflags 2.13.2",
"core-foundation 0.10.1",
"core-foundation-sys",
"libc",
"security-framework-sys",
]
[[package]]
name = "security-framework-sys"
version = "2.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]] [[package]]
name = "selectors" name = "selectors"
version = "0.38.0" version = "0.38.0"
@@ -3425,6 +3687,22 @@ version = "0.3.10"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
[[package]]
name = "simd_cesu8"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520"
dependencies = [
"rustc_version",
"simdutf8",
]
[[package]]
name = "simdutf8"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"
[[package]] [[package]]
name = "siphasher" name = "siphasher"
version = "1.0.4" version = "1.0.4"
@@ -3546,6 +3824,12 @@ version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "subtle"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]] [[package]]
name = "swift-rs" name = "swift-rs"
version = "1.0.9" version = "1.0.9"
@@ -3609,6 +3893,27 @@ dependencies = [
"syn 3.0.6", "syn 3.0.6",
] ]
[[package]]
name = "system-configuration"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b"
dependencies = [
"bitflags 2.13.2",
"core-foundation 0.9.4",
"system-configuration-sys",
]
[[package]]
name = "system-configuration-sys"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]] [[package]]
name = "system-deps" name = "system-deps"
version = "6.2.2" version = "6.2.2"
@@ -3630,7 +3935,7 @@ checksum = "f37f381f4e048e6cdf038b5705f8cf14ad108279d46eb968140a7b291aba9400"
dependencies = [ dependencies = [
"bitflags 2.13.2", "bitflags 2.13.2",
"block2", "block2",
"core-foundation", "core-foundation 0.10.1",
"core-graphics", "core-graphics",
"crossbeam-channel", "crossbeam-channel",
"dbus", "dbus",
@@ -3640,7 +3945,7 @@ dependencies = [
"gdkwayland-sys", "gdkwayland-sys",
"gdkx11-sys", "gdkx11-sys",
"gtk", "gtk",
"jni", "jni 0.21.1",
"libc", "libc",
"log", "log",
"ndk", "ndk",
@@ -3673,6 +3978,17 @@ dependencies = [
"syn 2.0.118", "syn 2.0.118",
] ]
[[package]]
name = "tar"
version = "0.4.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840"
dependencies = [
"filetime",
"libc",
"xattr",
]
[[package]] [[package]]
name = "target-lexicon" name = "target-lexicon"
version = "0.12.16" version = "0.12.16"
@@ -3696,7 +4012,7 @@ dependencies = [
"gtk", "gtk",
"heck 0.5.0", "heck 0.5.0",
"http", "http",
"jni", "jni 0.21.1",
"libc", "libc",
"log", "log",
"mime", "mime",
@@ -3872,6 +4188,16 @@ dependencies = [
"zbus", "zbus",
] ]
[[package]]
name = "tauri-plugin-process"
version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "74ae3d8549ae564c0397377373e262f340908eb23a5b9fbe03f2a00007dc0038"
dependencies = [
"tauri",
"tauri-plugin",
]
[[package]] [[package]]
name = "tauri-plugin-single-instance" name = "tauri-plugin-single-instance"
version = "2.5.3" version = "2.5.3"
@@ -3888,6 +4214,40 @@ dependencies = [
"zbus", "zbus",
] ]
[[package]]
name = "tauri-plugin-updater"
version = "2.14.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d957abbcb3f9f6c76d22a3a0f012f30880640d0bccb5634d2b12a9937e4c872b"
dependencies = [
"base64 0.23.1",
"dirs",
"flate2",
"futures-util",
"http",
"infer",
"libc",
"log",
"minisign-verify",
"osakit",
"percent-encoding",
"reqwest",
"rustls",
"semver",
"serde",
"serde_json",
"tar",
"tauri",
"tauri-plugin",
"tempfile",
"thiserror 2.0.21",
"time",
"tokio",
"url",
"windows-sys 0.61.2",
"zip",
]
[[package]] [[package]]
name = "tauri-runtime" name = "tauri-runtime"
version = "2.12.1" version = "2.12.1"
@@ -3898,7 +4258,7 @@ dependencies = [
"dpi", "dpi",
"gtk", "gtk",
"http", "http",
"jni", "jni 0.21.1",
"objc2", "objc2",
"objc2-ui-kit", "objc2-ui-kit",
"objc2-web-kit", "objc2-web-kit",
@@ -3921,7 +4281,7 @@ checksum = "7f9e7e0c9f80a5130773cfabb6df4dc924518fb1b2c923726966804634b57d22"
dependencies = [ dependencies = [
"gtk", "gtk",
"http", "http",
"jni", "jni 0.21.1",
"log", "log",
"objc2", "objc2",
"objc2-app-kit", "objc2-app-kit",
@@ -4110,6 +4470,16 @@ dependencies = [
"windows-sys 0.61.2", "windows-sys 0.61.2",
] ]
[[package]]
name = "tokio-rustls"
version = "0.26.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db"
dependencies = [
"rustls",
"tokio",
]
[[package]] [[package]]
name = "tokio-util" name = "tokio-util"
version = "0.7.20" version = "0.7.20"
@@ -4341,6 +4711,12 @@ version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
[[package]]
name = "typed-path"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e"
[[package]] [[package]]
name = "typeid" name = "typeid"
version = "1.0.3" version = "1.0.3"
@@ -4376,6 +4752,12 @@ version = "1.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
[[package]]
name = "untrusted"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
[[package]] [[package]]
name = "url" name = "url"
version = "2.5.8" version = "2.5.8"
@@ -4675,6 +5057,15 @@ dependencies = [
"system-deps", "system-deps",
] ]
[[package]]
name = "webpki-root-certs"
version = "1.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a"
dependencies = [
"rustls-pki-types",
]
[[package]] [[package]]
name = "webview2-com" name = "webview2-com"
version = "0.39.1" version = "0.39.1"
@@ -4839,6 +5230,17 @@ dependencies = [
"windows-link", "windows-link",
] ]
[[package]]
name = "windows-registry"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720"
dependencies = [
"windows-link",
"windows-result",
"windows-strings",
]
[[package]] [[package]]
name = "windows-result" name = "windows-result"
version = "0.4.1" version = "0.4.1"
@@ -4866,6 +5268,15 @@ dependencies = [
"windows-targets 0.42.2", "windows-targets 0.42.2",
] ]
[[package]]
name = "windows-sys"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
dependencies = [
"windows-targets 0.52.6",
]
[[package]] [[package]]
name = "windows-sys" name = "windows-sys"
version = "0.60.2" version = "0.60.2"
@@ -4899,6 +5310,22 @@ dependencies = [
"windows_x86_64_msvc 0.42.2", "windows_x86_64_msvc 0.42.2",
] ]
[[package]]
name = "windows-targets"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
dependencies = [
"windows_aarch64_gnullvm 0.52.6",
"windows_aarch64_msvc 0.52.6",
"windows_i686_gnu 0.52.6",
"windows_i686_gnullvm 0.52.6",
"windows_i686_msvc 0.52.6",
"windows_x86_64_gnu 0.52.6",
"windows_x86_64_gnullvm 0.52.6",
"windows_x86_64_msvc 0.52.6",
]
[[package]] [[package]]
name = "windows-targets" name = "windows-targets"
version = "0.53.5" version = "0.53.5"
@@ -4909,7 +5336,7 @@ dependencies = [
"windows_aarch64_gnullvm 0.53.1", "windows_aarch64_gnullvm 0.53.1",
"windows_aarch64_msvc 0.53.1", "windows_aarch64_msvc 0.53.1",
"windows_i686_gnu 0.53.1", "windows_i686_gnu 0.53.1",
"windows_i686_gnullvm", "windows_i686_gnullvm 0.53.1",
"windows_i686_msvc 0.53.1", "windows_i686_msvc 0.53.1",
"windows_x86_64_gnu 0.53.1", "windows_x86_64_gnu 0.53.1",
"windows_x86_64_gnullvm 0.53.1", "windows_x86_64_gnullvm 0.53.1",
@@ -4940,6 +5367,12 @@ version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8"
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
[[package]] [[package]]
name = "windows_aarch64_gnullvm" name = "windows_aarch64_gnullvm"
version = "0.53.1" version = "0.53.1"
@@ -4952,6 +5385,12 @@ version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
[[package]] [[package]]
name = "windows_aarch64_msvc" name = "windows_aarch64_msvc"
version = "0.53.1" version = "0.53.1"
@@ -4964,12 +5403,24 @@ version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f"
[[package]]
name = "windows_i686_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
[[package]] [[package]]
name = "windows_i686_gnu" name = "windows_i686_gnu"
version = "0.53.1" version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3"
[[package]]
name = "windows_i686_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
[[package]] [[package]]
name = "windows_i686_gnullvm" name = "windows_i686_gnullvm"
version = "0.53.1" version = "0.53.1"
@@ -4982,6 +5433,12 @@ version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060"
[[package]]
name = "windows_i686_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
[[package]] [[package]]
name = "windows_i686_msvc" name = "windows_i686_msvc"
version = "0.53.1" version = "0.53.1"
@@ -4994,6 +5451,12 @@ version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36"
[[package]]
name = "windows_x86_64_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
[[package]] [[package]]
name = "windows_x86_64_gnu" name = "windows_x86_64_gnu"
version = "0.53.1" version = "0.53.1"
@@ -5006,6 +5469,12 @@ version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
[[package]] [[package]]
name = "windows_x86_64_gnullvm" name = "windows_x86_64_gnullvm"
version = "0.53.1" version = "0.53.1"
@@ -5018,6 +5487,12 @@ version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]] [[package]]
name = "windows_x86_64_msvc" name = "windows_x86_64_msvc"
version = "0.53.1" version = "0.53.1"
@@ -5082,7 +5557,7 @@ dependencies = [
"gtk", "gtk",
"http", "http",
"javascriptcore-rs", "javascriptcore-rs",
"jni", "jni 0.21.1",
"libc", "libc",
"ndk", "ndk",
"objc2", "objc2",
@@ -5129,6 +5604,16 @@ dependencies = [
"pkg-config", "pkg-config",
] ]
[[package]]
name = "xattr"
version = "1.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"
dependencies = [
"libc",
"rustix",
]
[[package]] [[package]]
name = "yoke" name = "yoke"
version = "0.8.3" version = "0.8.3"
@@ -5243,6 +5728,12 @@ dependencies = [
"synstructure", "synstructure",
] ]
[[package]]
name = "zeroize"
version = "1.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"
[[package]] [[package]]
name = "zerotrie" name = "zerotrie"
version = "0.2.5" version = "0.2.5"
@@ -5276,6 +5767,22 @@ dependencies = [
"syn 3.0.6", "syn 3.0.6",
] ]
[[package]]
name = "zip"
version = "9.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eaeb7f16d2605b49aef586996ded29e65642fab7259a3077e537351df6d80426"
dependencies = [
"crc32fast",
"getrandom 0.4.3",
"indexmap 2.14.2",
"libc",
"memchr",
"nix",
"typed-path",
"windows-sys 0.61.2",
]
[[package]] [[package]]
name = "zlib-rs" name = "zlib-rs"
version = "0.6.8" version = "0.6.8"
+23
View File
@@ -52,6 +52,18 @@ npm install
npm run dev npm run dev
``` ```
### Testing
Each part has its own tests:
```bash
cargo test # the engine (gpx-rs), from the root of the repository
(cd wasm && wasm-pack test --node) # the WebAssembly bindings
npm test --prefix website # the website, once the WebAssembly engine is built
```
See [`tauri`](tauri/README.md) for the tests of the desktop app.
## Credits ## Credits
This project has been made possible thanks to the following open source projects: This project has been made possible thanks to the following open source projects:
@@ -59,6 +71,7 @@ This project has been made possible thanks to the following open source projects
- Development: - Development:
- [Svelte](https://github.com/sveltejs/svelte) and [SvelteKit](https://github.com/sveltejs/kit) — seamless development experience - [Svelte](https://github.com/sveltejs/svelte) and [SvelteKit](https://github.com/sveltejs/kit) — seamless development experience
- [MDsveX](https://github.com/pngwn/MDsveX) — allowing a Markdown-based documentation - [MDsveX](https://github.com/pngwn/MDsveX) — allowing a Markdown-based documentation
- [Tauri](https://github.com/tauri-apps/tauri) – making a desktop app possible
- Design: - Design:
- [shadcn-svelte](https://github.com/huntabyte/shadcn-svelte) — beautiful components - [shadcn-svelte](https://github.com/huntabyte/shadcn-svelte) — beautiful components
- [@lucide/svelte](https://github.com/lucide-icons/lucide/tree/main/packages/svelte) — beautiful icons - [@lucide/svelte](https://github.com/lucide-icons/lucide/tree/main/packages/svelte) — beautiful icons
@@ -74,6 +87,16 @@ This project has been made possible thanks to the following open source projects
- Search: - Search:
- [DocSearch](https://github.com/algolia/docsearch) — search engine for the documentation - [DocSearch](https://github.com/algolia/docsearch) — search engine for the documentation
## Integration
There are several ways to integrate **gpx.studio** into your website or tools:
- **Embedding**: show your GPX files on an interactive map in your website. See the [documentation](https://gpx.studio/help/integration) to configure the map and generate the HTML code.
- **Map object**: `window._map` gives access to the [MapLibre GL JS](https://maplibre.org/maplibre-gl-js/docs/) map instance.
- **Extension API**: `window.gpxstudio` lets browser extensions add map overlays that appear in the layer menu like built-in ones. See [`extension-api.ts`](website/src/lib/components/map/layer-control/extension-api.ts) for the reference.
To be notified about changes that may affect your integration, subscribe to [this discussion](https://github.com/gpxstudio/gpx.studio/discussions/410).
## License ## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
-20
View File
@@ -560,26 +560,6 @@ impl WaypointDetails {
} }
} }
#[derive(Serialize)]
pub struct TrackpointDetails {
lng: f64,
lat: f64,
ele: f64,
#[serde(skip_serializing_if = "Option::is_none")]
time: Option<f64>,
}
impl TrackpointDetails {
pub fn new(pt: &engine::Trackpoint) -> Self {
Self {
lng: pt.coordinates.lng,
lat: pt.coordinates.lat,
ele: pt.ele,
time: pt.time.map(|t| t as f64),
}
}
}
/// A trackpoint of the selection: what the statistics buffers do not hold for each trackpoint. /// A trackpoint of the selection: what the statistics buffers do not hold for each trackpoint.
/// Absent fields are unknown. /// Absent fields are unknown.
#[derive(Serialize)] #[derive(Serialize)]
-12
View File
@@ -63,18 +63,6 @@ pub fn waypoint<H: History>(
.map(WaypointDetails::new) .map(WaypointDetails::new)
} }
/// A trackpoint of a segment of a file, `None` if it does not exist.
pub fn trackpoint<H: History>(
engine: &Engine<H>,
file_id: Uuid,
segment_id: Uuid,
index: usize,
) -> Option<TrackpointDetails> {
engine
.trackpoint(&FileId(file_id), &engine::TrackSegmentId(segment_id), index)
.map(TrackpointDetails::new)
}
/// A file as GPX (UTF-8 bytes), `None` if it does not exist. The options say which data of the /// A file as GPX (UTF-8 bytes), `None` if it does not exist. The options say which data of the
/// trackpoints to keep. /// trackpoints to keep.
pub fn export_file<H: History>( pub fn export_file<H: History>(
+37 -5
View File
@@ -44,14 +44,24 @@ where
let last = trkseg.last_index().unwrap(); let last = trkseg.last_index().unwrap();
let mut kept = vec![(first, None)]; let mut kept = vec![(first, None)];
ramer_douglas_peucker_helper(trkseg, first, last, measure, epsilon, &mut kept); ramer_douglas_peucker_ranges(trkseg, first, last, measure, epsilon, &mut kept);
kept.push((last, None)); kept.push((last, None));
kept kept
} }
} }
} }
fn ramer_douglas_peucker_helper<M>( /// What is left to do for the points between two ends, in the order of the points.
enum Step {
/// Looks for the point to keep between these two.
Range(TrackSegmentIndex, TrackSegmentIndex),
/// Keeps a point, selected at this distance.
Keep(TrackSegmentIndex, f64),
}
/// Adds the points to keep between `start` and `end` to `kept`, in order. It does not recurse: a
/// track can make it go as deep as it has points, which would overflow the stack.
fn ramer_douglas_peucker_ranges<M>(
trkseg: &TrackSegment, trkseg: &TrackSegment,
start: TrackSegmentIndex, start: TrackSegmentIndex,
end: TrackSegmentIndex, end: TrackSegmentIndex,
@@ -61,6 +71,16 @@ fn ramer_douglas_peucker_helper<M>(
) where ) where
M: Fn(TrackSegmentIndex, TrackSegmentIndex, TrackSegmentIndex) -> f64, M: Fn(TrackSegmentIndex, TrackSegmentIndex, TrackSegmentIndex) -> f64,
{ {
let mut steps = vec![Step::Range(start, end)];
while let Some(step) = steps.pop() {
let (start, end) = match step {
Step::Keep(idx, dist) => {
kept.push((idx, Some(dist)));
continue;
}
Step::Range(start, end) => (start, end),
};
let mut max_idx = None; let mut max_idx = None;
let mut max_dist = 0.0; let mut max_dist = 0.0;
@@ -80,9 +100,11 @@ fn ramer_douglas_peucker_helper<M>(
} }
if let Some(idx) = max_idx.filter(|_| max_dist > epsilon) { if let Some(idx) = max_idx.filter(|_| max_dist > epsilon) {
ramer_douglas_peucker_helper(trkseg, start, idx, measure, epsilon, kept); // the last one pushed is done first
kept.push((idx, Some(max_dist))); steps.push(Step::Range(idx, end));
ramer_douglas_peucker_helper(trkseg, idx, end, measure, epsilon, kept); steps.push(Step::Keep(idx, max_dist));
steps.push(Step::Range(start, idx));
}
} }
} }
@@ -195,6 +217,16 @@ mod tests {
.collect() .collect()
} }
#[test]
fn test_goes_as_deep_as_the_segment_is_long_in_order() {
let n = 12_000;
let trkseg = segment(&vec![0.0; n]);
// the point before the end is always the farthest one, so each range only loses one point
let kept = ramer_douglas_peucker_by(&trkseg, &|_, _, idx| idx.flat as f64 + 1.0, 0.5);
let kept: Vec<usize> = kept.iter().map(|(idx, _)| idx.flat).collect();
assert_eq!(kept, (0..n).collect::<Vec<_>>());
}
#[test] #[test]
fn test_empty_and_single_point() { fn test_empty_and_single_point() {
assert!(simplify(&[], 1.0).is_empty()); assert!(simplify(&[], 1.0).is_empty());
+213 -9
View File
@@ -3,11 +3,11 @@ use crate::{
TrackpointCategories, TrackpointChunk, Waypoint, WaypointChunk, distance, TrackpointCategories, TrackpointChunk, Waypoint, WaypointChunk, distance,
}; };
use chrono::DateTime; use chrono::DateTime;
use quick_xml::Error;
use quick_xml::escape::resolve_predefined_entity; use quick_xml::escape::resolve_predefined_entity;
use quick_xml::events::Event; use quick_xml::events::Event;
use quick_xml::events::attributes::Attributes; use quick_xml::events::attributes::{Attribute, Attributes};
use quick_xml::reader::Reader; use quick_xml::reader::Reader;
use quick_xml::{Error, XmlVersion};
enum GPXElement { enum GPXElement {
Metadata, Metadata,
@@ -37,6 +37,8 @@ enum GPXElement {
Symbol, Symbol,
Type, Type,
Color, Color,
/// The color of a track or a route in the Garmin extensions (`gpxx:DisplayColor`).
DisplayColor,
Opacity, Opacity,
Width, Width,
} }
@@ -58,6 +60,50 @@ fn is_route_point_extension(name: &str) -> bool {
name == "rpt" || name.ends_with(":rpt") name == "rpt" || name.ends_with(":rpt")
} }
/// The color of a track (`RRGGBB`, the format of the style schema) and its opacity, from a color
/// that may start with `#` and may have an alpha channel first (`AARRGGBB`), as some applications
/// write it. A color in any other format is kept as it is, without opacity.
fn parse_color(value: &str) -> (String, Option<f64>) {
let value = value.trim();
let hex = value.strip_prefix('#').unwrap_or(value);
if !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
return (value.to_owned(), None);
}
match hex.len() {
6 => (hex.to_owned(), None),
8 => {
let alpha = u8::from_str_radix(&hex[..2], 16).unwrap_or(u8::MAX);
let opacity = (f64::from(alpha) / 255.0 * 100.0).round() / 100.0;
(hex[2..].to_owned(), Some(opacity))
}
_ => (value.to_owned(), None),
}
}
/// The hexadecimal color of a value of `DisplayColor_t` in the Garmin extensions. None for
/// `Transparent` and for what is not part of the schema.
fn garmin_display_color(name: &str) -> Option<&'static str> {
match name.trim() {
"Black" => Some("000000"),
"DarkRed" => Some("800000"),
"DarkGreen" => Some("008000"),
"DarkYellow" => Some("808000"),
"DarkBlue" => Some("000080"),
"DarkMagenta" => Some("800080"),
"DarkCyan" => Some("008080"),
"LightGray" => Some("c0c0c0"),
"DarkGray" => Some("808080"),
"Red" => Some("ff0000"),
"Green" => Some("00ff00"),
"Yellow" => Some("ffff00"),
"Blue" => Some("0000ff"),
"Magenta" => Some("ff00ff"),
"Cyan" => Some("00ffff"),
"White" => Some("ffffff"),
_ => None,
}
}
/// Whether the element holds a value, which is its text. /// Whether the element holds a value, which is its text.
fn holds_text(element: Option<&GPXElement>) -> bool { fn holds_text(element: Option<&GPXElement>) -> bool {
matches!( matches!(
@@ -81,6 +127,7 @@ fn holds_text(element: Option<&GPXElement>) -> bool {
| GPXElement::Symbol | GPXElement::Symbol
| GPXElement::Type | GPXElement::Type
| GPXElement::Color | GPXElement::Color
| GPXElement::DisplayColor
| GPXElement::Opacity | GPXElement::Opacity
| GPXElement::Width | GPXElement::Width
) )
@@ -166,16 +213,21 @@ fn apply_text(
} }
Some(GPXElement::Time) => { Some(GPXElement::Time) => {
stack.pop(); stack.pop();
if let Some(GPXElement::Trackpoint(trkpt)) = stack.last_mut() { let time = DateTime::parse_from_rfc3339(e)
trkpt.time = DateTime::parse_from_rfc3339(e)
.ok() .ok()
.map(|time| time.timestamp_millis()); .map(|time| time.timestamp_millis());
match stack.last_mut() {
Some(GPXElement::Trackpoint(trkpt)) => trkpt.time = time,
Some(GPXElement::Waypoint(wpt)) => wpt.time = time,
Some(GPXElement::Metadata) => gpx.info.time = time,
_ => (),
} }
} }
Some(GPXElement::Temperature) => { Some(GPXElement::Temperature) => {
stack.pop(); stack.pop();
if let Some(GPXElement::Trackpoint(trkpt)) = stack.last_mut() { if let Some(GPXElement::Trackpoint(trkpt)) = stack.last_mut() {
trkpt.atemp = e.parse().ok(); // Garmin Connect writes whole degrees as "21.0"
trkpt.atemp = e.parse::<f64>().ok().map(|t| t.round() as i16);
} }
} }
Some(GPXElement::Heartrate) => { Some(GPXElement::Heartrate) => {
@@ -241,7 +293,21 @@ fn apply_text(
Some(GPXElement::Color) => { Some(GPXElement::Color) => {
stack.pop(); stack.pop();
if let Some(GPXElement::Track(trk)) = stack.last_mut() { if let Some(GPXElement::Track(trk)) = stack.last_mut() {
trk.info.color = Some(e.to_owned()); let (color, opacity) = parse_color(e);
trk.info.color = Some(color);
// The opacity of the style schema has priority, wherever it is in the extensions
if trk.info.opacity.is_none() {
trk.info.opacity = opacity;
}
}
}
// The color of the style schema has priority, wherever it is in the extensions
Some(GPXElement::DisplayColor) => {
stack.pop();
if let Some(GPXElement::Track(trk)) = stack.last_mut()
&& trk.info.color.is_none()
{
trk.info.color = garmin_display_color(e).map(str::to_owned);
} }
} }
Some(GPXElement::Opacity) => { Some(GPXElement::Opacity) => {
@@ -260,6 +326,13 @@ fn apply_text(
} }
} }
/// The text of an attribute, without its escaping (`&amp;` is `&`), which is written back when the
/// file is. As it is in the file if it cannot be read.
fn attribute_text(attr: &Attribute<'_>) -> String {
attr.normalized_value(XmlVersion::Implicit1_0)
.map_or_else(|_| attr.value.to_string(), |text| text.into_owned())
}
/// The email of the author, given as the `id` and `domain` attributes of the element. /// The email of the author, given as the `id` and `domain` attributes of the element.
fn set_email(stack: &mut [GPXElement], attributes: Attributes<'_>) { fn set_email(stack: &mut [GPXElement], attributes: Attributes<'_>) {
let Some(GPXElement::Author(author)) = stack.last_mut() else { let Some(GPXElement::Author(author)) = stack.last_mut() else {
@@ -268,8 +341,8 @@ fn set_email(stack: &mut [GPXElement], attributes: Attributes<'_>) {
let (mut id, mut domain) = (None, None); let (mut id, mut domain) = (None, None);
for attr in attributes.flatten() { for attr in attributes.flatten() {
match attr.key.as_ref() { match attr.key.as_ref() {
"id" => id = Some(attr.value.to_string()), "id" => id = Some(attribute_text(&attr)),
"domain" => domain = Some(attr.value.to_string()), "domain" => domain = Some(attribute_text(&attr)),
_ => (), _ => (),
} }
} }
@@ -283,7 +356,7 @@ fn parse_link(attributes: Attributes<'_>) -> Link {
let mut link = Link::default(); let mut link = Link::default();
for attr in attributes.flatten() { for attr in attributes.flatten() {
if attr.key.as_ref() == "href" { if attr.key.as_ref() == "href" {
link.href = attr.value.to_string(); link.href = attribute_text(&attr);
} }
} }
link link
@@ -448,6 +521,7 @@ pub fn parse(data: &[u8], categories: &mut TrackpointCategories) -> Result<File,
"sym" => stack.push(GPXElement::Symbol), "sym" => stack.push(GPXElement::Symbol),
"type" => stack.push(GPXElement::Type), "type" => stack.push(GPXElement::Type),
e if e.ends_with("color") => stack.push(GPXElement::Color), e if e.ends_with("color") => stack.push(GPXElement::Color),
e if e.ends_with("DisplayColor") => stack.push(GPXElement::DisplayColor),
e if e.ends_with("opacity") => stack.push(GPXElement::Opacity), e if e.ends_with("opacity") => stack.push(GPXElement::Opacity),
e if e.ends_with("width") => stack.push(GPXElement::Width), e if e.ends_with("width") => stack.push(GPXElement::Width),
_ => (), _ => (),
@@ -626,6 +700,14 @@ mod tests {
.unwrap() .unwrap()
} }
#[test]
fn test_link_href_is_unescaped_and_written_back_once() {
let data =
r#"<gpx><metadata><link href="https://a.example/?x=1&amp;y=2"/></metadata></gpx>"#;
let gpx = parse(data.as_bytes(), &mut Default::default()).unwrap();
assert_eq!(gpx.info.links[0].href, "https://a.example/?x=1&y=2");
}
#[test] #[test]
fn test_parse_entities_and_cdata_in_text() { fn test_parse_entities_and_cdata_in_text() {
let data = r#"<gpx><metadata><name>Tom &amp; Jerry &lt;3 &#233;&#x41; &quot;x&quot; &apos;y&apos;</name> let data = r#"<gpx><metadata><name>Tom &amp; Jerry &lt;3 &#233;&#x41; &quot;x&quot; &apos;y&apos;</name>
@@ -1065,6 +1147,20 @@ mod tests {
assert!(wpt.type_.as_ref().is_some_and(|t| t == "Bike Trail")); assert!(wpt.type_.as_ref().is_some_and(|t| t == "Bike Trail"));
} }
#[test]
fn test_parse_waypoint_time() {
let data = r#"<gpx><wpt lat="1" lon="2"><time>2024-05-01T06:10:00Z</time></wpt></gpx>"#;
let gpx = parse(data.as_bytes(), &mut Default::default()).unwrap();
assert_eq!(gpx.wpt[0].time, Some(1714543800000));
}
#[test]
fn test_parse_metadata_time() {
let data = r#"<gpx><metadata><time>2024-05-01T06:10:00Z</time></metadata></gpx>"#;
let gpx = parse(data.as_bytes(), &mut Default::default()).unwrap();
assert_eq!(gpx.info.time, Some(1714543800000));
}
#[test] #[test]
fn test_parse_trackpoint_time() { fn test_parse_trackpoint_time() {
let gpx = parse_data("with_time"); let gpx = parse_data("with_time");
@@ -1248,6 +1344,14 @@ mod tests {
assert!(trkpt.atemp.is_some_and(|t| t == 21)); assert!(trkpt.atemp.is_some_and(|t| t == 21));
} }
#[test]
fn test_parse_trackpoint_decimal_atemp() {
let data = r#"<gpx><trk><trkseg><trkpt lat="1" lon="2"><extensions><gpxtpx:TrackPointExtension>
<gpxtpx:atemp>21.0</gpxtpx:atemp></gpxtpx:TrackPointExtension></extensions></trkpt></trkseg></trk></gpx>"#;
let gpx = parse(data.as_bytes(), &mut Default::default()).unwrap();
assert_eq!(gpx.trk[0].trkseg[0][0].atemp, Some(21));
}
#[test] #[test]
fn test_parse_track_style() { fn test_parse_track_style() {
let gpx = parse_data("with_style"); let gpx = parse_data("with_style");
@@ -1259,4 +1363,104 @@ mod tests {
assert!(trk.info.opacity.is_some_and(|o| o == 0.5)); assert!(trk.info.opacity.is_some_and(|o| o == 0.5));
assert!(trk.info.width.is_some_and(|w| w == 6.0)); assert!(trk.info.width.is_some_and(|w| w == 6.0));
} }
fn parse_text(text: &str) -> File {
parse(text.as_bytes(), &mut Default::default()).unwrap()
}
#[test]
fn test_parse_garmin_display_color_of_tracks_and_routes() {
let gpx = parse_text(
r#"<gpx xmlns:gpxx="http://www.garmin.com/xmlschemas/GpxExtensions/v3"
xmlns:gpxtrx="http://www.garmin.com/xmlschemas/GpxExtensions/v3">
<trk><extensions><gpxx:TrackExtension>
<gpxx:DisplayColor>Blue</gpxx:DisplayColor>
</gpxx:TrackExtension></extensions></trk>
<trk><extensions><gpxtrx:TrackExtension>
<gpxtrx:DisplayColor>DarkRed</gpxtrx:DisplayColor>
</gpxtrx:TrackExtension></extensions></trk>
<rte><extensions><gpxx:RouteExtension>
<gpxx:DisplayColor>Green</gpxx:DisplayColor>
</gpxx:RouteExtension></extensions></rte>
</gpx>"#,
);
assert_eq!(gpx.trk[0].info.color.as_deref(), Some("0000ff"));
assert_eq!(gpx.trk[1].info.color.as_deref(), Some("800000"));
assert_eq!(gpx.rte[0].info.color.as_deref(), Some("00ff00"));
}
#[test]
fn test_garmin_display_color_without_a_color_leaves_the_track_uncolored() {
let gpx = parse_text(
r#"<gpx>
<trk><extensions><gpxx:TrackExtension>
<gpxx:DisplayColor>Transparent</gpxx:DisplayColor>
</gpxx:TrackExtension></extensions></trk>
<trk><extensions><gpxx:TrackExtension>
<gpxx:DisplayColor>Mauve</gpxx:DisplayColor>
</gpxx:TrackExtension></extensions></trk>
</gpx>"#,
);
assert_eq!(gpx.trk[0].info.color, None);
assert_eq!(gpx.trk[1].info.color, None);
}
#[test]
fn test_style_color_has_priority_over_garmin_display_color() {
let gpx = parse_text(
r#"<gpx>
<trk><extensions>
<gpxx:TrackExtension><gpxx:DisplayColor>Red</gpxx:DisplayColor></gpxx:TrackExtension>
<gpx_style:line><gpx_style:color>2d3ee9</gpx_style:color></gpx_style:line>
</extensions></trk>
<trk><extensions>
<gpx_style:line><gpx_style:color>2d3ee9</gpx_style:color></gpx_style:line>
<gpxx:TrackExtension><gpxx:DisplayColor>Red</gpxx:DisplayColor></gpxx:TrackExtension>
</extensions></trk>
</gpx>"#,
);
assert_eq!(gpx.trk[0].info.color.as_deref(), Some("2d3ee9"));
assert_eq!(gpx.trk[1].info.color.as_deref(), Some("2d3ee9"));
}
#[test]
fn test_parse_color_with_hash_and_alpha() {
assert_eq!(parse_color("2d3ee9"), ("2d3ee9".into(), None));
assert_eq!(parse_color("#0000FF"), ("0000FF".into(), None));
assert_eq!(parse_color("#800000FF"), ("0000FF".into(), Some(0.5)));
assert_eq!(parse_color("FF0000FF"), ("0000FF".into(), Some(1.0)));
assert_eq!(parse_color("#00ff0000"), ("ff0000".into(), Some(0.0)));
assert_eq!(parse_color("red"), ("red".into(), None));
assert_eq!(parse_color("#abc"), ("#abc".into(), None));
}
#[test]
fn test_parse_track_color_with_alpha() {
let gpx = parse_text(
r#"<gpx>
<trk><extensions><xsi:gpx>
<physicalColor>#400000FF</physicalColor>
<width>4</width>
<color>#800000FF</color>
</xsi:gpx></extensions></trk>
<trk><extensions><gpx_style:line>
<gpx_style:opacity>0.3</gpx_style:opacity>
<gpx_style:color>#800000FF</gpx_style:color>
</gpx_style:line></extensions></trk>
<trk><extensions><gpx_style:line>
<gpx_style:color>#800000FF</gpx_style:color>
<gpx_style:opacity>0.3</gpx_style:opacity>
</gpx_style:line></extensions></trk>
</gpx>"#,
);
assert_eq!(gpx.trk[0].info.color.as_deref(), Some("0000FF"));
assert_eq!(gpx.trk[0].info.opacity, Some(0.5));
assert_eq!(gpx.trk[0].info.width, Some(4.0));
assert_eq!(gpx.trk[1].info.opacity, Some(0.3));
assert_eq!(gpx.trk[2].info.opacity, Some(0.3));
}
} }
-8
View File
@@ -24,14 +24,6 @@ pub struct Statistics {
} }
impl Statistics { impl Statistics {
pub fn total_speed(&self) -> Option<f64> {
self.global.total_speed()
}
pub fn moving_speed(&self) -> Option<f64> {
self.global.moving_speed()
}
pub fn compute(trkseg: &TrackSegment) -> Self { pub fn compute(trkseg: &TrackSegment) -> Self {
let mut stats = Self::default(); let mut stats = Self::default();
if trkseg.is_empty() { if trkseg.is_empty() {
@@ -36,6 +36,7 @@ impl StatisticsCache {
} }
/// Statistics of the segments of the selection. /// Statistics of the segments of the selection.
#[cfg(test)]
pub fn get<'a>( pub fn get<'a>(
&'a self, &'a self,
state: Option<&'a Files>, state: Option<&'a Files>,
+1 -17
View File
@@ -11,7 +11,7 @@ pub use outcome::*;
pub use state::*; pub use state::*;
use crate::{ use crate::{
ExportOptions, FileId, GlobalStatistics, Restored, Snapshot, TrackSegmentId, Trackpoint, ExportOptions, FileId, GlobalStatistics, Restored, Snapshot, TrackSegmentId,
TrackpointCategories, Waypoint, WaypointId, reduction_distances, write, TrackpointCategories, Waypoint, WaypointId, reduction_distances, write,
}; };
@@ -82,22 +82,6 @@ impl<H: History> Engine<H> {
.find(|wpt| wpt.id == *id) .find(|wpt| wpt.id == *id)
} }
/// A trackpoint of a segment (of a route or a track) of a file. `None` if it does not exist.
pub fn trackpoint(
&self,
file_id: &FileId,
segment_id: &TrackSegmentId,
index: usize,
) -> Option<&Trackpoint> {
let segment = self
.history
.current()?
.get(file_id)?
.segments()
.find(|seg| seg.id == *segment_id)?;
(index < segment.len()).then(|| &segment[index])
}
/// For each trackpoint of the selection (numbered as in the statistics), the tolerance up to /// For each trackpoint of the selection (numbered as in the statistics), the tolerance up to
/// which `Reduce` keeps it, see [`reduction_distances`]. /// which `Reduce` keeps it, see [`reduction_distances`].
pub fn reduction_distances(&self) -> Vec<f64> { pub fn reduction_distances(&self) -> Vec<f64> {
-18
View File
@@ -1169,24 +1169,6 @@ fn test_categories_are_shared_and_kept_by_the_history() {
assert_eq!(expand(&engine.statistics().surface, 5), [1, 1, 0, 2, 2]); assert_eq!(expand(&engine.statistics().surface, 5), [1, 1, 0, 2, 2]);
} }
#[test]
fn test_trackpoint() {
let mut engine = TestEngine::default();
load(&mut engine, "data/simple.gpx");
let file = engine.order()[0];
let structure = engine.file_structure(&file).unwrap();
let seg = &structure.tracks[0].segments[0];
let (seg_id, len) = (seg.id, seg.len);
let coordinates = engine.segment_coordinates(&seg_id).to_vec();
let last = engine.trackpoint(&file, &seg_id, len - 1).unwrap();
assert_eq!(
[last.coordinates.lng, last.coordinates.lat],
coordinates[(len - 1) * 2..]
);
assert!(engine.trackpoint(&file, &seg_id, len).is_none());
assert!(engine.trackpoint(&Default::default(), &seg_id, 0).is_none());
}
#[test] #[test]
fn test_export_writes_the_file_as_it_is() { fn test_export_writes_the_file_as_it_is() {
let mut engine = TestEngine::default(); let mut engine = TestEngine::default();
+5 -3
View File
@@ -1,9 +1,9 @@
use std::cell::RefCell; use std::cell::RefCell;
use std::collections::HashMap; use std::collections::HashMap;
use crate::{ #[cfg(test)]
Batch, ChunkKey, ChunkKind, CommitError, FileId, Revision, Storage, StorageError, StoredData, use crate::ChunkKind;
}; use crate::{Batch, ChunkKey, CommitError, FileId, Revision, Storage, StorageError, StoredData};
/// A storage that lives as long as the session. It is what an engine without a host storage uses, /// A storage that lives as long as the session. It is what an engine without a host storage uses,
/// and what the tests use. /// and what the tests use.
@@ -22,6 +22,7 @@ struct State {
} }
/// How much there is in a storage. /// How much there is in a storage.
#[cfg(test)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StorageCounts { pub struct StorageCounts {
pub files: usize, pub files: usize,
@@ -29,6 +30,7 @@ pub struct StorageCounts {
pub waypoint_chunks: usize, pub waypoint_chunks: usize,
} }
#[cfg(test)]
impl MemoryStorage { impl MemoryStorage {
/// How many files and chunks are stored. /// How many files and chunks are stored.
pub fn counts(&self) -> StorageCounts { pub fn counts(&self) -> StorageCounts {
+13
View File
@@ -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"] }
@@ -28,3 +37,7 @@ tauri-plugin-single-instance = "2.5.3"
tauri-plugin-opener = "2" tauri-plugin-opener = "2"
trash = "5" trash = "5"
[target.'cfg(any(target_os = "macos", windows, target_os = "linux"))'.dependencies]
tauri-plugin-process = "2.4.0"
tauri-plugin-updater = "2.14.1"
+38
View File
@@ -0,0 +1,38 @@
# tauri
The desktop app of gpx.studio, built with [Tauri 2](https://v2.tauri.app/).
Its UI is the website ([`../website`](../website)), and it runs the engine of [`../gpx-rs`](../gpx-rs) natively instead of in WebAssembly.
## Development
You will need the same tools as for the website: [Node.js](https://nodejs.org/), [Rust](https://rustup.rs/) and [wasm-pack](https://rustwasm.github.io/wasm-pack/).
To run the app in development mode, you will also need to install the [system dependencies of Tauri](https://v2.tauri.app/start/prerequisites/) for your platform and the Tauri CLI:
```bash
cargo install tauri-cli --version "^2"
```
### Setting up the frontend
The desktop app does not use the WebAssembly engine, but the website depends on its package.
From the root of the repository, build it once and install the website’s dependencies:
```bash
cd wasm && wasm-pack build --target bundler && cd ..
npm install --prefix website
```
For the MapTiler layers, add your key to `website/.env`, as explained in the [main README](../README.md#running-the-website).
### Running the app
```bash
cd tauri
cargo tauri dev
```
### Testing
```bash
cargo test -p gpx-studio-desktop
```
+17
View File
@@ -1,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()
} }
+1 -1
View File
@@ -3,5 +3,5 @@
"identifier": "default", "identifier": "default",
"description": "Permissions for the main window", "description": "Permissions for the main window",
"windows": ["main"], "windows": ["main"],
"permissions": ["core:default"] "permissions": ["core:default", "updater:default", "process:allow-restart"]
} }
-10
View File
@@ -57,16 +57,6 @@ pub fn waypoint(
state.read(move |e| api::waypoint(e, file_id, waypoint_id)) state.read(move |e| api::waypoint(e, file_id, waypoint_id))
} }
#[tauri::command(async)]
pub fn trackpoint(
state: State<AppState>,
file_id: Uuid,
segment_id: Uuid,
index: usize,
) -> Option<api::TrackpointDetails> {
state.read(move |e| api::trackpoint(e, file_id, segment_id, index))
}
/// A file as GPX (UTF-8 bytes), the first byte telling whether the file exists. /// A file as GPX (UTF-8 bytes), the first byte telling whether the file exists.
#[tauri::command(async)] #[tauri::command(async)]
#[allow(clippy::too_many_arguments)] #[allow(clippy::too_many_arguments)]
+12 -10
View File
@@ -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)
@@ -55,6 +55,12 @@ pub fn run() {
.plugin(tauri_plugin_dialog::init()) .plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_opener::init()) .plugin(tauri_plugin_opener::init())
.setup(|app| { .setup(|app| {
#[cfg(desktop)]
{
app.handle()
.plugin(tauri_plugin_updater::Builder::new().build())?;
app.handle().plugin(tauri_plugin_process::init())?;
}
let handle = app.handle().clone(); let handle = app.handle().clone();
let emit: state::Emit = std::sync::Arc::new(move |event, payload| { let emit: state::Emit = std::sync::Arc::new(move |event, payload| {
let _ = handle.emit(event, payload); let _ = handle.emit(event, payload);
@@ -108,7 +114,7 @@ fn menu<R: tauri::Runtime>(app: &tauri::AppHandle<R>) -> tauri::Result<tauri::me
} }
/// Gives the builder the commands that reach the engine (which it has to be given as `AppState`). /// 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,
@@ -167,7 +173,6 @@ fn register_commands<R: tauri::Runtime>(builder: tauri::Builder<R>) -> tauri::Bu
queries::can_redo, queries::can_redo,
queries::can_paste, queries::can_paste,
queries::waypoint, queries::waypoint,
queries::trackpoint,
queries::export_file, queries::export_file,
queries::exportable_data, queries::exportable_data,
queries::reduction_distances, queries::reduction_distances,
@@ -234,6 +239,3 @@ fn register_commands<R: tauri::Runtime>(builder: tauri::Builder<R>) -> tauri::Bu
system::reveal_path, system::reveal_path,
]) ])
} }
#[cfg(test)]
mod tests;
-7
View File
@@ -280,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));
-66
View File
@@ -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();
}
}
+2 -812
View File
@@ -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()) {
@@ -1040,813 +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]
.info
.name
.clone()
.unwrap_or_default()
}
fn rename(&mut self, id: Uuid, name: &str) {
api::select(&mut self.engine, &[id], SelectMode::Replace);
assert!(!api::metadata(&mut self.engine, name, "").has_error());
}
fn status(&self, id: Uuid) -> FileStatus {
self.workspace
.state(&self.engine)
.files
.remove(&id.to_string())
.unwrap()
}
}
impl Drop for Fixture {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.folder);
}
}
#[test]
fn an_opened_file_is_clean_until_it_is_edited_and_clean_again_once_saved() {
let mut fx = Fixture::new();
let path = fx.write("a.gpx", "a");
fx.workspace
.open_files(&mut fx.engine, std::slice::from_ref(&path), true);
let id = fx.ids()[0];
assert!(!fx.workspace.is_dirty(&fx.engine, id));
assert_eq!(fx.status(id).path.as_deref(), path.to_str());
fx.rename(id, "renamed");
assert!(fx.workspace.is_dirty(&fx.engine, id));
// nothing is written before it is saved
assert!(fs::read_to_string(&path).unwrap().contains(">a<"));
fx.save(&[id]);
assert!(!fx.workspace.is_dirty(&fx.engine, id));
assert!(fs::read_to_string(&path).unwrap().contains(">renamed<"));
// going back before the save is an edit again
api::select(&mut fx.engine, &[id], SelectMode::Replace);
api::undo(&mut fx.engine);
assert!(fx.workspace.is_dirty(&fx.engine, id));
api::redo(&mut fx.engine);
assert!(!fx.workspace.is_dirty(&fx.engine, id));
}
#[test]
fn a_file_that_is_not_on_the_disk_is_unsaved_until_it_is_given_a_place() {
let mut fx = Fixture::new();
api::new_file(&mut fx.engine, "fresh", None, None, None, false);
let id = fx.ids()[0];
assert!(fx.workspace.is_dirty(&fx.engine, id));
assert_eq!(
fx.workspace.unlinked(&fx.engine, &[id]),
[(id, "fresh".to_string())]
);
// nowhere to put it without being told
fx.save(&[id]);
assert!(fx.workspace.is_dirty(&fx.engine, id));
let path = fx.folder.join("fresh.gpx");
let paths = BTreeMap::from([(id, path.clone())]);
fx.workspace
.save(&mut fx.engine, &[id], &paths, None)
.unwrap();
assert!(path.exists());
assert!(!fx.workspace.is_dirty(&fx.engine, id));
assert!(fx.workspace.unlinked(&fx.engine, &[id]).is_empty());
}
#[test]
fn several_files_without_a_place_go_in_a_folder_with_names_that_are_free() {
let mut fx = Fixture::new();
fx.write("fresh.gpx", "already there");
api::new_file(&mut fx.engine, "fresh", None, None, None, false);
api::new_file(&mut fx.engine, "a/b: c", None, None, None, false);
api::new_file(&mut fx.engine, "fresh", None, None, None, false);
let ids = fx.ids();
let folder = fx.folder.clone();
fx.workspace
.save(&mut fx.engine, &ids, &BTreeMap::new(), Some(&folder))
.unwrap();
for name in ["fresh (2).gpx", "fresh (3).gpx", "a_b_ c.gpx"] {
assert!(fx.folder.join(name).exists(), "{name}");
}
assert!(ids.iter().all(|id| !fx.workspace.is_dirty(&fx.engine, *id)));
}
#[test]
fn what_this_app_writes_is_not_a_change_of_the_disk() {
let mut fx = Fixture::new();
let path = fx.write("a.gpx", "a");
fx.open_folder();
let id = fx.ids()[0];
api::select(&mut fx.engine, &[id], SelectMode::Replace);
assert!(!api::style(&mut fx.engine, Some("#ff0000"), None, None).has_error());
fx.save(&[id]);
assert!(fx.reconcile(Some(&[path])).is_none());
assert!(!fx.status(id).replaced && !fx.status(id).dirty);
}
#[test]
fn the_folders_of_the_files_outside_the_open_folder_are_watched_too() {
let mut fx = Fixture::new();
let inside = fx.write("in.gpx", "in");
let elsewhere = canonical(&std::env::temp_dir()).join(format!("gpx-ws-{}", Uuid::new_v4()));
fs::create_dir_all(&elsewhere).unwrap();
let (one, two) = (elsewhere.join("one.gpx"), elsewhere.join("two.gpx"));
fs::write(&one, gpx("one")).unwrap();
fs::write(&two, gpx("two")).unwrap();
let folder = fx.folder.clone();
// no folder: only the folder of the files
fx.workspace.open_files(&mut fx.engine, &[one, two], false);
assert_eq!(fx.workspace.watched(), [(elsewhere.clone(), false)]);
// the open folder as a whole, and the file in it needs nothing more
fx.workspace.open_folder(&mut fx.engine, &folder, false);
fx.workspace.open_files(&mut fx.engine, &[inside], false);
assert_eq!(
fx.workspace.watched(),
[(folder, true), (elsewhere.clone(), false)]
);
// closing the files stops it
let ids = fx.ids();
fx.workspace.close_files(&mut fx.engine, &ids, true);
assert_eq!(fx.workspace.watched(), [(fx.folder.clone(), true)]);
fs::remove_dir_all(elsewhere).unwrap();
}
#[test]
fn opening_a_folder_does_not_open_its_files() {
let mut fx = Fixture::new();
fx.write("a.gpx", "a");
let folder = fx.folder.clone();
let outcome = fx.workspace.open_folder(&mut fx.engine, &folder, false);
assert!(!outcome.changed);
assert!(fx.ids().is_empty());
assert_eq!(fx.workspace.folder.as_deref(), Some(folder.as_path()));
}
#[test]
fn folders_are_made_renamed_and_moved_and_the_open_files_follow() {
let mut fx = Fixture::new();
let a = fx.write("a.gpx", "a");
fx.open_folder();
let id = fx.ids()[0];
let root = fx.folder.clone();
let path_of = |fx: &Fixture| PathBuf::from(fx.status(id).path.unwrap());
let first = fx.workspace.create_folder(&root, "New folder").unwrap();
let second = fx.workspace.create_folder(&root, "New folder").unwrap();
assert_eq!(first, root.join("New folder"));
assert_eq!(second, root.join("New folder 2"));
fx.workspace.move_paths(&[a], &first).unwrap();
assert_eq!(path_of(&fx), first.join("a.gpx"));
assert!(first.join("a.gpx").exists() && !fx.status(id).dirty);
let trips = fx.workspace.rename_path(&first, "Trips").unwrap();
assert_eq!(path_of(&fx), root.join("Trips/a.gpx"));
// a folder does not go into itself, nor onto something else
assert!(
fx.workspace
.move_paths(std::slice::from_ref(&trips), &trips)
.is_err()
);
assert_eq!(
fx.workspace.rename_path(&trips, "New folder 2"),
Err(NAME_TAKEN.to_owned())
);
fx.workspace.move_paths(&[trips], &second).unwrap();
assert_eq!(path_of(&fx), second.join("Trips/a.gpx"));
// a file keeps its extension
let closed = fx.write("c.gpx", "c");
assert_eq!(
fx.workspace.rename_path(&closed, "d").unwrap(),
root.join("d.gpx")
);
// the open folder and what is not in it are left alone
assert!(fx.workspace.rename_path(&root, "x").is_err());
let elsewhere = canonical(&std::env::temp_dir());
assert!(fx.workspace.rename_path(&elsewhere, "x").is_err());
assert!(fx.workspace.create_folder(&elsewhere, "x").is_err());
}
#[test]
fn deleted_files_are_closed_unless_they_have_edits() {
let mut fx = Fixture::new();
let a = fx.write("a.gpx", "a");
let b = fx.write("b.gpx", "b");
fx.open_folder();
let (id_a, id_b) = (fx.id_named("a"), fx.id_named("b"));
api::select(&mut fx.engine, &[id_b], SelectMode::Replace);
assert!(!api::style(&mut fx.engine, Some("#ff0000"), None, None).has_error());
let outcome = fx
.workspace
.delete_paths(&mut fx.engine, &[a.clone(), b.clone()], |paths| {
paths.iter().for_each(|path| fs::remove_file(path).unwrap());
Ok(())
})
.unwrap();
assert!(outcome.changed);
assert_eq!(fx.ids(), [id_b]);
assert!(!fx.ids().contains(&id_a));
let status = fx.status(id_b);
assert!(status.dirty && status.missing);
assert!(!a.exists() && !b.exists());
}
#[test]
fn the_tree_of_the_folder_shows_folders_first_and_only_gpx_files() {
let mut fx = Fixture::new();
fx.write("b.gpx", "b");
fx.write("A.GPX", "a");
fx.write("b 10.gpx", "b 10");
fx.write("b 2.gpx", "b 2");
fx.write("notes.txt", "not a track");
fx.write(".hidden.gpx", "hidden");
fs::create_dir(fx.folder.join("zoo")).unwrap();
fs::create_dir(fx.folder.join("Alps")).unwrap();
fs::create_dir(fx.folder.join(".git")).unwrap();
fx.write("zoo/c.gpx", "c");
let folder = fx.folder.clone();
fx.workspace.open_folder(&mut fx.engine, &folder, false);
let names = |entries: Vec<Entry>| -> Vec<(String, bool)> {
entries.into_iter().map(|e| (e.name, e.is_dir)).collect()
};
assert_eq!(
names(fx.workspace.list_folder(&folder).unwrap()),
[
("Alps".to_string(), true),
("zoo".to_string(), true),
("A.GPX".to_string(), false),
("b.gpx".to_string(), false),
("b 2.gpx".to_string(), false),
("b 10.gpx".to_string(), false),
]
);
assert_eq!(
names(fx.workspace.list_folder(&folder.join("zoo")).unwrap()),
[("c.gpx".to_string(), false)]
);
// only what is in the open folder can be listed
let elsewhere = canonical(&std::env::temp_dir());
assert!(fx.workspace.list_folder(&elsewhere).is_err());
}
#[test]
fn names_are_sorted_by_the_numbers_they_hold() {
let mut names = vec![
"track 10",
"track 2",
"Track 1",
"track",
"track 02b",
"track 2a",
"b",
"A",
];
names.sort_by(|a, b| natural_cmp(a, b).then_with(|| a.cmp(b)));
assert_eq!(
names,
[
"A",
"b",
"track",
"Track 1",
"track 2",
"track 2a",
"track 02b",
"track 10",
]
);
}
#[test]
fn a_file_without_edits_is_read_again_when_the_disk_changes() {
let mut fx = Fixture::new();
let a = fx.write("a.gpx", "a");
fx.open_folder();
let id = fx.ids()[0];
fx.write("a.gpx", "theirs");
let outcome = fx.reconcile(Some(std::slice::from_ref(&a))).unwrap();
assert!(outcome.changed);
// the same file, now the one on the disk
assert_eq!(fx.ids(), [id]);
assert_eq!(fx.content(id), "theirs");
let status = fx.status(id);
assert!(!status.dirty && !status.replaced);
// looking again changes nothing
assert!(fx.reconcile(Some(std::slice::from_ref(&a))).is_none());
}
#[test]
fn a_file_with_edits_is_flagged_when_the_disk_changes_and_not_read_again() {
let mut fx = Fixture::new();
let a = fx.write("a.gpx", "a");
fx.open_folder();
let id = fx.ids()[0];
fx.rename(id, "mine");
fx.write("a.gpx", "theirs");
let outcome = fx.reconcile(Some(std::slice::from_ref(&a))).unwrap();
assert!(!outcome.changed);
assert_eq!(fx.name(id), "mine");
let status = fx.status(id);
assert!(status.dirty && status.replaced && !status.missing);
// looking again changes nothing
assert!(fx.reconcile(Some(std::slice::from_ref(&a))).is_none());
// the disk goes back to what was read: only the edits are left
fx.write("a.gpx", "a");
assert!(fx.reconcile(Some(std::slice::from_ref(&a))).is_some());
let status = fx.status(id);
assert!(status.dirty && !status.replaced);
}
#[test]
fn the_user_can_take_the_disk_instead_of_the_edits() {
let mut fx = Fixture::new();
fx.write("a.gpx", "a");
fx.open_folder();
let id = fx.ids()[0];
fx.rename(id, "mine");
fx.write("a.gpx", "theirs");
fx.reconcile(None);
assert!(fx.status(id).replaced);
fx.workspace.reload(&mut fx.engine, &[id]).unwrap();
assert_eq!(fx.content(id), "theirs");
let status = fx.status(id);
assert!(!status.dirty && !status.replaced);
// and it is one undo step
api::select(&mut fx.engine, &[id], SelectMode::Replace);
api::undo(&mut fx.engine);
assert_eq!(fx.content(id), "mine");
}
#[test]
fn saving_overwrites_what_replaced_the_file() {
let mut fx = Fixture::new();
let a = fx.write("a.gpx", "a");
fx.open_folder();
let id = fx.ids()[0];
fx.rename(id, "mine");
fx.write("a.gpx", "theirs");
fx.reconcile(None);
assert!(fx.status(id).replaced);
fx.save(&[id]);
assert!(fs::read_to_string(a).unwrap().contains(">mine<"));
assert!(!fx.status(id).replaced && !fx.status(id).dirty);
}
#[test]
fn a_file_that_is_gone_from_the_disk_stays_open_and_dirty_until_it_is_saved_again() {
let mut fx = Fixture::new();
let a = fx.write("a.gpx", "a");
fx.open_folder();
let id = fx.ids()[0];
fs::remove_file(&a).unwrap();
assert!(fx.reconcile(Some(std::slice::from_ref(&a))).is_some());
assert_eq!(fx.ids(), [id]);
let status = fx.status(id);
assert!(status.dirty && status.missing && status.path.is_some());
// saving puts it back
fx.save(&[id]);
assert!(a.exists());
let status = fx.status(id);
assert!(!status.dirty && !status.missing);
}
#[test]
fn a_file_that_comes_back_different_is_read_again() {
let mut fx = Fixture::new();
let a = fx.write("a.gpx", "a");
fx.open_folder();
let id = fx.ids()[0];
fs::remove_file(&a).unwrap();
fx.reconcile(None);
assert!(fx.status(id).missing);
fx.write("a.gpx", "back");
fx.reconcile(None);
assert_eq!(fx.content(id), "back");
let status = fx.status(id);
assert!(!status.dirty && !status.missing);
}
#[test]
fn what_changed_while_the_app_was_closed_is_found_when_it_starts() {
let mut fx = Fixture::new();
let a = fx.write("a.gpx", "a");
fx.open_folder();
let id = fx.ids()[0];
fx.write("a.gpx", "changed");
assert!(fx.reconcile(None).is_some());
assert_eq!(fx.content(id), "changed");
fs::remove_file(a).unwrap();
assert!(fx.reconcile(None).is_some());
assert!(fx.status(id).missing);
}
#[test]
fn new_files_made_from_a_file_of_the_folder_are_saved_next_to_it() {
let mut fx = Fixture::new();
fs::create_dir(fx.folder.join("sub")).unwrap();
fx.write("sub/b.gpx", "b");
fx.write("a.gpx", "a");
fx.open_folder();
let b = fx.id_named("b");
let sub = fx.folder.join("sub");
assert_eq!(fx.workspace.source_dir(&[b]), Some(canonical(&sub)));
let before = fx.ids();
api::select(&mut fx.engine, &[b], SelectMode::Replace);
let outcome = api::duplicate(&mut fx.engine);
let copy = fx
.ids()
.into_iter()
.find(|id| !before.contains(id))
.unwrap();
fx.workspace.inherit(outcome.added(), &canonical(&sub));
assert_eq!(fx.status(copy).folder.as_deref(), canonical(&sub).to_str());
assert!(fx.status(copy).path.is_none() && fx.status(copy).dirty);
// nobody needs to be asked where it goes
assert!(fx.workspace.unlinked(&fx.engine, &[copy]).is_empty());
fx.save(&[copy]);
assert!(sub.join("b (2).gpx").exists());
let status = fx.status(copy);
assert!(!status.dirty && status.folder.is_none());
assert_eq!(
status.path.as_deref(),
canonical(&sub.join("b (2).gpx")).to_str()
);
// the copy of the copy is next to it as well
assert_eq!(fx.workspace.source_dir(&[copy]), Some(canonical(&sub)));
}
#[test]
fn a_file_outside_the_open_folder_hands_nothing_down() {
let mut fx = Fixture::new();
let elsewhere = canonical(&std::env::temp_dir()).join(format!("gpx-ws-{}", Uuid::new_v4()));
fs::create_dir_all(&elsewhere).unwrap();
let outside = elsewhere.join("o.gpx");
fs::write(&outside, gpx("o")).unwrap();
let folder = fx.folder.clone();
fx.workspace.open_folder(&mut fx.engine, &folder, false);
fx.workspace
.open_files(&mut fx.engine, std::slice::from_ref(&outside), true);
let id = fx.ids()[0];
assert_eq!(fx.workspace.source_dir(&[id]), None);
// a new file with no source is not linked to a folder by `source_dir`: the caller falls back
fs::remove_dir_all(elsewhere).unwrap();
}
#[test]
fn closing_files_asks_what_to_do_with_the_unsaved_ones() {
let mut fx = Fixture::new();
fx.write("a.gpx", "a");
fx.write("b.gpx", "b");
fx.open_folder();
let (a, b) = (fx.id_named("a"), fx.id_named("b"));
fx.rename(a, "edited");
assert_eq!(fx.workspace.unsaved(&fx.engine, &[a, b]), [a]);
// without a choice what has edits stays
let outcome = fx.workspace.close_files(&mut fx.engine, &[a, b], false);
assert!(outcome.changed);
assert_eq!(fx.ids(), [a]);
// saved first
fx.save(&[a]);
fx.workspace.close_files(&mut fx.engine, &[a], false);
assert!(fx.ids().is_empty());
assert!(
fs::read_to_string(fx.folder.join("a.gpx"))
.unwrap()
.contains("edited")
);
assert!(fx.workspace.links.is_empty());
}
#[test]
fn closing_files_can_discard_their_edits() {
let mut fx = Fixture::new();
fx.write("a.gpx", "a");
fx.open_folder();
let a = fx.ids()[0];
fx.rename(a, "edited");
api::new_file(&mut fx.engine, "fresh", None, None, None, false);
let fresh = fx.id_named("fresh");
fx.workspace.close_files(&mut fx.engine, &[a, fresh], true);
assert!(fx.ids().is_empty());
assert!(
fs::read_to_string(fx.folder.join("a.gpx"))
.unwrap()
.contains(">a<")
);
}
#[test]
fn closing_the_folder_closes_every_file() {
let mut fx = Fixture::new();
fx.write("a.gpx", "a");
fx.open_folder();
api::new_file(&mut fx.engine, "fresh", None, None, None, false);
assert_eq!(fx.ids().len(), 2);
// the new file has nowhere to go: it has to be discarded
let outcome = fx.workspace.close_folder(&mut fx.engine, false);
assert!(outcome.changed);
assert_eq!(fx.ids().len(), 1);
assert!(fx.workspace.folder.is_none());
let outcome = fx.workspace.close_folder(&mut fx.engine, true);
assert!(outcome.changed);
assert!(fx.ids().is_empty());
}
#[test]
fn opening_another_folder_closes_the_first_with_all_its_files() {
let mut fx = Fixture::new();
fx.write("a.gpx", "a");
fx.open_folder();
let a = fx.ids()[0];
fx.rename(a, "edited");
let other = canonical(&std::env::temp_dir()).join(format!("gpx-ws-{}", Uuid::new_v4()));
fs::create_dir_all(&other).unwrap();
// the edits stay, nothing is lost without a choice
fx.workspace.open_folder(&mut fx.engine, &other, false);
assert_eq!(fx.ids(), [a]);
assert_eq!(fx.workspace.folder.as_deref(), Some(other.as_path()));
let first = fx.folder.clone();
fx.workspace.open_folder(&mut fx.engine, &first, true);
assert!(fx.ids().is_empty());
assert!(
fs::read_to_string(fx.folder.join("a.gpx"))
.unwrap()
.contains(">a<")
);
fs::remove_dir_all(other).unwrap();
}
#[test]
fn opening_the_same_folder_again_changes_nothing() {
let mut fx = Fixture::new();
fx.write("a.gpx", "a");
fx.open_folder();
let folder = fx.folder.clone();
let outcome = fx.workspace.open_folder(&mut fx.engine, &folder, true);
assert!(!outcome.changed);
assert_eq!(fx.ids().len(), 1);
}
#[test]
fn a_failed_save_stops_at_the_file_and_leaves_it_dirty() {
let mut fx = Fixture::new();
fx.write("a.gpx", "a");
fx.open_folder();
let id = fx.ids()[0];
fx.rename(id, "edited");
// the place of the file is taken by a folder
fs::remove_file(fx.folder.join("a.gpx")).unwrap();
fs::create_dir(fx.folder.join("a.gpx")).unwrap();
let result = fx
.workspace
.save(&mut fx.engine, &[id], &BTreeMap::new(), None);
assert!(result.is_err());
assert!(fx.workspace.is_dirty(&fx.engine, id));
}
#[test]
fn saving_as_gives_the_file_another_place() {
let mut fx = Fixture::new();
let a = fx.write("a.gpx", "a");
fx.write("b.gpx", "b");
fx.open_folder();
let id = fx.id_named("a");
let other = fx.id_named("b");
fx.rename(id, "edited");
let target = fx.folder.join("copy.gpx");
fx.workspace.save_as(&mut fx.engine, id, &target).unwrap();
assert!(fs::read_to_string(&target).unwrap().contains("edited"));
assert!(fs::read_to_string(a).unwrap().contains(">a<"));
let status = fx.status(id);
assert!(!status.dirty);
assert_eq!(status.path.as_deref(), canonical(&target).to_str());
// the place of another open file is not available
let taken = fx.folder.join("b.gpx");
assert!(fx.workspace.save_as(&mut fx.engine, id, &taken).is_err());
assert!(!fx.workspace.is_dirty(&fx.engine, other));
}
}
#[cfg(test)]
mod restart_tests {
use gpx_engine::Persister;
use super::*;
use crate::store::FileStorage;
/// What the app does when it starts again: the engine and the links are read from what was
/// kept.
fn restart(engine: &Engine, workspace: &Workspace, root: &Path) -> (Engine, Workspace) {
let storage = FileStorage::open(root).unwrap();
pollster::block_on(Persister::default().save(&storage, engine.snapshot())).unwrap();
let mut restarted = Engine::default();
let restored = pollster::block_on(Persister::default().restore(&storage)).unwrap();
restarted.restore(restored);
let links = serde_json::to_string(workspace).unwrap();
(restarted, serde_json::from_str(&links).unwrap())
}
fn setup() -> (PathBuf, Engine, Workspace, Vec<Uuid>) {
let root = std::env::temp_dir().join(format!("gpx-restart-{}", Uuid::new_v4()));
let folder = root.join("tracks");
fs::create_dir_all(&folder).unwrap();
for name in ["with_tracks", "with_time", "with_waypoint"] {
let _ = fs::copy(
format!("../gpx-rs/data/{name}.gpx"),
folder.join(format!("{name}.gpx")),
);
}
let mut engine = Engine::default();
let mut workspace = Workspace::default();
workspace.open_folder(&mut engine, &folder, false);
workspace.open_files(&mut engine, &tests::gpx_files(&folder), false);
let ids = engine.order().iter().map(|id| id.0).collect();
(root, engine, workspace, ids)
}
#[test]
fn files_that_were_not_edited_are_not_unsaved_after_a_restart() {
let (root, engine, workspace, ids) = setup();
assert!(ids.len() >= 2);
let (restarted, mut workspace) = restart(&engine, &workspace, &root.join("store"));
// the files are the same, but the engine knows their contents by new identities
assert!(ids.iter().any(|id| workspace.is_dirty(&restarted, *id)));
workspace.verify(&restarted);
assert!(ids.iter().all(|id| !workspace.is_dirty(&restarted, *id)));
fs::remove_dir_all(root).unwrap();
}
#[test]
fn files_that_were_edited_are_still_unsaved_after_a_restart() {
let (root, mut engine, workspace, ids) = setup();
api::select(&mut engine, &[ids[0]], gpx_engine::SelectMode::Replace);
api::metadata(&mut engine, "edited", "");
assert!(workspace.is_dirty(&engine, ids[0]));
let (restarted, mut workspace) = restart(&engine, &workspace, &root.join("store"));
workspace.verify(&restarted);
assert!(workspace.is_dirty(&restarted, ids[0]));
assert!(
ids[1..]
.iter()
.all(|id| !workspace.is_dirty(&restarted, *id))
);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn links_made_before_the_content_was_kept_are_checked_against_the_disk() {
let (root, mut engine, mut workspace, ids) = setup();
api::select(&mut engine, &[ids[0]], gpx_engine::SelectMode::Replace);
api::metadata(&mut engine, "edited", "");
for link in workspace.links.values_mut() {
link.export_hash = 0;
}
let (restarted, mut workspace) = restart(&engine, &workspace, &root.join("store"));
workspace.verify(&restarted);
assert!(workspace.is_dirty(&restarted, ids[0]));
assert!(
ids[1..]
.iter()
.all(|id| !workspace.is_dirty(&restarted, *id))
);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn the_folders_of_new_files_and_the_old_flag_name_survive_a_restart() {
let (root, engine, mut workspace, ids) = setup();
let folder = workspace.folder.clone().unwrap();
let fresh = Uuid::new_v4();
workspace.inherit(&[fresh.to_string()], &folder);
workspace.links.get_mut(&ids[0]).unwrap().replaced = true;
let json = serde_json::to_string(&workspace).unwrap();
// links written by the previous version had `conflict`, which is the same thing
let json = json.replace("\"replaced\"", "\"conflict\"");
assert!(json.contains("\"conflict\":true"));
let read: Workspace = serde_json::from_str(&json).unwrap();
assert!(read.links[&ids[0]].replaced);
assert_eq!(read.dirs.get(&fresh), Some(&folder));
let _ = engine;
fs::remove_dir_all(root).unwrap();
}
}
+10 -1
View File
@@ -27,7 +27,8 @@
}, },
"bundle": { "bundle": {
"active": true, "active": true,
"targets": "all", "targets": ["app", "dmg", "appimage", "deb", "rpm", "nsis"],
"macOS": { "signingIdentity": "-" },
"fileAssociations": [ "fileAssociations": [
{ {
"ext": ["gpx"], "ext": ["gpx"],
@@ -44,5 +45,13 @@
"icons/icon.icns", "icons/icon.icns",
"icons/icon.ico" "icons/icon.ico"
] ]
},
"plugins": {
"updater": {
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDE5NTFDQzVDOUYwNEMyNEMKUldSTXdnU2ZYTXhSR1ZXRDV6aVErc3dUWXBaK0VGSitYRnFFR21hZ2s5UEJTT01aYkE5Unp5c0cKdW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEFFNTU3Q0Y1NzhFODkyMTEKUldRUmt1aDQ5WHhWcmdXQmx0UG83V29TenRxSVJjdkc4ckN1Zi93ajc3ZUhVUVp3eFlCOXphb1IK",
"endpoints": [
"https://github.com/gpxstudio/gpx.studio/releases/latest/download/latest.json"
]
}
} }
} }
@@ -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(),
@@ -56,7 +65,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: InvokeBody::Json(args), body: InvokeBody::Json(args),
headers: Default::default(), headers: Default::default(),
invoke_key: INVOKE_KEY.to_string(), invoke_key: INVOKE_KEY.to_string(),
@@ -311,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()));
@@ -347,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()));
@@ -441,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());
@@ -461,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);
@@ -483,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();
@@ -516,19 +525,23 @@ fn files_made_from_a_file_of_the_open_folder_are_written_next_to_it_at_once() {
.collect(); .collect();
// the copy is in the subfolder, named after its name (the one in the file, not of the file) // the copy is in the subfolder, named after its name (the one in the file, not of the file)
assert!( assert!(
paths.iter().any(|path| path.ends_with("sub/simple.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();
@@ -649,7 +662,7 @@ fn a_file_keeps_its_name_and_its_file_is_renamed_apart() {
// the name of another file is not taken // the name of another file is not taken
let error = app.error("rename_file", json!({ "fileId": id, "name": "taken" })); let error = app.error("rename_file", json!({ "fileId": id, "name": "taken" }));
assert_eq!(error, crate::workspace::NAME_TAKEN); assert_eq!(error, gpx_studio_desktop_lib::workspace::NAME_TAKEN);
assert!(folder.join("moved.gpx").exists()); assert!(folder.join("moved.gpx").exists());
// a name is one that a file can have // a name is one that a file can have
+15
View File
@@ -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")
}
+69
View File
@@ -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();
}
+811
View File
@@ -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();
}
}
+14
View File
@@ -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
View File
@@ -26,6 +26,9 @@ thread_local! {
static PERSISTER: RefCell<Option<Persister>> = const { RefCell::new(None) }; static PERSISTER: RefCell<Option<Persister>> = const { RefCell::new(None) };
static SAVING: Cell<bool> = const { Cell::new(false) }; static SAVING: Cell<bool> = const { Cell::new(false) };
static DIRTY: Cell<bool> = const { Cell::new(false) }; static DIRTY: Cell<bool> = const { Cell::new(false) };
/// Whether the last write failed, or was not done because a newer version wrote the storage:
/// what the engine holds is then not all stored.
static NOT_WRITTEN: Cell<bool> = const { Cell::new(false) };
/// Resolve functions of the promises of `flush_storage`. /// Resolve functions of the promises of `flush_storage`.
/// Called after the files were written, and when a write was refused because they were /// Called after the files were written, and when a write was refused because they were
/// written by someone else since: see `open_storage`. /// written by someone else since: see `open_storage`.
@@ -73,20 +76,28 @@ pub(crate) fn schedule_save() {
let result = persister.save(&*storage, snapshot).await; let result = persister.save(&*storage, snapshot).await;
PERSISTER.with(|slot| *slot.borrow_mut() = Some(persister)); PERSISTER.with(|slot| *slot.borrow_mut() = Some(persister));
match result { match result {
Ok(()) => saved = true, Ok(()) => {
NOT_WRITTEN.set(false);
saved = true;
}
// nothing was written, so that the files of the other tab are not damaged: this // nothing was written, so that the files of the other tab are not damaged: this
// tab has to read them, which replaces what it did // tab has to read them, which replaces what it did
Err(engine::CommitError::Stale { .. }) => { Err(engine::CommitError::Stale { .. }) => {
NOT_WRITTEN.set(false);
DIRTY.set(false); DIRTY.set(false);
behind = true; behind = true;
} }
// nothing is written, so that the newer version finds its data again // nothing is written, so that the newer version finds its data again
Err(engine::CommitError::Failed(engine::StorageError::Newer)) => { Err(engine::CommitError::Failed(engine::StorageError::Newer)) => {
NOT_WRITTEN.set(true);
DIRTY.set(false); DIRTY.set(false);
newer = true; newer = true;
} }
// what failed is written with the next change // what failed is written with the next change
Err(error) => console_error(&error.to_string()), Err(error) => {
NOT_WRITTEN.set(true);
console_error(&error.to_string());
}
} }
} }
SAVING.set(false); SAVING.set(false);
@@ -188,17 +199,18 @@ pub(crate) fn to_js_error(error: engine::StorageError) -> JsValue {
JsValue::from_str(&error.to_string()) JsValue::from_str(&error.to_string())
} }
/// Resolves when what was changed has been written to the storage. /// Resolves when the writes of what was changed are done, to whether they went well. A write that
/// was refused because another tab wrote since is fine: this tab then reads what that tab wrote.
#[wasm_bindgen] #[wasm_bindgen]
pub async fn flush_storage() -> Result<(), JsValue> { pub async fn flush_storage() -> Result<bool, JsValue> {
if !SAVING.get() { if !SAVING.get() {
return Ok(()); return Ok(!NOT_WRITTEN.get());
} }
let promise = js_sys::Promise::new(&mut |resolve, _| { let promise = js_sys::Promise::new(&mut |resolve, _| {
WAITERS.with(|waiters| waiters.borrow_mut().push(resolve)); WAITERS.with(|waiters| waiters.borrow_mut().push(resolve));
}); });
wasm_bindgen_futures::JsFuture::from(promise).await?; wasm_bindgen_futures::JsFuture::from(promise).await?;
Ok(()) Ok(!NOT_WRITTEN.get())
} }
/// If another tab wrote the files since this one last did, reads them again and overwrites the /// If another tab wrote the files since this one last did, reads them again and overwrites the
-12
View File
@@ -101,18 +101,6 @@ pub fn waypoint(file_id: &str, waypoint_id: &str) -> WaypointDetails {
optional_js(details).unchecked_into() optional_js(details).unchecked_into()
} }
/// A trackpoint of a segment of a file, `undefined` if it does not exist.
#[wasm_bindgen]
pub fn trackpoint(file_id: &str, segment_id: &str, index: usize) -> TrackpointDetails {
let details =
parse_uuid(file_id)
.zip(parse_uuid(segment_id))
.and_then(|(file_id, segment_id)| {
with_engine(|e| api::trackpoint(e, file_id, segment_id, index)).flatten()
});
optional_js(details).unchecked_into()
}
/// What was copied or cut and is waiting to be pasted, `undefined` if nothing: the kind of the /// What was copied or cut and is waiting to be pasted, `undefined` if nothing: the kind of the
/// elements and their ids (UUID strings). /// elements and their ids (UUID strings).
#[wasm_bindgen] #[wasm_bindgen]
-10
View File
@@ -59,14 +59,6 @@ export interface WaypointDetails {
links?: { href: string; text?: string }[]; links?: { href: string; text?: string }[];
sym?: string; sym?: string;
} }
/** The position, elevation and time of a trackpoint. */
export interface TrackpointDetails {
lng: number;
lat: number;
ele: number;
/** ms since epoch */
time?: number;
}
/** /**
* A trackpoint of the selection: what the statistics buffers do not hold for each trackpoint. * A trackpoint of the selection: what the statistics buffers do not hold for each trackpoint.
* Absent fields are unknown. * Absent fields are unknown.
@@ -189,8 +181,6 @@ extern "C" {
pub type Selection; pub type Selection;
#[wasm_bindgen(typescript_type = "WaypointDetails | undefined")] #[wasm_bindgen(typescript_type = "WaypointDetails | undefined")]
pub type WaypointDetails; pub type WaypointDetails;
#[wasm_bindgen(typescript_type = "TrackpointDetails | undefined")]
pub type TrackpointDetails;
#[wasm_bindgen(typescript_type = "SelectionPoint | undefined")] #[wasm_bindgen(typescript_type = "SelectionPoint | undefined")]
pub type SelectionPoint; pub type SelectionPoint;
#[wasm_bindgen(typescript_type = "MoveTarget")] #[wasm_bindgen(typescript_type = "MoveTarget")]
+87 -53
View File
@@ -18,7 +18,7 @@
"gpx-wasm": "file:../wasm/pkg", "gpx-wasm": "file:../wasm/pkg",
"jszip": "^3.10.1", "jszip": "^3.10.1",
"mapillary-js": "^4.1.2", "mapillary-js": "^4.1.2",
"maplibre-gl": "^6.15.0", "maplibre-gl": "^6.18.0",
"sanitize-html": "^2.17.0", "sanitize-html": "^2.17.0",
"sortablejs": "^1.15.7" "sortablejs": "^1.15.7"
}, },
@@ -26,12 +26,15 @@
"@fontsource-variable/inter": "^5.2.8", "@fontsource-variable/inter": "^5.2.8",
"@internationalized/date": "^3.12.0", "@internationalized/date": "^3.12.0",
"@lucide/svelte": "^1.7.0", "@lucide/svelte": "^1.7.0",
"@mapbox/vector-tile": "^3.0.0",
"@sveltejs/adapter-static": "^3.0.8", "@sveltejs/adapter-static": "^3.0.8",
"@sveltejs/enhanced-img": "^0.6.0", "@sveltejs/enhanced-img": "^0.6.0",
"@sveltejs/kit": "^2.21.2", "@sveltejs/kit": "^2.21.2",
"@sveltejs/vite-plugin-svelte": "^6.2.4", "@sveltejs/vite-plugin-svelte": "^6.2.4",
"@tailwindcss/vite": "^4.1.8", "@tailwindcss/vite": "^4.1.8",
"@tauri-apps/api": "^2.12.3", "@tauri-apps/api": "^2.12.3",
"@tauri-apps/plugin-process": "^2.4.0",
"@tauri-apps/plugin-updater": "^2.14.1",
"@types/eslint": "^9.6.1", "@types/eslint": "^9.6.1",
"@types/events": "^3.0.3", "@types/events": "^3.0.3",
"@types/file-saver": "^2.0.7", "@types/file-saver": "^2.0.7",
@@ -44,6 +47,7 @@
"@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",
@@ -53,6 +57,7 @@
"mdsvex": "^0.12.6", "mdsvex": "^0.12.6",
"mode-watcher": "^1.1.0", "mode-watcher": "^1.1.0",
"paneforge": "^1.0.0-next.5", "paneforge": "^1.0.0-next.5",
"pbf": "^5.2.1",
"postcss": "^8.4.47", "postcss": "^8.4.47",
"prettier": "^3.5.3", "prettier": "^3.5.3",
"prettier-plugin-svelte": "^3.4.0", "prettier-plugin-svelte": "^3.4.0",
@@ -354,6 +359,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",
@@ -1739,18 +1751,6 @@
"pbf": "^5.0.0" "pbf": "^5.0.0"
} }
}, },
"node_modules/@mapbox/vector-tile/node_modules/pbf": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/pbf/-/pbf-5.1.2.tgz",
"integrity": "sha512-mnvGdvOrIvJOBGUEdGkrVXjN8E/VkIJCkf2eS1DH2yv82ORUlLttmDt0rWY38yYZmVwciZwBUvHM20qxBZf40w==",
"license": "BSD-3-Clause",
"dependencies": {
"resolve-protobuf-schema": "^2.1.0"
},
"bin": {
"pbf": "bin/pbf"
}
},
"node_modules/@maplibre/geojson-vt": { "node_modules/@maplibre/geojson-vt": {
"version": "6.3.0", "version": "6.3.0",
"resolved": "https://registry.npmjs.org/@maplibre/geojson-vt/-/geojson-vt-6.3.0.tgz", "resolved": "https://registry.npmjs.org/@maplibre/geojson-vt/-/geojson-vt-6.3.0.tgz",
@@ -1778,9 +1778,9 @@
} }
}, },
"node_modules/@maplibre/maplibre-gl-style-spec": { "node_modules/@maplibre/maplibre-gl-style-spec": {
"version": "26.4.4", "version": "26.7.0",
"resolved": "https://registry.npmjs.org/@maplibre/maplibre-gl-style-spec/-/maplibre-gl-style-spec-26.4.4.tgz", "resolved": "https://registry.npmjs.org/@maplibre/maplibre-gl-style-spec/-/maplibre-gl-style-spec-26.7.0.tgz",
"integrity": "sha512-hG4RZR4PBd/+6A3ODdZ3AnQRF106ZQk1y3bhwDg8bH/A4Oz2tnRUJVVWs9BZa6gXZ1d3UKe89C+Mm+olGBELvA==", "integrity": "sha512-9d7hK1zk1WRx/AFvq7NtmlTlaOGPXS2r+FZXsrMv8453Xy14bnXBpVCPJDBupCfQs/p8FL0/kb0ygbEWTufN0g==",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"@mapbox/jsonlint-lines-primitives": "^2.0.3", "@mapbox/jsonlint-lines-primitives": "^2.0.3",
@@ -1806,26 +1806,14 @@
} }
}, },
"node_modules/@maplibre/vt-pbf": { "node_modules/@maplibre/vt-pbf": {
"version": "4.3.2", "version": "4.3.3",
"resolved": "https://registry.npmjs.org/@maplibre/vt-pbf/-/vt-pbf-4.3.2.tgz", "resolved": "https://registry.npmjs.org/@maplibre/vt-pbf/-/vt-pbf-4.3.3.tgz",
"integrity": "sha512-j6p0AdjvAR19Z3XaCysle7A4ZSo08tYOzxD0Y9NQylwPAkwJJeYub5b2eVucdeDh7erhv69DahoLOevDRERRUw==", "integrity": "sha512-dEe5XUd64RQbxNxy2OzIkJnwNDWjVmSXjCd0A7zLirm7QJ/WWbmtDFIkfsiM4yt1cplqzG6oSivRYeWx1SM1yg==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@mapbox/point-geometry": "^1.1.0", "@mapbox/point-geometry": "^1.1.0",
"@types/geojson": "^7946.0.16", "@types/geojson": "^7946.0.16",
"pbf": "^5.1.0" "pbf": "^5.1.2"
}
},
"node_modules/@maplibre/vt-pbf/node_modules/pbf": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/pbf/-/pbf-5.1.2.tgz",
"integrity": "sha512-mnvGdvOrIvJOBGUEdGkrVXjN8E/VkIJCkf2eS1DH2yv82ORUlLttmDt0rWY38yYZmVwciZwBUvHM20qxBZf40w==",
"license": "BSD-3-Clause",
"dependencies": {
"resolve-protobuf-schema": "^2.1.0"
},
"bin": {
"pbf": "bin/pbf"
} }
}, },
"node_modules/@polka/url": { "node_modules/@polka/url": {
@@ -2659,6 +2647,26 @@
"url": "https://opencollective.com/tauri" "url": "https://opencollective.com/tauri"
} }
}, },
"node_modules/@tauri-apps/plugin-process": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/@tauri-apps/plugin-process/-/plugin-process-2.4.0.tgz",
"integrity": "sha512-GddrmsSLAYrLa/yTXlXK/YRDzUgYeeOnUXTbiyvJWkmI424RmDPD3FVLeqcon7rv6O6ZfhBilcrHWnSo7o6hIQ==",
"dev": true,
"license": "MIT OR Apache-2.0",
"dependencies": {
"@tauri-apps/api": "^2.12.0"
}
},
"node_modules/@tauri-apps/plugin-updater": {
"version": "2.14.1",
"resolved": "https://registry.npmjs.org/@tauri-apps/plugin-updater/-/plugin-updater-2.14.1.tgz",
"integrity": "sha512-Hr7nlBm1wT6xbwzjZ/S36YULazu8MNlj5vvOwMl47fXI7HTa5Bjl1PbDEwVHaZTAKzE1VZsUy35UqnbrQxmYQw==",
"dev": true,
"license": "MIT OR Apache-2.0",
"dependencies": {
"@tauri-apps/api": "^2.12.0"
}
},
"node_modules/@types/cookie": { "node_modules/@types/cookie": {
"version": "0.6.0", "version": "0.6.0",
"dev": true, "dev": true,
@@ -3275,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,
@@ -4009,6 +4035,8 @@
}, },
"node_modules/ieee754": { "node_modules/ieee754": {
"version": "1.2.1", "version": "1.2.1",
"resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
"integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
"funding": [ "funding": [
{ {
"type": "github", "type": "github",
@@ -4625,10 +4653,23 @@
"version": "2.1.0", "version": "2.1.0",
"license": "(MIT AND Zlib)" "license": "(MIT AND Zlib)"
}, },
"node_modules/mapillary-js/node_modules/pbf": {
"version": "3.3.0",
"resolved": "https://registry.npmjs.org/pbf/-/pbf-3.3.0.tgz",
"integrity": "sha512-XDF38WCH3z5OV/OVa8GKUNtLAyneuzbCisx7QUCF8Q6Nutx0WnJrQe5O+kOtBlLfRNUws98Y58Lblp+NJG5T4Q==",
"license": "BSD-3-Clause",
"dependencies": {
"ieee754": "^1.1.12",
"resolve-protobuf-schema": "^2.1.0"
},
"bin": {
"pbf": "bin/pbf"
}
},
"node_modules/maplibre-gl": { "node_modules/maplibre-gl": {
"version": "6.15.0", "version": "6.18.0",
"resolved": "https://registry.npmjs.org/maplibre-gl/-/maplibre-gl-6.15.0.tgz", "resolved": "https://registry.npmjs.org/maplibre-gl/-/maplibre-gl-6.18.0.tgz",
"integrity": "sha512-kxFetbvUHDOVaAP1CYb226Mdk2QhzIPddqM0xJTFD35wu78Mpd6NM7+H68ALjc6Oa0kAOX5EAdMKyvD2u3qfcg==", "integrity": "sha512-8ucT+RhJtEZGFvWGPioVQwvOPMAIuUehEgxl2dELw9aJmX4SpUi+OCHHAD33B9EuohNC7kC/gccJacUgTMQfQQ==",
"license": "BSD-3-Clause", "license": "BSD-3-Clause",
"dependencies": { "dependencies": {
"@mapbox/point-geometry": "^1.1.0", "@mapbox/point-geometry": "^1.1.0",
@@ -4636,9 +4677,9 @@
"@mapbox/unitbezier": "^1.0.0", "@mapbox/unitbezier": "^1.0.0",
"@mapbox/vector-tile": "^3.0.0", "@mapbox/vector-tile": "^3.0.0",
"@maplibre/geojson-vt": "^6.3.0", "@maplibre/geojson-vt": "^6.3.0",
"@maplibre/maplibre-gl-style-spec": "^26.4.4", "@maplibre/maplibre-gl-style-spec": "^26.6.0",
"@maplibre/mlt": "^1.3.0", "@maplibre/mlt": "^1.3.0",
"@maplibre/vt-pbf": "^4.3.2", "@maplibre/vt-pbf": "^4.3.3",
"@types/geojson": "^7946.0.16", "@types/geojson": "^7946.0.16",
"bidi-js": "^1.1.0", "bidi-js": "^1.1.0",
"earcut": "^3.2.4", "earcut": "^3.2.4",
@@ -4664,18 +4705,6 @@
"integrity": "sha512-FHc6yNpnTORB0tM5kmZ03iD2mDuNakDE2lvf4Hw1XkfxtEHIGVi01B/GqUSwx+NcC1WGjidAfpTXzeALtPtfpg==", "integrity": "sha512-FHc6yNpnTORB0tM5kmZ03iD2mDuNakDE2lvf4Hw1XkfxtEHIGVi01B/GqUSwx+NcC1WGjidAfpTXzeALtPtfpg==",
"license": "ISC" "license": "ISC"
}, },
"node_modules/maplibre-gl/node_modules/pbf": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/pbf/-/pbf-5.1.2.tgz",
"integrity": "sha512-mnvGdvOrIvJOBGUEdGkrVXjN8E/VkIJCkf2eS1DH2yv82ORUlLttmDt0rWY38yYZmVwciZwBUvHM20qxBZf40w==",
"license": "BSD-3-Clause",
"dependencies": {
"resolve-protobuf-schema": "^2.1.0"
},
"bin": {
"pbf": "bin/pbf"
}
},
"node_modules/martinez-polygon-clipping": { "node_modules/martinez-polygon-clipping": {
"version": "0.7.4", "version": "0.7.4",
"license": "MIT", "license": "MIT",
@@ -5037,11 +5066,12 @@
} }
}, },
"node_modules/pbf": { "node_modules/pbf": {
"version": "3.3.0", "version": "5.2.1",
"resolved": "https://registry.npmjs.org/pbf/-/pbf-5.2.1.tgz",
"integrity": "sha512-5s6y6g3akGMF98eemb+3QZAWTCUHyox40TJOwcY4M1w40RvoXrfbRUVmY02RlRiEPyE6KVaM0xxfF4+4vjSJTQ==",
"license": "BSD-3-Clause", "license": "BSD-3-Clause",
"dependencies": { "dependencies": {
"ieee754": "^1.1.12", "protocol-buffers-schema": "^3.6.1"
"resolve-protobuf-schema": "^2.1.0"
}, },
"bin": { "bin": {
"pbf": "bin/pbf" "pbf": "bin/pbf"
@@ -5265,7 +5295,9 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/protocol-buffers-schema": { "node_modules/protocol-buffers-schema": {
"version": "3.6.0", "version": "3.6.1",
"resolved": "https://registry.npmjs.org/protocol-buffers-schema/-/protocol-buffers-schema-3.6.1.tgz",
"integrity": "sha512-VG2K63Igkiv9p76tk1lilczEK1cT+kCjKtkdhw1dQZV3k3IXJbd3o6Ho8b9zJZaHSnT2hKe4I+ObmX9w6m5SmQ==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/punycode": { "node_modules/punycode": {
@@ -5347,6 +5379,8 @@
}, },
"node_modules/resolve-protobuf-schema": { "node_modules/resolve-protobuf-schema": {
"version": "2.1.0", "version": "2.1.0",
"resolved": "https://registry.npmjs.org/resolve-protobuf-schema/-/resolve-protobuf-schema-2.1.0.tgz",
"integrity": "sha512-kI5ffTiZWmJaS/huM8wZfEMer1eRd7oJQhDuxeCLe3t7N7mX3z94CN0xPxBQxFYQTSNz9T0i+v6inKqSdK8xrQ==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"protocol-buffers-schema": "^3.3.1" "protocol-buffers-schema": "^3.3.1"
+7 -2
View File
@@ -5,7 +5,7 @@
"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",
@@ -21,12 +21,15 @@
"@fontsource-variable/inter": "^5.2.8", "@fontsource-variable/inter": "^5.2.8",
"@internationalized/date": "^3.12.0", "@internationalized/date": "^3.12.0",
"@lucide/svelte": "^1.7.0", "@lucide/svelte": "^1.7.0",
"@mapbox/vector-tile": "^3.0.0",
"@sveltejs/adapter-static": "^3.0.8", "@sveltejs/adapter-static": "^3.0.8",
"@sveltejs/enhanced-img": "^0.6.0", "@sveltejs/enhanced-img": "^0.6.0",
"@sveltejs/kit": "^2.21.2", "@sveltejs/kit": "^2.21.2",
"@sveltejs/vite-plugin-svelte": "^6.2.4", "@sveltejs/vite-plugin-svelte": "^6.2.4",
"@tailwindcss/vite": "^4.1.8", "@tailwindcss/vite": "^4.1.8",
"@tauri-apps/api": "^2.12.3", "@tauri-apps/api": "^2.12.3",
"@tauri-apps/plugin-process": "^2.4.0",
"@tauri-apps/plugin-updater": "^2.14.1",
"@types/eslint": "^9.6.1", "@types/eslint": "^9.6.1",
"@types/events": "^3.0.3", "@types/events": "^3.0.3",
"@types/file-saver": "^2.0.7", "@types/file-saver": "^2.0.7",
@@ -39,6 +42,7 @@
"@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",
@@ -48,6 +52,7 @@
"mdsvex": "^0.12.6", "mdsvex": "^0.12.6",
"mode-watcher": "^1.1.0", "mode-watcher": "^1.1.0",
"paneforge": "^1.0.0-next.5", "paneforge": "^1.0.0-next.5",
"pbf": "^5.2.1",
"postcss": "^8.4.47", "postcss": "^8.4.47",
"prettier": "^3.5.3", "prettier": "^3.5.3",
"prettier-plugin-svelte": "^3.4.0", "prettier-plugin-svelte": "^3.4.0",
@@ -79,7 +84,7 @@
"gpx-wasm": "file:../wasm/pkg", "gpx-wasm": "file:../wasm/pkg",
"jszip": "^3.10.1", "jszip": "^3.10.1",
"mapillary-js": "^4.1.2", "mapillary-js": "^4.1.2",
"maplibre-gl": "^6.15.0", "maplibre-gl": "^6.18.0",
"sanitize-html": "^2.17.0", "sanitize-html": "^2.17.0",
"sortablejs": "^1.15.7" "sortablejs": "^1.15.7"
} }
@@ -31,6 +31,7 @@
statistics, statistics,
slicedStatistics, slicedStatistics,
hoveredPoint, hoveredPoint,
hoveredTrackpoint,
additionalDatasets, additionalDatasets,
elevationFill, elevationFill,
showControls = true, showControls = true,
@@ -38,6 +39,7 @@
statistics: Readable<SelectionStatistics>; statistics: Readable<SelectionStatistics>;
slicedStatistics: Writable<SlicedStatistics | undefined>; slicedStatistics: Writable<SlicedStatistics | undefined>;
hoveredPoint: Writable<Coordinates | null>; hoveredPoint: Writable<Coordinates | null>;
hoveredTrackpoint?: Readable<number | null>;
additionalDatasets: Writable<string[]>; additionalDatasets: Writable<string[]>;
elevationFill: Writable<'slope' | 'surface' | 'highway' | undefined>; elevationFill: Writable<'slope' | 'surface' | 'highway' | undefined>;
showControls?: boolean; showControls?: boolean;
@@ -55,7 +57,8 @@
additionalDatasets, additionalDatasets,
elevationFill, elevationFill,
canvas, canvas,
overlay overlay,
hoveredTrackpoint
); );
}); });
@@ -15,10 +15,15 @@ import {
getVelocityWithUnits, getVelocityWithUnits,
} from '$lib/units/units'; } from '$lib/units/units';
import Chart, { import Chart, {
Tooltip,
type ActiveDataPoint,
type ChartEvent, type ChartEvent,
type ChartOptions, type ChartOptions,
type ChartType,
type Point,
type ScriptableLineSegmentContext, type ScriptableLineSegmentContext,
type TooltipItem, type TooltipItem,
type TooltipPositionerFunction,
} from 'chart.js/auto'; } from 'chart.js/auto';
import { get, type Readable, type Writable } from 'svelte/store'; import { get, type Readable, type Writable } from 'svelte/store';
import type { Coordinates } from '$lib/geo/coordinates'; import type { Coordinates } from '$lib/geo/coordinates';
@@ -40,6 +45,25 @@ const { distanceUnits, velocityUnits, temperatureUnits } = settings;
Chart.defaults.font.family = Chart.defaults.font.family =
'ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"'; // Tailwind CSS font 'ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"'; // Tailwind CSS font
declare module 'chart.js' {
interface TooltipPositionerMap {
trackpoint: TooltipPositionerFunction<ChartType>;
}
}
/** Marks the positions of the trackpoints shown without an event of the chart. */
const trackpointPosition = Symbol('trackpointPosition');
/**
* Like the default for the events of the chart. A trackpoint that is shown without one is given by
* its position, as it can be between the points of the chart (see `activateTrackpoint`).
*/
Tooltip.positioners.trackpoint = function (items, position) {
return trackpointPosition in position
? position
: Tooltip.positioners.average.call(this, items, position);
};
/** `undefined` for a missing measure (NaN), so that Chart.js leaves a gap instead of a value. */ /** `undefined` for a missing measure (NaN), so that Chart.js leaves a gap instead of a value. */
function optional(value: number, convert: (value: number) => number = (v) => v) { function optional(value: number, convert: (value: number) => number = (v) => v) {
return Number.isNaN(value) ? undefined : convert(value); return Number.isNaN(value) ? undefined : convert(value);
@@ -55,6 +79,21 @@ interface ElevationProfilePoint {
index: number; index: number;
} }
/** The index of the point the closest to `x`, in points sorted by `x`. */
function nearestPointIndex(points: { x: number }[], x: number): number {
let low = 0;
let high = points.length - 1;
while (low < high) {
const middle = (low + high) >> 1;
if (points[middle].x < x) {
low = middle + 1;
} else {
high = middle;
}
}
return low > 0 && x - points[low - 1].x < points[low].x - x ? low - 1 : low;
}
export class ElevationProfile { export class ElevationProfile {
private _chart: Chart | null = null; private _chart: Chart | null = null;
private _canvas: HTMLCanvasElement; private _canvas: HTMLCanvasElement;
@@ -71,10 +110,14 @@ export class ElevationProfile {
*/ */
private _hovered: { index: number; loaded: boolean; point?: SelectionPoint } | null = null; private _hovered: { index: number; loaded: boolean; point?: SelectionPoint } | null = null;
private _loadingHovered = false; private _loadingHovered = false;
/** The last move over the chart, held until the data of its trackpoint is read. */
private _heldMove: MouseEvent | null = null;
private _slicedStatistics: Writable<SlicedStatistics | undefined>; private _slicedStatistics: Writable<SlicedStatistics | undefined>;
private _hoveredPoint: Writable<Coordinates | null>; private _hoveredPoint: Writable<Coordinates | null>;
/** All the points of each dataset, including the ones that the chart decimated. */
private _points: ElevationProfilePoint[][] = [];
/** The trackpoint hovered somewhere else, that the tooltip shows instead of its elements. */
private _shownTrackpoint: number | null = null;
private _hoveredTrackpoint: Readable<number | null> | undefined;
private _unsubscribeHoveredTrackpoint: (() => void) | undefined;
private _additionalDatasets: Readable<string[]>; private _additionalDatasets: Readable<string[]>;
private _elevationFill: Readable<'slope' | 'surface' | 'highway' | undefined>; private _elevationFill: Readable<'slope' | 'surface' | 'highway' | undefined>;
/** The statistics that are only read from the engine while the profile shows them. */ /** The statistics that are only read from the engine while the profile shows them. */
@@ -87,7 +130,8 @@ export class ElevationProfile {
additionalDatasets: Readable<string[]>, additionalDatasets: Readable<string[]>,
elevationFill: Readable<'slope' | 'surface' | 'highway' | undefined>, elevationFill: Readable<'slope' | 'surface' | 'highway' | undefined>,
canvas: HTMLCanvasElement, canvas: HTMLCanvasElement,
overlay: HTMLCanvasElement overlay: HTMLCanvasElement,
hoveredTrackpoint?: Readable<number | null>
) { ) {
this._statistics = statistics; this._statistics = statistics;
this._slicedStatistics = slicedStatistics; this._slicedStatistics = slicedStatistics;
@@ -96,6 +140,7 @@ export class ElevationProfile {
this._elevationFill = elevationFill; this._elevationFill = elevationFill;
this._canvas = canvas; this._canvas = canvas;
this._overlay = overlay; this._overlay = overlay;
this._hoveredTrackpoint = hoveredTrackpoint;
this._request = engine.requestStatistics(); this._request = engine.requestStatistics();
this.updateRequest(); this.updateRequest();
@@ -127,6 +172,9 @@ export class ElevationProfile {
this.updateRequest(); this.updateRequest();
this.updateFill(); this.updateFill();
}); });
this._unsubscribeHoveredTrackpoint = this._hoveredTrackpoint?.subscribe((index) => {
this.showTrackpoint(index);
});
}); });
} }
@@ -195,20 +243,16 @@ export class ElevationProfile {
}, },
tooltip: { tooltip: {
enabled: () => !this._dragging && !this._panning, enabled: () => !this._dragging && !this._panning,
position: 'trackpoint',
callbacks: { callbacks: {
title: () => { title: () => {
return ''; return '';
}, },
label: (context: TooltipItem<'line'>) => { label: (context: TooltipItem<'line'>) => {
const point = context.raw as ElevationProfilePoint; const point = this.pointOf(context);
if (context.datasetIndex === 0) { if (context.datasetIndex === 0) {
this._hoveredPoint.set( this._hoveredPoint.set(
this._dragging this._dragging ? null : this.coordinatesOf(point.index)
? null
: {
lat: this._data.lat[point.index],
lng: this._data.lng[point.index],
}
); );
return `${i18n._('quantities.elevation')}: ${getElevationWithUnits(point.y, false)}`; return `${i18n._('quantities.elevation')}: ${getElevationWithUnits(point.y, false)}`;
} else if (context.datasetIndex === 1) { } else if (context.datasetIndex === 1) {
@@ -228,7 +272,7 @@ export class ElevationProfile {
(context) => context.datasetIndex === 0 (context) => context.datasetIndex === 0
); );
if (context.length === 0) return; if (context.length === 0) return;
const point = context[0].raw as ElevationProfilePoint; const point = this.pointOf(context[0]);
// 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 =
@@ -365,29 +409,21 @@ export class ElevationProfile {
afterEvent: (chart: Chart, args: { event: ChartEvent }) => { afterEvent: (chart: Chart, args: { event: ChartEvent }) => {
if (args.event.type === 'mouseout') { if (args.event.type === 'mouseout') {
this._hovered = null; this._hovered = null;
this._heldMove = null;
this._hoveredPoint.set(null); this._hoveredPoint.set(null);
} }
}, },
}, },
{ {
// The tooltip only shows a trackpoint once all its data is read: a move to // The tooltip follows the pointer at once with what the chart knows of the
// another one is held until then, and replayed (see `loadHovered`). // trackpoint, and shows the rest of its data once it is read (see
id: 'waitForTrackpoint', // `loadHovered`).
id: 'loadTrackpoint',
events: ['mousemove'], events: ['mousemove'],
beforeEvent: (chart: Chart, args: { event: ChartEvent }) => { beforeEvent: (chart: Chart, args: { event: ChartEvent }) => {
const index = this.indexAt(args.event); const index = this.indexAt(args.event);
if (index === undefined) { if (index !== undefined) {
return;
}
const hovered = this._hovered;
if (hovered?.index === index && hovered.loaded) {
this._heldMove = null;
return;
}
this._heldMove = args.event.native as MouseEvent;
this.hover(index); this.hover(index);
return false; }
}, },
}, },
], ],
@@ -478,6 +514,7 @@ export class ElevationProfile {
} }
const data = get(this._statistics); const data = get(this._statistics);
this._data = data; this._data = data;
const shownTrackpoint = this._shownTrackpoint;
// the indices of the trackpoints are the ones of other statistics // the indices of the trackpoints are the ones of other statistics
this._hovered = null; this._hovered = null;
const units = { const units = {
@@ -524,6 +561,7 @@ export class ElevationProfile {
} }
} }
this._points = datasets;
this._chart.data.datasets[0] = { this._chart.data.datasets[0] = {
label: i18n._('quantities.elevation'), label: i18n._('quantities.elevation'),
data: datasets[0], data: datasets[0],
@@ -570,6 +608,10 @@ export class ElevationProfile {
this.setFill(); this.setFill();
this._chart.update(); this._chart.update();
if (shownTrackpoint !== null) {
this.showTrackpoint(shownTrackpoint);
}
} }
updateDataVisibility() { updateDataVisibility() {
@@ -678,6 +720,74 @@ export class ElevationProfile {
} }
} }
/** The point that a line of the tooltip is about. */
private pointOf(context: TooltipItem<'line'>): ElevationProfilePoint {
return this._shownTrackpoint === null
? (context.raw as ElevationProfilePoint)
: this._points[context.datasetIndex][this._shownTrackpoint];
}
private coordinatesOf(index: number): Coordinates {
return { lat: this._data.lat[index], lng: this._data.lng[index] };
}
/** Shows a trackpoint in the tooltip like when hovering it, or nothing anymore with `null`. */
private showTrackpoint(index: number | null) {
const shown = this._shownTrackpoint;
this._shownTrackpoint = index;
if (index !== null) {
this.hover(index);
if (this._hovered?.loaded) {
this.activateTrackpoint(index);
}
} else if (shown !== null) {
this._hovered = null;
this.setActiveElements([], { x: 0, y: 0 });
this._hoveredPoint.set(null);
}
}
/**
* Opens the tooltip on a trackpoint, once its data is read. The chart can only activate the
* points that it kept after decimating its data, which are different for each dataset and might
* not include the trackpoint: it activates the nearest ones, within a pixel of it, and the
* tooltip reads the values of the trackpoint (see `pointOf`).
*/
private activateTrackpoint(index: number) {
const point = this._points[0]?.[index];
if (!this._chart || !point) {
return;
}
const { x: xScale, y: yScale } = this._chart.scales;
const elements: ActiveDataPoint[] = [];
// when the chart is zoomed, the trackpoint can be outside of it
if (xScale.min <= point.x && point.x <= xScale.max) {
for (const { index: datasetIndex } of this._chart.getSortedVisibleDatasetMetas()) {
if (this._points[datasetIndex]?.[index]?.y !== undefined) {
const data = this._chart.data.datasets[datasetIndex].data as { x: number }[];
elements.push({ datasetIndex, index: nearestPointIndex(data, point.x) });
}
}
}
if (elements.length === 0) {
// no tooltip to tell the map about the point
this._hoveredPoint.set(this.coordinatesOf(index));
}
this.setActiveElements(elements, {
x: xScale.getPixelForValue(point.x),
y: yScale.getPixelForValue(point.y),
[trackpointPosition]: true,
} as Point);
}
private setActiveElements(elements: ActiveDataPoint[], position: Point) {
if (this._chart) {
this._chart.tooltip?.setActiveElements(elements, position);
this._chart.setActiveElements(elements);
this._chart.render();
}
}
/** The trackpoint that the tooltip shows for an event, `undefined` outside of the chart. */ /** The trackpoint that the tooltip shows for an event, `undefined` outside of the chart. */
private indexAt(event: ChartEvent): number | undefined { private indexAt(event: ChartEvent): number | undefined {
const elements = this._chart?.getElementsAtEventForMode( const elements = this._chart?.getElementsAtEventForMode(
@@ -718,11 +828,10 @@ export class ElevationProfile {
} }
hovered.loaded = true; hovered.loaded = true;
hovered.point = point; hovered.point = point;
// the move that was held can now show the tooltip if (this._shownTrackpoint === hovered.index) {
const move = this._heldMove; this.activateTrackpoint(hovered.index);
this._heldMove = null; } else {
if (move) { this.refreshTooltip();
this._canvas.dispatchEvent(new MouseEvent(move.type, move));
} }
} }
} finally { } finally {
@@ -730,6 +839,18 @@ export class ElevationProfile {
} }
} }
/** Writes the tooltip again, on the same trackpoint, for the data that was read since. */
private refreshTooltip() {
// the plugin of the tooltip, whose type only has its model
const tooltip = this._chart?.tooltip as
| (Chart['tooltip'] & { update(changed: boolean): void })
| undefined;
if (tooltip && tooltip.getActiveElements().length > 0) {
tooltip.update(true);
this._chart!.render();
}
}
/** The trackpoint that a segment of the chart starts at. */ /** The trackpoint that a segment of the chart starts at. */
private static segmentStart(context: ScriptableLineSegmentContext & { p0: { raw: any } }) { private static segmentStart(context: ScriptableLineSegmentContext & { p0: { raw: any } }) {
return (context.p0.raw as ElevationProfilePoint).index; return (context.p0.raw as ElevationProfilePoint).index;
@@ -758,6 +879,7 @@ export class ElevationProfile {
destroy() { destroy() {
this._request.release(); this._request.release();
this._unsubscribeHoveredTrackpoint?.();
if (this._chart) { if (this._chart) {
this._chart.destroy(); this._chart.destroy();
this._chart = null; this._chart = null;
@@ -18,7 +18,11 @@
import { untrack } from 'svelte'; import { untrack } from 'svelte';
import { isSelected, toggle } from '$lib/components/map/layer-control/utils'; import { isSelected, toggle } from '$lib/components/map/layer-control/utils';
import { engine } from '$lib/engine'; import { engine } from '$lib/engine';
import { hoveredPoint, slicedStatistics } from '$lib/state/selection-statistics'; import {
hoveredPoint,
hoveredTrackpoint,
slicedStatistics,
} from '$lib/state/selection-statistics';
let { let {
useHash = true, useHash = true,
@@ -119,6 +123,7 @@
{statistics} {statistics}
{slicedStatistics} {slicedStatistics}
{hoveredPoint} {hoveredPoint}
{hoveredTrackpoint}
{additionalDatasets} {additionalDatasets}
{elevationFill} {elevationFill}
showControls={options.elevation.controls} showControls={options.elevation.controls}
@@ -5,6 +5,7 @@
import { StartEndMarkers } from '$lib/components/map/gpx-layer/start-end-markers'; import { StartEndMarkers } from '$lib/components/map/gpx-layer/start-end-markers';
import { createPopups, removePopups } from '$lib/components/map/gpx-layer/gpx-layer-popup'; import { createPopups, removePopups } from '$lib/components/map/gpx-layer/gpx-layer-popup';
import { map } from '$lib/components/map/map'; import { map } from '$lib/components/map/map';
import { hoveredTrackpoint } from '$lib/state/selection-statistics';
let distanceMarkers: DistanceMarkers; let distanceMarkers: DistanceMarkers;
let startEndMarkers: StartEndMarkers; let startEndMarkers: StartEndMarkers;
@@ -14,6 +15,11 @@
startEndMarkers = new StartEndMarkers(); startEndMarkers = new StartEndMarkers();
distanceMarkers = new DistanceMarkers(); distanceMarkers = new DistanceMarkers();
createPopups(map_); createPopups(map_);
// the layers do not see the pointer when it leaves the map or when it drags something
const stopHovering = () => hoveredTrackpoint.set(null);
map_.on('mouseout', stopHovering);
map_.on('mousedown', stopHovering);
map_.on('movestart', stopHovering);
}); });
onDestroy(() => { onDestroy(() => {
@@ -2,17 +2,15 @@
import { Button } from '$lib/components/ui/button'; import { Button } from '$lib/components/ui/button';
import CopyCoordinates from '$lib/components/map/gpx-layer/CopyCoordinates.svelte'; import CopyCoordinates from '$lib/components/map/gpx-layer/CopyCoordinates.svelte';
import * as Card from '$lib/components/ui/card'; import * as Card from '$lib/components/ui/card';
import WithUnits from '$lib/components/WithUnits.svelte'; import { Compass, Earth } from '@lucide/svelte';
import { Compass, Earth, Mountain, Timer } from '@lucide/svelte';
import { i18n } from '$lib/i18n/i18n.svelte'; import { i18n } from '$lib/i18n/i18n.svelte';
import type { PopupItem } from '$lib/components/map/map-popup'; import type { PopupItem } from '$lib/components/map/map-popup';
import type { TrackpointDetails } from '$lib/engine';
import { map } from '$lib/components/map/map'; import { map } from '$lib/components/map/map';
let { let {
trackpoint, trackpoint,
}: { }: {
trackpoint: PopupItem<Pick<TrackpointDetails, 'lng' | 'lat'> & Partial<TrackpointDetails>>; trackpoint: PopupItem<{ lng: number; lat: number }>;
} = $props(); } = $props();
</script> </script>
@@ -22,24 +20,11 @@
<Compass size="14" /> <Compass size="14" />
{trackpoint.item.lat.toFixed(6)}&deg; {trackpoint.item.lng.toFixed(6)}&deg; {trackpoint.item.lat.toFixed(6)}&deg; {trackpoint.item.lng.toFixed(6)}&deg;
</div> </div>
{#if trackpoint.item.ele !== undefined}
<div class="flex flex-row items-center gap-1">
<Mountain size="14" />
<WithUnits value={trackpoint.item.ele} type="elevation" />
</div>
{/if}
{#if trackpoint.item.time !== undefined}
<div class="flex flex-row items-center gap-1">
<Timer size="14" />
{i18n.df.format(new Date(trackpoint.item.time))}
</div>
{/if}
<CopyCoordinates <CopyCoordinates
coordinates={trackpoint.item} coordinates={trackpoint.item}
onCopy={() => trackpoint.hide?.()} onCopy={() => trackpoint.hide?.()}
class="mt-0.5" class="mt-0.5"
/> />
{#if trackpoint.fileId === undefined}
<Button <Button
variant="outline" variant="outline"
class="justify-start" class="justify-start"
@@ -49,6 +34,5 @@
<Earth size="14" /> <Earth size="14" />
{i18n._('menu.edit_osm')} {i18n._('menu.edit_osm')}
</Button> </Button>
{/if}
</Card.Content> </Card.Content>
</Card.Root> </Card.Root>
@@ -7,8 +7,8 @@ import {
Point, Point,
} from 'maplibre-gl'; } from 'maplibre-gl';
import { map } from '$lib/components/map/map'; import { map } from '$lib/components/map/map';
import { waypointPopup, trackpointPopup } from './gpx-layer-popup'; import { waypointPopup } from './gpx-layer-popup';
import { closestPointIndex } from '$lib/geo/closest-point'; import { closestPointIndexIn } from '$lib/geo/closest-point';
import { getElevation, loadSVGIcon } from '$lib/utils'; import { getElevation, loadSVGIcon } from '$lib/utils';
import { selectedWaypoint } from '$lib/components/toolbar/tools/waypoint/waypoint'; import { selectedWaypoint } from '$lib/components/toolbar/tools/waypoint/waypoint';
import { MapPin, Square } from 'lucide-static'; import { MapPin, Square } from 'lucide-static';
@@ -21,6 +21,7 @@ import { currentTool, Tool } from '$lib/components/toolbar/tools';
import { splitAtPoint } from '$lib/components/toolbar/tools/scissors/scissors'; import { splitAtPoint } from '$lib/components/toolbar/tools/scissors/scissors';
import { mapCursor, MapCursorState } from '$lib/state/map-cursor'; import { mapCursor, MapCursorState } from '$lib/state/map-cursor';
import { ANCHOR_LAYER_KEY } from '$lib/components/map/style'; import { ANCHOR_LAYER_KEY } from '$lib/components/map/style';
import { hoveredTrackpoint } from '$lib/state/selection-statistics';
export function getSvgForSymbol(symbol?: string | undefined, layerColor?: string | undefined) { export function getSvgForSymbol(symbol?: string | undefined, layerColor?: string | undefined) {
const symbolSvg = symbol ? symbols[symbol]?.iconSvg : undefined; const symbolSvg = symbol ? symbols[symbol]?.iconSvg : undefined;
@@ -63,6 +64,7 @@ export class GPXLayer {
currentWaypointData: GeoJSON.FeatureCollection | null = null; currentWaypointData: GeoJSON.FeatureCollection | null = null;
draggedWaypointIndex: number | null = null; draggedWaypointIndex: number | null = null;
draggingStartingPosition: Point = new Point(0, 0); draggingStartingPosition: Point = new Point(0, 0);
hoversTrackpoint: boolean = false;
unsubscribe: (() => void)[] = []; unsubscribe: (() => void)[] = [];
updateBinded: () => void = this.update.bind(this); updateBinded: () => void = this.update.bind(this);
@@ -400,25 +402,55 @@ export class GPXLayer {
layerOnMouseLeave() { layerOnMouseLeave() {
mapCursor.notify(MapCursorState.SCISSORS, false); mapCursor.notify(MapCursorState.SCISSORS, false);
mapCursor.notify(MapCursorState.LAYER_HOVER, false); mapCursor.notify(MapCursorState.LAYER_HOVER, false);
this.stopHoveringTrackpoint();
} }
async layerOnMouseMove(e: MapLayerMouseEvent) { layerOnMouseMove(e: MapLayerMouseEvent) {
if (e.originalEvent.shiftKey) { // these tools act on the track under the pointer, and show it themselves
const { segmentId } = e.features![0].properties; const tool = get(currentTool);
const lngLat = { lng: e.lngLat.lng, lat: e.lngLat.lat }; const index =
const index = closestPointIndex(await engine.segmentCoordinates(segmentId), lngLat); tool === Tool.ROUTING || tool === Tool.SCISSORS
const trackpoint =
index === undefined
? undefined ? undefined
: await engine.trackpoint(this.fileId, segmentId, index); : this.selectedTrackpointAt(e);
if (trackpoint) { if (index === undefined) {
trackpointPopup?.setItem({ this.stopHoveringTrackpoint();
item: trackpoint, } else {
kind: 'trackpoint', this.hoversTrackpoint = true;
fileId: this.fileId, hoveredTrackpoint.set(index);
});
} }
} }
stopHoveringTrackpoint() {
if (this.hoversTrackpoint) {
this.hoversTrackpoint = false;
hoveredTrackpoint.set(null);
}
}
/**
* The trackpoint of the statistics of the selection that is the closest to the pointer, in the
* first segment under it that is part of the selection.
*/
selectedTrackpointAt(e: MapLayerMouseEvent): number | undefined {
const statistics = get(engine.statistics);
if (!statistics.segments) {
return undefined;
}
const { starts, ids } = statistics.segments;
for (const { properties } of e.features!) {
const segment = ids.indexOf(properties.segmentId);
if (segment >= 0) {
const end = segment + 1 < starts.length ? starts[segment + 1] : statistics.length;
return closestPointIndexIn(
statistics.lng,
statistics.lat,
starts[segment],
end,
e.lngLat
);
}
}
return undefined;
} }
layerOnClick(e: MapLayerMouseEvent) { layerOnClick(e: MapLayerMouseEvent) {
@@ -1,4 +1,4 @@
import { FileStateCollectionObserver } from '$lib/engine'; import { engine, FileStateCollectionObserver } from '$lib/engine';
import { writable } from 'svelte/store'; import { writable } from 'svelte/store';
import { GPXLayer } from './gpx-layer'; import { GPXLayer } from './gpx-layer';
@@ -14,6 +14,7 @@ export class GPXLayerCollection {
if (this._fileStateCollectionObserver) { if (this._fileStateCollectionObserver) {
return; return;
} }
engine.requestStatistics().set(['segments']);
this._fileStateCollectionObserver = new FileStateCollectionObserver( this._fileStateCollectionObserver = new FileStateCollectionObserver(
(newFiles) => { (newFiles) => {
newFiles.forEach((fileStore, fileId) => { newFiles.forEach((fileStore, fileId) => {
@@ -17,7 +17,6 @@
} from '$lib/data/layers'; } from '$lib/data/layers';
import { getLayers, isSelected, toggle } from '$lib/components/map/layer-control/utils'; import { getLayers, isSelected, toggle } from '$lib/components/map/layer-control/utils';
import { i18n } from '$lib/i18n/i18n.svelte'; import { i18n } from '$lib/i18n/i18n.svelte';
import { map } from '$lib/components/map/map';
import CustomLayers from './CustomLayers.svelte'; import CustomLayers from './CustomLayers.svelte';
import { settings } from '$lib/state/settings'; import { settings } from '$lib/state/settings';
import { untrack } from 'svelte'; import { untrack } from 'svelte';
@@ -209,19 +208,6 @@
disabled={selectedOverlay === undefined} disabled={selectedOverlay === undefined}
onValueChange={(value) => { onValueChange={(value) => {
if (selectedOverlay) { if (selectedOverlay) {
if (
$map &&
$currentOverlays &&
isSelected($currentOverlays, selectedOverlay)
) {
try {
if ($map.getLayer(selectedOverlay)) {
$map.removeLayer(selectedOverlay);
}
} catch {
// No reliable way to check if the map is ready to remove sources and layers
}
}
$opacities[selectedOverlay] = value; $opacities[selectedOverlay] = value;
} }
}} }}
@@ -12,6 +12,7 @@
let { let {
name, name,
node, node,
parent = '',
selected = '', selected = '',
onselect = () => {}, onselect = () => {},
multiple = false, multiple = false,
@@ -19,6 +20,7 @@
}: { }: {
name: string; name: string;
node: LayerTreeType; node: LayerTreeType;
parent?: string;
selected?: string; selected?: string;
onselect?: (value: string) => void; onselect?: (value: string) => void;
multiple: boolean; multiple: boolean;
@@ -26,7 +28,21 @@
} = $props(); } = $props();
const { customLayers } = settings; const { customLayers } = settings;
const { isLayerFromExtension, getLayerName } = extensionAPI; const { isLayerFromExtension, getLayerName, isExtensionGroup } = extensionAPI;
/** The groups of extensions are right below the overlays, with the name they were given. */
function getGroupLabel(id: string) {
return parent === 'overlays' && $isExtensionGroup(id)
? id
: i18n._(`layers.label.${id}`, id);
}
function getLabel(id: string) {
if (Object.hasOwn($customLayers, id)) {
return $customLayers[id].name;
}
return $isLayerFromExtension(id) ? $getLayerName(id) : i18n._(`layers.label.${id}`);
}
$effect.pre(() => { $effect.pre(() => {
if (checked !== undefined) { if (checked !== undefined) {
@@ -57,7 +73,7 @@
() => checked[id] === true, (value) => (checked[id] = value) () => checked[id] === true, (value) => (checked[id] = value)
} }
class="scale-90" class="scale-90"
aria-label={i18n._(`layers.label.${id}`)} aria-label={getLabel(id)}
/> />
{:else} {:else}
<input <input
@@ -74,25 +90,20 @@
/> />
{/if} {/if}
<Label for="{name}-{id}" class="flex flex-row items-center gap-1"> <Label for="{name}-{id}" class="flex flex-row items-center gap-1">
{#if Object.hasOwn($customLayers, id)} {getLabel(id)}
{$customLayers[id].name}
{:else if $isLayerFromExtension(id)}
{$getLayerName(id)}
{:else}
{i18n._(`layers.label.${id}`)}
{/if}
</Label> </Label>
</div> </div>
{/if} {/if}
{:else if anySelectedLayer(node[id])} {:else if anySelectedLayer(node[id])}
<CollapsibleTreeNode {id}> <CollapsibleTreeNode {id}>
{#snippet trigger()} {#snippet trigger()}
<span>{i18n._(`layers.label.${id}`, id)}</span> <span>{getGroupLabel(id)}</span>
{/snippet} {/snippet}
{#snippet content()} {#snippet content()}
<div class="ml-2"> <div class="ml-2">
<Self <Self
node={node[id] as LayerTreeType} node={node[id] as LayerTreeType}
parent={id}
{name} {name}
{selected} {selected}
{onselect} {onselect}
@@ -5,29 +5,16 @@ import { get } from 'svelte/store';
import { overlays, overlayTree, type LayerTreeType } from '$lib/data/layers'; import { overlays, overlayTree, type LayerTreeType } from '$lib/data/layers';
import { engine } from '$lib/engine'; import { engine } from '$lib/engine';
import { settings } from '$lib/state/settings'; import { settings } from '$lib/state/settings';
import { ExtensionAPI, type CustomOverlay } from './extension-api'; import { map } from '$lib/components/map/map';
import { isSelected } from './utils'; import type { StyleSpecification } from 'maplibre-gl';
import { ExtensionAPI, type ExtensionOverlay } from './extension-api';
import { isSelected, prefixStyle } from './utils';
const original = { set: engine.setSetting, delete: engine.deleteSetting }; const original = { set: engine.setSetting, delete: engine.deleteSetting };
/** The raster source that an overlay added by an extension uses. */
function rasterSource(id: string) {
const style = overlays[id];
assert.ok(typeof style === 'object');
const source = style.sources[id];
assert.ok(source?.type === 'raster');
return source;
}
const overlayTreeBefore = JSON.stringify(overlayTree); const overlayTreeBefore = JSON.stringify(overlayTree);
const overlayIdsBefore = Object.keys(overlays).sort(); const overlayIdsBefore = Object.keys(overlays).sort();
const overlay = (id: string, extensionName = 'My extension'): CustomOverlay => ({
extensionName,
id,
name: `Overlay ${id}`,
tileUrls: [`https://tiles.example.com/${id}/{z}/{x}/{y}.png`],
});
let api: ExtensionAPI; let api: ExtensionAPI;
beforeEach(() => { beforeEach(() => {
@@ -40,114 +27,335 @@ beforeEach(() => {
afterEach(() => { afterEach(() => {
// the layers are shared by the whole app: leave them as they were // the layers are shared by the whole app: leave them as they were
api.filterOverlays([]); api.setOverlays('Heatmaps', []);
for (const extension of ['My extension', 'Other extension']) { api.setOverlays('Other', []);
delete (overlayTree.overlays as LayerTreeType)[extension];
}
engine.setSetting = original.set; engine.setSetting = original.set;
engine.deleteSetting = original.delete; engine.deleteSetting = original.delete;
assert.equal(JSON.stringify(overlayTree), overlayTreeBefore); assert.equal(JSON.stringify(overlayTree), overlayTreeBefore);
assert.deepEqual(Object.keys(overlays).sort(), overlayIdsBefore); assert.deepEqual(Object.keys(overlays).sort(), overlayIdsBefore);
}); });
const rasterStyle = (url = 'https://tiles.example.com/{z}/{x}/{y}.png'): StyleSpecification => ({
version: 8,
sources: { tiles: { type: 'raster', tiles: [url], tileSize: 256 } },
layers: [{ id: 'tiles', type: 'raster', source: 'tiles' }],
});
const v2 = (id: string, extra: Partial<ExtensionOverlay> = {}): ExtensionOverlay => ({
id,
name: `Overlay ${id}`,
style: rasterStyle(),
...extra,
});
const id = (overlayId: string, extension = 'Heatmaps') =>
`extension-${encodeURIComponent(extension)}/${encodeURIComponent(overlayId)}`;
/** The overlays of an extension in a tree, with their state. */
const group = (tree: LayerTreeType | undefined, extension = 'Heatmaps') =>
(tree!.overlays as LayerTreeType)[extension] as LayerTreeType | undefined;
/** What the user does in the layer menu. */
function setShown(overlayId: string, shown: boolean) {
settings.currentOverlays.update((tree) => {
group(tree)![overlayId] = shown;
return tree;
});
}
describe('prefixStyle', () => {
it('prefixes the sources, the layers, and the source of the layers', () => {
const prefixed = prefixStyle('overlay', {
version: 8,
sources: { dem: { type: 'raster-dem', tiles: ['https://dem/{z}/{x}/{y}.png'] } },
layers: [
{ id: 'relief', type: 'color-relief', source: 'dem' },
{ id: 'background', type: 'background' },
],
});
assert.deepEqual(Object.keys(prefixed.sources), ['overlay/dem']);
assert.deepEqual(
prefixed.layers.map((layer) => layer.id),
['overlay/relief', 'overlay/background']
);
assert.equal((prefixed.layers[0] as { source: string }).source, 'overlay/dem');
assert.equal('source' in prefixed.layers[1], false);
});
it('refuses a style whose layers cannot work', () => {
const style = (layers: unknown) =>
({ version: 8, sources: {}, layers }) as StyleSpecification;
assert.throws(() => prefixStyle('o', style(undefined)), /list of layers/);
assert.throws(
() => prefixStyle('o', style([{ id: 'a', type: 'raster', source: 'none' }])),
/unknown source/
);
assert.throws(
() =>
prefixStyle(
'o',
style([
{ id: 'a', type: 'background' },
{ id: 'a', type: 'background' },
])
),
/repeated layer id/
);
});
});
describe('ExtensionAPI', () => { describe('ExtensionAPI', () => {
it('adds an overlay as a layer, in the tree of its extension', () => { it('adds the overlays of an extension, in the order of the list, hidden by default', () => {
api.addOrUpdateOverlay(overlay('one')); api.setOverlays('Heatmaps', [v2('b'), v2('a', { name: 'A' }), v2('c', { visible: true })]);
const source = rasterSource('extension-one'); const expected = [id('b'), id('a'), id('c')];
assert.deepEqual(source.tiles, ['https://tiles.example.com/one/{z}/{x}/{y}.png']); assert.deepEqual(Object.keys(group(overlayTree)!), expected);
assert.equal(source.tileSize, 256); assert.deepEqual(Object.keys(group(get(settings.selectedOverlayTree))!), expected);
assert.equal(source.maxzoom, 22); assert.deepEqual(group(get(settings.currentOverlays)), {
[id('b')]: false,
assert.ok((overlayTree.overlays as LayerTreeType)['My extension']); [id('a')]: false,
assert.equal(isSelected(overlayTree, 'extension-one'), true); [id('c')]: true,
assert.equal(isSelected(get(settings.selectedOverlayTree), 'extension-one'), true); });
// not shown until the user chooses to assert.ok(get(api.isLayerFromExtension)(id('a')));
assert.equal(isSelected(get(settings.currentOverlays)!, 'extension-one'), false); assert.equal(get(api.getLayerName)(id('a')), 'A');
assert.ok(get(api.isLayerFromExtension)('extension-one')); assert.equal(api.version, 2);
assert.equal(get(api.getLayerName)('extension-one'), 'Overlay one');
assert.equal(get(api.getLayerName)('other'), '');
}); });
it('uses big tiles when the urls say so, and the max zoom it is given', () => { it('uses the style as is, with prefixed ids', () => {
api.addOrUpdateOverlay({ api.setOverlays('Heatmaps', [v2('a')]);
...overlay('big'), const style = overlays[id('a')] as StyleSpecification;
tileUrls: ['https://tiles.example.com/512/{z}/{x}/{y}.png'], assert.deepEqual(Object.keys(style.sources), [`${id('a')}/tiles`]);
maxZoom: 15, assert.equal(style.layers[0].id, `${id('a')}/tiles`);
}); assert.equal((style.layers[0] as { source: string }).source, `${id('a')}/tiles`);
const source = rasterSource('extension-big');
assert.equal(source.tileSize, 512);
assert.equal(source.maxzoom, 15);
}); });
it('refuses an overlay that is not complete', () => { it('names its overlays after the extension', () => {
for (const bad of [ api.setOverlays('My heatmap', [v2('all')]);
{ ...overlay('a'), extensionName: '' }, assert.ok(isSelected(overlayTree, 'extension-My%20heatmap/all'));
{ ...overlay('a'), id: '' }, api.setOverlays('My heatmap', []);
{ ...overlay('a'), name: '' },
{ ...overlay('a'), tileUrls: [] },
{ ...overlay('a'), tileUrls: undefined as unknown as string[] },
]) {
assert.throws(() => api.addOrUpdateOverlay(bad), /must have/);
}
assert.ok(!('extension-a' in overlays));
}); });
it('updates an overlay that is added again, keeping it shown', () => { it('keeps two extensions with the same overlay ids, or similar names, apart', () => {
api.addOrUpdateOverlay(overlay('one')); api.setOverlays('Heatmaps', [v2('a')]);
settings.currentOverlays.update((current) => { api.setOverlays('Other', [v2('a')]);
(current.overlays as LayerTreeType)['My extension'] = { 'extension-one': true }; assert.deepEqual(Object.keys(group(overlayTree)!), [id('a')]);
return current; assert.deepEqual(Object.keys(group(overlayTree, 'Other')!), [id('a', 'Other')]);
api.setOverlays('Heatmaps/a', [v2('b')]);
api.setOverlays('Heatmaps', [v2('a'), v2('a/b')]);
assert.notEqual(id('a/b'), id('b', 'Heatmaps/a'));
assert.ok(get(api.isLayerFromExtension)(id('a/b')));
assert.ok(get(api.isLayerFromExtension)(id('b', 'Heatmaps/a')));
api.setOverlays('Other', []);
assert.deepEqual(Object.keys(group(overlayTree)!).length, 2);
api.setOverlays('Heatmaps/a', []);
}); });
api.addOrUpdateOverlay({ it('knows the groups of the extensions', () => {
...overlay('one'), api.setOverlays('Heatmaps', [v2('a')]);
name: 'Renamed', assert.equal(get(api.isExtensionGroup)('Heatmaps'), true);
tileUrls: ['https://other/{z}'], assert.equal(get(api.isExtensionGroup)('france'), false);
}); api.setOverlays('Heatmaps', []);
assert.equal(get(api.getLayerName)('extension-one'), 'Renamed'); assert.equal(get(api.isExtensionGroup)('Heatmaps'), false);
assert.deepEqual(rasterSource('extension-one').tiles, ['https://other/{z}']);
assert.equal(isSelected(get(settings.currentOverlays)!, 'extension-one'), true);
}); });
it('removes the overlays that are not in the list anymore, everywhere', () => { it('removes what is not in the list anymore, with its group when it is empty', () => {
api.addOrUpdateOverlay(overlay('one')); api.setOverlays('Heatmaps', [v2('a', { visible: true }), v2('b')]);
api.addOrUpdateOverlay(overlay('two', 'Other extension')); api.setOverlays('Heatmaps', [v2('b')]);
assert.ok(!(id('a') in overlays));
assert.equal(get(api.isLayerFromExtension)(id('a')), false);
assert.equal(isSelected(get(settings.currentOverlays)!, id('a')), false);
assert.deepEqual(Object.keys(group(overlayTree)!), [id('b')]);
api.filterOverlays(['two']); api.setOverlays('Heatmaps', []);
assert.ok(!('extension-one' in overlays)); assert.equal(group(overlayTree), undefined);
assert.ok('extension-two' in overlays); assert.equal(group(get(settings.selectedOverlayTree)), undefined);
assert.equal(get(api.isLayerFromExtension)('extension-one'), false); assert.equal(group(get(settings.currentOverlays)), undefined);
assert.equal(get(api.isLayerFromExtension)('extension-two'), true);
for (const tree of [
overlayTree,
get(settings.selectedOverlayTree),
get(settings.currentOverlays)!,
]) {
assert.equal(isSelected(tree, 'extension-one'), false);
}
assert.equal(isSelected(overlayTree, 'extension-two'), true);
api.filterOverlays([]);
assert.ok(!('extension-two' in overlays));
}); });
it('puts the overlays in the order it is given', () => { it('keeps the state of an overlay unless told otherwise, and the opacity and menu choices', () => {
api.addOrUpdateOverlay(overlay('one')); api.setOverlays('Heatmaps', [v2('a'), v2('b')]);
api.addOrUpdateOverlay(overlay('two')); setShown(id('a'), true);
api.addOrUpdateOverlay(overlay('three')); settings.opacities.update((opacities) => ({ ...opacities, [id('a')]: 0.3 }));
settings.selectedOverlayTree.update((tree) => {
group(tree)![id('b')] = false;
return tree;
});
api.updateOverlaysOrder(['three', 'one', 'two']); api.setOverlays('Heatmaps', [v2('b'), v2('a')]);
const extension = (get(settings.selectedOverlayTree).overlays as LayerTreeType)[ assert.equal(isSelected(get(settings.currentOverlays)!, id('a')), true);
'My extension' assert.equal(isSelected(get(settings.selectedOverlayTree), id('b')), false);
]; assert.equal(get(settings.opacities)[id('a')], 0.3);
assert.deepEqual(Object.keys(extension as LayerTreeType), [ assert.deepEqual(Object.keys(group(get(settings.selectedOverlayTree))!), [
'extension-three', id('b'),
'extension-one', id('a'),
'extension-two',
]); ]);
// ids it does not know are ignored
api.updateOverlaysOrder(['unknown', 'two']); api.setOverlays('Heatmaps', [v2('a', { visible: false }), v2('b', { visible: true })]);
assert.equal(Object.keys(extension as LayerTreeType).at(-1), 'extension-two'); assert.equal(isSelected(get(settings.currentOverlays)!, id('a')), false);
// the user took it out of the menu, where it could not be hidden again
assert.equal(isSelected(get(settings.currentOverlays)!, id('b')), false);
});
it('changes nothing when the list is not valid', () => {
api.setOverlays('Heatmaps', [v2('a')]);
const invalid: unknown[] = [
[v2('b'), v2('b')],
[v2('b'), { id: 'c', name: 'C' }],
[v2('b'), { ...v2('c'), style: { version: 8, sources: {} } }],
'not a list',
];
for (const list of invalid) {
assert.throws(() => api.setOverlays('Heatmaps', list as ExtensionOverlay[]));
}
assert.deepEqual(Object.keys(group(overlayTree)!), [id('a')]);
assert.ok(!(id('b') in overlays));
});
it('refuses the names that cannot be the group of an extension', () => {
for (const name of ['', 'world', 'countries', '__proto__']) {
assert.throws(() => api.setOverlays(name, [v2('a')]));
}
});
it('waits for the settings', () => {
const current = get(settings.currentOverlays);
(settings.currentOverlays as unknown as { _value: { set(v: unknown): void } })._value.set(
undefined
);
assert.throws(() => api.setOverlays('Heatmaps', [v2('a')]), /gpxstudio\.ready/);
settings.currentOverlays.set(current!);
});
it('tells the extension about the actions of the user only', () => {
const calls: Record<string, boolean>[] = [];
const stop = api.onVisibilityChange('Heatmaps', (visible) => calls.push(visible));
const others: unknown[] = [];
api.onVisibilityChange('Other', (visible) => others.push(visible));
api.setOverlays('Other', [v2('x')]);
api.setOverlays('Heatmaps', [v2('a'), v2('b', { visible: true })]);
api.setOverlays('Heatmaps', [v2('a', { visible: true }), v2('b', { visible: false })]);
assert.deepEqual(calls, []);
setShown(id('b'), true);
assert.deepEqual(calls, [{ a: true, b: true }]);
// nothing changed
setShown(id('b'), true);
assert.equal(calls.length, 1);
assert.deepEqual(others, []);
stop();
setShown(id('b'), false);
assert.equal(calls.length, 1);
});
it('tells the extension when the overlays are all hidden from the menu', () => {
const calls: Record<string, boolean>[] = [];
api.onVisibilityChange('Heatmaps', (visible) => calls.push(visible));
api.setOverlays('Heatmaps', [v2('a', { visible: true })]);
settings.currentOverlays.set({ overlays: {} });
assert.deepEqual(calls, [{ a: false }]);
});
it('survives a callback that throws, or that sets the overlays', () => {
const error = console.error;
console.error = () => {};
const calls: unknown[] = [];
api.onVisibilityChange('Heatmaps', () => {
throw new Error('from the extension');
});
api.onVisibilityChange('Heatmaps', (visible) => {
calls.push(visible);
api.setOverlays('Heatmaps', [v2('a', { visible: visible.a })]);
});
api.setOverlays('Heatmaps', [v2('a')]);
setShown(id('a'), true);
console.error = error;
assert.deepEqual(calls, [{ a: true }]);
});
it('forgets the state of the overlays with the next session', () => {
const saved = () => ({
currentOverlays: JSON.stringify(get(settings.currentOverlays)),
previousOverlays: JSON.stringify(get(settings.previousOverlays)),
selectedOverlayTree: JSON.stringify(get(settings.selectedOverlayTree)),
opacities: JSON.stringify(get(settings.opacities)),
});
// what was saved, not the default trees, which are the ones that are allowed
settings.connect(saved());
api.setOverlays('Heatmaps', [v2('a', { visible: true }), v2('b')]);
settings.selectedOverlayTree.update((tree) => {
group(tree)![id('b')] = false;
return tree;
});
settings.opacities.update((opacities) => ({ ...opacities, [id('a')]: 0.3 }));
const stored = saved();
assert.ok(stored.currentOverlays.includes(id('a')));
settings.connect(stored);
for (const tree of [
get(settings.currentOverlays),
get(settings.previousOverlays),
get(settings.selectedOverlayTree),
]) {
assert.ok(!JSON.stringify(tree).includes('extension-'));
}
assert.equal(get(settings.opacities)[id('a')], 0.3);
// an extension that is still there starts again, as the source of what it remembers
const next = new ExtensionAPI();
next.setOverlays('Heatmaps', [v2('a'), v2('b', { visible: true })]);
assert.equal(isSelected(get(settings.currentOverlays)!, id('a')), false);
assert.equal(isSelected(get(settings.currentOverlays)!, id('b')), true);
assert.equal(isSelected(get(settings.selectedOverlayTree), id('b')), true);
next.setOverlays('Heatmaps', []);
});
it('leaves a style URL for the map to fetch', () => {
const fetchBefore = globalThis.fetch;
globalThis.fetch = (() => assert.fail('fetched')) as typeof fetch;
try {
const url = 'https://example.com/style.json';
api.setOverlays('Heatmaps', [v2('a', { style: url })]);
assert.equal(overlays[id('a')], url);
} finally {
globalThis.fetch = fetchBefore;
}
});
it('removes a style that changes from the map, layers first, but not one that stays', () => {
const calls: string[] = [];
const prefix = id('a');
const fakeMap = {
getStyle: () => ({
sources: { [`${prefix}/tiles`]: {}, [`${prefix}2/tiles`]: {}, core: {} },
layers: [{ id: `${prefix}/tiles` }, { id: `${prefix}2/tiles` }, { id: 'core' }],
}),
removeLayer: (layer: string) => calls.push(`layer ${layer}`),
removeSource: (source: string) => calls.push(`source ${source}`),
};
const store = (map as unknown as { _mapStore: { set(value: unknown): void } })._mapStore;
store.set(fakeMap);
try {
api.setOverlays('Heatmaps', [v2('a', { visible: true })]);
api.setOverlays('Heatmaps', [v2('a', { name: 'Renamed' })]);
assert.deepEqual(calls, []);
api.setOverlays('Heatmaps', [v2('a', { style: rasterStyle('https://other/{z}') })]);
assert.deepEqual(calls, [`layer ${prefix}/tiles`, `source ${prefix}/tiles`]);
calls.length = 0;
api.setOverlays('Heatmaps', [v2('a', { style: 'https://example.com/style.json' })]);
assert.equal(calls.length, 2);
calls.length = 0;
api.setOverlays('Heatmaps', []);
assert.equal(calls.length, 2);
} finally {
store.set(null);
}
}); });
}); });
@@ -1,35 +1,87 @@
import { settings } from '$lib/state/settings'; import { settings } from '$lib/state/settings';
import type { StyleSpecification } from 'maplibre-gl';
import { derived, get, writable, type Writable } from 'svelte/store'; import { derived, get, writable, type Writable } from 'svelte/store';
import { isSelected, remove, removeAll } from './utils'; import { isSelected, prefixStyle, removeAll } from './utils';
import { layerGroup, overlays, overlayTree, type LayerTreeType } from '$lib/data/layers'; import { layerGroup, overlays, overlayTree, type LayerTreeType } from '$lib/data/layers';
import { browser } from '$app/environment'; import { browser } from '$app/environment';
import { map } from '$lib/components/map/map'; import { map } from '$lib/components/map/map';
const { currentOverlays, previousOverlays, selectedOverlayTree } = settings; const { currentOverlays, previousOverlays, selectedOverlayTree } = settings;
export type CustomOverlay = { /** An overlay given by an extension. */
extensionName: string; export type ExtensionOverlay = {
/** Unique within the extension. Keep it stable: the opacity and menu choices are tied to it. */
id: string; id: string;
name: string; name: string;
tileUrls: string[]; /**
maxZoom?: number; * The sources and layers of the overlay, or the URL of a style JSON (which must allow
* cross-origin requests). It is used as is, with MapLibre's defaults: a `raster` source has
* tiles of 512 pixels unless its `tileSize` says otherwise. Layers can only use the sources of
* this style, and the rest of a style (`sprite`, `glyphs`, `terrain`...) is ignored.
*/
style: StyleSpecification | string;
/** Applied if given, otherwise the current state is kept (hidden for a new overlay). */
visible?: boolean;
}; };
/** What the API knows of an overlay. */
type RegisteredOverlay = {
extensionName: string;
name: string;
/** The style given by the extension, to tell when it changes. */
signature: string;
};
type VisibilityCallback = (visible: Record<string, boolean>) => void;
/** The groups of the overlay tree that an extension cannot put its overlays in. */
const reservedGroups = new Set(['__proto__', ...Object.keys(layerGroup(overlayTree.overlays))]);
/** The id of an overlay. It is encoded so that two extensions cannot clash. */
function getExtensionOverlayId(extensionName: string, id: string): string {
return `extension-${encodeURIComponent(extensionName)}/${encodeURIComponent(id)}`;
}
/**
* Sets the overlays of an extension in a tree, in order, dropping its other entries. An extension
* that has nothing left has no group anymore.
*/
function setGroup(tree: LayerTreeType, extensionName: string, entries: Record<string, boolean>) {
const groups = layerGroup(tree.overlays);
if (Object.keys(entries).length > 0) {
groups[extensionName] = { ...entries };
} else {
delete groups[extensionName];
}
return tree;
}
export class ExtensionAPI { export class ExtensionAPI {
private _overlays: Writable<Map<string, CustomOverlay>> = writable(new Map()); /** The version of the API. */
readonly version = 2;
/**
* Resolved once overlays can be set. `gpxstudio:extension-api-ready` is sent on `window` at that
* moment.
*/
ready!: Promise<void>;
private _overlays: Writable<Map<string, RegisteredOverlay>> = writable(new Map());
/** What each extension knows of the visibility of its overlays, by its own overlay ids. */
private _visibility: Map<string, Record<string, boolean>> = new Map();
private _visibilityCallbacks: Map<string, Set<VisibilityCallback>> = new Map();
private _watchingVisibility = false;
init() { init() {
if (browser && !Object.hasOwn(window, 'gpxstudio')) { if (browser && !Object.hasOwn(window, 'gpxstudio')) {
this.ready = this.whenLoaded();
this.ready.then(() => window.dispatchEvent(new Event('gpxstudio:extension-api-ready')));
Object.defineProperty(window, 'gpxstudio', { Object.defineProperty(window, 'gpxstudio', {
value: this, value: this,
}); });
addEventListener('beforeunload', () => {
this.destroy();
});
} }
} }
ensureLoaded(): Promise<void> { private whenLoaded(): Promise<void> {
let unsubscribe: () => void; let unsubscribe: () => void;
const promise = new Promise<void>((resolve) => { const promise = new Promise<void>((resolve) => {
map.onLoad(() => { map.onLoad(() => {
@@ -46,134 +98,160 @@ export class ExtensionAPI {
return promise; return promise;
} }
addOrUpdateOverlay(overlay: CustomOverlay) { /**
if ( * Replaces the overlays of an extension: the order of the list is the order in the layer menu,
!overlay.extensionName || * and the overlays that are not in the list are removed. The opacity and the choices of the
!overlay.id || * layer menu are kept for the ones that stay. Throws, changing nothing, if the list is invalid;
!overlay.name || * a style URL is only fetched when the overlay is shown, and a failure is then only logged.
!overlay.tileUrls || */
overlay.tileUrls.length === 0 setOverlays(extensionName: string, newOverlays: ExtensionOverlay[]) {
) { if (typeof extensionName !== 'string' || !extensionName) {
throw new Error( throw new Error('An extension must have a name.');
'Overlay must have an extensionName, id, name, and at least one tile URL.'
);
} }
overlay.id = this.getOverlayId(overlay.id); if (reservedGroups.has(extensionName)) {
throw new Error(`The extension name ${extensionName} is reserved.`);
this._overlays.update(($overlays) => {
$overlays.set(overlay.id, overlay);
return $overlays;
});
overlays[overlay.id] = {
version: 8,
sources: {
[overlay.id]: {
type: 'raster',
tiles: overlay.tileUrls,
tileSize: overlay.tileUrls.some((url) => url.includes('512')) ? 512 : 256,
maxzoom: overlay.maxZoom ?? 22,
},
},
layers: [
{
id: overlay.id,
type: 'raster',
source: overlay.id,
},
],
};
const extensions = layerGroup(overlayTree.overlays);
if (!Object.hasOwn(extensions, overlay.extensionName)) {
extensions[overlay.extensionName] = {};
} }
if (!Array.isArray(newOverlays)) {
layerGroup(extensions[overlay.extensionName])[overlay.id] = true; throw new Error('The overlays must be a list.');
selectedOverlayTree.update((selected) => {
if (!Object.hasOwn(selected.overlays, overlay.extensionName)) {
selected.overlays[overlay.extensionName] = {};
} }
selected.overlays[overlay.extensionName][overlay.id] = true;
return selected;
});
const current = get(currentOverlays); const current = get(currentOverlays);
let show = false; if (!current) {
if (current && isSelected(current, overlay.id)) { throw new Error('Overlays cannot be set yet: wait for `gpxstudio.ready`.');
show = true;
try {
get(map)?.removeLayer(overlay.id);
} catch {
// No reliable way to check if the map is ready to remove sources and layers
}
} }
currentOverlays.update((current) => { const previous = this.getOverlaysOf(extensionName);
if (!Object.hasOwn(current.overlays, overlay.extensionName)) { const next = new Map<string, RegisteredOverlay>();
current.overlays[overlay.extensionName] = {}; const styles = new Map<string, StyleSpecification | string>();
for (const overlay of newOverlays) {
if (!overlay?.id || !overlay.name || !overlay.style) {
throw new Error('Overlay must have an id, a name and a style.');
} }
current.overlays[overlay.extensionName][overlay.id] = show; const id = getExtensionOverlayId(extensionName, overlay.id);
return current; if (next.has(id)) {
}); throw new Error(`Overlay ${overlay.id} is in the list twice.`);
} }
const signature = JSON.stringify(overlay.style);
filterOverlays(ids: string[]) { // the ids of the style at a URL are prefixed when the map fetches it
ids = ids.map((id) => this.getOverlayId(id)); styles.set(
const idsToRemove = Array.from(get(this._overlays).keys()).filter( id,
(id) => !ids.includes(id) typeof overlay.style === 'string'
? overlay.style
: prefixStyle(id, JSON.parse(signature))
); );
next.set(id, { extensionName, name: overlay.name, signature });
}
currentOverlays.update((current) => { // Nothing can fail from here. The map does not replace a source that it already has, so
removeAll(current, idsToRemove); // what has changed has to be removed first; it is then added back with the new style.
return current; const removedIds: string[] = [];
}); previous.forEach((overlay, id) => {
previousOverlays.update((previous) => { if (next.get(id)?.signature !== overlay.signature) {
removeAll(previous, idsToRemove); this.removeFromMap(id);
return previous; }
}); if (!next.has(id)) {
selectedOverlayTree.update((selected) => { removedIds.push(id);
removeAll(selected, idsToRemove);
return selected;
});
Object.keys(overlays).forEach((id) => {
if (idsToRemove.includes(id)) {
delete overlays[id]; delete overlays[id];
} }
}); });
removeAll(overlayTree, idsToRemove); styles.forEach((style, id) => {
overlays[id] = style;
});
this._overlays.update(($overlays) => { this._overlays.update(($overlays) => {
$overlays.forEach((_, id) => { removedIds.forEach((id) => $overlays.delete(id));
if (idsToRemove.includes(id)) { next.forEach((overlay, id) => $overlays.set(id, overlay));
$overlays.delete(id); return $overlays;
});
const available: Record<string, boolean> = {};
const selected: Record<string, boolean> = {};
const shown: Record<string, boolean> = {};
const visibility: Record<string, boolean> = {};
const selectedGroup = layerGroup(get(selectedOverlayTree).overlays)[extensionName];
newOverlays.forEach((overlay) => {
const id = getExtensionOverlayId(extensionName, overlay.id);
available[id] = true;
// an overlay that the user took out of the layer menu could not be hidden again
selected[id] =
typeof selectedGroup !== 'object' ||
!Object.hasOwn(selectedGroup, id) ||
selectedGroup[id] === true;
shown[id] = selected[id] && Boolean(overlay.visible ?? isSelected(current, id));
visibility[overlay.id] = shown[id];
});
setGroup(overlayTree, extensionName, available);
selectedOverlayTree.update((tree) => setGroup(tree, extensionName, selected));
previousOverlays.update((tree) => removeAll(tree, removedIds));
// this is not an action of the user: there must be nothing to tell the extension about
this._visibility.set(extensionName, visibility);
currentOverlays.update((tree) => setGroup(tree, extensionName, shown));
}
/**
* Calls `callback` with the visibility of all the overlays of the extension, by id, when the
* user shows or hides one of them (not when `setOverlays` does). Returns how to stop.
*/
onVisibilityChange(extensionName: string, callback: VisibilityCallback): () => void {
const callbacks = this._visibilityCallbacks.get(extensionName) ?? new Set();
this._visibilityCallbacks.set(extensionName, callbacks);
callbacks.add(callback);
if (!this._watchingVisibility) {
this._watchingVisibility = true;
currentOverlays.subscribe(() => this.notifyVisibility());
}
return () => {
callbacks.delete(callback);
};
}
private notifyVisibility() {
const current = get(currentOverlays);
if (!current) return;
this._visibilityCallbacks.forEach((callbacks, extensionName) => {
const known = this._visibility.get(extensionName);
if (!known) return;
const visibility = Object.fromEntries(
Object.keys(known).map((id) => [
id,
isSelected(current, getExtensionOverlayId(extensionName, id)),
])
);
if (Object.keys(known).every((id) => known[id] === visibility[id])) return;
this._visibility.set(extensionName, visibility);
callbacks.forEach((callback) => {
try {
callback({ ...visibility });
} catch (e) {
// an extension must not break the updates of the store for the others
console.error(e);
} }
}); });
return $overlays;
}); });
} }
updateOverlaysOrder(ids: string[]) { private getOverlaysOf(extensionName: string): Map<string, RegisteredOverlay> {
ids = ids.map((id) => this.getOverlayId(id)); return new Map(
selectedOverlayTree.update((selected) => { Array.from(get(this._overlays)).filter(
const isSelected: Record<string, boolean> = {}; ([, overlay]) => overlay.extensionName === extensionName
ids.forEach((id) => { )
const overlay = get(this._overlays).get(id); );
if ( }
overlay &&
Object.hasOwn(selected.overlays, overlay.extensionName) && /** Removes the layers and sources of an overlay: their ids start with the one of the overlay. */
Object.hasOwn(selected.overlays[overlay.extensionName] as LayerTreeType, id) private removeFromMap(overlayId: string) {
) { const map_ = get(map);
isSelected[id] = selected.overlays[overlay.extensionName][id]; if (!map_) return;
delete selected.overlays[overlay.extensionName][id]; try {
const style = map_.getStyle();
style.layers
.filter((layer) => layer.id.startsWith(`${overlayId}/`))
.forEach((layer) => map_.removeLayer(layer.id));
Object.keys(style.sources)
.filter((source) => source.startsWith(`${overlayId}/`))
.forEach((source) => map_.removeSource(source));
} catch {
// No reliable way to check if the map is ready to remove sources and layers
} }
});
Object.entries(isSelected).forEach(([id, value]) => {
const overlay = get(this._overlays).get(id)!;
selected.overlays[overlay.extensionName][id] = value;
});
return selected;
});
} }
isLayerFromExtension = derived(this._overlays, ($overlays) => { isLayerFromExtension = derived(this._overlays, ($overlays) => {
@@ -184,31 +262,11 @@ export class ExtensionAPI {
return (id: string) => $overlays.get(id)?.name || ''; return (id: string) => $overlays.get(id)?.name || '';
}); });
private getOverlayId(id: string): string { /** Whether a group of the layer trees is an extension, whose name is shown as it was given. */
return `extension-${id}`; isExtensionGroup = derived(this._overlays, ($overlays) => {
} const names = new Set(Array.from($overlays.values(), (overlay) => overlay.extensionName));
return (id: string) => names.has(id);
private destroy() {
const ids = Array.from(get(this._overlays).keys());
currentOverlays.update((current) => {
ids.forEach((id) => {
remove(current, id);
}); });
return current;
});
previousOverlays.update((previous) => {
ids.forEach((id) => {
remove(previous, id);
});
return previous;
});
selectedOverlayTree.update((selected) => {
ids.forEach((id) => {
remove(selected, id);
});
return selected;
});
}
} }
export const extensionAPI = new ExtensionAPI(); export const extensionAPI = new ExtensionAPI();
@@ -1,7 +1,16 @@
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { describe, it } from 'node:test'; import { describe, it } from 'node:test';
import type { LayerTreeType } from '$lib/data/layers'; import type { LayerTreeType } from '$lib/data/layers';
import { anySelectedLayer, getLayers, isSelected, remove, removeAll, toggle } from './utils'; import type { LayerSpecification } from 'maplibre-gl';
import {
anySelectedLayer,
getLayers,
getOpacityPaint,
isSelected,
remove,
removeAll,
toggle,
} from './utils';
// roads: bike (selected), foot // roads: bike (selected), foot
// satellite: esri, ign: fr (selected) // satellite: esri, ign: fr (selected)
@@ -72,3 +81,39 @@ describe('layer trees', () => {
assert.deepEqual(removeAll(tree(), []), tree()); assert.deepEqual(removeAll(tree(), []), tree());
}); });
}); });
describe('getOpacityPaint', () => {
const layer = (type: string, paint?: Record<string, unknown>) =>
({ id: 'layer', type, source: 'source', paint }) as LayerSpecification;
it('uses the opacity properties of each type of layer', () => {
assert.deepEqual(getOpacityPaint(layer('raster'), 0.5), { 'raster-opacity': 0.5 });
assert.deepEqual(getOpacityPaint(layer('color-relief'), 0.5), {
'color-relief-opacity': 0.5,
});
assert.deepEqual(getOpacityPaint(layer('symbol'), 0.5), {
'icon-opacity': 0.5,
'text-opacity': 0.5,
});
assert.deepEqual(getOpacityPaint(layer('circle'), 0.5), {
'circle-opacity': 0.5,
'circle-stroke-opacity': 0.5,
});
assert.deepEqual(getOpacityPaint(layer('hillshade'), 0.5), {
'hillshade-exaggeration': 0.25,
});
});
it('scales the opacity that the layer already has', () => {
assert.deepEqual(getOpacityPaint(layer('line', { 'line-opacity': 0.5 }), 0.5), {
'line-opacity': 0.25,
});
});
it('replaces an expression, unless the opacity is left at 1', () => {
const expression = ['interpolate', ['linear'], ['zoom'], 5, 0, 10, 1];
const paint = { 'fill-opacity': expression };
assert.deepEqual(getOpacityPaint(layer('fill', paint), 0.5), { 'fill-opacity': 0.5 });
assert.deepEqual(getOpacityPaint(layer('fill', paint), 1), { 'fill-opacity': expression });
});
});
@@ -1,4 +1,89 @@
import type { LayerTreeType } from '$lib/data/layers'; import type { LayerTreeType } from '$lib/data/layers';
import type { LayerSpecification, StyleSpecification } from 'maplibre-gl';
/** Parts of a style that apply to a whole map, not to an overlay. */
const ignoredStyleProperties = ['sprite', 'glyphs', 'terrain', 'sky', 'light', 'projection'];
/** The overlays that were warned about those: a style at a URL is read again and again. */
const warnedOverlays = new Set<string>();
/**
* A copy of the style of an overlay whose sources and layers have ids of their own, so that they
* cannot clash with the ones of gpx.studio or of another overlay.
*/
export function prefixStyle(overlayId: string, style: StyleSpecification): StyleSpecification {
if (typeof style !== 'object' || style === null || !Array.isArray(style.layers)) {
throw new Error(`The style of overlay ${overlayId} must have a list of layers.`);
}
const ignored = ignoredStyleProperties.filter((property) => Object.hasOwn(style, property));
if (ignored.length > 0 && !warnedOverlays.has(overlayId)) {
warnedOverlays.add(overlayId);
console.warn(`Overlay ${overlayId} ignores these style properties: ${ignored.join(', ')}.`);
}
const prefixed = (id: string) => `${overlayId}/${id}`;
const sources = style.sources ?? {};
const layerIds = new Set<string>();
const layers = style.layers.map((layer) => {
if (!layer.id || layerIds.has(layer.id)) {
throw new Error(`Overlay ${overlayId} has a missing or repeated layer id.`);
}
layerIds.add(layer.id);
if ('source' in layer) {
if (!Object.hasOwn(sources, layer.source)) {
throw new Error(
`Layer ${layer.id} of overlay ${overlayId} uses unknown source ${layer.source}.`
);
}
return { ...layer, id: prefixed(layer.id), source: prefixed(layer.source) };
}
return { ...layer, id: prefixed(layer.id) };
}) as LayerSpecification[];
return {
...style,
sources: Object.fromEntries(
Object.entries(sources).map(([id, source]) => [prefixed(id), source])
),
layers,
};
}
/** The paint properties that make a layer transparent, by type of layer. */
const opacityProperties: Partial<Record<LayerSpecification['type'], string[]>> = {
background: ['background-opacity'],
circle: ['circle-opacity', 'circle-stroke-opacity'],
'color-relief': ['color-relief-opacity'],
fill: ['fill-opacity'],
'fill-extrusion': ['fill-extrusion-opacity'],
heatmap: ['heatmap-opacity'],
line: ['line-opacity'],
raster: ['raster-opacity'],
symbol: ['icon-opacity', 'text-opacity'],
};
/**
* The paint properties that give a layer an opacity. The opacity of an overlay applies on top of
* those of its layers, so that they stay different from one another. A value that is computed
* (an expression) cannot always be scaled: the opacity replaces it, unless it is left at 1.
*/
export function getOpacityPaint(
layer: LayerSpecification,
opacity: number
): Record<string, unknown> {
if (layer.type === 'hillshade') {
return { 'hillshade-exaggeration': opacity / 2 };
}
const paint = (layer.paint ?? {}) as Record<string, unknown>;
return Object.fromEntries(
(opacityProperties[layer.type] ?? []).map((property) => {
const value = paint[property];
if (typeof value === 'number') {
return [property, value * opacity];
}
return [property, value !== undefined && opacity === 1 ? value : opacity];
})
);
}
export function anySelectedLayer(node: LayerTreeType) { export function anySelectedLayer(node: LayerTreeType) {
return ( return (
+1 -1
View File
@@ -6,7 +6,7 @@ import MapPopupComponent from '$lib/components/map/MapPopup.svelte';
export type PopupItem<T = any> = { export type PopupItem<T = any> = {
/** Has a position (`lng` and `lat`). */ /** Has a position (`lng` and `lat`). */
item: T; item: T;
/** What the item is: a `WaypointDetails`, a `TrackpointDetails` or an Overpass element. */ /** What the item is: a `WaypointDetails`, the coordinates of a point or an Overpass element. */
kind: 'waypoint' | 'trackpoint' | 'overpass'; kind: 'waypoint' | 'trackpoint' | 'overpass';
fileId?: string; fileId?: string;
hide?: () => void; hide?: () => void;
+2
View File
@@ -10,6 +10,7 @@ import { settings } from '$lib/state/settings';
import { tick } from 'svelte'; import { tick } from 'svelte';
import { ANCHOR_LAYER_KEY, StyleManager } from '$lib/components/map/style'; import { ANCHOR_LAYER_KEY, StyleManager } from '$lib/components/map/style';
import { MapLayerEventManager } from '$lib/components/map/map-layer-event-manager'; import { MapLayerEventManager } from '$lib/components/map/map-layer-event-manager';
import { registerOpenSatelliteProtocol } from '$lib/components/map/open-satellite';
const { treeFileView, elevationProfile, bottomPanelSize, rightPanelSize, distanceUnits } = settings; const { treeFileView, elevationProfile, bottomPanelSize, rightPanelSize, distanceUnits } = settings;
@@ -41,6 +42,7 @@ export class MapLibreGLMap {
geolocate: boolean geolocate: boolean
) { ) {
maplibregl.setWorkerUrl(workerUrl); maplibregl.setWorkerUrl(workerUrl);
registerOpenSatelliteProtocol(maptilerKey);
this._maptilerKey = maptilerKey; this._maptilerKey = maptilerKey;
this._styleManager = new StyleManager(this._mapStore, this._maptilerKey); this._styleManager = new StyleManager(this._mapStore, this._maptilerKey);
// MapLibre gives Safari more workers, but only recognizes it by its user agent: not // MapLibre gives Safari more workers, but only recognizes it by its user agent: not
@@ -0,0 +1,147 @@
// Which imagery each tile of the open satellite basemap is made of, from saved tiles of the
// tileset of the countries.
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { describe, it } from 'node:test';
import { fallbackNeeded, planTile, type CountryTiles } from './open-satellite';
const fixtures = new URL('../../../test/fixtures/satellite-countries/', import.meta.url);
/** The saved tiles, none where there is no file, and the ones that were asked for. */
function savedTiles() {
const asked: string[] = [];
const tiles: CountryTiles = async (z, x, y) => {
asked.push(`${z}/${x}/${y}`);
try {
return new Uint8Array(readFileSync(new URL(`${z}-${x}-${y}.mvt`, fixtures))).buffer;
} catch {
return null;
}
};
return { asked, tiles };
}
function tile(lon: number, lat: number, z: number): [number, number, number] {
const n = 2 ** z;
const sin = Math.sin((lat * Math.PI) / 180);
return [
z,
Math.floor(((lon + 180) / 360) * n),
Math.floor((0.5 - Math.log((1 + sin) / (1 - sin)) / (4 * Math.PI)) * n),
];
}
async function plan([z, x, y]: [number, number, number], tiles: CountryTiles) {
const { parts, fallback } = await planTile(z, x, y, tiles);
return { parts: parts.map((p) => `${p.source.id}:${p.relation}`).sort(), fallback };
}
describe('planTile', () => {
it('takes every tile up to zoom 12 from the imagery of the whole world', async () => {
const { asked, tiles } = savedTiles();
assert.deepEqual(await plan(tile(2.35, 48.85, 12), tiles), { parts: [], fallback: true });
assert.deepEqual(asked, []);
});
it('takes a tile far from every country from the fallback, without asking for countries', async () => {
const { asked, tiles } = savedTiles();
// London, and the Atlantic
assert.deepEqual(await plan(tile(-0.12, 51.5, 14), tiles), { parts: [], fallback: true });
assert.deepEqual(await plan(tile(-30, 40, 13), tiles), { parts: [], fallback: true });
assert.deepEqual(asked, []);
});
it('takes a tile inside a country from its agency alone', async () => {
const { tiles } = savedTiles();
assert.deepEqual(await plan(tile(2.35, 48.85, 15), tiles), {
parts: ['FR:full'],
fallback: false,
});
});
it('puts the countries of a border tile together, over the fallback where none is', async () => {
const { tiles } = savedTiles();
// Basel: France, Switzerland and Germany, which is not in the patchwork
assert.deepEqual(await plan([13, 4268, 2861], tiles), {
parts: ['CH:partial', 'FR:partial'],
fallback: true,
});
// only Germany
assert.deepEqual(await plan([13, 4269, 2860], tiles), { parts: [], fallback: true });
});
it('needs no fallback where the countries cover the tile between them', async () => {
const { tiles } = savedTiles();
// Wattrelos: France and Belgium
assert.deepEqual(await plan([13, 4166, 2750], tiles), {
parts: ['BE:partial', 'FR:partial'],
fallback: false,
});
// Baarle, with its enclaves of Belgium and the Netherlands
assert.deepEqual(await plan([13, 4208, 2726], tiles), {
parts: ['BE:partial', 'NL:partial'],
fallback: false,
});
// Elvas and Badajoz, on the border of Portugal and Spain
assert.deepEqual(await plan([13, 3935, 3135], tiles), {
parts: ['ES:partial', 'PT:partial'],
fallback: false,
});
});
it('takes a country from its agency next to one without open imagery', async () => {
const { tiles } = savedTiles();
// Padborg, with Germany to the south
assert.deepEqual(await plan([13, 4309, 2597], tiles), {
parts: ['DK:partial'],
fallback: true,
});
});
it('leaves the islands of Portugal to the fallback', async () => {
const { asked, tiles } = savedTiles();
// Funchal, on Madeira
assert.deepEqual(await plan(tile(-16.91, 32.65, 15), tiles), { parts: [], fallback: true });
assert.deepEqual(asked, []);
});
it('asks for a tile of the countries once for all the tiles of imagery inside it', async () => {
const { asked, tiles } = savedTiles();
// around Lausanne, which no other test asks for
const [, x, y] = tile(6.63, 46.52, 12);
for (let dx = 0; dx < 4; dx++) {
for (let dy = 0; dy < 4; dy++) {
await planTile(14, x * 4 + dx, y * 4 + dy, tiles);
}
}
assert.deepEqual(asked, [`12/${x}/${y}`]);
});
});
describe('fallbackNeeded', () => {
it('is not needed up to zoom 12, where the imagery of the whole world is', async () => {
const { asked, tiles } = savedTiles();
// a tile of 512 pixels at zoom 11 covers four tiles of the open imagery at zoom 12
assert.equal(await fallbackNeeded(...tile(-0.12, 51.5, 11), tiles), false);
assert.deepEqual(asked, []);
});
it('is needed far from every country, without asking for countries', async () => {
const { asked, tiles } = savedTiles();
assert.equal(await fallbackNeeded(...tile(-0.12, 51.5, 13), tiles), true);
assert.deepEqual(asked, []);
});
it('is not needed where the countries cover its four tiles', async () => {
const { tiles } = savedTiles();
// Paris, and Wattrelos between France and Belgium
assert.equal(await fallbackNeeded(...tile(2.35, 48.85, 14), tiles), false);
assert.equal(await fallbackNeeded(12, 2083, 1375, tiles), false);
});
it('is needed where one of its four tiles is outside the countries', async () => {
const { tiles } = savedTiles();
// Basel, with a tile entirely in Germany
assert.equal(await fallbackNeeded(12, 2134, 1430, tiles), true);
});
});
@@ -0,0 +1,494 @@
import * as maplibregl from 'maplibre-gl';
import { VectorTile } from '@mapbox/vector-tile';
import { PbfReader } from 'pbf';
/**
* A satellite basemap made of the open imagery of national mapping agencies, in two layers drawn
* through custom protocols:
* - above, the open imagery: each tile is taken from the agency whose country covers it, the
* tiles on a border are put together on a canvas clipped to the border of each country, and
* the rest is transparent;
* - below, the commercial fallback, whose tiles are only fetched where the open imagery leaves
* something to see.
*/
export const OPEN_SATELLITE_PROTOCOL = 'opensat';
type TileUrl = (z: number, x: number, y: number) => string;
type ImagerySource = {
/** ISO code of the country, in the tileset of the countries */
id: string;
url: TileUrl;
/** Above it, the tile of this zoom level is scaled up. */
maxzoom: number;
};
const xyz =
(template: string): TileUrl =>
(z, x, y) =>
template.replace('{z}', String(z)).replace('{x}', String(x)).replace('{y}', String(y));
/**
* For a WMS: the tile as an image of its bounds in Web Mercator. A WMS that draws nothing below
* the scale of zoom `minzoom` is asked for a larger image there, at that scale.
*/
const wms =
(base: string, minzoom = 0): TileUrl =>
(z, x, y) => {
const half = 20037508.342789244;
const size = (2 * half) / 2 ** z;
const pixels = 256 * 2 ** Math.max(0, minzoom - z);
const bbox = [
x * size - half,
half - (y + 1) * size,
(x + 1) * size - half,
half - y * size,
];
return `${base}&SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&STYLES=&CRS=EPSG:3857&WIDTH=${pixels}&HEIGHT=${pixels}&BBOX=${bbox.join(',')}`;
};
const ignOrthophotos = xyz(
'https://data.geopf.fr/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=ORTHOIMAGERY.ORTHOPHOTOS&STYLE=normal&FORMAT=image/jpeg&TILEMATRIXSET=PM&TILEMATRIX={z}&TILECOL={x}&TILEROW={y}'
);
/**
* Up to zoom 12, IGN's orthophotos cover the whole world with a mosaic of satellite images: all
* tiles come from it there, and the national sources and the commercial fallback only above.
*/
const world: ImagerySource = { id: 'world', url: ignOrthophotos, maxzoom: 12 };
/** In order of priority, the first one covering a point is used. */
const sources: ImagerySource[] = [
{
id: 'CH',
url: xyz(
'https://wmts.geo.admin.ch/1.0.0/ch.swisstopo.swissimage/default/current/3857/{z}/{x}/{y}.jpeg'
),
maxzoom: 20,
},
{
id: 'FR',
url: ignOrthophotos,
maxzoom: 19,
},
{
id: 'ES',
url: xyz(
'https://www.ign.es/wmts/pnoa-ma?layer=OI.OrthoimageCoverage&style=default&tilematrixset=GoogleMapsCompatible&Service=WMTS&Request=GetTile&Version=1.0.0&Format=image/jpeg&TileMatrix={z}&TileCol={x}&TileRow={y}'
),
maxzoom: 19,
},
{
id: 'AT',
url: xyz(
'https://mapsneu.wien.gv.at/basemap/bmaporthofoto30cm/normal/google3857/{z}/{y}/{x}.jpeg'
),
maxzoom: 19,
},
{
id: 'NL',
url: xyz(
'https://service.pdok.nl/hwh/luchtfotorgb/wmts/v1_0/Actueel_orthoHR/EPSG:3857/{z}/{x}/{y}.jpeg'
),
maxzoom: 19,
},
{
id: 'LU',
url: xyz(
'https://wmts1.geoportail.lu/opendata/wmts/ortho_latest/GLOBAL_WEBMERCATOR_4_V3/{z}/{x}/{y}.jpeg'
),
maxzoom: 19,
},
{
id: 'CZ',
url: xyz(
'https://ags.cuzk.gov.cz/arcgis1/rest/services/ORTOFOTO_WM/MapServer/tile/{z}/{y}/{x}'
),
maxzoom: 19,
},
{
id: 'BE',
url: xyz(
'https://wmts.ngi.be/inspire/ortho/1.0.0/orthoimage_coverage/default/3857/latest/{z}/{y}/{x}.png'
),
maxzoom: 19,
},
{
id: 'PL',
url: xyz(
'https://mapy.geoportal.gov.pl/wss/service/PZGIK/ORTO/WMTS/StandardResolution?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=ORTOFOTOMAPA&STYLE=default&FORMAT=image/jpeg&TILEMATRIXSET=EPSG:3857&TILEMATRIX=EPSG:3857:{z}&TILEROW={y}&TILECOL={x}'
),
maxzoom: 19,
},
{
// mainland Portugal only, as in the tileset of the countries
id: 'PT',
url: wms(
'https://cartografia.dgterritorio.gov.pt/wms/ortos2025?LAYERS=Ortos2025-RGB&FORMAT=image/jpeg',
// blank at zoom 13
14
),
maxzoom: 19,
},
{
id: 'DK',
url: xyz(
'https://wmts.datafordeler.dk/GeoDanmarkOrto/orto_foraar_webm/1.0.0/WMTS/orto_foraar_webm/default/DFD_GoogleMapsCompatible/{z}/{y}/{x}.jpg?apikey=pDSRuC5YLFT3jHf4XbaWDGSa9Td4TfYiGiB7YfhCKikJhZE6xibJAlaNp1KpDAzHdDss9DSKdq3nNoT2UFU3cmecaLrcRNTOc'
),
maxzoom: 20,
},
];
export const openSatelliteAttribution = [
'<a href="https://www.swisstopo.admin.ch/" target="_blank">swisstopo</a>',
'<a href="https://geoservices.ign.fr/" target="_blank">IGN-F/Géoplateforme</a>',
'PNOA © <a href="https://www.ign.es/" target="_blank">IGN España</a>',
'<a href="https://basemap.at/" target="_blank">basemap.at</a>',
'<a href="https://www.pdok.nl/" target="_blank">PDOK</a>',
'<a href="https://geoportail.lu/" target="_blank">geoportail.lu</a>',
'<a href="https://cuzk.gov.cz/" target="_blank">ČÚZK</a>',
'<a href="https://www.ngi.be/" target="_blank">NGI/IGN</a>',
'<a href="https://www.geoportal.gov.pl/" target="_blank">GUGiK</a>',
'<a href="https://www.dgterritorio.gov.pt/" target="_blank">DGT</a>',
'GeoDanmark © <a href="https://klimadatastyrelsen.dk/" target="_blank">Klimadatastyrelsen</a>',
].join(', ');
// Countries, from the tileset of their polygons, built from the borders of OpenStreetMap
const COUNTRIES_URL = xyz('https://tiles.gpx.studio/satellite-countries/{z}/{x}/{y}.mvt');
/** The only zoom level of the tileset. */
const COUNTRIES_ZOOM = 12;
const sourceByCountry = new Map(sources.map((source) => [source.id, source]));
/** The tiles of the countries, from their tileset: null where there is none. */
export type CountryTiles = (z: number, x: number, y: number) => Promise<ArrayBuffer | null>;
async function fetchCountryTile(z: number, x: number, y: number): Promise<ArrayBuffer | null> {
try {
const response = await fetch(COUNTRIES_URL(z, x, y));
if (!response.ok) return null;
const bytes = await response.arrayBuffer();
return bytes.byteLength > 0 ? bytes : null;
} catch {
return null;
}
}
/** A tile of the countries is shared by the 4^(z - 12) tiles of imagery inside it. */
const countryTiles = new Map<string, Promise<ArrayBuffer | null>>();
function getCountryTile(x: number, y: number, tiles: CountryTiles) {
const key = `${x}/${y}`;
let tile = countryTiles.get(key);
if (tile) {
// the last used, at the end of the map
countryTiles.delete(key);
} else {
tile = tiles(COUNTRIES_ZOOM, x, y);
if (countryTiles.size >= 256) countryTiles.delete(countryTiles.keys().next().value!);
}
countryTiles.set(key, tile);
return tile;
}
/** The tiles of zoom `zoom` where there is a country, as y * 2^zoom + x. */
let areas: Promise<{ zoom: number; tiles: Set<number> }> | null = null;
function getAreas() {
areas ??= import('$lib/data/satellite-countries.json').then((module) => ({
zoom: module.default.zoom,
tiles: new Set(module.default.tiles),
}));
return areas;
}
// Geometry, in pixels of the tile of imagery
const TILE_SIZE = 256;
const TILE_AREA = TILE_SIZE * TILE_SIZE;
type Ring = [number, number][];
/** The ring cut to the tile (Sutherland–Hodgman), which keeps its orientation. */
function clipRing(ring: Ring): Ring {
let points = ring;
const edges: [(p: [number, number]) => number, number][] = [
[(p) => p[0], 0],
[(p) => -p[0], -TILE_SIZE],
[(p) => p[1], 0],
[(p) => -p[1], -TILE_SIZE],
];
for (const [value, min] of edges) {
if (points.length === 0) break;
const clipped: Ring = [];
for (let i = 0; i < points.length; i++) {
const current = points[i];
const previous = points[(i + points.length - 1) % points.length];
const inCurrent = value(current) >= min;
const inPrevious = value(previous) >= min;
if (inCurrent !== inPrevious) {
const t = (min - value(previous)) / (value(current) - value(previous));
clipped.push([
previous[0] + t * (current[0] - previous[0]),
previous[1] + t * (current[1] - previous[1]),
]);
}
if (inCurrent) clipped.push(current);
}
points = clipped;
}
return points;
}
/** Positive for an outer ring of a vector tile, negative for a hole. */
function signedArea(ring: Ring) {
let area = 0;
for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
area += ring[j][0] * ring[i][1] - ring[i][0] * ring[j][1];
}
return area / 2;
}
/** The polygons of the countries with imagery in the tile, cut to it, with their area. */
function countriesInTile(
bytes: ArrayBuffer,
z: number,
x: number,
y: number
): { source: ImagerySource; rings: Ring[]; area: number }[] {
const layer = new VectorTile(new PbfReader(bytes)).layers.countries;
if (!layer) return [];
const d = z - COUNTRIES_ZOOM;
const scale = (TILE_SIZE * 2 ** d) / layer.extent;
const offsetX = (x - ((x >> d) << d)) * TILE_SIZE;
const offsetY = (y - ((y >> d) << d)) * TILE_SIZE;
const countries = [];
for (let i = 0; i < layer.length; i++) {
const feature = layer.feature(i);
const source = sourceByCountry.get(String(feature.properties.country));
if (!source) continue;
const rings = feature
.loadGeometry()
.map((ring) =>
clipRing(ring.map((p) => [p.x * scale - offsetX, p.y * scale - offsetY]))
)
.filter((ring) => ring.length >= 3);
const area = rings.reduce((sum, ring) => sum + signedArea(ring), 0);
// less than a pixel: a polygon of the tile of the countries outside this one
if (area >= 1) countries.push({ source, rings, area });
}
return countries;
}
// Imagery
async function fetchBytes(url: string, signal: AbortSignal): Promise<ArrayBuffer | null> {
try {
const response = await fetch(url, { signal });
if (!response.ok) return null;
const contentType = response.headers.get('content-type') ?? '';
if (!contentType.startsWith('image/')) return null;
const bytes = await response.arrayBuffer();
return (await isBlank(bytes)) ? null : bytes;
} catch (e) {
if (signal.aborted) throw e;
return null;
}
}
/**
* Whether the image is all white or transparent: what some agencies give where they have no
* imagery, such as IGN on the French part of Lake Geneva. Such an image is small, the others
* are not even decoded.
*/
async function isBlank(bytes: ArrayBuffer) {
if (bytes.byteLength > 4096) return false;
try {
const image = await createImageBitmap(new Blob([bytes]));
const canvas = new OffscreenCanvas(16, 16);
const context = canvas.getContext('2d')!;
context.drawImage(image, 0, 0, 16, 16);
image.close();
const pixels = context.getImageData(0, 0, 16, 16).data;
for (let i = 0; i < pixels.length; i += 4) {
const transparent = pixels[i + 3] < 8;
const white = pixels[i] >= 250 && pixels[i + 1] >= 250 && pixels[i + 2] >= 250;
if (!transparent && !white) return false;
}
return true;
} catch {
return false;
}
}
/** The image of the tile, or of the part of its ancestor at the max zoom of the source. */
async function fetchImage(
url: TileUrl,
maxzoom: number,
z: number,
x: number,
y: number,
signal: AbortSignal
): Promise<{ image: ImageBitmap; sx: number; sy: number; size: number } | null> {
const d = Math.max(0, z - maxzoom);
const bytes = await fetchBytes(url(z - d, x >> d, y >> d), signal);
if (!bytes) return null;
try {
const image = await createImageBitmap(new Blob([bytes]));
const size = image.width / 2 ** d;
return {
image,
sx: (x - ((x >> d) << d)) * size,
sy: (y - ((y >> d) << d)) * size,
size,
};
} catch {
return null;
}
}
function clipTo(context: OffscreenCanvasRenderingContext2D, rings: Ring[]) {
context.beginPath();
for (const ring of rings) {
ring.forEach(([px, py], i) => (i === 0 ? context.moveTo(px, py) : context.lineTo(px, py)));
context.closePath();
}
context.clip('evenodd');
}
type TilePart = { source: ImagerySource; relation: 'full' | 'partial'; rings: Ring[] };
/**
* The sources of the tile, in drawing order: the one covering the whole tile, or those
* covering part of it, and whether the fallback is needed below them.
*/
export async function planTile(
z: number,
x: number,
y: number,
tiles: CountryTiles = fetchCountryTile
): Promise<{ parts: TilePart[]; fallback: boolean }> {
const none = { parts: [], fallback: true };
if (z <= world.maxzoom) return none;
const { zoom, tiles: withCountries } = await getAreas();
const d = z - zoom;
if (!withCountries.has((y >> d) * 2 ** zoom + (x >> d))) return none;
const bytes = await getCountryTile(x >> (z - COUNTRIES_ZOOM), y >> (z - COUNTRIES_ZOOM), tiles);
if (!bytes) return none;
const countries = countriesInTile(bytes, z, x, y);
// a pixel of margin, for the rounding of the coordinates of the tiles
const whole = countries.find((country) => country.area >= TILE_AREA - TILE_SIZE);
if (whole) {
return { parts: [{ source: whole.source, relation: 'full', rings: [] }], fallback: false };
}
const covered = countries.reduce((sum, country) => sum + country.area, 0);
return {
parts: countries.map(({ source, rings }) => ({ source, relation: 'partial', rings })),
fallback: covered < TILE_AREA - TILE_SIZE,
};
}
function transparentTile() {
const canvas = new OffscreenCanvas(1, 1);
// without a context, the canvas cannot give its image
canvas.getContext('2d');
return canvas.transferToImageBitmap();
}
/**
* The tile of the layer of the open imagery: up to zoom 12, the imagery of the whole world, and
* above, the imagery of each country clipped to its border, transparent where there is none.
*/
export async function loadTile(
z: number,
x: number,
y: number,
signal: AbortSignal
): Promise<ArrayBuffer | ImageBitmap> {
if (z <= world.maxzoom) {
return (await fetchBytes(world.url(z, x, y), signal)) ?? transparentTile();
}
const { parts } = await planTile(z, x, y);
if (parts.length === 0) return transparentTile();
// a single tile as it is, without drawing it again
if (parts.length === 1 && parts[0].relation === 'full' && z <= parts[0].source.maxzoom) {
return (await fetchBytes(parts[0].source.url(z, x, y), signal)) ?? transparentTile();
}
const images = await Promise.all(
parts.map((p) => fetchImage(p.source.url, p.source.maxzoom, z, x, y, signal))
);
const canvas = new OffscreenCanvas(TILE_SIZE, TILE_SIZE);
const context = canvas.getContext('2d')!;
parts.forEach((p, i) => {
const result = images[i];
if (!result) return;
context.save();
if (p.relation === 'partial') clipTo(context, p.rings);
const { image, sx, sy, size } = result;
context.drawImage(image, sx, sy, size, size, 0, 0, TILE_SIZE, TILE_SIZE);
context.restore();
image.close();
});
return canvas.transferToImageBitmap();
}
// The commercial fallback, in its own layer below, with its tiles of 512 pixels as they are
export const OPEN_SATELLITE_FALLBACK_PROTOCOL = 'opensat-fallback';
export const openSatelliteFallbackAttribution =
'<a href="https://www.maptiler.com/copyright/" target="_blank">© MapTiler</a>';
/**
* Whether the tile of 512 pixels of the fallback is seen somewhere: whether one of the four
* tiles of 256 pixels of the open imagery that it covers, one zoom level above, needs it.
*/
export async function fallbackNeeded(
z: number,
x: number,
y: number,
tiles: CountryTiles = fetchCountryTile
): Promise<boolean> {
const plans = await Promise.all(
[0, 1, 2, 3].map((i) => planTile(z + 1, 2 * x + (i % 2), 2 * y + (i >> 1), tiles))
);
return plans.some((plan) => plan.fallback && z + 1 > world.maxzoom);
}
export async function loadFallbackTile(
z: number,
x: number,
y: number,
maptilerKey: string,
signal: AbortSignal
): Promise<ArrayBuffer | ImageBitmap> {
if (!(await fallbackNeeded(z, x, y))) return transparentTile();
const url = `https://api.maptiler.com/tiles/satellite-v2/${z}/${x}/${y}.jpg?key=${maptilerKey}`;
const response = await fetch(url, { signal });
if (!response.ok) throw new Error(`No imagery for tile ${z}/${x}/${y}: ${response.status}`);
return await response.arrayBuffer();
}
function tileOf(url: string) {
const match = url.match(/(\d+)\/(\d+)\/(\d+)$/);
if (!match) throw new Error(`Invalid tile URL: ${url}`);
return match.slice(1).map(Number) as [number, number, number];
}
export function registerOpenSatelliteProtocol(maptilerKey: string) {
maplibregl.addProtocol(OPEN_SATELLITE_PROTOCOL, async (params, abortController) => {
const [z, x, y] = tileOf(params.url);
return { data: await loadTile(z, x, y, abortController.signal) };
});
maplibregl.addProtocol(OPEN_SATELLITE_FALLBACK_PROTOCOL, async (params, abortController) => {
const [z, x, y] = tileOf(params.url);
return {
data: await loadFallbackTile(z, x, y, maptilerKey, abortController.signal),
};
});
}
@@ -0,0 +1,252 @@
// How the map shows the overlays: here, those of extensions that give the URL of their style.
import assert from 'node:assert/strict';
import { afterEach, beforeEach, describe, it } from 'node:test';
import type { Map as MapLibreMap, StyleSpecification } from 'maplibre-gl';
import { writable } from 'svelte/store';
import { basemaps, overlays, type LayerTreeType } from '$lib/data/layers';
import { engine } from '$lib/engine';
import { settings } from '$lib/state/settings';
import { StyleManager } from './style';
import { openSatelliteAttribution, openSatelliteFallbackAttribution } from './open-satellite';
const URL_A = 'https://example.com/a.json';
const URL_B = 'https://example.com/b.json';
const ID = 'extension-Heatmaps/a';
const style = (tiles: string): StyleSpecification => ({
version: 8,
sources: { tiles: { type: 'raster', tiles: [tiles], tileSize: 256 } },
layers: [{ id: 'tiles', type: 'raster', source: 'tiles' }],
});
const original = {
set: engine.setSetting,
delete: engine.deleteSetting,
fetch: globalThis.fetch,
error: console.error,
};
/** A map that only knows of its overlays. */
function fakeMap() {
const sources = new Map<string, { tiles: string[] }>([['empty-source', { tiles: [] }]]);
const layers = new Map<string, { source: string; paint: Record<string, unknown> }>();
return {
sources,
layers,
on: () => {},
setStyle: () => {},
getPitch: () => 0,
getTerrain: () => null,
setTerrain: () => {},
getSource: (id: string) => sources.get(id),
addSource: (id: string, source: { tiles: string[] }) => sources.set(id, source),
getLayer: (id: string) => layers.get(id),
addLayer: (layer: { id: string; source: string; paint: Record<string, unknown> }) =>
layers.set(layer.id, layer),
removeLayer: (id: string) => layers.delete(id),
setPaintProperty: (id: string, name: string, value: unknown) => {
layers.get(id)!.paint[name] = value;
},
};
}
/** Shows the overlay, and gives the manager of the map. */
function setUp(fake: ReturnType<typeof fakeMap>) {
settings.currentOverlays.update((tree) => {
(tree.overlays as LayerTreeType).Heatmaps = { [ID]: true };
return tree;
});
const store = writable<MapLibreMap | null>(null);
const manager = new StyleManager(store, '');
store.set(fake as unknown as MapLibreMap);
return manager;
}
beforeEach(() => {
engine.setSetting = () => {};
engine.deleteSetting = () => {};
settings.connect({});
settings.initialize();
});
afterEach(() => {
delete overlays[ID];
delete overlays.plainUrl;
settings.currentOverlays.update((tree) => {
delete (tree.overlays as LayerTreeType).Heatmaps;
delete (tree.overlays as LayerTreeType).plainUrl;
return tree;
});
engine.setSetting = original.set;
engine.deleteSetting = original.delete;
globalThis.fetch = original.fetch;
console.error = original.error;
});
/** Answers the style requests with the styles of `responses`, by URL. */
function answerWith(responses: Record<string, StyleSpecification>) {
globalThis.fetch = (async (url: string) =>
Object.hasOwn(responses, url)
? new Response(JSON.stringify(responses[url]))
: new Response(JSON.stringify(style('https://basemap/{z}')))) as typeof fetch;
}
describe('StyleManager, with the style URL of an extension', () => {
it('fetches it, and prefixes the ids of its sources and layers', async () => {
answerWith({ [URL_A]: style('https://a/{z}') });
overlays[ID] = URL_A;
const fake = fakeMap();
await setUp(fake).updateOverlays();
assert.deepEqual(fake.sources.get(`${ID}/tiles`)?.tiles, ['https://a/{z}']);
assert.equal(fake.layers.get(`${ID}/tiles`)?.source, `${ID}/tiles`);
assert.ok(!fake.sources.has('tiles'));
});
it('uses the opacity of the overlay', async () => {
answerWith({ [URL_A]: style('https://a/{z}') });
overlays[ID] = URL_A;
settings.opacities.update((opacities) => ({ ...opacities, [ID]: 0.3 }));
const fake = fakeMap();
await setUp(fake).updateOverlays();
assert.equal(fake.layers.get(`${ID}/tiles`)?.paint['raster-opacity'], 0.3);
});
it('removes its layers when it is hidden', async () => {
answerWith({ [URL_A]: style('https://a/{z}') });
overlays[ID] = URL_A;
const fake = fakeMap();
const manager = setUp(fake);
await manager.updateOverlays();
assert.ok(fake.layers.has(`${ID}/tiles`));
settings.currentOverlays.update((tree) => {
(tree.overlays as LayerTreeType).Heatmaps = { [ID]: false };
return tree;
});
await manager.updateOverlays();
assert.ok(!fake.layers.has(`${ID}/tiles`));
});
it('does not fetch it while the overlay is hidden', async () => {
const urls: string[] = [];
answerWith({});
const answer = globalThis.fetch;
globalThis.fetch = ((url: string) => {
urls.push(url);
return answer(url);
}) as typeof fetch;
overlays[ID] = URL_A;
settings.currentOverlays.update((tree) => {
(tree.overlays as LayerTreeType).Heatmaps = { [ID]: false };
return tree;
});
const store = writable<MapLibreMap | null>(null);
const manager = new StyleManager(store, '');
store.set(fakeMap() as unknown as MapLibreMap);
await manager.updateOverlays();
assert.ok(!urls.includes(URL_A));
});
it('ignores a style that was replaced or removed while it was fetched', async () => {
for (const next of [URL_B, undefined]) {
let respond: (response: Response) => void = () => {};
const answers: Record<string, StyleSpecification> = {
[URL_B]: style('https://b/{z}'),
};
answerWith(answers);
const answer = globalThis.fetch;
globalThis.fetch = ((url: string) =>
url === URL_A
? new Promise((resolve) => (respond = resolve))
: answer(url)) as typeof fetch;
overlays[ID] = URL_A;
const fake = fakeMap();
const manager = setUp(fake);
const pending = manager.updateOverlays();
await new Promise((resolve) => setTimeout(resolve));
if (next) {
overlays[ID] = next;
} else {
delete overlays[ID];
}
respond(new Response(JSON.stringify(style('https://a/{z}'))));
await pending;
assert.ok(!fake.sources.has(`${ID}/tiles`));
await manager.updateOverlays();
assert.deepEqual(
fake.sources.get(`${ID}/tiles`)?.tiles,
next ? ['https://b/{z}'] : undefined
);
}
});
it('logs a style that cannot be used, which leaves the others alone', async () => {
const logged: unknown[] = [];
console.error = (...args) => logged.push(args);
for (const answer of [
new Response('', { status: 404 }),
new Response(JSON.stringify({ version: 8, sources: {} })),
]) {
answerWith({});
const basemap = globalThis.fetch;
globalThis.fetch = ((url: string) =>
url === URL_A ? Promise.resolve(answer.clone()) : basemap(url)) as typeof fetch;
overlays[ID] = URL_A;
const fake = fakeMap();
logged.length = 0;
await setUp(fake).updateOverlays();
assert.ok(logged.length > 0);
assert.equal(fake.layers.size, 0);
}
});
it('does not prefix the style URL of anything else', async () => {
answerWith({ [URL_A]: style('https://a/{z}') });
overlays.plainUrl = URL_A;
settings.currentOverlays.update((tree) => {
(tree.overlays as LayerTreeType).plainUrl = { plainUrl: true };
return tree;
});
const fake = fakeMap();
const store = writable<MapLibreMap | null>(null);
const manager = new StyleManager(store, '');
store.set(fake as unknown as MapLibreMap);
await manager.updateOverlays();
assert.ok(fake.sources.has('tiles'));
assert.ok(fake.layers.has('tiles'));
});
});
describe('StyleManager, with a basemap of the open satellite imagery', () => {
it('gives its imagery the credits of the agencies, its fallback those of MapTiler, and leaves the other sources alone', async () => {
answerWith({
[basemaps.libertySatellite as string]: {
version: 8,
sources: {
satellite: { type: 'raster', tiles: ['opensat://{z}/{x}/{y}'], tileSize: 256 },
fallback: {
type: 'raster',
tiles: ['opensat-fallback://{z}/{x}/{y}'],
tileSize: 512,
},
other: { type: 'raster', tiles: ['https://other/{z}/{x}/{y}'] },
},
layers: [{ id: 'satellite', type: 'raster', source: 'satellite' }],
},
});
const manager = new StyleManager(writable<MapLibreMap | null>(null), 'key');
const built = await manager.buildStyle('libertySatellite');
assert.equal(
(built.sources.satellite as { attribution?: string }).attribution,
openSatelliteAttribution
);
assert.equal(
(built.sources.fallback as { attribution?: string }).attribution,
openSatelliteFallbackAttribution
);
assert.equal((built.sources.other as { attribution?: string }).attribution, undefined);
});
});
+58 -20
View File
@@ -14,8 +14,14 @@ import {
overlays, overlays,
terrainSources, terrainSources,
} from '$lib/data/layers'; } from '$lib/data/layers';
import { getLayers } from '$lib/components/map/layer-control/utils'; import { getLayers, getOpacityPaint, prefixStyle } from '$lib/components/map/layer-control/utils';
import { i18n } from '$lib/i18n/i18n.svelte'; import { i18n } from '$lib/i18n/i18n.svelte';
import {
OPEN_SATELLITE_FALLBACK_PROTOCOL,
OPEN_SATELLITE_PROTOCOL,
openSatelliteAttribution,
openSatelliteFallbackAttribution,
} from '$lib/components/map/open-satellite';
const { currentBasemap, currentOverlays, customLayers, opacities, terrainSource, distanceUnits } = const { currentBasemap, currentOverlays, customLayers, opacities, terrainSource, distanceUnits } =
settings; settings;
@@ -123,6 +129,18 @@ export class StyleManager {
) { ) {
src.url = src.url.replace(maptilerKeyPlaceHolder, this._maptilerKey); src.url = src.url.replace(maptilerKeyPlaceHolder, this._maptilerKey);
} }
if (src && typeof src === 'object' && 'tiles' in src) {
// the credits of the open satellite imagery, kept with its code
if (src.tiles?.some((url) => url.startsWith(`${OPEN_SATELLITE_PROTOCOL}://`))) {
src.attribution = openSatelliteAttribution;
} else if (
src.tiles?.some((url) =>
url.startsWith(`${OPEN_SATELLITE_FALLBACK_PROTOCOL}://`)
)
) {
src.attribution = openSatelliteFallbackAttribution;
}
}
} }
} catch (e) { } catch (e) {
console.error(e instanceof Error ? e.message : e); console.error(e instanceof Error ? e.message : e);
@@ -147,13 +165,18 @@ export class StyleManager {
const custom = get(customLayers); const custom = get(customLayers);
const overlayOpacities = get(opacities); const overlayOpacities = get(opacities);
try { try {
// an overlay on the map can be gone from the tree, which has been replaced as a whole
const layers = getLayers(get(currentOverlays) ?? {}); const layers = getLayers(get(currentOverlays) ?? {});
this._pastOverlays.forEach((id) => (layers[id] ??= false));
for (const overlay in layers) { for (const overlay in layers) {
if (!layers[overlay]) {
if (this._pastOverlays.has(overlay)) {
const overlayInfo = custom[overlay]?.value ?? overlays[overlay]; const overlayInfo = custom[overlay]?.value ?? overlays[overlay];
if (!overlayInfo) {
// removed, together with what it had on the map
this._pastOverlays.delete(overlay);
} else if (!layers[overlay]) {
if (this._pastOverlays.has(overlay)) {
try { try {
const overlayStyle = await this.get(overlayInfo); const overlayStyle = await this.getOverlayStyle(overlay, overlayInfo);
for (const layer of overlayStyle.layers ?? []) { for (const layer of overlayStyle.layers ?? []) {
if (map_.getLayer(layer.id)) { if (map_.getLayer(layer.id)) {
map_.removeLayer(layer.id); map_.removeLayer(layer.id);
@@ -165,9 +188,10 @@ export class StyleManager {
this._pastOverlays.delete(overlay); this._pastOverlays.delete(overlay);
} }
} else { } else {
const overlayInfo = custom[overlay]?.value ?? overlays[overlay];
try { try {
const overlayStyle = await this.get(overlayInfo); const overlayStyle = await this.getOverlayStyle(overlay, overlayInfo);
// replaced or removed while it was fetched: its new style has its own turn
if (!custom[overlay] && overlays[overlay] !== overlayInfo) continue;
const opacity = overlayOpacities[overlay]; const opacity = overlayOpacities[overlay];
for (const sourceId in overlayStyle.sources) { for (const sourceId in overlayStyle.sources) {
@@ -177,21 +201,24 @@ export class StyleManager {
} }
for (const layer of overlayStyle.layers ?? []) { for (const layer of overlayStyle.layers ?? []) {
if (!map_.getLayer(layer.id)) { const paint =
if (opacity !== undefined) { opacity === undefined ? {} : getOpacityPaint(layer, opacity);
if (layer.type === 'raster') { if (map_.getLayer(layer.id)) {
if (!layer.paint) { for (const property in paint) {
layer.paint = {}; map_.setPaintProperty(
layer.id,
property as never,
paint[property] as never
);
} }
layer.paint['raster-opacity'] = opacity; } else {
} else if (layer.type === 'hillshade') { map_.addLayer(
if (!layer.paint) { {
layer.paint = {}; ...layer,
} paint: { ...layer.paint, ...paint },
layer.paint['hillshade-exaggeration'] = opacity / 2; } as LayerSpecification,
} ANCHOR_LAYER_KEY.overlays
} );
map_.addLayer(layer, ANCHOR_LAYER_KEY.overlays);
} }
} }
this._pastOverlays.add(overlay); this._pastOverlays.add(overlay);
@@ -221,6 +248,17 @@ export class StyleManager {
} }
} }
/** The style of an overlay. The ids of one from an extension's URL still have to be prefixed. */
private async getOverlayStyle(
overlay: string,
styleInfo: StyleSpecification | string
): Promise<StyleSpecification> {
const style = await this.get(styleInfo);
return typeof styleInfo === 'string' && overlay.startsWith('extension-')
? prefixStyle(overlay, style)
: style;
}
async get(styleInfo: StyleSpecification | string): Promise<StyleSpecification> { async get(styleInfo: StyleSpecification | string): Promise<StyleSpecification> {
if (typeof styleInfo === 'string') { if (typeof styleInfo === 'string') {
const styleUrl = styleInfo as string; const styleUrl = styleInfo as string;
@@ -218,6 +218,7 @@
</span> </span>
{:else} {:else}
<TimePicker <TimePicker
id="speed"
bind:value={speed} bind:value={speed}
showHours={false} showHours={false}
disabled={!canUpdate} disabled={!canUpdate}
@@ -243,6 +244,7 @@
{i18n._('toolbar.time.total_time')} {i18n._('toolbar.time.total_time')}
</Label> </Label>
<TimePicker <TimePicker
id="duration"
bind:value={movingTime} bind:value={movingTime}
disabled={!canUpdate} disabled={!canUpdate}
onChange={() => { onChange={() => {
@@ -633,6 +633,11 @@ export class RoutingControls {
const anchor = this.anchors[e.features![0].properties.anchorIndex]; const anchor = this.anchors[e.features![0].properties.anchorIndex];
if (!anchor) { if (!anchor) {
// The temporary anchor on the line is not one of the anchors (nor is a feature
// still rendered from before they were rebuilt), a click on it adds it
if (e.type === 'click') {
this.addIntermediateAnchor(e);
}
return; return;
} }
if (e.originalEvent.shiftKey) { if (e.originalEvent.shiftKey) {
@@ -45,6 +45,19 @@
let marker: Marker | null = null; let marker: Marker | null = null;
// A number field holds what is typed, out of range or empty (null) on the way to a
// coordinate, and a map click sets strings. MapLibre throws on a latitude past ±90.
function inRange(value: number | string | null, limit: number) {
if (value === null || value === '') {
return false;
}
const n = Number(value);
return Number.isFinite(n) && Math.abs(n) <= limit;
}
let latitudeValid = $derived(inRange(latitude, 90));
let longitudeValid = $derived(inRange(longitude, 180));
let coordinatesValid = $derived(latitudeValid && longitudeValid);
function reset() { function reset() {
if ($selectedWaypoint) { if ($selectedWaypoint) {
selectedWaypoint.reset(); selectedWaypoint.reset();
@@ -78,6 +91,9 @@
}); });
async function createOrUpdateWaypoint() { async function createOrUpdateWaypoint() {
if (!coordinatesValid) {
return;
}
if (typeof latitude === 'string') { if (typeof latitude === 'string') {
latitude = parseFloat(latitude); latitude = parseFloat(latitude);
} }
@@ -128,7 +144,8 @@
marker = null; marker = null;
} }
} else if (latitude != 0 || longitude != 0) { } else if (latitude != 0 || longitude != 0) {
if ($map) { // while a coordinate is being typed the pin stays where it last was
if ($map && coordinatesValid) {
if (marker) { if (marker) {
marker.setLngLat([longitude, latitude]).getElement().innerHTML = marker.setLngLat([longitude, latitude]).getElement().innerHTML =
getSvgForSymbol(symbolKey); getSvgForSymbol(symbolKey);
@@ -248,6 +265,7 @@
min={-90} min={-90}
max={90} max={90}
class="text-xs h-8" class="text-xs h-8"
aria-invalid={!latitudeValid}
disabled={!canCreate && !$selectedWaypoint} disabled={!canCreate && !$selectedWaypoint}
/> />
</div> </div>
@@ -261,6 +279,7 @@
min={-180} min={-180}
max={180} max={180}
class="text-xs h-8" class="text-xs h-8"
aria-invalid={!longitudeValid}
disabled={!canCreate && !$selectedWaypoint} disabled={!canCreate && !$selectedWaypoint}
/> />
</div> </div>
@@ -269,7 +288,7 @@
<div class="flex flex-row gap-1.5 items-center"> <div class="flex flex-row gap-1.5 items-center">
<Button <Button
variant="outline" variant="outline"
disabled={!canCreate && !$selectedWaypoint} disabled={(!canCreate && !$selectedWaypoint) || !coordinatesValid}
class="grow shrink h-fit min-h-8 whitespace-normal py-1" class="grow shrink h-fit min-h-8 whitespace-normal py-1"
onclick={createOrUpdateWaypoint} onclick={createOrUpdateWaypoint}
> >
@@ -1,63 +1,40 @@
<script lang="ts"> <script lang="ts" module>
import { Input } from '$lib/components/ui/input'; /** Shown by an empty field: real text rather than a placeholder, so that it can be selected. */
export const EMPTY_FIELD = '--';
let {
id,
value = $bindable(),
disabled,
oninput = () => {},
onchange = () => {},
onkeypress = () => {},
onfocusin = () => {},
class: className,
}: {
id: string;
value: string | number;
disabled?: boolean;
oninput?: (e: Event) => void;
onchange?: (e: Event) => void;
onkeypress?: (e: KeyboardEvent) => void;
onfocusin?: (e: FocusEvent) => void;
class?: string;
} = $props();
</script> </script>
<div> <script lang="ts">
<Input import { cn, type WithElementRef } from '$lib/utils.js';
{id} import type { HTMLInputAttributes } from 'svelte/elements';
let {
ref = $bindable(null),
value,
class: className,
...restProps
}: WithElementRef<Omit<HTMLInputAttributes, 'type' | 'value'>> & { value: string } = $props();
// The padding of the fields of a native time input, which is larger in Firefox.
const padding = 'px-px [@supports(-moz-appearance:none)]:px-[3px]';
</script>
<!-- The invisible copy of the text sizes the field to its exact width, like in a native time input. -->
<span class="relative inline-block">
<span aria-hidden="true" class={cn('invisible block whitespace-pre', padding)}>
{value || EMPTY_FIELD}
</span>
<input
bind:this={ref}
type="text" type="text"
step={1} inputmode="numeric"
bind:value autocomplete="off"
{disabled} value={value || EMPTY_FIELD}
{oninput} class={cn(
{onchange} 'absolute inset-0 w-full bg-transparent text-center outline-none',
{onkeypress} padding,
onfocusin={(e) => { className
let input = document.activeElement; )}
if (input instanceof HTMLInputElement) { onfocus={(e) => e.currentTarget.select()}
input.select(); {...restProps}
}
onfocusin(e);
}}
class="w-[22px] {className ?? ''}"
/> />
</div> </span>
<style lang="postcss">
@reference "tailwindcss";
div :global(input) {
@apply px-0.5;
@apply py-0;
@apply bg-transparent;
@apply text-right;
@apply border-none;
@apply shadow-none;
@apply focus:ring-0;
@apply focus:ring-offset-0;
@apply focus:outline-none;
@apply focus-visible:ring-0;
@apply focus-visible:ring-offset-0;
@apply focus-visible:outline-none;
}
</style>
@@ -1,174 +1,176 @@
<script lang="ts"> <script lang="ts">
import { untrack } from 'svelte'; import { untrack } from 'svelte';
import TimeComponentInput from './TimeComponentInput.svelte'; import { cn } from '$lib/utils.js';
import TimeComponentInput, { EMPTY_FIELD } from './TimeComponentInput.svelte';
let { let {
id,
showHours = true, showHours = true,
value = $bindable(), value = $bindable(),
disabled = false, disabled = false,
onChange = () => {}, onChange = () => {},
}: { }: {
/** Set on the first field, so that a label can target the picker. */
id?: string;
showHours?: boolean; showHours?: boolean;
value?: number; value?: number;
disabled?: boolean; disabled?: boolean;
onChange?: () => void; onChange?: () => void;
} = $props(); } = $props();
let hours: string | number = $state('--'); let hours = $state('');
let minutes: string | number = $state('--'); let minutes = $state('');
let seconds: string | number = $state('--'); let seconds = $state('');
function maybeParseInt(value: string | number): number { let hoursInput: HTMLInputElement | null = $state(null);
if (value === '--' || value === '') { let minutesInput: HTMLInputElement | null = $state(null);
return 0; let secondsInput: HTMLInputElement | null = $state(null);
}
return typeof value === 'string' ? parseInt(value) : value; function parseField(field: string): number {
return field === '' ? 0 : parseInt(field, 10);
} }
function computeValue(): number { function fieldsToSeconds(): number {
return Math.max( const total =
maybeParseInt(hours) * 3600 + maybeParseInt(minutes) * 60 + maybeParseInt(seconds), (showHours ? parseField(hours) * 3600 : 0) +
1 parseField(minutes) * 60 +
); parseField(seconds);
// Callers divide by this value, so it must stay positive.
return Math.max(total, 1);
} }
$effect(() => { function pad(field: number): string {
const val = computeValue(); return field.toString().padStart(2, '0');
untrack(() => { }
value = val;
});
});
$effect(() => { function showValue(newValue: number | undefined) {
if (value === undefined) { if (!Number.isFinite(newValue)) {
untrack(() => { hours = minutes = seconds = '';
hours = '--'; return;
minutes = '--'; }
seconds = '--'; const total = Math.max(Math.round(newValue!), 1);
}); const totalMinutes = Math.floor(total / 60);
} else {
untrack(() => {
if (value != computeValue()) {
let rounded = Math.max(Math.round(value!), 1);
if (showHours) { if (showHours) {
hours = Math.floor(rounded / 3600); hours = Math.floor(total / 3600).toString();
minutes = Math.floor((rounded % 3600) / 60) minutes = pad(totalMinutes % 60);
.toString()
.padStart(2, '0');
} else { } else {
minutes = Math.floor(rounded / 60).toString(); minutes = totalMinutes.toString();
} }
seconds = (rounded % 60).toString().padStart(2, '0'); seconds = pad(total % 60);
}
// Only the display follows `value`: it is written back on user input only, so that showing a
// value never rounds or overwrites it. A value that matches the fields comes from them, and
// must not reformat them during typing.
$effect(() => {
const newValue = value;
void showHours;
untrack(() => {
if (newValue !== fieldsToSeconds()) {
showValue(newValue);
} }
}); });
}
}); });
let container: HTMLDivElement; /** A field without an upper bound: hours, or minutes when there are no hours. */
let countKeyPress = 0; function normalizeUnbounded(input: string): string {
function onKeyPress(e: KeyboardEvent) { const digits = input.replace(/\D/g, '').slice(-6);
const target = e.target as HTMLInputElement | null; return digits === '' ? '' : parseInt(digits, 10).toString();
if (target && ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'].includes(e.key)) { }
countKeyPress++;
if (countKeyPress === 2) { /** Minutes or seconds: new digits shift in from the right, so "12" then "3" gives "23". */
const nextInput = function normalizeSexagesimal(input: string): string {
target.id === 'hours' const digits = input.replace(/\D/g, '').slice(-2);
? (container.querySelector('#minutes') as HTMLInputElement) return digits === '' ? '' : pad(Math.min(parseInt(digits, 10), 59));
: target.id === 'minutes' }
? (container.querySelector('#seconds') as HTMLInputElement)
: null; let digitsTyped = 0;
if (nextInput) {
nextInput.focus(); function handleInput(
e: Event & { currentTarget: HTMLInputElement },
normalize: (input: string) => string,
setField: (field: string) => void,
nextInput: HTMLInputElement | null
) {
const input = e.currentTarget;
const field = normalize(input.value);
// The state is unchanged when the input is rejected (a letter, for example), in which case
// Svelte would leave the rejected text in the DOM.
input.value = field || EMPTY_FIELD;
if (!field) {
input.select();
}
setField(field);
value = fieldsToSeconds();
onChange();
if (/^\d$/.test((e as unknown as InputEvent).data ?? '')) {
digitsTyped++;
if (digitsTyped === 2) {
nextInput?.focus();
} }
} }
} }
function handlePointerDown(e: PointerEvent) {
// Like a native input, the whole box gives focus, not only the text.
if (e.target === e.currentTarget) {
e.preventDefault();
(hoursInput ?? minutesInput)?.focus();
}
}
function handleFocusOut(e: FocusEvent & { currentTarget: HTMLDivElement }) {
// Fill in the fields left empty once the user is done with the picker.
if (!e.currentTarget.contains(e.relatedTarget as Node | null)) {
showValue(value);
}
} }
</script> </script>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div <div
bind:this={container} data-slot="time-picker"
class="h-9 flex flex-row items-center w-full min-w-fit border rounded-md px-3 focus-within:outline-none focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 {disabled class={cn(
? 'opacity-50 cursor-not-allowed' 'dark:bg-input/30 border-input focus-within:border-ring focus-within:ring-ring/50 flex h-8 w-full min-w-28 cursor-text items-center justify-end rounded-lg border bg-transparent px-2.5 py-1 text-base transition-colors focus-within:ring-3 md:text-sm',
: ''}" disabled && 'bg-input/50 dark:bg-input/80 pointer-events-none cursor-not-allowed opacity-50'
)}
onpointerdown={handlePointerDown}
onfocusin={() => {
digitsTyped = 0;
}}
onfocusout={handleFocusOut}
> >
{#if showHours} {#if showHours}
<TimeComponentInput <TimeComponentInput
id="hours" {id}
bind:value={hours} bind:ref={hoursInput}
value={hours}
{disabled} {disabled}
class="w-[30px]" oninput={(e) =>
oninput={() => { handleInput(e, normalizeUnbounded, (field) => (hours = field), minutesInput)}
if (typeof hours === 'string') {
hours = parseInt(hours);
}
if (hours < 0) {
hours = 0;
}
onChange();
}}
onkeypress={onKeyPress}
onfocusin={() => {
countKeyPress = 0;
}}
/> />
<span class="text-sm">:</span> <span>:</span>
{/if} {/if}
<TimeComponentInput <TimeComponentInput
id="minutes" id={showHours ? undefined : id}
bind:value={minutes} bind:ref={minutesInput}
value={minutes}
{disabled} {disabled}
oninput={() => { oninput={(e) =>
if (typeof minutes === 'string') { handleInput(
minutes = parseInt(minutes); e,
} showHours ? normalizeSexagesimal : normalizeUnbounded,
if (showHours && minutes > 59) { (field) => (minutes = field),
minutes = 59; secondsInput
} else if (minutes < 0) { )}
minutes = 0;
}
minutes = minutes.toString().padStart(showHours ? 2 : 1, '0');
onChange();
}}
onkeypress={onKeyPress}
onfocusin={() => {
countKeyPress = 0;
}}
/> />
<span class="text-sm">:</span> <span>:</span>
<TimeComponentInput <TimeComponentInput
id="seconds" bind:ref={secondsInput}
bind:value={seconds} value={seconds}
{disabled} {disabled}
oninput={() => { oninput={(e) => handleInput(e, normalizeSexagesimal, (field) => (seconds = field), null)}
if (typeof seconds === 'string') {
seconds = parseInt(seconds);
}
if (seconds > 59) {
seconds = 59;
} else if (seconds < 0) {
seconds = 0;
}
seconds = seconds.toString().padStart(2, '0');
onChange();
}}
onkeypress={onKeyPress}
onfocusin={() => {
countKeyPress = 0;
}}
/> />
</div> </div>
<style>
div :global(input::-webkit-outer-spin-button) {
-webkit-appearance: none;
margin: 0;
}
div :global(input::-webkit-inner-spin-button) {
-webkit-appearance: none;
margin: 0;
}
div :global(input[type='number']) {
appearance: textfield;
-moz-appearance: textfield;
}
</style>
+55 -24
View File
@@ -32,28 +32,6 @@ export const basemaps: { [key: string]: string | StyleSpecification } = {
libertySatellite: 'https://styles.gpx.studio/liberty-satellite.json', libertySatellite: 'https://styles.gpx.studio/liberty-satellite.json',
osm: 'https://styles.gpx.studio/osm.json', osm: 'https://styles.gpx.studio/osm.json',
osmTopo: 'https://styles.gpx.studio/osm-topo.json', osmTopo: 'https://styles.gpx.studio/osm-topo.json',
esriSatellite: {
version: 8,
sources: {
esriSatellite: {
type: 'raster',
tiles: [
'https://services.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/WMTS/tile/1.0.0/World_Imagery/default/default028mm/{z}/{y}/{x}.jpg',
],
tileSize: 256,
maxzoom: 19,
attribution:
'© <a href="https://www.esri.com/" target="_blank">Esri</a>, Vantor, Earthstar Geographics, and the GIS User Community',
},
},
layers: [
{
id: 'esriSatellite',
type: 'raster',
source: 'esriSatellite',
},
],
},
openStreetMap: { openStreetMap: {
version: 8, version: 8,
sources: { sources: {
@@ -302,6 +280,28 @@ export const basemaps: { [key: string]: string | StyleSpecification } = {
}, },
], ],
}, },
denmarkTopo: {
version: 8,
sources: {
denmarkTopo: {
type: 'raster',
tiles: [
'https://wms.datafordeler.dk/DKtopokort/dtk_25/1.0.0/WMS?apikey=pDSRuC5YLFT3jHf4XbaWDGSa9Td4TfYiGiB7YfhCKikJhZE6xibJAlaNp1KpDAzHdDss9DSKdq3nNoT2UFU3cmecaLrcRNTOc&SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&LAYERS=dtk25&STYLES=&FORMAT=image/png&CRS=EPSG:3857&BBOX={bbox-epsg-3857}&WIDTH=256&HEIGHT=256',
],
tileSize: 256,
maxzoom: 18,
attribution:
'&copy; <a href="https://klimadatastyrelsen.dk/" target="_blank">Klimadatastyrelsen</a>',
},
},
layers: [
{
id: 'denmarkTopo',
type: 'raster',
source: 'denmarkTopo',
},
],
},
finlandTopo: { finlandTopo: {
version: 8, version: 8,
sources: { sources: {
@@ -365,6 +365,27 @@ export const basemaps: { [key: string]: string | StyleSpecification } = {
}, },
], ],
}, },
luxTopo: {
version: 8,
sources: {
luxTopo: {
type: 'raster',
tiles: [
'https://wmts3.geoportail.lu/mapproxy_4_v3/wmts/topogg/GLOBAL_WEBMERCATOR_4_V3/{z}/{x}/{y}.png',
],
tileSize: 256,
maxzoom: 16,
attribution: '<a href="https://geoportail.lu/" target="_blank">geoportail.lu</a>',
},
},
layers: [
{
id: 'luxTopo',
type: 'raster',
source: 'luxTopo',
},
],
},
}; };
export const overlays: { [key: string]: string | StyleSpecification } = { export const overlays: { [key: string]: string | StyleSpecification } = {
@@ -810,7 +831,6 @@ export const basemapTree: LayerTreeType = {
libertySatellite: true, libertySatellite: true,
osm: true, osm: true,
osmTopo: true, osmTopo: true,
esriSatellite: true,
openStreetMap: true, openStreetMap: true,
openTopoMap: true, openTopoMap: true,
openHikingMap: true, openHikingMap: true,
@@ -824,6 +844,9 @@ export const basemapTree: LayerTreeType = {
bulgaria: { bulgaria: {
bgMountains: true, bgMountains: true,
}, },
denmark: {
denmarkTopo: true,
},
finland: { finland: {
finlandTopo: true, finlandTopo: true,
}, },
@@ -833,6 +856,9 @@ export const basemapTree: LayerTreeType = {
ignFrScan25: true, ignFrScan25: true,
ignFrSatellite: true, ignFrSatellite: true,
}, },
luxembourg: {
luxTopo: true,
},
new_zealand: { new_zealand: {
linz: true, linz: true,
linzTopo: true, linzTopo: true,
@@ -1036,7 +1062,6 @@ export const defaultBasemapTree: LayerTreeType = {
libertySatellite: true, libertySatellite: true,
osm: true, osm: true,
osmTopo: true, osmTopo: true,
esriSatellite: false,
openStreetMap: true, openStreetMap: true,
openTopoMap: true, openTopoMap: true,
openHikingMap: true, openHikingMap: true,
@@ -1050,6 +1075,9 @@ export const defaultBasemapTree: LayerTreeType = {
bulgaria: { bulgaria: {
bgMountains: false, bgMountains: false,
}, },
denmark: {
denmarkTopo: false,
},
finland: { finland: {
finlandTopo: false, finlandTopo: false,
}, },
@@ -1059,6 +1087,9 @@ export const defaultBasemapTree: LayerTreeType = {
ignFrScan25: false, ignFrScan25: false,
ignFrSatellite: false, ignFrSatellite: false,
}, },
luxembourg: {
luxTopo: false,
},
new_zealand: { new_zealand: {
linz: false, linz: false,
linzTopo: false, linzTopo: false,
@@ -0,0 +1 @@
{"zoom":10,"tiles":[316951,316952,316953,316954,316955,316956,316957,316958,317975,317976,317977,317978,317979,317980,317981,317982,318999,319000,319001,319002,319003,319004,319005,319006,319007,320023,320024,320025,320026,320027,320028,320029,320030,320031,321046,321047,321048,321049,321050,321051,321052,321053,321054,321055,322070,322071,322072,322073,322074,322075,322076,322077,322078,322079,323094,323095,323096,323097,323098,323099,323100,323101,323102,323103,323104,323105,324118,324119,324120,324121,324122,324123,324124,324125,324126,324127,325142,325143,325144,325145,325146,325147,325148,325149,325150,325151,325153,326166,326167,326168,326169,326170,326171,326172,326173,326174,326175,326176,326177,326178,326179,327190,327191,327192,327193,327194,327195,327196,327197,327198,327199,327200,327201,327202,327203,328214,328215,328216,328217,328218,328219,328220,328221,328222,328223,328224,328225,328226,328227,328228,329238,329239,329240,329241,329242,329243,329244,329245,329246,329247,329248,329249,329250,329251,329252,330262,330263,330264,330265,330266,330267,330268,330269,330270,330271,330272,330273,330274,330275,330281,330282,330283,331286,331287,331288,331289,331290,331291,331292,331293,331294,331295,331296,331297,331298,331299,331305,331306,331307,332310,332311,332312,332313,332314,332315,332316,332317,332318,332319,332320,332321,332322,332323,332328,332329,332330,332331,332332,332333,332334,332335,332336,332337,332338,332339,332340,332341,332342,332343,332344,332345,332346,332347,332348,332349,332350,332351,332352,332353,332354,332355,332356,333342,333343,333344,333345,333346,333352,333353,333354,333355,333356,333357,333358,333359,333360,333361,333362,333363,333364,333365,333366,333367,333368,333369,333370,333371,333372,333373,333374,333375,333376,333377,333378,333379,333380,334369,334370,334376,334377,334378,334379,334380,334381,334382,334383,334384,334385,334386,334387,334388,334389,334390,334391,334392,334393,334394,334395,334396,334397,334398,334399,334400,334401,334402,334403,334404,335400,335401,335402,335403,335404,335405,335406,335407,335408,335409,335410,335411,335412,335413,335414,335415,335416,335417,335418,335419,335420,335421,335422,335423,335424,335425,335426,335427,335428,336424,336425,336426,336427,336428,336429,336430,336431,336432,336433,336434,336435,336436,336437,336438,336439,336440,336441,336442,336443,336444,336445,336446,336447,336448,336449,336450,336451,336452,337448,337449,337450,337451,337452,337453,337454,337455,337456,337457,337458,337459,337460,337461,337462,337463,337464,337465,337466,337467,337468,337469,337470,337471,337472,337473,337474,337475,337476,338450,338472,338473,338474,338475,338476,338477,338478,338479,338480,338481,338482,338483,338484,338485,338486,338487,338488,338489,338490,338491,338492,338493,338494,338495,338496,338497,338498,338499,338500,339465,339466,339467,339468,339469,339470,339471,339472,339473,339474,339475,339476,339496,339497,339498,339499,339500,339501,339502,339503,339504,339505,339506,339507,339508,339509,339510,339511,339512,339513,339514,339515,339516,339517,339518,339519,339520,339521,339522,339523,339524,340489,340490,340491,340492,340493,340494,340495,340496,340497,340498,340499,340500,340520,340521,340522,340523,340524,340525,340526,340527,340528,340529,340530,340531,340532,340533,340534,340535,340536,340537,340538,340539,340540,340541,340542,340543,340544,340545,340546,340547,340548,341513,341514,341515,341516,341517,341518,341519,341520,341521,341522,341523,341524,341544,341545,341546,341547,341548,341549,341550,341551,341552,341553,341554,341555,341556,341557,341558,341559,341560,341561,341562,341563,341564,341565,341566,341567,341568,341569,341570,341571,341572,342537,342538,342539,342540,342541,342542,342543,342544,342545,342546,342547,342548,342568,342569,342570,342571,342572,342573,342574,342575,342576,342577,342578,342579,342580,342581,342582,342583,342584,342585,342586,342587,342588,342589,342590,342591,342592,342593,342594,342595,342596,343561,343562,343563,343564,343565,343566,343567,343568,343569,343570,343571,343572,343592,343593,343594,343595,343596,343597,343598,343599,343600,343601,343602,343603,343604,343605,343606,343607,343608,343609,343610,343611,343612,343613,343614,343615,343616,343617,343618,343619,343620,344585,344586,344587,344588,344589,344590,344591,344592,344593,344594,344595,344596,344616,344617,344618,344619,344620,344621,344622,344623,344624,344625,344626,344627,344628,344629,344630,344631,344632,344633,344634,344635,344636,344637,344638,344639,344640,344641,344642,344643,344644,345609,345610,345611,345612,345613,345614,345615,345616,345617,345618,345619,345620,345640,345641,345642,345643,345644,345645,345646,345647,345648,345649,345650,345651,345652,345653,345654,345655,345656,345657,345658,345659,345660,345661,345662,345663,345664,345665,345666,345667,345668,346633,346634,346635,346636,346637,346638,346639,346640,346641,346642,346643,346644,346664,346665,346666,346667,346668,346669,346670,346671,34Line truncated
+58
View File
@@ -0,0 +1,58 @@
import { BundleType, getBundleType, getVersion } from '@tauri-apps/api/app';
import { relaunch } from '@tauri-apps/plugin-process';
import { check, type Update } from '@tauri-apps/plugin-updater';
import { toast } from 'svelte-sonner';
import { engine } from '$lib/engine';
import { i18n } from '$lib/i18n/i18n.svelte';
/** Where the `.deb` and `.rpm` packages can be downloaded, as they do not update themselves. */
const releases = 'https://github.com/gpxstudio/gpx.studio/releases/latest';
/**
* Offers the update, if there is one. The app does not restart by itself, as it would interrupt
* the user. The beta versions are not updated, as they would be replaced by the stable release.
*/
export async function checkForUpdates() {
if (import.meta.env.DEV || (await getVersion()).includes('-')) {
return;
}
const update = await check().catch((error) => {
// most likely offline: it will be checked again the next time the app starts
console.warn('Could not check for updates', error);
return null;
});
if (update === null) {
return;
}
const message = i18n._('desktop.update_available').replace('{version}', update.version);
const bundle = await getBundleType();
if (bundle === BundleType.Deb || bundle === BundleType.Rpm) {
toast.info(message, {
duration: Number.POSITIVE_INFINITY,
action: {
label: i18n._('desktop.update_download'),
onClick: () => engine.openUrl(releases),
},
});
} else {
toast.info(message, {
duration: Number.POSITIVE_INFINITY,
action: {
label: i18n._('desktop.update_restart'),
onClick: () => install(update),
},
});
}
}
async function install(update: Update) {
const installing = toast.loading(i18n._('desktop.update_installing'));
try {
await update.downloadAndInstall();
await relaunch();
} catch (error) {
console.error('Could not install the update', error);
toast.error(i18n._('desktop.update_failed'), { id: installing });
}
}
-6
View File
@@ -67,12 +67,6 @@ Since a route has a single segment, a track with multiple segments is converted
When the selected files contain only routes, or only tracks, you can also convert all of them at once. When the selected files contain only routes, or only tracks, you can also convert all of them at once.
<DocsNote>
Except for whole files, this action is only available when the tree layout of the files list is enabled.
</DocsNote>
### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Select all ### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Select all
Add all file items in the current hierarchy level to the selection. Add all file items in the current hierarchy level to the selection.
-6
View File
@@ -67,12 +67,6 @@ Since a route has a single segment, a track with multiple segments is converted
When the selected files contain only routes, or only tracks, you can also convert all of them at once. When the selected files contain only routes, or only tracks, you can also convert all of them at once.
<DocsNote>
Except for whole files, this action is only available when the tree layout of the files list is enabled.
</DocsNote>
### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Selecciona tot ### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Selecciona tot
Afegeix a la selecció tots els elements de l'arxiu en el nivell de jerarquia actual. Afegeix a la selecció tots els elements de l'arxiu en el nivell de jerarquia actual.
-6
View File
@@ -67,12 +67,6 @@ Since a route has a single segment, a track with multiple segments is converted
When the selected files contain only routes, or only tracks, you can also convert all of them at once. When the selected files contain only routes, or only tracks, you can also convert all of them at once.
<DocsNote>
Except for whole files, this action is only available when the tree layout of the files list is enabled.
</DocsNote>
### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Vybrat vše ### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Vybrat vše
Přidejte k výběru všechny prvky souborů v dané úrovni hierarchie. Přidejte k výběru všechny prvky souborů v dané úrovni hierarchie.
-6
View File
@@ -67,12 +67,6 @@ Since a route has a single segment, a track with multiple segments is converted
When the selected files contain only routes, or only tracks, you can also convert all of them at once. When the selected files contain only routes, or only tracks, you can also convert all of them at once.
<DocsNote>
Except for whole files, this action is only available when the tree layout of the files list is enabled.
</DocsNote>
### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Select all ### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Select all
Add all file items in the current hierarchy level to the selection. Add all file items in the current hierarchy level to the selection.
-6
View File
@@ -67,12 +67,6 @@ Since a route has a single segment, a track with multiple segments is converted
When the selected files contain only routes, or only tracks, you can also convert all of them at once. When the selected files contain only routes, or only tracks, you can also convert all of them at once.
<DocsNote>
Except for whole files, this action is only available when the tree layout of the files list is enabled.
</DocsNote>
### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Alle auswählen ### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Alle auswählen
Alle Dateielemente in der aktuellen Hierarchieebene zur Auswahl hinzufügen. Alle Dateielemente in der aktuellen Hierarchieebene zur Auswahl hinzufügen.
-6
View File
@@ -67,12 +67,6 @@ Since a route has a single segment, a track with multiple segments is converted
When the selected files contain only routes, or only tracks, you can also convert all of them at once. When the selected files contain only routes, or only tracks, you can also convert all of them at once.
<DocsNote>
Except for whole files, this action is only available when the tree layout of the files list is enabled.
</DocsNote>
### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Select all ### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Select all
Add all file items in the current hierarchy level to the selection. Add all file items in the current hierarchy level to the selection.
-6
View File
@@ -67,12 +67,6 @@ Since a route has a single segment, a track with multiple segments is converted
When the selected files contain only routes, or only tracks, you can also convert all of them at once. When the selected files contain only routes, or only tracks, you can also convert all of them at once.
<DocsNote>
Except for whole files, this action is only available when the tree layout of the files list is enabled.
</DocsNote>
### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Select all ### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Select all
Add all file items in the current hierarchy level to the selection. Add all file items in the current hierarchy level to the selection.
+4 -10
View File
@@ -40,7 +40,7 @@ Además, la selección debe ser un solo archivo.
### <Plus size="16" class="inline-block" style="margin-bottom: 2px" /> New route ### <Plus size="16" class="inline-block" style="margin-bottom: 2px" /> New route
Create a new route in the selected file. Crear una nueva ruta en el archivo seleccionado.
<DocsNote> <DocsNote>
@@ -62,16 +62,10 @@ Además, la selección debe ser una sola pista.
### <ArrowRightLeft size="16" class="inline-block" style="margin-bottom: 2px" /> Convert to route/track ### <ArrowRightLeft size="16" class="inline-block" style="margin-bottom: 2px" /> Convert to route/track
Convert the selected routes to tracks, or the selected tracks or segments to routes. Convertir las rutas seleccionadas a recorridos o los recorridos o segmentos seleccionados a rutas.
Since a route has a single segment, a track with multiple segments is converted into one route per segment. Dado que una ruta tiene un solo segmento, un recorrido con múltiples segmentos se convierte en una ruta por segmento.
When the selected files contain only routes, or only tracks, you can also convert all of them at once. Cuando los archivos seleccionados solo contienen rutas o pistas, también puede convertir todos a la vez.
<DocsNote>
Except for whole files, this action is only available when the tree layout of the files list is enabled.
</DocsNote>
### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Seleccionar todo ### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Seleccionar todo
+1 -1
View File
@@ -69,4 +69,4 @@ Global eta tokiko mapa oinarri bilduma handia dago **gpx.studio**-n eskuragarri,
Ezarpen horietan, gainjartzeen opakutasuna ere kudeatu dezakezu. Ezarpen horietan, gainjartzeen opakutasuna ere kudeatu dezakezu.
Erabiltzaile aurreratuentzat, oinarrizko mapa pertsonalizatuak eta gainjartzeak gehi daitezke <a href="https://en.wikipedia.org/wiki/Web_Map_Tile_Service" target="_blank">WMTS</a>, <a href="https://en.wikipedia.org/wiki/Web_Map_Service" target="_blank">WMS</a> edo <a href="https://en.wikipedia.org/wiki/Web_Map_Service" target="_blank">WMS</a>https:///malibrea-spec.org/malibrea-spec. target="_blank">MapLibre estiloko JSON</a> URLak. Erabiltzaile aurreratuentzat, oinarrizko mapa pertsonalizatuak eta gainjartzeak gehi daitezke <a href="https://en.wikipedia.org/wiki/Web_Map_Tile_Service" target="_blank">WMTS</a>, <a href="https://en.wikipedia.org/wiki/Web_Map_Service" target="_blank">WMS</a> edo <a href="https://maplibre.org/maplibre-style-spec/" target="_blank">MapLibre estiloko JSON</a> URLak.
+7 -13
View File
@@ -10,7 +10,7 @@ title: Edizio ekintzak
# { title } # { title }
Fitxategi-ekintzak ez bezala, edizio-ekintzek hautatutako fitxategien edukia alda dezakete. Fitxategi-ekintzak ez bezala, edizio-ekintzek hautatutako fitxategien edukia alda dezakete.
Moreover, when the tree layout of the files list is enabled (see [Files and statistics](../files-and-stats)), they can also be applied to [tracks, segments, routes, and points of interest](../gpx). Gainera, fitxategien zerrendaren zuhaitz-diseinua gaituta dagoenean (ikus [Fitxategiak eta estatistikak](../fitxategiak-and-stats)), [arrasto, segmentu, ibilbide eta interesguneetan](../gpx) ere aplika daitezke.
Hori dela eta, ekintza hauek alda dezaketen elementuei _fitxategi-elementuak_ izendatzen ditugu. Hori dela eta, ekintza hauek alda dezaketen elementuei _fitxategi-elementuak_ izendatzen ditugu.
Ohar zaitez, desegin eta berregin ekintzak ez, beste guztiak fitxategi-elementu hauen alboko menuaren bidez (eskuin-klik) ere erabili daitezke. Ohar zaitez, desegin eta berregin ekintzak ez, beste guztiak fitxategi-elementu hauen alboko menuaren bidez (eskuin-klik) ere erabili daitezke.
@@ -38,9 +38,9 @@ Gainera, fitxategi bakarra egon behar du hautatuta.
</DocsNote> </DocsNote>
### <Plus size="16" class="inline-block" style="margin-bottom: 2px" /> New route ### <Plus size="16" class="inline-block" style="margin-bottom: 2px" /> Ibilbide berria
Create a new route in the selected file. Sortu ibilbide berria hautatutako fitxategian.
<DocsNote> <DocsNote>
@@ -60,18 +60,12 @@ Gainera, arrasto bakarra egon behar du hautatuta.
</DocsNote> </DocsNote>
### <ArrowRightLeft size="16" class="inline-block" style="margin-bottom: 2px" /> Convert to route/track ### <ArrowRightLeft size="16" class="inline-block" style="margin-bottom: 2px" /> Bihurtu ibilbide/arrasto
Convert the selected routes to tracks, or the selected tracks or segments to routes. Bihurtu hautatutako ibilbideak arrasto, edo hautatutako arrasto edo segmentuak ibilbide bihurtu.
Since a route has a single segment, a track with multiple segments is converted into one route per segment. Ibilbide batek segmentu bakarra duenez, segmentu anitz dituen arrasto bat segmentu bakoitzeko ibilbide batean bihurtzen da.
When the selected files contain only routes, or only tracks, you can also convert all of them at once. Hautatutako fitxategiek ibilbideak edo arrasto soilik dituztenean, guztiak aldi berean bihur ditzakezu.
<DocsNote>
Except for whole files, this action is only available when the tree layout of the files list is enabled.
</DocsNote>
### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Hautatu denak ### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Hautatu denak
-6
View File
@@ -67,12 +67,6 @@ Since a route has a single segment, a track with multiple segments is converted
When the selected files contain only routes, or only tracks, you can also convert all of them at once. When the selected files contain only routes, or only tracks, you can also convert all of them at once.
<DocsNote>
Except for whole files, this action is only available when the tree layout of the files list is enabled.
</DocsNote>
### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Select all ### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Select all
Add all file items in the current hierarchy level to the selection. Add all file items in the current hierarchy level to the selection.
+1 -1
View File
@@ -51,7 +51,7 @@ En faisant un clic droit sur un onglet de fichier, vous pouvez accéder aux mêm
Comme mentionné dans la [section des options d'affichage](./menu/view), vous pouvez basculer vers une présentation en arborescence pour la liste des fichiers. Comme mentionné dans la [section des options d'affichage](./menu/view), vous pouvez basculer vers une présentation en arborescence pour la liste des fichiers.
Cette disposition est idéale pour gérer un grand nombre de fichiers ouverts, car elle les organise en une liste verticale à droite de la carte. Cette disposition est idéale pour gérer un grand nombre de fichiers ouverts, car elle les organise en une liste verticale à droite de la carte.
In addition, the file tree view enables you to inspect the [tracks, segments, routes, and points of interest](./gpx) contained inside the files through collapsible sections. De plus, la vue en arborescence des fichiers vous permet d'inspecter les [traces, segments, routes, et points d'intérêt](./gpx) contenus dans les fichiers grâce à des sections pliables.
Vous pouvez également appliquer les [actions d'édition](./menu/edit) et les [outils](./toolbar) aux éléments intérieurs aux fichiers. Vous pouvez également appliquer les [actions d'édition](./menu/edit) et les [outils](./toolbar) aux éléments intérieurs aux fichiers.
De plus, vous pouvez glisser-déposer les éléments intérieurs pour les réorganiser, ou les déplacer dans la hiérarchie ou même dans un autre fichier. De plus, vous pouvez glisser-déposer les éléments intérieurs pour les réorganiser, ou les déplacer dans la hiérarchie ou même dans un autre fichier.
+7 -7
View File
@@ -11,7 +11,7 @@ title: Format de fichier GPX
Le format de fichier <a href="https://www.topografix.com/gpx.asp" target="_blank">GPX</a> est un standard ouvert pour l'échange de données GPS entre applications et appareils GPS. Le format de fichier <a href="https://www.topografix.com/gpx.asp" target="_blank">GPX</a> est un standard ouvert pour l'échange de données GPS entre applications et appareils GPS.
Il consiste principalement en une série de points GPS encodant une ou plusieurs traces GPS, et, éventuellement, certains points d'intérêt. Il consiste principalement en une série de points GPS encodant une ou plusieurs traces GPS, et, éventuellement, certains points d'intérêt.
These traces can be stored either as tracks or as routes. Ces traces peuvent être stockées sous forme de pistes ou de routes.
Les fichiers GPX peuvent aussi contenir des métadonnées, dont les champs **nom** et **description** sont les plus utiles pour les utilisateurs. Les fichiers GPX peuvent aussi contenir des métadonnées, dont les champs **nom** et **description** sont les plus utiles pour les utilisateurs.
@@ -31,15 +31,15 @@ Cependant, la hiérarchie décrite ci-dessus permet des cas d'utilisation plus a
### <Route size="16" class="inline-block" style="margin-bottom: 2px" /> Routes ### <Route size="16" class="inline-block" style="margin-bottom: 2px" /> Routes
A **route** is a single continuous path made of a sequence of **route points**. Une **route** est un chemin continu constitué d'une séquence de **points de passage**.
These are mandatory checkpoints, which correspond to the anchor points of the [routing tool](./toolbar/routing). Ces points de passage correspondent aux points d'ancrage de [l'outil de routage](./toolbar/routing).
The points in between are only a suggested path connecting the route points. Les points intermédiaires entre les points de passage ne sont qu'un chemin suggéré pour les relier.
Like a track, a route can have a **name**, a **description**, and **appearance properties**. Comme une piste, une route peut avoir un **nom**, une **description**, et des **propriétés d'apparence**.
<DocsNote> <DocsNote>
Nowadays, most apps and GPS devices work perfectly well with tracks, even for navigation. De nos jours, la plupart des applications et des appareils GPS fonctionnent parfaitement avec les pistes, même pour la navigation.
However, some of them only work with routes: in that case, you can [convert](./menu/edit) your tracks to routes, or [create](./menu/file) a route file from the start. Cependant, certains d'entre eux ne fonctionnent qu'avec des routes : dans ce cas, vous pouvez [convertir](./menu/edit) vos pistes en routes, ou [créer](./menu/file) un fichier route dès le début.
</DocsNote> </DocsNote>
+7 -13
View File
@@ -10,7 +10,7 @@ title: Actions d'édition
# { title } # { title }
Contrairement aux actions sur les fichiers, les actions d'édition peuvent potentiellement modifier le contenu des fichiers sélectionnés. Contrairement aux actions sur les fichiers, les actions d'édition peuvent potentiellement modifier le contenu des fichiers sélectionnés.
Moreover, when the tree layout of the files list is enabled (see [Files and statistics](../files-and-stats)), they can also be applied to [tracks, segments, routes, and points of interest](../gpx). De plus, lorsque la présentation en arborescence de la liste de fichiers est activée (voir [Fichiers et statistiques](../files-and-stats)), elles peuvent également être appliquées aux [pistes, segments, routes, et points d'intérêt](../gpx).
Par conséquent, nous appellerons les éléments qui peuvent être modifiés par ces actions des _éléments de fichier_. Par conséquent, nous appellerons les éléments qui peuvent être modifiés par ces actions des _éléments de fichier_.
Notez que, à part les actions annuler et rétablir, les actions d'édition sont également accessibles via le menu contextuel (clic droit) des éléments de fichier. Notez que, à part les actions annuler et rétablir, les actions d'édition sont également accessibles via le menu contextuel (clic droit) des éléments de fichier.
@@ -38,9 +38,9 @@ De plus, la sélection doit contenir un seul fichier.
</DocsNote> </DocsNote>
### <Plus size="16" class="inline-block" style="margin-bottom: 2px" /> New route ### <Plus size="16" class="inline-block" style="margin-bottom: 2px" /> Nouvelle route
Create a new route in the selected file. Créer une nouvelle route dans le fichier sélectionné.
<DocsNote> <DocsNote>
@@ -60,18 +60,12 @@ De plus, la sélection doit contenir une seule piste.
</DocsNote> </DocsNote>
### <ArrowRightLeft size="16" class="inline-block" style="margin-bottom: 2px" /> Convert to route/track ### <ArrowRightLeft size="16" class="inline-block" style="margin-bottom: 2px" /> Convertir en fichier route/piste
Convert the selected routes to tracks, or the selected tracks or segments to routes. Convertir les routes sélectionnées en pistes, ou les pistes ou segments sélectionnés en routes.
Since a route has a single segment, a track with multiple segments is converted into one route per segment. Comme une route a un seul segment, une piste avec plusieurs segments est convertie en une route par segment.
When the selected files contain only routes, or only tracks, you can also convert all of them at once. Lorsque les fichiers sélectionnés ne contiennent que des routes, ou seulement des pistes, vous pouvez également les convertir tous en même temps.
<DocsNote>
Except for whole files, this action is only available when the tree layout of the files list is enabled.
</DocsNote>
### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Sélectionner tout ### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Sélectionner tout
+2 -2
View File
@@ -15,9 +15,9 @@ Le menu des actions sur les fichiers contient un ensemble d'opérations de fichi
Créer un nouveau fichier vide. Créer un nouveau fichier vide.
### <Plus size="16" class="inline-block" style="margin-bottom: 2px" /> New route file ### <Plus size="16" class="inline-block" style="margin-bottom: 2px" />Nouveau fichier route
Create a new file containing an empty [route](../gpx). Créer un nouveau fichier contenant une [route](../gpx) vide.
### <FolderOpen size="16" class="inline-block" style="margin-bottom: 2px" /> Ouvrir... ### <FolderOpen size="16" class="inline-block" style="margin-bottom: 2px" /> Ouvrir...
+5 -5
View File
@@ -19,7 +19,7 @@ Masquer le profil altimétrique pour faire de la place pour la carte, ou l'affic
Activer/désactiver la présentation en arborescence pour la [liste de fichiers](../files-and-stats). Activer/désactiver la présentation en arborescence pour la [liste de fichiers](../files-and-stats).
Cette disposition est idéale pour gérer un grand nombre de fichiers ouverts, car elle les organise en une liste verticale à droite de la carte. Cette disposition est idéale pour gérer un grand nombre de fichiers ouverts, car elle les organise en une liste verticale à droite de la carte.
In addition, the file tree view enables you to inspect the [tracks, segments, routes, and points of interest](../gpx) contained inside the files through collapsible sections. De plus, la vue en arborescence des fichiers vous permet d'inspecter les [traces, segments, routes, et points d'intérêt](../gpx) contenus dans les fichiers grâce à des sections pliables.
### <Map size="16" class="inline-block" style="margin-bottom: 2px" /> Basculer au fond de carte précédent ### <Map size="16" class="inline-block" style="margin-bottom: 2px" /> Basculer au fond de carte précédent
@@ -38,13 +38,13 @@ Ceux-ci sont affichés pour la sélection courante, comme le [profil altimétriq
Activer/désactiver la visibilité des flèches de direction sur la carte. Activer/désactiver la visibilité des flèches de direction sur la carte.
### <EyeOff size="16" class="inline-block" style="margin-bottom: 2px" /> Hide/unhide ### <EyeOff size="16" class="inline-block" style="margin-bottom: 2px" /> Cacher/afficher
Toggle the visibility of the selected file items on the map. Activer/désactiver la visibilité des éléments de fichier sélectionnés sur la carte.
### <Maximize size="16" class="inline-block" style="margin-bottom: 2px" /> Center ### <Maximize size="16" class="inline-block" style="margin-bottom: 2px" /> Centrer
Center the map on the selected file items. Centrer la carte sur les éléments de fichier sélectionnés.
### <Box size="16" class="inline-block" style="margin-bottom: 2px" /> Activer/désactiver la 3D ### <Box size="16" class="inline-block" style="margin-bottom: 2px" /> Activer/désactiver la 3D
+1 -1
View File
@@ -16,7 +16,7 @@ Cet outil vous permet d'extraire [des pistes (ou des segments)](../gpx) de fichi
<Extract class="text-foreground p-3 border rounded-md shadow-lg" /> <Extract class="text-foreground p-3 border rounded-md shadow-lg" />
</div> </div>
Applying the tool to a file containing multiple [tracks or routes](../gpx) will create a new file for each of the tracks and routes it contains. Appliquer l'outil à un fichier contenant plusieurs [pistes ou routes](../gpx) créera un nouveau fichier pour chacune des pistes et routes qu'il contient.
De même, appliquer l'outil à une piste contenant plusieurs segments créera (dans le même fichier) une nouvelle piste pour chacun des segments qu'elle contient. De même, appliquer l'outil à une piste contenant plusieurs segments créera (dans le même fichier) une nouvelle piste pour chacun des segments qu'elle contient.
<DocsNote> <DocsNote>
+3 -3
View File
@@ -10,11 +10,11 @@ title: Fusionner
# <Group size="24" class="inline-block" style="margin-bottom: 5px" /> { title } # <Group size="24" class="inline-block" style="margin-bottom: 5px" /> { title }
To use this tool, you need to [select](../files-and-stats) multiple files, [tracks, segments or routes](../gpx). Pour utiliser cet outil, vous devez [sélectionner](../files-and-stats) plusieurs fichiers, [pistes, segments ou routes](../gpx).
- Si votre objectif est de créer une seule trace continue à partir de votre sélection, utilisez l'option **Connecter les traces** et validez. - Si votre objectif est de créer une seule trace continue à partir de votre sélection, utilisez l'option **Connecter les traces** et validez.
- The second option can be used to create or manage files with multiple [tracks, segments or routes](../gpx). - La deuxième option peut être utilisée pour créer ou gérer des fichiers avec plusieurs [pistes, segments ou routes](../gpx).
Merging files (or tracks) will result in a single file (or track) containing all tracks and routes (or segments) from the selection. Fusionner des fichiers (ou des pistes) résultera en un seul fichier (ou piste) contenant toutes les pistes et routes (ou tous les segments) de la sélection.
<DocsNote> <DocsNote>
+1 -1
View File
@@ -27,6 +27,6 @@ Pour diviser la trace sélectionnée en deux parties, cliquez sur l'un des marqu
Pour diviser à un point précis de votre choix, survolez la trace sur la carte. Pour diviser à un point précis de votre choix, survolez la trace sur la carte.
Des ciseaux apparaîtront à la position du curseur, montrant que vous pouvez diviser la trace à ce point. Des ciseaux apparaîtront à la position du curseur, montrant que vous pouvez diviser la trace à ce point.
You can choose to split the trace into two GPX files, or to keep the split parts in the same file as [tracks, segments or routes](../gpx). Vous pouvez choisir de diviser la trace en deux fichiers GPX, ou de créer [une piste, un segment ou une route](../gpx) pour chaque partie dans le même fichier.
<DocsImage src="tools/split" alt="Survoler la trace sélectionnée transforme votre curseur en ciseaux." /> <DocsImage src="tools/split" alt="Survoler la trace sélectionnée transforme votre curseur en ciseaux." />
-6
View File
@@ -67,12 +67,6 @@ Since a route has a single segment, a track with multiple segments is converted
When the selected files contain only routes, or only tracks, you can also convert all of them at once. When the selected files contain only routes, or only tracks, you can also convert all of them at once.
<DocsNote>
Except for whole files, this action is only available when the tree layout of the files list is enabled.
</DocsNote>
### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Select all ### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Select all
Add all file items in the current hierarchy level to the selection. Add all file items in the current hierarchy level to the selection.
-6
View File
@@ -67,12 +67,6 @@ Since a route has a single segment, a track with multiple segments is converted
When the selected files contain only routes, or only tracks, you can also convert all of them at once. When the selected files contain only routes, or only tracks, you can also convert all of them at once.
<DocsNote>
Except for whole files, this action is only available when the tree layout of the files list is enabled.
</DocsNote>
### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Az összes kijelölése ### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Az összes kijelölése
Az aktuális hierarchiaszinten lévő összes fájlelem hozzáadása a kijelöléshez. Az aktuális hierarchiaszinten lévő összes fájlelem hozzáadása a kijelöléshez.
-6
View File
@@ -67,12 +67,6 @@ Since a route has a single segment, a track with multiple segments is converted
When the selected files contain only routes, or only tracks, you can also convert all of them at once. When the selected files contain only routes, or only tracks, you can also convert all of them at once.
<DocsNote>
Except for whole files, this action is only available when the tree layout of the files list is enabled.
</DocsNote>
### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Select all ### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Select all
Add all file items in the current hierarchy level to the selection. Add all file items in the current hierarchy level to the selection.
-6
View File
@@ -67,12 +67,6 @@ Since a route has a single segment, a track with multiple segments is converted
When the selected files contain only routes, or only tracks, you can also convert all of them at once. When the selected files contain only routes, or only tracks, you can also convert all of them at once.
<DocsNote>
Except for whole files, this action is only available when the tree layout of the files list is enabled.
</DocsNote>
### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Seleziona tutto ### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Seleziona tutto
Aggiunge tutti i file nel corrente livello gerarchico alla selezione. Aggiunge tutti i file nel corrente livello gerarchico alla selezione.
-6
View File
@@ -67,12 +67,6 @@ Since a route has a single segment, a track with multiple segments is converted
When the selected files contain only routes, or only tracks, you can also convert all of them at once. When the selected files contain only routes, or only tracks, you can also convert all of them at once.
<DocsNote>
Except for whole files, this action is only available when the tree layout of the files list is enabled.
</DocsNote>
### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Select all ### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Select all
Add all file items in the current hierarchy level to the selection. Add all file items in the current hierarchy level to the selection.
-6
View File
@@ -67,12 +67,6 @@ Since a route has a single segment, a track with multiple segments is converted
When the selected files contain only routes, or only tracks, you can also convert all of them at once. When the selected files contain only routes, or only tracks, you can also convert all of them at once.
<DocsNote>
Except for whole files, this action is only available when the tree layout of the files list is enabled.
</DocsNote>
### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Select all ### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Select all
Add all file items in the current hierarchy level to the selection. Add all file items in the current hierarchy level to the selection.
-6
View File
@@ -67,12 +67,6 @@ Since a route has a single segment, a track with multiple segments is converted
When the selected files contain only routes, or only tracks, you can also convert all of them at once. When the selected files contain only routes, or only tracks, you can also convert all of them at once.
<DocsNote>
Except for whole files, this action is only available when the tree layout of the files list is enabled.
</DocsNote>
### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Select all ### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Select all
Add all file items in the current hierarchy level to the selection. Add all file items in the current hierarchy level to the selection.
+1 -1
View File
@@ -51,7 +51,7 @@ Door met de rechtermuisknop te klikken op een tabblad bestanden, kun je dezelfde
Zoals vermeld in de [opties bekijken](./menu/view), kun je schakelen tussen een horizontale en een verticale indeling voor de bestandslijst. Zoals vermeld in de [opties bekijken](./menu/view), kun je schakelen tussen een horizontale en een verticale indeling voor de bestandslijst.
Deze indeling is ideaal voor het beheren van een groot aantal open bestanden, omdat deze geordend worden in een verticale lijst op de rechterkant van de kaart. Deze indeling is ideaal voor het beheren van een groot aantal open bestanden, omdat deze geordend worden in een verticale lijst op de rechterkant van de kaart.
In addition, the file tree view enables you to inspect the [tracks, segments, routes, and points of interest](./gpx) contained inside the files through collapsible sections. Daarnaast kun je met de boomweergave de [sporen, routes, segmenten, en interessante punten](./gpx) in de bestanden bekijken door middel van inklapbare secties.
Je kunt ook [bewerk acties](./menu/edit) en [tools](./toolbar) toepassen op interne bestands items. Je kunt ook [bewerk acties](./menu/edit) en [tools](./toolbar) toepassen op interne bestands items.
Bovendien kun je de interne onderdelen slepen en neerzetten om ze te rangschikken, of ze in de hiërarchie of zelfs naar een ander bestand verplaatsen. Bovendien kun je de interne onderdelen slepen en neerzetten om ze te rangschikken, of ze in de hiërarchie of zelfs naar een ander bestand verplaatsen.
+7 -7
View File
@@ -11,7 +11,7 @@ title: GPX bestandsindeling
De <a href="https://www.topografix.com/gpx.asp" target="_blank">GPX bestandsindeling</a> is open voor het uitwisselen van GPS-gegevens tussen applicaties en GPS-apparaten. De <a href="https://www.topografix.com/gpx.asp" target="_blank">GPX bestandsindeling</a> is open voor het uitwisselen van GPS-gegevens tussen applicaties en GPS-apparaten.
Het bestaat in wezen uit een reeks GPS-punten die één of meerdere GPS-sporen coderen, en eventueel enkele aandachtspunten. Het bestaat in wezen uit een reeks GPS-punten die één of meerdere GPS-sporen coderen, en eventueel enkele aandachtspunten.
These traces can be stored either as tracks or as routes. Deze sporen kunnen worden opgeslagen als tracks of als routes.
GPX-bestanden kunnen ook metagegevens bevatten, waarvan de **naam** en **omschrijving** velden het nuttigst zijn voor gebruikers. GPX-bestanden kunnen ook metagegevens bevatten, waarvan de **naam** en **omschrijving** velden het nuttigst zijn voor gebruikers.
@@ -31,15 +31,15 @@ De hierboven beschreven hiërarchie maakt echter meer geavanceerd gebruik mogeli
### <Route size="16" class="inline-block" style="margin-bottom: 2px" />Routes ### <Route size="16" class="inline-block" style="margin-bottom: 2px" />Routes
A **route** is a single continuous path made of a sequence of **route points**. Een **route** is een enkel continu pad gemaakt van een reeks van **routepunten**.
These are mandatory checkpoints, which correspond to the anchor points of the [routing tool](./toolbar/routing). Dit zijn verplichte checkpoints, die overeenkomen met de ankerpunten van de [routing tool](./toolbar/routing).
The points in between are only a suggested path connecting the route points. De tussenpunten zijn alleen een voorgesteld pad dat de route punten met elkaar verbindt.
Like a track, a route can have a **name**, a **description**, and **appearance properties**. Net zoals een track kan een route een **naam**, een **beschrijving** en **uiterlijke eigenschappen** hebben.
<DocsNote> <DocsNote>
Nowadays, most apps and GPS devices work perfectly well with tracks, even for navigation. Tegenwoordig werken de meeste apps en GPS-apparaten perfect met tracks, zelfs voor navigatie.
However, some of them only work with routes: in that case, you can [convert](./menu/edit) your tracks to routes, or [create](./menu/file) a route file from the start. Sommige van hen werken echter alleen met routes: in dat geval, kunt u uw tracks [converteren](./menu/edit) naar routes of een route bestand [maken](./menu/file) vanaf het begin.
</DocsNote> </DocsNote>
+5 -11
View File
@@ -10,7 +10,7 @@ title: Bewerkingen
# { title } # { title }
In tegenstelling tot de bestandsacties, kunnen de bewerkingsacties mogelijk de inhoud van de huidige geselecteerde bestanden wijzigen. In tegenstelling tot de bestandsacties, kunnen de bewerkingsacties mogelijk de inhoud van de huidige geselecteerde bestanden wijzigen.
Moreover, when the tree layout of the files list is enabled (see [Files and statistics](../files-and-stats)), they can also be applied to [tracks, segments, routes, and points of interest](../gpx). Bovendien, wanneer de verticale indeling van de bestandenlijst is ingeschakeld (zie [Bestanden en statistieken](../files-and-stats)), kunnen deze ook worden toegepast op [tracks, segmenten, routes en interessante punten](../gpx).
Daarom zullen we verwijzen naar de elementen die door deze acties kunnen worden gewijzigd als _bestanden_. Daarom zullen we verwijzen naar de elementen die door deze acties kunnen worden gewijzigd als _bestanden_.
Merk op dat behalve het ongedaan maken en opnieuw doen de acties ook toegankelijk zijn via het contextmenu (rechtermuisklik) van de bestandsitems. Merk op dat behalve het ongedaan maken en opnieuw doen de acties ook toegankelijk zijn via het contextmenu (rechtermuisklik) van de bestandsitems.
@@ -38,9 +38,9 @@ Bovendien moet de selectie een enkel bestand zijn.
</DocsNote> </DocsNote>
### <Plus size="16" class="inline-block" style="margin-bottom: 2px" /> New route ### <Plus size="16" class="inline-block" style="margin-bottom: 2px" />Nieuwe route
Create a new route in the selected file. Maak een nieuwe route aan in het geselecteerde bestand.
<DocsNote> <DocsNote>
@@ -60,19 +60,13 @@ Bovendien moet de selectie een enkele route zijn.
</DocsNote> </DocsNote>
### <ArrowRightLeft size="16" class="inline-block" style="margin-bottom: 2px" /> Convert to route/track ### <ArrowRightLeft size="16" class="inline-block" style="margin-bottom: 2px" />Converteer naar route/track
Convert the selected routes to tracks, or the selected tracks or segments to routes. Converteer de geselecteerde routes naar tracks, of de geselecteerde tracks of segmenten naar routes.
Since a route has a single segment, a track with multiple segments is converted into one route per segment. Since a route has a single segment, a track with multiple segments is converted into one route per segment.
When the selected files contain only routes, or only tracks, you can also convert all of them at once. When the selected files contain only routes, or only tracks, you can also convert all of them at once.
<DocsNote>
Except for whole files, this action is only available when the tree layout of the files list is enabled.
</DocsNote>
### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Selecteer alles ### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Selecteer alles
Alle bestanden in het huidige hiërarchie niveau aan de selectie toevoegen. Alle bestanden in het huidige hiërarchie niveau aan de selectie toevoegen.
@@ -1,5 +1,5 @@
--- ---
title: Stijging title: Hoogte
--- ---
<script> <script>
-6
View File
@@ -67,12 +67,6 @@ Since a route has a single segment, a track with multiple segments is converted
When the selected files contain only routes, or only tracks, you can also convert all of them at once. When the selected files contain only routes, or only tracks, you can also convert all of them at once.
<DocsNote>
Except for whole files, this action is only available when the tree layout of the files list is enabled.
</DocsNote>
### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Select all ### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Select all
Add all file items in the current hierarchy level to the selection. Add all file items in the current hierarchy level to the selection.
-6
View File
@@ -67,12 +67,6 @@ Since a route has a single segment, a track with multiple segments is converted
When the selected files contain only routes, or only tracks, you can also convert all of them at once. When the selected files contain only routes, or only tracks, you can also convert all of them at once.
<DocsNote>
Except for whole files, this action is only available when the tree layout of the files list is enabled.
</DocsNote>
### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Zaznacz wszystko ### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Zaznacz wszystko
Dodaj do zaznaczenia wszystkie pliki na bieżącym poziomie hierarchii. Dodaj do zaznaczenia wszystkie pliki na bieżącym poziomie hierarchii.
-6
View File
@@ -67,12 +67,6 @@ Since a route has a single segment, a track with multiple segments is converted
When the selected files contain only routes, or only tracks, you can also convert all of them at once. When the selected files contain only routes, or only tracks, you can also convert all of them at once.
<DocsNote>
Except for whole files, this action is only available when the tree layout of the files list is enabled.
</DocsNote>
### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Selecionar tudo ### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Selecionar tudo
Adicionar todos os itens na hierarquia atual à seleção. Adicionar todos os itens na hierarquia atual à seleção.
-6
View File
@@ -67,12 +67,6 @@ Since a route has a single segment, a track with multiple segments is converted
When the selected files contain only routes, or only tracks, you can also convert all of them at once. When the selected files contain only routes, or only tracks, you can also convert all of them at once.
<DocsNote>
Except for whole files, this action is only available when the tree layout of the files list is enabled.
</DocsNote>
### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Select all ### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Select all
Add all file items in the current hierarchy level to the selection. Add all file items in the current hierarchy level to the selection.
-6
View File
@@ -67,12 +67,6 @@ Since a route has a single segment, a track with multiple segments is converted
When the selected files contain only routes, or only tracks, you can also convert all of them at once. When the selected files contain only routes, or only tracks, you can also convert all of them at once.
<DocsNote>
Except for whole files, this action is only available when the tree layout of the files list is enabled.
</DocsNote>
### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Select all ### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Select all
Add all file items in the current hierarchy level to the selection. Add all file items in the current hierarchy level to the selection.
-6
View File
@@ -67,12 +67,6 @@ Since a route has a single segment, a track with multiple segments is converted
When the selected files contain only routes, or only tracks, you can also convert all of them at once. When the selected files contain only routes, or only tracks, you can also convert all of them at once.
<DocsNote>
Except for whole files, this action is only available when the tree layout of the files list is enabled.
</DocsNote>
### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" />Выбрать всё ### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" />Выбрать всё
Добавить все файлы текущего уровня иерархии к выделению. Добавить все файлы текущего уровня иерархии к выделению.
-6
View File
@@ -67,12 +67,6 @@ Since a route has a single segment, a track with multiple segments is converted
When the selected files contain only routes, or only tracks, you can also convert all of them at once. When the selected files contain only routes, or only tracks, you can also convert all of them at once.
<DocsNote>
Except for whole files, this action is only available when the tree layout of the files list is enabled.
</DocsNote>
### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Izaberi sve ### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Izaberi sve
Dodaj sve stavke datoteke na trenutnom nivou hijerarhije u selekciju. Dodaj sve stavke datoteke na trenutnom nivou hijerarhije u selekciju.
-6
View File
@@ -67,12 +67,6 @@ Since a route has a single segment, a track with multiple segments is converted
When the selected files contain only routes, or only tracks, you can also convert all of them at once. When the selected files contain only routes, or only tracks, you can also convert all of them at once.
<DocsNote>
Except for whole files, this action is only available when the tree layout of the files list is enabled.
</DocsNote>
### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Select all ### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Select all
Lägg till alla filer i den aktuella hierarkinivån till valet. Lägg till alla filer i den aktuella hierarkinivån till valet.
-6
View File
@@ -67,12 +67,6 @@ Since a route has a single segment, a track with multiple segments is converted
When the selected files contain only routes, or only tracks, you can also convert all of them at once. When the selected files contain only routes, or only tracks, you can also convert all of them at once.
<DocsNote>
Except for whole files, this action is only available when the tree layout of the files list is enabled.
</DocsNote>
### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Select all ### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Select all
Add all file items in the current hierarchy level to the selection. Add all file items in the current hierarchy level to the selection.
Loaded 100 of 169 files, more files were not shown because too many files have changed in this diff. Show more